mirror of
https://github.com/storytold/wordcraft.git
synced 2026-11-29 01:05:16 -06:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c1b16b5e88 |
@@ -4,10 +4,10 @@
|
||||
"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",
|
||||
"producer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
|
||||
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
|
||||
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
|
||||
"signer_tooling_revision": "main",
|
||||
"signer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
|
||||
"release_branch": "nightly-signer",
|
||||
"manual_actors": [
|
||||
"bflatastic",
|
||||
@@ -95,15 +95,7 @@
|
||||
"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",
|
||||
|
||||
@@ -44,10 +44,10 @@ jobs:
|
||||
- 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
|
||||
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@f5141455aac7b2eb4708aa259d8ffcdf10fde939
|
||||
with:
|
||||
ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@main
|
||||
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@f5141455aac7b2eb4708aa259d8ffcdf10fde939
|
||||
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
|
||||
with:
|
||||
toolchain: stable
|
||||
@@ -128,10 +128,10 @@ jobs:
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Check out craft-fonts
|
||||
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@main
|
||||
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@f5141455aac7b2eb4708aa259d8ffcdf10fde939
|
||||
with:
|
||||
ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@main
|
||||
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@f5141455aac7b2eb4708aa259d8ffcdf10fde939
|
||||
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
|
||||
with:
|
||||
toolchain: stable
|
||||
@@ -188,10 +188,10 @@ jobs:
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Check out craft-fonts
|
||||
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@main
|
||||
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@f5141455aac7b2eb4708aa259d8ffcdf10fde939
|
||||
with:
|
||||
ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@main
|
||||
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@f5141455aac7b2eb4708aa259d8ffcdf10fde939
|
||||
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
|
||||
with:
|
||||
toolchain: stable
|
||||
|
||||
@@ -34,26 +34,12 @@ jobs:
|
||||
checks: read
|
||||
attestations: write
|
||||
id-token: write
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@main
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
|
||||
with:
|
||||
tooling-revision: main
|
||||
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
|
||||
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.
|
||||
|
||||
@@ -22,9 +22,9 @@ jobs:
|
||||
actions: read
|
||||
attestations: write
|
||||
id-token: write
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
|
||||
with:
|
||||
tooling-revision: main
|
||||
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
|
||||
app-name: wordcraft
|
||||
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
@@ -32,4 +32,3 @@ jobs:
|
||||
# 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"]'
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
name: Notify Services on Release Change
|
||||
|
||||
on:
|
||||
release:
|
||||
types:
|
||||
- published
|
||||
- unpublished
|
||||
- created
|
||||
- edited
|
||||
- deleted
|
||||
- prereleased
|
||||
- released
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
notify:
|
||||
uses: storytold/craft-common-actions/.github/workflows/notify-services.yml@main
|
||||
secrets:
|
||||
ARTCRAFT_SERVICES_DISPATCH_TOKEN: ${{ secrets.ARTCRAFT_SERVICES_DISPATCH_TOKEN }}
|
||||
@@ -74,6 +74,5 @@ 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`.
|
||||
|
||||
Generated
+264
-207
File diff suppressed because it is too large
Load Diff
+56
-52
@@ -37,25 +37,29 @@ 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 = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-ssip = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
wordcraft-proof = { package = "craft-proof", git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-ssip = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", 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" }
|
||||
wordcraft-validate = { path = "crates/validate" }
|
||||
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0", default-features = false }
|
||||
craft-ui-test-kit = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0", default-features = false }
|
||||
craft-ui-test-kit = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
|
||||
# foundation
|
||||
kurbo = { version = "0.13", features = ["serde"] }
|
||||
thiserror = "2"
|
||||
# Command lines: clap derive types, with completions and man pages generated from them (RFC-0018).
|
||||
clap = { version = "4", features = ["derive", "env"] }
|
||||
clap_complete = "4"
|
||||
clap_mangen = "0.2"
|
||||
serde = { version = "1", features = ["derive", "rc"] }
|
||||
serde_json = { version = "1", features = ["float_roundtrip"] }
|
||||
quick-xml = "0.41"
|
||||
@@ -84,28 +88,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 = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0", default-features = false, features = ["write"] }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0", default-features = false, features = ["write"] }
|
||||
|
||||
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0", features = ["doc"] }
|
||||
craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-flow = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-odf = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0", features = ["text"] }
|
||||
craft-markdown = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-html = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0", features = ["flow"] }
|
||||
craft-latex = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0", features = ["detect"] }
|
||||
craft-sheet = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0", features = ["doc"] }
|
||||
craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-flow = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-odf = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0", features = ["text"] }
|
||||
craft-markdown = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-html = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0", features = ["flow"] }
|
||||
craft-latex = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0", features = ["detect"] }
|
||||
craft-sheet = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", 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"
|
||||
@@ -173,27 +177,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 = "7097741460d683b4ddf1ba78026e7759f2d5ee21" }
|
||||
hayro = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541" }
|
||||
hayro = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
|
||||
|
||||
|
||||
@@ -157,7 +157,7 @@ Command line:
|
||||
|
||||
```sh
|
||||
wordcraft-cli convert report.docx report.pdf # docx, pdf, odt, rtf, html, md, tex, txt, png
|
||||
wordcraft-cli convert report.docx report.pdf --strict # exit 3, no file, if a character or picture would be left out
|
||||
wordcraft-cli convert report.docx report.pdf --strict # exit 1, no file, if a character or picture would be left out
|
||||
wordcraft-cli text report.docx # plain text
|
||||
wordcraft-cli inspect report.docx # structure as JSON
|
||||
wordcraft-cli run --template sample \
|
||||
@@ -165,16 +165,27 @@ wordcraft-cli run --template sample \
|
||||
wordcraft-cli run --script job.json # the same from a file: commands, then save to docx and pdf
|
||||
```
|
||||
|
||||
`convert --strict` (a `.pdf` or `.png` output only) and `render --strict` (a PNG of one page) refuse a silently incomplete render: they exit 3
|
||||
`wordcraft-cli` follows [RFC-0018](https://github.com/storytold/craft-contrib/blob/main/rfcs/0018-cli-conventions.md)
|
||||
(command-line conventions); `wordcraft-cli --help` and `<subcommand> --help` are the reference for every flag. Exit status:
|
||||
0 success, 1 the command failed, 2 a usage error (an unknown or repeated flag, a bad value, flags that conflict or that a
|
||||
subcommand doesn't take, all checked before any file is opened), and 128 plus the signal number when a signal ends the
|
||||
process. Errors are `error: <message>` on stderr; results are on stdout. `--version`/`-V` work on every subcommand and there
|
||||
is no `version` subcommand. `WORDCRAFT_PASSWORD` is read by `--password` (a flag wins, an empty variable counts as unset,
|
||||
and `--help` never shows its value); `WORDCRAFT_REGION` sets the paper. The Linux packages (deb, rpm and tar.gz) and the
|
||||
FreeBSD package install the man pages and the bash, zsh and fish completions.
|
||||
|
||||
`convert --strict` (a `.pdf` or `.png` output only) and `render --strict` (a PNG of one page) refuse a silently incomplete render: they exit 1
|
||||
and write nothing if the output would draw a character no font has (an empty box) or leave out a
|
||||
picture. Exit codes are 0 (written), 1 (unreadable input, usage error, or `--strict` with another
|
||||
output type, checked before the input is read) and 3 (strict refusal). On exit 3, stderr has one
|
||||
`wordcraft-cli: strict: …` line per kind, then one JSON line:
|
||||
picture. Exit codes are 0 (written) and 1 (unreadable input or a strict refusal); `--strict` with another
|
||||
output type is a usage error (2), checked before the input is read. On a strict refusal, stderr has one
|
||||
`error: strict: …` line per kind, then one JSON line. (Before RFC-0018 a strict refusal exited 3; RFC-0018 has no code 3.)
|
||||
`validate` exits 0 for PASS and 1 for FAIL, INCOMPLETE or a file it can't read: the verdict is the first line of the report
|
||||
(`verdict` with `--json`).
|
||||
|
||||
```sh
|
||||
wordcraft-cli convert in.docx out.pdf --strict
|
||||
# wordcraft-cli: strict: 1 character cannot be drawn: U+2D30 (×3)
|
||||
# wordcraft-cli: strict: 1 picture(s) left out: word/media/image2.bin (header2.xml): unsupported format
|
||||
# error: strict: 1 character cannot be drawn: U+2D30 (×3)
|
||||
# error: strict: 1 picture(s) left out: word/media/image2.bin (header2.xml): unsupported format
|
||||
# {"schema":1,"strict":"failed","missing_glyphs":[{"cp":"U+2D30","count":3}],"missing_pictures":[{"part":"word/media/image2.bin","source_part":"word/header2.xml","reason":"unsupported_format"}],"truncated":false,"total_missing_glyphs":1,"total_missing_pictures":1,"glyphs_truncated":false,"pictures_truncated":false}
|
||||
```
|
||||
|
||||
@@ -282,8 +293,7 @@ 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:** on 64-bit builds with a usable DirectX 12 GPU, the
|
||||
desktop app initializes only DirectX 12 by default.
|
||||
**If the app doesn't open on Windows:** 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
|
||||
|
||||
@@ -153,8 +153,6 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm
|
||||
|
||||
## Progress log
|
||||
|
||||
- 2026-11-28: Layout indexes numbering definitions for each list and STYLEREF walk. List labels still follow the document's literal labels, start overrides and nested restart rules (#3615).
|
||||
|
||||
- 2026-11-24: Pasting a plain table over selected cells overwrites from the selection's top-left, even when the copy is wider than the selection (#6742).
|
||||
- 2026-11-21: Layout: strict column balancing measures a kept paragraph again in each candidate column, so a float in one column does not make the paragraph skip another where it fits (#6821). Readiness estimates unchanged.
|
||||
|
||||
@@ -172,10 +170,8 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm
|
||||
- 2026-11-15: Native, built-in and web Insert/Change Picture choosers offer both TIFF extensions (`.tif`, `.tiff`) alongside other supported pictures; native drops, picked-file inbox dispatch and pasted picture paths recognize the same suffixes (#6704). TIFF decoding remains limited to supported compression.
|
||||
|
||||
|
||||
- 2026-11-27: Replace with curls a quote typed there when smart quotes are on, as typing does: finding `^034` and replacing with a typed `"` curls stray straight quotes in bulk; `^034` and `^039` stay straight, and a curly quote a typed `'` also finds is left and not counted (#7307).
|
||||
- 2026-11-15: Get the Missing Fonts. A document opened from a file that is missing fonts their publisher gives away (Microsoft's Aptos family, the default in recent Word documents; Cascadia Code and Mono) brings up a box naming each font, the font drawn instead, the publisher's download page and how to install the download, with Don't show this again. `font.missing` reports the same page, so agents get it without the box. WordCraft links to the page only; it downloads and bundles nothing.
|
||||
- 2026-10-30: Track Changes: a list item deleted whole, text and paragraph mark, shows its number as deleted text, in the deletion's colour and with its mark (struck through by default, or caret, #, bold, italic, underline), and hides it with No Markup or when Track Changes Options hide deletions (#4828). Readiness unchanged.
|
||||
- 2026-11-03: A picture inserted or pasted in a table cell fits the cell, as in Word, instead of running out of it; in text columns it fits the column, in a section with other margins that section's width (#5428).
|
||||
- 2026-11-09: Touchpad and mouse-wheel scroll speed settings (#6146): scales Wayland touchpad point input by default (4×) so two-finger scrolling matches desktop speed rather than crawling 1:1, and scales mouse wheel line distance; File › Options › Advanced › Scrolling; commands ui.scrollSpeed and ui.touchpadScrollSpeed.
|
||||
|
||||
- 2026-11-15: Layout: from Word 2013's layout (compatibility mode 15), balancing the columns before a continuous break keeps the last two, three or five lines of a paragraph that began on the page before together, keeps a two- or three-line paragraph that begins the last page whole, and holds a paragraph with keep lines together (or keep with next) whole in the first column when the strict rules fit. Synthetic tests also cover a footnote and a float (#6821); mode 14 splits them as before. Readiness estimates unchanged.
|
||||
@@ -206,7 +202,6 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm
|
||||
- 2026-11-08: Layout: a turned inline picture whose file keeps no room for the turn (no or a zero `wp:effectExtent`, as other tools write) keeps its line to its frame and overhangs it, cut at the line's top and bottom, as Word does: the frame as it is in Word 2007 layout, with width and height exchanged from 45° to 135° and 225° to 315° in Word 2013+ layout. Such a file saves the same way. Pictures with the room recorded (Word's own files) still take their rotated bounds. Readiness unchanged.
|
||||
- 2026-11-08: XML text and CDATA read with their line ends normalised (XML 1.0 §2.11): CR LF and a lone CR are one line feed, ` ` stays a CR, so a line break inside `w:t` in a file saved with Windows line ends is one space, not two (#5897); readiness estimates unchanged.
|
||||
- 2026-11-08: Layout: contextual spacing drops the space after a table cell's last paragraph when that paragraph is in the Normal style, the end-of-cell mark counting as a Normal paragraph next to it; a last paragraph in another style keeps its space after. The rule is inferred from docxide-pdf's notes and its `cell-end-*` fixtures (`cell-end-text-context`, `cell-end-empty-context`); a Word comparison that tells it apart from the neighbouring paragraph's style is still open. Readiness unchanged.
|
||||
- 2026-11-07: Justified paragraphs that start with a tab or contain tabs shrink the spaces after their last tab in Word 2013+ compatibility mode (mode 15), matching Word (#5847). Spaces before the line's last tab remain at their natural width.
|
||||
- 2026-11-07: An in-line picture lowered past its own height (`w:position`) lowers its line as far, as in Word; all 156 synthetic lines measured for #3984 match Word (#5796). Exact spacing keeps the line's baseline.
|
||||
- 2026-11-07: DOCX: a VML text box keeps its text direction: `mso-layout-flow-alt:bottom-to-top` reads as Rotate all text 270° whatever `layout-flow` says, and otherwise `layout-flow:vertical` (or `vertical-ideographic`) as 90°, so the turned text box in a compatibility-mode document's header is drawn turned, as in Word. (#5193)
|
||||
- 2026-11-07: Newly opened secondary windows constrain their initial viewport dimensions to the monitor's usable area with margins for system panels, preventing new windows from exceeding screen width on high-DPI scaled displays (#5871).
|
||||
@@ -984,7 +979,6 @@ MATH glyphs that reference the same construction now share its immutable variant
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-27 | trivial | Progress log: a quote typed in Replace with goes in curly when smart quotes are on (#7307) |
|
||||
| 2026-11-18 | trivial | DOCX validation reports undeclared binary tombstones in coverage notes when relationship discovery establishes that no relationship targets the part. |
|
||||
| 2026-11-18 | trivial | DOCX validation excludes the content-type manifest from main-part cardinality and reports untargeted ordinary document parts in coverage when one ordinary main is established. |
|
||||
| 2026-11-18 | trivial | DOCX validation warns on an image signature mismatch when the image is unused or can be decoded in another raster format. Used, unusable images retain their error. |
|
||||
@@ -999,7 +993,6 @@ MATH glyphs that reference the same construction now share its immutable variant
|
||||
| 2026-11-12 | trivial | Validator: exclude every glossary-typed part from main traversal and fallback assignment; multiple content-type fallback candidates are ambiguous, with no selected anchor (#5875). Synthetic controls; no parity estimate changed. |
|
||||
| 2026-11-12 | trivial | Validator: mixed Transitional/Strict entry points to the same target skip document checks with coverage in either order (#5875); distinct competing roots retain ambiguity treatment without evaluating the profile gate. No parity estimate changed. |
|
||||
| 2026-11-12 | trivial | Validator: competing official role targets produce coverage and suppress dependent findings; both-order, repeated-target, malformed-source and owner-isolation controls (#5875). No parity estimate changed. |
|
||||
| 2026-11-03 | trivial | Progress log: a picture inserted or pasted in a table cell fits the cell (#5428) |
|
||||
| 2026-11-10 | trivial | Save As on Linux: the desktop portal's Save dialog reports the file type picked, updating the extension so saving as PDF writes a .pdf (#6180) |
|
||||
| 2026-11-08 | trivial | Progress log: freestanding custom.dic dictionary file support in File › Options › Proofing (#5840) |
|
||||
| 2026-11-08 | trivial | Progress log: XML line ends in text normalised (#5897) |
|
||||
@@ -1535,7 +1528,6 @@ MATH glyphs that reference the same construction now share its immutable variant
|
||||
| 2026-10-10 | major | Full re-measure; progress docs restructured (stage banner, two numbers, dimensions, languages, upcoming, progress log); parity tables moved to `docs/target-app-parity.md`, milestones to `docs/roadmap.md` |
|
||||
| 2026-10-09 | minor | Recently landed: RTL, Ukrainian and Brazilian Portuguese |
|
||||
| 2026-10-06 | major | First honest estimate: 88% catalog, ~62% real parity, alpha ~85% of the way |
|
||||
| 2026-11-07 | trivial | Progress log: a justified line with a tab shrinks the spaces after it (#5847) |
|
||||
> 2026-10-27 · Technical synchronization: existing Proofing pane hooks and regression tests follow the extracted engine/UI modules on main `436d444`; compact context menus remain upstream. New-SHA validation is pending; readiness unchanged.
|
||||
|
||||
> 2026-10-23 · cu20we review follow-up: Only paragraph-relative box floats use the pre-spacing origin. Line-relative floats and page/margin fallbacks in cells and text boxes keep the text-top origin. Synthetic controls compare zero and 24 pt space-before across all four box contexts. New cap conversion helpers and regression tests document their contracts; readiness estimates unchanged.
|
||||
|
||||
@@ -6,6 +6,9 @@ license.workspace = true
|
||||
publish = false
|
||||
description = "WordCraft command line: convert, inspect, render, run commands, MCP server"
|
||||
|
||||
[lib]
|
||||
path = "src/lib.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "wordcraft-cli"
|
||||
path = "src/main.rs"
|
||||
@@ -22,9 +25,14 @@ wordcraft-zotero = { workspace = true }
|
||||
wordcraft-validate = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
sys-locale = "0.3"
|
||||
thiserror = { workspace = true }
|
||||
clap = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
wordcraft-fonts = { workspace = true }
|
||||
wordcraft-geom = { workspace = true, features = ["image"] }
|
||||
image = { workspace = true }
|
||||
craft-zip = { workspace = true }
|
||||
# The completions and man pages (examples/man-and-completions.rs), generated from the clap definition.
|
||||
clap_complete = { workspace = true }
|
||||
clap_mangen = { workspace = true }
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
//! Writes wordcraft-cli's shell completions ([`clap_complete`]: bash, zsh, fish, elvish,
|
||||
//! PowerShell) and man pages ([`clap_mangen`]: `wordcraft-cli.1` and one per subcommand, such as
|
||||
//! `wordcraft-cli-run.1`) into a directory. The Linux and FreeBSD packages ship them
|
||||
//! (see `packaging/`):
|
||||
//!
|
||||
//! ```sh
|
||||
//! cargo run -p wordcraft-cli --example man-and-completions -- <out-dir>
|
||||
//! ```
|
||||
|
||||
use std::path::Path;
|
||||
use std::process::ExitCode;
|
||||
|
||||
use clap::ValueEnum;
|
||||
use clap_complete::Shell;
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let mut args = std::env::args_os().skip(1);
|
||||
let (Some(dir), None) = (args.next(), args.next()) else {
|
||||
eprintln!("usage: man-and-completions <out-dir>");
|
||||
return ExitCode::from(2);
|
||||
};
|
||||
let dir = Path::new(&dir);
|
||||
match generate(dir) {
|
||||
Ok(()) => ExitCode::SUCCESS,
|
||||
Err(e) => {
|
||||
eprintln!("error: {}: {e}", dir.display());
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Also run by the tests.
|
||||
pub(crate) fn generate(dir: &Path) -> std::io::Result<()> {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
let mut cmd = wordcraft_cli::command();
|
||||
for &shell in Shell::value_variants() {
|
||||
clap_complete::generate_to(shell, &mut cmd, "wordcraft-cli", dir)?;
|
||||
}
|
||||
// A fresh command: `clap_complete::generate_to` built `cmd`, adding the `help` subcommand,
|
||||
// which `clap_mangen` would otherwise give pages of its own (`wordcraft-cli-help-convert.1`).
|
||||
clap_mangen::generate_to(wordcraft_cli::command(), dir)
|
||||
}
|
||||
@@ -0,0 +1,343 @@
|
||||
//! The command line as clap derive types (RFC-0018). Values arrive typed, so the commands never validate a string; what
|
||||
//! clap cannot say alone is a [`UsageError`], printed and exited like clap's own.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use clap::{ArgMatches, Args, CommandFactory, FromArgMatches, Parser, Subcommand, ValueEnum};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// The end of every subcommand's `--help`.
|
||||
const EXIT_STATUS: &str = "Exit status:\n 0 success\n 1 the command failed (for `convert --strict` and `render --strict`, a refusal; for `validate`, a verdict other than PASS)\n 2 usage error\n\nA process ended by a signal exits 128 + the signal number (130 for Ctrl-C), as in the shell.";
|
||||
|
||||
/// The top-level `--help` ends with the environment and the exit status.
|
||||
const TOP_NOTES: &str = "A password-protected Word file is opened with --password PASS, --password-file PATH or the WORDCRAFT_PASSWORD environment variable; a password given on the command line is readable by every other process, so the other two are better. A file opened with a password is written with it again, as the app does. Exports that cannot carry a password (pdf, html, txt) stay plain.\n\nPaper: documents created here, and HTML, Markdown and text files (which give no page size), use the system region's paper (A4, or Letter in the US and other Letter regions), read from LC_ALL / LC_PAPER / LANG or the platform. Set WORDCRAFT_REGION=en-US (or another tag) for the same output on every machine.\n\nEnvironment:\n WORDCRAFT_PASSWORD the password of a protected Word file, when neither --password nor --password-file is given\n WORDCRAFT_REGION the paper and region to use instead of the system's (a tag such as en-US)\n\nExit status:\n 0 success\n 1 the command failed (for `convert --strict` and `render --strict`, a refusal; for `validate`, a verdict other than PASS)\n 2 usage error\n\nA process ended by a signal exits 128 + the signal number (130 for Ctrl-C), as in the shell.";
|
||||
|
||||
/// WordCraft from the command line: convert, inspect, render, run commands, validate, serve MCP
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(name = "wordcraft-cli", version, propagate_version = true, arg_required_else_help = true, after_help = TOP_NOTES)]
|
||||
pub(crate) struct Cli {
|
||||
#[command(subcommand)]
|
||||
pub(crate) command: Command,
|
||||
}
|
||||
|
||||
#[derive(Subcommand, Debug)]
|
||||
pub(crate) enum Command {
|
||||
/// Convert between formats (docx, doc [read], pdf, odt, rtf, html, md, tex, txt, json, png, xml)
|
||||
///
|
||||
/// `--update-fields` refreshes unlocked fields before saving (if protection blocks updates, they are skipped with a
|
||||
/// warning). An .xml file is a Word XML Document (Flat OPC), or with `--format wordml2003` a Word 2003 XML Document.
|
||||
/// `--markup` (Print Markup) puts comments beside each page and tracked changes in pdf/png, and a comment list in
|
||||
/// html/md/txt. `--strict` (pdf or png output only) writes nothing and exits 1 if a character can't be drawn or a
|
||||
/// picture is missing or undecodable; the report is on stderr, with one JSON line.
|
||||
#[command(after_help = EXIT_STATUS)]
|
||||
Convert(ConvertArgs),
|
||||
/// Pages, words, paragraphs and properties (JSON)
|
||||
#[command(after_help = EXIT_STATUS)]
|
||||
Info(FileArgs),
|
||||
/// The plain text
|
||||
#[command(after_help = EXIT_STATUS)]
|
||||
Text(FileArgs),
|
||||
/// The document structure (JSON)
|
||||
#[command(after_help = EXIT_STATUS)]
|
||||
Inspect(FileArgs),
|
||||
/// Render one page to a PNG
|
||||
///
|
||||
/// `--strict` writes nothing and exits 1 if a character on the page can't be drawn or a picture is missing or
|
||||
/// undecodable (the report is on stderr, as for `convert --strict`).
|
||||
#[command(after_help = EXIT_STATUS)]
|
||||
Render(RenderArgs),
|
||||
/// Run commands headlessly, then save
|
||||
///
|
||||
/// `--script` runs a JSON file (`-` is stdin) first: {"file"?, "template"?, "commands": [{"command": id, "params"?:
|
||||
/// {…}} | id, …], "save"?: [OUT, …]}; save formats follow the extension (docx and pdf in one run); relative paths
|
||||
/// resolve against the script's folder. `file.new` and `file.open` open another document and make it active; later
|
||||
/// commands and the saves work on the active one; `view.switchWindows` lists the open documents and with {"id": N}
|
||||
/// makes one active. PNG saves use `--page` (1-based, default 1) and `--scale` (default 2).
|
||||
#[command(after_help = EXIT_STATUS)]
|
||||
Run(RunArgs),
|
||||
/// List every command
|
||||
#[command(after_help = EXIT_STATUS)]
|
||||
Commands(JsonArgs),
|
||||
/// Feature-catalog parity
|
||||
#[command(after_help = EXIT_STATUS)]
|
||||
Parity(ParityArgs),
|
||||
/// Structural integrity check
|
||||
///
|
||||
/// Exit 0 for PASS; 1 for FAIL, INCOMPLETE or a file that can't be read (the verdict is the first line of the report,
|
||||
/// and `verdict` in `--json`).
|
||||
#[command(after_help = EXIT_STATUS)]
|
||||
Validate(ValidateArgs),
|
||||
/// MCP server on stdio, with a headless session
|
||||
///
|
||||
/// Both roots are required: the agent's commands read files (open, insert text or picture, mail-merge data,
|
||||
/// templates…) only inside the read root and write them (save, export, merge output…) only inside the write root,
|
||||
/// links followed; the same folder may be both. `--connect` (bridge to the running app) is refused until the app
|
||||
/// confines its control channel (#3695, #5819).
|
||||
#[command(after_help = EXIT_STATUS)]
|
||||
Mcp(McpArgs),
|
||||
/// Run a Zotero command on a document (Zotero must be running)
|
||||
///
|
||||
/// The commands are addEditCitation, addEditBibliography, addNote, refresh, removeCodes and setDocPrefs; `--cmd`
|
||||
/// runs first (for example `--cmd caret.docEnd`).
|
||||
#[command(after_help = EXIT_STATUS)]
|
||||
Zotero(ZoteroArgs),
|
||||
}
|
||||
|
||||
/// How a password-protected Word file is opened.
|
||||
#[derive(Args, Debug, Default)]
|
||||
pub(crate) struct Password {
|
||||
/// The password (readable by every other process on the machine; prefer --password-file)
|
||||
#[arg(long, value_name = "PASS", env = "WORDCRAFT_PASSWORD", hide_env_values = true)]
|
||||
pub(crate) password: Option<String>,
|
||||
/// Read the password from this file (a trailing newline is dropped)
|
||||
#[arg(long = "password-file", value_name = "PATH")]
|
||||
pub(crate) password_file: Option<PathBuf>,
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub(crate) struct FileArgs {
|
||||
/// The document
|
||||
pub(crate) file: PathBuf,
|
||||
#[command(flatten)]
|
||||
pub(crate) open: Password,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, ValueEnum)]
|
||||
pub(crate) enum XmlFormat {
|
||||
/// A Word 2003 XML Document
|
||||
Wordml2003,
|
||||
/// A Word XML Document (Flat OPC), the default
|
||||
Flatopc,
|
||||
}
|
||||
|
||||
impl XmlFormat {
|
||||
pub(crate) fn name(self) -> &'static str {
|
||||
match self {
|
||||
XmlFormat::Wordml2003 => "wordml2003",
|
||||
XmlFormat::Flatopc => "flatopc",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub(crate) struct ConvertArgs {
|
||||
/// The document to read
|
||||
pub(crate) input: PathBuf,
|
||||
/// The file to write; its extension names the format
|
||||
pub(crate) output: PathBuf,
|
||||
/// Print Markup: comments beside each page and tracked changes
|
||||
#[arg(long)]
|
||||
pub(crate) markup: bool,
|
||||
/// Refresh unlocked fields before saving
|
||||
#[arg(long = "update-fields")]
|
||||
pub(crate) update_fields: bool,
|
||||
/// For pdf or png output: write nothing and fail if a character can't be drawn or a picture is missing
|
||||
#[arg(long)]
|
||||
pub(crate) strict: bool,
|
||||
/// The kind of .xml file to write
|
||||
#[arg(long, value_enum, value_name = "KIND")]
|
||||
pub(crate) format: Option<XmlFormat>,
|
||||
#[command(flatten)]
|
||||
pub(crate) open: Password,
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub(crate) struct RenderArgs {
|
||||
/// The document
|
||||
pub(crate) input: PathBuf,
|
||||
/// The PNG to write
|
||||
pub(crate) output: PathBuf,
|
||||
/// The page, from 1
|
||||
#[arg(long, value_name = "N", value_parser = page, default_value = "1")]
|
||||
pub(crate) page: u64,
|
||||
/// Device pixels per point
|
||||
#[arg(long, value_name = "S", allow_negative_numbers = true, value_parser = scale, default_value = "2")]
|
||||
pub(crate) scale: f64,
|
||||
/// Write nothing and fail if a character can't be drawn or a picture is missing
|
||||
#[arg(long)]
|
||||
pub(crate) strict: bool,
|
||||
#[command(flatten)]
|
||||
pub(crate) open: Password,
|
||||
}
|
||||
|
||||
/// One `--cmd ID[=JSON]`.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct Cmd {
|
||||
pub(crate) id: String,
|
||||
pub(crate) params: Value,
|
||||
}
|
||||
|
||||
fn cmd(text: &str) -> Result<Cmd, UsageError> {
|
||||
match text.split_once('=') {
|
||||
Some((id, p)) => {
|
||||
let params = serde_json::from_str(p).map_err(|e| UsageError::CmdJson { id: id.to_owned(), why: e.to_string() })?;
|
||||
Ok(Cmd { id: id.to_owned(), params })
|
||||
}
|
||||
None => Ok(Cmd { id: text.to_owned(), params: json!({}) }),
|
||||
}
|
||||
}
|
||||
|
||||
fn page(text: &str) -> Result<u64, UsageError> {
|
||||
match text.parse::<u64>() {
|
||||
Ok(0) => Err(UsageError::Page("invalid --page `0`: page numbers start at 1".to_owned())),
|
||||
Ok(n) => Ok(n),
|
||||
Err(_) => Err(UsageError::Page(format!("invalid --page `{text}`: not a valid integer"))),
|
||||
}
|
||||
}
|
||||
|
||||
fn scale(text: &str) -> Result<f64, UsageError> {
|
||||
let n = text.parse::<f64>().map_err(|_| UsageError::Scale(format!("invalid --scale `{text}`: not a number")))?;
|
||||
if n.is_finite() && n > 0.0 { Ok(n) } else { Err(UsageError::Scale(format!("invalid --scale `{text}`: scale must be a finite positive number"))) }
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub(crate) struct RunArgs {
|
||||
/// Open this document first
|
||||
#[arg(long, value_name = "F", conflicts_with = "template")]
|
||||
pub(crate) file: Option<PathBuf>,
|
||||
/// Start from this template
|
||||
#[arg(long, value_name = "T")]
|
||||
pub(crate) template: Option<String>,
|
||||
/// A script to run first (`-` is stdin)
|
||||
#[arg(long, value_name = "FILE")]
|
||||
pub(crate) script: Option<PathBuf>,
|
||||
/// Run one command, `ID` or `ID={json}`; repeatable
|
||||
#[arg(long = "cmd", value_name = "ID={JSON}", value_parser = cmd)]
|
||||
pub(crate) cmds: Vec<Cmd>,
|
||||
/// Save the result here (the extension names the format)
|
||||
#[arg(long, value_name = "OUT")]
|
||||
pub(crate) save: Option<PathBuf>,
|
||||
/// The page of a PNG save, from 1 (default 1)
|
||||
#[arg(long, value_name = "N", value_parser = page)]
|
||||
pub(crate) page: Option<u64>,
|
||||
/// The scale of a PNG save (default 2)
|
||||
#[arg(long, value_name = "S", allow_negative_numbers = true, value_parser = scale)]
|
||||
pub(crate) scale: Option<f64>,
|
||||
/// Print each command's result
|
||||
#[arg(long)]
|
||||
pub(crate) print: bool,
|
||||
/// Who tracked changes and comments are by
|
||||
#[arg(long, value_name = "NAME")]
|
||||
pub(crate) author: Option<String>,
|
||||
#[command(flatten)]
|
||||
pub(crate) open: Password,
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub(crate) struct JsonArgs {
|
||||
/// JSON alone on stdout
|
||||
#[arg(long)]
|
||||
pub(crate) json: bool,
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub(crate) struct ParityArgs {
|
||||
/// Markdown instead of JSON
|
||||
#[arg(long)]
|
||||
pub(crate) markdown: bool,
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub(crate) struct ValidateArgs {
|
||||
/// The document
|
||||
pub(crate) file: PathBuf,
|
||||
/// JSON alone on stdout
|
||||
#[arg(long)]
|
||||
pub(crate) json: bool,
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub(crate) struct McpArgs {
|
||||
/// The folder the agent may read in (links followed); the same folder may be the write root
|
||||
#[arg(long = "automation-read-root", value_name = "DIR", required_unless_present = "connect", value_parser = folder)]
|
||||
pub(crate) read_root: Option<PathBuf>,
|
||||
/// The folder the agent may write in (links followed)
|
||||
#[arg(long = "automation-write-root", value_name = "DIR", required_unless_present = "connect", value_parser = folder)]
|
||||
pub(crate) write_root: Option<PathBuf>,
|
||||
/// Who tracked changes and comments are by
|
||||
#[arg(long, value_name = "NAME")]
|
||||
pub(crate) author: Option<String>,
|
||||
/// Refused for now: the desktop app does not confine its control channel to automation roots yet
|
||||
#[arg(long, value_name = "HOST:PORT")]
|
||||
pub(crate) connect: Option<String>,
|
||||
}
|
||||
|
||||
fn folder(text: &str) -> Result<PathBuf, UsageError> {
|
||||
if text.is_empty() { Err(UsageError::EmptyFolder) } else { Ok(PathBuf::from(text)) }
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub(crate) struct ZoteroArgs {
|
||||
/// The Zotero command (addEditCitation, addEditBibliography, addNote, refresh, removeCodes or setDocPrefs)
|
||||
#[arg(value_parser = zotero_command)]
|
||||
pub(crate) command: String,
|
||||
/// The document
|
||||
pub(crate) file: PathBuf,
|
||||
/// Run one command first, `ID` or `ID={json}`; repeatable
|
||||
#[arg(long = "cmd", value_name = "ID={JSON}", value_parser = cmd)]
|
||||
pub(crate) cmds: Vec<Cmd>,
|
||||
/// Save the document here afterwards
|
||||
#[arg(long, value_name = "OUT")]
|
||||
pub(crate) save: Option<PathBuf>,
|
||||
/// Show the calls to and from Zotero on stderr
|
||||
#[arg(long)]
|
||||
pub(crate) trace: bool,
|
||||
/// Zotero's port
|
||||
#[arg(long, value_name = "P")]
|
||||
pub(crate) port: Option<u16>,
|
||||
}
|
||||
|
||||
fn zotero_command(text: &str) -> Result<String, UsageError> {
|
||||
if wordcraft_zotero::Command::from_name(text).is_some() { Ok(text.to_owned()) } else { Err(UsageError::Zotero(text.to_owned())) }
|
||||
}
|
||||
|
||||
/// A mistake in the command line that clap can't see by itself.
|
||||
#[derive(Debug, PartialEq, thiserror::Error)]
|
||||
pub(crate) enum UsageError {
|
||||
#[error("{0}")]
|
||||
Page(String),
|
||||
#[error("{0}")]
|
||||
Scale(String),
|
||||
#[error("--cmd {id}: bad JSON params: {why}")]
|
||||
CmdJson { id: String, why: String },
|
||||
#[error("a folder is needed, not an empty name")]
|
||||
EmptyFolder,
|
||||
#[error("unknown Zotero command `{0}` (addEditCitation, addEditBibliography, addNote, refresh, removeCodes or setDocPrefs)")]
|
||||
Zotero(String),
|
||||
}
|
||||
|
||||
/// The clap definition of the whole command line (completions and man pages are generated from it).
|
||||
pub fn command() -> clap::Command {
|
||||
Cli::command()
|
||||
}
|
||||
|
||||
/// Parse the arguments (without the program name). Help and the version come back as the `Err` clap uses for them.
|
||||
pub(crate) fn parse(args: &[OsString]) -> Result<Cli, clap::Error> {
|
||||
let matches = Cli::command().try_get_matches_from(std::iter::once(OsString::from("wordcraft-cli")).chain(args.iter().cloned()))?;
|
||||
let mut cli = Cli::from_arg_matches(&matches)?;
|
||||
if let Some((name, sub)) = matches.subcommand() {
|
||||
password_precedence(&mut cli.command, sub, name);
|
||||
}
|
||||
Ok(cli)
|
||||
}
|
||||
|
||||
/// `--password`, `--password-file`, then `WORDCRAFT_PASSWORD`: a password file named on the command line beats the
|
||||
/// variable, which clap would otherwise read into `--password`.
|
||||
fn password_precedence(command: &mut Command, sub: &ArgMatches, _name: &str) {
|
||||
let open = match command {
|
||||
Command::Convert(a) => &mut a.open,
|
||||
Command::Info(a) | Command::Text(a) | Command::Inspect(a) => &mut a.open,
|
||||
Command::Render(a) => &mut a.open,
|
||||
Command::Run(a) => &mut a.open,
|
||||
_ => return,
|
||||
};
|
||||
let from_env = sub.value_source("password") == Some(clap::parser::ValueSource::EnvVariable);
|
||||
if from_env && open.password_file.is_some() {
|
||||
open.password = None;
|
||||
}
|
||||
// A blank variable counts as unset.
|
||||
if from_env && open.password.as_deref() == Some("") {
|
||||
open.password = None;
|
||||
}
|
||||
}
|
||||
@@ -1,90 +0,0 @@
|
||||
//! Parse `--automation-read-root` / `--automation-write-root` before the server starts. A malformed
|
||||
//! flag must not silently remove a root and leave the server unconfined.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub struct AutomationArgs {
|
||||
pub read_root: Option<PathBuf>,
|
||||
pub write_root: Option<PathBuf>,
|
||||
read_given: bool,
|
||||
write_given: bool,
|
||||
}
|
||||
|
||||
impl AutomationArgs {
|
||||
pub fn new(read_root: Option<PathBuf>, write_root: Option<PathBuf>) -> Self {
|
||||
Self { read_root, write_root, read_given: false, write_given: false }
|
||||
}
|
||||
|
||||
/// Returns whether this argument is a root flag. A second occurrence of a flag is an error,
|
||||
/// including when the two spellings (`--flag DIR`, `--flag=DIR`) are mixed.
|
||||
pub fn consume(&mut self, arg: &str, args: &mut impl Iterator<Item = String>) -> Result<bool, String> {
|
||||
let (flag, inline) = arg.split_once('=').map_or((arg, None), |(flag, value)| (flag, Some(value)));
|
||||
let (root, given) = match flag {
|
||||
"--automation-read-root" => (&mut self.read_root, &mut self.read_given),
|
||||
"--automation-write-root" => (&mut self.write_root, &mut self.write_given),
|
||||
_ => return Ok(false),
|
||||
};
|
||||
if *given {
|
||||
return Err(format!("{flag} given twice"));
|
||||
}
|
||||
let value = match inline {
|
||||
Some(value) => value.to_owned(),
|
||||
None => {
|
||||
let value = args.next().ok_or_else(|| format!("{flag} needs a folder"))?;
|
||||
if value.starts_with('-') {
|
||||
return Err(format!("{flag} needs a folder; use {flag}=<dir> for a folder starting with '-'"));
|
||||
}
|
||||
value
|
||||
}
|
||||
};
|
||||
if value.is_empty() {
|
||||
return Err(format!("{flag} needs a non-empty folder"));
|
||||
}
|
||||
*root = Some(value.into());
|
||||
*given = true;
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn roots_are_taken_once_and_other_arguments_are_left() {
|
||||
let mut roots = AutomationArgs::new(None, None);
|
||||
let mut args = ["a folder".to_owned(), "report.docx".to_owned()].into_iter();
|
||||
assert!(roots.consume("--automation-read-root", &mut args).unwrap());
|
||||
assert!(roots.consume("--automation-write-root=out", &mut args).unwrap());
|
||||
assert!(!roots.consume("--author", &mut args).unwrap());
|
||||
assert_eq!(roots.read_root, Some("a folder".into()));
|
||||
assert_eq!(roots.write_root, Some("out".into()));
|
||||
assert_eq!(args.next().as_deref(), Some("report.docx"));
|
||||
assert!(roots.consume("--automation-read-root=other", &mut args).is_err());
|
||||
assert_eq!(roots.read_root, Some("a folder".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_operands_leave_roots_unchanged() {
|
||||
for flag in ["--automation-read-root", "--automation-write-root"] {
|
||||
for operand in [None, Some(""), Some("--version"), Some("--connect"), Some("-folder")] {
|
||||
let mut roots = AutomationArgs::new(Some("read".into()), Some("write".into()));
|
||||
let mut args = operand.map(str::to_owned).into_iter();
|
||||
assert!(roots.consume(flag, &mut args).is_err(), "{flag} {operand:?}");
|
||||
assert_eq!(roots.read_root, Some("read".into()));
|
||||
assert_eq!(roots.write_root, Some("write".into()));
|
||||
}
|
||||
let mut roots = AutomationArgs::new(None, None);
|
||||
assert!(roots.consume(&format!("{flag}="), &mut std::iter::empty()).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_dash_folder_and_relative_dash_folder_are_valid() {
|
||||
let mut roots = AutomationArgs::new(None, None);
|
||||
assert!(roots.consume("--automation-read-root=-folder", &mut std::iter::empty()).unwrap());
|
||||
assert!(roots.consume("--automation-write-root", &mut ["./-folder".to_owned()].into_iter()).unwrap());
|
||||
assert_eq!(roots.read_root, Some("-folder".into()));
|
||||
assert_eq!(roots.write_root, Some("./-folder".into()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,609 @@
|
||||
//! The subcommands: each takes its parsed arguments and the output streams, and returns the exit status.
|
||||
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use wordcraft_engine::{CmdError, Session};
|
||||
|
||||
use crate::args::{self, Command, ConvertArgs, FileArgs, JsonArgs, McpArgs, ParityArgs, Password, RenderArgs, RunArgs, ValidateArgs, ZoteroArgs};
|
||||
use crate::error::CliError;
|
||||
use crate::script;
|
||||
use crate::{Io, errln};
|
||||
|
||||
type Result<T> = std::result::Result<T, CliError>;
|
||||
|
||||
fn engine_error(e: impl std::fmt::Display) -> CliError {
|
||||
CliError::Failed(escape_text(&e.to_string(), false))
|
||||
}
|
||||
|
||||
/// Open a document for a subcommand. A password-protected Word file needs its password
|
||||
/// ([`password_from`]). As in the app, a document opened with one is saved with it again, so
|
||||
/// `convert` does not quietly write a copy the password no longer protects.
|
||||
fn open(path: &Path, password: Option<&str>) -> Result<Session> {
|
||||
// A file that gives no page size (HTML, Markdown, plain text) opens on the system region's
|
||||
// paper, as in the app: A4 in Italy, Letter in the US (#1381).
|
||||
let region = system_region();
|
||||
let (doc, encrypted) = wordcraft_engine::io::open_path_in(path, password, ®ion).map_err(engine_error)?;
|
||||
let mut s = session(doc);
|
||||
s.path = Some(path.into());
|
||||
if encrypted {
|
||||
s.password = password.map(wordcraft_engine::io::Password::new);
|
||||
}
|
||||
Ok(s)
|
||||
}
|
||||
|
||||
/// The password for a protected Word file: `--password`, `--password-file` or `WORDCRAFT_PASSWORD` (clap reads the
|
||||
/// variable into `--password`; a blank one counts as unset). The file form exists because a password on a command line
|
||||
/// is readable by every other process on the machine; a trailing newline is dropped so a file written by `echo` works.
|
||||
/// Never logged, and never named in an error.
|
||||
pub(crate) fn password_from(open: &Password) -> Result<Option<String>> {
|
||||
if let Some(password) = &open.password {
|
||||
return Ok(Some(password.clone()));
|
||||
}
|
||||
if let Some(path) = &open.password_file {
|
||||
let raw =
|
||||
std::fs::read_to_string(path).map_err(|e| CliError::Failed(escape_text(&format!("--password-file {}: {e}", path.display()), false)))?;
|
||||
return Ok(Some(raw.trim_end_matches(['\r', '\n']).to_string()));
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// A path the engine takes as text: output paths must be valid Unicode (only the opened file may not be, #1440).
|
||||
fn unicode(path: &Path) -> Result<&str> {
|
||||
path.to_str().ok_or_else(|| CliError::Failed(format!("{}: the file name is not valid Unicode", path.display().to_string().escape_debug())))
|
||||
}
|
||||
|
||||
/// A headless session in the system region: every way the CLI starts one gives `file.new` the
|
||||
/// same paper (#1381).
|
||||
fn session(doc: wordcraft_doc::Document) -> Session {
|
||||
let mut s = Session::new(doc);
|
||||
s.system_region = system_region();
|
||||
s
|
||||
}
|
||||
|
||||
/// The system region, read as the app reads it (locale variables, else the platform's locale).
|
||||
fn system_region() -> wordcraft_engine::Region {
|
||||
wordcraft_engine::Region::from_locale_vars(|name| std::env::var(name).ok(), sys_locale::get_locale)
|
||||
}
|
||||
|
||||
/// The body text for `text`: the plain-text export, so list items keep their bullet or number label.
|
||||
fn listed_text(doc: &wordcraft_doc::Document) -> std::result::Result<String, String> {
|
||||
let bytes = wordcraft_engine::io::save_bytes("out.txt", doc)?;
|
||||
Ok(String::from_utf8_lossy(&bytes).replace("\r\n", "\n"))
|
||||
}
|
||||
|
||||
/// `--author NAME`: the author recorded on tracked changes and comments (`file.setAuthor`).
|
||||
/// The command also checks whether the open document is protected: this name determines which
|
||||
/// named editing exceptions the session can use, so the flag must not bypass that check.
|
||||
fn set_author(s: &mut Session, name: &str) -> std::result::Result<(), String> {
|
||||
s.run("file.setAuthor", &json!({"name": name})).map(|_| ()).map_err(|e| escape_text(&format!("--author: {e}"), false))
|
||||
}
|
||||
|
||||
/// `mcp`'s headless backend: a session confined to `roots`, its author `author` when given. The caller confines the
|
||||
/// process to the same roots first (`confine_process`), which a test must not do.
|
||||
fn headless_mcp(
|
||||
roots: std::sync::Arc<wordcraft_engine::file_access::AutomationRoots>,
|
||||
author: Option<&str>,
|
||||
) -> std::result::Result<wordcraft_mcp::Headless, String> {
|
||||
let mut headless = wordcraft_mcp::Headless::default().with_automation_roots(Some(roots));
|
||||
if let Some(name) = author {
|
||||
set_author(&mut headless.session, name)?;
|
||||
}
|
||||
Ok(headless)
|
||||
}
|
||||
|
||||
/// A failed `--strict` export: a strict refusal becomes [`CliError::Strict`] carrying what stderr
|
||||
/// shows (each line of the report as `error: …`, then its JSON on one line, from
|
||||
/// `file.strictReport` for `page` of a page image, else the PDF); any other error is an ordinary
|
||||
/// failure.
|
||||
fn refusal(s: &mut Session, e: wordcraft_engine::CmdError, markup: bool, page: Option<u64>) -> CliError {
|
||||
if !matches!(&e, wordcraft_engine::CmdError::Failed(m) if m.starts_with("strict: ")) {
|
||||
return engine_error(e);
|
||||
}
|
||||
let mut params = json!({"markup": markup});
|
||||
if let Some(page) = page {
|
||||
params["page"] = json!(page);
|
||||
}
|
||||
CliError::Strict(match s.run("file.strictReport", ¶ms).map_err(|e| e.to_string()) {
|
||||
Ok(json) => {
|
||||
let mut text = String::new();
|
||||
for line in report_lines(&json) {
|
||||
text += &format!("error: {}\n", escape_peer(&line));
|
||||
}
|
||||
text + &json_line_safe(&json.to_string())
|
||||
}
|
||||
Err(e) => format!("error: strict: refused, and the report could not be made: {}", escape_text(&e, false)),
|
||||
})
|
||||
}
|
||||
|
||||
/// The report's human lines, from its JSON (the engine's `StrictReport::lines`).
|
||||
fn report_lines(json: &Value) -> Vec<String> {
|
||||
wordcraft_engine::strict::lines_from_json(json)
|
||||
}
|
||||
|
||||
/// Explicitly update unlocked fields in a session before saving the document.
|
||||
///
|
||||
/// If field updates are disabled by document protection (`CmdError::Disabled`), logs a warning to
|
||||
/// stderr and continues conversion rather than aborting. Other command failures are converted to
|
||||
/// [`CliError`] via [`engine_error`].
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `s` - The active document [`Session`] whose unlocked fields should be refreshed.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns `Err(CliError)` if the command fails with an error other than `CmdError::Disabled`.
|
||||
fn update_fields(s: &mut Session, io: &mut Io) -> Result<()> {
|
||||
if let Err(e) = s.run("references.updateFields", &json!({})) {
|
||||
if matches!(e, CmdError::Disabled(_)) {
|
||||
errln!(io, "warning: {e}");
|
||||
} else {
|
||||
return Err(engine_error(e));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// At most 400 characters of `s`, for traces.
|
||||
fn clip(s: &str) -> String {
|
||||
match s.char_indices().nth(400) {
|
||||
Some((i, _)) => format!("{}…", s.get(..i).unwrap_or(s)),
|
||||
None => s.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Text from another program (Zotero, or whatever answered on its port) for one diagnostic
|
||||
/// line: backslashes, control characters (newline, escape, C1…), line separators and bidi
|
||||
/// overrides are shown as escapes (`\\`, `\n`, `\u{1b}`), so it can't end its line, drive the
|
||||
/// terminal or pass for other output.
|
||||
fn escape_peer(s: &str) -> String {
|
||||
escape_text(s, true)
|
||||
}
|
||||
|
||||
/// Whether `c` must not reach a terminal as itself: a control character, a line or paragraph
|
||||
/// separator, a bidi control, or one that shows nothing (soft hyphen, zero-width characters, word
|
||||
/// joiners, the byte order mark, tag characters), which can hide or reorder what a line says.
|
||||
fn is_unsafe_char(c: char) -> bool {
|
||||
c.is_control()
|
||||
|| matches!(
|
||||
c,
|
||||
'\u{00ad}'
|
||||
| '\u{061c}'
|
||||
| '\u{200b}'..='\u{200f}'
|
||||
| '\u{2028}'..='\u{202e}'
|
||||
| '\u{2060}'..='\u{2064}'
|
||||
| '\u{2066}'..='\u{2069}'
|
||||
| '\u{feff}'
|
||||
| '\u{e0000}'..='\u{e007f}'
|
||||
)
|
||||
}
|
||||
|
||||
/// [`escape_peer`], with backslashes escaped only when `backslash` (error messages quote Windows
|
||||
/// paths, and a backslash can't forge or hide anything).
|
||||
fn escape_text(s: &str, backslash: bool) -> String {
|
||||
let mut out = String::with_capacity(s.len());
|
||||
for c in s.chars() {
|
||||
match c {
|
||||
'\\' if backslash => out.push_str("\\\\"),
|
||||
'\n' => out.push_str("\\n"),
|
||||
'\r' => out.push_str("\\r"),
|
||||
'\t' => out.push_str("\\t"),
|
||||
c if is_unsafe_char(c) => out.extend(c.escape_unicode()),
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A JSON line safe to print: serde escapes control characters below U+0020 but not the other
|
||||
/// characters [`is_unsafe_char`] names, which a crafted file could put in a report. They become
|
||||
/// `\uXXXX` escapes (a surrogate pair above U+FFFF), so the line parses to the same value and
|
||||
/// can't drive or spoof a terminal.
|
||||
fn json_line_safe(json: &str) -> String {
|
||||
let mut out = String::with_capacity(json.len());
|
||||
for c in json.chars() {
|
||||
if is_unsafe_char(c) {
|
||||
for unit in c.encode_utf16(&mut [0u16; 2]) {
|
||||
out.push_str(&format!("\\u{unit:04x}"));
|
||||
}
|
||||
} else {
|
||||
out.push(c);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn parity_markdown(p: &Value) -> String {
|
||||
let mut s = String::from(
|
||||
"# WordCraft feature parity\n\nGenerated by `cargo xtask parity` (`wordcraft-cli parity --markdown`): the word-processor feature catalog (`crates/engine/src/catalog.rs`) compared with the live command registry.\n\n",
|
||||
);
|
||||
s += &format!(
|
||||
"**{} of {} catalog features have commands ({}%).**\n\n| Tab | Live | Total |\n|---|---|---|\n",
|
||||
p["live"], p["total"], p["percent"]
|
||||
);
|
||||
for t in p["tabs"].as_array().cloned().unwrap_or_default() {
|
||||
s += &format!("| {} | {} | {} |\n", t["tab"].as_str().unwrap_or(""), t["live"], t["total"]);
|
||||
}
|
||||
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();
|
||||
if m.is_empty() {
|
||||
continue;
|
||||
}
|
||||
s += &format!("### {}\n\n", t["tab"].as_str().unwrap_or(""));
|
||||
for x in m {
|
||||
s += &format!("- {}\n", x.as_str().unwrap_or(""));
|
||||
}
|
||||
s += "\n";
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// 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 dyn Write, 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",
|
||||
}
|
||||
}
|
||||
|
||||
/// Why `mcp --connect` is refused: the running app would not confine the agent's file access.
|
||||
// lean: refused outright; allow it once the app confines its control channel and reports both roots.
|
||||
const MCP_CONNECT_REFUSED: &str = "mcp: --connect is refused for now: the desktop app does not confine its control \
|
||||
channel to automation roots yet (storytold/wordcraft#3695, #5819). Use the headless server: wordcraft-cli mcp \
|
||||
--automation-read-root DIR --automation-write-root DIR";
|
||||
|
||||
/// Run one parsed subcommand; the result is the exit status.
|
||||
pub(crate) fn dispatch(command: Command, io: &mut Io) -> Result<u8> {
|
||||
match command {
|
||||
Command::Convert(a) => convert(a, io).map(|()| 0),
|
||||
Command::Info(a) => info(a, io).map(|()| 0),
|
||||
Command::Text(a) => text(a, io).map(|()| 0),
|
||||
Command::Inspect(a) => inspect(a, io).map(|()| 0),
|
||||
Command::Render(a) => render(a, io).map(|()| 0),
|
||||
Command::Run(a) => run_script(a, io).map(|()| 0),
|
||||
Command::Commands(a) => commands(a, io).map(|()| 0),
|
||||
Command::Parity(a) => parity(a, io).map(|()| 0),
|
||||
Command::Validate(a) => validate(a, io),
|
||||
Command::Mcp(a) => mcp(a, io).map(|()| 0),
|
||||
Command::Zotero(a) => zotero(a, io).map(|()| 0),
|
||||
}
|
||||
}
|
||||
|
||||
/// Write to stdout and flush. A closed stdout comes back as [`CliError::StdoutClosed`] instead of a panic.
|
||||
fn write_stdout(io: &mut Io, write: impl FnOnce(&mut dyn Write) -> std::io::Result<()>) -> Result<()> {
|
||||
write(&mut *io.out)?;
|
||||
io.out.flush()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn convert(a: ConvertArgs, io: &mut Io) -> Result<()> {
|
||||
let o = unicode(&a.output)?.to_owned();
|
||||
// Before the input is opened: a wrong output type is a usage error, not a file error.
|
||||
let to_png = o.to_ascii_lowercase().ends_with(".png");
|
||||
if a.strict && !(to_png || o.to_ascii_lowercase().ends_with(".pdf")) {
|
||||
return Err(CliError::Usage("convert: --strict needs a .pdf or .png output".into()));
|
||||
}
|
||||
let password = password_from(&a.open)?;
|
||||
let mut s = open(&a.input, password.as_deref())?;
|
||||
if a.update_fields {
|
||||
update_fields(&mut s, io)?;
|
||||
}
|
||||
let r = if to_png {
|
||||
s.run("file.exportPng", &json!({"path": o, "page": 1, "markup": a.markup, "strict": a.strict}))
|
||||
} else {
|
||||
let mut params = json!({"path": o, "markup": a.markup, "strict": a.strict});
|
||||
if let Some(f) = a.format {
|
||||
params["format"] = json!(f.name());
|
||||
}
|
||||
s.run("file.save", ¶ms)
|
||||
};
|
||||
if let Err(e) = r {
|
||||
return Err(if a.strict { refusal(&mut s, e, a.markup, to_png.then_some(1)) } else { engine_error(e) });
|
||||
}
|
||||
errln!(io, "wrote {o}");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn open_file(a: &FileArgs) -> Result<Session> {
|
||||
let password = password_from(&a.open)?;
|
||||
open(&a.file, password.as_deref())
|
||||
}
|
||||
|
||||
fn info(a: FileArgs, io: &mut Io) -> Result<()> {
|
||||
let mut s = open_file(&a)?;
|
||||
let info = serde_json::to_string_pretty(&s.run("file.info", &json!({})).map_err(engine_error)?).unwrap_or_default();
|
||||
write_stdout(io, |o| writeln!(o, "{info}"))
|
||||
}
|
||||
|
||||
fn text(a: FileArgs, io: &mut Io) -> Result<()> {
|
||||
let s = open_file(&a)?;
|
||||
let text = listed_text(&s.doc)?;
|
||||
write_stdout(io, |o| writeln!(o, "{text}"))
|
||||
}
|
||||
|
||||
fn inspect(a: FileArgs, io: &mut Io) -> Result<()> {
|
||||
let mut s = open_file(&a)?;
|
||||
let tree = serde_json::to_string_pretty(&s.run("document.inspect", &json!({})).map_err(engine_error)?).unwrap_or_default();
|
||||
write_stdout(io, |o| writeln!(o, "{tree}"))
|
||||
}
|
||||
|
||||
fn render(a: RenderArgs, io: &mut Io) -> Result<()> {
|
||||
let o = unicode(&a.output)?.to_owned();
|
||||
let password = password_from(&a.open)?;
|
||||
let mut s = open(&a.input, password.as_deref())?;
|
||||
let mut params = json!({"path": o, "page": a.page, "scale": a.scale, "strict": a.strict});
|
||||
if a.strict {
|
||||
// The check and its report must see the page as it is written.
|
||||
params["markup"] = json!(false);
|
||||
}
|
||||
let r = match s.run("file.exportPng", ¶ms) {
|
||||
Ok(r) => r,
|
||||
Err(e) if a.strict => return Err(refusal(&mut s, e, false, Some(a.page))),
|
||||
Err(e) => return Err(engine_error(e)),
|
||||
};
|
||||
write_stdout(io, |o| writeln!(o, "{r}"))
|
||||
}
|
||||
|
||||
fn load_run_script(path: Option<&Path>) -> Result<Option<script::Script>> {
|
||||
path.map(|p| script::load(p).map_err(engine_error)).transpose()
|
||||
}
|
||||
|
||||
fn run_script(a: RunArgs, io: &mut Io) -> Result<()> {
|
||||
let password = password_from(&a.open)?;
|
||||
let script = load_run_script(a.script.as_deref())?;
|
||||
// A source named on the command line wins over both of the script's.
|
||||
let (mut from_file, mut from_template) = (a.file.clone(), a.template.clone());
|
||||
if from_file.is_none() && from_template.is_none() {
|
||||
from_file = script.as_ref().and_then(|loaded| loaded.file.as_deref().map(std::path::PathBuf::from));
|
||||
from_template = script.as_ref().and_then(|loaded| loaded.template.clone());
|
||||
}
|
||||
let mut s = match (from_file, from_template) {
|
||||
(Some(f), _) => open(&f, password.as_deref())?,
|
||||
// Both go through `file.new`, which puts a blank document on the region's paper (#3152).
|
||||
// `file.new` opens beside the session's first document, which is then closed: the
|
||||
// run starts with one open document.
|
||||
(None, t) => {
|
||||
let mut s = session(wordcraft_doc::Document::new());
|
||||
let first = s.document_id();
|
||||
let params = t.map_or_else(|| json!({}), |t| json!({"template": t}));
|
||||
s.run("file.new", ¶ms).map_err(engine_error)?;
|
||||
s.close_document(first).map_err(engine_error)?;
|
||||
s
|
||||
}
|
||||
};
|
||||
if let Some(name) = &a.author {
|
||||
set_author(&mut s, name).map_err(CliError::Failed)?;
|
||||
}
|
||||
for (n, (id, params)) in script.iter().flat_map(|c| c.commands.iter()).enumerate() {
|
||||
let r = s.run(id, params).map_err(|e| engine_error(format!("command {} ({id}): {e}", n + 1)))?;
|
||||
if a.print {
|
||||
write_stdout(io, |o| writeln!(o, "{id}: {r}"))?;
|
||||
}
|
||||
}
|
||||
for args::Cmd { id, params } in &a.cmds {
|
||||
let r = s.run(id, params).map_err(|e| engine_error(format!("{id}: {e}")))?;
|
||||
if a.print {
|
||||
write_stdout(io, |o| writeln!(o, "{id}: {r}"))?;
|
||||
}
|
||||
}
|
||||
let mut outputs: Vec<String> = script.iter().flat_map(|c| c.save.iter().cloned()).collect();
|
||||
if let Some(save) = &a.save {
|
||||
outputs.push(unicode(save)?.to_owned());
|
||||
}
|
||||
// Check every output can be made before writing any, so a bad one leaves no half-done job.
|
||||
for out in &outputs {
|
||||
let parent = Path::new(out).parent().filter(|p| !p.as_os_str().is_empty());
|
||||
if let Some(p) = parent.filter(|p| !p.is_dir()) {
|
||||
return Err(format!("{out}: folder {} does not exist", p.display()).into());
|
||||
}
|
||||
if Path::new(out).is_dir() {
|
||||
return Err(format!("{out}: is a folder, not a file").into());
|
||||
}
|
||||
if !out.to_ascii_lowercase().ends_with(".png") {
|
||||
wordcraft_engine::io::save_bytes(out, &s.doc).map_err(engine_error)?;
|
||||
}
|
||||
}
|
||||
for out in outputs {
|
||||
let r = if out.to_ascii_lowercase().ends_with(".png") {
|
||||
let mut v = json!({"path": out});
|
||||
if let Some(n) = a.page {
|
||||
v["page"] = json!(n);
|
||||
}
|
||||
if let Some(k) = a.scale {
|
||||
v["scale"] = json!(k);
|
||||
}
|
||||
s.run("file.exportPng", &v)
|
||||
} else {
|
||||
s.run("file.save", &json!({"path": out}))
|
||||
};
|
||||
r.map_err(engine_error)?;
|
||||
errln!(io, "wrote {out}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn commands(a: JsonArgs, io: &mut Io) -> Result<()> {
|
||||
let s = session(wordcraft_doc::Document::new());
|
||||
if a.json {
|
||||
let list = serde_json::to_string_pretty(&s.registry.describe()).unwrap_or_default();
|
||||
write_stdout(io, |o| writeln!(o, "{list}"))
|
||||
} else {
|
||||
write_stdout(io, |o| {
|
||||
for c in s.registry.all() {
|
||||
writeln!(o, "{:<32} {:<36} {:<24} {}", c.id, c.label, c.shortcut, c.location)?;
|
||||
}
|
||||
writeln!(o, "{:<32} Structural integrity check", "validate")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn parity(a: ParityArgs, io: &mut Io) -> Result<()> {
|
||||
let s = session(wordcraft_doc::Document::new());
|
||||
let p = wordcraft_engine::catalog::parity(&s.registry);
|
||||
if a.markdown {
|
||||
write_stdout(io, |o| write!(o, "{}", parity_markdown(&p)))
|
||||
} else {
|
||||
write_stdout(io, |o| writeln!(o, "{}", serde_json::to_string_pretty(&p).unwrap_or_default()))
|
||||
}
|
||||
}
|
||||
|
||||
fn mcp(a: McpArgs, io: &mut Io) -> Result<()> {
|
||||
if a.connect.is_some() {
|
||||
return Err(MCP_CONNECT_REFUSED.into());
|
||||
}
|
||||
// Shared rule 18 (#7124): an agent entry point never runs unconfined. clap requires both roots.
|
||||
let roots = wordcraft_engine::file_access::AutomationRoots::new(a.read_root.as_deref(), a.write_root.as_deref())
|
||||
.map_err(|e| CliError::Failed(format!("mcp: {e}")))?;
|
||||
let Some(roots) = roots.filter(|r| r.read_root().is_some() && r.write_root().is_some()) else {
|
||||
return Err(CliError::Usage("mcp: give both --automation-read-root DIR and --automation-write-root DIR".into()));
|
||||
};
|
||||
// Every thread of this process, not only the server's: nothing reaches past the roots.
|
||||
wordcraft_engine::file_access::confine_process(roots.clone());
|
||||
let show = |root: Option<&Path>| root.map_or_else(|| "none".to_string(), |r| r.display().to_string());
|
||||
errln!(io, "files confined: read root {}, write root {}", show(roots.read_root()), show(roots.write_root()));
|
||||
let backend: Box<dyn wordcraft_mcp::Backend> = Box::new(headless_mcp(roots, a.author.as_deref()).map_err(CliError::Failed)?);
|
||||
let mut server = wordcraft_mcp::Server::new(backend);
|
||||
let stdin = std::io::stdin();
|
||||
// A client that closes our stdout has hung up: `serve` returns BrokenPipe and we end cleanly.
|
||||
Ok(server.serve(stdin.lock(), &mut *io.out)?)
|
||||
}
|
||||
|
||||
fn zotero(a: ZoteroArgs, io: &mut Io) -> Result<()> {
|
||||
let command =
|
||||
wordcraft_zotero::Command::from_name(&a.command).ok_or_else(|| CliError::Usage(format!("unknown Zotero command `{}`", a.command)))?;
|
||||
let mut s = open(&a.file, None)?;
|
||||
for args::Cmd { id, params } in &a.cmds {
|
||||
s.run(id, params).map_err(|e| engine_error(format!("{id}: {e}")))?;
|
||||
}
|
||||
let mut opts = wordcraft_zotero::client::Options::default();
|
||||
if let Some(p) = a.port {
|
||||
opts.addr.set_port(p);
|
||||
}
|
||||
let mut bridge = wordcraft_zotero::Bridge::new();
|
||||
let mut host = wordcraft_zotero::Headless::default();
|
||||
let mut trace = Vec::new();
|
||||
let out = wordcraft_zotero::client::run_command(&opts, command, &mut |call| {
|
||||
let r = bridge.handle(&mut s, &mut host, call);
|
||||
if a.trace {
|
||||
trace.push(format!("← {} {}", escape_peer(&call.method), escape_peer(&clip(&Value::Array(call.args.clone()).to_string()))));
|
||||
trace.push(format!("→ {}", escape_peer(&clip(&String::from_utf8_lossy(&wordcraft_zotero::wire::encode_reply(&r))))));
|
||||
}
|
||||
r
|
||||
})
|
||||
.map_err(engine_error)?;
|
||||
for line in &trace {
|
||||
errln!(io, "{line}");
|
||||
}
|
||||
for alert in &host.alerts {
|
||||
errln!(io, "Zotero: {}", escape_peer(alert));
|
||||
}
|
||||
errln!(io, "{} calls, {}", out.calls, if out.completed { "completed" } else { "ended without completing (cancelled?)" });
|
||||
if let Some(o) = &a.save {
|
||||
let o = unicode(o)?;
|
||||
s.run("file.save", &json!({"path": o})).map_err(engine_error)?;
|
||||
errln!(io, "wrote {o}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `validate`: 0 for PASS, 1 for any other verdict or a file that can't be read (RFC-0018 rule 1.2 has no other code;
|
||||
/// the verdict is in the report).
|
||||
fn validate(a: ValidateArgs, io: &mut Io) -> Result<u8> {
|
||||
let report =
|
||||
wordcraft_validate::validate_path(&a.file).map_err(|e| CliError::Failed(escape_text(&format!("{}: {e}", a.file.display()), false)))?;
|
||||
let written = if a.json {
|
||||
let json = serde_json::to_string_pretty(&report).unwrap_or_default();
|
||||
write_stdout(io, |o| writeln!(o, "{json}"))
|
||||
} else {
|
||||
write_stdout(io, |o| write_validate_report(o, &report))
|
||||
};
|
||||
match written {
|
||||
// A reader closing early must not turn a FAIL or INCOMPLETE verdict into PASS.
|
||||
Ok(()) | Err(CliError::StdoutClosed) => {}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
Ok(match report.verdict {
|
||||
wordcraft_validate::Verdict::Pass => 0,
|
||||
wordcraft_validate::Verdict::Fail | wordcraft_validate::Verdict::Incomplete => 1,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,37 @@
|
||||
//! What stops a command, and how each case exits.
|
||||
|
||||
/// Why a CLI run stopped early.
|
||||
#[derive(Debug, PartialEq, thiserror::Error)]
|
||||
pub enum CliError {
|
||||
/// The command failed (exit 1); the text is already safe to print.
|
||||
#[error("{0}")]
|
||||
Failed(String),
|
||||
/// A mistake in the command line found after parsing (exit 2).
|
||||
#[error("{0}")]
|
||||
Usage(String),
|
||||
/// A strict export refused (exit 1): the report's lines, then its JSON line, ready for stderr.
|
||||
#[error("{0}")]
|
||||
Strict(String),
|
||||
/// Whoever read stdout closed it (`wordcraft-cli commands --json | head`): nobody is left to write to, so a quiet
|
||||
/// exit 0 (`validate` keeps its verdict's status).
|
||||
#[error("stdout closed")]
|
||||
StdoutClosed,
|
||||
}
|
||||
|
||||
impl From<String> for CliError {
|
||||
fn from(e: String) -> Self {
|
||||
CliError::Failed(e)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&str> for CliError {
|
||||
fn from(e: &str) -> Self {
|
||||
CliError::Failed(e.into())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<std::io::Error> for CliError {
|
||||
fn from(e: std::io::Error) -> Self {
|
||||
if e.kind() == std::io::ErrorKind::BrokenPipe { CliError::StdoutClosed } else { CliError::Failed(e.to_string()) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
//! Headless WordCraft (`wordcraft-cli`). [`run`] is the whole program, so it can be tested in-process as well as
|
||||
//! through the binary; `wordcraft-cli --help` lists the subcommands. The conventions are RFC-0018's: exit 0, 1 (a
|
||||
//! command failed) or 2 (a usage error), results on stdout, `error: <message>` on stderr.
|
||||
|
||||
mod args;
|
||||
mod commands;
|
||||
mod error;
|
||||
mod script;
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::io::Write;
|
||||
|
||||
use error::CliError;
|
||||
|
||||
pub use args::command;
|
||||
|
||||
/// Where a command writes: results to `out`, diagnostics and progress to `err`.
|
||||
pub(crate) struct Io<'a> {
|
||||
pub(crate) out: &'a mut dyn Write,
|
||||
pub(crate) err: &'a mut dyn Write,
|
||||
}
|
||||
|
||||
/// Writes a line of progress or a warning; a closed stderr is not worth an error.
|
||||
macro_rules! errln {
|
||||
($io:expr, $($arg:tt)*) => {
|
||||
drop(writeln!($io.err, $($arg)*))
|
||||
};
|
||||
}
|
||||
|
||||
pub(crate) use errln;
|
||||
|
||||
/// 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=")
|
||||
})
|
||||
}
|
||||
|
||||
/// Run the CLI on its arguments (without the program name), writing results to `out` and diagnostics to `err`.
|
||||
/// Returns the process exit code: 0 on success, 1 when a command failed, 2 for a usage error. Help and the version go
|
||||
/// to `out`, exit 0.
|
||||
pub fn run<I, T>(args: I, out: &mut dyn Write, err: &mut dyn Write) -> i32
|
||||
where
|
||||
I: IntoIterator<Item = T>,
|
||||
T: Into<OsString>,
|
||||
{
|
||||
let args: Vec<OsString> = args.into_iter().map(Into::into).collect();
|
||||
if launcher_profile_flag(&args) {
|
||||
let _ = writeln!(err, "error: --launch-profile and --profile-root are the desktop app's Nightly bootstrap, not a CLI option");
|
||||
return 2;
|
||||
}
|
||||
// Help and the version (`help`, `-h`, `<subcommand> --help`, `-V`) come back as errors too.
|
||||
let cli = match args::parse(&args) {
|
||||
Ok(cli) => cli,
|
||||
Err(e) => {
|
||||
let to: &mut dyn Write = if e.use_stderr() { err } else { out };
|
||||
let _ = write!(to, "{}", e.render());
|
||||
return e.exit_code();
|
||||
}
|
||||
};
|
||||
let mut io = Io { out, err };
|
||||
// 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);
|
||||
if let Some(source) = wordcraft_engine::packs::index_override() {
|
||||
errln!(io, "Language packs come from a test source: {source}");
|
||||
}
|
||||
match commands::dispatch(cli.command, &mut io) {
|
||||
Ok(code) => i32::from(code),
|
||||
// A reader that stopped early (a closed pipe) ends the program quietly, as ripgrep does.
|
||||
Err(CliError::StdoutClosed) => 0,
|
||||
Err(CliError::Usage(e)) => {
|
||||
errln!(io, "error: {e}");
|
||||
2
|
||||
}
|
||||
// The report's lines already start with `error:`.
|
||||
Err(CliError::Strict(report)) => {
|
||||
errln!(io, "{report}");
|
||||
1
|
||||
}
|
||||
Err(e) => {
|
||||
errln!(io, "error: {e}");
|
||||
1
|
||||
}
|
||||
}
|
||||
}
|
||||
+4
-1072
File diff suppressed because it is too large
Load Diff
+280
-448
@@ -1,5 +1,285 @@
|
||||
use super::*;
|
||||
use crate::launcher_profile_flag;
|
||||
use std::ffi::{OsStr, OsString};
|
||||
use std::io::Read;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// A failed in-process run: the exit code and what stderr said (without its `error: ` prefix).
|
||||
#[derive(Debug, PartialEq)]
|
||||
struct Fail {
|
||||
code: i32,
|
||||
text: String,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Fail {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(&self.text)
|
||||
}
|
||||
}
|
||||
|
||||
/// Run the whole CLI in this process, as the binary does.
|
||||
fn exec<S: AsRef<OsStr>>(args: &[S]) -> (i32, String, String) {
|
||||
let (mut out, mut err) = (Vec::new(), Vec::new());
|
||||
let code = crate::run(args.iter().map(|a| a.as_ref().to_owned()), &mut out, &mut err);
|
||||
(code, String::from_utf8_lossy(&out).into_owned(), String::from_utf8_lossy(&err).into_owned())
|
||||
}
|
||||
|
||||
/// `Ok` for exit 0, else the exit code and message.
|
||||
fn run<S: AsRef<OsStr>>(args: &[S]) -> std::result::Result<(), Fail> {
|
||||
let (code, _, err) = exec(args);
|
||||
if code == 0 { Ok(()) } else { Err(Fail { code, text: err.trim_end().strip_prefix("error: ").unwrap_or(err.trim_end()).to_owned() }) }
|
||||
}
|
||||
|
||||
fn args(values: &[&str]) -> Vec<String> {
|
||||
values.iter().map(|value| (*value).into()).collect()
|
||||
}
|
||||
|
||||
/// A usage error: exit 2, the message on stderr, nothing on stdout, and no work done.
|
||||
fn usage(argv: &[&str]) -> String {
|
||||
let (code, out, err) = exec(argv);
|
||||
assert_eq!((code, out.as_str()), (2, ""), "{argv:?}: {err}");
|
||||
err
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_and_scale_are_checked_before_any_file_is_opened() {
|
||||
for sub in [vec!["render", "missing.docx", "out.png"], vec!["run", "--template", "sample", "--save", "out.png"]] {
|
||||
let with = |extra: &[&str]| usage(&[&sub[..], extra].concat());
|
||||
for missing in [&["--page"][..], &["--scale"], &["--page", "--scale", "2"], &["--scale", "--page", "1"]] {
|
||||
with(missing);
|
||||
}
|
||||
assert!(with(&["--page", "banana"]).contains("invalid --page `banana`: not a valid integer"));
|
||||
assert!(with(&["--page", "0"]).contains("invalid --page `0`: page numbers start at 1"));
|
||||
with(&["--page", "-1"]);
|
||||
assert!(with(&["--scale", "banana"]).contains("invalid --scale `banana`: not a number"));
|
||||
for bad in ["0", "-2", "NaN", "inf"] {
|
||||
assert!(with(&["--scale", bad]).contains(&format!("invalid --scale `{bad}`: scale must be a finite positive number")));
|
||||
}
|
||||
with(&["--page", "1", "--page", "2"]);
|
||||
with(&["--scale", "1", "--scale", "2"]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_repeated_and_conflicting_options_are_usage_errors_before_file_access() {
|
||||
assert!(usage(&["info", "missing.docx", "--passwrod", "x"]).contains("--passwrod"));
|
||||
assert!(usage(&["render", "missing.docx", "out.png", "--sclae", "2"]).contains("--sclae"));
|
||||
assert!(usage(&["zotero", "refresh", "missing.docx", "--prot", "1"]).contains("--prot"));
|
||||
usage(&["convert", "missing.docx", "out.xml", "--format"]);
|
||||
usage(&["convert", "missing.docx", "out.xml", "--format", "--markup"]);
|
||||
usage(&["convert", "missing.docx", "out.xml", "--format", "flatopc", "--format", "wordml2003"]);
|
||||
assert!(usage(&["convert", "missing.docx", "out.xml", "--format", "docx"]).contains("wordml2003"));
|
||||
usage(&["convert", "missing.docx"]);
|
||||
usage(&["convert", "a.docx", "b.docx", "c.docx"]);
|
||||
usage(&["run", "--file", "a.docx", "--template", "blank"]);
|
||||
usage(&["info"]);
|
||||
usage(&["frobnicate"]);
|
||||
assert!(usage(&["convert", "missing.docx", "out.docx", "--strict"]).contains("--strict needs a .pdf or .png output"));
|
||||
// A valid single value reaches file access, rather than an option error.
|
||||
let (code, _, err) = exec(&["convert", "missing.docx", "out.xml", "--format", "flatopc"]);
|
||||
assert_eq!(code, 1);
|
||||
assert!(err.starts_with("error: missing.docx:"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmd_and_script_values_are_checked_by_the_parser() {
|
||||
for argv in [
|
||||
vec!["run", "--cmd"],
|
||||
vec!["run", "--cmd", "--save", "out.docx"],
|
||||
vec!["run", "--cmd", "caret.docEnd", "--cmd", "--print"],
|
||||
vec!["run", "--cmd", "--bogus"],
|
||||
vec!["run", "--script", "--cmd", "caret.docEnd"],
|
||||
] {
|
||||
usage(&argv);
|
||||
}
|
||||
assert!(usage(&["run", "--cmd", "text.insert={nope"]).contains("bad JSON params"));
|
||||
assert_eq!(run(&args(&["run", "--cmd", "caret.docEnd", "--cmd", "caret.docStart"])), Ok(()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_author_flag_names_the_headless_session() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
assert!(set_author(&mut s, " Claude (copyedit) ").is_ok());
|
||||
assert_eq!(s.author, "Claude (copyedit)");
|
||||
assert!(set_author(&mut s, " ").is_err_and(|e| e.starts_with("--author:")));
|
||||
assert_eq!(run(&args(&["run", "--author", "Claude", "--cmd", "review.trackChanges={\"value\":true}"])), Ok(()));
|
||||
// The flag goes through the same protection check as the command.
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.run("review.restrict", &json!({"mode": "readOnly"})).unwrap();
|
||||
let before = s.author.clone();
|
||||
assert!(set_author(&mut s, "Claude").is_err());
|
||||
assert_eq!(s.author, before);
|
||||
assert!(s.run("file.setAuthor", &json!({"name": "Claude"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_password_comes_from_an_option_or_a_file_and_never_shows_in_an_error() {
|
||||
let open = |password: Option<&str>, file: Option<&str>| Password { password: password.map(Into::into), password_file: file.map(PathBuf::from) };
|
||||
assert_eq!(password_from(&open(None, None)), Ok(None));
|
||||
assert_eq!(password_from(&open(Some("s3cret"), None)), Ok(Some("s3cret".into())));
|
||||
// `--password` wins over the file.
|
||||
assert_eq!(password_from(&open(Some("a"), Some("/nonexistent"))), Ok(Some("a".into())));
|
||||
let path = std::env::temp_dir().join(format!("wordcraft-cli-password-test-{}.txt", std::process::id()));
|
||||
std::fs::write(&path, "s3cret\r\n").unwrap();
|
||||
let got = password_from(&open(None, path.to_str()));
|
||||
std::fs::remove_file(&path).ok();
|
||||
assert_eq!(got, Ok(Some("s3cret".into())), "only the trailing newline is lost");
|
||||
let err = password_from(&open(None, Some("/nonexistent/secret.txt"))).unwrap_err().to_string();
|
||||
assert!(err.contains("--password-file"), "{err}");
|
||||
}
|
||||
|
||||
/// A password file on the command line beats the variable, a blank variable is unset, and `--help` shows neither value.
|
||||
#[test]
|
||||
fn the_password_variable_is_read_by_the_flag_and_hidden() {
|
||||
let parse = |argv: &[&str]| crate::args::parse(&argv.iter().map(OsString::from).collect::<Vec<_>>());
|
||||
let help = parse(&["info", "--help"]).unwrap_err().render().to_string();
|
||||
assert!(help.contains("WORDCRAFT_PASSWORD") || help.contains("--password"), "{help}");
|
||||
let Err(e) = parse(&["info", "--password"]) else { panic!("a missing value must not parse") };
|
||||
assert_eq!(e.exit_code(), 2);
|
||||
let top = parse(&["--help"]).unwrap_err().render().to_string();
|
||||
assert!(top.contains("WORDCRAFT_PASSWORD") && top.contains("WORDCRAFT_REGION") && top.contains("Exit status"), "{top}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mcp_needs_both_roots_and_refuses_connect() {
|
||||
let scratch = Scratch::new("entry");
|
||||
let base = scratch.0.clone();
|
||||
std::fs::create_dir_all(base.join("in")).unwrap();
|
||||
std::fs::create_dir_all(base.join("out")).unwrap();
|
||||
let read = format!("--automation-read-root={}", base.join("in").display());
|
||||
let write = format!("--automation-write-root={}", base.join("out").display());
|
||||
for given in [vec![], vec![read.clone()], vec![write.clone()], vec!["--author".to_string(), "Claude".to_string()]] {
|
||||
let line = [vec!["mcp".to_string()], given].concat();
|
||||
let err = usage(&line.iter().map(String::as_str).collect::<Vec<_>>());
|
||||
assert!(err.contains("--automation-read-root") || err.contains("--automation-write-root"), "{line:?}: {err}");
|
||||
}
|
||||
let missing = usage(&["mcp", "--automation-read-root", "a", "--automation-read-root=b", "--automation-write-root", "c"]);
|
||||
assert!(missing.contains("--automation-read-root"), "{missing}");
|
||||
usage(&["mcp", "--automation-read-root=", "--automation-write-root=x"]);
|
||||
// A folder that does not exist is an error, not a server that quietly runs unconfined.
|
||||
let (code, _, err) = exec(&["mcp", "--automation-read-root", "/definitely/not/a/folder", "--automation-write-root", "/definitely/not/a/folder"]);
|
||||
assert_eq!(code, 1);
|
||||
assert!(err.starts_with("error: mcp: cannot open the automation read root"), "{err}");
|
||||
// `--connect` is refused whether or not it has roots, before anything connects (#3695, #5819).
|
||||
let dir = base.to_string_lossy().into_owned();
|
||||
for line in [
|
||||
args(&["mcp", "--connect", "127.0.0.1:9"]),
|
||||
args(&["mcp", "--connect=127.0.0.1:9", "--author", "Claude"]),
|
||||
args(&["mcp", "--connect", "127.0.0.1:9", "--automation-read-root", &dir, "--automation-write-root", &dir]),
|
||||
] {
|
||||
let (code, _, err) = exec(&line);
|
||||
assert_eq!(code, 1, "{line:?}");
|
||||
assert!(err.contains("--connect") && err.contains("#3695") && err.contains("#5819"), "{line:?}: {err}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_file_opening_subcommand_reaches_the_open_with_a_non_unicode_name_but_not_an_output() {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
let latin1 = || OsString::from_vec(b"/definitely/not/caf\xe9.docx".to_vec());
|
||||
for argv in [
|
||||
vec![OsString::from("convert"), latin1(), "out.pdf".into()],
|
||||
vec!["info".into(), latin1()],
|
||||
vec!["text".into(), latin1()],
|
||||
vec!["inspect".into(), latin1()],
|
||||
vec!["render".into(), latin1(), "out.png".into()],
|
||||
vec!["run".into(), "--file".into(), latin1()],
|
||||
vec!["zotero".into(), "refresh".into(), latin1()],
|
||||
] {
|
||||
let (code, _, err) = exec(&argv);
|
||||
assert_eq!(code, 1, "{argv:?}: {err}");
|
||||
assert!(err.contains("No such file"), "{argv:?}: {err}");
|
||||
}
|
||||
// An output the engine takes as text must be Unicode: a failure, and nothing opened.
|
||||
let out = OsString::from_vec(b"caf\xe9.png".to_vec());
|
||||
let (code, _, err) = exec(&["render".into(), OsString::from("in.docx"), out]);
|
||||
assert_eq!(code, 1);
|
||||
assert!(err.contains("not valid Unicode"), "{err}");
|
||||
// Elsewhere clap refuses it as usage.
|
||||
assert_eq!(exec(&["run".into(), OsString::from("--template"), OsString::from_vec(b"caf\xe9".to_vec())]).0, 2);
|
||||
}
|
||||
}
|
||||
|
||||
/// `validate`: PASS is 0; FAIL, INCOMPLETE and a file that can't be read are 1 (RFC-0018 rule 1.2); usage is 2.
|
||||
#[test]
|
||||
fn validate_exits_0_for_pass_1_for_anything_else_and_2_for_usage() {
|
||||
let dir = script_dir("validate-exit");
|
||||
let good = dir.join("good.docx");
|
||||
run(&args(&["run", "--template", "sample", "--save", &good.to_string_lossy()])).unwrap();
|
||||
let good = good.to_string_lossy().into_owned();
|
||||
let (code, out, _) = exec(&["validate", &good]);
|
||||
assert_eq!((code, out.lines().next()), (0, Some("PASS")));
|
||||
let (code, out, _) = exec(&["validate", "--json", &good]);
|
||||
assert_eq!(code, 0);
|
||||
assert!(out.contains("\"verdict\""), "{out}");
|
||||
let broken = dir.join("broken.docx");
|
||||
std::fs::write(&broken, b"not a zip").unwrap();
|
||||
let (code, out, _) = exec(&["validate".to_string(), broken.to_string_lossy().into_owned()]);
|
||||
assert_eq!(code, 1, "{out}");
|
||||
assert!(out.starts_with("FAIL") || out.starts_with("INCOMPLETE"), "{out}");
|
||||
let (code, _, err) = exec(&["validate", "/definitely/not/there.docx"]);
|
||||
assert_eq!(code, 1);
|
||||
assert!(err.starts_with("error: /definitely/not/there.docx:"), "{err}");
|
||||
usage(&["validate"]);
|
||||
usage(&["validate", &good, &good]);
|
||||
usage(&["validate", &good, "--bogus"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn help_and_version_go_to_stdout_with_exit_0() {
|
||||
for argv in [vec!["--version"], vec!["-V"], vec!["--help"], vec!["-h"], vec!["help"], vec!["convert", "--help"], vec!["help", "validate"]] {
|
||||
let (code, out, err) = exec(&argv);
|
||||
assert_eq!((code, err.as_str()), (0, ""), "{argv:?}");
|
||||
assert!(out.contains("wordcraft-cli"), "{argv:?}: {out}");
|
||||
}
|
||||
let (_, out, _) = exec(&["--version"]);
|
||||
assert_eq!(out.trim(), format!("wordcraft-cli {}", env!("CARGO_PKG_VERSION")));
|
||||
// The version is not a subcommand; with no arguments the help is shown as an error, exit 2.
|
||||
usage(&["version"]);
|
||||
assert_eq!(exec::<&str>(&[]).0, 2);
|
||||
// Every subcommand's help ends with the exit status.
|
||||
for sub in crate::command().get_subcommands().map(|c| c.get_name().to_owned()).filter(|n| n != "help") {
|
||||
let (code, out, _) = exec(&[sub.as_str(), "--help"]);
|
||||
assert_eq!(code, 0, "{sub}");
|
||||
assert!(out.contains("Exit status"), "{sub}: {out}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_launcher_bootstrap_exits_2_before_anything_runs() {
|
||||
let err = usage(&["--launch-profile=nightly-v1", "info", "x.docx"]);
|
||||
assert!(err.starts_with("error: --launch-profile and --profile-root"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_closed_stdout_ends_quietly_and_other_write_errors_fail() {
|
||||
struct Closed(std::io::ErrorKind);
|
||||
impl Write for Closed {
|
||||
fn write(&mut self, _: &[u8]) -> std::io::Result<usize> {
|
||||
Err(self.0.into())
|
||||
}
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
Err(self.0.into())
|
||||
}
|
||||
}
|
||||
let mut err = Vec::new();
|
||||
assert_eq!(crate::run(["commands"], &mut Closed(std::io::ErrorKind::BrokenPipe), &mut err), 0);
|
||||
assert!(err.is_empty());
|
||||
assert_eq!(crate::run(["commands"], &mut Closed(std::io::ErrorKind::PermissionDenied), &mut err), 1);
|
||||
assert!(String::from_utf8_lossy(&err).starts_with("error: "));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convert_strict_and_render_strict_refusals_exit_1() {
|
||||
// A document whose text can't be drawn is a refusal: exit 1 with the report on stderr and no file.
|
||||
let dir = script_dir("strict-exit");
|
||||
let out = dir.join("out.pdf");
|
||||
let (code, _, err) = exec(&["convert", "/definitely/not/there.docx", &out.to_string_lossy(), "--strict"]);
|
||||
assert_eq!(code, 1, "{err}");
|
||||
assert!(!out.exists());
|
||||
}
|
||||
|
||||
/// The desktop app's Nightly bootstrap is never a CLI option, in either spelling.
|
||||
#[test]
|
||||
@@ -18,10 +298,6 @@ fn the_launcher_profile_bootstrap_is_refused_in_both_forms() {
|
||||
}
|
||||
}
|
||||
|
||||
fn args(values: &[&str]) -> Vec<String> {
|
||||
values.iter().map(|value| (*value).into()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn peer_text_stays_on_one_visible_line() {
|
||||
let alert = "Done.\nwrote /etc/passwd\r\u{1b}[2J\u{9b}31m\u{202e}txt.exe\\n\tok é";
|
||||
@@ -31,127 +307,12 @@ fn peer_text_stays_on_one_visible_line() {
|
||||
assert_eq!(escape_peer("Citation (Doe, 2020) — “ok”"), "Citation (Doe, 2020) — “ok”");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validators_accept_only_the_documented_options() {
|
||||
assert!(validate_options("info", &args(&["file.docx"]), PASSWORD_OPTIONS).is_ok());
|
||||
assert!(validate_options("render", &args(&["in.docx", "out.png", "--page", "2", "--scale", "1.5"]), RENDER_OPTIONS).is_ok());
|
||||
assert!(validate_options("run", &args(&["--cmd", "text.insert={}", "--cmd", "edit.undo", "--print"]), RUN_OPTIONS).is_ok());
|
||||
assert!(validate_options("commands", &args(&["--json"]), COMMANDS_OPTIONS).is_ok());
|
||||
assert!(validate_options("parity", &args(&["--markdown"]), PARITY_OPTIONS).is_ok());
|
||||
assert!(validate_options("mcp", &args(&["--connect", "127.0.0.1:9000"]), MCP_OPTIONS).is_ok());
|
||||
assert!(validate_options("render", &args(&["in.docx", "out.png", "--page"]), RENDER_OPTIONS).is_ok());
|
||||
assert!(
|
||||
validate_options(
|
||||
"zotero",
|
||||
&args(&["refresh", "in.docx", "--cmd", "caret.docEnd", "--save", "out.docx", "--trace", "--port", "23119"]),
|
||||
ZOTERO_OPTIONS
|
||||
)
|
||||
.is_ok()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_option_value_is_never_read_as_a_path() {
|
||||
// `--password`'s value sits between the paths and would be taken for one without
|
||||
// `positionals`, so `render` would write its picture over a file called after the password.
|
||||
assert_eq!(positionals(&args(&["in.docx", "--password", "secret", "out.png"]), RENDER_OPTIONS), vec!["in.docx", "out.png"]);
|
||||
assert_eq!(positionals(&args(&["in.docx", "out.png", "--page", "2"]), RENDER_OPTIONS), vec!["in.docx", "out.png"]);
|
||||
// A bare flag takes no value, so the next argument stays a path.
|
||||
assert_eq!(positionals(&args(&["--print", "in.docx"]), RUN_OPTIONS), vec!["in.docx"]);
|
||||
// `convert` is the one with a value-taking flag between the two paths.
|
||||
assert_eq!(positionals(&args(&["in.docx", "--format", "flatopc", "out.docx"]), CONVERT_OPTIONS), vec!["in.docx", "out.docx"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_password_comes_from_an_option_a_file_or_the_environment() {
|
||||
assert_eq!(password_from(&args(&["f.docx"])), Ok(None));
|
||||
assert_eq!(password_from(&args(&["f.docx", "--password", "s3cret"])), Ok(Some("s3cret".into())));
|
||||
// `--password` wins over the other two sources.
|
||||
assert_eq!(password_from(&args(&["--password", "a", "--password-file", "/nonexistent"])), Ok(Some("a".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_password_file_loses_only_its_trailing_newline() {
|
||||
let path = std::env::temp_dir().join("wordcraft-cli-password-test.txt");
|
||||
std::fs::write(&path, "s3cret\r\n").unwrap();
|
||||
let got = password_from(&args(&["f.docx", "--password-file", &path.to_string_lossy()]));
|
||||
std::fs::remove_file(&path).ok();
|
||||
assert_eq!(got, Ok(Some("s3cret".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_password_file_is_named_without_the_password() {
|
||||
let err = password_from(&args(&["f.docx", "--password-file", "/nonexistent/secret.txt"])).unwrap_err();
|
||||
assert!(err.contains("--password-file"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_options_are_rejected_before_file_access() {
|
||||
assert_eq!(run(&args(&["info", "missing.docx", "--passwrod", "x"])), Err("info: unknown option --passwrod".into()));
|
||||
assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--sclae", "2"])), Err("render: unknown option --sclae".into()));
|
||||
assert_eq!(run(&args(&["zotero", "refresh", "missing.docx", "--prot", "1"])), Err("zotero: unknown option --prot".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convert_rejects_malformed_format_options_before_file_access() {
|
||||
for (options, error) in [
|
||||
(vec!["--format"], "convert: --format requires a value"),
|
||||
(vec!["--format", "--markup"], "convert: --format requires a value"),
|
||||
(vec!["--format", "flatopc", "--format", "wordml2003"], "convert: duplicate --format option"),
|
||||
] {
|
||||
let mut argv = args(&["convert", "missing.docx", "out.xml"]);
|
||||
argv.extend(args(&options));
|
||||
assert_eq!(run(&argv), Err(error.into()), "{options:?}");
|
||||
}
|
||||
// A valid single value reaches file access, rather than a format-option error.
|
||||
let error = run(&args(&["convert", "missing.docx", "out.xml", "--format", "flatopc"])).unwrap_err().to_string();
|
||||
assert!(error.starts_with("missing.docx:"), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn help_or_h_after_a_subcommand_asks_for_the_usage() {
|
||||
for cmd in SUBCOMMANDS {
|
||||
assert!(wants_help(cmd, &args(&["in.docx", "--help"])), "{cmd}");
|
||||
assert!(wants_help(cmd, &args(&["-h"])), "{cmd}");
|
||||
assert!(!wants_help(cmd, &args(&["in.docx", "--hepl"])), "{cmd}");
|
||||
}
|
||||
assert!(!wants_help("frobnicate", &args(&["--help"])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn usage_lists_exactly_the_subcommands() {
|
||||
let listed: Vec<&str> = USAGE
|
||||
.lines()
|
||||
.filter_map(|line| line.strip_prefix(" wordcraft-cli ")?.split_whitespace().next())
|
||||
.filter(|word| !word.starts_with(['-', '[']))
|
||||
.collect();
|
||||
assert_eq!(listed, SUBCOMMANDS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_keeps_bullet_and_number_labels() {
|
||||
let doc = wordcraft_engine::io::open_bytes("lists.md", b"- alpha\n- beta\n\n1. first\n2. second\n").unwrap();
|
||||
assert_eq!(listed_text(&doc).unwrap(), "\u{2022}\talpha\n\u{2022}\tbeta\n1.\tfirst\n2.\tsecond");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn author_flag_names_the_headless_session() {
|
||||
assert!(validate_options("run", &args(&["--author", "Claude (copyedit)", "--cmd", "edit.undo"]), RUN_OPTIONS).is_ok());
|
||||
assert!(validate_options("mcp", &args(&["--author", "Claude"]), MCP_OPTIONS).is_ok());
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
assert!(set_author(&mut s, " Claude (copyedit) ").is_ok());
|
||||
assert_eq!(s.author, "Claude (copyedit)");
|
||||
assert!(set_author(&mut s, " ").is_err_and(|e| e.starts_with("--author:")));
|
||||
assert!(run(&args(&["run", "--author", "Claude", "--cmd", "review.trackChanges={\"value\":true}"])).is_ok());
|
||||
// The flag goes through the same protection check as the command.
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.run("review.restrict", &json!({"mode": "readOnly"})).unwrap();
|
||||
let before = s.author.clone();
|
||||
assert!(set_author(&mut s, "Claude").is_err());
|
||||
assert_eq!(s.author, before);
|
||||
assert!(s.run("file.setAuthor", &json!({"name": "Claude"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn author_flag_cannot_claim_a_named_exception_after_protection() {
|
||||
use wordcraft_doc::{CharProps, InlineObject, StoryRef};
|
||||
@@ -170,91 +331,6 @@ fn author_flag_cannot_claim_a_named_exception_after_protection() {
|
||||
assert!(s.run("text.insert", &json!({"text": "Changed"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn automation_root_flags_are_taken_out_of_the_mcp_arguments() {
|
||||
let base = std::env::temp_dir().join(format!("wc-cli-roots-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
std::fs::create_dir_all(base.join("in")).unwrap();
|
||||
std::fs::create_dir_all(base.join("out")).unwrap();
|
||||
let (read, write) = (base.join("in").to_string_lossy().into_owned(), base.join("out").to_string_lossy().into_owned());
|
||||
|
||||
let (roots, left) =
|
||||
automation_roots("mcp", &args(&["--automation-read-root", &read, "--author", "Claude", &format!("--automation-write-root={write}")]))
|
||||
.unwrap();
|
||||
let roots = roots.unwrap();
|
||||
assert_eq!(left, args(&["--author", "Claude"]));
|
||||
assert!(roots.read_root().is_some() && roots.write_root().is_some());
|
||||
assert!(validate_options("mcp", &left, MCP_OPTIONS).is_ok());
|
||||
|
||||
// A root left out grants none of its access.
|
||||
let (roots, _) = automation_roots("mcp", &args(&["--automation-read-root", &read])).unwrap();
|
||||
let roots = roots.unwrap();
|
||||
assert!(roots.write_root().is_none());
|
||||
assert!(roots.check(&format!("{write}/x.docx"), wordcraft_engine::file_access::Access::Write).unwrap_err().contains("write authority is absent"));
|
||||
|
||||
// No flags: nothing is confined and the arguments pass through.
|
||||
let (roots, left) = automation_roots("mcp", &args(&["--connect", "127.0.0.1:9"])).unwrap();
|
||||
assert!(roots.is_none());
|
||||
assert_eq!(left, args(&["--connect", "127.0.0.1:9"]));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn automation_root_flags_reject_bad_operands_and_missing_folders() {
|
||||
for bad in [
|
||||
args(&["--automation-read-root"]),
|
||||
args(&["--automation-read-root", "--author"]),
|
||||
args(&["--automation-write-root="]),
|
||||
args(&["--automation-read-root", "a", "--automation-read-root=b"]),
|
||||
] {
|
||||
assert!(automation_roots("mcp", &bad).is_err(), "{bad:?}");
|
||||
}
|
||||
let e = automation_roots("mcp", &args(&["--automation-read-root", "/definitely/not/a/folder"])).err().unwrap();
|
||||
assert!(e.starts_with("mcp: cannot open the automation read root"), "{e}");
|
||||
// Through the command line: an error, not a server that quietly runs unconfined.
|
||||
assert!(run(&args(&["mcp", "--automation-write-root", "/definitely/not/a/folder"])).is_err());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn only_the_opened_file_may_be_other_than_unicode() {
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
let latin1 = || OsString::from_vec(b"caf\xe9.docx".to_vec());
|
||||
let ok = |raw: Vec<OsString>| text_args(&raw).unwrap().1;
|
||||
assert_eq!(ok(vec!["zotero".into(), "refresh".into(), latin1()]), Some(PathBuf::from(latin1())));
|
||||
assert_eq!(ok(vec!["render".into(), latin1(), "out.png".into(), "--page".into(), "2".into()]), Some(PathBuf::from(latin1())));
|
||||
assert_eq!(ok(vec!["render".into(), "--page".into(), "2".into(), latin1(), "out.png".into()]), Some(PathBuf::from(latin1())));
|
||||
assert_eq!(ok(vec!["convert".into(), "--format".into(), "flatopc".into(), latin1(), "out.xml".into()]), Some(PathBuf::from(latin1())));
|
||||
assert_eq!(ok(vec!["info".into(), "--password".into(), "secret".into(), latin1()]), Some(PathBuf::from(latin1())));
|
||||
assert_eq!(ok(vec!["zotero".into(), "--port".into(), "23119".into(), "refresh".into(), latin1()]), Some(PathBuf::from(latin1())));
|
||||
assert_eq!(ok(vec!["run".into(), "--print".into(), "--file".into(), latin1()]), Some(PathBuf::from(latin1())));
|
||||
assert_eq!(ok(vec!["info".into(), "in.docx".into()]), None);
|
||||
// Every command that opens a file reaches the open with it (no such file here), so
|
||||
// `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()]);
|
||||
for raw in opening {
|
||||
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),
|
||||
(vec!["render".into(), "--page".into(), latin1(), "in.docx".into(), "out.png".into()], 3),
|
||||
(vec!["run".into(), "--save".into(), latin1()], 3),
|
||||
(vec!["commands".into(), latin1()], 2),
|
||||
] {
|
||||
assert_eq!(text_args(&raw).unwrap_err(), format!("argument {n} is not valid Unicode: caf\u{FFFD}.docx"));
|
||||
}
|
||||
}
|
||||
|
||||
/// An exclusively created scratch folder, removed on drop even when an assertion fails.
|
||||
struct Scratch(PathBuf);
|
||||
|
||||
@@ -281,66 +357,6 @@ impl Drop for Scratch {
|
||||
}
|
||||
}
|
||||
|
||||
/// Shared rule 18 (#7124): every agent entry point, a subcommand that serves a client's requests
|
||||
/// rather than running what the person typed and exiting, refuses to start without both
|
||||
/// automation roots. Each subcommand has a row, so a new one fails here until it is classified,
|
||||
/// and a new agent entry point fails until it refuses.
|
||||
#[test]
|
||||
fn every_agent_entry_point_refuses_to_start_without_both_roots() {
|
||||
enum Kind {
|
||||
Agent,
|
||||
NotAgent(&'static str),
|
||||
}
|
||||
use Kind::{Agent, NotAgent};
|
||||
let table = [
|
||||
("convert", NotAgent("converts the files named on its command line, then exits")),
|
||||
("info", NotAgent("reads the one file named on its command line, then exits")),
|
||||
("text", NotAgent("reads the one file named on its command line, then exits")),
|
||||
("inspect", NotAgent("reads the one file named on its command line, then exits")),
|
||||
("render", NotAgent("renders the file named on its command line, then exits")),
|
||||
("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")),
|
||||
];
|
||||
assert_eq!(table.iter().map(|(name, _)| *name).collect::<Vec<_>>(), SUBCOMMANDS);
|
||||
|
||||
let scratch = Scratch::new("entry");
|
||||
let base = scratch.0.clone();
|
||||
std::fs::create_dir_all(base.join("in")).unwrap();
|
||||
std::fs::create_dir_all(base.join("out")).unwrap();
|
||||
let read = format!("--automation-read-root={}", base.join("in").display());
|
||||
let write = format!("--automation-write-root={}", base.join("out").display());
|
||||
for (name, kind) in table {
|
||||
if let NotAgent(why) = kind {
|
||||
assert!(!why.is_empty(), "{name}: say why it is not an agent entry point");
|
||||
continue;
|
||||
}
|
||||
for given in [vec![], vec![read.clone()], vec![write.clone()], vec!["--author".to_string(), "Claude".to_string()]] {
|
||||
let line = [vec![name.to_string()], given].concat();
|
||||
let e = run(&line).unwrap_err().to_string();
|
||||
assert!(e.contains("--automation-read-root") && e.contains("--automation-write-root"), "{line:?}: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The desktop app doesn't confine its control channel to roots yet (#3695, #5819), so the bridge
|
||||
/// to it is refused, with roots or without, before anything connects.
|
||||
#[test]
|
||||
fn mcp_connect_is_refused_until_the_app_confines_its_control_channel() {
|
||||
let dir = std::env::temp_dir().to_string_lossy().into_owned();
|
||||
for line in [
|
||||
args(&["mcp", "--connect", "127.0.0.1:9"]),
|
||||
args(&["mcp", "--connect", "127.0.0.1:9", "--author", "Claude"]),
|
||||
args(&["mcp", "--connect", "127.0.0.1:9", "--automation-read-root", &dir, "--automation-write-root", &dir]),
|
||||
] {
|
||||
let e = run(&line).unwrap_err().to_string();
|
||||
assert!(e.contains("--connect") && e.contains("#3695") && e.contains("#5819"), "{line:?}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// `mcp`'s headless session takes `--author` as the session's author, and refuses a blank one as `run` does.
|
||||
#[test]
|
||||
fn mcp_headless_session_takes_the_author_flag() {
|
||||
@@ -352,120 +368,6 @@ fn mcp_headless_session_takes_the_author_flag() {
|
||||
assert_eq!(unnamed.session.author, wordcraft_mcp::Headless::default().session.author, "no flag keeps the default author");
|
||||
}
|
||||
|
||||
/// `--connect` is refused whether or not it has a value, written apart or as `--connect=…`, even with both roots valid.
|
||||
#[test]
|
||||
fn mcp_connect_is_refused_without_a_value_too() {
|
||||
let scratch = Scratch::new("connect-bare");
|
||||
let dir = scratch.0.to_string_lossy().into_owned();
|
||||
let roots = ["--automation-read-root", &dir, "--automation-write-root", &dir];
|
||||
for tail in [vec!["--connect"], vec!["--connect", "--author", "Claude"], vec!["--connect=127.0.0.1:9"], vec!["--connect="]] {
|
||||
let line = args(&[&["mcp"][..], &roots, &tail].concat());
|
||||
let e = run(&line).unwrap_err().to_string();
|
||||
assert!(e.contains("--connect") && e.contains("#3695") && e.contains("#5819"), "{line:?}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_rejects_missing_or_invalid_page_and_scale() {
|
||||
// Missing operands
|
||||
assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--page"])), Err("render: --page requires a value".into()));
|
||||
assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--scale"])), Err("render: --scale requires a value".into()));
|
||||
assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--page", "--scale", "2"])), Err("render: --page requires a value".into()));
|
||||
assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--scale", "--page", "1"])), Err("render: --scale requires a value".into()));
|
||||
|
||||
// Non-numeric operands
|
||||
assert_eq!(
|
||||
run(&args(&["render", "missing.docx", "out.png", "--page", "banana"])),
|
||||
Err("render: invalid --page `banana`: not a valid integer".into())
|
||||
);
|
||||
assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--scale", "banana"])), Err("render: invalid --scale `banana`: not a number".into()));
|
||||
|
||||
// Out-of-range values
|
||||
assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--page", "0"])), Err("render: invalid --page `0`: page numbers start at 1".into()));
|
||||
assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--page", "-1"])), Err("render: invalid --page `-1`: not a valid integer".into()));
|
||||
assert_eq!(
|
||||
run(&args(&["render", "missing.docx", "out.png", "--scale", "0"])),
|
||||
Err("render: invalid --scale `0`: scale must be a finite positive number".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["render", "missing.docx", "out.png", "--scale", "-2"])),
|
||||
Err("render: invalid --scale `-2`: scale must be a finite positive number".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["render", "missing.docx", "out.png", "--scale", "NaN"])),
|
||||
Err("render: invalid --scale `NaN`: scale must be a finite positive number".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["render", "missing.docx", "out.png", "--scale", "inf"])),
|
||||
Err("render: invalid --scale `inf`: scale must be a finite positive number".into())
|
||||
);
|
||||
|
||||
// Duplicate options
|
||||
assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--page", "1", "--page", "2"])), Err("render: duplicate --page option".into()));
|
||||
assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--scale", "1", "--scale", "2"])), Err("render: duplicate --scale option".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_rejects_missing_or_invalid_page_and_scale() {
|
||||
// Missing operands
|
||||
assert_eq!(run(&args(&["run", "--template", "sample", "--save", "out.png", "--page"])), Err("run: --page requires a value".into()));
|
||||
assert_eq!(run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale"])), Err("run: --scale requires a value".into()));
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--page", "--scale", "2"])),
|
||||
Err("run: --page requires a value".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale", "--page", "1"])),
|
||||
Err("run: --scale requires a value".into())
|
||||
);
|
||||
|
||||
// Non-numeric operands
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--page", "banana"])),
|
||||
Err("run: invalid --page `banana`: not a valid integer".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale", "banana"])),
|
||||
Err("run: invalid --scale `banana`: not a number".into())
|
||||
);
|
||||
|
||||
// Out-of-range values
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--page", "0"])),
|
||||
Err("run: invalid --page `0`: page numbers start at 1".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--page", "-1"])),
|
||||
Err("run: invalid --page `-1`: not a valid integer".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale", "0"])),
|
||||
Err("run: invalid --scale `0`: scale must be a finite positive number".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale", "-1"])),
|
||||
Err("run: invalid --scale `-1`: scale must be a finite positive number".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale", "NaN"])),
|
||||
Err("run: invalid --scale `NaN`: scale must be a finite positive number".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale", "inf"])),
|
||||
Err("run: invalid --scale `inf`: scale must be a finite positive number".into())
|
||||
);
|
||||
|
||||
// Duplicate options
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--page", "1", "--page", "2"])),
|
||||
Err("run: duplicate --page option".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale", "1", "--scale", "2"])),
|
||||
Err("run: duplicate --scale option".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_and_run_valid_options_and_defaults_produce_files() {
|
||||
let dir = std::env::temp_dir().join(format!("wc-cli-render-{}", std::process::id()));
|
||||
@@ -615,33 +517,6 @@ fn command_line_template_wins_over_the_scripts_file() {
|
||||
assert!(std::fs::read_to_string(&b).unwrap().contains("FROM FILE"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmd_value_missing_is_reported() {
|
||||
let missing = std::env::temp_dir().join(format!(
|
||||
"wc-cli-missing-cmd-{}-{}.docx",
|
||||
std::process::id(),
|
||||
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_nanos()
|
||||
));
|
||||
assert!(!missing.exists());
|
||||
let missing = missing.to_string_lossy();
|
||||
for argv in [
|
||||
vec!["run", "--cmd"],
|
||||
vec!["run", "--cmd", "--save", "out.docx"],
|
||||
vec!["run", "--cmd", "caret.docEnd", "--cmd", "--print"],
|
||||
vec!["run", "--cmd", "--bogus"],
|
||||
vec!["run", "--cmd", "--file", &missing],
|
||||
] {
|
||||
assert_eq!(run(&args(&argv)), Err("--cmd needs a value".into()), "{argv:?}");
|
||||
}
|
||||
assert!(run(&args(&["run", "--cmd", "caret.docEnd", "--cmd", "caret.docStart"])).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_value_missing_is_reported() {
|
||||
let e = run(&args(&["run", "--script", "--cmd", "caret.docEnd"])).unwrap_err().to_string();
|
||||
assert!(e.contains("--script requires a value"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_reads_from_a_stream_and_caps_its_size() {
|
||||
let s = script::load_from(&br#"{"commands":["caret.docEnd"],"save":["o.docx"]}"#[..], "-", None).unwrap();
|
||||
@@ -704,34 +579,6 @@ fn script_parse_resolves_paths_against_the_base() {
|
||||
assert_eq!(s.commands.len(), 1);
|
||||
}
|
||||
|
||||
/// Finding 3: a surplus operand is a usage error (exit 3) rejected in the operand check, before any
|
||||
/// file is validated, so a valid first path can no longer make `validate a.docx b.docx` print PASS.
|
||||
/// The two paths are DIFFERENT files and validating either one would return `Ok`; the code path
|
||||
/// returns `Status(3)` from the `paths.len() != 1` check before `validate_path` runs, so no file was
|
||||
/// validated to produce it. (A `Status(3)` on its own does not prove that — `validate` also returns
|
||||
/// it for an I/O error after a single valid operand reaches the validator — which is why the
|
||||
/// operand check, not the status, is what establishes the rejection happened first.)
|
||||
#[test]
|
||||
fn validate_rejects_missing_or_surplus_operands_without_validating() {
|
||||
let dir = std::env::temp_dir().join(format!("wc-cli-validate-args-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let first = dir.join("first.docx");
|
||||
let second = dir.join("second.docx");
|
||||
run(&args(&["run", "--template", "sample", "--save", &first.to_string_lossy()])).unwrap();
|
||||
run(&args(&["run", "--template", "sample", "--save", &second.to_string_lossy()])).unwrap();
|
||||
let (first, second) = (first.to_string_lossy().into_owned(), second.to_string_lossy().into_owned());
|
||||
assert_ne!(first, second, "the two operands must be different files");
|
||||
assert_eq!(run(&args(&["validate", &first])), Ok(()), "one valid path reports PASS");
|
||||
assert_eq!(
|
||||
run(&args(&["validate", &first, &second])),
|
||||
Err(Failure::Status(3)),
|
||||
"two different paths are a usage error; validating either would return Ok, so it validated neither"
|
||||
);
|
||||
assert_eq!(run(&args(&["validate"])), Err(Failure::Status(3)), "no path is a usage error");
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// Finding 4: `validate` is in `OPENS_FILE`, so a file name that is not valid Unicode reaches the
|
||||
/// validator by its preserved path rather than being rejected as a bad argument.
|
||||
/// APFS refuses invalid UTF-8 file names, so macOS covers native path handling without creating one.
|
||||
@@ -827,18 +674,3 @@ fn invisible_characters_are_escaped_and_json_lines_still_parse_back() {
|
||||
assert!(line.contains("\\ud800") || line.contains("\\udb40"), "{line}");
|
||||
assert_eq!(serde_json::from_str::<Value>(&line).unwrap(), value);
|
||||
}
|
||||
|
||||
/// Native non-Unicode paths survive argument parsing and reach the validator's I/O error path.
|
||||
/// No file is created: APFS refuses invalid UTF-8 names. The original bytes, rather than their
|
||||
/// lossy display spelling, must be retained even when options precede the operand.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn validate_preserves_a_non_unicode_path_without_creating_a_file() {
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
let raw_path = OsString::from_vec(b"wordcraft-nonexistent-caf\xe9.docx".to_vec());
|
||||
let raw = vec![OsString::from("validate"), OsString::from("--json"), raw_path.clone()];
|
||||
let (_, parsed) = text_args(&raw).unwrap();
|
||||
assert_eq!(parsed.as_deref(), Some(Path::new(&raw_path)));
|
||||
assert!(parsed.as_deref().unwrap().to_str().is_none());
|
||||
assert_eq!(run(&raw), Err(Failure::Status(3)), "native path reaches I/O handling");
|
||||
}
|
||||
|
||||
@@ -59,7 +59,7 @@ fn validate_closed_stdout_preserves_verdict() {
|
||||
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 (fixture, expected) in [(pass.clone(), 0), (corpus.join("14-comment-dup.docx"), 1), (sparse.clone(), 1)] {
|
||||
for json in [false, true] {
|
||||
let mut open = cli();
|
||||
open.arg("validate").arg(&fixture);
|
||||
@@ -87,7 +87,7 @@ fn validate_closed_stdout_preserves_verdict() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Other report-write failures are I/O status 3; a child-only file-size limit forces EFBIG on stdout.
|
||||
/// Other report-write failures are status 1 (RFC-0018: there is no 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");
|
||||
@@ -105,7 +105,7 @@ fn validate_stdout_write_error_is_io_status() {
|
||||
}
|
||||
std::fs::remove_file(stdout).unwrap();
|
||||
for (json, output) in results {
|
||||
assert_eq!(output.status.code(), Some(3), "json={json}: {output:?}");
|
||||
assert_eq!(output.status.code(), Some(1), "json={json}: {output:?}");
|
||||
assert!(!String::from_utf8_lossy(&output.stderr).contains("panicked"), "{output:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
use std::process::{Command, Output};
|
||||
|
||||
const SUBCOMMANDS: [&str; 10] = ["convert", "info", "text", "inspect", "render", "run", "commands", "parity", "mcp", "zotero"];
|
||||
const SUBCOMMANDS: [&str; 11] = ["convert", "info", "text", "inspect", "render", "run", "commands", "parity", "validate", "mcp", "zotero"];
|
||||
|
||||
fn cli(args: &[&str]) -> Output {
|
||||
// `output()` gives the child no stdin, so `mcp` can't wait for a client.
|
||||
@@ -14,7 +14,7 @@ fn assert_prints_usage(args: &[&str]) {
|
||||
let out = cli(args);
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(out.status.success(), "{args:?}: status {:?}, stderr: {stderr}", out.status);
|
||||
assert!(String::from_utf8_lossy(&out.stdout).starts_with("wordcraft-cli — "), "{args:?}: stdout: {}", String::from_utf8_lossy(&out.stdout));
|
||||
assert!(String::from_utf8_lossy(&out.stdout).contains("wordcraft-cli"), "{args:?}: stdout: {}", String::from_utf8_lossy(&out.stdout));
|
||||
assert!(stderr.is_empty(), "{args:?}: stderr: {stderr}");
|
||||
}
|
||||
|
||||
@@ -39,9 +39,9 @@ fn help_comes_before_opening_files_and_folders() {
|
||||
#[test]
|
||||
fn misspelled_options_and_unknown_commands_still_fail() {
|
||||
let out = cli(&["info", "--hepl"]);
|
||||
assert!(!out.status.success());
|
||||
assert!(String::from_utf8_lossy(&out.stderr).contains("info: unknown option --hepl"));
|
||||
assert_eq!(out.status.code(), Some(2));
|
||||
assert!(String::from_utf8_lossy(&out.stderr).contains("--hepl"));
|
||||
let out = cli(&["frobnicate", "--help"]);
|
||||
assert!(!out.status.success());
|
||||
assert!(String::from_utf8_lossy(&out.stderr).contains("unknown command `frobnicate`"));
|
||||
assert_eq!(out.status.code(), Some(2));
|
||||
assert!(String::from_utf8_lossy(&out.stderr).contains("frobnicate"));
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ mod closed_stdout;
|
||||
mod convert_fields;
|
||||
mod convert_region;
|
||||
mod help;
|
||||
mod man_and_completions;
|
||||
mod mcp_roots;
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
mod non_utf8_args;
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
//! The clap definition is consistent, and every shell's completions and every man page
|
||||
//! (`examples/man-and-completions.rs`) can be generated from it.
|
||||
|
||||
use clap::ValueEnum;
|
||||
use clap_complete::Shell;
|
||||
|
||||
// The example itself, so the test writes the files exactly as the packages get them.
|
||||
#[allow(dead_code)]
|
||||
#[path = "../../examples/man-and-completions.rs"]
|
||||
mod example;
|
||||
|
||||
#[test]
|
||||
fn command_is_consistent() {
|
||||
wordcraft_cli::command().debug_assert();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completions_generate_for_every_shell() {
|
||||
for &shell in Shell::value_variants() {
|
||||
let mut out = Vec::new();
|
||||
clap_complete::generate(shell, &mut wordcraft_cli::command(), "wordcraft-cli", &mut out);
|
||||
assert!(!out.is_empty(), "{shell}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn man_pages_render_for_the_command_and_every_subcommand() {
|
||||
let cmd = wordcraft_cli::command();
|
||||
for page in std::iter::once(&cmd).chain(cmd.get_subcommands()) {
|
||||
let mut out = Vec::new();
|
||||
clap_mangen::Man::new(page.clone()).render(&mut out).unwrap();
|
||||
assert!(!out.is_empty(), "{}", page.get_name());
|
||||
}
|
||||
}
|
||||
|
||||
/// The example writes the five completion files under the names `packaging/linux/package.sh` and
|
||||
/// `packaging/freebsd/package.sh` install, `wordcraft-cli.1` and a page per subcommand, and no
|
||||
/// pages for the `help` subcommand.
|
||||
#[test]
|
||||
fn the_example_writes_the_files_the_packages_install() {
|
||||
let dir = std::env::temp_dir().join(format!("wc-cli-{}-man-and-completions", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
example::generate(&dir).unwrap();
|
||||
|
||||
let mut written: Vec<String> = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().file_name().into_string().unwrap()).collect();
|
||||
written.sort();
|
||||
let completions = ["wordcraft-cli.bash", "_wordcraft-cli", "wordcraft-cli.fish", "wordcraft-cli.elv", "_wordcraft-cli.ps1"];
|
||||
let subcommands = ["commands", "convert", "info", "inspect", "mcp", "parity", "render", "run", "text", "validate", "zotero"];
|
||||
let mut expected: Vec<String> = completions.map(String::from).into();
|
||||
expected.push("wordcraft-cli.1".into());
|
||||
expected.extend(subcommands.iter().map(|s| format!("wordcraft-cli-{s}.1")));
|
||||
expected.sort();
|
||||
assert_eq!(written, expected);
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
@@ -67,17 +67,19 @@ fn any_other_such_argument_is_an_error_naming_it() {
|
||||
let (dir, file) = folder("error");
|
||||
let out_name = dir.join(OsString::from_vec(b"caf\xe9.md".to_vec())).into_os_string();
|
||||
let cmd = OsString::from_vec(b"text.insert={\"text\":\"\xe9\"}".to_vec());
|
||||
for (args, n) in [
|
||||
(vec!["convert".into(), file.clone(), out_name.clone()], 3),
|
||||
(vec!["run".into(), "--file".into(), file.clone(), "--cmd".into(), cmd], 5),
|
||||
(vec![OsString::from_vec(b"t\xe9xt".to_vec()), file.clone()], 1),
|
||||
// An output the engine takes as text: a failure (1), naming it; the other arguments are usage errors (2).
|
||||
for (args, code, shown) in [
|
||||
(vec!["convert".into(), file.clone(), out_name.clone()], 1, out_name.clone()),
|
||||
(vec!["run".into(), "--file".into(), file.clone(), "--cmd".into(), cmd.clone()], 2, cmd),
|
||||
(vec![OsString::from_vec(b"t\xe9xt".to_vec()), file.clone()], 2, OsString::from_vec(b"t\xe9xt".to_vec())),
|
||||
] {
|
||||
let out = cli(&args);
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
let shown = args[n - 1].to_string_lossy();
|
||||
let shown = shown.to_string_lossy();
|
||||
assert!(shown.contains('\u{FFFD}'));
|
||||
assert_eq!(out.status.code(), Some(1), "{args:?}: stderr: {stderr}");
|
||||
assert_eq!(stderr, format!("wordcraft-cli: argument {n} is not valid Unicode: {shown}\n"), "{args:?}");
|
||||
assert_eq!(out.status.code(), Some(code), "{args:?}: stderr: {stderr}");
|
||||
assert!(stderr.starts_with("error: "), "{args:?}: {stderr}");
|
||||
assert!(stderr.contains("not valid Unicode") || stderr.contains("invalid UTF-8") || stderr.contains(&*shown), "{args:?}: {stderr}");
|
||||
}
|
||||
assert!(!std::path::Path::new(&out_name).exists());
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! `convert --strict` (#6005): exit 3 and a report when a PDF or PNG would silently lack a
|
||||
//! `convert --strict` (#6005): exit 1 and a report when a PDF or PNG would silently lack a
|
||||
//! character or a picture, nothing written; exit 0 otherwise.
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Output};
|
||||
@@ -145,9 +145,9 @@ fn an_uncovered_code_point_fails_strict_with_a_report_and_no_file() {
|
||||
for out in ["out.pdf", "out.png"] {
|
||||
let out = d.join(out);
|
||||
let r = convert(&input, &out, true);
|
||||
assert_eq!(r.status.code(), Some(3), "{}", stderr(&r));
|
||||
assert_eq!(r.status.code(), Some(1), "{}", stderr(&r));
|
||||
let text = stderr(&r);
|
||||
assert!(text.contains(&format!("wordcraft-cli: strict: 1 character cannot be drawn: {cp} (×3)")), "{text}");
|
||||
assert!(text.contains(&format!("error: strict: 1 character cannot be drawn: {cp} (×3)")), "{text}");
|
||||
let json = report_json(&r);
|
||||
assert_eq!(json["schema"], 1);
|
||||
assert_eq!(json["strict"], "failed");
|
||||
@@ -186,7 +186,7 @@ fn a_corrupt_header_picture_fails_strict_naming_the_part_and_the_header() {
|
||||
for out in ["out.pdf", "out.png"] {
|
||||
let out = d.join(out);
|
||||
let r = convert(&input, &out, true);
|
||||
assert_eq!(r.status.code(), Some(3), "{}", stderr(&r));
|
||||
assert_eq!(r.status.code(), Some(1), "{}", stderr(&r));
|
||||
let text = stderr(&r);
|
||||
assert!(text.contains("word/media/image2.bin (header2.xml): unsupported format"), "{text}");
|
||||
let json = report_json(&r);
|
||||
@@ -218,7 +218,7 @@ fn an_external_picture_target_is_never_fetched_and_is_reported_under_strict() {
|
||||
assert_eq!(lenient.status.code(), Some(0), "{}", stderr(&lenient));
|
||||
let out = d.join("strict.pdf");
|
||||
let strict = convert(&input, &out, true);
|
||||
assert_eq!(strict.status.code(), Some(3), "{}", stderr(&strict));
|
||||
assert_eq!(strict.status.code(), Some(1), "{}", stderr(&strict));
|
||||
let json = report_json(&strict);
|
||||
assert_eq!(json["missing_pictures"][0]["reason"], "external_target");
|
||||
assert!(stderr(&strict).contains("external target"));
|
||||
@@ -246,19 +246,19 @@ fn bad_input_exits_1_with_the_usual_message_with_and_without_strict() {
|
||||
assert_eq!(plain.status.code(), Some(1), "{}", stderr(&plain));
|
||||
assert_eq!(strict.status.code(), Some(1), "{}", stderr(&strict));
|
||||
assert_eq!(stderr(&plain), stderr(&strict));
|
||||
assert!(stderr(&plain).starts_with("wordcraft-cli: "), "{}", stderr(&plain));
|
||||
assert!(stderr(&plain).starts_with("error: "), "{}", stderr(&plain));
|
||||
assert!(!d.join("a.pdf").exists() && !d.join("b.pdf").exists());
|
||||
}
|
||||
std::fs::remove_dir_all(d).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_with_another_output_type_exits_1_before_the_input_is_read() {
|
||||
fn strict_with_another_output_type_exits_2_before_the_input_is_read() {
|
||||
let d = dir("wrong-output");
|
||||
let missing = d.join("does-not-exist.docx");
|
||||
for out in ["out.docx", "out.txt", "out.odt"] {
|
||||
let r = convert(&missing, &d.join(out), true);
|
||||
assert_eq!(r.status.code(), Some(1));
|
||||
assert_eq!(r.status.code(), Some(2));
|
||||
let text = stderr(&r);
|
||||
assert!(text.contains("--strict needs a .pdf or .png output"), "{text}");
|
||||
assert!(!d.join(out).exists());
|
||||
@@ -291,11 +291,11 @@ fn render_strict_refuses_an_uncovered_character_on_the_page_with_no_stdout_or_fi
|
||||
let input = two_page_input(&d, &format!("a{c}b"));
|
||||
let out = d.join("p1.png");
|
||||
let r = render(&input, &out, &["--strict"]);
|
||||
assert_eq!(r.status.code(), Some(3), "{}", stderr(&r));
|
||||
assert_eq!(r.status.code(), Some(1), "{}", stderr(&r));
|
||||
assert!(r.stdout.is_empty(), "{}", String::from_utf8_lossy(&r.stdout));
|
||||
assert!(!out.exists());
|
||||
let text = stderr(&r);
|
||||
assert!(text.contains(&format!("wordcraft-cli: strict: 1 character cannot be drawn: {cp} (×1)")), "{text}");
|
||||
assert!(text.contains(&format!("error: strict: 1 character cannot be drawn: {cp} (×1)")), "{text}");
|
||||
assert_eq!(report_json(&r)["missing_glyphs"][0]["cp"], cp.as_str());
|
||||
eprintln!("{text}");
|
||||
|
||||
@@ -323,7 +323,7 @@ fn render_strict_refuses_a_corrupt_header_picture_and_bad_input_still_exits_1()
|
||||
std::fs::write(&input, docx_with_header_picture(b"corrupt bytes, not a picture")).unwrap();
|
||||
let out = d.join("out.png");
|
||||
let r = render(&input, &out, &["--strict"]);
|
||||
assert_eq!(r.status.code(), Some(3), "{}", stderr(&r));
|
||||
assert_eq!(r.status.code(), Some(1), "{}", stderr(&r));
|
||||
assert!(r.stdout.is_empty());
|
||||
assert!(stderr(&r).contains("word/media/image2.bin (header2.xml)"), "{}", stderr(&r));
|
||||
assert!(!out.exists());
|
||||
@@ -341,16 +341,16 @@ fn a_picture_target_with_a_newline_and_a_bidi_override_cannot_forge_a_report_lin
|
||||
let d = dir("escape");
|
||||
let input = d.join("in.docx");
|
||||
// XML character references put a newline and U+202E in the target.
|
||||
std::fs::write(&input, docx_with_external_picture("http://example.invalid/a wordcraft-cli: strict: forged‮gnp.png")).unwrap();
|
||||
std::fs::write(&input, docx_with_external_picture("http://example.invalid/a error: strict: forged‮gnp.png")).unwrap();
|
||||
let out = d.join("out.pdf");
|
||||
let r = convert(&input, &out, true);
|
||||
assert_eq!(r.status.code(), Some(3), "{}", stderr(&r));
|
||||
assert_eq!(r.status.code(), Some(1), "{}", stderr(&r));
|
||||
let text = stderr(&r);
|
||||
let lines: Vec<&str> = text.lines().collect();
|
||||
// One human line for the picture, then the JSON line.
|
||||
assert_eq!(lines.len(), 2, "{text}");
|
||||
assert!(lines[0].starts_with("wordcraft-cli: strict: 1 picture(s) left out: "), "{text}");
|
||||
assert!(lines[0].contains("\\nwordcraft-cli: strict: forged\\u{202e}gnp.png"), "{text}");
|
||||
assert!(lines[0].starts_with("error: strict: 1 picture(s) left out: "), "{text}");
|
||||
assert!(lines[0].contains("\\nerror: strict: forged\\u{202e}gnp.png"), "{text}");
|
||||
assert!(!text.contains('\u{202e}'), "the raw bidi override reached the terminal");
|
||||
// The JSON keeps the raw value, escaped by the JSON encoder.
|
||||
let json = report_json(&r);
|
||||
@@ -363,14 +363,14 @@ fn a_picture_target_with_a_newline_and_a_bidi_override_cannot_forge_a_report_lin
|
||||
fn run_with_strict_cannot_forge_an_error_line_either() {
|
||||
let d = dir("run-escape");
|
||||
let input = d.join("in.docx");
|
||||
std::fs::write(&input, docx_with_external_picture("http://example.invalid/a wordcraft-cli: strict: forged[2J‮gnp.png")).unwrap();
|
||||
std::fs::write(&input, docx_with_external_picture("http://example.invalid/a error: strict: forged[2J‮gnp.png")).unwrap();
|
||||
let out = d.join("out.pdf");
|
||||
let cmd = format!("file.exportPdf={}", serde_json::json!({"path": out, "strict": true}));
|
||||
let r = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli")).arg("run").arg("--file").arg(&input).arg("--cmd").arg(cmd).output().unwrap();
|
||||
assert_eq!(r.status.code(), Some(1));
|
||||
let text = stderr(&r);
|
||||
assert_eq!(text.lines().count(), 1, "{text}");
|
||||
assert!(text.contains("\\nwordcraft-cli: strict: forged") && text.contains("\\u{202e}"), "{text}");
|
||||
assert!(text.contains("\\nerror: strict: forged") && text.contains("\\u{202e}"), "{text}");
|
||||
assert!(!text.contains('\u{1b}') && !text.contains('\u{202e}'), "{text:?}");
|
||||
assert!(!out.exists());
|
||||
std::fs::remove_dir_all(d).unwrap();
|
||||
@@ -378,19 +378,20 @@ fn run_with_strict_cannot_forge_an_error_line_either() {
|
||||
|
||||
#[test]
|
||||
fn usage_errors_keep_their_line_breaks() {
|
||||
// Errors go to stderr with the usage after a blank line (`missing argument`, `unknown command`).
|
||||
// Errors go to stderr (clap's message, then its usage), exit 2.
|
||||
for args in [&["frobnicate"][..], &["convert"][..]] {
|
||||
let r = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli")).args(args).output().unwrap();
|
||||
let text = stderr(&r);
|
||||
assert_eq!(r.status.code(), Some(1), "{args:?}: {text}");
|
||||
assert!(text.lines().count() > 3, "{args:?}: {text}");
|
||||
assert!(text.lines().any(|l| l == "USAGE:"), "{args:?}: {text}");
|
||||
assert_eq!(r.status.code(), Some(2), "{args:?}: {text}");
|
||||
assert!(text.lines().count() > 2, "{args:?}: {text}");
|
||||
assert!(text.lines().any(|l| l.starts_with("Usage:")), "{args:?}: {text}");
|
||||
assert!(!text.contains("\\n"), "{args:?}: {text}");
|
||||
}
|
||||
// No arguments at all prints the usage as help, on stdout.
|
||||
// No arguments at all prints the help (on stderr, as clap does for a missing subcommand), exit 2.
|
||||
let r = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli")).output().unwrap();
|
||||
assert_eq!(r.status.code(), Some(2));
|
||||
let all = format!("{}{}", String::from_utf8_lossy(&r.stdout), stderr(&r));
|
||||
assert!(all.lines().count() > 3 && all.lines().any(|l| l == "USAGE:"), "{all}");
|
||||
assert!(all.lines().count() > 3 && all.lines().any(|l| l.starts_with("Usage:")), "{all}");
|
||||
}
|
||||
|
||||
/// A minimal EMF (88-byte header, 100 mm square frame) with one EMR_EXTTEXTOUTW record showing
|
||||
@@ -444,7 +445,7 @@ fn a_character_in_a_metafile_pictures_text_fails_strict_like_the_pages_own() {
|
||||
for out in ["out.pdf", "out.png"] {
|
||||
let out = d.join(out);
|
||||
let r = convert(&input, &out, true);
|
||||
assert_eq!(r.status.code(), Some(3), "{}", stderr(&r));
|
||||
assert_eq!(r.status.code(), Some(1), "{}", stderr(&r));
|
||||
assert_eq!(report_json(&r)["missing_glyphs"][0]["cp"], cp.as_str(), "{}", stderr(&r));
|
||||
assert!(!out.exists(), "{} was written", out.display());
|
||||
// Without --strict it converts, the character a hollow box.
|
||||
@@ -454,7 +455,7 @@ fn a_character_in_a_metafile_pictures_text_fails_strict_like_the_pages_own() {
|
||||
}
|
||||
let out = d.join("p1.png");
|
||||
let r = render(&input, &out, &["--strict"]);
|
||||
assert_eq!(r.status.code(), Some(3), "{}", stderr(&r));
|
||||
assert_eq!(r.status.code(), Some(1), "{}", stderr(&r));
|
||||
assert!(r.stdout.is_empty() && !out.exists());
|
||||
assert_eq!(report_json(&r)["missing_glyphs"][0]["cp"], cp.as_str());
|
||||
// Text the faces cover passes.
|
||||
@@ -479,7 +480,7 @@ fn a_metafile_page_background_fails_strict_for_png_but_not_for_pdf() {
|
||||
std::fs::write(&input, serde_json::to_vec(&doc).unwrap()).unwrap();
|
||||
let png = d.join("out.png");
|
||||
let r = convert(&input, &png, true);
|
||||
assert_eq!(r.status.code(), Some(3), "{}", stderr(&r));
|
||||
assert_eq!(r.status.code(), Some(1), "{}", stderr(&r));
|
||||
let json = report_json(&r);
|
||||
assert_eq!(json["missing_pictures"][0]["part"], "bg.emf", "{}", stderr(&r));
|
||||
assert_eq!(json["missing_pictures"][0]["source_part"], "background");
|
||||
|
||||
@@ -57,7 +57,7 @@ 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", "menu"] }
|
||||
craft = { workspace = true, features = ["platform-apple-events"] }
|
||||
|
||||
[target.'cfg(all(unix, not(target_os = "macos")))'.dependencies]
|
||||
winit = { version = "0.30", default-features = false, features = ["x11"] }
|
||||
|
||||
@@ -20,8 +20,6 @@ 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;
|
||||
@@ -56,8 +54,6 @@ 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
|
||||
@@ -75,22 +71,10 @@ struct App {
|
||||
}
|
||||
|
||||
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() {
|
||||
@@ -139,7 +123,7 @@ impl eframe::App for App {
|
||||
if !files.is_empty() {
|
||||
self.drops.dropped(files);
|
||||
}
|
||||
self.before_input(ctx);
|
||||
embed::before_input(ctx, |out| self.app.frame_input(out));
|
||||
}
|
||||
fn logic(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) {
|
||||
self.logic_pass(ctx, Some(frame));
|
||||
@@ -814,8 +798,6 @@ fn main() -> eframe::Result {
|
||||
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,
|
||||
@@ -1032,29 +1014,14 @@ mod smoke {
|
||||
let drops = intake.sender();
|
||||
let session = Session::new(wordcraft_doc::Document::new());
|
||||
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,
|
||||
}
|
||||
Run { app: App { 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;
|
||||
app.before_input(ctx);
|
||||
embed::before_input(ctx, |out| app.app.frame_input(out));
|
||||
let mut first = true;
|
||||
frames.frame_without_input(events, |ui| {
|
||||
if std::mem::take(&mut first) {
|
||||
@@ -1077,7 +1044,7 @@ mod smoke {
|
||||
/// cancelling the close.
|
||||
fn close_request_is_let_through(&mut self) -> bool {
|
||||
let Run { app, ctx, .. } = self;
|
||||
app.before_input(ctx);
|
||||
embed::before_input(ctx, |out| app.app.frame_input(out));
|
||||
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() });
|
||||
@@ -1151,47 +1118,6 @@ 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)]
|
||||
|
||||
@@ -1,64 +0,0 @@
|
||||
//! 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");
|
||||
}
|
||||
}
|
||||
@@ -157,9 +157,6 @@ fn private_subdirectory(root: &Path, name: impl AsRef<Path>, label: &str) -> Res
|
||||
if child == chosen || !child.starts_with(&chosen) {
|
||||
return Err(format!("the nightly {label} must stay inside its selected profile"));
|
||||
}
|
||||
if std::fs::metadata(&child).is_ok_and(|meta| !meta.is_dir()) {
|
||||
return Err(format!("the nightly {label} must be a directory"));
|
||||
}
|
||||
Ok(child)
|
||||
}
|
||||
|
||||
@@ -174,56 +171,11 @@ fn entries_stay_inside(root: &Path) -> Result<(), String> {
|
||||
};
|
||||
for entry in entries {
|
||||
let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
|
||||
let path = entry.path();
|
||||
let metadata = std::fs::symlink_metadata(&path).map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
|
||||
// Settings and session state are ordinary files, not directories. Keep the existing
|
||||
// directory-boundary check for folders (including the known folder-only entries).
|
||||
let folder_only = PROFILE_FOLDERS.iter().any(|name| entry.file_name().eq_ignore_ascii_case(name));
|
||||
if metadata.is_file() && !folder_only {
|
||||
private_regular_file(&path, &metadata)?;
|
||||
} else {
|
||||
private_subdirectory(root, entry.file_name(), "profile entry")?;
|
||||
}
|
||||
private_subdirectory(root, entry.file_name(), "profile entry")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Persisted files must have their own ordinary file identity, not an alias to other data.
|
||||
fn private_regular_file(path: &Path, metadata: &std::fs::Metadata) -> Result<(), String> {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::MetadataExt as _;
|
||||
if metadata.nlink() != 1 {
|
||||
return Err("the nightly profile file must not be shared".into());
|
||||
}
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use winsafe::{HFILE, co};
|
||||
let (file, _) = HFILE::CreateFile(
|
||||
path.to_str().ok_or("the nightly profile file path is not textual")?,
|
||||
co::GENERIC::default(),
|
||||
Some(co::FILE_SHARE::READ | co::FILE_SHARE::WRITE | co::FILE_SHARE::DELETE),
|
||||
None,
|
||||
co::DISPOSITION::OPEN_EXISTING,
|
||||
co::FILE_ATTRIBUTE::NORMAL,
|
||||
Some(co::FILE_FLAG::OPEN_REPARSE_POINT),
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let info = file.GetFileInformationByHandle().map_err(|e| e.to_string())?;
|
||||
if info.dwFileAttributes.has(co::FILE_ATTRIBUTE::REPARSE_POINT | co::FILE_ATTRIBUTE::DIRECTORY) {
|
||||
return Err("the nightly profile file must not be an alias or directory".into());
|
||||
}
|
||||
if info.nNumberOfLinks != 1 {
|
||||
return Err("the nightly profile file must not be shared".into());
|
||||
}
|
||||
}
|
||||
let _ = (path, metadata);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The app's exclusive create probe: a file only this process can have made, created and removed.
|
||||
pub fn probe_writable(dir: &Path) -> std::io::Result<()> {
|
||||
static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
|
||||
@@ -293,8 +245,6 @@ fn validate_for(
|
||||
Ok(confirmed)
|
||||
}
|
||||
|
||||
const PROFILE_FOLDERS: [&str; 5] = ["recovery", "logs", "fonts", "Templates", "FontStore"];
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -391,31 +341,6 @@ mod tests {
|
||||
assert_eq!(std::fs::read_dir(nightly).unwrap().count(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_profile_reopens_after_saving_settings_and_session_state() {
|
||||
let fixture = Fixture::new();
|
||||
for platform in [Platform::Mac, Platform::Linux, Platform::Windows] {
|
||||
let private = fixture.root.join(format!("nightly-reopen-{platform:?}"));
|
||||
assert_eq!(fixture.check(platform, &private).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 PROFILE_FOLDERS {
|
||||
std::fs::create_dir(private.join(name)).unwrap();
|
||||
}
|
||||
assert_eq!(fixture.check(platform, &private).unwrap(), private);
|
||||
assert_eq!(std::fs::read(private.join("config.toml")).unwrap(), b"saved profile data");
|
||||
for name in PROFILE_FOLDERS {
|
||||
let path = private.join(name);
|
||||
std::fs::remove_dir(&path).unwrap();
|
||||
std::fs::write(&path, b"not a directory").unwrap();
|
||||
assert!(fixture.check(platform, &private).is_err(), "{name} must stay a directory");
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
std::fs::create_dir(&path).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linux_fences_the_stable_flatpak_data_folder() {
|
||||
let fixture = Fixture::new();
|
||||
|
||||
+27
-48
@@ -647,20 +647,6 @@ 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)) }
|
||||
@@ -702,6 +688,7 @@ fn trim_para(para: &Paragraph, from: usize, to: usize, clear_section: bool) -> P
|
||||
}
|
||||
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
|
||||
@@ -1656,41 +1643,13 @@ impl Document {
|
||||
Some(id)
|
||||
}
|
||||
|
||||
/// 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.
|
||||
/// 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.
|
||||
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, parts, 0, &mut budget);
|
||||
self.adopt_text_boxes(&mut blocks, &frag.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)",
|
||||
@@ -1702,7 +1661,18 @@ 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 media_remap = self.adopt_media(&frag.media);
|
||||
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());
|
||||
}
|
||||
}
|
||||
// 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());
|
||||
@@ -1719,7 +1689,16 @@ impl Document {
|
||||
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();
|
||||
remap_media_in(&mut blocks, &mut parts, &media_remap);
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
// 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);
|
||||
|
||||
@@ -1192,61 +1192,6 @@ 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]
|
||||
|
||||
+9
-145
@@ -109,55 +109,6 @@ 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")]
|
||||
@@ -370,28 +321,10 @@ 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| n.level(Some(abs), k as u8);
|
||||
let level_def = |k: usize| numbering.level(num, k as u8);
|
||||
// A "none" level (Word's numFmt none) still counts and restarts the levels below it; only
|
||||
// its number reads as nothing, so its literal text ("RESPONSE:") shows (#4985).
|
||||
let def = level_def(lv)?.clone();
|
||||
@@ -445,7 +378,7 @@ impl Counters {
|
||||
let vals = *st;
|
||||
let started = *fl;
|
||||
let numeric = def.format != NumFormat::Bullet;
|
||||
let label = if numeric { render_label(level_def, &def, &vals, &started) } else { def.text.clone() };
|
||||
let label = if numeric { render_label(numbering, num, &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 {
|
||||
@@ -467,19 +400,18 @@ 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 n = numbering.num(num)?;
|
||||
let abs = numbering.abstracts.iter().find(|a| a.id == n.abstract_id)?;
|
||||
let abs = numbering.abstract_of(num)?;
|
||||
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 = n.level(Some(abs), level.min(8))?;
|
||||
let def = numbering.level(num, 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(|k| n.level(Some(abs), k as u8), def, &vals, &started))
|
||||
Some(render_label(numbering, num, def, &vals, &started))
|
||||
}
|
||||
|
||||
/// Levels shown by the last rendered label, or the current definition for an implicit level.
|
||||
@@ -512,7 +444,8 @@ pub fn template_levels(text: &str) -> Vec<usize> {
|
||||
}
|
||||
|
||||
/// Render a list label without advancing counters, retaining the existing hostile-input caps.
|
||||
fn render_label<'a>(level_def: impl Fn(usize) -> Option<&'a Level>, def: &Level, vals: &[u32; 9], started: &[LevelFlags; 9]) -> String {
|
||||
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);
|
||||
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();
|
||||
@@ -524,11 +457,10 @@ fn render_label<'a>(level_def: impl Fn(usize) -> Option<&'a Level>, def: &Level,
|
||||
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 level = level_def(k);
|
||||
let val = if counted { val } else { level.map_or(1, |l| l.start) };
|
||||
let val = if counted { val } else { level_def(k).map(|l| l.start).unwrap_or(1) };
|
||||
// Legal numbering (w:isLgl) shows every level in Arabic digits, whatever its own
|
||||
// format (二 of a Chinese outline becomes 2 in "2.1"); a "none" level stays empty.
|
||||
let fmt = match level.map_or(NumFormat::Decimal, |l| l.format) {
|
||||
let fmt = match level_def(k).map(|l| l.format).unwrap_or(NumFormat::Decimal) {
|
||||
f @ (NumFormat::DecimalZero | NumFormat::None) => f,
|
||||
_ if def.legal => NumFormat::Decimal,
|
||||
f => f,
|
||||
@@ -841,72 +773,4 @@ 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));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -506,11 +506,6 @@ 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 {
|
||||
|
||||
@@ -183,13 +183,6 @@ 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")]
|
||||
@@ -356,8 +349,6 @@ impl Default for Settings {
|
||||
zoom: None,
|
||||
remove_personal_info: false,
|
||||
remove_date_time: false,
|
||||
hide_spelling_errors: false,
|
||||
hide_grammar_errors: false,
|
||||
odf: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -221,17 +221,6 @@ 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);
|
||||
}
|
||||
|
||||
@@ -755,38 +744,6 @@ 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]
|
||||
|
||||
@@ -175,7 +175,6 @@ 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 {
|
||||
@@ -203,7 +202,7 @@ mod tests {
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
source.settings.compat_mode = Some(11);
|
||||
source.settings.compat_mode = 11;
|
||||
let image = Arc::new(vec![0x5a; 1 << 20]);
|
||||
source.media.insert("image1.png".into(), image.clone());
|
||||
|
||||
|
||||
@@ -100,35 +100,18 @@ fn object_value_from_shared(
|
||||
float: convert(float)?,
|
||||
ch_w,
|
||||
ch_h,
|
||||
children: group_children_from_shared(children, graphics)?,
|
||||
children: children.into_iter().map(|c| group_child_value_from_shared(c, graphics)).collect::<Result<_, _>>()?,
|
||||
canvas: canvas.map(convert).transpose()?,
|
||||
}),
|
||||
other => convert(other),
|
||||
}
|
||||
}
|
||||
|
||||
/// 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>,
|
||||
fn group_child_value_from_shared(
|
||||
source: craft_wordmodel::para::GroupChild,
|
||||
graphics: &mut GraphicCache,
|
||||
) -> 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)
|
||||
) -> Result<wordcraft_doc::para::GroupChild, DocxError> {
|
||||
Ok(wordcraft_doc::para::GroupChild { x: source.x, y: source.y, obj: object_value_from_shared(source.obj, graphics)? })
|
||||
}
|
||||
|
||||
fn table_value_from_shared(source: craft_wordmodel::table::Table, graphics: &mut GraphicCache) -> Result<wordcraft_doc::table::Table, DocxError> {
|
||||
@@ -232,10 +215,7 @@ 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)?;
|
||||
@@ -341,7 +321,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 { link: None, x: source.x, y: source.y, obj: object_value_to_shared(&source.obj)? })
|
||||
Ok(craft_wordmodel::para::GroupChild { 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> {
|
||||
@@ -578,7 +558,6 @@ 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 {
|
||||
@@ -606,7 +585,7 @@ mod tests {
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
source.settings.compat_mode = Some(11);
|
||||
source.settings.compat_mode = 11;
|
||||
let image = Arc::new(vec![0x5a; 1 << 16]);
|
||||
source.media.insert("image1.png".into(), image.clone());
|
||||
|
||||
|
||||
@@ -4781,20 +4781,3 @@ 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}");
|
||||
}
|
||||
|
||||
@@ -229,7 +229,6 @@ 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() },
|
||||
|
||||
@@ -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 w16du\""), "cycle {cycle}: {xml}");
|
||||
assert!(xml.contains("xmlns:w15=") && xml.contains("mc:Ignorable=\"w14 w15 wp14\""), "cycle {cycle}: {xml}");
|
||||
document = wordcraft_docx::read(&bytes).unwrap();
|
||||
let json = serde_json::to_vec(&document).unwrap();
|
||||
document = serde_json::from_slice(&json).unwrap();
|
||||
|
||||
@@ -265,23 +265,3 @@ 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}");
|
||||
}
|
||||
|
||||
@@ -532,98 +532,6 @@ 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
|
||||
@@ -638,13 +546,9 @@ 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 => {
|
||||
@@ -660,8 +564,7 @@ pub fn parity(reg: &Registry) -> Value {
|
||||
if have {
|
||||
t.1 += 1;
|
||||
} else {
|
||||
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));
|
||||
t.3.push(format!("{group} › {label} (`{id}`)"));
|
||||
}
|
||||
}
|
||||
let live = tabs.iter().map(|t| t.1).sum::<usize>();
|
||||
@@ -670,7 +573,6 @@ 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<_>>(),
|
||||
})
|
||||
}
|
||||
@@ -695,44 +597,6 @@ 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();
|
||||
|
||||
@@ -477,7 +477,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);
|
||||
let n = p::u64(v, "occurrence").unwrap_or(1).max(1) as usize;
|
||||
if needle.is_empty() {
|
||||
return Err(CmdError::Params("`text` is empty".into()));
|
||||
}
|
||||
|
||||
@@ -161,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} (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)"#),
|
||||
.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}"#),
|
||||
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"#)
|
||||
@@ -496,9 +496,6 @@ 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`.
|
||||
@@ -538,13 +535,6 @@ 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() {
|
||||
@@ -561,9 +551,6 @@ fn search_matches(s: &Session, story: StoryRef, with_rep: bool, chain: bool) ->
|
||||
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();
|
||||
@@ -626,8 +613,6 @@ fn search_matches(s: &Session, story: StoryRef, with_rep: bool, chain: bool) ->
|
||||
};
|
||||
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;
|
||||
@@ -651,24 +636,11 @@ fn search_matches(s: &Session, story: StoryRef, with_rep: bool, chain: bool) ->
|
||||
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, found, &group, &s.clipboard_text, quotes)
|
||||
find_pattern::expand(pc, hay.get(m.range()).unwrap_or(""), &group, &s.clipboard_text)
|
||||
});
|
||||
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 });
|
||||
out.push(Found { a, b, rep });
|
||||
if out.len() >= 100_000 {
|
||||
return Ok(out);
|
||||
}
|
||||
@@ -807,8 +779,7 @@ 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;
|
||||
// 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) {
|
||||
if let Some(f) = results.into_iter().find(|f| f.a == a && f.b == b) {
|
||||
super::paste_text(s, &f.rep.unwrap_or_default())?;
|
||||
replaced = 1;
|
||||
}
|
||||
@@ -828,11 +799,10 @@ fn replace_all(s: &mut Session, v: &Value) -> CmdResult {
|
||||
need_query(s, v)?;
|
||||
read_opts(s, v);
|
||||
let story = s.sel.focus.story;
|
||||
// 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 results = search_full(s, story, true)?;
|
||||
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.
|
||||
|
||||
@@ -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();
|
||||
let name = name.trim_end();
|
||||
if name.is_empty() {
|
||||
return Err(CmdError::Params("`name` must not be blank".into()));
|
||||
}
|
||||
|
||||
@@ -359,20 +359,6 @@ 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
|
||||
@@ -452,11 +438,6 @@ 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);
|
||||
@@ -530,8 +511,7 @@ fn as_inserted(s: &str) -> String {
|
||||
}
|
||||
|
||||
/// Fill in Replace with text for one match: `found` is the matched text, `group(n)` a group's.
|
||||
/// 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 {
|
||||
pub fn expand(pieces: &[Piece], found: &str, group: &dyn Fn(usize) -> Option<String>, clip: &str) -> String {
|
||||
let mut out = String::new();
|
||||
for p in pieces {
|
||||
match p {
|
||||
@@ -540,39 +520,11 @@ 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::*;
|
||||
@@ -583,45 +535,7 @@ mod tests {
|
||||
}
|
||||
|
||||
fn replaced(with: &str) -> String {
|
||||
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"));
|
||||
expand(&parse_replace(with, &Opts::default()), "", &|_| None, "")
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -906,7 +906,6 @@ 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),
|
||||
|
||||
@@ -37,7 +37,6 @@ 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();
|
||||
@@ -46,27 +45,6 @@ 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);
|
||||
@@ -139,9 +117,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.
|
||||
|
||||
@@ -176,7 +176,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 positive integer (1 = the first sheet)".into())),
|
||||
Some(_) => return Err(CmdError::Params("`sheet` must be a sheet name or number".into())),
|
||||
};
|
||||
let (names, rows) = read_rows(&bytes, pick).map_err(CmdError::Failed)?;
|
||||
let chosen = match pick {
|
||||
|
||||
@@ -242,10 +242,7 @@ 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!(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": data, "sheet": 0})).is_err());
|
||||
assert!(s.run("mailings.recipients", &json!({"data": "%%%"})).is_err());
|
||||
}
|
||||
|
||||
|
||||
@@ -304,7 +304,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
/// start, so all of a paragraph's text is still text, except in the last paragraph of its story,
|
||||
/// cell or box, where it stands for the paragraph with its mark. A selected picture, shape or text
|
||||
/// box is its object character, not text (a field's object character is).
|
||||
pub fn shades_text(s: &Session) -> bool {
|
||||
fn shades_text(s: &Session) -> bool {
|
||||
let (a, b) = s.sel.ordered();
|
||||
if a == b || a.story != b.story || a.path != b.path {
|
||||
return false;
|
||||
|
||||
@@ -144,21 +144,6 @@ pub(super) fn set_props(s: &mut Session, v: &Value) -> CmdResult {
|
||||
para.props.indent_right = Some(x);
|
||||
}
|
||||
para.touch();
|
||||
// An indent given in points wins over one in characters, the paragraph's own or its
|
||||
// style's, unless `props` gives the characters too: Word's dialog writes
|
||||
// `w:firstLineChars="0"` (and the like) for it. Paragraphs without one stay as they are.
|
||||
let points = |pt: bool, chars: Option<f32>| pt && chars.is_none();
|
||||
let set = [
|
||||
points(props.indent_left.is_some() || start.is_some(), props.indent_left_chars),
|
||||
points(props.indent_right.is_some() || end.is_some(), props.indent_right_chars),
|
||||
points(props.indent_first.is_some(), props.indent_first_chars),
|
||||
];
|
||||
let Some(para) = s.doc.para(story, &path) else { continue };
|
||||
let chars = s.doc.styles.resolve_para(¶.props).indent_chars;
|
||||
let [l, r, f] = [0, 1, 2].map(|i| set[i] && chars[i] != 0.0);
|
||||
if l || r || f {
|
||||
s.doc.para_mut(story, &path)?.props.cancel_char_indents(l, r, f);
|
||||
}
|
||||
}
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
@@ -29,6 +29,7 @@ pub(super) fn apply_style(s: &mut Session, v: &Value) -> CmdResult {
|
||||
if kind == StyleKind::Character {
|
||||
return crate::cmd::format::apply(s, &|c| c.style = Some(id.clone()));
|
||||
}
|
||||
let (a, b) = s.sel.ordered();
|
||||
// A style linked to a list level (a heading in a numbered-headings list) brings its number.
|
||||
let numbered = s.doc.styles.resolve_para(&ParaProps { style: Some(id.clone()), ..Default::default() }).numbering.is_some();
|
||||
fmt(s, &|p| {
|
||||
@@ -39,108 +40,33 @@ pub(super) fn apply_style(s: &mut Session, v: &Value) -> CmdResult {
|
||||
p.numbering = None;
|
||||
}
|
||||
})?;
|
||||
reset_direct_formatting(s)?;
|
||||
// A paragraph style resets direct character formatting that matches nothing (Word keeps
|
||||
// direct formatting unless it covers most of the paragraph; we clear font/size/colour).
|
||||
if a.path == b.path || a == b {
|
||||
let paths = s.doc.paths_between(&a, &b);
|
||||
for path in paths {
|
||||
let para = s.doc.para_mut(a.story, &path)?;
|
||||
let len = para.len();
|
||||
para.format(0, len, &|c| {
|
||||
c.font = None;
|
||||
c.font_cs = None;
|
||||
c.font_ea = None;
|
||||
c.size = None;
|
||||
c.size_cs = None;
|
||||
c.color = None;
|
||||
})?;
|
||||
para.mark.font = None;
|
||||
para.mark.font_cs = None;
|
||||
para.mark.font_ea = None;
|
||||
para.mark.size = None;
|
||||
para.mark.size_cs = None;
|
||||
para.mark.color = None;
|
||||
}
|
||||
}
|
||||
s.pending = None;
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
/// A character property a paragraph style can reset: whether a run sets it directly, and how to
|
||||
/// clear it.
|
||||
type Reset = (fn(&CharProps) -> bool, fn(&mut CharProps));
|
||||
|
||||
/// The direct character formatting applying a paragraph style can reset, as observed in Word.
|
||||
/// Word keeps highlight, superscript and subscript, scale, shading, borders, the underline's
|
||||
/// colour, language, no-proof and the character style whatever they cover, so they are not here.
|
||||
const RESETS: [Reset; 24] = [
|
||||
(|c| c.font.is_some(), |c| c.font = None),
|
||||
(|c| c.font_cs.is_some(), |c| c.font_cs = None),
|
||||
(|c| c.font_ea.is_some(), |c| c.font_ea = None),
|
||||
(|c| c.size.is_some(), |c| c.size = None),
|
||||
(|c| c.size_cs.is_some(), |c| c.size_cs = None),
|
||||
(|c| c.color.is_some(), |c| c.color = None),
|
||||
(|c| c.bold.is_some(), |c| c.bold = None),
|
||||
(|c| c.bold_cs.is_some(), |c| c.bold_cs = None),
|
||||
(|c| c.italic.is_some(), |c| c.italic = None),
|
||||
(|c| c.italic_cs.is_some(), |c| c.italic_cs = None),
|
||||
(|c| c.underline.is_some(), |c| c.underline = None),
|
||||
(|c| c.strike.is_some(), |c| c.strike = None),
|
||||
(|c| c.double_strike.is_some(), |c| c.double_strike = None),
|
||||
(|c| c.caps.is_some(), |c| c.caps = None),
|
||||
(|c| c.small_caps.is_some(), |c| c.small_caps = None),
|
||||
(|c| c.spacing.is_some(), |c| c.spacing = None),
|
||||
(|c| c.position.is_some(), |c| c.position = None),
|
||||
(|c| c.kern.is_some(), |c| c.kern = None),
|
||||
(|c| c.hidden.is_some(), |c| c.hidden = None),
|
||||
(|c| c.emboss.is_some(), |c| c.emboss = None),
|
||||
(|c| c.engrave.is_some(), |c| c.engrave = None),
|
||||
(|c| c.outline.is_some(), |c| c.outline = None),
|
||||
(|c| c.shadow.is_some(), |c| c.shadow = None),
|
||||
(|c| c.emphasis.is_some(), |c| c.emphasis = None),
|
||||
];
|
||||
|
||||
/// Clear `resets` in `a..b` of `para` (bytes), and in its mark when `mark`.
|
||||
fn clear_resets(para: &mut wordcraft_doc::Paragraph, a: usize, b: usize, mark: bool, resets: &[fn(&mut CharProps)]) -> Result<(), CmdError> {
|
||||
if resets.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let reset = |c: &mut CharProps| {
|
||||
for f in resets {
|
||||
f(c);
|
||||
}
|
||||
};
|
||||
para.format(a, b, &reset)?;
|
||||
if mark {
|
||||
reset(&mut para.mark);
|
||||
}
|
||||
para.touch();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// What applying a paragraph style does to direct character formatting, as observed in Word:
|
||||
/// - A caret, or a selection of a whole paragraph or of several paragraphs: the selection from its
|
||||
/// start to the end of its first paragraph decides, the paragraph mark counted as one character
|
||||
/// (the whole paragraph for a caret). Each property in [`RESETS`] set directly on at least half
|
||||
/// of those characters is reset in every selected paragraph, text and mark. One set on less
|
||||
/// stays everywhere, even where it covers a whole later paragraph.
|
||||
/// - A selection inside one paragraph: only the selection loses that formatting. Outside it,
|
||||
/// nothing changes, however much of the paragraph it covers.
|
||||
fn reset_direct_formatting(s: &mut Session) -> Result<(), CmdError> {
|
||||
let story = s.sel.focus.story;
|
||||
let (a, b) = s.sel.ordered();
|
||||
let paths = crate::cmd::selected_paths(s);
|
||||
let Some(first) = paths.first() else { return Ok(()) };
|
||||
let all: Vec<fn(&mut CharProps)> = RESETS.iter().map(|(_, clear)| *clear).collect();
|
||||
if a != b && a.path == b.path && paths.len() == 1 {
|
||||
let para = s.doc.para_mut(story, first)?;
|
||||
let (from, to) = (para.clamp(a.off), para.clamp(b.off));
|
||||
if from > 0 || to < para.len() {
|
||||
return clear_resets(para, from, to, false, &all);
|
||||
}
|
||||
}
|
||||
// Characters of the first paragraph from `start`, the mark included, and how many of them set
|
||||
// each property.
|
||||
let para = s.doc.para(story, first).ok_or_else(|| CmdError::Failed("the selected paragraph is gone".into()))?;
|
||||
let start = if a != b && a.path == *first { para.clamp(a.off) } else { 0 };
|
||||
let total = para.text.get(start..).map_or(0, |t| t.chars().count()).saturating_add(1);
|
||||
let mut set = [0usize; RESETS.len()];
|
||||
let runs = para.run_ranges().map(|(r, c)| (para.text.get(r.start.max(start)..r.end.max(start)).map_or(0, |t| t.chars().count()), c));
|
||||
for (n, c) in runs.chain(std::iter::once((1, ¶.mark))) {
|
||||
for (count, (has, _)) in set.iter_mut().zip(RESETS.iter()) {
|
||||
if has(c) {
|
||||
*count = count.saturating_add(n);
|
||||
}
|
||||
}
|
||||
}
|
||||
let reset: Vec<fn(&mut CharProps)> =
|
||||
set.iter().zip(RESETS.iter()).filter(|(count, _)| count.saturating_mul(2) >= total).map(|(_, (_, clear))| *clear).collect();
|
||||
for path in &paths {
|
||||
let para = s.doc.para_mut(story, path)?;
|
||||
let len = para.len();
|
||||
clear_resets(para, 0, len, true, &reset)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn create_style(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let name = p::req_str(v, "name")?.trim().to_string();
|
||||
if name.is_empty() {
|
||||
|
||||
@@ -499,23 +499,10 @@ pub(crate) fn unlink_sections(blocks: &mut [Block]) {
|
||||
/// lists and styles it refers to (renumbered so they can't collide with ours).
|
||||
fn adopt(s: &mut Session, src: Document) -> Fragment {
|
||||
let mut frag = s.doc.adopt(src);
|
||||
// Pasted pictures fit the room where they go, like Insert › Pictures: the table cell, the
|
||||
// column, its own section (#5428; layout keeps their size). Measured (a layout) only when
|
||||
// the fragment holds an inline picture.
|
||||
let mut has_picture = false;
|
||||
// Pasted pictures fit our text width, like Insert › Pictures (layout keeps their size).
|
||||
let max_w = crate::io::text_width(&s.doc);
|
||||
for b in &mut frag.blocks {
|
||||
each_para(b, 0, &mut |p| {
|
||||
has_picture |= p
|
||||
.objects
|
||||
.iter()
|
||||
.any(|o| matches!(o, wordcraft_doc::InlineObject::Image { float, .. } if float.wrap == wordcraft_doc::para::Wrap::Inline));
|
||||
});
|
||||
}
|
||||
if has_picture {
|
||||
let max_w = s.room_at(&s.sel.ordered().0);
|
||||
for b in &mut frag.blocks {
|
||||
crate::io::fit_block_pictures(b, max_w);
|
||||
}
|
||||
crate::io::fit_block_pictures(b, max_w);
|
||||
}
|
||||
unlink_sections(&mut frag.blocks);
|
||||
frag
|
||||
|
||||
@@ -65,11 +65,7 @@ pub(super) fn to_text(s: &mut Session, v: &Value) -> CmdResult {
|
||||
Some("other") => match p::str(v, "char").and_then(|c| c.chars().next()) {
|
||||
// U+FFFC marks an object in the text, so it cannot set the cells apart.
|
||||
Some(c) if c != '\n' && c != '\r' && c != wordcraft_doc::para::OBJ => Some(c),
|
||||
_ => {
|
||||
return Err(CmdError::Params(
|
||||
"`char` with `other` must start with a character other than CR, LF or U+FFFC (the object marker); only the first character is used".into(),
|
||||
));
|
||||
}
|
||||
_ => return Err(CmdError::Params("`char` (the separating character) is required with `other`".into())),
|
||||
},
|
||||
Some(x) => return Err(CmdError::Params(format!("unknown separator `{x}`"))),
|
||||
};
|
||||
@@ -368,11 +364,7 @@ pub(super) fn from_text(s: &mut Session, v: &Value) -> CmdResult {
|
||||
Some("paragraph") => None,
|
||||
Some("other") => match p::str(v, "char").and_then(|c| c.chars().next()) {
|
||||
Some(c) if c != '\n' && c != '\r' => Some(c),
|
||||
_ => {
|
||||
return Err(CmdError::Params(
|
||||
"`char` with `other` must start with a character other than CR or LF; only the first character is used".into(),
|
||||
));
|
||||
}
|
||||
_ => return Err(CmdError::Params("`char` (the separating character) is required with `other`".into())),
|
||||
},
|
||||
Some(x) => return Err(CmdError::Params(format!("unknown separator `{x}`"))),
|
||||
};
|
||||
|
||||
@@ -14,7 +14,6 @@ mod enter_tab;
|
||||
mod unicode;
|
||||
|
||||
use autoformat::insert;
|
||||
pub(crate) use autoformat::smart_quote;
|
||||
use delete::{backspace, delete, delete_sentence_back, delete_word_back, delete_word_fwd};
|
||||
pub use enter_tab::MAX_TYPED_PARAGRAPHS;
|
||||
use enter_tab::{back_tab, new_paragraph, tab};
|
||||
|
||||
@@ -17,13 +17,7 @@ fn autoformat(s: &mut Session, text: &str) -> Option<String> {
|
||||
let f = &s.sel.focus;
|
||||
let para = s.doc.para_at(f)?;
|
||||
let before = para.text.get(..f.off)?;
|
||||
smart_quote(before.chars().next_back(), c).map(String::from)
|
||||
}
|
||||
|
||||
/// The curly form of a straight quote `c` that follows `prev` (`None` at a paragraph's start):
|
||||
/// opening after a space, an opening bracket, a dash or the other opening quote, else closing.
|
||||
/// A quote typed in Replace with goes in by the same rule (#7307).
|
||||
pub(crate) fn smart_quote(prev: Option<char>, c: char) -> Option<&'static str> {
|
||||
let prev = before.chars().next_back();
|
||||
let opening = prev.is_none_or(|p| {
|
||||
p.is_whitespace()
|
||||
|| "([{<\u{2014}\u{2013}\u{00AB}\u{2039}\u{201E}\u{201A}".contains(p)
|
||||
@@ -31,8 +25,8 @@ pub(crate) fn smart_quote(prev: Option<char>, c: char) -> Option<&'static str> {
|
||||
|| (c == '\'' && p == '\u{201C}')
|
||||
});
|
||||
match c {
|
||||
'"' => Some(if opening { "\u{201C}" } else { "\u{201D}" }),
|
||||
'\'' => Some(if opening { "\u{2018}" } else { "\u{2019}" }),
|
||||
'"' => Some(if opening { "\u{201C}" } else { "\u{201D}" }.into()),
|
||||
'\'' => Some(if opening { "\u{2018}" } else { "\u{2019}" }.into()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ mod typing;
|
||||
|
||||
pub use autocorrect::{AUTOCORRECT, AutoCap, AutoCorrectPrefs, lenient_autocorrect};
|
||||
#[cfg(test)]
|
||||
use compare::{Op, collapse_noise_matches, lcs_len, lcs_ops};
|
||||
use compare::{Op, collapse_noise_matches, lcs_ops};
|
||||
pub use specs::specs;
|
||||
pub use typing::{INITIAL_CAPS_EXCEPTIONS, autocorrect, autocorrect_word, emphasis_autoformat, has_emphasis};
|
||||
pub(crate) use typing::{is_turkic, lower_char, upper_char};
|
||||
|
||||
@@ -485,7 +485,7 @@ pub(super) fn spreadsheet_rows(v: &Value) -> Result<Vec<Vec<String>>, CmdError>
|
||||
Value::Number(x) => x.to_string(),
|
||||
Value::Bool(x) => x.to_string(),
|
||||
Value::Null => String::new(),
|
||||
_ => return Err(CmdError::Params(format!("`values` row {} holds a cell that is not text, a number, a boolean or null", r + 1))),
|
||||
_ => return Err(CmdError::Params(format!("`values` row {} holds a cell that is not text, a number or a boolean", r + 1))),
|
||||
});
|
||||
}
|
||||
rows.push(out);
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -204,43 +204,6 @@ impl Session {
|
||||
Arc::new(wordcraft_layout::layout(doc, &mut LayoutCache::new(), &opts))
|
||||
}
|
||||
|
||||
/// How wide a picture put in at `pos` may be, as Word fits an inserted or pasted picture
|
||||
/// (#5428): the room its paragraph's lines have (the width available to its widest laid-out line,
|
||||
/// so the paragraph's indents are already taken out; inside a table cell, the innermost cell's
|
||||
/// text area, nested tables included; a turned cell isn't measured and falls back to the
|
||||
/// column width), never wider than the column it is in, of its own section. The narrowest
|
||||
/// section's text width ([`crate::io::text_width`]) when `pos` isn't laid out. It is measured on the pages, whatever the view: Web Layout and Read Mode reflow the
|
||||
/// text to the window, and a picture put in there keeps the size it gets in the document.
|
||||
pub(crate) fn room_at(&mut self, pos: &wordcraft_doc::Pos) -> f32 {
|
||||
let first = crate::io::text_width(&self.doc);
|
||||
let l =
|
||||
if !self.view.read_mode && self.view.mode == ViewMode::Print { self.layout() } else { self.output_layout_of(&self.doc, false, false) };
|
||||
let Some((caret, page)) = l.caret_on(pos, self.page_hint).and_then(|c| Some((c, l.pages.get(c.page)?))) else { return first };
|
||||
// A page can hold several continuous sections: the body's own comes from the position.
|
||||
let at = match (pos.story, pos.path.0.first()) {
|
||||
(StoryRef::Body, Some(b)) => self.doc.section_index_of(*b as usize),
|
||||
_ => page.section,
|
||||
};
|
||||
let section = self.doc.sections().get(at).map(|(_, sp)| (*sp).clone());
|
||||
let column = match (§ion, pos.story) {
|
||||
(Some(sp), StoryRef::Body) => {
|
||||
let boxes = sp.column_boxes();
|
||||
let x = caret.x - page.body.x;
|
||||
boxes.iter().find(|(cx, w)| x >= cx - 0.5 && x <= cx + w + 0.5).map_or_else(|| sp.text_width(), |(_, w)| *w)
|
||||
}
|
||||
(Some(sp), StoryRef::Part(_)) => sp.text_width(),
|
||||
(None, _) => first,
|
||||
};
|
||||
let lines = wordcraft_layout::hit::page_lines(page, pos.story)
|
||||
.iter()
|
||||
.filter(|h| *h.path == pos.path)
|
||||
.map(|h| h.right - h.left)
|
||||
.filter(|w| w.is_finite())
|
||||
.fold(0.0f32, f32::max);
|
||||
let room = if lines >= 1.0 { lines.min(column) } else { column };
|
||||
if room.is_finite() && room >= 1.0 { room } else { first }
|
||||
}
|
||||
|
||||
/// Invalidate the cached layout (fonts changed etc.).
|
||||
pub fn relayout(&mut self) {
|
||||
self.layout = Default::default();
|
||||
|
||||
+7
-457
@@ -1124,164 +1124,6 @@ fn applying_a_heading_clears_list_numbering() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Make the first `upto` bytes of body paragraph `block` 20 pt, red and bold.
|
||||
fn formatted_words(s: &mut Session, block: usize, upto: usize) {
|
||||
select(s, (block, 0), (block, upto));
|
||||
run(s, "format.size", json!({"size": 20}));
|
||||
run(s, "format.color", json!({"color": "FF0000"}));
|
||||
run(s, "format.bold", json!({"value": true}));
|
||||
}
|
||||
|
||||
/// 39 characters, 40 with the paragraph mark.
|
||||
const WORDS: &str = "keep this text and some more words here";
|
||||
|
||||
fn select(s: &mut Session, from: (usize, usize), to: (usize, usize)) {
|
||||
run(s, "select.range", json!({"anchor": {"block": from.0, "off": from.1}, "focus": {"block": to.0, "off": to.1}}));
|
||||
}
|
||||
|
||||
/// Size, colour and bold set directly on the character at `off` of body paragraph `block`.
|
||||
fn direct(s: &Session, block: usize, off: usize) -> (Option<f32>, bool, Option<bool>) {
|
||||
let c = s.doc.para_at(&Pos::body(block, 0)).unwrap().props_of_char(off);
|
||||
(c.size, c.color.is_some(), c.bold)
|
||||
}
|
||||
|
||||
const KEPT: (Option<f32>, bool, Option<bool>) = (Some(20.0), true, Some(true));
|
||||
const RESET: (Option<f32>, bool, Option<bool>) = (None, false, None);
|
||||
|
||||
#[test]
|
||||
fn a_paragraph_style_keeps_direct_formatting_on_less_than_half_the_paragraph() {
|
||||
// #5947, as in Word: "keep" is 4 of 40 characters (the paragraph mark counts), so Heading 1
|
||||
// keeps its size, colour and bold with the caret or the whole paragraph selected. Its size and
|
||||
// colour used to go.
|
||||
for (case, from, to) in [("caret", 37, 37), ("whole paragraph", 0, 39)] {
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": WORDS}));
|
||||
formatted_words(&mut s, 0, 4);
|
||||
select(&mut s, (0, from), (0, to));
|
||||
run(&mut s, "para.heading1", json!({}));
|
||||
assert_eq!(para_style(&s, 0).as_deref(), Some("Heading1"), "{case}");
|
||||
assert_eq!(direct(&s, 0, 0), KEPT, "{case}");
|
||||
let doc = crate::io::open_bytes("k.docx", &crate::io::save_bytes("k.docx", &s.doc).unwrap()).unwrap();
|
||||
let back = doc.para_at(&Pos::body(0, 0)).unwrap().props_of_char(0);
|
||||
assert_eq!((back.size, back.bold), (Some(20.0), Some(true)), "{case}: saved and reopened");
|
||||
}
|
||||
// Characters, not bytes: 6 of 16 characters, but 12 of 22 bytes.
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "\u{e9}\u{e9}\u{e9}\u{e9}\u{e9}\u{e9} abcdefgh"}));
|
||||
formatted_words(&mut s, 0, 12);
|
||||
run(&mut s, "caret.set", json!({"pos": {"story": "body", "path": [0], "off": 20}}));
|
||||
run(&mut s, "para.heading1", json!({}));
|
||||
assert_eq!(direct(&s, 0, 0), KEPT);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_paragraph_style_resets_direct_formatting_on_half_the_paragraph_or_more() {
|
||||
// As in Word: "keep this text and some more" is 28 of 40 characters, so Heading 1 resets its
|
||||
// size, colour and bold everywhere in the paragraph, wherever the caret is. Each property
|
||||
// counts on its own: italic on "keep" alone stays, and highlight always stays.
|
||||
{
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": WORDS}));
|
||||
formatted_words(&mut s, 0, 28);
|
||||
run(&mut s, "format.highlight", json!({"color": "yellow"}));
|
||||
select(&mut s, (0, 0), (0, 4));
|
||||
run(&mut s, "format.italic", json!({"value": true}));
|
||||
run(&mut s, "caret.set", json!({"pos": {"story": "body", "path": [0], "off": 37}}));
|
||||
run(&mut s, "para.heading1", json!({}));
|
||||
for off in [0, 10, 27] {
|
||||
assert_eq!(direct(&s, 0, off), RESET, "offset {off}");
|
||||
}
|
||||
let p = s.doc.para_at(&Pos::body(0, 0)).unwrap();
|
||||
assert_eq!(p.props_of_char(0).italic, Some(true), "italic on 4 characters stays");
|
||||
assert!(p.props_of_char(10).highlight.is_some(), "highlight stays");
|
||||
}
|
||||
// Exactly half resets: 11 of 22. 10 of 21 doesn't, but a formatted paragraph mark makes the
|
||||
// size 11 of 21.
|
||||
for (text, upto, mark, want) in [
|
||||
("aaaa bbbb cccc ddddd.", 11, false, RESET),
|
||||
("aaaa bbbb cccc dddd.", 10, false, KEPT),
|
||||
("aaaa bbbb cccc dddd.", 10, true, (None, true, Some(true))),
|
||||
] {
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": text}));
|
||||
formatted_words(&mut s, 0, upto);
|
||||
if mark {
|
||||
s.doc.para_mut(StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap().mark.size = Some(20.0);
|
||||
}
|
||||
run(&mut s, "caret.set", json!({"pos": {"story": "body", "path": [0], "off": 18}}));
|
||||
run(&mut s, "para.heading1", json!({}));
|
||||
assert_eq!(direct(&s, 0, 0), want, "{upto} of {}, mark formatted: {mark}", text.len() + 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_paragraph_style_on_part_of_a_paragraph_resets_only_the_selection() {
|
||||
// As in Word: with part of one paragraph selected, the selection loses its direct formatting
|
||||
// and nothing outside it changes, however much of the paragraph it covers. First the #5947
|
||||
// case: "keep" formatted, "this" selected. Then 28 of 40 formatted: "words" selected keeps it
|
||||
// all, "this" selected loses only its own. Checked at "keep", "this" and "more".
|
||||
for (upto, from, to, want) in [(4, 5, 9, (KEPT, RESET, RESET)), (28, 29, 34, (KEPT, KEPT, KEPT)), (28, 5, 9, (KEPT, RESET, KEPT))] {
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": WORDS}));
|
||||
formatted_words(&mut s, 0, upto);
|
||||
select(&mut s, (0, from), (0, to));
|
||||
run(&mut s, "para.heading1", json!({}));
|
||||
assert_eq!(para_style(&s, 0).as_deref(), Some("Heading1"));
|
||||
assert_eq!((direct(&s, 0, 0), direct(&s, 0, 6), direct(&s, 0, 24)), want, "{upto} formatted, {from}..{to} selected");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_paragraph_style_on_several_paragraphs_follows_the_first() {
|
||||
// As in Word: the selection from its start to the end of its first paragraph decides, and
|
||||
// what it resets goes from every selected paragraph. Nothing was reset across paragraphs
|
||||
// before. One undo takes it all back.
|
||||
let two = |first: usize, second: usize| {
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": format!("{WORDS}\n{WORDS}")}));
|
||||
formatted_words(&mut s, 0, first);
|
||||
formatted_words(&mut s, 1, second);
|
||||
s
|
||||
};
|
||||
// 4 of 40 in the first: both keep theirs, the second's 28 of 40 too.
|
||||
let mut s = two(4, 28);
|
||||
select(&mut s, (0, 0), (1, 2));
|
||||
run(&mut s, "para.heading1", json!({}));
|
||||
assert_eq!((para_style(&s, 0).as_deref(), para_style(&s, 1).as_deref()), (Some("Heading1"), Some("Heading1")));
|
||||
assert_eq!((direct(&s, 0, 0), direct(&s, 1, 0), direct(&s, 1, 10)), (KEPT, KEPT, KEPT));
|
||||
// 28 of 40 in the first: both lose it, the second's 4 of 40 too.
|
||||
let mut s = two(28, 4);
|
||||
let before = s.doc.body.clone();
|
||||
select(&mut s, (0, 0), (1, 2));
|
||||
run(&mut s, "para.heading1", json!({}));
|
||||
assert_eq!((direct(&s, 0, 0), direct(&s, 0, 10), direct(&s, 1, 0)), (RESET, RESET, RESET));
|
||||
let after = s.doc.body.clone();
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(s.doc.body, before, "one undo");
|
||||
run(&mut s, "edit.redo", json!({}));
|
||||
assert_eq!(s.doc.body, after, "redo");
|
||||
// From "here" (unformatted, 5 characters with the mark) in the first: nothing is reset.
|
||||
let mut s = two(28, 28);
|
||||
select(&mut s, (0, 35), (1, 2));
|
||||
run(&mut s, "para.heading1", json!({}));
|
||||
assert_eq!((direct(&s, 0, 0), direct(&s, 1, 0)), (KEPT, KEPT));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_style_created_from_formatted_text_carries_its_formatting() {
|
||||
// New Style from the selection: the style takes the paragraph's look, so its direct
|
||||
// formatting (all of the paragraph) goes and the text looks the same.
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": WORDS}));
|
||||
formatted_words(&mut s, 0, 39);
|
||||
run(&mut s, "caret.set", json!({"pos": {"story": "body", "path": [0], "off": 6}}));
|
||||
let id = run(&mut s, "styles.create", json!({"name": "Loud"}))["id"].as_str().unwrap().to_string();
|
||||
let st = s.doc.styles.get(&id).unwrap();
|
||||
assert_eq!((st.chr.size, st.chr.color.is_some(), st.chr.bold), KEPT);
|
||||
assert_eq!(para_style(&s, 0).as_deref(), Some(id.as_str()));
|
||||
assert_eq!(direct(&s, 0, 6), RESET, "the style carries it now");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_replace() {
|
||||
let mut s = s();
|
||||
@@ -2693,40 +2535,6 @@ fn table_doc() -> Session {
|
||||
s
|
||||
}
|
||||
|
||||
/// #6326: text typed into a row added by Insert Above, Insert Below or Tab in the last cell gets
|
||||
/// the font of the cells it was copied from, as in Word, not the default font.
|
||||
#[test]
|
||||
fn new_table_rows_type_in_the_rows_font() {
|
||||
let mut s = table_doc();
|
||||
for (text, font) in [("A1", "Courier New"), ("A2", "Courier New"), ("B1", "Georgia"), ("B2", "Georgia")] {
|
||||
run(&mut s, "select.text", json!({"text": text}));
|
||||
run(&mut s, "format.font", json!({"name": font}));
|
||||
run(&mut s, "format.size", json!({"size": 16}));
|
||||
run(&mut s, "format.bold", json!({}));
|
||||
}
|
||||
let typed = |s: &Session, r: usize, c: usize| {
|
||||
let t = s.doc.body.iter().find_map(|b| b.as_table()).unwrap();
|
||||
let p = t.rows[r].cells[c].blocks[0].as_para().unwrap();
|
||||
(p.plain_text(), p.props_at(0).font.clone(), p.props_at(0).size, p.props_at(0).bold)
|
||||
};
|
||||
let courier = |t: &str| (t.to_string(), Some("Courier New".to_string()), Some(16.0), Some(true));
|
||||
let georgia = |t: &str| (t.to_string(), Some("Georgia".to_string()), Some(16.0), Some(true));
|
||||
// (command, the caret's row, the new row)
|
||||
for (cmd, src, r) in [("table.insertRowBelow", 0, 1), ("table.insertRowAbove", 2, 2)] {
|
||||
run(&mut s, "caret.set", json!({"pos": {"story": "body", "path": [1, src, 0, 0], "off": 1}}));
|
||||
run(&mut s, cmd, json!({}));
|
||||
run(&mut s, "text.insert", json!({"text": "new"}));
|
||||
run(&mut s, "text.tab", json!({}));
|
||||
run(&mut s, "text.insert", json!({"text": "cell"}));
|
||||
assert_eq!((typed(&s, r, 0), typed(&s, r, 1)), (courier("new"), georgia("cell")), "{cmd}");
|
||||
}
|
||||
// Tab in the last cell adds a row like the last one.
|
||||
run(&mut s, "caret.set", json!({"pos": {"story": "body", "path": [1, 3, 1, 0], "off": 2}}));
|
||||
run(&mut s, "text.tab", json!({}));
|
||||
run(&mut s, "text.insert", json!({"text": "tab"}));
|
||||
assert_eq!(typed(&s, 4, 0), courier("tab"));
|
||||
}
|
||||
|
||||
fn body_table_cells(s: &Session) -> Vec<Vec<String>> {
|
||||
s.doc
|
||||
.body
|
||||
@@ -4752,10 +4560,6 @@ fn set_author_refuses_blank_names_and_clamps_long_ones() {
|
||||
}
|
||||
run(&mut s, "file.setAuthor", json!({"name": "Ada\u{0}\u{1b} Lovelace"}));
|
||||
assert_eq!(s.author, "Ada Lovelace", "control characters can't reach the saved XML");
|
||||
for name in ["\u{0} Ada Lovelace", "\u{1b}\t Ada Lovelace \u{0}"] {
|
||||
run(&mut s, "file.setAuthor", json!({"name": name}));
|
||||
assert_eq!(s.author, "Ada Lovelace", "whitespace exposed by removing controls is trimmed; internal spaces stay");
|
||||
}
|
||||
run(&mut s, "file.setAuthor", json!({"name": "é".repeat(100_000)}));
|
||||
assert_eq!(s.author.chars().count(), cmd::file::MAX_AUTHOR_CHARS);
|
||||
}
|
||||
@@ -6159,22 +5963,6 @@ fn caret_navigation() {
|
||||
assert_eq!(s.sel.focus.off, 10);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn select_text_does_not_wrap_large_occurrence_numbers() {
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "match match"}));
|
||||
run(&mut s, "select.text", json!({"text": "match", "occurrence": 2}));
|
||||
let selected = s.sel.clone();
|
||||
let depth = s.undo_depth();
|
||||
// On a 32-bit target, narrowing either number to usize would select the first match.
|
||||
for occurrence in [4_294_967_297u64, 8_589_934_593] {
|
||||
let result = s.run("select.text", &json!({"text": "match", "occurrence": occurrence}));
|
||||
assert!(matches!(result, Err(crate::CmdError::Failed(_))), "{occurrence}: no such match");
|
||||
assert_eq!(s.sel, selected, "{occurrence}: a failed search keeps the selection");
|
||||
assert_eq!(s.undo_depth(), depth, "{occurrence}: a failed search adds no undo step");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_box_insert_puts_the_caret_inside() {
|
||||
let mut s = s();
|
||||
@@ -6493,8 +6281,8 @@ fn cut_and_copy_with_bare_caret_beside_object_change_nothing() {
|
||||
assert!(s.sel.is_collapsed());
|
||||
assert!(crate::cmd::objects::object_selection(&s).is_none());
|
||||
|
||||
let copy_res = s.run("edit.copy", &json!({}));
|
||||
assert!(matches!(copy_res, Err(crate::CmdError::Disabled(_))), "copy on bare caret is disabled");
|
||||
let copy_res = run(&mut s, "edit.copy", json!({}));
|
||||
assert_eq!(copy_res["text"], "", "copy on bare caret returns empty text");
|
||||
assert!(s.clipboard.is_none(), "clipboard remains unset");
|
||||
|
||||
let cut_res = s.run("edit.cut", &json!({}));
|
||||
@@ -6509,8 +6297,8 @@ fn cut_and_copy_with_bare_caret_beside_object_change_nothing() {
|
||||
assert!(s.sel.is_collapsed());
|
||||
assert!(crate::cmd::objects::object_selection(&s).is_none());
|
||||
|
||||
let copy_res = s.run("edit.copy", &json!({}));
|
||||
assert!(matches!(copy_res, Err(crate::CmdError::Disabled(_))), "copy on bare caret is disabled");
|
||||
let copy_res = run(&mut s, "edit.copy", json!({}));
|
||||
assert_eq!(copy_res["text"], "", "copy on bare caret returns empty text");
|
||||
assert!(s.clipboard.is_none(), "clipboard remains unset");
|
||||
|
||||
let cut_res = s.run("edit.cut", &json!({}));
|
||||
@@ -7967,46 +7755,6 @@ fn props_colours_take_hex_strings() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The Paragraph dialog's indents in points win over indents in characters, as in Word: a
|
||||
/// document from WPS with `w:firstLineChars="400" w:firstLine="1417"` set to a first line of
|
||||
/// 2.5 cm keeps 2.5 cm, not four characters. The paragraph's own characters and its style's are
|
||||
/// cancelled; a paragraph without any is left without, and characters given with it stay.
|
||||
#[test]
|
||||
fn para_set_indents_in_points_win_over_indents_in_characters() {
|
||||
use wordcraft_doc::{Path, Pos};
|
||||
let mut s = s();
|
||||
run(&mut s, "text.insert", json!({"text": "One"}));
|
||||
run(&mut s, "text.newParagraph", json!({}));
|
||||
run(&mut s, "text.insert", json!({"text": "Two"}));
|
||||
let own = |s: &Session, i: usize| s.doc.para_at(&Pos::body(i, 0)).unwrap().props.clone();
|
||||
let shown = |s: &Session, i: usize| s.doc.styles.resolve_para(&own(s, i));
|
||||
{
|
||||
let p = &mut s.doc.para_mut(StoryRef::Body, &Path::top(0)).unwrap().props;
|
||||
(p.indent_first_chars, p.indent_first) = (Some(4.0), Some(70.85));
|
||||
}
|
||||
assert!((shown(&s, 0).indent_first - 70.85).abs() > 1.0, "four characters, not the points beside them");
|
||||
let cm = 2.5 * 72.0 / 2.54;
|
||||
|
||||
s.sel = crate::Selection::caret(Pos::body(0, 0));
|
||||
run(&mut s, "para.set", json!({"props": {"indentFirst": cm}}));
|
||||
assert_eq!((own(&s, 0).indent_first, own(&s, 0).indent_first_chars), (Some(cm), Some(0.0)));
|
||||
assert!((shown(&s, 0).indent_first - cm).abs() < 0.01, "2.5 cm on the page");
|
||||
|
||||
s.sel = crate::Selection::caret(Pos::body(1, 0));
|
||||
run(&mut s, "para.set", json!({"props": {"indentFirst": cm}}));
|
||||
assert_eq!(own(&s, 1).indent_first_chars, None, "no characters to cancel, none written");
|
||||
|
||||
// The style's characters, on the start edge through `onPage`, give way too.
|
||||
run(&mut s, "styles.modify", json!({"style": "Normal", "para": {"indentLeftChars": 2.0}}));
|
||||
run(&mut s, "para.set", json!({"props": {}, "onPage": {"left": 36.0}}));
|
||||
assert_eq!((own(&s, 1).indent_left, own(&s, 1).indent_left_chars), (Some(36.0), Some(0.0)));
|
||||
assert!((shown(&s, 1).indent_left - 36.0).abs() < 0.01);
|
||||
|
||||
// Characters given along with the points are kept.
|
||||
run(&mut s, "para.set", json!({"props": {"indentFirst": 24.0, "indentFirstChars": 2.0}}));
|
||||
assert_eq!(own(&s, 1).indent_first_chars, Some(2.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn para_set_frame_geometry_keeps_anchor_lock_unless_replaced() {
|
||||
use wordcraft_doc::props::TextFrame;
|
||||
@@ -10604,21 +10352,13 @@ fn convert_to_text_takes_each_separator() {
|
||||
let obj = wordcraft_doc::para::OBJ.to_string();
|
||||
for bad in [
|
||||
json!({"separator": "other"}),
|
||||
json!({"separator": "other", "char": ""}),
|
||||
json!({"separator": "other", "char": "\n"}),
|
||||
json!({"separator": "other", "char": "\r"}),
|
||||
json!({"separator": "other", "char": obj}),
|
||||
json!({"separator": "pipe"}),
|
||||
] {
|
||||
let mut s = typed_table(2, &["a", "b", "c", "d"]);
|
||||
let depth = s.undo_depth();
|
||||
let err = s.run("table.toText", &bad).unwrap_err();
|
||||
if bad["separator"] == "other" {
|
||||
assert!(
|
||||
matches!(err, crate::CmdError::Params(ref message) if message == "`char` with `other` must start with a character other than CR, LF or U+FFFC (the object marker); only the first character is used"),
|
||||
"{bad}: {err}"
|
||||
);
|
||||
}
|
||||
assert!(s.run("table.toText", &bad).is_err(), "{bad}");
|
||||
assert!(s.doc.body.iter().any(|b| b.as_table().is_some()), "{bad}: the table stays");
|
||||
assert_eq!(s.undo_depth(), depth);
|
||||
}
|
||||
@@ -10976,18 +10716,8 @@ fn convert_text_to_table_dialog_options() {
|
||||
let mut s1 = s();
|
||||
run(&mut s1, "document.setText", json!({"text": "a-b"}));
|
||||
run(&mut s1, "select.all", json!({}));
|
||||
for bad in [
|
||||
json!({"separator": "other"}),
|
||||
json!({"separator": "other", "char": ""}),
|
||||
json!({"separator": "other", "char": "\n"}),
|
||||
json!({"separator": "other", "char": "\r"}),
|
||||
] {
|
||||
let err = s1.run("table.fromText", &bad).unwrap_err();
|
||||
assert!(
|
||||
matches!(err, crate::CmdError::Params(ref message) if message == "`char` with `other` must start with a character other than CR or LF; only the first character is used"),
|
||||
"{bad}: {err}"
|
||||
);
|
||||
}
|
||||
assert!(s1.run("table.fromText", &json!({"separator": "other"})).is_err(), "no character");
|
||||
assert!(s1.run("table.fromText", &json!({"separator": "other", "char": ""})).is_err());
|
||||
assert!(s1.run("table.fromText", &json!({"separator": "nonsense"})).is_err());
|
||||
assert!(s1.run("table.fromText", &json!({"autofit": "nonsense"})).is_err());
|
||||
assert_eq!(body_texts(&s1), ["a-b"]);
|
||||
@@ -11799,49 +11529,6 @@ fn review_language_validates_tags_and_marks_text_unchecked() {
|
||||
assert_eq!(run(&mut s, "review.issues", json!({})), json!([]));
|
||||
}
|
||||
|
||||
/// #6013: as in Word, a table inserted in French text is French. Its cells take the language at
|
||||
/// the caret, not the document's default, so what is typed in them is proofed in that language.
|
||||
#[test]
|
||||
fn a_new_table_is_in_the_language_at_the_caret() {
|
||||
polish_test_dictionary();
|
||||
let cell_langs = |s: &Session| -> Vec<Option<String>> {
|
||||
let t = s.doc.body.iter().find_map(|b| b.as_table()).unwrap();
|
||||
t.rows.iter().flat_map(|r| &r.cells).flat_map(|c| &c.blocks).filter_map(|b| b.as_para()).map(|p| p.mark.lang.clone()).collect()
|
||||
};
|
||||
let mut fr = s();
|
||||
assert_eq!(fr.doc.styles.default_chr.lang.as_deref(), Some("en-US"));
|
||||
run(&mut fr, "review.language", json!({"lang": "fr-FR"}));
|
||||
run(&mut fr, "text.insert", json!({"text": "Bonjour"}));
|
||||
run(&mut fr, "text.newParagraph", json!({}));
|
||||
let at = run(&mut fr, "insert.table", json!({"rows": 2, "cols": 2}))["table"][0].clone();
|
||||
assert_eq!(cell_langs(&fr), vec![Some("fr-FR".to_string()); 4]);
|
||||
// Click in a cell, then type.
|
||||
for (cell, word) in [(1, "Vin"), (2, "Fromage")] {
|
||||
run(&mut fr, "caret.set", json!({"pos": {"story": "body", "path": [at, cell / 2, cell % 2, 0], "off": 0}}));
|
||||
assert_eq!(run(&mut fr, "format.state", json!({}))["lang"], "fr-FR", "cell {cell}");
|
||||
run(&mut fr, "text.insert", json!({"text": word}));
|
||||
}
|
||||
let t = fr.doc.body.iter().find_map(|b| b.as_table()).unwrap();
|
||||
for (cell, word) in [(1, "Vin"), (2, "Fromage")] {
|
||||
let p = t.rows[cell / 2].cells[cell % 2].blocks[0].as_para().unwrap();
|
||||
assert_eq!((p.plain_text().as_str(), p.props_of_char(0).lang.as_deref()), (word, Some("fr-FR")));
|
||||
}
|
||||
|
||||
// At the end of a Polish paragraph: Polish words typed in the cell aren't misspelt.
|
||||
let mut pl = Session::new(wordcraft_doc::Document::from_text("Płynie rzeka."));
|
||||
run(&mut pl, "select.all", json!({}));
|
||||
run(&mut pl, "review.language", json!({"lang": "pl-PL"}));
|
||||
run(&mut pl, "caret.docEnd", json!({}));
|
||||
run(&mut pl, "insert.table", json!({"rows": 1, "cols": 1}));
|
||||
run(&mut pl, "text.insert", json!({"text": "Zażółć gęślą jaźń."}));
|
||||
assert_eq!(run(&mut pl, "review.issues", json!({})), json!([]));
|
||||
|
||||
// Text with no language of its own: the cells follow the document's default.
|
||||
let mut plain = s();
|
||||
run(&mut plain, "insert.table", json!({"rows": 1, "cols": 2}));
|
||||
assert_eq!(cell_langs(&plain), vec![None, None]);
|
||||
}
|
||||
|
||||
/// The editing language (set by the front end from the interface language): new blank
|
||||
/// documents and opened plain text are written in it; the untouched first document switches,
|
||||
/// a document with changes never does, and templates stay English.
|
||||
@@ -15256,143 +14943,6 @@ fn page_down_extends_a_selection_that_ends_in_collapsed_outline_text() {
|
||||
assert!(s.layout().caret(&s.sel.focus).is_some(), "to a place the outline shows");
|
||||
}
|
||||
|
||||
/// #5428: an inserted or pasted picture fits where it goes, as in Word: a table cell's width
|
||||
/// (a nested cell's too), a column's, not the whole page's text width.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn an_inserted_or_pasted_picture_fits_where_it_goes() {
|
||||
let png = |w: u32, h: u32| {
|
||||
let mut b = Vec::new();
|
||||
image::RgbaImage::from_pixel(w, h, image::Rgba([30, 90, 200, 255]))
|
||||
.write_to(&mut std::io::Cursor::new(&mut b), image::ImageFormat::Png)
|
||||
.unwrap();
|
||||
cmd::insert::base64_encode(&b)
|
||||
};
|
||||
let widths = |s: &Session| {
|
||||
let mut v = Vec::new();
|
||||
for b in s.doc.body.iter() {
|
||||
let mut b = (**b).clone();
|
||||
cmd::paste::each_para(&mut b, 0, &mut |p| {
|
||||
for o in &p.objects {
|
||||
if let wordcraft_doc::InlineObject::Image { w, h, .. } = o {
|
||||
v.push((*w, *h));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
v
|
||||
};
|
||||
let text_w = crate::io::text_width(&Session::new(wordcraft_doc::Document::new()).doc);
|
||||
let in_cell = |cols: u32| {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
run(&mut s, "insert.table", json!({"rows": 1, "cols": cols}));
|
||||
assert!(s.sel.focus.path.depth() > 0, "the caret is in the first cell");
|
||||
s
|
||||
};
|
||||
// Insert › Pictures and Paste in a cell of a three-column table.
|
||||
let cell = text_w / 3.0;
|
||||
let mut s = in_cell(3);
|
||||
run(&mut s, "insert.picture", json!({"data": png(1000, 200)}));
|
||||
let mut p = in_cell(3);
|
||||
let html = format!("<p><img src=\"data:image/png;base64,{}\"></p>", png(1000, 200));
|
||||
run(&mut p, "edit.pasteSpecial", json!({"as": "html", "html": html}));
|
||||
for (how, s) in [("inserted", &s), ("pasted", &p)] {
|
||||
let got = widths(s);
|
||||
let [(w, h)] = got.as_slice() else { panic!("{how}: {got:?}") };
|
||||
assert!(*w <= cell && *w > cell - 20.0, "{how}: {w} fits the cell's text area ({cell} less its margins)");
|
||||
assert!((h * 5.0 - w).abs() < 0.1, "{how}: proportions kept: {w} × {h}");
|
||||
}
|
||||
// A table in that cell: its own narrower cell.
|
||||
let mut s = in_cell(2);
|
||||
let outer = s.room_at(&s.sel.focus.clone());
|
||||
// (A table inserted in a cell takes the page's text width for its columns, so four columns
|
||||
// make its cells narrower than the outer one.)
|
||||
run(&mut s, "insert.table", json!({"rows": 1, "cols": 4}));
|
||||
assert!(s.sel.focus.path.depth() > 1, "the caret is in the nested cell");
|
||||
let nested = s.room_at(&s.sel.focus.clone());
|
||||
assert!(nested < outer - 50.0, "the nested cell ({nested}) is narrower than the outer one ({outer})");
|
||||
run(&mut s, "insert.picture", json!({"data": png(1000, 200)}));
|
||||
let w = widths(&s)[0].0;
|
||||
assert!((w - nested).abs() < 0.5 && w <= text_w / 4.0, "{w} fits the nested cell ({nested})");
|
||||
// Two text columns: one column's width.
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
run(&mut s, "layout.columns", json!({"count": 2}));
|
||||
let column = s.doc.sections()[0].1.column_boxes()[0].1;
|
||||
run(&mut s, "insert.picture", json!({"data": png(1000, 200)}));
|
||||
let w = widths(&s)[0].0;
|
||||
assert!((w - column).abs() < 0.5, "{w} fits the column ({column})");
|
||||
// Body text keeps the full text width.
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
run(&mut s, "insert.picture", json!({"data": png(1000, 200)}));
|
||||
assert!((widths(&s)[0].0 - text_w).abs() < 0.5);
|
||||
}
|
||||
|
||||
/// #5428 review: a page can hold several continuous sections; a picture goes by the section of the
|
||||
/// position, not of the page's first one (two columns, then a continuous single-column section).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_picture_after_a_continuous_break_fits_its_own_section() {
|
||||
let sect = |cols: &str, kind: &str| format!(r#"<w:sectPr>{kind}<w:pgSz w:w="11906" w:h="16838"/><w:cols {cols} w:space="708"/></w:sectPr>"#);
|
||||
let body = [
|
||||
"<w:p><w:r><w:t>one</w:t></w:r></w:p>".to_string(),
|
||||
format!("<w:p><w:pPr>{}</w:pPr></w:p>", sect(r#"w:num="2""#, "")),
|
||||
"<w:p><w:r><w:t>two</w:t></w:r></w:p>".to_string(),
|
||||
sect("", r#"<w:type w:val="continuous"/>"#),
|
||||
]
|
||||
.concat();
|
||||
let mut s = Session::new(wordcraft_docx::read(&docx_with_styles(&body, "")).unwrap());
|
||||
let last = s.doc.body.len() - 1;
|
||||
s.sel = crate::Selection::caret(Pos::body(last, 0));
|
||||
let room = s.room_at(&s.sel.focus.clone());
|
||||
let column = s.doc.sections()[0].1.column_boxes()[0].1;
|
||||
assert!(room > column + 50.0, "{room} is the single column's width, not the earlier two columns' ({column})");
|
||||
}
|
||||
|
||||
/// #5428 review: Web Layout and Read Mode reflow the text to the window, but a picture put in
|
||||
/// there is fitted to the page's text width, as in Print Layout: the size stays in the document.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_picture_put_in_in_web_layout_fits_the_page_not_the_window() {
|
||||
let png = |w: u32, h: u32| {
|
||||
let mut b = Vec::new();
|
||||
image::RgbaImage::from_pixel(w, h, image::Rgba([30, 90, 200, 255]))
|
||||
.write_to(&mut std::io::Cursor::new(&mut b), image::ImageFormat::Png)
|
||||
.unwrap();
|
||||
cmd::insert::base64_encode(&b)
|
||||
};
|
||||
let width = |s: &Session| {
|
||||
s.doc.body.iter().filter_map(|b| b.as_para()).flat_map(|p| p.objects.iter()).find_map(|o| match o {
|
||||
wordcraft_doc::InlineObject::Image { w, .. } => Some(*w),
|
||||
_ => None,
|
||||
})
|
||||
};
|
||||
let text_w = crate::io::text_width(&Session::new(wordcraft_doc::Document::new()).doc);
|
||||
let web = || {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
run(&mut s, "view.webLayout", json!({}));
|
||||
// A narrow window, or a high zoom.
|
||||
s.view.web_width = 350.0;
|
||||
assert!(s.layout().pages[0].w < text_w, "the window is narrower than the page's text");
|
||||
s
|
||||
};
|
||||
let mut s = web();
|
||||
run(&mut s, "insert.picture", json!({"data": png(1000, 200)}));
|
||||
let mut p = web();
|
||||
let html = format!("<p><img src=\"data:image/png;base64,{}\"></p>", png(1000, 200));
|
||||
run(&mut p, "edit.pasteSpecial", json!({"as": "html", "html": html}));
|
||||
for (how, s) in [("inserted", &s), ("pasted", &p)] {
|
||||
let w = width(s).unwrap();
|
||||
assert!((w - text_w).abs() < 0.5, "{how}: {w} fits the page's text width ({text_w})");
|
||||
}
|
||||
// Read Mode's narrow pages don't set it either.
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
run(&mut s, "text.insert", json!({"text": "Read"}));
|
||||
run(&mut s, "view.readMode", json!({}));
|
||||
s.view.read_width = 240.0;
|
||||
let room = s.room_at(&s.sel.focus.clone());
|
||||
assert!((room - text_w).abs() < 0.5, "Read Mode: {room} is the page's text width ({text_w})");
|
||||
}
|
||||
|
||||
/// A picture an OpenDocument file gives no size is shown at its own, fitted to the text as other
|
||||
/// formats' are; one with a stated size keeps it, in line too.
|
||||
#[test]
|
||||
|
||||
@@ -92,91 +92,3 @@ fn normal_double_quote_search_keeps_exact_modes_and_original_byte_ranges() {
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(text(&s), original);
|
||||
}
|
||||
|
||||
/// #7307: with smart quotes on, a quote typed in Replace with goes in curly by the character
|
||||
/// before the match, as typing curls it, so finding a straight quote and replacing it with a
|
||||
/// typed one curls a manuscript's stray quotes in bulk.
|
||||
#[test]
|
||||
fn a_quote_typed_in_replace_with_is_curled_by_smart_quotes() {
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "He said \"hi\" (\"no\") and 'bye' -- don't"}));
|
||||
assert_eq!(run(&mut s, "edit.replaceAll", json!({"text": "^034", "with": "\""}))["replaced"], 4);
|
||||
assert_eq!(text(&s), "He said “hi” (“no”) and 'bye' -- don't");
|
||||
assert_eq!(run(&mut s, "edit.replaceAll", json!({"text": "^039", "with": "'"}))["replaced"], 3);
|
||||
assert_eq!(text(&s), "He said “hi” (“no”) and ‘bye’ -- don’t");
|
||||
// One undo step each.
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(text(&s), "He said “hi” (“no”) and 'bye' -- don't");
|
||||
|
||||
// A match touching the one before it curls by that one's replacement: after an opening
|
||||
// double quote a single quote opens too.
|
||||
let mut s = super::s();
|
||||
run(&mut s, "document.setText", json!({"text": "xx"}));
|
||||
assert_eq!(run(&mut s, "edit.replaceAll", json!({"text": "x", "with": "'\""}))["replaced"], 2);
|
||||
assert_eq!(text(&s), "‘“‘“");
|
||||
|
||||
// Replace (one at a time) changes only the selected match, so the text before it as it is
|
||||
// decides: the second `x` follows an unreplaced `x` and closes.
|
||||
let mut s = super::s();
|
||||
run(&mut s, "document.setText", json!({"text": "xx"}));
|
||||
run(&mut s, "select.range", json!({"anchor": wordcraft_doc::Pos::body(0, 1), "focus": wordcraft_doc::Pos::body(0, 2)}));
|
||||
assert_eq!(run(&mut s, "edit.replace", json!({"text": "x", "with": "'\""}))["replaced"], 1);
|
||||
assert_eq!(text(&s), "x’”");
|
||||
}
|
||||
|
||||
/// #7307: a typed `'` in Find what also finds curly apostrophes. A match that already is a curly
|
||||
/// quote of that kind is left as it is and not counted, so an apostrophe set on purpose (’90s)
|
||||
/// isn't turned into an opening quote.
|
||||
#[test]
|
||||
fn replace_with_a_typed_quote_leaves_curly_ones_and_does_not_count_them() {
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "the ’90s, it’s 'x' and “y”"}));
|
||||
assert_eq!(run(&mut s, "edit.replaceAll", json!({"text": "'", "with": "'"}))["replaced"], 2);
|
||||
assert_eq!(text(&s), "the ’90s, it’s ‘x’ and “y”");
|
||||
assert_eq!(run(&mut s, "edit.replaceAll", json!({"text": "\"", "with": "\""}))["replaced"], 0);
|
||||
assert_eq!(text(&s), "the ’90s, it’s ‘x’ and “y”");
|
||||
// A whole word with its apostrophe: already curled, left alone; straight, curled.
|
||||
run(&mut s, "document.setText", json!({"text": "don’t don't"}));
|
||||
assert_eq!(run(&mut s, "edit.replaceAll", json!({"text": "don't", "with": "don't"}))["replaced"], 1);
|
||||
assert_eq!(text(&s), "don’t don’t");
|
||||
|
||||
// Replace (one at a time) skips such a match too, and moves on to the next.
|
||||
let mut s = super::s();
|
||||
run(&mut s, "document.setText", json!({"text": "it’s 'x"}));
|
||||
let first = run(&mut s, "edit.replace", json!({"text": "'", "with": "'"}));
|
||||
assert_eq!(first["replaced"], 0, "the first call selects the first match");
|
||||
let kept = run(&mut s, "edit.replace", json!({}));
|
||||
assert_eq!((kept["replaced"].clone(), text(&s)), (json!(0), "it’s 'x".to_string()), "the curly apostrophe stays");
|
||||
assert_eq!(run(&mut s, "edit.replace", json!({}))["replaced"], 1);
|
||||
assert_eq!(text(&s), "it’s ‘x");
|
||||
}
|
||||
|
||||
/// #7307: a quote given by its code stays straight, so curly quotes can still be made straight on
|
||||
/// purpose; with smart quotes off, or with a regular expression, a typed quote stays straight too.
|
||||
#[test]
|
||||
fn coded_quotes_and_smart_quotes_off_replace_with_straight_quotes() {
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "“hi” it’s"}));
|
||||
assert_eq!(run(&mut s, "edit.replaceAll", json!({"text": "\"", "with": "^034"}))["replaced"], 2);
|
||||
assert_eq!(run(&mut s, "edit.replaceAll", json!({"text": "'", "with": "^039"}))["replaced"], 1);
|
||||
assert_eq!(text(&s), "\"hi\" it's");
|
||||
|
||||
let mut s = super::s();
|
||||
run(&mut s, "document.setText", json!({"text": "“hi”"}));
|
||||
assert_eq!(run(&mut s, "edit.replaceAll", json!({"text": "\"", "with": "\"", "regex": false, "wildcards": false}))["replaced"], 0);
|
||||
assert_eq!(run(&mut s, "edit.replaceAll", json!({"text": "[“”]", "with": "\"", "regex": true}))["replaced"], 2);
|
||||
assert_eq!(text(&s), "\"hi\"");
|
||||
|
||||
// Special characters off takes Replace with as written: with codes off it is the way, besides
|
||||
// turning smart quotes off, to put a straight quote in.
|
||||
let mut s = super::s();
|
||||
run(&mut s, "document.setText", json!({"text": "“hi”"}));
|
||||
assert_eq!(run(&mut s, "edit.replaceAll", json!({"text": "“", "with": "\"", "special": false}))["replaced"], 1);
|
||||
assert_eq!(text(&s), "\"hi”");
|
||||
|
||||
let mut s = super::s();
|
||||
s.prefs.autocorrect.smart_quotes = false;
|
||||
run(&mut s, "document.setText", json!({"text": "“hi”"}));
|
||||
assert_eq!(run(&mut s, "edit.replaceAll", json!({"text": "\"", "with": "\"", "regex": false}))["replaced"], 2);
|
||||
assert_eq!(text(&s), "\"hi\"");
|
||||
}
|
||||
|
||||
@@ -1258,16 +1258,3 @@ fn html_container_shading_is_paragraph_shading_while_inline_highlight_stays_on_r
|
||||
assert_eq!(p2.runs.first().and_then(|r| r.props.shading), Some(wordcraft_doc::Rgb(0xff, 0xff, 0x00)), "{exported}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn odt_list_item_later_paragraphs_stay_in_the_item() {
|
||||
// "One" has two paragraphs. The second must stay inside item 1, so HTML's "Two" is item 2.
|
||||
let fodt = r#"<?xml version="1.0" encoding="UTF-8"?>
|
||||
<office:document xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" office:version="1.3" office:mimetype="application/vnd.oasis.opendocument.text"><office:automatic-styles><text:list-style style:name="L1"><text:list-level-style-number text:level="1" style:num-format="1"/></text:list-style></office:automatic-styles><office:body><office:text><text:list text:style-name="L1"><text:list-item><text:p>One</text:p><text:p>Still one</text:p></text:list-item><text:list-item><text:p>Two</text:p></text:list-item></text:list></office:text></office:body></office:document>"#;
|
||||
let doc = crate::odt::import_flat(fodt.as_bytes()).unwrap();
|
||||
let html = crate::html::export(&doc);
|
||||
assert_eq!(html.matches("<ol").count(), 1, "one list, not restarted: {html}");
|
||||
let (one, still, two) = (html.find("One").unwrap(), html.find("Still one").unwrap(), html.find("Two").unwrap());
|
||||
assert!(one < still && still < two, "{html}");
|
||||
assert!(html[one..still].matches("</li>").count() == 0, "later paragraph left item 1: {html}");
|
||||
}
|
||||
|
||||
@@ -23,7 +23,6 @@ pub(crate) enum Pass {
|
||||
/// Walk state while paginating.
|
||||
pub(crate) struct Ctx<'a> {
|
||||
pub(crate) doc: &'a Document,
|
||||
pub(crate) numbering: wordcraft_doc::numbering::NumberingIndex<'a>,
|
||||
pub(crate) cache: &'a mut LayoutCache,
|
||||
pub(crate) opts: &'a LayoutOptions,
|
||||
pub(crate) counters: Counters,
|
||||
@@ -290,11 +289,11 @@ impl Ctx<'_> {
|
||||
.numbering
|
||||
.or_else(|| self.doc.styles.resolve_para(&p.props).numbering)
|
||||
.filter(|n| n.num != 0)
|
||||
.is_some_and(|n| self.numbering.shows_label(n.num, n.level))
|
||||
.is_some_and(|n| self.doc.numbering.shows_label(n.num, n.level))
|
||||
}
|
||||
pub(crate) fn next_label(&mut self, p: &Paragraph) -> Option<(String, Level)> {
|
||||
let n = p.props.numbering.or_else(|| self.doc.styles.resolve_para(&p.props).numbering).filter(|n| n.num != 0)?;
|
||||
self.counters.next_label_indexed(&self.numbering, n.num, n.level)
|
||||
self.counters.next_label(&self.doc.numbering, n.num, n.level)
|
||||
}
|
||||
|
||||
/// Lay out `p` with its already counted `label`, so laying a paragraph out again (around
|
||||
@@ -588,7 +587,6 @@ mod tests {
|
||||
let mut cache = LayoutCache::new();
|
||||
let mut ctx = Ctx {
|
||||
doc: &doc,
|
||||
numbering: wordcraft_doc::numbering::NumberingIndex::new(&doc.numbering),
|
||||
cache: &mut cache,
|
||||
opts: &opts,
|
||||
counters: Default::default(),
|
||||
|
||||
@@ -750,14 +750,11 @@ fn inline_objects(ctx: &LineContext<'_, '_, '_>, out: &mut Vec<Draw>) {
|
||||
}
|
||||
|
||||
fn proofing_marks(ctx: &LineContext<'_, '_, '_>, out: &mut Vec<Draw>) {
|
||||
// Spaces hanging past the right margin are marked only up to where the caret stops (#6434).
|
||||
let limit = ctx.pl.caret_limit(ctx.li);
|
||||
for (start, end, grammar) in &ctx.pl.issues {
|
||||
if *end <= ctx.line.start || *start >= ctx.line.stop {
|
||||
continue;
|
||||
}
|
||||
for (x0, x1) in ctx.pl.x_spans(ctx.li, (*start).max(ctx.line.start), (*end).min(ctx.line.stop)) {
|
||||
let (x0, x1) = limit.map_or((x0, x1), |m| (x0.min(m), x1.min(m)));
|
||||
if x1 - x0 < 1.0 {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::options::DisplayOptions;
|
||||
use super::paint::{Paint, paint_for};
|
||||
use super::{BezPath, Document, Draw, FaceRef, Graphic, GraphicItem, GraphicKind, InlineObject, PathSeg, Rect, Rgb, ShapeKind, Spin, TextAlign};
|
||||
use wordcraft_doc::connector::{ArrowStyle, LineCap};
|
||||
use wordcraft_doc::connector::ArrowStyle;
|
||||
|
||||
/// The draws of a chart or diagram's items inside `rect` (page coordinates). The items were built
|
||||
/// for the size `g.w` × `g.h` (0: `rect`'s own size), so they are scaled to `rect`; strokes and text
|
||||
@@ -294,14 +294,9 @@ fn line_draws(
|
||||
out: &mut Vec<Draw>,
|
||||
) {
|
||||
use wordcraft_doc::connector::{connector_segs, end_direction};
|
||||
let start_dir = end_direction(kind, rect.w, rect.h, false);
|
||||
let end_dir = end_direction(kind, rect.w, rect.h, true);
|
||||
// An arrowed end stops inside its head, which the stroke would otherwise stick out of.
|
||||
let inset = |on: bool, style| if on && stroke.is_some() { arrow_inset(stroke_width, style, extra.cap) } else { 0.0 };
|
||||
let ends = [(inset(extra.arrow_start, extra.start_style), start_dir), (inset(extra.arrow_end, extra.end_style), end_dir)];
|
||||
match connector_segs(kind, rect.w, rect.h) {
|
||||
Some(segs) => {
|
||||
let mut segs: Vec<PathSeg> = segs
|
||||
let segs = segs
|
||||
.into_iter()
|
||||
.map(|s| match s {
|
||||
PathSeg::Move(x, y) => PathSeg::Move(rect.x + x, rect.y + y),
|
||||
@@ -310,92 +305,32 @@ fn line_draws(
|
||||
PathSeg::Close => PathSeg::Close,
|
||||
})
|
||||
.collect();
|
||||
shorten_ends(&mut segs, ends);
|
||||
let width = path_stroke_width(stroke_width);
|
||||
out.push(Draw::Path { segs, fill: None, stroke, stroke_width: width, dash: extra.dash.pattern(width), cap: extra.cap });
|
||||
}
|
||||
None => {
|
||||
// A line's frame is its diagonal, top left to bottom right: shortened, it stays one.
|
||||
let mut segs = [PathSeg::Move(rect.x, rect.y), PathSeg::Line(rect.right(), rect.bottom())];
|
||||
shorten_ends(&mut segs, ends);
|
||||
let line = match segs {
|
||||
[PathSeg::Move(x0, y0), PathSeg::Line(x1, y1)] => Rect::new(x0.min(x1), y0.min(y1), (x1 - x0).abs(), (y1 - y0).abs()),
|
||||
_ => rect,
|
||||
};
|
||||
out.push(Draw::Shape {
|
||||
rect: line,
|
||||
kind,
|
||||
fill: None,
|
||||
stroke,
|
||||
stroke_width,
|
||||
effects,
|
||||
corner: None,
|
||||
dash: extra.dash.pattern(stroke_width),
|
||||
cap: extra.cap,
|
||||
});
|
||||
}
|
||||
None => out.push(Draw::Shape {
|
||||
rect,
|
||||
kind,
|
||||
fill: None,
|
||||
stroke,
|
||||
stroke_width,
|
||||
effects,
|
||||
corner: None,
|
||||
dash: extra.dash.pattern(stroke_width),
|
||||
cap: extra.cap,
|
||||
}),
|
||||
}
|
||||
let Some(color) = stroke else { return };
|
||||
// A line runs from the top-left corner to the bottom-right, as it is drawn (DrawingML's
|
||||
// `line`), and so do connectors; flips are the frame's turn.
|
||||
let (start, end) = ((rect.x, rect.y), (rect.right(), rect.bottom()));
|
||||
for (on, tip, dir, style) in [(extra.arrow_start, start, start_dir, extra.start_style), (extra.arrow_end, end, end_dir, extra.end_style)] {
|
||||
for (on, tip, at_end, style) in [(extra.arrow_start, start, false, extra.start_style), (extra.arrow_end, end, true, extra.end_style)] {
|
||||
if on {
|
||||
out.push(arrowhead(tip, dir, stroke_width, style, color));
|
||||
out.push(arrowhead(tip, end_direction(kind, rect.w, rect.h, at_end), stroke_width, style, color));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How far short of an arrowhead's tip a line `stroke_width` wide with `cap` ends stops, so that
|
||||
/// none of its stroke shows outside the head (#6767): where the head is as wide as the stroke,
|
||||
/// plus what the cap reaches past the end. A head is at least twice as wide as its line, so this
|
||||
/// is inside the head; never past its base.
|
||||
fn arrow_inset(stroke_width: f32, style: ArrowStyle, cap: LineCap) -> f32 {
|
||||
let width = path_stroke_width(stroke_width);
|
||||
let (len, wide) = style.dims(stroke_width);
|
||||
let reach = if cap == LineCap::Flat { 0.0 } else { width / 2.0 };
|
||||
(len * width / wide.max(f32::EPSILON) + reach).clamp(0.0, len)
|
||||
}
|
||||
|
||||
/// Draw the path `segs` (a line's or connector's, from its start to its end) short of its ends:
|
||||
/// each end by its distance, back against its unit direction (where its arrowhead points). An end
|
||||
/// moves at most half way to its neighbouring point, so the path keeps its shape, and a curve its
|
||||
/// direction at the end. The two ends of a single straight segment share its length in proportion
|
||||
/// to their distances instead, so an end without an arrowhead leaves its share to the other.
|
||||
fn shorten_ends(segs: &mut [PathSeg], [(start, start_dir), (end, end_dir)]: [(f32, (f32, f32)); 2]) {
|
||||
let distance = |by: f32| if by.is_finite() { by.max(0.0) } else { 0.0 };
|
||||
let (start, end) = (distance(start), distance(end));
|
||||
let share = |by: f32| match segs {
|
||||
[PathSeg::Move(..), PathSeg::Line(..)] => by / (start + end).max(f32::EPSILON),
|
||||
_ => 0.5,
|
||||
};
|
||||
let (start_share, end_share) = (share(start), share(end));
|
||||
let pull = |(x, y): (f32, f32), toward: Option<(f32, f32)>, by: f32, share: f32, (dx, dy): (f32, f32)| {
|
||||
let room = toward.map_or(0.0, |(tx, ty)| (tx - x).hypot(ty - y) * share);
|
||||
let by = if room.is_finite() { by.min(room) } else { 0.0 };
|
||||
(x - dx * by, y - dy * by)
|
||||
};
|
||||
// The points next to each end, before either moves.
|
||||
let after_first = match segs.get(1) {
|
||||
Some(PathSeg::Line(x, y) | PathSeg::Cubic(x, y, ..)) => Some((*x, *y)),
|
||||
_ => None,
|
||||
};
|
||||
let before_last = match segs.len().checked_sub(1).map(|i| segs.split_at(i)) {
|
||||
Some((_, [PathSeg::Cubic(_, _, x, y, ..)])) => Some((*x, *y)),
|
||||
Some((head, [PathSeg::Line(..)])) => match head.last() {
|
||||
Some(PathSeg::Move(x, y) | PathSeg::Line(x, y) | PathSeg::Cubic(.., x, y)) => Some((*x, *y)),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
};
|
||||
if let Some(PathSeg::Move(x, y)) = segs.first_mut() {
|
||||
(*x, *y) = pull((*x, *y), after_first, start, start_share, start_dir);
|
||||
}
|
||||
if let Some(PathSeg::Line(x, y) | PathSeg::Cubic(.., x, y)) = segs.last_mut() {
|
||||
(*x, *y) = pull((*x, *y), before_last, end, end_share, end_dir);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn seg_path(segs: &[PathSeg]) -> BezPath {
|
||||
let mut p = BezPath::new();
|
||||
for s in segs {
|
||||
|
||||
@@ -712,10 +712,9 @@ impl<'a> Flow<'a> {
|
||||
},
|
||||
);
|
||||
self.late.drew();
|
||||
let raised = items.len()..items.len() + front.len();
|
||||
items.extend(front);
|
||||
items.extend(line_numbers(ctx, pb, &self.pl, (l0, l1), y));
|
||||
add_items(pb, behind, items, raised);
|
||||
add_items(pb, behind, items);
|
||||
if let (Some(f), Some(l)) = (self.pl.lines.get(l0), self.pl.lines.get(l1 - 1)) {
|
||||
pb.y = y + (l.top + l.height - f.top);
|
||||
pb.content_bottom = pb.content_bottom.max(pb.y);
|
||||
@@ -958,17 +957,10 @@ fn line_numbers(ctx: &mut Ctx, pb: &mut PageBuilder, pl: &ParaLayout, (l0, l1):
|
||||
items
|
||||
}
|
||||
|
||||
/// Add a piece's items to the last page: those `behind` the text at the front, the rest at the end,
|
||||
/// the `raised` ones among them (its floating objects) to be drawn over the page's text.
|
||||
fn add_items(pb: &mut PageBuilder, behind: Vec<Placed>, items: Vec<Placed>, raised: std::ops::Range<usize>) {
|
||||
/// Add a piece's items to the last page: those `behind` the text at the front, the rest at the end.
|
||||
fn add_items(pb: &mut PageBuilder, behind: Vec<Placed>, items: Vec<Placed>) {
|
||||
let n_behind = behind.len();
|
||||
if let Some(pg) = pb.pages.last_mut() {
|
||||
let at = pg.items.len().saturating_sub(pb.behind.last().copied().unwrap_or(0));
|
||||
if !raised.is_empty()
|
||||
&& let Some(f) = pb.front.last_mut()
|
||||
{
|
||||
f.push(at.saturating_add(raised.start)..at.saturating_add(raised.end));
|
||||
}
|
||||
for (i, it) in behind.into_iter().enumerate() {
|
||||
pg.items.insert(i.min(pg.items.len()), it);
|
||||
}
|
||||
@@ -1174,7 +1166,7 @@ fn next_first_line(ctx: &mut Ctx, block: usize, width: f32, depth: usize, new_pa
|
||||
// Keep list indents and label metrics without consuming the document counters.
|
||||
let rp = ctx.doc.styles.resolve_para(&p.props);
|
||||
let label =
|
||||
p.props.numbering.or(rp.numbering).filter(|n| n.num != 0).and_then(|n| counters.next_label_indexed(&ctx.numbering, n.num, n.level));
|
||||
p.props.numbering.or(rp.numbering).filter(|n| n.num != 0).and_then(|n| counters.next_label(&ctx.doc.numbering, n.num, n.level));
|
||||
let pl = match ctx.para_ahead(p, width, label.clone()) {
|
||||
Some(pl) => pl,
|
||||
None => {
|
||||
|
||||
@@ -988,19 +988,15 @@ impl DocLayout {
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// Spaces hanging past the right margin are highlighted only up to where the
|
||||
// caret stops (#6434).
|
||||
let limit = para.caret_limit(li);
|
||||
let clamp = |x: f32| limit.map_or(x, |m| x.min(m));
|
||||
let x0 = clamp(para.x_of(li, from).unwrap_or(l.left));
|
||||
let mut x1 = clamp(para.x_of(li, to).unwrap_or(x0));
|
||||
let x0 = para.x_of(li, from).unwrap_or(l.left);
|
||||
let mut x1 = para.x_of(li, to).unwrap_or(x0);
|
||||
// Selection continuing past the paragraph end shows the paragraph mark.
|
||||
let last_line = li + 1 == para.lines.len();
|
||||
if last_line && path != b.path {
|
||||
x1 += PARA_MARK_WIDTH;
|
||||
}
|
||||
if path == b.path && to >= l.stop && li + 1 < para.lines.len() && b.off > l.stop {
|
||||
x1 = clamp(para.x_of(li, l.stop).unwrap_or(x1));
|
||||
x1 = para.x_of(li, l.stop).unwrap_or(x1);
|
||||
}
|
||||
if x1 <= x0 && !(last_line && path != b.path) {
|
||||
continue;
|
||||
|
||||
@@ -303,12 +303,7 @@ pub struct Page {
|
||||
pub section: usize,
|
||||
/// Page number as displayed (after section restarts).
|
||||
pub number: u32,
|
||||
/// The body's items in drawing order: floating objects in front of the text after all of it.
|
||||
pub items: Vec<Placed>,
|
||||
/// Where each of `items` comes in reading order (its anchor's), when that isn't its place in
|
||||
/// `items`: floating objects in front of the text are drawn after it (#5534) but read after
|
||||
/// their anchor. Empty when the two orders are the same; items past its end are read in place.
|
||||
pub reading: Vec<usize>,
|
||||
/// Header / footer items (drawn dimmed while editing the body).
|
||||
pub header: Vec<Placed>,
|
||||
pub footer: Vec<Placed>,
|
||||
|
||||
@@ -65,10 +65,6 @@ pub(crate) struct PageBuilder<'a> {
|
||||
/// Per page: how many items were inserted at the front of its list (behind the text), so a
|
||||
/// [`Snap`] can take them out again.
|
||||
pub(crate) behind: Vec<usize>,
|
||||
/// Per page: the items of its floating objects that are not behind the text (indices counted
|
||||
/// after the items behind it), drawn over all of its text once it is laid out
|
||||
/// ([`PageBuilder::raise_front`]).
|
||||
pub(crate) front: Vec<Vec<std::ops::Range<usize>>>,
|
||||
/// The bottom of the tallest column on the current page before the current one.
|
||||
pub(crate) max_y: f32,
|
||||
/// The bottom of the lowest line or table row placed on the current page (without the space
|
||||
@@ -307,32 +303,12 @@ impl PageBuilder<'_> {
|
||||
}
|
||||
self.pages.pop();
|
||||
self.behind.pop();
|
||||
self.front.pop();
|
||||
self.number = self.number.saturating_sub(1);
|
||||
self.after_break_mark = false;
|
||||
// The page before was aligned when it was left: nothing on it moves again.
|
||||
self.page_items_start = self.pages.last().map_or(0, |p| p.items.len());
|
||||
true
|
||||
}
|
||||
/// Draw each page's floating objects that are not behind the text over all of its text, in
|
||||
/// their own order: Word draws them on top, and the shading, borders and lines of the
|
||||
/// paragraphs and tables after their anchor would otherwise cover them (#5534). Once all
|
||||
/// pages are laid out, so going back to a [`Snap`] still finds the items where they went.
|
||||
/// Their place in reading order stays in [`Page::reading`].
|
||||
pub(crate) fn raise_front(&mut self) {
|
||||
for ((pg, ranges), behind) in self.pages.iter_mut().zip(&mut self.front).zip(&self.behind) {
|
||||
if ranges.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let mut raised = vec![false; pg.items.len()];
|
||||
for r in ranges.drain(..) {
|
||||
let (start, end) = (r.start.saturating_add(*behind), r.end.saturating_add(*behind));
|
||||
raised.get_mut(start..end.min(pg.items.len())).into_iter().flatten().for_each(|f| *f = true);
|
||||
}
|
||||
let (top, under): (Vec<_>, Vec<_>) = std::mem::take(&mut pg.items).into_iter().zip(raised).enumerate().partition(|(_, (_, up))| *up);
|
||||
(pg.reading, pg.items) = under.into_iter().chain(top).map(|(at, (it, _))| (at, it)).unzip();
|
||||
}
|
||||
}
|
||||
/// Finish the current page: the lines between its columns, its vertical alignment and its
|
||||
/// footnotes, placed with the section state in effect (margins, gutter, separators).
|
||||
/// `new_page` starts with this; after it has run, `new_page` finds nothing left to finish.
|
||||
@@ -369,7 +345,6 @@ impl PageBuilder<'_> {
|
||||
self.page_valign = s.valign;
|
||||
self.pages.push(Page { w, h, section: self.sect_idx, number: self.number, body, first_block, items: decor, ..Default::default() });
|
||||
self.behind.push(0);
|
||||
self.front.push(Vec::new());
|
||||
self.col = 0;
|
||||
self.cols = s.column_boxes();
|
||||
self.top = body_top;
|
||||
|
||||
@@ -214,15 +214,13 @@ impl ParaLayout {
|
||||
}
|
||||
/// The farthest right a caret goes on left-to-right line `li`: spaces at the end of a line
|
||||
/// hang past its right edge, but the caret after them stays at the edge, as in Word (#2146);
|
||||
/// text that overflows the line still carries it. Markers and breaks after the spaces hang
|
||||
/// with them, as where the line's content ends (#6434). `None` on bidirectional lines.
|
||||
/// text that overflows the line still carries it. `None` on bidirectional lines.
|
||||
pub fn caret_limit(&self, li: usize) -> Option<f32> {
|
||||
let l = self.lines.get(li)?;
|
||||
if !l.vis.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let hangs = |c: &Cluster| matches!(c.kind, ClKind::Space | ClKind::Marker | ClKind::LineBreak | ClKind::PageBreak | ClKind::ColumnBreak);
|
||||
let ink = (l.c0..l.c1).rev().find(|&k| self.clusters.get(k).is_some_and(|c| !hangs(c)));
|
||||
let ink = (l.c0..l.c1).rev().find(|&k| self.clusters.get(k).is_some_and(|c| c.kind != ClKind::Space));
|
||||
let end = match ink {
|
||||
Some(k) => l.xs.get(k + 1 - l.c0).copied(),
|
||||
None => l.xs.first().copied(),
|
||||
@@ -490,60 +488,4 @@ mod tests {
|
||||
}
|
||||
assert_eq!(lookup_family(&d, "No Such Roman Font"), MISSING_ROMAN_FONT);
|
||||
}
|
||||
|
||||
/// #5847: shrink_line_spaces is a no-op when there are no spaces after the line's last tab,
|
||||
/// guarding against division by zero, negative room, or shifting pre-tab clusters.
|
||||
#[test]
|
||||
fn shrink_line_spaces_with_no_spaces_after_last_tab_is_noop() {
|
||||
crate::test_fonts();
|
||||
let chr = CharProps { font: Some("Source Sans 3".into()), size: Some(12.0), ..Default::default() };
|
||||
let mut d = Document::new();
|
||||
d.settings.compat_mode = 15;
|
||||
let fields = FieldCtx::default();
|
||||
let env = ParaEnv {
|
||||
doc: &d,
|
||||
fields: &fields,
|
||||
width: 468.0,
|
||||
label: None,
|
||||
show_hidden: false,
|
||||
hide_deleted: Default::default(),
|
||||
table: None,
|
||||
proofing: None,
|
||||
typing_word: None,
|
||||
field_codes: false,
|
||||
grid: Grid::default(),
|
||||
exclusions: &[],
|
||||
eq_number: 0,
|
||||
numeral: Default::default(),
|
||||
read_line_spacing: None,
|
||||
fit_objects: false,
|
||||
fitted: &[],
|
||||
joined: false,
|
||||
};
|
||||
let mut p = Paragraph::with_text("n n n n\tWordWithoutSpaces", chr);
|
||||
p.props = ParaProps {
|
||||
align: Some(Align::Justify),
|
||||
tabs: Some(vec![TabStop { pos: 150.0, align: TabAlign::Left, leader: Default::default() }]),
|
||||
..Default::default()
|
||||
};
|
||||
let mut pl = layout_para(&p, &env);
|
||||
let mark_style = pl.clusters[0].style;
|
||||
break_lines(&mut pl, &env, mark_style, None);
|
||||
let c0 = pl.lines[0].c0;
|
||||
let c1 = pl.lines[0].c1;
|
||||
let last_tab = (c0..c1).rev().find(|k| pl.clusters.get(*k).is_some_and(|c| c.kind == ClKind::Tab)).unwrap();
|
||||
let from = last_tab + 1;
|
||||
|
||||
let spaces_after = (from..c1).filter(|k| pl.clusters.get(*k).is_some_and(|c| c.kind == ClKind::Space)).count();
|
||||
assert_eq!(spaces_after, 0);
|
||||
|
||||
let orig_xs = pl.lines[0].xs.clone();
|
||||
let content_end = *orig_xs.last().unwrap();
|
||||
|
||||
for slack in [-20.0, 0.0, f32::NEG_INFINITY] {
|
||||
let mut xs = orig_xs.clone();
|
||||
justify::shrink_line_spaces(&pl, &mut xs, (c0, from), c1, content_end, slack);
|
||||
assert_eq!(xs, orig_xs, "slack {slack} with 0 post-tab spaces must not shift any cluster");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,29 +22,23 @@ pub(super) fn space_room(spaces: f32, word: f32) -> f32 {
|
||||
(spaces * MAX_SPACE_SHRINK).min(word.max(0.0) * MAX_WORD_OVERRUN)
|
||||
}
|
||||
|
||||
/// Take `-slack` (an overflow) out of the line's inner spaces from `from` on (after the line's last
|
||||
/// left/default tab), in proportion to their widths and never more than [`MAX_SPACE_SHRINK`] of them.
|
||||
/// Trailing spaces hang and are left alone.
|
||||
///
|
||||
/// `c0` is the first cluster on the line, and `from` is where space shrinking begins (the cluster
|
||||
/// following the line's last tab, or `c0` when there are no tabs on the line). `c1` is the end of
|
||||
/// the line's cluster range.
|
||||
pub(super) fn shrink_line_spaces(pl: &ParaLayout, xs: &mut [f32], (c0, from): (usize, usize), c1: usize, content_end: f32, slack: f32) {
|
||||
let from = from.max(c0);
|
||||
let spaces: Vec<(usize, f32)> = (from..c1)
|
||||
/// Take `-slack` (an overflow) out of the line's inner spaces, in proportion to their widths and
|
||||
/// never more than [`MAX_SPACE_SHRINK`] of them. Trailing spaces hang and are left alone.
|
||||
pub(super) fn shrink_line_spaces(pl: &ParaLayout, xs: &mut [f32], c0: usize, c1: usize, content_end: f32, slack: f32) {
|
||||
let spaces: Vec<(usize, f32)> = (c0..c1)
|
||||
.filter_map(|k| {
|
||||
let c = pl.clusters.get(k).filter(|c| c.kind == ClKind::Space)?;
|
||||
(xs.get(k - c0).copied().unwrap_or(f32::MAX) < content_end - 0.01).then_some((k, c.adv))
|
||||
})
|
||||
.collect();
|
||||
let total: f32 = spaces.iter().map(|s| s.1).sum();
|
||||
if !total.is_finite() || total <= 0.0 || !slack.is_finite() {
|
||||
if total <= 0.0 || !slack.is_finite() {
|
||||
return;
|
||||
}
|
||||
let ratio = (-slack / total).clamp(0.0, MAX_SPACE_SHRINK);
|
||||
let mut take = 0.0;
|
||||
let mut next = spaces.iter().peekable();
|
||||
for k in from..c1 {
|
||||
for k in c0..c1 {
|
||||
if let Some(v) = xs.get_mut(k - c0) {
|
||||
*v -= take;
|
||||
}
|
||||
|
||||
@@ -25,7 +25,7 @@ struct Breaker<'e> {
|
||||
/// Where default tab stops are counted from (see [`next_tab`]).
|
||||
tab_origin: f32,
|
||||
/// Word 2013+ (compatibility mode 15) fits more text on a justified line by shrinking its
|
||||
/// spaces (`space_room`); on a line with tabs, only the spaces after a final left/default tab.
|
||||
/// spaces (`space_room`); never on lines with tabs.
|
||||
shrink_spaces: bool,
|
||||
/// Word 2003's indent rules (`w:doNotSuppressIndentation`) before Word 2013's layout, for an
|
||||
/// unnumbered paragraph: a row starts right after a floating object before the indent.
|
||||
@@ -100,13 +100,9 @@ struct Scan {
|
||||
pending_tab: Option<(usize, TabStop, f32)>,
|
||||
/// The text after a pending decimal tab looked at so far for its '.'.
|
||||
decimal: Option<DecimalScan>,
|
||||
/// The width of the spaces so far on this line, after its last tab.
|
||||
/// The width of the spaces so far on this line.
|
||||
space_w: f32,
|
||||
/// Whether spaces after the last tab so far may shrink (true initially and after left/default
|
||||
/// tabs; false after right, center, or decimal tabs whose anchors use unshrunk widths).
|
||||
shrink_tab: bool,
|
||||
/// Tab cluster indices on this line whose alignment is not `TabAlign::Left`.
|
||||
non_left_tabs: Vec<usize>,
|
||||
has_tab: bool,
|
||||
/// The first word doesn't fit a span narrowed by a floating object: it moves on whole.
|
||||
skip: bool,
|
||||
}
|
||||
@@ -310,8 +306,7 @@ impl<'e> Breaker<'e> {
|
||||
pending_tab: None,
|
||||
decimal: None,
|
||||
space_w: 0.0,
|
||||
shrink_tab: true,
|
||||
non_left_tabs: Vec::new(),
|
||||
has_tab: false,
|
||||
skip: false,
|
||||
}
|
||||
}
|
||||
@@ -608,12 +603,10 @@ impl<'e> Breaker<'e> {
|
||||
// A line ending in a manual line break is stretched too, unless `doNotExpandShiftReturn` says not to.
|
||||
let stretch_end = sc.end == LineEnd::Wrap || (sc.end == LineEnd::LineBreak && self.expand_break);
|
||||
let justify = display.is_none() && ((align == Align::Justify && stretch_end) || align == Align::Distribute);
|
||||
// A line that only fits with shrunk spaces is shrunk, the last line of the paragraph too,
|
||||
// unless its last tab is a non-left tab whose anchor was resolved with unshrunk widths.
|
||||
let can_shrink_tab = last_tab.is_none_or(|k| !sc.non_left_tabs.contains(&k));
|
||||
let shrink = display.is_none() && self.shrink_spaces && slack < 0.0 && can_shrink_tab;
|
||||
// A line that only fits with shrunk spaces is shrunk, the last line of the paragraph too.
|
||||
let shrink = display.is_none() && self.shrink_spaces && slack < 0.0 && last_tab.is_none();
|
||||
if shrink {
|
||||
shrink_line_spaces(pl, &mut sc.xs, (c0, align_from), c1, content_end, slack);
|
||||
shrink_line_spaces(pl, &mut sc.xs, c0, c1, content_end, slack);
|
||||
} else if justify && slack > 0.0 {
|
||||
justify_line(pl, &mut sc.xs, (c0, c1, align_from), (content_end, slack), align == Align::Distribute);
|
||||
}
|
||||
@@ -841,8 +834,7 @@ impl Scan {
|
||||
/// A tab: its stop, and the room to it. True when the line ends before it.
|
||||
fn tab(&mut self, bk: &mut Breaker, pl: &mut ParaLayout) -> bool {
|
||||
let j = self.j;
|
||||
// Only the spaces after a line's last tab shrink (measured in Word for Mac).
|
||||
self.space_w = 0.0;
|
||||
self.has_tab = true;
|
||||
resolve_tab(pl, &mut self.pending_tab, &mut self.xs, self.c0, self.x, &mut self.x);
|
||||
let rp = &bk.rp;
|
||||
let ptab = pl.ptabs.iter().find(|t| t.0 == j).map(|&(_, a, b, l)| ptab_stop(a, b, l, bk.width, (rp.indent_left, rp.indent_right)));
|
||||
@@ -885,10 +877,6 @@ impl Scan {
|
||||
/// decimal tab).
|
||||
fn place_tab(&mut self, pl: &mut ParaLayout, stop: TabStop) {
|
||||
let j = self.j;
|
||||
self.shrink_tab = stop.align == TabAlign::Left;
|
||||
if !self.shrink_tab {
|
||||
self.non_left_tabs.push(j);
|
||||
}
|
||||
match stop.align {
|
||||
TabAlign::Left | TabAlign::Bar | TabAlign::Clear => {
|
||||
let w = (stop.pos - self.x).max(0.0);
|
||||
@@ -929,7 +917,7 @@ impl Scan {
|
||||
// each segment's font, glyphs and position for painting.
|
||||
let advance = pl.atomic_advance(j);
|
||||
let absorbs = self.absorbs(pl, advance);
|
||||
let shrink = if bk.shrink_spaces && self.shrink_tab {
|
||||
let shrink = if bk.shrink_spaces && !self.has_tab {
|
||||
space_room(self.space_w, self.x + advance - pl.auto_space_after(j) - self.word_from)
|
||||
} else {
|
||||
0.0
|
||||
@@ -1069,7 +1057,6 @@ impl Scan {
|
||||
self.last_break = Some(tj - 1);
|
||||
self.pending_tab = None;
|
||||
self.leaders.retain(|(k, _)| *k < tj);
|
||||
self.non_left_tabs.retain(|&k| k < tj);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -79,7 +79,6 @@ fn new_ctx<'a>(
|
||||
});
|
||||
Ctx {
|
||||
doc,
|
||||
numbering: wordcraft_doc::numbering::NumberingIndex::new(&doc.numbering),
|
||||
cache,
|
||||
opts,
|
||||
hide_deleted: opts.hides_deleted(StoryRef::Body),
|
||||
@@ -225,7 +224,6 @@ fn new_page_builder<'p>(
|
||||
seps: NoteSeps::default(),
|
||||
para_end: None,
|
||||
behind: Vec::new(),
|
||||
front: Vec::new(),
|
||||
max_y: 0.0,
|
||||
content_bottom: 0.0,
|
||||
balance: None,
|
||||
@@ -458,7 +456,6 @@ fn finish_pages(pb: PageBuilder, doc: &Document, sections: &[(usize, &SectionPro
|
||||
pb.flush_notes();
|
||||
}
|
||||
pb.carry.clear();
|
||||
pb.raise_front();
|
||||
let mut pages = pb.pages;
|
||||
if !web {
|
||||
for p in &mut pages {
|
||||
@@ -663,9 +660,9 @@ struct Snap<'a> {
|
||||
impl<'a> Snap<'a> {
|
||||
fn take(pb: &mut PageBuilder<'a>, ctx: &Ctx) -> Self {
|
||||
// The pages stay out of the copy: it would cost the whole document per block.
|
||||
let (pages, behind, front) = (std::mem::take(&mut pb.pages), std::mem::take(&mut pb.behind), std::mem::take(&mut pb.front));
|
||||
let (pages, behind) = (std::mem::take(&mut pb.pages), std::mem::take(&mut pb.behind));
|
||||
let copy = pb.clone();
|
||||
(pb.pages, pb.behind, pb.front) = (pages, behind, front);
|
||||
(pb.pages, pb.behind) = (pages, behind);
|
||||
Snap {
|
||||
pb: copy,
|
||||
pages: pb.pages.len(),
|
||||
@@ -682,15 +679,9 @@ impl<'a> Snap<'a> {
|
||||
/// Go back to this state: drop the pages added since and what was added to the last one
|
||||
/// (appended, or inserted at the front behind the text).
|
||||
fn restore(&self, pb: &mut PageBuilder<'a>, ctx: &mut Ctx) {
|
||||
let (mut pages, mut behind, mut front) = (std::mem::take(&mut pb.pages), std::mem::take(&mut pb.behind), std::mem::take(&mut pb.front));
|
||||
let (mut pages, mut behind) = (std::mem::take(&mut pb.pages), std::mem::take(&mut pb.behind));
|
||||
pages.truncate(self.pages);
|
||||
behind.truncate(self.pages);
|
||||
front.truncate(self.pages);
|
||||
// The objects in front of the text that were added to the last page since go with them.
|
||||
let kept = self.items.saturating_sub(self.behind);
|
||||
if let Some(f) = front.last_mut() {
|
||||
f.retain(|r| r.end <= kept);
|
||||
}
|
||||
if let Some(pg) = pages.last_mut() {
|
||||
let k = behind.last().copied().unwrap_or(0).saturating_sub(self.behind).min(pg.items.len());
|
||||
pg.items.drain(..k);
|
||||
@@ -700,7 +691,7 @@ impl<'a> Snap<'a> {
|
||||
*b = self.behind;
|
||||
}
|
||||
*pb = self.pb.clone();
|
||||
(pb.pages, pb.behind, pb.front) = (pages, behind, front);
|
||||
(pb.pages, pb.behind) = (pages, behind);
|
||||
ctx.counters = self.counters.clone();
|
||||
ctx.eq_count = self.eq_count;
|
||||
ctx.fields.page = self.page_field;
|
||||
|
||||
@@ -169,7 +169,6 @@ impl StyleIndex {
|
||||
styles.entry(st.name.to_lowercase()).or_insert_with(|| v.clone());
|
||||
styles.insert(st.id.to_lowercase(), v);
|
||||
}
|
||||
let numbering = wordcraft_doc::numbering::NumberingIndex::new(&doc.numbering);
|
||||
let mut counters = Counters::default();
|
||||
let mut ordinals: HashMap<String, u32> = HashMap::new();
|
||||
let mut entries = Vec::new();
|
||||
@@ -185,12 +184,12 @@ impl StyleIndex {
|
||||
let num = p.props.numbering.or_else(|| doc.styles.resolve_para(&p.props).numbering).filter(|n| n.num != 0);
|
||||
let (mut label, mut levels, mut level) = (None, Vec::new(), 0u8);
|
||||
if let Some(n) = num
|
||||
&& let Some((l, def)) = counters.next_label_indexed(&numbering, n.num, n.level)
|
||||
&& let Some((l, def)) = counters.next_label(&doc.numbering, n.num, n.level)
|
||||
&& def.format != NumFormat::Bullet
|
||||
{
|
||||
let vals = counters.values_indexed(&numbering, n.num).unwrap_or_default();
|
||||
let vals = counters.values(&doc.numbering, n.num).unwrap_or_default();
|
||||
for (k, v) in vals.iter().enumerate().take(usize::from(n.level.min(8)) + 1) {
|
||||
let Some(lv) = numbering.level(n.num, k as u8) else { continue };
|
||||
let Some(lv) = doc.numbering.level(n.num, k as u8) else { continue };
|
||||
if matches!(lv.format, NumFormat::None | NumFormat::Bullet) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ use wordcraft_geom::Rect;
|
||||
|
||||
use crate::boxes::BoxContext;
|
||||
use crate::para::{CellText, ClKind, ParaLayout};
|
||||
use crate::{BoxInput, BoxLayout, Ctx, Placed, ViewMode, layout_box};
|
||||
use crate::{BoxInput, BoxLayout, Ctx, Placed, layout_box};
|
||||
|
||||
/// Largest preferred table width, as a share of the text column, that a file can ask for.
|
||||
const MAX_WIDTH_SHARE: f32 = 10.0;
|
||||
@@ -431,12 +431,6 @@ fn table_frame(ctx: &mut Ctx, t: &Table, avail: f32, depth: usize, style: Option
|
||||
grid.iter_mut().for_each(|w| *w *= k);
|
||||
total = avail;
|
||||
}
|
||||
// The reading view reflows to its column, so even a table with its own width fits it (#7988).
|
||||
if ctx.opts.view == ViewMode::Read && total > avail && avail > 0.0 {
|
||||
let k = avail / total;
|
||||
grid.iter_mut().for_each(|w| *w *= k);
|
||||
total = avail;
|
||||
}
|
||||
if !t.props.fixed {
|
||||
// Measuring lays paragraphs out once more; it mustn't count their equations twice.
|
||||
let eq_count = ctx.eq_count;
|
||||
@@ -483,14 +477,6 @@ fn table_frame(ctx: &mut Ctx, t: &Table, avail: f32, depth: usize, style: Option
|
||||
} else {
|
||||
indent - first_cell_left_margin_in(t, margins_def)
|
||||
};
|
||||
// The reading view fits the table into what the start offset leaves of the column, mirrored or not (#7988).
|
||||
let room = (avail - start_offset.max(0.0)).max(1.0);
|
||||
if ctx.opts.view == ViewMode::Read && acc > room && !matches!(t.props.align, Some(Align::Center | Align::Right)) {
|
||||
let k = room / acc;
|
||||
colx.iter_mut().for_each(|c| *c *= k);
|
||||
acc = room;
|
||||
total = room;
|
||||
}
|
||||
let x = match (t.props.align, rtl) {
|
||||
(Some(Align::Center), _) => (avail - total) / 2.0,
|
||||
// End alignment: the right margin, or the left one in a right-to-left table.
|
||||
@@ -499,13 +485,6 @@ fn table_frame(ctx: &mut Ctx, t: &Table, avail: f32, depth: usize, style: Option
|
||||
(_, true) => avail - total - start_offset,
|
||||
(_, false) => start_offset,
|
||||
};
|
||||
// The reading view has no margin to hang a negative indent into: keep the table inside the column (#8020).
|
||||
// The clamp also pulls in an over-large positive indent. A table wider than the column keeps its start edge.
|
||||
let x = if ctx.opts.view == crate::ViewMode::Read {
|
||||
if total > avail { if rtl { avail - total } else { 0.0 } } else { x.clamp(0.0, avail - total) }
|
||||
} else {
|
||||
x
|
||||
};
|
||||
TableFrame { ncols, colx, acc, total, margins_def, tborders, rtl, x }
|
||||
}
|
||||
|
||||
@@ -1527,7 +1506,7 @@ fn blocks_content(ctx: &mut Ctx, blocks: &Blocks, text: Option<&CellText>, depth
|
||||
/// The list level `p` is in, for its indents (without counting it: measuring isn't laying out).
|
||||
fn list_level(ctx: &Ctx, p: &Paragraph) -> Option<wordcraft_doc::numbering::Level> {
|
||||
let n = p.props.numbering.or_else(|| ctx.doc.styles.resolve_para(&p.props).numbering).filter(|n| n.num != 0)?;
|
||||
ctx.numbering.level(n.num, n.level).cloned()
|
||||
ctx.doc.numbering.level(n.num, n.level).cloned()
|
||||
}
|
||||
|
||||
/// A width to lay a paragraph out in so that only its own line breaks end lines.
|
||||
|
||||
+1
-741
@@ -660,31 +660,6 @@ fn reading_layout_reflows_into_viewport_height_pages_without_changing_print_layo
|
||||
assert!(invalid.pages.iter().all(|p| p.w.is_finite() && p.h.is_finite()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reading_layout_fits_a_wide_table_to_the_column() {
|
||||
crate::test_fonts();
|
||||
// #7988: a 468 pt table is wider than a reading column but must not run past its edge, however it is indented or mirrored.
|
||||
let cases = [(0.0, false, None), (36.0, false, None), (36.0, true, None)];
|
||||
let aligned = [None, Some(Align::Left), Some(Align::Center), Some(Align::Right)].map(|a| (36.0, false, a));
|
||||
let aligned_rtl = [Some(Align::Left), Some(Align::Right)].map(|a| (36.0, true, a));
|
||||
for (indent, rtl, align) in cases.into_iter().chain(aligned).chain(aligned_rtl) {
|
||||
let mut d = Document::from_text("Before.");
|
||||
let mut t = Table::new(2, 4, 468.0);
|
||||
t.props.indent = Some(indent);
|
||||
t.props.bidi_visual = rtl;
|
||||
t.props.align = align;
|
||||
d.insert_block(StoryRef::Body, &Path::top(1), wordcraft_doc::Block::Table(t)).unwrap();
|
||||
let opts = LayoutOptions { view: ViewMode::Read, web_width: 360.0, read_height: 600.0, ..Default::default() };
|
||||
let l = layout(&d, &mut LayoutCache::new(), &opts);
|
||||
let p = &l.pages[0];
|
||||
let cells: Vec<_> = p.items.iter().filter_map(|i| if let Placed::Cell { rect, .. } = i { Some(*rect) } else { None }).collect();
|
||||
let (left, right) = cells.iter().fold((f32::MAX, 0.0f32), |(l, r), c| (l.min(c.x), r.max(c.x + c.w)));
|
||||
assert!(right > left, "cells placed");
|
||||
assert!(right <= p.body.x + p.body.w + 0.5, "indent {indent} rtl {rtl} {align:?}: right {right} vs column {}", p.body.x + p.body.w);
|
||||
assert!(left >= p.body.x - 0.5, "indent {indent} rtl {rtl} {align:?}: left {left} vs column {}", p.body.x);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hit_and_caret_agree() {
|
||||
crate::test_fonts();
|
||||
@@ -3762,70 +3737,6 @@ fn caret_after_hanging_spaces_stays_at_the_margin() {
|
||||
}
|
||||
}
|
||||
|
||||
/// "a" and 200 spaces hanging past the right margin: at the paragraph's end, before a letter that
|
||||
/// wraps, before a bookmark (a zero-width marker) and before a line break.
|
||||
fn hanging_space_paragraphs() -> Vec<(&'static str, wordcraft_doc::Paragraph)> {
|
||||
let spaces = format!("a{}", " ".repeat(200));
|
||||
let mut marked = wordcraft_doc::Paragraph::with_text(&spaces, Default::default());
|
||||
marked.insert_object(spaces.len(), InlineObject::BookmarkStart { name: "end".into() }, &Default::default()).unwrap();
|
||||
let text = |t: &str| wordcraft_doc::Paragraph::with_text(t, Default::default());
|
||||
vec![
|
||||
("at the end", text(&spaces)),
|
||||
("before a wrap", text(&format!("{spaces}b"))),
|
||||
("before a bookmark", marked),
|
||||
("before a line break", text(&format!("{spaces}{}b", wordcraft_doc::para::LINE_BREAK))),
|
||||
]
|
||||
}
|
||||
|
||||
/// The selection highlight over spaces hanging past the right margin stops at the margin with the
|
||||
/// caret (#6434), whatever follows the spaces. Selected through the paragraph's end, its mark
|
||||
/// shows just past the margin.
|
||||
#[test]
|
||||
fn selection_over_hanging_spaces_stops_at_the_margin() {
|
||||
crate::test_fonts();
|
||||
for (case, p) in hanging_space_paragraphs() {
|
||||
let len = p.text.len();
|
||||
let mut d = Document::new();
|
||||
d.body = vec![wordcraft_doc::para_block(p), wordcraft_doc::para_block(wordcraft_doc::Paragraph::new())];
|
||||
let right = d.last_section.page_w - d.last_section.margin_right;
|
||||
let l = lay(&d);
|
||||
let c = l.caret(&Pos::body(0, 201)).unwrap();
|
||||
assert!(c.x <= right + 0.5, "{case}: caret after the spaces at {} past the margin at {right}", c.x);
|
||||
for (end, mark) in [(Pos::body(0, len), 0.0), (Pos::body(1, 0), crate::para::PARA_MARK_WIDTH)] {
|
||||
let rects = l.selection_rects(&d, &Pos::body(0, 0), &end, 0);
|
||||
assert!(rects.iter().any(|(_, r)| r.right() >= right - 0.5), "{case} to {end:?}: the highlight reaches the margin: {rects:?}");
|
||||
for (_, r) in &rects {
|
||||
assert!(r.right() <= right + mark + 0.5, "{case} to {end:?}: highlight {r:?} past the margin at {right}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The grammar underline over a run of spaces hanging past the right margin ("Extra space") stops
|
||||
/// at the margin with the caret (#6434), whatever follows the spaces.
|
||||
#[test]
|
||||
fn proofing_marks_over_hanging_spaces_stop_at_the_margin() {
|
||||
crate::test_fonts();
|
||||
for (case, p) in hanging_space_paragraphs() {
|
||||
let mut d = Document::new();
|
||||
d.body = vec![wordcraft_doc::para_block(p)];
|
||||
let right = d.last_section.page_w - d.last_section.margin_right;
|
||||
let l = layout(&d, &mut LayoutCache::new(), &LayoutOptions { proofing: true, ..Default::default() });
|
||||
let issues = l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para.issues.clone()) } else { None });
|
||||
assert!(issues.as_ref().is_some_and(|v| v.contains(&(1, 201, true))), "{case}: the spaces are a grammar issue: {issues:?}");
|
||||
let items = display::page_display(&d, &l.pages[0], &display::DisplayOptions::default());
|
||||
let underlines: Vec<(f32, f32)> = items
|
||||
.iter()
|
||||
.filter_map(|i| match i {
|
||||
display::Draw::Line { x0, x1, stroke: display::Stroke::Double, .. } => Some((*x0, *x1)),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert!(underlines.iter().any(|&(_, x1)| x1 >= right - 0.5), "{case}: the underline reaches the margin: {underlines:?}");
|
||||
assert!(underlines.iter().all(|&(_, x1)| x1 <= right + 0.5), "{case}: {underlines:?} past the margin at {right}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tall_first_page_header_pushes_body_down() {
|
||||
crate::test_fonts();
|
||||
@@ -4827,147 +4738,7 @@ fn a_lines_arrowheads_sit_at_its_ends() {
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let [(x0, y0), (x1, y1)] = tips[..] else { panic!("two arrowheads: {tips:?}") };
|
||||
assert!((x1 - x0 - 60.0).abs() < 0.01 && (y1 - y0 - 40.0).abs() < 0.01, "tips at the frame's corners: {tips:?}");
|
||||
// The line, drawn short of its arrowed ends (#6767), runs along the same diagonal.
|
||||
assert!(rect.x > x0 && rect.y > y0 && rect.right() < x1 && rect.bottom() < y1, "{rect:?} between {tips:?}");
|
||||
assert!(((rect.x - x0) / 60.0 - (rect.y - y0) / 40.0).abs() < 0.001, "{rect:?} on the diagonal from {tips:?}");
|
||||
assert!(((x1 - rect.right()) / 60.0 - (y1 - rect.bottom()) / 40.0).abs() < 0.001, "{rect:?} on the diagonal to {tips:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_thick_lines_stroke_ends_inside_its_arrowheads() {
|
||||
// #6767: the stroke stopped at each arrowhead's tip, so a thick line's body and cap stuck out
|
||||
// of the narrow head. Each arrowed end now stops where the head is as wide as the stroke (and
|
||||
// its cap's reach before that), for lines and every connector.
|
||||
use wordcraft_doc::connector::{LineCap, ShapeExtra};
|
||||
use wordcraft_doc::para::{Float, ShapeKind};
|
||||
use wordcraft_doc::props::Rgb;
|
||||
|
||||
let width = 6.0;
|
||||
let kinds = [ShapeKind::Line, ShapeKind::StraightConnector, ShapeKind::ElbowConnector, ShapeKind::CurvedConnector];
|
||||
for kind in kinds {
|
||||
for cap in [LineCap::Flat, LineCap::Square, LineCap::Round] {
|
||||
let shape = InlineObject::Shape {
|
||||
kind,
|
||||
w: 120.0,
|
||||
h: 60.0,
|
||||
fill: None,
|
||||
stroke: Some(Rgb::BLACK),
|
||||
stroke_width: width,
|
||||
float: Float::default(),
|
||||
story: None,
|
||||
freeform: None,
|
||||
effects: Default::default(),
|
||||
extra: ShapeExtra { arrow_start: true, arrow_end: true, cap, ..Default::default() },
|
||||
};
|
||||
let (ends, heads, draws) = line_ends_and_heads(shape);
|
||||
assert_eq!((ends.len(), heads.len()), (2, 2), "{kind:?} {cap:?}: {draws:?}");
|
||||
for (end, head) in ends.iter().zip(&heads) {
|
||||
for corner in stroke_end_corners(*end, *head, width, cap) {
|
||||
assert!(in_triangle(corner, *head), "{kind:?} {cap:?}: stroke corner {corner:?} outside the head {head:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_short_lines_lone_arrowhead_takes_the_room_its_other_end_does_not_need() {
|
||||
// #6767: an arrowed end moved at most half way along a straight line, even when the other end
|
||||
// had no arrowhead and stayed put, so a short thick line's stroke still stuck out of its head.
|
||||
use wordcraft_doc::connector::{LineCap, ShapeExtra};
|
||||
use wordcraft_doc::para::{Float, ShapeKind};
|
||||
use wordcraft_doc::props::Rgb;
|
||||
|
||||
let width = 6.0;
|
||||
// Each is shorter than twice its inset (6 pt flat, 9 pt with the cap's reach) but no shorter
|
||||
// than one inset, so the head can cover the stroke: 8 pt and 10 pt diagonals.
|
||||
for (cap, (w, h)) in [(LineCap::Flat, (6.4, 4.8)), (LineCap::Square, (8.0, 6.0)), (LineCap::Round, (8.0, 6.0))] {
|
||||
for kind in [ShapeKind::Line, ShapeKind::StraightConnector] {
|
||||
for at_start in [true, false] {
|
||||
let shape = InlineObject::Shape {
|
||||
kind,
|
||||
w,
|
||||
h,
|
||||
fill: None,
|
||||
stroke: Some(Rgb::BLACK),
|
||||
stroke_width: width,
|
||||
float: Float::default(),
|
||||
story: None,
|
||||
freeform: None,
|
||||
effects: Default::default(),
|
||||
extra: ShapeExtra { arrow_start: at_start, arrow_end: !at_start, cap, ..Default::default() },
|
||||
};
|
||||
let (ends, heads, draws) = line_ends_and_heads(shape);
|
||||
let (&[start, end], &[head]) = (&ends[..], &heads[..]) else { panic!("{kind:?} {cap:?}: {draws:?}") };
|
||||
let tip = head[0];
|
||||
let (near, far) = if at_start { (start, end) } else { (end, start) };
|
||||
// The end without an arrowhead stays where it was.
|
||||
let other = if at_start { (tip.0 + w, tip.1 + h) } else { (tip.0 - w, tip.1 - h) };
|
||||
assert!((far.0 - other.0).abs() < 0.01 && (far.1 - other.1).abs() < 0.01, "{kind:?} {cap:?}: {far:?} moved from {other:?}");
|
||||
for corner in stroke_end_corners(near, head, width, cap) {
|
||||
assert!(in_triangle(corner, head), "{kind:?} {cap:?} start={at_start}: stroke corner {corner:?} outside the head {head:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The ends of the stroked line or connector `shape` draws, from its start to its end, its
|
||||
/// arrowheads (each tip first), and all its draws.
|
||||
fn line_ends_and_heads(shape: InlineObject) -> (Vec<(f32, f32)>, Vec<[(f32, f32); 3]>, Vec<display::Draw>) {
|
||||
use wordcraft_doc::graphic::PathSeg;
|
||||
use wordcraft_doc::para::ShapeKind;
|
||||
|
||||
let mut doc = Document::from_text("Scan");
|
||||
doc.insert_object(&Pos::body(0, 0), shape, &Default::default()).unwrap();
|
||||
let draws = flat(display::page_display(&doc, &lay(&doc).pages[0], &Default::default()));
|
||||
let mut ends = Vec::new();
|
||||
let mut heads = Vec::new();
|
||||
for d in &draws {
|
||||
match d {
|
||||
display::Draw::Shape { rect, kind: ShapeKind::Line, .. } => ends.extend([(rect.x, rect.y), (rect.right(), rect.bottom())]),
|
||||
display::Draw::Path { fill: None, stroke: Some(_), segs, .. } => {
|
||||
let point = |s: &PathSeg| match *s {
|
||||
PathSeg::Move(x, y) | PathSeg::Line(x, y) | PathSeg::Cubic(.., x, y) => Some((x, y)),
|
||||
PathSeg::Close => None,
|
||||
};
|
||||
ends.extend(segs.first().and_then(point));
|
||||
ends.extend(segs.last().and_then(point));
|
||||
}
|
||||
display::Draw::Path { fill: Some(_), segs, .. } => {
|
||||
if let [PathSeg::Move(tx, ty), PathSeg::Line(ax, ay), PathSeg::Line(bx, by), PathSeg::Close] = segs[..] {
|
||||
heads.push([(tx, ty), (ax, ay), (bx, by)]);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
(ends, heads, draws)
|
||||
}
|
||||
|
||||
/// The corners of a `width` stroke's `end` under arrowhead `head`, its `cap` included (a round
|
||||
/// cap lies inside them).
|
||||
fn stroke_end_corners(end: (f32, f32), head: [(f32, f32); 3], width: f32, cap: wordcraft_doc::connector::LineCap) -> [(f32, f32); 2] {
|
||||
let [tip, a, b] = head;
|
||||
let base = ((a.0 + b.0) / 2.0, (a.1 + b.1) / 2.0);
|
||||
let len = (tip.0 - base.0).hypot(tip.1 - base.1);
|
||||
// The head's direction, and across it.
|
||||
let (dx, dy) = ((tip.0 - base.0) / len, (tip.1 - base.1) / len);
|
||||
let (nx, ny) = (-dy, dx);
|
||||
let reach = if cap == wordcraft_doc::connector::LineCap::Flat { 0.0 } else { width / 2.0 };
|
||||
[-1.0, 1.0].map(|side| (end.0 + dx * reach + nx * side * width / 2.0, end.1 + dy * reach + ny * side * width / 2.0))
|
||||
}
|
||||
|
||||
/// Whether `p` lies inside (or within 0.01 pt of) triangle `t`.
|
||||
fn in_triangle(p: (f32, f32), t: [(f32, f32); 3]) -> bool {
|
||||
let edge = |(ax, ay): (f32, f32), (bx, by): (f32, f32)| {
|
||||
let len = (bx - ax).hypot(by - ay);
|
||||
((bx - ax) * (p.1 - ay) - (by - ay) * (p.0 - ax)) / len
|
||||
};
|
||||
let sides = [edge(t[0], t[1]), edge(t[1], t[2]), edge(t[2], t[0])];
|
||||
sides.iter().all(|s| *s >= -0.01) || sides.iter().all(|s| *s <= 0.01)
|
||||
assert_eq!(tips, [(rect.x, rect.y), (rect.right(), rect.bottom())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -7614,425 +7385,6 @@ fn justified_spaces_shrink_a_quarter_at_most_and_by_the_word() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Measured in Word for Mac (compatibility mode 15, synthetic justified paragraphs that start
|
||||
/// with a label and a tab, or with words and then a left tab): a line with a tab shrinks its
|
||||
/// spaces too, but only those after its last tab. WordCraft never shrank a line with a tab, so a
|
||||
/// numbered paragraph's first line wrapped a word earlier than Word's (#4845, #5847).
|
||||
#[test]
|
||||
fn justified_line_with_a_tab_shrinks_only_the_spaces_after_it() {
|
||||
use wordcraft_doc::props::{TabAlign, TabStop};
|
||||
let chr = wordcraft_doc::CharProps { font: Some("Source Sans 3".into()), size: Some(12.0), ..Default::default() };
|
||||
let word = "nnnn";
|
||||
let (lead, n) = ("n n n n n n n n n n n n", 12);
|
||||
let tab_at = 200.0;
|
||||
let para = |text: &str, right: f32| {
|
||||
let mut d = Document::new();
|
||||
d.settings.compat_mode = 15;
|
||||
let mut p = wordcraft_doc::Paragraph::with_text(text, chr.clone());
|
||||
p.props = ParaProps {
|
||||
align: Some(Align::Justify),
|
||||
indent_right: Some(right),
|
||||
tabs: Some(vec![TabStop { pos: tab_at, align: TabAlign::Left, leader: Default::default() }]),
|
||||
..Default::default()
|
||||
};
|
||||
d.body = vec![wordcraft_doc::para_block(p)];
|
||||
d
|
||||
};
|
||||
// Words after the tab on the first line.
|
||||
let after_tab = |d: &Document| {
|
||||
let l = lay(d);
|
||||
let pl = l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
|
||||
let line = &pl.lines[0];
|
||||
let text = &d.para(StoryRef::Body, &Path::top(0)).unwrap().text[line.start..line.stop];
|
||||
text.split('\t').nth(1).unwrap_or("").split_whitespace().count()
|
||||
};
|
||||
let probe = para(&format!("{word} {word}"), 0.0);
|
||||
let l = lay(&probe);
|
||||
let pl = l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
|
||||
let w = pl.x_of(0, word.len()).unwrap() - pl.x_of(0, 0).unwrap();
|
||||
let sw = pl.x_of(0, word.len() + 1).unwrap() - pl.x_of(0, word.len()).unwrap();
|
||||
// Room from the n spaces after the tab alone; the eleven before it would allow more.
|
||||
let room = (0.25 * n as f32 * sw).min(0.355 * (w + sw));
|
||||
let all_room = (0.25 * (n + 11) as f32 * sw).min(0.355 * (w + sw));
|
||||
assert!(all_room > room + 0.5, "the test needs the spaces before the tab to matter: {room} vs {all_room}");
|
||||
let text = format!("{lead}\t{}", vec![word; 3 * n].join(" "));
|
||||
let full = probe.last_section.text_width();
|
||||
let width = |overrun: f32| tab_at + (n + 1) as f32 * w + n as f32 * sw - overrun;
|
||||
for (overrun, words) in [(room - 0.1, n + 1), (room + 0.1, n)] {
|
||||
let d = para(&text, full - width(overrun));
|
||||
assert_eq!(after_tab(&d), words, "overrun {overrun:.2} of {room:.2} allowed");
|
||||
}
|
||||
|
||||
// Verify rendered positions: spaces after the tab shrink in the allowed-overrun case,
|
||||
// while positions before the tab remain unchanged.
|
||||
let shrunk_doc = para(&text, full - width(room - 0.1));
|
||||
let unconstrained_doc = para(&text, 0.0);
|
||||
let l_shrunk = lay(&shrunk_doc);
|
||||
let l_unconstrained = lay(&unconstrained_doc);
|
||||
let pl_shrunk = l_shrunk.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
|
||||
let pl_unconstrained =
|
||||
l_unconstrained.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
|
||||
|
||||
// Characters in `lead` and the tab's start position must have identical positions.
|
||||
for k in 0..=lead.len() {
|
||||
assert_eq!(pl_shrunk.x_of(0, k), pl_unconstrained.x_of(0, k), "char {k} before tab must not move when spaces after tab shrink");
|
||||
}
|
||||
// Text after the tab starts at tab_at.
|
||||
assert!((pl_shrunk.x_of(0, lead.len() + 1).unwrap() - tab_at).abs() < 0.01, "tab position");
|
||||
// Text after the tab is shifted left compared to its natural (un-shrunk) positions:
|
||||
// for each word k after the tab on line 0, natural position is tab_at + k * (w + sw).
|
||||
let natural_x = |k: usize| tab_at + k as f32 * (w + sw);
|
||||
for k in 1..=n {
|
||||
let char_pos = lead.len() + 1 + k * (word.len() + 1);
|
||||
let x = pl_shrunk.x_of(0, char_pos).expect("word position on shrunk line");
|
||||
assert!(x < natural_x(k), "word {k} after tab at {x} must be shifted left from natural {}", natural_x(k));
|
||||
}
|
||||
}
|
||||
|
||||
/// #5847: a justified line with multiple tabs shrinks spaces only after its last tab.
|
||||
/// Spaces before the first tab and between tabs retain their natural width and positions,
|
||||
/// and only spaces after the last tab count toward space_room.
|
||||
#[test]
|
||||
fn justified_line_with_multiple_tabs_shrinks_only_spaces_after_last_tab() {
|
||||
use wordcraft_doc::props::{TabAlign, TabStop};
|
||||
let chr = wordcraft_doc::CharProps { font: Some("Source Sans 3".into()), size: Some(12.0), ..Default::default() };
|
||||
let word = "nnnn";
|
||||
let (lead1, lead2, n) = ("n n n n n n", "n n n n n n", 12);
|
||||
let tab1_at = 120.0;
|
||||
let tab2_at = 240.0;
|
||||
let para = |text: &str, right: f32| {
|
||||
let mut d = Document::new();
|
||||
d.settings.compat_mode = 15;
|
||||
let mut p = wordcraft_doc::Paragraph::with_text(text, chr.clone());
|
||||
p.props = ParaProps {
|
||||
align: Some(Align::Justify),
|
||||
indent_right: Some(right),
|
||||
tabs: Some(vec![
|
||||
TabStop { pos: tab1_at, align: TabAlign::Left, leader: Default::default() },
|
||||
TabStop { pos: tab2_at, align: TabAlign::Left, leader: Default::default() },
|
||||
]),
|
||||
..Default::default()
|
||||
};
|
||||
d.body = vec![wordcraft_doc::para_block(p)];
|
||||
d
|
||||
};
|
||||
// Words after the second tab on the first line.
|
||||
let after_second_tab = |d: &Document| {
|
||||
let l = lay(d);
|
||||
let pl = l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
|
||||
let line = &pl.lines[0];
|
||||
let text = &d.para(StoryRef::Body, &Path::top(0)).unwrap().text[line.start..line.stop];
|
||||
text.split('\t').nth(2).unwrap_or("").split_whitespace().count()
|
||||
};
|
||||
let probe = para(&format!("{word} {word}"), 0.0);
|
||||
let l = lay(&probe);
|
||||
let pl = l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
|
||||
let w = pl.x_of(0, word.len()).unwrap() - pl.x_of(0, 0).unwrap();
|
||||
let sw = pl.x_of(0, word.len() + 1).unwrap() - pl.x_of(0, word.len()).unwrap();
|
||||
// Room from the n spaces after the second tab alone; spaces before tab 1 or between tabs would allow more.
|
||||
let room = (0.25 * n as f32 * sw).min(0.355 * (w + sw));
|
||||
let all_room = (0.25 * (n + 10) as f32 * sw).min(0.355 * (w + sw));
|
||||
assert!(all_room > room + 0.5, "the test needs the spaces before the last tab to matter: {room} vs {all_room}");
|
||||
let text = format!("{lead1}\t{lead2}\t{}", vec![word; 3 * n].join(" "));
|
||||
let full = probe.last_section.text_width();
|
||||
let width = |overrun: f32| tab2_at + (n + 1) as f32 * w + n as f32 * sw - overrun;
|
||||
for (overrun, words) in [(room - 0.1, n + 1), (room + 0.1, n)] {
|
||||
let d = para(&text, full - width(overrun));
|
||||
assert_eq!(after_second_tab(&d), words, "overrun {overrun:.2} of {room:.2} allowed");
|
||||
}
|
||||
|
||||
// Verify rendered positions: spaces after the last tab shrink in the allowed-overrun case,
|
||||
// while positions before tab 1 and between tabs remain completely unchanged.
|
||||
let shrunk_doc = para(&text, full - width(room - 0.1));
|
||||
let unconstrained_doc = para(&text, 0.0);
|
||||
let l_shrunk = lay(&shrunk_doc);
|
||||
let l_unconstrained = lay(&unconstrained_doc);
|
||||
let pl_shrunk = l_shrunk.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
|
||||
let pl_unconstrained =
|
||||
l_unconstrained.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
|
||||
|
||||
// Characters in `lead1`, tab 1, and `lead2` up to the second tab must have identical positions.
|
||||
let pre_last_tab_len = lead1.len() + 1 + lead2.len();
|
||||
for k in 0..=pre_last_tab_len {
|
||||
assert_eq!(pl_shrunk.x_of(0, k), pl_unconstrained.x_of(0, k), "char {k} before last tab must not move when spaces after last tab shrink");
|
||||
}
|
||||
// Text after the second tab starts at tab2_at.
|
||||
assert!((pl_shrunk.x_of(0, pre_last_tab_len + 1).unwrap() - tab2_at).abs() < 0.01, "second tab position");
|
||||
// Text after the second tab is shifted left compared to its natural (un-shrunk) positions:
|
||||
let natural_x = |k: usize| tab2_at + k as f32 * (w + sw);
|
||||
for k in 1..=n {
|
||||
let char_pos = pre_last_tab_len + 1 + k * (word.len() + 1);
|
||||
let x = pl_shrunk.x_of(0, char_pos).expect("word position on shrunk line");
|
||||
assert!(x < natural_x(k), "word {k} after last tab at {x} must be shifted left from natural {}", natural_x(k));
|
||||
}
|
||||
}
|
||||
|
||||
/// #5847: a tabbed line with no spaces after its last tab has zero shrink room.
|
||||
/// Space shrinking is a no-op, guarding against division by zero, negative room,
|
||||
/// or shifting pre-tab clusters when there are no spaces to shrink after the tab.
|
||||
#[test]
|
||||
fn justified_line_with_tab_and_no_spaces_after_it_does_not_shrink() {
|
||||
use wordcraft_doc::props::{TabAlign, TabStop};
|
||||
let chr = wordcraft_doc::CharProps { font: Some("Source Sans 3".into()), size: Some(12.0), ..Default::default() };
|
||||
let lead = "n n n n n n n n";
|
||||
let word = "OverlongWordWithoutAnySpace";
|
||||
let tab_at = 200.0;
|
||||
let para = |text: &str, right: f32| {
|
||||
let mut d = Document::new();
|
||||
d.settings.compat_mode = 15;
|
||||
let mut p = wordcraft_doc::Paragraph::with_text(text, chr.clone());
|
||||
p.props = ParaProps {
|
||||
align: Some(Align::Justify),
|
||||
indent_right: Some(right),
|
||||
tabs: Some(vec![TabStop { pos: tab_at, align: TabAlign::Left, leader: Default::default() }]),
|
||||
..Default::default()
|
||||
};
|
||||
d.body = vec![wordcraft_doc::para_block(p)];
|
||||
d
|
||||
};
|
||||
|
||||
let probe = para(word, 0.0);
|
||||
let l = lay(&probe);
|
||||
let pl = l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
|
||||
let word_w = pl.x_of(0, word.len()).unwrap() - pl.x_of(0, 0).unwrap();
|
||||
|
||||
let text = format!("{lead}\t{word}");
|
||||
let full = probe.last_section.text_width();
|
||||
// Constrain the line so that `word` overruns the right edge by 2.0 pt.
|
||||
// Because there are no spaces after the tab, shrink room is 0 and the word
|
||||
// must wrap to line 1 rather than shrinking onto line 0.
|
||||
let tight_doc = para(&text, full - (tab_at + word_w - 2.0));
|
||||
let l_tight = lay(&tight_doc);
|
||||
let pl_tight = l_tight.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
|
||||
assert_eq!(pl_tight.lines.len(), 2, "word with no spaces after tab must wrap when it overruns the line");
|
||||
|
||||
// When the word fits within the line, characters before the tab and the word after the tab
|
||||
// remain at their exact natural positions (no pre-tab shift, no shrink).
|
||||
let fit_doc = para(&text, full - (tab_at + word_w + 50.0));
|
||||
let unconstrained_doc = para(&text, 0.0);
|
||||
let l_fit = lay(&fit_doc);
|
||||
let l_unconstrained = lay(&unconstrained_doc);
|
||||
let pl_fit = l_fit.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
|
||||
let pl_unconstrained =
|
||||
l_unconstrained.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
|
||||
|
||||
for k in 0..=text.len() {
|
||||
assert_eq!(
|
||||
pl_fit.x_of(0, k),
|
||||
pl_unconstrained.x_of(0, k),
|
||||
"char {k} position must be unchanged when there are no spaces to shrink after the tab"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// #5847: justified paragraphs starting with a tab shrink spaces on the first line in Word 2013+
|
||||
/// mode, fitting more text than legacy mode 14 just as non-tab lines do.
|
||||
#[test]
|
||||
fn justified_lines_with_tab_shrink_spaces_in_word_2013_mode() {
|
||||
let chr = wordcraft_doc::CharProps { font: Some("Source Sans 3".into()), size: Some(12.0), ..Default::default() };
|
||||
let word = "nnnn";
|
||||
let n = 12;
|
||||
let tab_at = 36.0; // default 0.5" tab stop
|
||||
let para = |text: &str, right: f32, mode: u32| {
|
||||
let mut d = Document::new();
|
||||
d.settings.compat_mode = mode;
|
||||
let mut p = wordcraft_doc::Paragraph::with_text(text, chr.clone());
|
||||
p.props = ParaProps { align: Some(Align::Justify), indent_right: Some(right), ..Default::default() };
|
||||
d.body = vec![wordcraft_doc::para_block(p)];
|
||||
d
|
||||
};
|
||||
let first = |d: &Document| {
|
||||
let l = lay(d);
|
||||
let pl = l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
|
||||
let line = &pl.lines[0];
|
||||
let text = &d.para(StoryRef::Body, &Path::top(0)).unwrap().text[line.start..line.stop];
|
||||
text.split('\t').nth(1).unwrap_or("").split_whitespace().count()
|
||||
};
|
||||
let probe = para(&format!("{word} {word}"), 0.0, 15);
|
||||
let l = lay(&probe);
|
||||
let pl = l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
|
||||
let w = pl.x_of(0, word.len()).unwrap() - pl.x_of(0, 0).unwrap();
|
||||
let sw = pl.x_of(0, word.len() + 1).unwrap() - pl.x_of(0, word.len()).unwrap();
|
||||
let room = (0.25 * n as f32 * sw).min(0.355 * (w + sw));
|
||||
let text = format!("\t{}", vec![word; 3 * n].join(" "));
|
||||
let full = probe.last_section.text_width();
|
||||
let width = tab_at + (n + 1) as f32 * w + n as f32 * sw - (room - 0.1);
|
||||
|
||||
// Verify on the tabbed first line that mode 15 fits the extra word via space shrinking
|
||||
// while legacy mode 14 does not shrink spaces, wrapping the extra word to the next line.
|
||||
let modern_doc = para(&text, full - width, 15);
|
||||
let legacy_doc = para(&text, full - width, 14);
|
||||
assert_eq!(first(&modern_doc), n + 1, "mode 15 with leading tab fits extra word within allowable overrun");
|
||||
assert_eq!(first(&legacy_doc), n, "mode 14 with leading tab does not shrink spaces and wraps extra word");
|
||||
|
||||
// Multi-line justified paragraph with leading tab also fits more lines overall in mode 15.
|
||||
let text_full = format!("\t{}", "We tie the spend to a pipe and to the books, so it is in an ad hoc view of all of it. ".repeat(40));
|
||||
let (modern, ends) = justified_lines(&text_full, 15, Align::Justify);
|
||||
let (legacy, legacy_ends) = justified_lines(&text_full, 14, Align::Justify);
|
||||
assert!(modern < legacy, "mode 15 with leading tab fits more per line: {modern} vs {legacy} lines");
|
||||
for e in ends.iter().chain(&legacy_ends) {
|
||||
assert!(*e <= 540.0 + 0.05, "line ends past the right margin: {e}");
|
||||
}
|
||||
for e in &ends[..ends.len() - 1] {
|
||||
assert!((*e - 540.0).abs() < 0.05, "justified line ends at {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// #5847: leading tab on a justified line shrinks spaces after the tab when fitting words.
|
||||
#[test]
|
||||
fn justified_line_with_leading_tab_shrinks_spaces() {
|
||||
let chr = wordcraft_doc::CharProps { font: Some("Source Sans 3".into()), size: Some(12.0), ..Default::default() };
|
||||
let word = "nnnn";
|
||||
let n = 12;
|
||||
let tab_at = 36.0; // default 0.5" tab stop
|
||||
let para = |text: &str, right: f32| {
|
||||
let mut d = Document::new();
|
||||
d.settings.compat_mode = 15;
|
||||
let mut p = wordcraft_doc::Paragraph::with_text(text, chr.clone());
|
||||
p.props = ParaProps { align: Some(Align::Justify), indent_right: Some(right), ..Default::default() };
|
||||
d.body = vec![wordcraft_doc::para_block(p)];
|
||||
d
|
||||
};
|
||||
let first = |d: &Document| {
|
||||
let l = lay(d);
|
||||
let pl = l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
|
||||
let line = &pl.lines[0];
|
||||
let text = &d.para(StoryRef::Body, &Path::top(0)).unwrap().text[line.start..line.stop];
|
||||
text.split('\t').nth(1).unwrap_or("").split_whitespace().count()
|
||||
};
|
||||
let probe = para(&format!("{word} {word}"), 0.0);
|
||||
let l = lay(&probe);
|
||||
let pl = l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
|
||||
let w = pl.x_of(0, word.len()).unwrap() - pl.x_of(0, 0).unwrap();
|
||||
let sw = pl.x_of(0, word.len() + 1).unwrap() - pl.x_of(0, word.len()).unwrap();
|
||||
let room = (0.25 * n as f32 * sw).min(0.355 * (w + sw));
|
||||
let text = format!("\t{}", vec![word; 3 * n].join(" "));
|
||||
let full = probe.last_section.text_width();
|
||||
let width = |overrun: f32| tab_at + (n + 1) as f32 * w + n as f32 * sw - overrun;
|
||||
for (overrun, words) in [(room - 0.1, n + 1), (room + 0.1, n)] {
|
||||
let d = para(&text, full - width(overrun));
|
||||
assert_eq!(first(&d), words, "leading tab overrun {overrun:.2} of {room:.2} allowed");
|
||||
}
|
||||
}
|
||||
|
||||
/// #5847: fit-time and final space compression apply only after left/default tabs, not after
|
||||
/// right, center, or decimal tabs whose anchors are resolved with unshrunk widths.
|
||||
#[test]
|
||||
fn justified_line_with_non_left_tab_preserves_anchor_and_does_not_shrink() {
|
||||
use wordcraft_doc::props::{TabAlign, TabStop};
|
||||
let chr = wordcraft_doc::CharProps { font: Some("Source Sans 3".into()), size: Some(12.0), ..Default::default() };
|
||||
let para = |text: &str, right: f32, tabs: Vec<TabStop>| {
|
||||
let mut d = Document::new();
|
||||
d.settings.compat_mode = 15;
|
||||
let mut p = wordcraft_doc::Paragraph::with_text(text, chr.clone());
|
||||
p.props = ParaProps { align: Some(Align::Justify), indent_right: Some(right), tabs: Some(tabs), ..Default::default() };
|
||||
d.body = vec![wordcraft_doc::para_block(p)];
|
||||
d
|
||||
};
|
||||
let first_pl = |d: &Document| {
|
||||
let l = lay(d);
|
||||
l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para.clone()) } else { None }).unwrap()
|
||||
};
|
||||
|
||||
// 1. Right tab past the usable right edge: multiword run is absorbed against the stop and
|
||||
// must keep its final edge at the stop rather than shrinking left of it.
|
||||
let right_text = "lead\tnnnn nnnn nnnn";
|
||||
let right_stop = 280.0;
|
||||
let right_edge = 240.0;
|
||||
let right_tabs = vec![TabStop { pos: right_stop, align: TabAlign::Right, leader: Default::default() }];
|
||||
let right_unconstrained = para(right_text, 0.0, right_tabs.clone());
|
||||
let full = right_unconstrained.last_section.text_width();
|
||||
let pl_right_unconstrained = first_pl(&right_unconstrained);
|
||||
let pl_right = first_pl(¶(right_text, full - right_edge, right_tabs));
|
||||
assert_eq!(pl_right.lines.len(), 1, "absorbed multiword run after right tab stays on line 0");
|
||||
assert!(
|
||||
(pl_right.x_of(0, right_text.len()).unwrap() - right_stop).abs() < 0.01,
|
||||
"right-tabbed multiword run must remain aligned to stop {right_stop}, got {:?}",
|
||||
pl_right.x_of(0, right_text.len())
|
||||
);
|
||||
for k in 0..=right_text.len() {
|
||||
assert_eq!(pl_right.x_of(0, k), pl_right_unconstrained.x_of(0, k), "char {k} after right tab must not shrink");
|
||||
}
|
||||
|
||||
// 2. Decimal tab on an overfull line: spaces before the decimal point must not shrink and
|
||||
// pull the decimal point left of its stop.
|
||||
let dec_text = "\t12 34.56789";
|
||||
let dec_stop = 200.0;
|
||||
let dec_tabs = vec![TabStop { pos: dec_stop, align: TabAlign::Decimal, leader: Default::default() }];
|
||||
let dec_unconstrained = para(dec_text, 0.0, dec_tabs.clone());
|
||||
let pl_dec_unconstrained = first_pl(&dec_unconstrained);
|
||||
let dot_idx = dec_text.find('.').unwrap();
|
||||
let dec_end = pl_dec_unconstrained.x_of(0, dec_text.len()).unwrap();
|
||||
let pl_dec = first_pl(¶(dec_text, full - (dec_end - 5.0), dec_tabs));
|
||||
assert_eq!(pl_dec.lines.len(), 1, "decimal-tabbed run stays on line 0");
|
||||
assert_eq!(
|
||||
pl_dec.x_of(0, dot_idx),
|
||||
pl_dec_unconstrained.x_of(0, dot_idx),
|
||||
"decimal point must keep its unconstrained anchor on an overfull line"
|
||||
);
|
||||
for k in 0..=dec_text.len() {
|
||||
assert_eq!(pl_dec.x_of(0, k), pl_dec_unconstrained.x_of(0, k), "char {k} after decimal tab must not shrink");
|
||||
}
|
||||
|
||||
// 3. Center tab:
|
||||
// (a) Overfull center-tabbed line must not run final compression and shift off its stop.
|
||||
let center_overfull_text = "\taaaaaaaaaa bbbbbbbbbb";
|
||||
let center_overfull_stop = 250.0;
|
||||
let center_overfull_tabs = vec![TabStop { pos: center_overfull_stop, align: TabAlign::Center, leader: Default::default() }];
|
||||
let center_unconstrained = para(center_overfull_text, 0.0, center_overfull_tabs.clone());
|
||||
let pl_center_unconstrained = first_pl(¢er_unconstrained);
|
||||
let pl_center_overfull = first_pl(¶(center_overfull_text, full - 260.0, center_overfull_tabs));
|
||||
assert_eq!(pl_center_overfull.lines.len(), 1, "overfull center-tabbed line stays on line 0");
|
||||
let mid = (pl_center_overfull.x_of(0, 1).unwrap() + pl_center_overfull.x_of(0, center_overfull_text.len()).unwrap()) / 2.0;
|
||||
assert!((mid - center_overfull_stop).abs() < 0.01, "centered midpoint {mid} must stay at {center_overfull_stop}");
|
||||
for k in 0..=center_overfull_text.len() {
|
||||
assert_eq!(pl_center_overfull.x_of(0, k), pl_center_unconstrained.x_of(0, k), "char {k} after center tab must not shrink");
|
||||
}
|
||||
|
||||
// (b) Fit-time compression must not pull an overflowing trailing word onto a non-left-tabbed line.
|
||||
let probe = para("n n i", 0.0, Vec::new());
|
||||
let pl_probe = first_pl(&probe);
|
||||
let sw = pl_probe.x_of(0, 2).unwrap() - pl_probe.x_of(0, 1).unwrap();
|
||||
let w_i = pl_probe.x_of(0, 5).unwrap() - pl_probe.x_of(0, 4).unwrap();
|
||||
let prefix = "n ".repeat(12);
|
||||
let fit_text = format!("\t{prefix}i");
|
||||
let pl_prefix = first_pl(¶(&prefix, 0.0, Vec::new()));
|
||||
let w_pre = pl_prefix.x_of(0, prefix.len()).unwrap();
|
||||
let room = (0.25 * 12.0 * sw).min(0.355 * (sw + w_i));
|
||||
let fit_edge = w_pre + w_i - (room - 0.1);
|
||||
for align in [TabAlign::Right, TabAlign::Center, TabAlign::Decimal] {
|
||||
let pl_fit = first_pl(¶(&fit_text, full - fit_edge, vec![TabStop { pos: 3.0, align, leader: Default::default() }]));
|
||||
assert_eq!(pl_fit.lines.len(), 2, "{align:?} tab must not use fit-time space shrinking to accept 'i'");
|
||||
}
|
||||
|
||||
// 4. Right tab followed by a left tab: spaces after the final left tab still shrink while the
|
||||
// earlier right tab keeps its anchor.
|
||||
let word = "nnnn";
|
||||
let n = 12;
|
||||
let right_seg = "aa bb";
|
||||
let pl_w = first_pl(¶(&format!("{word} {word}"), 0.0, Vec::new()));
|
||||
let w = pl_w.x_of(0, word.len()).unwrap();
|
||||
let left_room = (0.25 * n as f32 * sw).min(0.355 * (w + sw));
|
||||
let mixed_text = format!("\t{right_seg}\t{}", vec![word; 3 * n].join(" "));
|
||||
let mixed_right_stop = 120.0;
|
||||
let mixed_left_stop = 160.0;
|
||||
let mixed_width = mixed_left_stop + (n + 1) as f32 * w + n as f32 * sw - (left_room - 0.1);
|
||||
let pl_mixed = first_pl(¶(
|
||||
&mixed_text,
|
||||
full - mixed_width,
|
||||
vec![
|
||||
TabStop { pos: mixed_right_stop, align: TabAlign::Right, leader: Default::default() },
|
||||
TabStop { pos: mixed_left_stop, align: TabAlign::Left, leader: Default::default() },
|
||||
],
|
||||
));
|
||||
assert!(
|
||||
(pl_mixed.x_of(0, 1 + right_seg.len()).unwrap() - mixed_right_stop).abs() < 0.01,
|
||||
"earlier right tab must keep its stop {mixed_right_stop}"
|
||||
);
|
||||
let first_line_words = mixed_text[pl_mixed.lines[0].start..pl_mixed.lines[0].stop].split('\t').nth(2).unwrap_or("").split_whitespace().count();
|
||||
assert_eq!(first_line_words, n + 1, "spaces after final left tab still shrink");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn space_shrinking_is_only_for_justified_text() {
|
||||
crate::test_fonts();
|
||||
@@ -14721,35 +14073,6 @@ fn a_paragraph_left_out_whole_takes_no_room() {
|
||||
assert!((three_top(&d, &plain, 2) - without).abs() < 0.01);
|
||||
}
|
||||
|
||||
/// #5534: a picture floating beside or in front of the text is drawn over the paragraphs after its
|
||||
/// anchor, their shading included, as Word draws it. It was drawn with its anchor, and each shaded
|
||||
/// paragraph below painted a white band across it: the picture showed in strips. One behind the
|
||||
/// text stays under the shading.
|
||||
#[test]
|
||||
fn a_floating_object_is_drawn_over_the_shading_of_the_paragraphs_below_it() {
|
||||
use wordcraft_doc::para::{Anchor, Float, Wrap};
|
||||
crate::test_fonts();
|
||||
for (wrap, over) in [(Wrap::Square, true), (Wrap::InFrontOfText, true), (Wrap::BehindText, false)] {
|
||||
let mut d = Document::from_text("Anchor\n\n\n\n\n\nAfter");
|
||||
d.format_paragraphs(&Pos::body(0, 0), &Pos::body(6, 0), &|p| p.shading = Some(wordcraft_doc::Rgb(0xFF, 0xFF, 0xFF))).unwrap();
|
||||
let f = Float { wrap, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, x: 100.0, y: 4.0, ..Default::default() };
|
||||
d.insert_object(&Pos::body(0, 0), rect_shape(144.0, 100.0, f), &Default::default()).unwrap();
|
||||
let l = lay(&d);
|
||||
let items = &l.pages[0].items;
|
||||
let (shape, rect) =
|
||||
items.iter().enumerate().find_map(|(k, i)| if let Placed::Shape { rect, .. } = i { Some((k, *rect)) } else { None }).unwrap();
|
||||
let fills: Vec<(usize, Rect)> =
|
||||
items.iter().enumerate().filter_map(|(k, i)| if let Placed::Fill { rect, .. } = i { Some((k, *rect)) } else { None }).collect();
|
||||
let covering: Vec<usize> = fills.iter().filter(|(_, r)| r.y > rect.y && r.y < rect.bottom()).map(|(k, _)| *k).collect();
|
||||
assert!(covering.len() >= 3, "{wrap:?}: the shaded paragraphs below reach across the picture: {fills:?} {rect:?}");
|
||||
if over {
|
||||
assert!(covering.iter().all(|k| *k < shape), "{wrap:?}: shading drawn over the picture: fills {covering:?}, picture {shape}");
|
||||
} else {
|
||||
assert!(covering.iter().all(|k| *k > shape), "{wrap:?}: the picture behind the text is under the shading");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Gap #5 review: a paragraph left out whole draws no shading and no borders (they would be
|
||||
/// lines across the page at its zero height).
|
||||
#[test]
|
||||
@@ -17917,66 +17240,3 @@ fn header_text_covers_the_whole_band_of_centred_and_right_lines() {
|
||||
assert!(hit(x + left - 60.0), "{align:?}: beyond 40pt left of the band the picture is hit");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reading_layout_keeps_a_negatively_indented_table_in_the_column() {
|
||||
crate::test_fonts();
|
||||
// #8020: a table indented left of the margin ran out of the column's start edge (right edge when mirrored).
|
||||
for (rtl, width, indent, align) in [
|
||||
(false, 300.0, -36.0, None),
|
||||
(true, 300.0, -36.0, None),
|
||||
(true, 400.0, -36.0, None),
|
||||
(false, 400.0, -36.0, None),
|
||||
(false, 300.0, -36.0, Some(Align::Center)),
|
||||
] {
|
||||
let mut d = Document::from_text("Before.");
|
||||
let mut t = Table::new(2, 4, width);
|
||||
t.props.indent = Some(indent);
|
||||
t.props.bidi_visual = rtl;
|
||||
t.props.align = align;
|
||||
d.insert_block(StoryRef::Body, &Path::top(1), wordcraft_doc::Block::Table(t)).unwrap();
|
||||
let opts = LayoutOptions { view: ViewMode::Read, web_width: 360.0, read_height: 600.0, ..Default::default() };
|
||||
let l = layout(&d, &mut LayoutCache::new(), &opts);
|
||||
let p = &l.pages[0];
|
||||
let cells: Vec<_> = p.items.iter().filter_map(|i| if let Placed::Cell { rect, .. } = i { Some(*rect) } else { None }).collect();
|
||||
let (left, right) = cells.iter().fold((f32::MAX, 0.0f32), |(l, r), c| (l.min(c.x), r.max(c.x + c.w)));
|
||||
assert!(right > left, "cells placed");
|
||||
// A table wider than the column keeps its start edge there; one that fits is inside at both edges.
|
||||
if !rtl || width <= 300.0 {
|
||||
assert!(left >= p.body.x - 0.5, "rtl {rtl} width {width}: left {left} vs column {}", p.body.x);
|
||||
}
|
||||
if rtl || width <= 300.0 {
|
||||
assert!(right <= p.body.x + p.body.w + 0.5, "rtl {rtl} width {width}: right {right} vs column {}", p.body.x + p.body.w);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn many_list_definitions_keep_the_list_numbering_in_order() {
|
||||
use wordcraft_doc::numbering::{AbstractNum, Level, Num};
|
||||
use wordcraft_doc::props::NumRef;
|
||||
|
||||
let mut doc = Document::from_text(&(0..512).map(|i| format!("Item {i}")).collect::<Vec<_>>().join("\n"));
|
||||
let numbering = Arc::make_mut(&mut doc.numbering);
|
||||
numbering.abstracts = (0..12_000).map(|id| AbstractNum { id, levels: vec![Level::default()], ..Default::default() }).collect();
|
||||
numbering.nums = (1..=12_000).map(|id| Num { id, abstract_id: id - 1, ..Default::default() }).collect();
|
||||
for block in &mut doc.body {
|
||||
let Block::Para(p) = Arc::make_mut(block) else { panic!("paragraph fixture") };
|
||||
p.props.numbering = Some(NumRef { num: 12_000, level: 0 });
|
||||
p.props.space_before = Some(0.0);
|
||||
p.props.space_after = Some(0.0);
|
||||
}
|
||||
let layout = lay(&doc);
|
||||
let labels: Vec<_> = layout
|
||||
.pages
|
||||
.iter()
|
||||
.flat_map(|page| &page.items)
|
||||
.filter_map(|item| match item {
|
||||
Placed::Lines { story: StoryRef::Body, para, .. } => para.label.as_ref().map(|label| label.text.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(labels.len(), 512);
|
||||
assert_eq!(labels.first().copied(), Some("1."));
|
||||
assert_eq!(labels.last().copied(), Some("512."));
|
||||
}
|
||||
|
||||
@@ -104,7 +104,6 @@ fn write_attempt(doc: &Document, lay: &DocLayout, opts: &PdfOptions, pages: &[us
|
||||
vectors: HashMap::new(),
|
||||
tags: Vec::new(),
|
||||
tag_index: HashMap::new(),
|
||||
at: (0, 0),
|
||||
links: Vec::new(),
|
||||
bookmarks: std::cell::OnceCell::new(),
|
||||
};
|
||||
|
||||
@@ -35,8 +35,6 @@ pub(crate) struct Exporter<'a> {
|
||||
pub(crate) vectors: HashMap<String, Option<Arc<Vector>>>,
|
||||
pub(crate) tags: Vec<TagEntry>,
|
||||
pub(crate) tag_index: HashMap<(StoryRef, DocPath), usize>,
|
||||
/// Where the item being drawn is read ([`TagEntry::at`]).
|
||||
pub(crate) at: (usize, usize),
|
||||
/// Link rectangles on the current page: (x0, y0, x1, y1, target).
|
||||
pub(crate) links: Vec<(f32, f32, f32, f32, String)>,
|
||||
/// Bookmark positions by name (the first of a name wins), gathered once: looking each internal
|
||||
@@ -147,7 +145,7 @@ impl Exporter<'_> {
|
||||
s.end_tagged();
|
||||
let alt = alt.map(str::to_string).filter(|a| !a.is_empty()).or_else(|| Some("picture".to_string()));
|
||||
let g = TagGroup::with_children(Tag::Figure(alt), vec![Node::Leaf(id)]);
|
||||
self.tags.push(TagEntry { kind: Tag::Div.into(), children: vec![Node::Group(g)], at: self.at });
|
||||
self.tags.push(TagEntry { kind: Tag::Div.into(), children: vec![Node::Group(g)] });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -224,7 +222,6 @@ impl Exporter<'_> {
|
||||
|
||||
/// Draws the content of a single page (background, watermark, headers, footers, body items, and comments) onto the surface.
|
||||
pub(crate) fn page(&mut self, s: &mut Surface, page: &Page, w: f32, h: f32) {
|
||||
self.at = (self.at.0.saturating_add(1), 0);
|
||||
if let Some(c) = self.doc.settings.page_color
|
||||
&& let Some(p) = rect_path(&Rect::new(0.0, 0.0, w, h))
|
||||
{
|
||||
@@ -255,8 +252,7 @@ impl Exporter<'_> {
|
||||
}
|
||||
});
|
||||
}
|
||||
for (i, it) in page.items.iter().enumerate() {
|
||||
self.at.1 = page.reading.get(i).copied().unwrap_or(i);
|
||||
for it in &page.items {
|
||||
let draws = shown.draws(it, &dopts);
|
||||
match it {
|
||||
Placed::Lines { story, path, para, .. } => {
|
||||
@@ -332,7 +328,7 @@ impl Exporter<'_> {
|
||||
}
|
||||
_ => Tag::P.into(),
|
||||
};
|
||||
self.tags.push(TagEntry { kind, children: Vec::new(), at: self.at });
|
||||
self.tags.push(TagEntry { kind, children: Vec::new() });
|
||||
let i = self.tags.len() - 1;
|
||||
self.tag_index.insert((story, path.clone()), i);
|
||||
i
|
||||
@@ -340,12 +336,7 @@ impl Exporter<'_> {
|
||||
|
||||
pub(crate) fn tag_tree(&mut self) -> TagTree {
|
||||
let mut tree = TagTree::new().with_lang(self.doc.styles.default_chr.lang.clone());
|
||||
// In reading order: a floating object drawn over the text after it is read after its
|
||||
// anchor (#5534). The sort is stable, so what is read at one place keeps its order.
|
||||
let mut tags = std::mem::take(&mut self.tags);
|
||||
tags.sort_by_key(|e| e.at);
|
||||
self.tag_index.clear();
|
||||
for e in tags {
|
||||
for e in std::mem::take(&mut self.tags) {
|
||||
if e.children.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -32,13 +32,10 @@ pub(crate) fn figure_alt(alt: &str, kind: Option<GraphicKind>) -> &str {
|
||||
}
|
||||
}
|
||||
|
||||
/// A structure element being collected (one per paragraph or figure).
|
||||
/// A structure element being collected (one per paragraph, in reading order).
|
||||
pub(crate) struct TagEntry {
|
||||
pub(crate) kind: TagKind,
|
||||
pub(crate) children: Vec<Node>,
|
||||
/// Where it is first read: the page (in the order pages are drawn) and the place there of
|
||||
/// the item it came from (`Page::reading`). The tree is in this order, not the drawing order.
|
||||
pub(crate) at: (usize, usize),
|
||||
}
|
||||
|
||||
/// What the content being drawn is, for tagging.
|
||||
|
||||
@@ -1350,104 +1350,6 @@ fn decorative_pictures_are_artifacts_not_figures() {
|
||||
}
|
||||
}
|
||||
|
||||
/// #5534 review: a floating picture or text box in front of the text is drawn after the shaded
|
||||
/// paragraph below its anchor, so the shading doesn't cover it, but a tagged PDF still reads it
|
||||
/// (the picture's Figure, the box's paragraph) right after its anchor paragraph, not after the
|
||||
/// rest of the page.
|
||||
#[test]
|
||||
fn a_floating_object_is_read_after_its_anchor_though_drawn_over_the_text_below() {
|
||||
use hayro_syntax::object::{Dict, Name, Object};
|
||||
use wordcraft_doc::para::{Anchor, Float, ShapeKind, Wrap};
|
||||
// The marked content in a structure element: its ids number the content in drawing order.
|
||||
fn marked(o: Object<'_>, out: &mut Vec<i64>) {
|
||||
match o {
|
||||
Object::Number(n) => out.push(n.as_i64()),
|
||||
Object::Array(a) => a.iter::<Object>().for_each(|o| marked(o, out)),
|
||||
Object::Dict(d) => match (d.get::<Object>(b"MCID"), d.get::<Object>(b"K")) {
|
||||
(Some(id), _) | (None, Some(id)) => marked(id, out),
|
||||
(None, None) => {}
|
||||
},
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let shaded = |text: &str| {
|
||||
let mut p = Paragraph::with_text(text, CharProps::default());
|
||||
p.props.shading = Some(wordcraft_doc::Rgb(0xEE, 0xEE, 0xEE));
|
||||
p
|
||||
};
|
||||
let float = Float { wrap: Wrap::InFrontOfText, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, x: 100.0, y: 4.0, ..Default::default() };
|
||||
for (name, text_box, expected) in [("picture", false, ["P", "Div", "P"]), ("text box", true, ["P", "P", "P"])] {
|
||||
let mut d = Document::new();
|
||||
let object = if text_box {
|
||||
let story = d.add_part(wordcraft_doc::PartKind::TextBox, vec![para_block(Paragraph::with_text("Inside the box", CharProps::default()))]);
|
||||
InlineObject::Shape {
|
||||
kind: ShapeKind::TextBox,
|
||||
w: 120.0,
|
||||
h: 60.0,
|
||||
fill: None,
|
||||
stroke: None,
|
||||
stroke_width: 0.0,
|
||||
float: float.clone(),
|
||||
story: Some(story),
|
||||
freeform: None,
|
||||
effects: Default::default(),
|
||||
extra: Default::default(),
|
||||
}
|
||||
} else {
|
||||
let media = d.add_media(red_right_half_emf(), "emf");
|
||||
InlineObject::Image {
|
||||
media,
|
||||
w: 70.0,
|
||||
h: 70.0,
|
||||
alt: "A red square".into(),
|
||||
float: float.clone(),
|
||||
crop: [0.0; 4],
|
||||
fx: Default::default(),
|
||||
ole: None,
|
||||
}
|
||||
};
|
||||
let mut first = shaded("Anchor");
|
||||
first.insert_object(0, object, &CharProps::default()).unwrap();
|
||||
d.body = vec![para_block(first), para_block(shaded("After"))];
|
||||
let bytes = export(&d, &PdfOptions { compress: false, tagged: true, ..Default::default() }).unwrap();
|
||||
let pdf = hayro_syntax::Pdf::new(bytes).unwrap();
|
||||
let root = pdf.xref().get::<Dict>(pdf.xref().root_id()).unwrap().get::<Dict>(b"StructTreeRoot").unwrap();
|
||||
let mut tops: Vec<Dict> = match root.get::<Object>(b"K") {
|
||||
Some(Object::Array(a)) => a.iter::<Dict>().collect(),
|
||||
Some(Object::Dict(d)) => vec![d],
|
||||
_ => Vec::new(),
|
||||
};
|
||||
// A document element holding them all is looked through.
|
||||
while let [only] = tops.as_slice()
|
||||
&& only.get::<Name>(b"S").is_some_and(|s| s.as_str() == "Document")
|
||||
{
|
||||
tops = match only.get::<Object>(b"K") {
|
||||
Some(Object::Array(a)) => a.iter::<Dict>().collect(),
|
||||
Some(Object::Dict(d)) => vec![d],
|
||||
_ => Vec::new(),
|
||||
};
|
||||
}
|
||||
let read: Vec<(String, Vec<i64>)> = tops
|
||||
.iter()
|
||||
.map(|e| {
|
||||
let mut ids = Vec::new();
|
||||
if let Some(k) = e.get::<Object>(b"K") {
|
||||
marked(k, &mut ids);
|
||||
}
|
||||
(e.get::<Name>(b"S").map(|s| s.as_str().to_string()).unwrap_or_default(), ids)
|
||||
})
|
||||
.collect();
|
||||
let names: Vec<&str> = read.iter().map(|(s, _)| s.as_str()).collect();
|
||||
assert_eq!(names, expected, "{name}: three elements: {read:?}");
|
||||
// The second element read is the object's: it is drawn after the third, the paragraph below.
|
||||
let (object, after) = (&read[1].1, &read[2].1);
|
||||
assert!(
|
||||
!object.is_empty() && !after.is_empty() && object.iter().min() > after.iter().max(),
|
||||
"{name}: read after its anchor paragraph, drawn after the paragraph below it: {read:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A row of exact height cuts its cell's lines (one clip around them): text and a picture in
|
||||
/// it are tagged as they are in a row that fits, the text as the paragraph's, the picture as a
|
||||
/// Figure with its alt text.
|
||||
@@ -1943,7 +1845,6 @@ fn bookmark_destination_is_the_page_of_its_start() {
|
||||
vectors: HashMap::new(),
|
||||
tags: Vec::new(),
|
||||
tag_index: HashMap::new(),
|
||||
at: (0, 0),
|
||||
links: Vec::new(),
|
||||
bookmarks: std::cell::OnceCell::new(),
|
||||
};
|
||||
|
||||
@@ -16,7 +16,7 @@ craft = { workspace = true, features = [
|
||||
"color", "color-ui", "control", "draw", "font-manager", "gpu", "menu", "pages", "print", "review", "table", "text",
|
||||
"text-find", "web-api", "web-host", "window",
|
||||
] }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21" }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541" }
|
||||
wordcraft-geom = { workspace = true, features = ["image"] }
|
||||
wordcraft-doc = { workspace = true }
|
||||
wordcraft-fonts = { workspace = true }
|
||||
@@ -76,7 +76,7 @@ craft-ui-test-kit = { workspace = true }
|
||||
craft = { workspace = true, features = ["ui-testing"] }
|
||||
|
||||
[build-dependencies]
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", features = ["subset"] }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", features = ["subset"] }
|
||||
serde_json = { workspace = true }
|
||||
toml = "1"
|
||||
|
||||
|
||||
@@ -319,7 +319,6 @@ impl WordApp {
|
||||
pub fn logic(&mut self, ctx: &egui::Context) {
|
||||
let lang = i18n::Lang::from_pref(&self.ui.language);
|
||||
if self.ctx.is_none() {
|
||||
theme::set_dark_text_curve(ctx);
|
||||
self.ctx = Some(ctx.clone());
|
||||
}
|
||||
updates_ui::tick(self, ctx);
|
||||
|
||||
@@ -147,12 +147,6 @@ const LINKED_EDIT: [craft::ui::runtime::commands::EditCommands; 5] = {
|
||||
[Cut, Copy, Paste, Undo, Redo]
|
||||
};
|
||||
|
||||
/// The English parts of a registry `location` (`Home › Font`, split as `i18n::location` does); `None` for no place.
|
||||
pub(crate) fn location_path(location: &str) -> Option<Vec<&str>> {
|
||||
let path: Vec<&str> = location.split(" › ").filter(|part| !part.is_empty()).collect();
|
||||
(!path.is_empty()).then_some(path)
|
||||
}
|
||||
|
||||
impl WordApp {
|
||||
/// The app's commands as the keymap knows them: every engine command with its default
|
||||
/// chords, then the interface commands. The interface commands come last because a tie in the
|
||||
@@ -189,11 +183,6 @@ impl WordApp {
|
||||
// warned about), so their chords go in as the set's replaced defaults (the `LINKED_EDIT` fold below).
|
||||
for spec in registry.all().iter().filter(|spec| seen.insert(spec.id) && !LINKED_EDIT.iter().any(|c| c.id() == spec.id)) {
|
||||
let mut def = CommandDef::new(CommandRef::new(spec.id), tl!(spec.label), Scope::app());
|
||||
// Its ribbon place is its menu path, in English: Customize Keyboard files it under the tab by name,
|
||||
// and the framework translates each segment where it shows it.
|
||||
if let Some(path) = location_path(spec.location) {
|
||||
def = def.with_path(path.into_iter().map(str::to_owned).collect());
|
||||
}
|
||||
for binding in default_bindings(spec.shortcut) {
|
||||
def = def.with_default(binding);
|
||||
}
|
||||
|
||||
@@ -684,7 +684,7 @@ impl WordApp {
|
||||
}
|
||||
None => {
|
||||
return Some(Err(format!(
|
||||
"`percent` must be \"auto\" or a finite number (clamped between {} and {})",
|
||||
"`percent` must be \"auto\" or a number from {} to {}",
|
||||
theme::InterfaceSize::MIN,
|
||||
theme::InterfaceSize::MAX
|
||||
)));
|
||||
|
||||
@@ -87,34 +87,26 @@ impl WordApp {
|
||||
.screen_mode(Bind::given(mode))
|
||||
.dropped(Bind::given(dropped))
|
||||
.window_title(self.window_title())
|
||||
.page(self.ui.backstage, crate::backstage::scope(), |_| None, crate::backstage::show)
|
||||
.title_bar(|_| None, chrome::title_bar::show)
|
||||
.top(Slot::new("screenBar").screen_bar(), |_| None, chrome::screen_bar::show)
|
||||
.page(self.ui.backstage, crate::backstage::scope(), crate::backstage::show)
|
||||
.title_bar(chrome::title_bar::show)
|
||||
.top(Slot::new("screenBar").screen_bar(), chrome::screen_bar::show)
|
||||
// The ribbon is a tab strip over a group row: its slots are as tall as it is and stack it. A slot of the
|
||||
// default size is one options bar high and lays its content in one line, which put the groups beside the
|
||||
// tabs and collapsed every one of them.
|
||||
.top(
|
||||
Slot::new("ribbonDrop").drops().size(SlotSize::Content),
|
||||
|_| None,
|
||||
|ui, _cx, app: &mut WordApp| {
|
||||
if !stale(app) {
|
||||
*ribbon_out.borrow_mut() = Some(ribbon::show(app, ui));
|
||||
}
|
||||
},
|
||||
)
|
||||
.top(
|
||||
Slot::new("ribbon").size(SlotSize::Content),
|
||||
|_| None,
|
||||
|ui, _cx, app: &mut WordApp| {
|
||||
if !stale(app) {
|
||||
*ribbon_out.borrow_mut() = Some(ribbon::show(app, ui));
|
||||
}
|
||||
},
|
||||
)
|
||||
.top(Slot::new("ribbonDrop").drops().size(SlotSize::Content), |ui, _cx, app: &mut WordApp| {
|
||||
if !stale(app) {
|
||||
*ribbon_out.borrow_mut() = Some(ribbon::show(app, ui));
|
||||
}
|
||||
})
|
||||
.top(Slot::new("ribbon").size(SlotSize::Content), |ui, _cx, app: &mut WordApp| {
|
||||
if !stale(app) {
|
||||
*ribbon_out.borrow_mut() = Some(ribbon::show(app, ui));
|
||||
}
|
||||
})
|
||||
// As tall as the bar: a failure's line under the message puts Install below the first line, and a slot of
|
||||
// the default size (one options bar high) clips it, so a press on it reached nothing.
|
||||
.top(Slot::new("languagePack").size(SlotSize::Content).visible(language_packs::bar_offer(self)), |_| None, language_packs::pack_bar)
|
||||
.status(true, |_| None, chrome::status_bar::show)
|
||||
.top(Slot::new("languagePack").size(SlotSize::Content).visible(language_packs::bar_offer(self)), language_packs::pack_bar)
|
||||
.status(true, chrome::status_bar::show)
|
||||
.body(|ui, _cx, app: &mut WordApp| {
|
||||
if !app.has_document() || stale(app) {
|
||||
return;
|
||||
|
||||
@@ -250,8 +250,7 @@ fn side_menu(ui: &mut Ui, band: f32, current: &str, has_document: bool, show_dis
|
||||
.least_width(LeastWidth::SideMenu)
|
||||
.surface(SurfaceKind::Brand)
|
||||
.label(label("File"))
|
||||
// v0.19.1's row pitch (~42 pt against the 38 pt rows): the theme's tight gap between the page rows.
|
||||
.gap(Gap::Tight)
|
||||
.gap(Gap::None)
|
||||
.scroll(Scroll::vertical())
|
||||
.header(move |ui, _| {
|
||||
ui.add_space(band);
|
||||
|
||||
@@ -748,7 +748,7 @@ fn about_stays_at_the_bottom_of_a_side_menu_that_fits() {
|
||||
}
|
||||
|
||||
/// The side menu is production's rail: 200 pt wide (five rail columns, `LeastWidth::SideMenu`), its page rows about
|
||||
/// 38 pt tall a tight gap apart. The footer's links are rows of the same place, so they read in the rail's white ink;
|
||||
/// 38 pt tall one after another. The footer's links are rows of the same place, so they read in the rail's white ink;
|
||||
/// production's were a little shorter (32 pt), which the side menu place has no row for.
|
||||
#[test]
|
||||
fn the_side_menu_rows_are_production_s_rail_rows() {
|
||||
@@ -758,9 +758,7 @@ fn the_side_menu_rows_are_production_s_rail_rows() {
|
||||
// The least width holds in the row beside the page: before, the row gave the menu only its widest name (~123 pt).
|
||||
assert!((190.0..=260.0).contains(&info.width()), "the menu is production's 200 pt rail: {info:?}");
|
||||
assert!((34.0..=44.0).contains(&info.height()), "a page row is a rail row: {info:?}");
|
||||
// v0.19.1's pitch was ~42 pt for 38 pt rows: the rows are a little apart, not touching and not far apart.
|
||||
let gap = recover.min.y - info.max.y;
|
||||
assert!((1.0..=8.0).contains(&gap), "the rows have a small gap between them: {info:?} {recover:?}");
|
||||
assert!((recover.min.y - info.max.y).abs() < 1.0, "the rows follow each other without a gap: {info:?} {recover:?}");
|
||||
assert!(about.height() <= info.height() + 1.0, "the footer link is no taller than a page row: {info:?} {about:?}");
|
||||
}
|
||||
|
||||
|
||||
@@ -716,17 +716,8 @@ fn show_reading(app: &mut WordApp, ui: &mut Ui, layout: &Arc<DocLayout>, full: R
|
||||
let mut state = std::mem::take(&mut app.canvas.reading);
|
||||
let source = source::WordPages::new(app, layout, false, None);
|
||||
let out = ReadingView::new(tl!("Document"), &source, &mut state, paper).zoom(zoom).show_at(ui, columns);
|
||||
// The page-turn row sits at the bottom right, as in v0.19.1 (the far end, so the bottom left in a right-to-left UI),
|
||||
// the page view's side margin in from the edge.
|
||||
let margin = Env::of(ui).tokens.space.inset.page_side;
|
||||
let footer = footer.shrink2(egui::vec2(margin, 0.0));
|
||||
let far = if crate::i18n::current().rtl() {
|
||||
egui::Layout::left_to_right(egui::Align::Center)
|
||||
} else {
|
||||
egui::Layout::right_to_left(egui::Align::Center)
|
||||
};
|
||||
let nav = ui
|
||||
.scope_builder(egui::UiBuilder::new().max_rect(footer).layout(far), |ui| {
|
||||
.scope_builder(egui::UiBuilder::new().max_rect(footer), |ui| {
|
||||
ReadingNav::new(&mut state, layout.pages.len()).position(true).action(tl!("Edit Document")).show(ui)
|
||||
})
|
||||
.inner;
|
||||
|
||||
@@ -56,7 +56,7 @@ impl Component for ReadingProbe {
|
||||
|
||||
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> egui::Vec2 {
|
||||
let measure = ReadingMeasure::of(TypeRole::Body, |run| cx.layout(run));
|
||||
self.measured = Some(metrics(cx.style.column_gap, cx.style.nav_bar, measure));
|
||||
self.measured = Some(ReadingMetrics::new(cx.style.column_gap, cx.style.nav_bar, measure));
|
||||
egui::Vec2::ZERO
|
||||
}
|
||||
|
||||
@@ -69,19 +69,6 @@ impl Component for ReadingProbe {
|
||||
}
|
||||
}
|
||||
|
||||
/// Column widths Read Mode has always used (about one column per 295 screen points, none under 192), as v0.19.1 laid out 4
|
||||
/// columns at 1440 screen points. craft's body-text measure (66 characters) gives 2 there, so only the gaps come from it.
|
||||
const COLUMN_TARGET: f32 = 295.0;
|
||||
const COLUMN_MIN: f32 = 192.0;
|
||||
|
||||
fn metrics(column_gap: f32, nav_bar: f32, measure: ReadingMeasure) -> ReadingMetrics {
|
||||
let mut m = ReadingMetrics::new(column_gap, nav_bar, measure);
|
||||
// lean: fixed px, not the text size; follow the body text again if Read Mode should scale with it.
|
||||
m.column_target = COLUMN_TARGET;
|
||||
m.column_min = COLUMN_MIN;
|
||||
m
|
||||
}
|
||||
|
||||
/// The reading metrics under the current theme, or `None` when the probe did not measure this pass.
|
||||
pub(super) fn read(ui: &mut Ui) -> Option<ReadingMetrics> {
|
||||
ReadingProbe { common: Common::new(), measured: None }.label("Reading metrics").show(ui).metrics
|
||||
|
||||
@@ -253,48 +253,6 @@ fn drawing_over_the_pages_follows_the_read_mode_page_color() {
|
||||
assert_eq!(blank(&a), Rgb::WHITE, "the paper under the raster, not the page color");
|
||||
}
|
||||
|
||||
/// #8019: at 1440 x 900 Read Mode lays out several narrow columns (v0.19.1: 4), not the two the body
|
||||
/// text's measure gave after the port.
|
||||
#[test]
|
||||
fn read_mode_lays_out_several_columns_at_1440() {
|
||||
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::from_text("Hello WordCraft")), Default::default());
|
||||
a.run("view.readMode", json!({})).unwrap();
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|
||||
|ui, app: &mut WordApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
a,
|
||||
);
|
||||
h.run_steps(4);
|
||||
let px = ReadingView::screen_scale(1.0) * h.state().session.view.read_width;
|
||||
assert!(px > 0.0 && 4.0 * px < 1440.0, "columns {px} px wide: four do not fit");
|
||||
}
|
||||
|
||||
/// #8019: the page-turn row (position and Edit Document) sits in the bottom-right quadrant, as in v0.19.1,
|
||||
/// not at the bottom left where craft's row starts.
|
||||
#[test]
|
||||
fn read_mode_pager_is_at_the_bottom_right() {
|
||||
use egui_kittest::kittest::Queryable;
|
||||
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::from_text("Hello WordCraft")), Default::default());
|
||||
a.run("view.readMode", json!({})).unwrap();
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|
||||
|ui, app: &mut WordApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
a,
|
||||
);
|
||||
h.run_steps(4);
|
||||
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440.0, 900.0));
|
||||
for label in ["Edit Document", "1 / 1"] {
|
||||
let r = h.get_all_by_label(label).last().unwrap().rect();
|
||||
assert!(r.center().x > screen.center().x && r.center().y > screen.center().y, "{label} at {r:?}: not bottom right");
|
||||
}
|
||||
}
|
||||
|
||||
/// #299: the caret's colour is worked out only when the caret is drawn: with text selected
|
||||
/// there is no caret, so the page's draw list isn't built for it.
|
||||
#[test]
|
||||
|
||||
@@ -9,8 +9,7 @@
|
||||
//! [`GLIDE_SECS`], fast at first and settling ([`ease`]). The time is the same for one
|
||||
//! character and for a whole line.
|
||||
//! - **Another move before it arrives:** it snaps to where it was heading and glides from there.
|
||||
//! - **A click moves the caret:** it glides the same way, so the eye follows it to the new place
|
||||
//! (our choice; Word draws it at once).
|
||||
//! - **A click moves the caret:** no glide; it is drawn at its new place.
|
||||
//! - **A command from a script or the control channel:** no glide, no fade.
|
||||
//! - **The blink is a fade:** each time the caret turns on or off it takes [`GLIDE_SECS`] to get
|
||||
//! there. A move by a key or a click turns it on the same way, from however visible it was, so
|
||||
@@ -215,8 +214,8 @@ impl CaretGlide {
|
||||
// A key or a click turns the caret on, from however visible it was.
|
||||
self.fade = Some(FadeIn { from: was_opacity, started: f.now });
|
||||
self.glide = match heading {
|
||||
// Keys and clicks glide, from where the caret was heading (not from where it has got to).
|
||||
Some(from) if same_view => {
|
||||
// Keys glide, from where the caret was heading (not from where it has got to).
|
||||
Some(from) if by_keys && !by_pointer && same_view => {
|
||||
let seen = f.viewport.expand(OFFSCREEN_SLACK);
|
||||
let on_screen = |b: Bar| seen.intersects(Rect::from_two_pos(b[0], b[1]));
|
||||
(on_screen(from) && on_screen(f.target)).then_some(Glide { from, to: f.target, started: f.now })
|
||||
|
||||
@@ -142,18 +142,16 @@ fn a_new_key_move_sets_off_from_where_the_caret_was_heading() {
|
||||
assert!(!r.glide.is_gliding());
|
||||
}
|
||||
|
||||
/// A click glides like a key; a script's move does not.
|
||||
/// Word: a click puts the caret where it was clicked, a script's move likewise; only keys glide.
|
||||
#[test]
|
||||
fn clicks_glide_and_scripts_do_not() {
|
||||
fn clicks_and_scripts_do_not_glide() {
|
||||
let mut r = Rig::new(bar(100.0, 100.0));
|
||||
r.click_to(bar(400.0, 300.0));
|
||||
let look = r.step(DT);
|
||||
assert!(r.glide.is_gliding(), "a click glides to its place");
|
||||
assert_ne!(look.bar, bar(400.0, 300.0));
|
||||
assert_eq!(look.bar, bar(400.0, 300.0));
|
||||
assert!(!r.glide.is_gliding());
|
||||
assert_eq!(look.opacity, 1.0, "a lit caret stays lit");
|
||||
r.rest(0.2);
|
||||
assert!(!r.glide.is_gliding());
|
||||
assert_eq!(r.step(DT).bar, bar(400.0, 300.0));
|
||||
r.script_to(bar(50.0, 50.0));
|
||||
assert_eq!(r.step(DT), Look { bar: bar(50.0, 50.0), opacity: 1.0, moving: false });
|
||||
// A script's move during a glide ends the glide.
|
||||
@@ -163,12 +161,12 @@ fn clicks_glide_and_scripts_do_not() {
|
||||
assert!(r.glide.is_gliding());
|
||||
r.script_to(bar(20.0, 20.0));
|
||||
assert_eq!(r.step(DT), Look { bar: bar(20.0, 20.0), opacity: 1.0, moving: false });
|
||||
// A click during a glide starts a new glide.
|
||||
// A click during a glide too.
|
||||
r.key_to(bar(250.0, 20.0));
|
||||
r.step(DT);
|
||||
r.click_to(bar(300.0, 300.0));
|
||||
r.step(DT);
|
||||
assert!(r.glide.is_gliding());
|
||||
assert_eq!(r.step(DT).bar, bar(300.0, 300.0));
|
||||
assert!(!r.glide.is_gliding());
|
||||
}
|
||||
|
||||
/// Word: the blink is a fade, and a move turns the caret on from however visible it was.
|
||||
@@ -202,15 +200,15 @@ fn the_blink_fades_and_a_move_turns_the_caret_on() {
|
||||
assert!(seen.windows(2).all(|w| w[1] >= w[0]) && seen[1] > 0.1 && seen[2] > seen[1], "{seen:?}");
|
||||
assert!((seen[3] - 0.5).abs() < 0.02, "half lit half-way: {seen:?}");
|
||||
assert_eq!(r.step(DT).opacity, 1.0);
|
||||
// A click while it is off fades in too, as it glides.
|
||||
// A click while it is off fades in too, in place.
|
||||
r.rest(0.8);
|
||||
assert_eq!(r.glide.opacity(), 0.0);
|
||||
r.click_to(bar(300.0, 200.0));
|
||||
let look = r.step(DT);
|
||||
assert!(look.opacity < 0.2 && look.moving, "{look:?}");
|
||||
r.rest(0.05);
|
||||
assert!(r.glide.opacity() > 0.2, "fading in");
|
||||
assert_eq!(r.rest(0.2).opacity, 1.0);
|
||||
assert_eq!((look.bar, look.opacity, look.moving), (bar(300.0, 200.0), 0.0, true));
|
||||
let look = r.rest(0.05);
|
||||
assert!(look.opacity > 0.3 && look.opacity < 0.7 && look.bar == bar(300.0, 200.0), "{look:?}");
|
||||
assert_eq!(r.rest(0.1).opacity, 1.0);
|
||||
// A script's move while it is off: lit at once.
|
||||
r.rest(0.7);
|
||||
assert_eq!(r.glide.opacity(), 0.0);
|
||||
|
||||
@@ -25,11 +25,7 @@ pub(crate) fn help_entries(app: &WordApp) -> Vec<HelpEntry> {
|
||||
.map(|c| {
|
||||
let command =
|
||||
if c.id == "view.paperColor" { CommandRef::with_params("file.options", json!({"pane": "general"})) } else { CommandRef::new(c.id) };
|
||||
let entry = HelpEntry::new(command, tl!(c.label).to_string()).with_english(c.label.to_string());
|
||||
match crate::app::command_board::location_path(c.location) {
|
||||
Some(path) => entry.with_path(path.into_iter().map(|part| tl!(part).to_string())),
|
||||
None => entry,
|
||||
}
|
||||
HelpEntry::new(command, tl!(c.label).to_string()).with_english(c.label.to_string())
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -85,17 +81,3 @@ pub(super) fn show(app: &mut WordApp, ui: &mut Ui, compact: bool) -> egui::Rect
|
||||
}
|
||||
rect
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::{Services, WordApp};
|
||||
|
||||
/// #7983: a search result names the ribbon place of its command.
|
||||
#[test]
|
||||
fn search_entries_show_the_ribbon_location() {
|
||||
let app = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Services::default());
|
||||
let entries = super::help_entries(&app);
|
||||
let bold = entries.iter().find(|e| e.command().id == "format.bold").expect("format.bold is searchable");
|
||||
assert!(!bold.path().is_empty(), "the entry has a path");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -241,67 +241,14 @@ pub fn apply(app: &mut WordApp, target: &Target, hex: &str) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The colour every item has, `None` for no items, no colour, or items that differ.
|
||||
fn agree(mut colors: impl Iterator<Item = Option<Rgb>>) -> Option<Rgb> {
|
||||
let first = colors.next()??;
|
||||
colors.all(|c| c == Some(first)).then_some(first)
|
||||
}
|
||||
|
||||
/// The shading the given cells share; cells a ragged table lacks are skipped, not read as unshaded.
|
||||
fn cell_shading(table: &wordcraft_doc::Table, cells: impl IntoIterator<Item = (usize, usize)>) -> Option<Rgb> {
|
||||
agree(cells.into_iter().filter_map(|(r, c)| table.rows.get(r)?.cells.get(c).map(|cell| cell.props.shading)))
|
||||
}
|
||||
|
||||
/// The colour a target has now (the dialog's Current swatch), read from what its command changes:
|
||||
/// `para.shading` reads the selected text's shading when the selection is text within one paragraph,
|
||||
/// else the paragraphs'; `shape.effects` reads shapes only. `None` when it has none, is Automatic,
|
||||
/// differs across the selection, or cannot be read (a picture's icon colour is not stored).
|
||||
/// The colour a target has now (the dialog's Current swatch).
|
||||
fn current_of(app: &mut WordApp, target: &Target) -> Option<Rgb> {
|
||||
use wordcraft_doc::InlineObject;
|
||||
let Target::Run { cmd, .. } = target else { return None };
|
||||
let s = &app.session;
|
||||
let shapes = |o: &InlineObject| matches!(o, InlineObject::Shape { .. }) || o.is_canvas();
|
||||
let objects = || wordcraft_engine::cmd::objects::target_objects(s, shapes).into_iter().map(|(_, o)| o);
|
||||
match cmd.as_str() {
|
||||
"format.color" | "format.underlineColor" => {
|
||||
let st = wordcraft_engine::cmd::format::state(s);
|
||||
let key = if cmd == "format.color" { "color" } else { "underlineColor" };
|
||||
st.get(key).and_then(Value::as_str).and_then(parse)
|
||||
"format.color" => {
|
||||
let st = wordcraft_engine::cmd::format::state(&app.session);
|
||||
st.get("color").and_then(Value::as_str).and_then(parse)
|
||||
}
|
||||
// The command shades the selected text, not its paragraph, when the selection is text within one.
|
||||
"para.shading" if wordcraft_engine::cmd::para::shades_text(s) => {
|
||||
wordcraft_engine::cmd::format::state(s).get("shading").and_then(Value::as_str).and_then(parse)
|
||||
}
|
||||
"para.shading" => agree(
|
||||
wordcraft_engine::cmd::selected_paths(s)
|
||||
.iter()
|
||||
.map(|path| s.doc.para(s.sel.focus.story, path).and_then(|p| s.doc.styles.resolve_para(&p.props).shading)),
|
||||
),
|
||||
"table.shading" => {
|
||||
let (tp, _, _) = s.sel.focus.path.cell()?;
|
||||
let table = s.doc.table(s.sel.focus.story, &tp)?;
|
||||
cell_shading(table, wordcraft_engine::cmd::table::selected_cells(s))
|
||||
}
|
||||
"design.pageColor" => s.doc.settings.page_color,
|
||||
"shape.fill" => agree(objects().map(|o| {
|
||||
let fill = match &o {
|
||||
InlineObject::Shape { fill, .. } => fill.as_ref(),
|
||||
o => o.canvas_style().and_then(|c| c.fill.as_ref()),
|
||||
};
|
||||
match fill {
|
||||
Some(wordcraft_doc::fill::Fill::Solid { color, .. }) => Some(*color),
|
||||
_ => None,
|
||||
}
|
||||
})),
|
||||
"shape.outline" => agree(objects().map(|o| match &o {
|
||||
InlineObject::Shape { stroke, .. } => *stroke,
|
||||
o => o.canvas_style().and_then(|c| c.stroke),
|
||||
})),
|
||||
// Glow is applied to shapes only, so a canvas in the selection is not read.
|
||||
"shape.effects" => agree(objects().filter(|o| matches!(o, InlineObject::Shape { .. })).map(|o| match &o {
|
||||
InlineObject::Shape { effects, .. } => effects.glow.as_ref().map(|g| g.color),
|
||||
_ => None,
|
||||
})),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -582,15 +529,14 @@ pub fn highlight_split(ui: &mut Ui, app: &mut WordApp, label: impl Into<Label>)
|
||||
// More Colors…
|
||||
|
||||
/// The Colors dialog: Standard honeycomb and greys, Custom compact picker. `current` is the colour
|
||||
/// the target has now, `None` when it has none: Current then shows no colour (as in v0.19.1) and
|
||||
/// Restore does nothing, while New starts on black. `key` comes back in the result.
|
||||
/// the target has now; `key` comes back in the result.
|
||||
pub fn more_colors(current: Option<Rgb>, key: String, tab: ColorPickerTab) -> ColorPickerDialog {
|
||||
let (cells, greys) = standard_cells();
|
||||
let dialog = ColorPickerDialog::new(key, tl!("Colors").to_string(), current.map_or(Srgba::rgb(0.0, 0.0, 0.0), srgba))
|
||||
ColorPickerDialog::new(key, tl!("Colors").to_string(), current.map_or(Srgba::rgb(0.0, 0.0, 0.0), srgba))
|
||||
.layout(ColorPickerDialogLayout::Tabbed)
|
||||
.standard(cells, greys)
|
||||
.tab(tab);
|
||||
if current.is_some() { dialog } else { dialog.no_current() }
|
||||
.compare(current.is_some())
|
||||
.tab(tab)
|
||||
}
|
||||
|
||||
/// Opens the Colors dialog for `target`, remembering where its answer goes.
|
||||
@@ -820,62 +766,4 @@ mod tests {
|
||||
assert_eq!(app.ui.recent_colors.first().map(String::as_str), Some("7A3EC8"));
|
||||
assert!(app.more_colors.is_empty(), "no entry outlives its dialog");
|
||||
}
|
||||
|
||||
/// The Current swatch reads what the selection has, and says "no colour" where there is none or it
|
||||
/// differs (#7984).
|
||||
#[test]
|
||||
fn current_reads_the_selection_and_is_none_when_unset_or_mixed() {
|
||||
let c = |hex: u8| Rgb(hex, hex, hex);
|
||||
assert_eq!(agree([Some(c(1)), Some(c(1))].into_iter()), Some(c(1)), "all alike");
|
||||
assert_eq!(agree([Some(c(1)), Some(c(2))].into_iter()), None, "mixed");
|
||||
assert_eq!(agree([Some(c(1)), None].into_iter()), None, "one has none");
|
||||
assert_eq!(agree(std::iter::empty()), None, "nothing selected");
|
||||
|
||||
// Set on the caret's paragraph directly: the commands lay the page out, which costs ~0.7 s.
|
||||
let mut app = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default());
|
||||
let shading = Target::cmd("para.shading");
|
||||
assert_eq!(current_of(&mut app, &shading), None, "no shading yet");
|
||||
assert_eq!(current_of(&mut app, &Target::cmd("table.shading")), None, "no table, no colour");
|
||||
assert_eq!(current_of(&mut app, &Target::cmd("shape.fill")), None, "no shape selected");
|
||||
let at = app.session.sel.focus.clone();
|
||||
app.session.doc.para_mut(at.story, &at.path).unwrap().props.shading = Some(c(0xAA));
|
||||
assert_eq!(current_of(&mut app, &shading), Some(c(0xAA)), "a collapsed caret reads its paragraph");
|
||||
}
|
||||
|
||||
/// Text selected inside a paragraph is what Shading changes, so Current must not report the
|
||||
/// paragraph's shading for it (#7984).
|
||||
#[test]
|
||||
fn partial_selection_reads_the_text_shading_not_the_paragraph() {
|
||||
let mut app = WordApp::new(Session::new(wordcraft_doc::Document::from_text("hello world")), crate::Services::default());
|
||||
let at = app.session.sel.focus.clone();
|
||||
app.session.doc.para_mut(at.story, &at.path).unwrap().props.shading = Some(Rgb(0xAA, 0xAA, 0xAA));
|
||||
let mut end = at.clone();
|
||||
end.off = 5;
|
||||
app.session.sel = wordcraft_engine::Selection { anchor: at, focus: end };
|
||||
let shading = Target::cmd("para.shading");
|
||||
assert_eq!(current_of(&mut app, &shading), None, "the text has no shading, whatever its paragraph has");
|
||||
let _ = app.session.run("format.shading", &json!({"color": "112233"}));
|
||||
assert_eq!(current_of(&mut app, &shading), Some(Rgb(0x11, 0x22, 0x33)), "the selected run's shading");
|
||||
}
|
||||
|
||||
/// A ragged table's missing cells do not blank Current when the real cells agree (#7984).
|
||||
#[test]
|
||||
fn table_shading_skips_missing_cells() {
|
||||
let mut t = wordcraft_doc::Table::new(2, 2, 100.0);
|
||||
t.rows[1].cells.pop();
|
||||
for cell in t.rows.iter_mut().flat_map(|r| r.cells.iter_mut()) {
|
||||
cell.props.shading = Some(Rgb(1, 2, 3));
|
||||
}
|
||||
let all = [(0, 0), (0, 1), (1, 0), (1, 1)];
|
||||
assert_eq!(cell_shading(&t, all), Some(Rgb(1, 2, 3)), "the missing (1,1) is skipped");
|
||||
t.rows[0].cells[1].props.shading = None;
|
||||
assert_eq!(cell_shading(&t, all), None, "a real unshaded cell still blanks it");
|
||||
}
|
||||
|
||||
/// A target with no colour opens with no Current colour, not black (#7984).
|
||||
#[test]
|
||||
fn no_current_colour_is_not_black() {
|
||||
assert!(more_colors(None, "k".into(), ColorPickerTab::Standard).has_no_current());
|
||||
assert!(!more_colors(Some(Rgb(0, 0, 0)), "k".into(), ColorPickerTab::Standard).has_no_current(), "a real black stays a current colour");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,13 +39,6 @@ pub(crate) use host::close_all;
|
||||
pub(crate) use mailings::{FilterRow, RecipientDraft, RecipientFilter, RecipientListDialog, hold_rows, merge_order, visible_recipients};
|
||||
pub(crate) use page_setup::PAPER_LABELS;
|
||||
|
||||
/// `max_rows` for a `TileGrid` that shows `rows` rows of `columns` tiles. The collection counts the cap in
|
||||
/// items (the tile `rows` in, not the grid row it is in), so a cap of `rows` shows one row; a cap past the item
|
||||
/// count adds blank rows, so it stops at `len`. lean: upstream fix in craft-libs `rows_height`, then drop this.
|
||||
pub(crate) fn tile_rows_cap(len: usize, columns: usize, rows: usize) -> u16 {
|
||||
u16::try_from(len.min(columns * rows)).unwrap_or(u16::MAX)
|
||||
}
|
||||
|
||||
/// Opens the dialog `name` for a script, a button or a command, with `params`; the module of the name reads what it
|
||||
/// needs of them. Returns the dialog's id, or `None` when no dialog opened (an unknown name, nothing to show, or a
|
||||
/// pane such as Restrict Editing).
|
||||
|
||||
@@ -5,11 +5,10 @@
|
||||
//! through `tools.customizeKeyboard`, so agents get the same result without the dialog.
|
||||
|
||||
use craft::keymap::{Binding, CommandDef, Keymap, Overrides};
|
||||
use craft::menu::shortcuts::{Area, DialogState, Layout, Options, Outcome, ShortcutsDialog};
|
||||
use craft::menu::shortcuts::{DialogState, Layout, Options, Outcome, ShortcutsDialog};
|
||||
use craft::ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id};
|
||||
use egui::{Context, Ui};
|
||||
use serde_json::{Value, json};
|
||||
use wordcraft_engine::ribbon::{CONTEXTUAL_TABS, TABS};
|
||||
|
||||
use super::host::{DialogHooks, Settle, open_with};
|
||||
use crate::WordApp;
|
||||
@@ -50,61 +49,11 @@ fn assignable(binding: &Binding) -> bool {
|
||||
chord.mods.cmd || chord.mods.ctrl || chord.mods.alt || chord.is_function_key()
|
||||
}
|
||||
|
||||
/// The ribbon tab a command lives on, in English (the first part of its path).
|
||||
fn tab(def: &CommandDef) -> &str {
|
||||
def.paths.first().and_then(|path| path.first()).map_or("", String::as_str)
|
||||
}
|
||||
|
||||
/// Tabs that come up with the selection or a view, besides the engine's contextual ones; they share one Categories entry.
|
||||
const EXTRA_CONTEXT_TABS: [&str; 3] = ["Header & Footer", "Outlining", "Reading"];
|
||||
|
||||
fn in_tab<const N: usize>(def: &CommandDef) -> bool {
|
||||
tab(def) == TABS[N]
|
||||
}
|
||||
|
||||
fn in_context_tab(def: &CommandDef) -> bool {
|
||||
CONTEXTUAL_TABS.contains(&tab(def)) || EXTRA_CONTEXT_TABS.contains(&tab(def))
|
||||
}
|
||||
|
||||
fn in_no_tab(def: &CommandDef) -> bool {
|
||||
!TABS.contains(&tab(def)) && !in_context_tab(def)
|
||||
}
|
||||
|
||||
/// One filter per entry of `TABS` (the array's length makes the compiler check it).
|
||||
const TAB_FILTERS: [fn(&CommandDef) -> bool; TABS.len()] = [
|
||||
in_tab::<0>,
|
||||
in_tab::<1>,
|
||||
in_tab::<2>,
|
||||
in_tab::<3>,
|
||||
in_tab::<4>,
|
||||
in_tab::<5>,
|
||||
in_tab::<6>,
|
||||
in_tab::<7>,
|
||||
in_tab::<8>,
|
||||
in_tab::<9>,
|
||||
in_tab::<10>,
|
||||
in_tab::<11>,
|
||||
in_tab::<12>,
|
||||
];
|
||||
|
||||
/// Categories as Word lists them: the ribbon tabs (not the framework's menu and panel ids), the contextual tabs, the
|
||||
/// rest, then All Commands.
|
||||
fn areas() -> Vec<Area> {
|
||||
let mut areas: Vec<Area> = TABS.iter().copied().zip(TAB_FILTERS).map(|(name, rows)| Area::new(name, tl!(name), rows)).collect();
|
||||
areas.push(Area::new("Contextual Tabs", tl!("Contextual Tabs"), in_context_tab));
|
||||
areas.push(Area::new("Other", tl!("Other"), in_no_tab));
|
||||
areas.push(Area::new("All Commands", tl!("All Commands"), |_| true));
|
||||
areas
|
||||
}
|
||||
|
||||
/// The framework dialog's options: the command-list layout, sorted by label, with the assign rule above.
|
||||
fn options() -> Options {
|
||||
Options::default().with(|o| {
|
||||
o.layout = Layout::CommandLists;
|
||||
o.sort_by_label = true;
|
||||
o.own_areas = true;
|
||||
o.size = Some(egui::vec2(720.0, 700.0));
|
||||
o.areas = areas();
|
||||
o.title = Some(tl!("Customize Keyboard").to_string());
|
||||
o.accept = Some(Box::new(|_: &CommandDef, binding: &Binding| {
|
||||
if assignable(binding) { Ok(()) } else { Err(tl!("Use a key combination with Ctrl, Alt or a function key.").to_string()) }
|
||||
@@ -298,53 +247,4 @@ mod tests {
|
||||
let unbound_labels = keys_list_labels(&h);
|
||||
assert!(unbound_labels.iter().any(|t| t == "None"), "empty keys list says None: {unbound_labels:?}");
|
||||
}
|
||||
|
||||
/// #7971: Categories are the ribbon tabs a command is on, not menu or panel ids; a command with no tab is under Other,
|
||||
/// and every command is under All Commands.
|
||||
#[test]
|
||||
fn categories_are_ribbon_tabs() {
|
||||
use craft::keymap::{CommandDef, Scope};
|
||||
let on = |path: &[&str]| {
|
||||
let mut def = CommandDef::new(CommandRef::new("x"), "X", Scope::app());
|
||||
if !path.is_empty() {
|
||||
def = def.with_path(path.iter().map(|part| part.to_string()).collect());
|
||||
}
|
||||
def
|
||||
};
|
||||
let areas = super::areas();
|
||||
let listing = |def: &CommandDef| areas.iter().filter(|a| (a.rows)(def)).map(|a| a.id).collect::<Vec<_>>();
|
||||
assert_eq!(listing(&on(&["Home", "Font"])), ["Home", "All Commands"]);
|
||||
assert_eq!(listing(&on(&["Help", "Support"])), ["Help", "All Commands"], "every ribbon tab has its entry");
|
||||
assert_eq!(listing(&on(&["Table Design", "Styles"])), ["Contextual Tabs", "All Commands"]);
|
||||
assert_eq!(listing(&on(&[])), ["Other", "All Commands"]);
|
||||
assert_eq!(areas.last().map(|a| a.id), Some("All Commands"), "All Commands comes last");
|
||||
}
|
||||
|
||||
/// #7971: under another language, and for the SmartArt tab that shows as "Diagram Design", commands still land
|
||||
/// under their tab (the catalog keeps English paths; only the display is translated).
|
||||
#[test]
|
||||
fn commands_stay_under_their_tab_in_another_language() {
|
||||
let ctx = egui::Context::default();
|
||||
crate::i18n::fixture_host(&ctx, "x-fixture", "\tHome\tHome-FX\n\tFont\tFont-FX\n\tDiagram Design\tDiagram-FX\n");
|
||||
let mut a = app();
|
||||
let catalog = a.catalog().expect("catalog");
|
||||
let areas = super::areas();
|
||||
let under = |id: &str, area: &str| {
|
||||
let def = catalog.defs().iter().find(|def| def.command == CommandRef::new(id)).unwrap_or_else(|| panic!("{id} in catalog"));
|
||||
areas.iter().any(|a| a.id == area && (a.rows)(def))
|
||||
};
|
||||
assert!(under("format.bold", "Home"), "Bold is under Home in a translated interface");
|
||||
assert!(!under("format.bold", "Other"));
|
||||
let smart = a.session.registry.all().iter().find(|spec| spec.location.starts_with("SmartArt Design")).expect("a SmartArt command");
|
||||
assert!(under(smart.id, "Contextual Tabs") && !under(smart.id, "Other"), "{} is under the contextual tabs", smart.id);
|
||||
}
|
||||
|
||||
/// #7971: the board's catalog files each engine command under its ribbon tab.
|
||||
#[test]
|
||||
fn catalog_paths_follow_the_ribbon_location() {
|
||||
let mut a = app();
|
||||
let catalog = a.catalog().expect("catalog");
|
||||
let bold = catalog.defs().iter().find(|def| def.command == CommandRef::new("format.bold")).expect("format.bold");
|
||||
assert_eq!(bold.paths.first().and_then(|p| p.first()).map(String::as_str), Some("Home"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,9 +6,10 @@ use craft::ui::buttons::Button;
|
||||
use craft::ui::choice::{Radio, RadioGroup};
|
||||
use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _, clicked};
|
||||
use craft::ui::dialog::DialogId;
|
||||
use craft::ui::display::{Picture, PictureSize, Text};
|
||||
use craft::ui::display::{Picture, Text};
|
||||
use craft::ui::form::FieldGroup;
|
||||
use craft::ui::layout_components::Row;
|
||||
use craft::ui::list::{ThumbAspect, ThumbSize};
|
||||
use craft::ui::list::ThumbAspect;
|
||||
use craft::ui::patterns::form_dialogs::FormCx;
|
||||
use craft::ui::primitives::{ContentPainterCx, TextureCache};
|
||||
use craft::ui::runtime::env::Label;
|
||||
@@ -19,7 +20,7 @@ use wordcraft_doc::props::Align;
|
||||
|
||||
use super::dialogs_insert::symbol::SymbolRequest;
|
||||
use super::font::FontRequest;
|
||||
use super::host::{Asks, ChildAnswer, WordForm, captioned, open_form};
|
||||
use super::host::{Asks, ChildAnswer, WordForm, open_form};
|
||||
use crate::WordApp;
|
||||
|
||||
/// The alignments the dialog offers: `para.defineBullet`'s `align` and their names.
|
||||
@@ -182,7 +183,6 @@ impl DefineBulletForm {
|
||||
}
|
||||
},
|
||||
)
|
||||
.extent(PictureSize::Sample(ThumbSize::Large))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -210,8 +210,8 @@ impl WordForm for DefineBulletForm {
|
||||
});
|
||||
let entries: Vec<Entry<String>> = ALIGNMENTS.iter().map(|(k, n)| Entry::new((*k).to_string(), Label::from(tl!(n)))).collect();
|
||||
let current = if self.align.is_empty() { "left".to_string() } else { self.align.clone() };
|
||||
let group = captioned(ui, Label::from(tl!("Alignment:")), |name, ui| {
|
||||
RadioGroup::new(name, Bind::given(current.clone())).show(ui, |ui, _| {
|
||||
FieldGroup::new(Label::from(tl!("Alignment:"))).show(ui, |ui, _| {
|
||||
let group = RadioGroup::new(Label::from(tl!("Alignment:")), Bind::given(current.clone())).show(ui, |ui, _| {
|
||||
Row::new().show(ui, |ui, _| {
|
||||
for e in &entries {
|
||||
if let (Some(id), label) = (e.value(), e.label()) {
|
||||
@@ -219,12 +219,12 @@ impl WordForm for DefineBulletForm {
|
||||
}
|
||||
}
|
||||
});
|
||||
})
|
||||
});
|
||||
if let Some(a) = group.output.value().cloned() {
|
||||
self.align = a;
|
||||
}
|
||||
});
|
||||
if let Some(a) = group.and_then(|g| g.output.value().cloned()) {
|
||||
self.align = a;
|
||||
}
|
||||
captioned(ui, Label::from(tl!("Preview")), |_, ui| {
|
||||
FieldGroup::new(Label::from(tl!("Preview"))).show(ui, |ui, _| {
|
||||
self.preview().show(ui);
|
||||
});
|
||||
self.ch.chars().count() == 1
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user