Compare commits

..
Author SHA1 Message Date
FredApps 331f61f925 ci: pass only the dispatch token to the notify-services workflow
secrets: inherit hands the called workflow every repository secret, including
the signing credentials. The reusable workflow only reads
ARTCRAFT_SERVICES_DISPATCH_TOKEN, so map just that one.
2026-11-27 14:43:30 +07:00
Dylan M. Taylor dfa190bf62 ci: notify artcraft-services on release state changes 2026-11-26 21:56:32 -05:00
202 changed files with 2151 additions and 12454 deletions
+5 -15
View File
@@ -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",
@@ -83,9 +83,7 @@
}
},
"max_artifact_bytes": 2147483648,
"automatic_signer_actors": [
"github-actions[bot]"
],
"automatic_signer_actors": [],
"platforms": {
"windows-x86_64": {
"unsigned_artifact_name": "nightly-unsigned-windows-x86_64",
@@ -97,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",
+9 -9
View File
@@ -35,7 +35,7 @@ jobs:
CARGO_INCREMENTAL: 0
steps:
- name: Harden runner
uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
@@ -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
@@ -121,17 +121,17 @@ jobs:
shell: pwsh
steps:
- name: Harden runner
uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Check out craft-fonts
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@main
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
@@ -181,17 +181,17 @@ jobs:
CARGO_INCREMENTAL: 0
steps:
- name: Harden runner
uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Check out craft-fonts
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@main
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
+2 -2
View File
@@ -11,9 +11,9 @@ permissions: {}
jobs:
dispatch:
# Automatic Stage 2 signer dispatch for completed scheduled nightly producer runs.
# SOURCE PREPARATION: literal off until immutable shared tooling and policy qualification.
if: >-
github.repository == 'storytold/wordcraft' &&
false && github.repository == 'storytold/wordcraft' &&
github.event_name == 'workflow_run'
runs-on: ubuntu-latest
timeout-minutes: 5
+2 -16
View File
@@ -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.
+4 -6
View File
@@ -1,9 +1,8 @@
name: WordCraft unsigned nightly
# Automated daily unsigned nightly build at 07:00 UTC plus supervised manual runs.
# Enabled for supervised manual runs by the reviewed manual actor only; no schedule yet.
# A later explicit opt-in may add a cadence (and turn on nightly-dispatch.yml with it).
on:
schedule:
- cron: '0 7 * * *'
workflow_dispatch:
permissions:
@@ -23,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
@@ -33,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"]'
+2 -2
View File
@@ -28,7 +28,7 @@ jobs:
runs-on: windows-latest
steps:
- name: Harden runner
uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
@@ -58,7 +58,7 @@ jobs:
contents: read
steps:
- name: Harden runner
uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+1 -1
View File
@@ -10,7 +10,7 @@ permissions:
contents: read
concurrency:
group: ${{ github.ref == 'refs/heads/main' && format('sonarcloud-main-{0}', github.sha) || format('sonarcloud-{0}', github.ref) }}
group: sonarcloud-${{ github.ref }}
# A push to main is the run that publishes coverage; superseded runs there would never finish.
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
-1
View File
@@ -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`.
-1
View File
@@ -258,7 +258,6 @@ The UI icons are SVG files in `crates/ui-egui/icons/`, one row each below. Gener
| `crates/ui-egui/icons/pageNumber.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/pageWidth.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/painter.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/painter-fill.svg` | WordCraft contributors | original: the Format Painter's yellow bar, split out as the fill drawn under `painter.svg` | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/paraSpacing.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/pastCitation.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/paste.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
Generated
+134 -266
View File
File diff suppressed because it is too large Load Diff
+52 -53
View File
@@ -37,22 +37,21 @@ 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-nightly = { git = "https://github.com/storytold/craft-libs", rev = "1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24" }
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"] }
@@ -85,28 +84,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"
@@ -174,27 +173,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" }
-31
View File
@@ -188,34 +188,3 @@ Permission is hereby granted, free of charge, to any person obtaining a copy of
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Linux Wayland window decorations
-------------------------------
sctk-adwaita 0.10.1 (https://github.com/PolyMeilex/sctk-adwaita,
commit d5f343c45c04d4a026db57f76760819b7325db00) is used by winit on Linux
for vector window controls. Its title-font features are disabled: no Cantarell
font is embedded by this dependency and no font file is added to this repo.
sctk-adwaita's MIT licence:
MIT License
Copyright (c) 2022 Bartłomiej Maryńczak
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+1 -2
View File
@@ -282,8 +282,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
+1 -13
View File
File diff suppressed because one or more lines are too long
-11
View File
@@ -889,17 +889,6 @@ fn parity_markdown(p: &Value) -> String {
for t in p["tabs"].as_array().cloned().unwrap_or_default() {
s += &format!("| {} | {} | {} |\n", t["tab"].as_str().unwrap_or(""), t["live"], t["total"]);
}
let h = &p["headless"];
s += &format!(
"\n**Headless ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): {} yes, {} no (window {}, os {}, engine-gap {}), {} partial, {} unknown.** A feature is `headless: yes` when its command is in the engine registry that `wordcraft-cli` and the MCP server load, so every live feature above is `yes`; the missing ones carry the hand mark from `HEADLESS` in `crates/engine/src/catalog.rs`, or `unknown`.\n",
h["yes"],
h["no"]["window"].as_u64().unwrap_or(0) + h["no"]["os"].as_u64().unwrap_or(0) + h["no"]["engine-gap"].as_u64().unwrap_or(0),
h["no"]["window"],
h["no"]["os"],
h["no"]["engine-gap"],
h["partial"],
h["unknown"]
);
s += "\n## Missing\n\n";
for t in p["tabs"].as_array().cloned().unwrap_or_default() {
let m = t["missing"].as_array().cloned().unwrap_or_default();
+2 -9
View File
@@ -43,7 +43,6 @@ craft = { workspace = true, features = [
"platform-appearance",
"platform-clipboard-system",
] }
craft-nightly = { workspace = true }
[dev-dependencies]
# Temporary settings folders for the `prefs` tests.
@@ -58,16 +57,10 @@ 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"] }
[target.'cfg(all(unix, not(any(target_os = "macos", target_os = "linux"))))'.dependencies]
winit = { version = "0.30", default-features = false, features = ["x11"] }
[target.'cfg(target_os = "linux")'.dependencies]
# Retain X11 fallback; draw Wayland client-side controls without bundled title fonts.
winit = { version = "0.30", default-features = false, features = ["x11", "wayland-csd-adwaita-notitle"] }
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"] }
# Check that the libraries winit's X11 backend opens are installed before choosing XWayland (see
# `x11_libraries` in main.rs). Both are already in the build through winit's `x11` feature, at
# these versions and with this feature.
+25 -19
View File
@@ -1,11 +1,23 @@
//! Build-time channel is distinct from a launch selector. A runtime environment cannot promote a stable build.
use crate::launch_profile::Profile;
use std::ffi::OsString;
pub use craft_nightly::BuildFlavor;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BuildFlavor {
Stable,
NightlyV1,
}
pub const COMPILED: BuildFlavor = if cfg!(wordcraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable };
pub fn require_profile(flavor: BuildFlavor, profile: &Profile) -> Result<(), String> {
match (flavor, profile.is_nightly()) {
(BuildFlavor::NightlyV1, false) => Err("Open WordCraft Nightly from ArtCraft Launcher".into()),
(BuildFlavor::Stable, true) => Err("This is a stable WordCraft build; nightly-v1 requires the nightly build".into()),
_ => Ok(()),
}
}
pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool {
desktop_session && flavor == BuildFlavor::NightlyV1
}
@@ -25,10 +37,7 @@ pub fn version_query(args: &[OsString]) -> bool {
#[cfg(test)]
mod tests {
use super::{BuildFlavor, needs_native_error, version, version_query};
use craft_nightly::{Profile, ProfileError, StartupOptions, canonical_profile_root, parse_startup};
use std::ffi::OsString;
use super::*;
#[test]
fn only_a_nightly_desktop_refusal_requests_a_native_dialog() {
assert!(needs_native_error(BuildFlavor::NightlyV1, true));
@@ -38,22 +47,19 @@ mod tests {
}
#[test]
fn direct_nightly_launch_self_isolates_into_canonical_profile_root() {
let spec = crate::profile_root::spec();
let expected_root = canonical_profile_root(spec.app_id).unwrap();
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, [OsString::from("letter.docx")], &StartupOptions::new()).unwrap();
assert_eq!(launch.profile, Profile::NightlyV1(expected_root));
assert_eq!(launch.passthrough_args, vec![OsString::from("letter.docx")]);
fn nightly_build_without_a_profile_is_refused_before_startup() {
let started = std::cell::Cell::new(false);
let result = require_profile(BuildFlavor::NightlyV1, &Profile::Stable).map(|()| started.set(true));
assert!(result.unwrap_err().contains("ArtCraft Launcher"));
assert!(!started.get());
}
#[test]
fn stable_build_refuses_nightly_launch_flags() {
let spec = crate::profile_root::spec();
let args = craft_nightly::launch_arguments(std::path::Path::new(crate::launch_profile::launcher_root()), &[]);
let err = parse_startup(BuildFlavor::Stable, &spec, args, &StartupOptions::new()).unwrap_err();
assert!(matches!(err, ProfileError::NightlyFlagsInStableBuild));
fn stable_and_nightly_flavors_accept_only_their_own_profile() {
let nightly = Profile::NightlyV1(std::path::PathBuf::from("already validated root"));
assert!(require_profile(BuildFlavor::Stable, &Profile::Stable).is_ok());
assert!(require_profile(BuildFlavor::Stable, &nightly).is_err());
assert!(require_profile(BuildFlavor::NightlyV1, &nightly).is_ok());
}
#[test]
fn nightly_version_query_is_unambiguous_and_never_reinterprets_file_arguments() {
assert_eq!(version(BuildFlavor::Stable, "0.18.1"), "0.18.1");
+160 -101
View File
@@ -1,132 +1,174 @@
//! Nightly-v1 bootstrap backed by `craft-nightly`. Selected before logging, preferences, fonts or
//! saved state. Stable launches retain their original arguments and directory policy.
//! Launcher-owned nightly-v1 bootstrap. Selected before logging, preferences, fonts or saved state.
//! Stable launches retain their original arguments and directory policy. No environment mutation.
use std::ffi::{OsStr, OsString};
use std::ffi::OsString;
use std::path::{Component, Path, PathBuf};
use std::sync::OnceLock;
pub use craft_nightly::Profile;
pub const VERSION: &str = "nightly-v1";
/// Returns the active launch profile for this process, defaulting to [`Profile::Stable`] before
/// `craft_nightly::prepare_launch` installs one.
pub fn current() -> &'static Profile {
static STABLE: Profile = Profile::Stable;
craft_nightly::current().unwrap_or(&STABLE)
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Profile {
Stable,
NightlyV1(PathBuf),
}
fn is_nightly_flag_token(arg: &OsStr) -> bool {
arg.to_str().is_some_and(|s| {
s == craft_nightly::LAUNCH_PROFILE_FLAG
|| s == craft_nightly::PROFILE_ROOT_FLAG
|| s.starts_with("--launch-profile=")
|| s.starts_with("--profile-root=")
})
}
/// Returns `true` when `args` starts with nightly launch protocol flags followed by `--`.
/// `craft_nightly::parse_startup` consumes that `--`; preserving it lets `main.rs`'s
/// `split_at_delimiter` treat every argument after `--` as a document path.
pub fn had_launcher_separator(args: &[OsString]) -> bool {
if !args.first().is_some_and(|arg| is_nightly_flag_token(arg)) {
return false;
impl Profile {
pub fn is_nightly(&self) -> bool {
matches!(self, Self::NightlyV1(_))
}
let mut idx = 0;
while let Some(arg) = args.get(idx) {
if arg == "--" {
return true;
pub fn root(&self) -> Option<&Path> {
match self {
Self::Stable => None,
Self::NightlyV1(root) => Some(root),
}
if arg == craft_nightly::LAUNCH_PROFILE_FLAG || arg == craft_nightly::PROFILE_ROOT_FLAG {
idx += 2;
} else if arg.to_str().is_some_and(|s| s.starts_with("--launch-profile=") || s.starts_with("--profile-root=")) {
idx += 1;
} else {
}
}
#[derive(Debug, PartialEq, Eq)]
pub struct Launch {
pub profile: Profile,
pub args: Vec<OsString>,
}
static PROFILE: OnceLock<Profile> = OnceLock::new();
pub fn current() -> &'static Profile {
PROFILE.get().unwrap_or(&Profile::Stable)
}
pub fn install(profile: Profile) -> Result<(), String> {
PROFILE.set(profile).map_err(|_| "the launch profile was already selected".into())
}
/// Recognize only the agreed literal selector/root pair before `--`. Everything after it is
/// a file, even when it looks like a profile flag. No filesystem or startup hook runs here.
pub fn parse(args: Vec<OsString>) -> Result<Launch, String> {
let mut selector = None;
let mut root = None;
let mut other = Vec::new();
let mut files = Vec::new();
let mut iter = args.iter();
let mut delimiter = false;
while let Some(arg) = iter.next() {
if arg == "--" {
delimiter = true;
files.extend(iter.cloned());
break;
}
if arg == "--launch-profile" || arg == "--profile-root" {
let slot = if arg == "--launch-profile" { &mut selector } else { &mut root };
if slot.is_some() {
return Err("the profile selector and root must each occur exactly once".into());
}
let value = iter.next().filter(|v| !v.is_empty()).ok_or("the profile selector/root needs a value")?;
if value.to_string_lossy().starts_with("--") {
return Err("the profile selector/root needs a value".into());
}
*slot = Some(value.clone());
} else if arg.to_string_lossy().starts_with("--launch-profile=") || arg.to_string_lossy().starts_with("--profile-root=") {
return Err("the nightly protocol requires separate literal selector/root argument tokens".into());
} else {
other.push(arg.clone());
}
}
match (selector, root) {
(None, None) => Ok(Launch { profile: Profile::Stable, args }),
(Some(version), Some(root)) if version == VERSION => {
if !delimiter || !other.is_empty() {
return Err("nightly-v1 accepts only its selector/root followed by -- and file names".into());
}
let root = PathBuf::from(root);
if !root.is_absolute() || root.components().any(|c| matches!(c, Component::ParentDir)) {
return Err("the nightly profile root must be absolute and contain no parent traversal".into());
}
Ok(Launch { profile: Profile::NightlyV1(root), args: std::iter::once(OsString::from("--")).chain(files).collect() })
}
(Some(_), Some(_)) => Err("unsupported launch profile (expected nightly-v1)".into()),
_ => Err("--launch-profile and --profile-root must be supplied together".into()),
}
false
}
/// Re-attaches the `--` separator when `craft_nightly` stripped one from an explicit launcher
/// header, leaving direct-launch arguments untouched.
pub fn passthrough_args(args: Vec<OsString>, had_separator: bool) -> Vec<OsString> {
if had_separator { std::iter::once(OsString::from("--")).chain(args).collect() } else { args }
/// The Launcher's version check: the selector/root pair followed by exactly `--version` (or `-V`),
/// answered like a plain version query. Only [`parse`]'s lexical checks apply; the root is never
/// validated or touched, and `-- --version` stays a file name.
pub fn version_query(args: &[OsString]) -> bool {
let Some((last, pair)) = args.split_last() else { return false };
if last != "--version" && last != "-V" {
return false;
}
let lexical = pair.iter().cloned().chain(std::iter::once(OsString::from("--"))).collect();
matches!(parse(lexical), Ok(Launch { profile: Profile::NightlyV1(_), args }) if args.len() == 1)
}
/// Validation finishes before the caller's first startup effect. Stable never calls the nightly
/// root validator, so its old settings-folder resolution stays unchanged.
pub fn prepare(mut launch: Launch, validate: impl FnOnce(&Path) -> Result<PathBuf, String>) -> Result<Launch, String> {
if let Profile::NightlyV1(root) = &launch.profile {
launch.profile = Profile::NightlyV1(validate(root)?);
}
Ok(launch)
}
/// The root the Launcher hands a nightly on this platform, in that platform's own spelling: `C:\NightlyData\profiles\wordcraft`
/// on Windows, `/nightly-data/profiles/wordcraft` elsewhere. A test that fixtures the hand-off uses this rather than a
/// literal, because a root literal in the other platform's spelling is not absolute here and validation refuses it (#7849).
/// literal, because a root literal in the other platform's spelling is not absolute here and `parse` refuses it (#7849).
#[cfg(test)]
pub(crate) fn launcher_root() -> &'static str {
if cfg!(windows) { r"C:\NightlyData\profiles\wordcraft" } else { "/nightly-data/profiles/wordcraft" }
}
/// Resolve the selected private root before the caller's first startup effect.
pub fn validate_root(root: &Path) -> Result<PathBuf, String> {
crate::profile_root::validate(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref(), crate::profile_root::probe_writable)
}
#[cfg(test)]
mod tests {
use super::{had_launcher_separator, launcher_root, passthrough_args};
use craft_nightly::{
BuildFlavor, NIGHTLY_V1_CONTRACT, Profile, ProfileError, StartupOptions, canonical_profile_root, parse_startup, validate_and_prepare_root,
};
use std::ffi::OsString;
use std::path::PathBuf;
use super::*;
use std::cell::Cell;
fn args(values: &[&str]) -> Vec<OsString> {
values.iter().map(OsString::from).collect()
}
fn absolute() -> &'static str {
launcher_root()
super::launcher_root()
}
fn nightly() -> Vec<OsString> {
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--"])
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"])
}
#[test]
fn stable_arguments_and_directory_policy_are_unchanged() {
let spec = crate::profile_root::spec();
for argv in [args(&[]), args(&["--control", "7981", "a.docx"]), args(&["--", "--launch-profile", "file.docx"])] {
let had_sep = had_launcher_separator(&argv);
assert!(!had_sep);
let launch = parse_startup(BuildFlavor::Stable, &spec, argv.clone(), &StartupOptions::new()).unwrap();
assert_eq!(launch.profile, Profile::Stable);
assert_eq!(passthrough_args(launch.passthrough_args, had_sep), argv);
let launch = prepare(parse(argv.clone()).unwrap(), |_| panic!("stable must never validate a nightly root")).unwrap();
assert_eq!(launch, Launch { profile: Profile::Stable, args: argv });
}
}
#[test]
fn direct_nightly_launch_resolves_canonical_root_and_preserves_user_arguments() {
let spec = crate::profile_root::spec();
let expected_root = canonical_profile_root(spec.app_id).unwrap();
let argv = args(&["--sample", "letter.docx"]);
let had_sep = had_launcher_separator(&argv);
assert!(!had_sep);
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::new()).unwrap();
assert_eq!(launch.profile, Profile::NightlyV1(expected_root));
assert_eq!(passthrough_args(launch.passthrough_args, had_sep), argv);
}
#[test]
fn exact_version_and_root_are_parsed_without_reinterpreting_file_names() {
let spec = crate::profile_root::spec();
let mut argv = nightly();
argv.extend(args(&["--profile-root", "letter with spaces.docx"]));
let had_sep = had_launcher_separator(&argv);
assert!(had_sep);
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv, &StartupOptions::new()).unwrap();
let launch = parse(argv).unwrap();
assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute())));
assert_eq!(passthrough_args(launch.passthrough_args, had_sep), args(&["--", "--profile-root", "letter with spaces.docx"]));
assert_eq!(launch.args, args(&["--", "--profile-root", "letter with spaces.docx"]));
}
#[test]
fn missing_duplicate_and_unknown_profile_arguments_are_refused() {
let spec = crate::profile_root::spec();
fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() {
for argv in [
args(&["--launch-profile", NIGHTLY_V1_CONTRACT]),
args(&["--launch-profile", VERSION]),
args(&["--profile-root", absolute()]),
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]),
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--"]),
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--profile-root", absolute(), "--"]),
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", "", "--"]),
args(&["--launch-profile", VERSION, "--launch-profile", VERSION, "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", "", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--sample", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute()]),
] {
assert!(parse_startup(BuildFlavor::NightlyV1, &spec, argv, &StartupOptions::new()).is_err());
assert!(parse(argv).is_err());
}
}
@@ -135,36 +177,53 @@ mod tests {
/// instead of run against a directory this platform never meant.
#[test]
fn a_root_absolute_only_in_the_other_platforms_spelling_is_refused() {
let spec = crate::profile_root::spec();
let foreign = if cfg!(windows) { "/nightly-data/profiles/wordcraft" } else { r"C:\NightlyData\profiles\wordcraft" };
let err = validate_and_prepare_root(std::path::Path::new(foreign), &spec).unwrap_err();
assert!(matches!(err, ProfileError::RelativeProfileRoot(_)), "the other platform's root spelling must not stand in: {foreign}");
let argv = args(&["--launch-profile", VERSION, "--profile-root", foreign, "--"]);
assert!(parse(argv).is_err(), "the other platform's root spelling must not stand in: {foreign}");
}
#[test]
fn launcher_and_plain_version_queries_are_recognized() {
let spec = crate::profile_root::spec();
let pair = &["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute()];
let reversed = &["--profile-root", absolute(), "--launch-profile", NIGHTLY_V1_CONTRACT];
fn the_launcher_version_check_is_a_version_query_only_in_its_exact_form() {
let pair = &["--launch-profile", VERSION, "--profile-root", absolute()];
let reversed = &["--profile-root", absolute(), "--launch-profile", VERSION];
for flag in ["--version", "-V"] {
let plain = parse_startup(BuildFlavor::NightlyV1, &spec, args(&[flag]), &StartupOptions::new()).unwrap();
assert!(plain.is_version_query());
for form in [pair, reversed] {
let mut argv = args(form);
argv.push(flag.into());
let direct = parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::new()).unwrap();
assert!(direct.is_version_query());
argv.push("letter with spaces.docx".into());
let with_document = parse_startup(BuildFlavor::NightlyV1, &spec, argv, &StartupOptions::new()).unwrap();
assert!(!with_document.is_version_query());
assert_eq!(with_document.passthrough_args, args(&[flag, "letter with spaces.docx"]));
let mut with_sep = args(form);
with_sep.push("--".into());
with_sep.push(flag.into());
let separated = parse_startup(BuildFlavor::NightlyV1, &spec, with_sep, &StartupOptions::new()).unwrap();
assert!(separated.is_version_query());
assert!(version_query(&argv), "{argv:?}");
}
}
for argv in [
args(&["--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--sample", "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--version"]),
args(&["--version", "--launch-profile", VERSION, "--profile-root", absolute()]),
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--version"]),
args(&["--launch-profile", VERSION, "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--help"]),
] {
assert!(!version_query(&argv), "{argv:?}");
}
// Outside the query the strict protocol still refuses the version flag.
assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version"])).is_err());
}
#[test]
fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() {
let reached = Cell::new(false);
let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".into())).map(|_| reached.set(true));
assert!(result.is_err());
assert!(!reached.get());
}
#[test]
fn successful_root_validation_keeps_the_persistent_root_not_the_binary_tag() {
let checked = PathBuf::from(absolute()).join("checked");
let launch = prepare(parse(nightly()).unwrap(), |_| Ok(checked.clone())).unwrap();
assert_eq!(launch.profile.root(), Some(checked.as_path()));
assert!(launch.profile.is_nightly());
}
}
+21 -109
View File
@@ -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));
@@ -415,40 +399,34 @@ fn report_launch_profile_error(error: &str) {
/// Select the immutable launch profile before any startup service or side effect.
fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
// The launch profile is decided before logging, crash handling, the update helper,
// The trusted Launcher protocol is decided before logging, crash handling, the update helper,
// fonts, preferences or the settings folder.
let argv: Vec<_> = std::env::args_os().skip(1).collect();
// Plain `--version` / `-V` on nightly: answered before root resolution, validation,
// process identity, IPC or any window.
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && build_flavor::version_query(&argv) {
// Plain `--version`, or the Launcher's `--launch-profile nightly-v1 --profile-root <dir>
// --version`: answered before root validation, process identity, IPC or any window.
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv))
{
let line = build_flavor::version(build_flavor::COMPILED, env!("WORDCRAFT_BUILT_VERSION"));
let _ = std::io::Write::write_all(&mut std::io::stdout(), format!("{line}\n").as_bytes());
return None;
}
let had_separator = launch_profile::had_launcher_separator(&argv);
let early = craft_nightly::prepare_launch(build_flavor::COMPILED, &profile_root::spec(), argv, &craft_nightly::StartupOptions::new())
let early = launch_profile::parse(argv)
.and_then(|launch| {
build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?;
initialize_nightly_process_identity().map_err(|error| error.to_string())?;
Ok(launch)
})
.and_then(|launch| launch_profile::prepare(launch, launch_profile::validate_root))
.unwrap_or_else(|error| {
report_launch_profile_error(&error.to_string());
report_launch_profile_error(&error);
std::process::exit(2)
});
// Launcher `--launch-profile nightly-v1 --profile-root <dir> [--] --version` / `-V`:
// `craft_nightly::prepare_launch` skips root validation and profile installation for
// version queries, so answer and exit before any startup side effect.
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && early.is_version_query() {
let line = build_flavor::version(build_flavor::COMPILED, env!("WORDCRAFT_BUILT_VERSION"));
let _ = std::io::Write::write_all(&mut std::io::stdout(), format!("{line}\n").as_bytes());
return None;
}
if let Err(error) = initialize_nightly_process_identity() {
report_launch_profile_error(&error.to_string());
std::process::exit(2);
}
let identity = if early.profile.is_nightly() {
wordcraft_ui_egui::os_window::LaunchIdentity::NightlyV1
} else {
wordcraft_ui_egui::os_window::LaunchIdentity::Stable
};
if let Err(error) = wordcraft_ui_egui::os_window::select_identity(identity) {
if let Err(error) = launch_profile::install(early.profile).and_then(|()| wordcraft_ui_egui::os_window::select_identity(identity)) {
report_launch_profile_error(&error);
std::process::exit(2);
}
@@ -460,7 +438,7 @@ fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
report_launch_profile_error(&error);
std::process::exit(2);
}
Some(launch_profile::passthrough_args(early.passthrough_args, had_separator))
Some(early.args)
}
/// Parses the command line, installs logging and the panic hook, restores preferences and window
@@ -820,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,
@@ -1038,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) {
@@ -1083,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() });
@@ -1157,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)]
@@ -1205,22 +1125,14 @@ mod command_line_tests {
use super::{documents_to_open, split_at_delimiter};
/// The argv the Launcher starts a nightly with, as `prepare_launch` hands it on. The root is the one this
/// platform would pass: `/nightly-data/...` has no drive prefix, so on Windows validation rightly refuses it.
/// platform would pass: `/nightly-data/...` has no drive prefix, so on Windows `parse` rightly refuses it.
fn launcher_argv(tail: &[&str]) -> Vec<String> {
let mut argv: Vec<std::ffi::OsString> = ["--launch-profile", "nightly-v1", "--profile-root", super::launch_profile::launcher_root(), "--"]
.iter()
.map(std::ffi::OsString::from)
.collect();
argv.extend(tail.iter().map(std::ffi::OsString::from));
let had_separator = super::launch_profile::had_launcher_separator(&argv);
let launch = craft_nightly::parse_startup(
crate::build_flavor::BuildFlavor::NightlyV1,
&crate::profile_root::spec(),
argv,
&craft_nightly::StartupOptions::new(),
)
.unwrap();
super::launch_profile::passthrough_args(launch.passthrough_args, had_separator).iter().map(|a| a.to_string_lossy().into_owned()).collect()
super::launch_profile::parse(argv).unwrap().args.iter().map(|a| a.to_string_lossy().into_owned()).collect()
}
#[test]
-64
View File
@@ -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");
}
}
+477 -159
View File
@@ -1,5 +1,4 @@
//! App-owned nightly profile specification for `craft-nightly`; no stable fallback, migration or
//! process environment changes.
//! App-owned nightly profile fences; no stable fallback, migration or process environment changes.
//!
//! WordCraft keeps all of its user state in one settings folder (`wordcraft_control_key::settings_dir`):
//! `config.toml`, `window.json`, `logs/`, `recovery/`, `fonts/`, `Templates/`,
@@ -9,209 +8,528 @@
//! (`wordcraft_engine::packs::use_font_store_in`). Every stable location of either is fenced here.
use std::ffi::OsString;
use std::path::PathBuf;
use craft_nightly::AppProfileSpec;
use std::path::{Component, Path, PathBuf};
pub const APP_ID: &str = "wordcraft";
pub const DISPLAY_NAME: &str = "WordCraft";
pub const STABLE_PACKAGE_ID: &str = "ai.storyteller.wordcraft";
pub const NIGHTLY_PACKAGE_ID: &str = "ai.storyteller.wordcraft.nightly";
pub const STABLE_DIR_NAMES: &[&str] = &["wordcraft", "WordCraft", "craft-fonts", "Craft Fonts"];
pub const FORBIDDEN_ENV_VARS: &[&str] = &["WORDCRAFT_PROFILE_DIR"];
pub const FOLDER_ONLY_ENTRIES: &[&str] = &["recovery", "logs", "fonts", "Templates", "FontStore"];
/// The app id of the nightly Flatpak this build ships in (`packaging/linux/flatpak-bundle.sh`).
pub const NIGHTLY_FLATPAK_ID: &str = "ai.storyteller.wordcraft.nightly";
/// Returns WordCraft's `craft-nightly` isolation specification, including OS-specific installation
/// and sandbox roots that must never overlap a nightly profile.
pub fn spec() -> AppProfileSpec {
spec_with(|key| std::env::var_os(key))
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Platform {
Windows,
Linux,
Mac,
}
fn spec_with(env: impl Fn(&str) -> Option<OsString>) -> AppProfileSpec {
AppProfileSpec {
app_id: APP_ID,
display_name: DISPLAY_NAME,
stable_dir_names: STABLE_DIR_NAMES,
stable_package_id: STABLE_PACKAGE_ID,
nightly_package_id: NIGHTLY_PACKAGE_ID,
profile_root_env: None,
forbidden_env_vars: FORBIDDEN_ENV_VARS,
portable_markers: &[],
folder_only_entries: FOLDER_ONLY_ENTRIES,
extra_forbidden_roots: extra_forbidden_roots_with(env),
}
}
#[cfg(any(unix, target_os = "windows"))]
fn non_empty_abs(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Option<PathBuf> {
let value = env(key)?;
if value.is_empty() {
return None;
}
let path = PathBuf::from(value);
if path.is_absolute() { Some(path) } else { None }
}
fn extra_forbidden_roots_with(env: impl Fn(&str) -> Option<OsString>) -> Vec<PathBuf> {
let mut roots = Vec::new();
#[cfg(target_os = "windows")]
{
// Per-user and per-machine MSI install locations.
if let Some(local) =
non_empty_abs(&env, "LOCALAPPDATA").or_else(|| non_empty_abs(&env, "USERPROFILE").map(|p| p.join("AppData").join("Local")))
{
roots.push(local.join("Programs").join("ArtCraft").join("WordCraft"));
impl Platform {
fn current() -> Result<Self, String> {
match std::env::consts::OS {
"windows" => Ok(Self::Windows),
"linux" => Ok(Self::Linux),
"macos" => Ok(Self::Mac),
_ => Err("nightly-v1 is not defined for this operating system".into()),
}
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
if let Some(base) = non_empty_abs(&env, key) {
roots.push(base.join("ArtCraft").join("WordCraft"));
}
fn ignores_case(self) -> bool {
self != Self::Linux
}
}
fn absolute(path: PathBuf, label: &str) -> Result<PathBuf, String> {
if !path.is_absolute() || path.components().any(|c| matches!(c, Component::ParentDir)) {
return Err(format!("{label} must be absolute and contain no parent traversal"));
}
Ok(path)
}
fn required_base(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Result<PathBuf, String> {
let value = env(key).filter(|v| !v.is_empty()).ok_or_else(|| format!("cannot establish the stable {key} boundary"))?;
absolute(PathBuf::from(value), key)
}
fn xdg_base(env: &impl Fn(&str) -> Option<OsString>, key: &str, fallback: &str) -> Result<PathBuf, String> {
match env(key).filter(|v| !v.is_empty()) {
Some(value) => absolute(PathBuf::from(value), key),
None => Ok(required_base(env, "HOME")?.join(fallback)),
}
}
/// Resolve existing ancestors before creating anything. A dangling link or inaccessible ancestor
/// is not a missing directory that may be replaced or followed later.
fn canonical_future(path: &Path) -> Result<PathBuf, String> {
let mut parent = path;
let mut missing = Vec::new();
loop {
match std::fs::symlink_metadata(parent) {
Ok(_) => break,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
missing.push(parent.file_name().ok_or("the profile root has no existing ancestor")?.to_os_string());
parent = parent.parent().ok_or("the profile root has no existing ancestor")?;
}
Err(error) => return Err(format!("cannot inspect the profile boundary: {error}")),
}
}
#[cfg(all(unix, not(target_os = "macos")))]
{
// Native packages' locations and the stable Flatpak's per-app data folder.
roots.extend(["/usr/bin/wordcraft", "/usr/local/bin/wordcraft", "/opt/wordcraft"].map(PathBuf::from));
if let Some(home) = non_empty_abs(&env, "HOME") {
roots.push(home.join(".var/app/ai.storyteller.wordcraft"));
let mut resolved = std::fs::canonicalize(parent).map_err(|e| format!("cannot resolve the profile boundary: {e}"))?;
for part in missing.into_iter().rev() {
resolved.push(part);
}
Ok(resolved)
}
fn overlaps(a: &Path, b: &Path, platform: Platform) -> bool {
let parts = |p: &Path| {
p.components()
.map(|c| {
let value = c.as_os_str().to_string_lossy().into_owned();
if platform.ignores_case() { value.to_lowercase() } else { value }
})
.collect::<Vec<_>>()
};
let (a, b) = (parts(a), parts(b));
a.starts_with(&b) || b.starts_with(&a)
}
fn installation_boundary(platform: Platform, exe: &Path) -> Result<PathBuf, String> {
let parent = exe.parent().ok_or("cannot establish the installation boundary")?;
if platform == Platform::Mac {
// A profile in Resources is still inside the versioned install, not beside MacOS.
if let Some(bundle) = exe.ancestors().find(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("app"))) {
return Ok(bundle.to_path_buf());
}
}
#[cfg(target_os = "macos")]
{
roots.push(PathBuf::from("/Applications/WordCraft.app"));
if let Some(home) = non_empty_abs(&env, "HOME") {
Ok(parent.to_path_buf())
}
fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option<OsString>, exe: &Path) -> Result<Vec<PathBuf>, String> {
let mut roots = match platform {
Platform::Windows => {
let mut roots = ["APPDATA", "LOCALAPPDATA"]
.into_iter()
.map(|key| required_base(env, key).map(|p| p.join("WordCraft")))
.collect::<Result<Vec<_>, _>>()?;
// The suite's shared font store and the MSI's default per-user and per-machine folders.
roots.push(required_base(env, "LOCALAPPDATA")?.join("Craft Fonts"));
roots.push(required_base(env, "LOCALAPPDATA")?.join("Programs").join("ArtCraft").join("WordCraft"));
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
if let Some(base) = env(key).filter(|v| !v.is_empty()) {
roots.push(absolute(PathBuf::from(base), key)?.join("ArtCraft").join("WordCraft"));
}
}
roots
}
Platform::Linux => {
let mut roots =
[("XDG_CONFIG_HOME", ".config"), ("XDG_DATA_HOME", ".local/share"), ("XDG_CACHE_HOME", ".cache"), ("XDG_STATE_HOME", ".local/state")]
.into_iter()
.map(|(key, fallback)| xdg_base(env, key, fallback).map(|p| p.join("wordcraft")))
.collect::<Result<Vec<_>, _>>()?;
// The shared font store (fonts and Language packs) and the native packages' locations.
roots.push(xdg_base(env, "XDG_DATA_HOME", ".local/share")?.join("craft-fonts"));
roots.extend(["/usr/bin/wordcraft", "/usr/local/bin/wordcraft", "/opt/wordcraft"].map(PathBuf::from));
// The stable Flatpak keeps its data in its own per-app folder.
roots.push(required_base(env, "HOME")?.join(".var/app/ai.storyteller.wordcraft"));
roots
}
Platform::Mac => {
let home = required_base(env, "HOME")?;
let library = home.join("Library");
roots.push(library.join("Preferences/ai.storyteller.wordcraft.plist"));
roots.push(library.join("Saved Application State/ai.storyteller.wordcraft.savedState"));
roots.push(home.join("Applications/WordCraft.app"));
vec![
library.join("Application Support/WordCraft"),
library.join("Caches/WordCraft"),
library.join("Caches/ai.storyteller.wordcraft"),
library.join("Preferences/WordCraft"),
library.join("Preferences/ai.storyteller.wordcraft.plist"),
library.join("Saved Application State/ai.storyteller.wordcraft.savedState"),
library.join("Application Support/Craft Fonts"),
home.join("Applications/WordCraft.app"),
PathBuf::from("/Applications/WordCraft.app"),
]
}
};
roots.push(installation_boundary(platform, exe)?);
roots.into_iter().map(|p| canonical_future(&p)).collect()
}
fn private_subdirectory(root: &Path, name: impl AsRef<Path>, label: &str) -> Result<PathBuf, String> {
let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?;
let child = canonical_future(&chosen.join(name))?;
if child == chosen || !child.starts_with(&chosen) {
return Err(format!("the nightly {label} must stay inside its selected profile"));
}
#[cfg(not(any(unix, target_os = "windows")))]
let _ = env;
roots
Ok(child)
}
/// Every existing entry directly in the profile (`config.toml`, `logs`, `recovery`, `fonts`,
/// `Templates`, `window.json` and so on) must resolve inside it, so a link there cannot point
/// Nightly's writes at another app's data.
fn entries_stay_inside(root: &Path) -> Result<(), String> {
let entries = match std::fs::read_dir(root) {
Ok(entries) => entries,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(error) => return Err(format!("cannot inspect the nightly profile: {error}")),
};
for entry in entries {
let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
private_subdirectory(root, entry.file_name(), "profile entry")?;
}
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);
let probe = dir.join(format!(".nightly-writable-{}-{}", std::process::id(), NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)));
let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?;
drop(file);
std::fs::remove_file(probe)
}
/// The writable hook is injected so filesystem boundary tests exercise the real policy without
/// starting the app or creating the profile of the person running them.
pub fn validate(
root: &Path,
env: impl Fn(&str) -> Option<OsString>,
exe: Option<&Path>,
writable: impl FnOnce(&Path) -> std::io::Result<()>,
) -> Result<PathBuf, String> {
validate_for(Platform::current()?, root, env, exe, writable)
}
fn validate_for(
platform: Platform,
root: &Path,
env: impl Fn(&str) -> Option<OsString>,
exe: Option<&Path>,
writable: impl FnOnce(&Path) -> std::io::Result<()>,
) -> Result<PathBuf, String> {
absolute(root.to_path_buf(), "the nightly profile root")?;
// The developer switch that points a run at any folder: Nightly's folder comes from the Launcher.
if env("WORDCRAFT_PROFILE_DIR").is_some_and(|v| !v.is_empty()) {
return Err("nightly-v1 cannot be combined with WORDCRAFT_PROFILE_DIR".into());
}
// These rows are native tar/app-bundle launches, not a Flatpak package. Inheriting a Flatpak
// runtime could point another profile at the stable app's token files; the nightly Flatpak
// itself (`packaging/linux/flatpak-bundle.sh`) is the one sandbox this build ships in.
if platform != Platform::Windows
&& let Some(id) = env("FLATPAK_ID").filter(|v| !v.is_empty())
&& id != NIGHTLY_FLATPAK_ID
{
return Err("nightly-v1 native packages cannot inherit a Flatpak instance; launch through the native Launcher".into());
}
let chosen = canonical_future(root)?;
let exe = absolute(exe.ok_or("cannot establish the installation boundary")?.to_path_buf(), "the executable")?;
let forbidden = forbidden_roots(platform, &env, &exe)?;
if forbidden.iter().any(|stable| overlaps(&chosen, stable, platform)) {
return Err("the nightly root must not overlap stable data or an installation".into());
}
// Existing aliases under the profile must not redirect its own subfolders elsewhere.
entries_stay_inside(&chosen)?;
// Recovery can read, adopt and sweep entries; a link there must never leave the profile.
private_subdirectory(&chosen, "recovery", "recovery folder")?;
let mut create = std::fs::DirBuilder::new();
create.recursive(true);
#[cfg(unix)]
{
use std::os::unix::fs::DirBuilderExt as _;
create.mode(0o700);
}
create.create(&chosen).map_err(|e| format!("cannot create the nightly profile: {e}"))?;
let confirmed = std::fs::canonicalize(&chosen).map_err(|e| format!("cannot resolve the created nightly profile: {e}"))?;
if confirmed != chosen || forbidden.iter().any(|stable| overlaps(&confirmed, stable, platform)) {
return Err("the nightly profile changed while it was being validated".into());
}
private_subdirectory(&confirmed, "recovery", "recovery folder")?;
entries_stay_inside(&confirmed)?;
writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?;
Ok(confirmed)
}
#[cfg(test)]
mod tests {
use super::{
APP_ID, DISPLAY_NAME, FOLDER_ONLY_ENTRIES, FORBIDDEN_ENV_VARS, NIGHTLY_PACKAGE_ID, STABLE_DIR_NAMES, STABLE_PACKAGE_ID,
extra_forbidden_roots_with, spec_with,
};
use craft_nightly::{ProfileError, validate_and_prepare_root};
use super::*;
use std::collections::BTreeMap;
use std::ffi::OsString;
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
struct TempRoot(PathBuf);
struct Fixture {
root: PathBuf,
env: BTreeMap<String, OsString>,
exe: PathBuf,
}
impl TempRoot {
fn new(label: &str) -> Self {
impl Fixture {
fn new() -> Self {
static NEXT: AtomicU64 = AtomicU64::new(0);
let root = loop {
let candidate = std::env::temp_dir().join(format!(
"wordcraft-profile-spec-{label}-{}-{}",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed)
));
let candidate =
std::env::temp_dir().join(format!("wordcraft-profile-policy-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
match std::fs::create_dir(&candidate) {
Ok(()) => break std::fs::canonicalize(candidate).unwrap(),
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(error) => panic!("cannot create owned fixture: {error}"),
}
};
Self(root)
let home = root.join("home");
let exe = root.join("install/wordcraft");
std::fs::create_dir_all(&home).unwrap();
std::fs::create_dir_all(exe.parent().unwrap()).unwrap();
std::fs::write(&exe, b"fixture executable, never run").unwrap();
let env = [("HOME", home), ("APPDATA", root.join("roaming")), ("LOCALAPPDATA", root.join("local"))]
.into_iter()
.map(|(key, value)| (key.into(), value.into_os_string()))
.collect();
Self { root, env, exe }
}
fn get(&self, key: &str) -> Option<OsString> {
self.env.get(key).cloned()
}
fn check(&self, platform: Platform, root: &Path) -> Result<PathBuf, String> {
validate_for(
platform,
root,
|key| self.get(key),
Some(&self.exe),
|dir| {
let probe = dir.join("exclusive-test-probe");
let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?;
drop(file);
std::fs::remove_file(probe)
},
)
}
fn home(&self) -> PathBuf {
PathBuf::from(self.get("HOME").unwrap())
}
}
impl Drop for TempRoot {
impl Drop for Fixture {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
// Only the directory successfully created by this fixture is owned for removal.
std::fs::remove_dir_all(&self.root).unwrap();
}
}
#[test]
fn spec_preserves_wordcraft_isolation_contract() {
let spec = spec_with(|_| None);
assert_eq!(spec.app_id, APP_ID);
assert_eq!(spec.display_name, DISPLAY_NAME);
assert_eq!(spec.stable_dir_names, STABLE_DIR_NAMES);
assert_eq!(spec.stable_package_id, STABLE_PACKAGE_ID);
assert_eq!(spec.nightly_package_id, NIGHTLY_PACKAGE_ID);
assert_eq!(spec.profile_root_env, None);
assert_eq!(spec.forbidden_env_vars, FORBIDDEN_ENV_VARS);
assert!(spec.portable_markers.is_empty());
assert_eq!(spec.folder_only_entries, FOLDER_ONLY_ENTRIES);
}
#[cfg(all(unix, not(target_os = "macos")))]
#[test]
fn linux_extra_forbidden_roots_cover_native_packages_and_stable_flatpak() {
let env = BTreeMap::from([(String::from("HOME"), OsString::from("/home/tester"))]);
let roots = extra_forbidden_roots_with(|k| env.get(k).cloned());
assert!(roots.contains(&PathBuf::from("/usr/bin/wordcraft")));
assert!(roots.contains(&PathBuf::from("/usr/local/bin/wordcraft")));
assert!(roots.contains(&PathBuf::from("/opt/wordcraft")));
assert!(roots.contains(&PathBuf::from("/home/tester/.var/app/ai.storyteller.wordcraft")));
}
#[cfg(target_os = "macos")]
#[test]
fn macos_extra_forbidden_roots_cover_bundles_plist_and_saved_state() {
let env = BTreeMap::from([(String::from("HOME"), OsString::from("/Users/tester"))]);
let roots = extra_forbidden_roots_with(|k| env.get(k).cloned());
assert!(roots.contains(&PathBuf::from("/Applications/WordCraft.app")));
assert!(roots.contains(&PathBuf::from("/Users/tester/Applications/WordCraft.app")));
assert!(roots.contains(&PathBuf::from("/Users/tester/Library/Preferences/ai.storyteller.wordcraft.plist")));
assert!(roots.contains(&PathBuf::from("/Users/tester/Library/Saved Application State/ai.storyteller.wordcraft.savedState")));
}
#[cfg(target_os = "windows")]
#[test]
fn windows_extra_forbidden_roots_cover_per_user_and_machine_installs() {
let env = BTreeMap::from([
(String::from("LOCALAPPDATA"), OsString::from(r"C:\Users\tester\AppData\Local")),
(String::from("ProgramFiles"), OsString::from(r"C:\Program Files")),
(String::from("ProgramFiles(x86)"), OsString::from(r"C:\Program Files (x86)")),
]);
let roots = extra_forbidden_roots_with(|k| env.get(k).cloned());
assert!(roots.contains(&PathBuf::from(r"C:\Users\tester\AppData\Local\Programs\ArtCraft\WordCraft")));
assert!(roots.contains(&PathBuf::from(r"C:\Program Files\ArtCraft\WordCraft")));
assert!(roots.contains(&PathBuf::from(r"C:\Program Files (x86)\ArtCraft\WordCraft")));
fn linux_fences_the_settings_folders_font_store_and_packages_but_allows_the_launcher_sibling() {
let mut fixture = Fixture::new();
for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
fixture.env.insert(key.into(), fixture.root.join(key).into_os_string());
}
for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
let stable = PathBuf::from(fixture.get(key).unwrap()).join("wordcraft");
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("stable-sentinel"), b"stable bytes").unwrap();
for candidate in [stable.clone(), stable.join("nightly"), stable.parent().unwrap().to_path_buf()] {
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"));
}
assert_eq!(std::fs::read(stable.join("stable-sentinel")).unwrap(), b"stable bytes");
}
let fonts = PathBuf::from(fixture.get("XDG_DATA_HOME").unwrap()).join("craft-fonts");
std::fs::create_dir_all(fonts.join("language-packs")).unwrap();
for candidate in [fonts.clone(), fonts.join("nightly")] {
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"));
}
for package in ["/usr/bin/wordcraft", "/usr/local/bin/wordcraft", "/opt/wordcraft"] {
assert!(fixture.check(Platform::Linux, &PathBuf::from(package)).is_err());
}
let data = PathBuf::from(fixture.get("XDG_DATA_HOME").unwrap());
let nightly = data.join("ArtCraftLauncher/nightly/profiles/wordcraft");
assert_eq!(fixture.check(Platform::Linux, &nightly).unwrap(), nightly);
assert_eq!(std::fs::read_dir(nightly).unwrap().count(), 0);
}
#[test]
fn nightly_profile_reopens_and_enforces_folder_only_entries_and_extra_fences() {
let temp = TempRoot::new("reopen");
let fenced = temp.0.join("fenced-stable");
let mut spec = spec_with(|_| None);
spec.extra_forbidden_roots.push(fenced.clone());
fn linux_fences_the_stable_flatpak_data_folder() {
let fixture = Fixture::new();
let flatpak = fixture.home().join(".var/app/ai.storyteller.wordcraft");
for candidate in [flatpak.clone(), flatpak.join("data/nightly")] {
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"));
}
assert!(!flatpak.exists());
assert!(fixture.check(Platform::Linux, &fixture.home().join(".var/app/ai.storyteller.launcher/nightly")).is_ok());
// Inside the Nightly Flatpak, XDG_DATA_HOME is this app's own persistent data folder, so
// the launcher's profile lands there rather than on the discarded sandbox home.
let nightly = fixture.home().join(".var/app/ai.storyteller.wordcraft.nightly/data/wordcraft-nightly");
assert_eq!(fixture.check(Platform::Linux, &nightly).unwrap(), nightly);
}
let overlap = validate_and_prepare_root(&fenced.join("nightly"), &spec).unwrap_err();
assert!(matches!(overlap, ProfileError::ForbiddenRootOverlap { .. }));
assert!(!fenced.exists());
#[test]
fn mac_fences_the_app_library_subtrees_the_shared_font_store_and_the_whole_bundle() {
let mut fixture = Fixture::new();
fixture.exe = fixture.root.join("install/WordCraft Nightly.app/Contents/MacOS/WordCraft");
std::fs::create_dir_all(fixture.exe.parent().unwrap()).unwrap();
std::fs::write(&fixture.exe, b"fixture executable, never run").unwrap();
let library = fixture.home().join("Library");
for suffix in [
"Application Support/WordCraft",
"Caches/WordCraft",
"Caches/ai.storyteller.wordcraft",
"Preferences/WordCraft",
"Saved Application State/ai.storyteller.wordcraft.savedState",
"Application Support/Craft Fonts",
] {
let stable = library.join(suffix);
assert!(fixture.check(Platform::Mac, &stable.join("nightly")).unwrap_err().contains("overlap"));
assert!(!stable.exists());
}
let inside_resources = fixture.exe.parent().unwrap().parent().unwrap().join("Resources/profile");
assert!(fixture.check(Platform::Mac, &inside_resources).unwrap_err().contains("overlap"));
assert!(!inside_resources.exists());
let valid = library.join("Application Support/ArtCraftLauncher/nightly/profiles/wordcraft");
assert_eq!(fixture.check(Platform::Mac, &valid).unwrap(), valid);
}
let private = temp.0.join("nightly-private");
assert_eq!(validate_and_prepare_root(&private, &spec).unwrap(), private);
for name in ["config.toml", "window.json", "nightly-session.lock", "nightly-session.json"] {
std::fs::write(private.join(name), b"saved profile data").unwrap();
#[test]
fn windows_roaming_local_font_store_and_install_fences_remain_active() {
let fixture = Fixture::new();
let mut fixture = fixture;
for key in ["APPDATA", "LOCALAPPDATA"] {
let stable = PathBuf::from(fixture.get(key).unwrap()).join("WordCraft");
assert!(fixture.check(Platform::Windows, &stable.join("nightly")).unwrap_err().contains("overlap"));
assert!(!stable.exists());
}
for name in FOLDER_ONLY_ENTRIES {
std::fs::create_dir(private.join(name)).unwrap();
}
assert_eq!(validate_and_prepare_root(&private, &spec).unwrap(), private);
for name in ["config.toml", "window.json", "nightly-session.lock", "nightly-session.json"] {
assert_eq!(std::fs::read(private.join(name)).unwrap(), b"saved profile data", "{name} remains intact after reopen");
let fonts = PathBuf::from(fixture.get("LOCALAPPDATA").unwrap()).join("Craft Fonts");
assert!(fixture.check(Platform::Windows, &fonts.join("nightly")).unwrap_err().contains("overlap"));
assert!(fixture.check(Platform::Windows, &fixture.exe.parent().unwrap().join("profile")).is_err());
let local = PathBuf::from(fixture.get("LOCALAPPDATA").unwrap());
let per_user = local.join("Programs").join("ArtCraft").join("WordCraft");
assert!(fixture.check(Platform::Windows, &per_user.join("nightly")).unwrap_err().contains("overlap"));
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
let base = fixture.root.join(format!("machine {key}"));
fixture.env.insert(key.into(), base.clone().into_os_string());
let machine = base.join("ArtCraft").join("WordCraft");
assert!(fixture.check(Platform::Windows, &machine.join("nightly")).unwrap_err().contains("overlap"));
assert!(!machine.exists());
}
let sibling = local.join("Programs").join("ArtCraft").join("ArtCraftLauncher").join("nightly").join("wordcraft");
assert!(fixture.check(Platform::Windows, &sibling).is_ok(), "the Launcher's own Programs sibling is not WordCraft's install");
}
for name in FOLDER_ONLY_ENTRIES {
let path = private.join(name);
std::fs::remove_dir(&path).unwrap();
std::fs::write(&path, b"not a directory").unwrap();
let err = validate_and_prepare_root(&private, &spec).unwrap_err();
assert!(matches!(err, ProfileError::ExpectedDirectoryEntry(_)), "{name} must stay a directory");
std::fs::remove_file(&path).unwrap();
std::fs::create_dir(&path).unwrap();
#[test]
fn overlap_check_handles_ancestor_descendant_and_prefix_lookalikes() {
let fixture = Fixture::new();
let root = fixture.home().join("nightly/profiles/wordcraft");
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
assert!(overlaps(&root, &root.join("recovery"), platform));
assert!(overlaps(&root.join("recovery"), &root, platform));
assert!(!overlaps(&root, &root.with_file_name("wordcraft-other"), platform));
}
}
#[cfg(unix)]
#[test]
fn recovery_and_entry_aliases_cannot_leave_the_profile_and_stable_bytes_stay_untouched() {
let fixture = Fixture::new();
let stable = fixture.home().join(".config/wordcraft/recovery");
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("stable-autosave"), b"stable recovery bytes").unwrap();
for (index, target) in [stable.clone(), fixture.root.join("missing recovery target")].into_iter().enumerate() {
let private = fixture.root.join(format!("nightly-{index}"));
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(&target, private.join("recovery")).unwrap();
let probed = std::cell::Cell::new(false);
let result = validate_for(
Platform::Linux,
&private,
|key| fixture.get(key),
Some(&fixture.exe),
|_| {
probed.set(true);
Ok(())
},
);
assert!(result.is_err(), "recovery must not escape the private profile or follow a dangling alias");
assert!(!probed.get());
}
for name in ["logs", "fonts", "config.toml"] {
let private = fixture.root.join(format!("nightly-entry-{name}"));
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(&stable, private.join(name)).unwrap();
assert!(fixture.check(Platform::Linux, &private).is_err(), "{name} must not lead outside the profile");
}
assert_eq!(std::fs::read(stable.join("stable-autosave")).unwrap(), b"stable recovery bytes");
assert_eq!(std::fs::read_dir(stable).unwrap().count(), 1);
}
#[cfg(unix)]
#[test]
fn a_recovery_alias_inside_the_profile_keeps_it_usable() {
let fixture = Fixture::new();
let private = fixture.root.join("nightly-private");
let recovery = private.join("private-recovery");
std::fs::create_dir_all(&recovery).unwrap();
std::os::unix::fs::symlink(&recovery, private.join("recovery")).unwrap();
assert!(fixture.check(Platform::Linux, &private).is_ok());
assert_eq!(std::fs::canonicalize(private.join("recovery")).unwrap(), recovery);
}
#[test]
fn ambiguous_environment_and_non_native_sandbox_are_refused_before_creation() {
let mut fixture = Fixture::new();
let candidate = fixture.home().join("nightly/profiles/wordcraft");
fixture.env.insert("XDG_CACHE_HOME".into(), "relative/cache".into());
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("absolute"));
fixture.env.remove("XDG_CACHE_HOME");
fixture.env.insert("WORDCRAFT_PROFILE_DIR".into(), fixture.home().join("custom-stable").into_os_string());
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("WORDCRAFT_PROFILE_DIR"));
fixture.env.remove("WORDCRAFT_PROFILE_DIR");
fixture.env.insert("FLATPAK_ID".into(), "ai.storyteller.wordcraft".into());
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("Flatpak"));
fixture.env.remove("FLATPAK_ID");
// The nightly Flatpak is the one sandbox this build ships in, so its own id is accepted.
let flatpak_profile = fixture.home().join("nightly/flatpak-profile");
fixture.env.insert("FLATPAK_ID".into(), NIGHTLY_FLATPAK_ID.into());
assert_eq!(fixture.check(Platform::Linux, &flatpak_profile).unwrap(), flatpak_profile);
fixture.env.remove("FLATPAK_ID");
fixture.env.remove("HOME");
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("HOME"));
assert!(!candidate.exists());
}
#[test]
fn non_directory_and_failed_write_probe_never_fall_back_to_stable() {
let fixture = Fixture::new();
let file = fixture.home().join("not-a-directory");
std::fs::write(&file, b"do not replace me").unwrap();
assert!(fixture.check(Platform::Linux, &file).is_err());
assert_eq!(std::fs::read(file).unwrap(), b"do not replace me");
let candidate = fixture.home().join("nightly");
let calls = std::cell::Cell::new(0);
let result = validate_for(
Platform::Linux,
&candidate,
|key| fixture.get(key),
Some(&fixture.exe),
|_| {
calls.set(calls.get() + 1);
Err(std::io::Error::new(std::io::ErrorKind::PermissionDenied, "injected write refusal"))
},
);
assert!(result.unwrap_err().contains("not writable"));
assert_eq!(calls.get(), 1);
assert!(!fixture.home().join(".config/wordcraft").exists());
}
#[cfg(unix)]
#[test]
fn symlink_and_dangling_aliases_cannot_create_or_modify_stable_data() {
use std::os::unix::fs::symlink;
let fixture = Fixture::new();
let stable = fixture.home().join(".config/wordcraft");
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("sentinel"), b"untouched").unwrap();
let alias = fixture.home().join("alias");
symlink(&stable, &alias).unwrap();
assert!(fixture.check(Platform::Linux, &alias.join("nightly")).unwrap_err().contains("overlap"));
let missing = fixture.home().join("missing-target");
let dangling = fixture.home().join("dangling");
symlink(&missing, &dangling).unwrap();
assert!(fixture.check(Platform::Linux, &dangling.join("nightly")).is_err());
assert!(!missing.exists());
assert!(!stable.join("nightly").exists());
assert_eq!(std::fs::read(stable.join("sentinel")).unwrap(), b"untouched");
}
}
@@ -1,167 +0,0 @@
//! Integration test for Linux Wayland client-side window decoration controls (#5814, #5375).
//!
//! Ensures that on Linux, client-side window controls use font-free Adwaita vector paths
//! so the close button is rendered as a clean vector cross rather than a square fallback,
//! and that sctk-adwaita has proper license attribution in NOTICE without bundling font files.
use std::path::Path;
/// Strips an unquoted TOML `#` comment from a single line.
fn strip_toml_comment(line: &str) -> &str {
let mut in_double = false;
let mut in_single = false;
for (idx, ch) in line.char_indices() {
match ch {
'"' if !in_single => in_double = !in_double,
'\'' if !in_double => in_single = !in_single,
'#' if !in_double && !in_single => return &line[..idx],
_ => {}
}
}
line
}
/// Extracts the comment-stripped body of a TOML table section by exact `[header]`.
fn toml_section(content: &str, header: &str) -> String {
let mut in_section = false;
let mut out = String::new();
for raw_line in content.lines() {
let line = strip_toml_comment(raw_line).trim();
if line.starts_with('[') && line.ends_with(']') {
if in_section {
break;
}
in_section = line == header;
continue;
}
if in_section && !line.is_empty() {
out.push_str(line);
out.push('\n');
}
}
assert!(in_section, "expected target section {header} in apps/wordcraft/Cargo.toml");
out
}
/// Parses the `features = [...]` string array from the `winit = { ... }` dependency entry in a TOML section.
fn winit_features(section: &str) -> Vec<&str> {
let winit_start = section.find("winit").expect("target section must declare a winit dependency");
let after_winit = &section[winit_start..];
let table_end = after_winit.find('}').expect("winit inline table must close with '}'");
let winit_table = &after_winit[..=table_end];
let features_start = winit_table.find("features").expect("winit dependency must declare features");
let after_features = &winit_table[features_start..];
let open_bracket = after_features.find('[').expect("winit features must open with '['");
let after_open = &after_features[open_bracket + 1..];
let close_bracket = after_open.find(']').expect("winit features must close with ']'");
let array_body = &after_open[..close_bracket];
array_body.split(',').map(|item| item.trim().trim_matches('"')).filter(|item| !item.is_empty()).collect()
}
/// Verifies that `apps/wordcraft/Cargo.toml` enables `wayland-csd-adwaita-notitle` for Linux.
#[test]
fn linux_manifest_enables_wayland_csd_adwaita_notitle() {
let cargo_toml = Path::new(env!("CARGO_MANIFEST_DIR")).join("Cargo.toml");
let content = std::fs::read_to_string(&cargo_toml).expect("read apps/wordcraft/Cargo.toml");
let linux_section = toml_section(&content, "[target.'cfg(target_os = \"linux\")'.dependencies]");
let linux_features = winit_features(&linux_section);
assert!(
linux_features.contains(&"x11") && linux_features.contains(&"wayland-csd-adwaita-notitle"),
"Linux winit dependency must enable x11 and wayland-csd-adwaita-notitle, got: {linux_features:?}"
);
let other_unix_section = toml_section(&content, "[target.'cfg(all(unix, not(any(target_os = \"macos\", target_os = \"linux\"))))'.dependencies]");
let other_unix_features = winit_features(&other_unix_section);
assert!(
other_unix_features.contains(&"x11") && !other_unix_features.contains(&"wayland-csd-adwaita-notitle"),
"Non-Linux Unix winit dependency must enable x11 without wayland-csd-adwaita-notitle, got: {other_unix_features:?}"
);
}
/// Verifies that `NOTICE` documents sctk-adwaita and its MIT licence.
#[test]
fn notice_documents_sctk_adwaita_attribution() {
let workspace_root = Path::new(env!("CARGO_MANIFEST_DIR")).parent().and_then(Path::parent).expect("workspace root");
let notice = std::fs::read_to_string(workspace_root.join("NOTICE")).expect("read NOTICE");
assert!(notice.contains("Linux Wayland window decorations"), "NOTICE must include 'Linux Wayland window decorations'");
assert!(notice.contains("sctk-adwaita"), "NOTICE must document sctk-adwaita");
assert!(notice.contains("Bartłomiej Maryńczak"), "NOTICE must retain sctk-adwaita's author copyright");
}
/// Parses `[[package]]` entries from `Cargo.lock` as `(name, version, dependencies)`.
fn parse_lockfile_packages(lockfile: &str) -> Vec<(&str, &str, Vec<&str>)> {
lockfile
.split("[[package]]")
.skip(1)
.filter_map(|chunk| {
let mut name = None;
let mut version = None;
let mut deps = Vec::new();
let mut in_deps = false;
for raw_line in chunk.lines() {
let line = raw_line.trim();
if in_deps {
if line == "]" {
in_deps = false;
continue;
}
let dep = line.trim_end_matches(',').trim().trim_matches('"');
if !dep.is_empty() {
deps.push(dep);
}
continue;
}
if let Some(rest) = line.strip_prefix("name = ") {
name = Some(rest.trim_matches('"'));
} else if let Some(rest) = line.strip_prefix("version = ") {
version = Some(rest.trim_matches('"'));
} else if line == "dependencies = [" {
in_deps = true;
}
}
Some((name?, version?, deps))
})
.collect()
}
/// Verifies that WordCraft's resolved Linux `winit` -> `sctk-adwaita` dependency path in
/// `Cargo.lock` does not pull in any title-font renderer crates.
#[test]
fn cargo_lock_contains_font_free_sctk_adwaita() {
use std::collections::{HashSet, VecDeque};
let workspace_root = Path::new(env!("CARGO_MANIFEST_DIR")).parent().and_then(Path::parent).expect("workspace root");
let lockfile = std::fs::read_to_string(workspace_root.join("Cargo.lock")).expect("read Cargo.lock");
let packages = parse_lockfile_packages(&lockfile);
let has_dep = |pkg_name: &str, target: &str| {
packages.iter().any(|(name, _, deps)| *name == pkg_name && deps.iter().any(|spec| spec.split_whitespace().next() == Some(target)))
};
assert!(has_dep("winit", "sctk-adwaita"), "winit in Cargo.lock must depend on sctk-adwaita");
let mut queue = VecDeque::new();
let mut visited = HashSet::new();
for (idx, (name, _, _)) in packages.iter().enumerate() {
if *name == "sctk-adwaita" && visited.insert(idx) {
queue.push_back(idx);
}
}
assert!(!queue.is_empty(), "Cargo.lock must include sctk-adwaita");
let forbidden = ["fontdue", "ab_glyph", "cosmic-text", "crossfont"];
while let Some(idx) = queue.pop_front() {
let (name, _, deps) = &packages[idx];
assert!(!forbidden.contains(name), "sctk-adwaita's resolved dependency path must not include title-font renderer {name}");
for spec in deps {
let mut parts = spec.split_whitespace();
let dep_name = parts.next().expect("dependency name");
let dep_ver = parts.next();
for (next_idx, (cand_name, cand_ver, _)) in packages.iter().enumerate() {
if *cand_name == dep_name && dep_ver.is_none_or(|v| v == *cand_ver) && visited.insert(next_idx) {
queue.push_back(next_idx);
}
}
}
}
}
-2
View File
@@ -2,7 +2,5 @@
mod appimage_env;
mod control_arg;
mod help;
#[cfg(target_os = "linux")]
mod linux_decorations;
#[cfg(unix)]
mod non_utf8_args;
+7 -26
View File
@@ -703,44 +703,25 @@ impl Document {
}
/// A drawing id no shape uses yet (for gluing a connector to a shape that has none).
///
/// Returns one past the largest in-use shape id across the body, all secondary parts, and
/// footnote/endnote separator stories (walking nested groups and tables); if `u32::MAX` is
/// already in use, falls back via [`free_id`] to the smallest unused non-zero id (or `0` only
/// if every non-zero `u32` id is taken).
pub fn next_shape_id(&self) -> u32 {
let mut largest: Option<u32> = None;
let mut used: Vec<u32> = Vec::new();
let mut record = |id: u32| {
if id != 0 {
largest = largest.max(Some(id));
used.push(id);
}
};
let mut max = 0u32;
let mut see = |o: &InlineObject| match o {
InlineObject::Shape { extra, .. } => record(extra.id),
InlineObject::Shape { extra, .. } => max = max.max(extra.id),
InlineObject::Group { children, .. } => {
let mut todo: Vec<&InlineObject> = children.iter().map(|c| &c.obj).collect();
while let Some(obj) = todo.pop() {
match obj {
InlineObject::Shape { extra, .. } => record(extra.id),
InlineObject::Group { children, .. } => todo.extend(children.iter().map(|c| &c.obj)),
_ => {}
for c in children {
if let InlineObject::Shape { extra, .. } = &c.obj {
max = max.max(extra.id);
}
}
}
_ => {}
};
let sep_stories = [&self.footnote_separators, &self.endnote_separators]
.into_iter()
.flat_map(|s| [&s.separator, &s.continuation_separator, &s.continuation_notice])
.flatten();
for blocks in std::iter::once(&self.body).chain(self.parts.values().map(|p| &p.blocks)).chain(sep_stories) {
for blocks in std::iter::once(&self.body).chain(self.parts.values().map(|p| &p.blocks)) {
for b in blocks {
edit::each_para(b, 0, &mut |p| p.objects.iter().for_each(&mut see));
}
}
free_id(largest, used.into_iter(), 1).unwrap_or(0)
max.saturating_add(1).max(1)
}
/// Change every inline object in every story (paragraphs inside tables too), copying only
+27 -48
View File
@@ -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);
-55
View File
@@ -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
View File
@@ -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));
}
}
+10 -32
View File
@@ -291,47 +291,25 @@ impl InlineObject {
_ => None,
}
}
/// The text box stories this object shows: a text box's, or its group members' (nested groups
/// included, in member order).
/// The text box stories this object shows: a text box's, or its group members'.
pub fn text_boxes(&self) -> Vec<u32> {
match self {
InlineObject::Shape { story: Some(id), .. } => vec![*id],
InlineObject::Group { children, .. } => {
let mut out = Vec::new();
let mut todo: Vec<&InlineObject> = children.iter().rev().map(|c| &c.obj).collect();
while let Some(obj) = todo.pop() {
match obj {
InlineObject::Shape { story: Some(id), .. } => out.push(*id),
InlineObject::Group { children, .. } => {
todo.extend(children.iter().rev().map(|c| &c.obj));
}
_ => {}
}
}
out
}
InlineObject::Group { children, .. } => children.iter().filter_map(|c| c.obj.text_box()).collect(),
_ => Vec::new(),
}
}
/// The text box story slots of this object and its group members (nested groups included, in
/// member order), to repoint.
/// The text box story slots of this object and its group members, to repoint.
pub fn text_box_slots(&mut self) -> Vec<&mut Option<u32>> {
match self {
InlineObject::Shape { story, .. } => vec![story],
InlineObject::Group { children, .. } => {
let mut out = Vec::new();
let mut todo: Vec<&mut InlineObject> = children.iter_mut().rev().map(|c| &mut c.obj).collect();
while let Some(obj) = todo.pop() {
match obj {
InlineObject::Shape { story, .. } => out.push(story),
InlineObject::Group { children, .. } => {
todo.extend(children.iter_mut().rev().map(|c| &mut c.obj));
}
_ => {}
}
}
out
}
InlineObject::Group { children, .. } => children
.iter_mut()
.filter_map(|c| match &mut c.obj {
InlineObject::Shape { story, .. } => Some(story),
_ => None,
})
.collect(),
_ => Vec::new(),
}
}
-5
View File
@@ -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 {
+1 -17
View File
@@ -42,27 +42,11 @@ pub struct Revision {
/// insertion or deletion.
#[serde(skip_serializing_if = "Option::is_none")]
pub move_name: Option<String>,
/// The change's UTC timestamp: from the file (`w16du:dateUtc`, where `date` is the local time
/// Word writes in `w:date`), or the time WordCraft stamped the change with. `None` when the
/// file doesn't give it.
#[serde(skip_serializing_if = "Option::is_none")]
pub date_utc: Option<String>,
}
impl Revision {
pub fn new(kind: RevisionKind, author: impl Into<String>, date: impl Into<String>) -> Revision {
Revision { kind, author: author.into(), date: date.into(), move_name: None, date_utc: None }
}
/// A change made here: `date` is the local wall-clock time it was made at, as Word writes
/// `w:date`, and `date_utc` the same instant in UTC.
pub fn made_at(kind: RevisionKind, author: impl Into<String>, date: impl Into<String>, utc: impl Into<String>) -> Revision {
Revision { kind, author: author.into(), date: date.into(), move_name: None, date_utc: Some(utc.into()) }
}
/// The instant changes are grouped by: the UTC time when it is known, else `date`.
pub fn instant(&self) -> &str {
self.date_utc.as_deref().unwrap_or(&self.date)
Revision { kind, author: author.into(), date: date.into(), move_name: None }
}
}
-9
View File
@@ -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,
}
}
-43
View File
@@ -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]
-272
View File
@@ -440,116 +440,6 @@ fn prune_text_boxes_drops_only_unshown_ones() {
assert_eq!(d.prune_text_boxes(), 0);
}
/// A text-box shape (`story: Some(id)`) or plain shape (`story: None`) for nested-group tests.
fn test_shape(story: Option<u32>) -> InlineObject {
InlineObject::Shape {
kind: para::ShapeKind::TextBox,
w: 50.0,
h: 20.0,
fill: None,
stroke: None,
stroke_width: 0.0,
float: Default::default(),
story,
freeform: None,
effects: Default::default(),
extra: Default::default(),
}
}
/// A group holding `children`.
fn test_group(children: Vec<InlineObject>) -> InlineObject {
InlineObject::Group {
w: 100.0,
h: 100.0,
float: Default::default(),
ch_w: 100.0,
ch_h: 100.0,
children: children.into_iter().map(|obj| para::GroupChild { x: 0.0, y: 0.0, obj }).collect(),
canvas: None,
}
}
/// `obj` wrapped inside `levels` nested [`InlineObject::Group`]s.
fn nested_group(levels: usize, obj: InlineObject) -> InlineObject {
(0..levels).fold(obj, |inner, _| test_group(vec![inner]))
}
#[test]
fn nested_group_text_boxes_are_collected_and_slots_repointed_in_order() {
let mut outer = test_group(vec![
test_shape(Some(1)),
test_shape(None),
nested_group(1, test_shape(Some(2))), // depth 2 from outer
test_group(vec![nested_group(1, test_shape(Some(3))), test_shape(Some(4))]), // depth 3 and depth 2
nested_group(39, test_shape(Some(5))), // depth 40 from outer
]);
assert_eq!(outer.text_boxes(), vec![1, 2, 3, 4, 5]);
let slots = outer.text_box_slots();
assert_eq!(slots.len(), 6);
for id in slots.into_iter().flatten() {
*id += 100;
}
assert_eq!(outer.text_boxes(), vec![101, 102, 103, 104, 105]);
}
#[test]
fn prune_text_boxes_keeps_nested_group_boxes_and_drops_unreachable() {
let para_of = |t: &str| vec![para_block(Paragraph::with_text(t, CharProps::default()))];
let mut d = Document::from_text("body");
let depth2 = d.add_part(PartKind::TextBox, para_of("depth 2"));
let depth3 = d.add_part(PartKind::TextBox, para_of("depth 3"));
let deep = d.add_part(PartKind::TextBox, para_of("depth 40"));
let linked_live = d.add_part(PartKind::TextBox, para_of("linked follower"));
let orphan = d.add_part(PartKind::TextBox, para_of("unreachable"));
let orphan_nested = d.add_part(PartKind::TextBox, para_of("inside unreachable"));
// Live link between two nested-group boxes and a dangling link to an unreachable box.
d.parts.get_mut(&depth2).unwrap().body.next = Some(linked_live);
d.parts.get_mut(&depth3).unwrap().body.next = Some(orphan);
d.insert_object(&Pos::body(0, 0), nested_group(2, test_shape(Some(depth2))), &CharProps::default()).unwrap();
d.insert_object(&Pos::body(0, 0), nested_group(3, test_shape(Some(depth3))), &CharProps::default()).unwrap();
d.insert_object(&Pos::body(0, 0), nested_group(40, test_shape(Some(deep))), &CharProps::default()).unwrap();
d.insert_object(&Pos::body(0, 0), nested_group(2, test_shape(Some(linked_live))), &CharProps::default()).unwrap();
let at_orphan = Pos { story: StoryRef::Part(orphan), path: Path::top(0), off: 0 };
d.insert_object(&at_orphan, nested_group(2, test_shape(Some(orphan_nested))), &CharProps::default()).unwrap();
assert_eq!(d.prune_text_boxes(), 2);
let kept: Vec<u32> = d.parts.keys().copied().collect();
assert_eq!(kept, vec![depth2, depth3, deep, linked_live]);
assert_eq!(d.plain_text(StoryRef::Part(depth2)), "depth 2");
assert_eq!(d.plain_text(StoryRef::Part(depth3)), "depth 3");
assert_eq!(d.plain_text(StoryRef::Part(deep)), "depth 40");
assert_eq!(d.parts.get(&depth2).unwrap().body.next, Some(linked_live), "live chain link stays");
assert_eq!(d.parts.get(&depth3).unwrap().body.next, None, "dangling chain link is cleared");
assert_eq!(d.prune_text_boxes(), 0);
}
#[test]
fn prune_text_boxes_terminates_on_cyclic_nested_group_stories() {
let para_of = |t: &str| vec![para_block(Paragraph::with_text(t, CharProps::default()))];
let mut d = Document::from_text("body");
let a = d.add_part(PartKind::TextBox, para_of("a"));
let b = d.add_part(PartKind::TextBox, para_of("b"));
let dead_c = d.add_part(PartKind::TextBox, para_of("dead c"));
let dead_d = d.add_part(PartKind::TextBox, para_of("dead d"));
let at = |id| Pos { story: StoryRef::Part(id), path: Path::top(0), off: 0 };
// Reachable cycle: body -> nested group -> a -> nested group -> b -> nested group -> (a, b).
d.insert_object(&Pos::body(0, 0), nested_group(2, test_shape(Some(a))), &CharProps::default()).unwrap();
d.insert_object(&at(a), nested_group(2, test_shape(Some(b))), &CharProps::default()).unwrap();
d.insert_object(&at(b), nested_group(2, test_group(vec![test_shape(Some(a)), test_shape(Some(b))])), &CharProps::default()).unwrap();
// Unreachable cycle: dead_c <-> dead_d through nested groups.
d.insert_object(&at(dead_c), nested_group(2, test_shape(Some(dead_d))), &CharProps::default()).unwrap();
d.insert_object(&at(dead_d), nested_group(2, test_shape(Some(dead_c))), &CharProps::default()).unwrap();
assert_eq!(d.prune_text_boxes(), 2);
let kept: Vec<u32> = d.parts.keys().copied().collect();
assert_eq!(kept, vec![a, b]);
assert_eq!(d.counted_stories(), vec![StoryRef::Body, StoryRef::Part(a), StoryRef::Part(b)]);
}
/// `blocks` in the only cell of `levels` tables, each nested in the next.
fn nested_tables(levels: usize, blocks: Blocks) -> Blocks {
(0..levels).fold(blocks, |inner, _| {
@@ -928,165 +818,3 @@ fn missing_pictures_are_capped_deduplicated_and_not_content() {
assert!(!serde_json::to_string(&d).unwrap().contains("p0"));
assert_eq!(MissingPictureReason::ExternalTarget.label(), "external target");
}
fn shape_with_id(id: u32, story: Option<u32>) -> InlineObject {
InlineObject::Shape {
kind: para::ShapeKind::Rectangle,
w: 50.0,
h: 20.0,
fill: None,
stroke: None,
stroke_width: 0.0,
float: Default::default(),
story,
freeform: None,
effects: Default::default(),
extra: connector::ShapeExtra { id, ..Default::default() },
}
}
fn group_of(children: Vec<InlineObject>) -> InlineObject {
InlineObject::Group {
w: 100.0,
h: 100.0,
float: Default::default(),
ch_w: 100.0,
ch_h: 100.0,
children: children.into_iter().map(|obj| para::GroupChild { x: 0.0, y: 0.0, obj }).collect(),
canvas: None,
}
}
fn nested_group_of(depth: usize, leaf: InlineObject) -> InlineObject {
(0..depth).fold(leaf, |inner, _| group_of(vec![inner]))
}
#[test]
fn next_shape_id_accounts_for_shapes_in_nested_groups() {
// Doubly-nested group carrying shape id 1: must not reissue id 1.
let mut d = Document::from_text("body");
d.insert_object(&Pos::body(0, 0), nested_group_of(2, shape_with_id(1, None)), &CharProps::default()).unwrap();
assert_eq!(d.next_shape_id(), 2);
// Deeper nesting (5-level and 40-level groups) with mixed siblings.
d.insert_object(
&Pos::body(0, 0),
nested_group_of(5, group_of(vec![shape_with_id(42, None), nested_group_of(35, shape_with_id(99, None))])),
&CharProps::default(),
)
.unwrap();
assert_eq!(d.next_shape_id(), 100);
// Nested group inside a secondary story (part).
let hdr = d.add_part(PartKind::Header, vec![para_block(Paragraph::with_text("hdr", CharProps::default()))]);
let at_hdr = Pos { story: StoryRef::Part(hdr), path: Path::top(0), off: 0 };
d.insert_object(&at_hdr, nested_group_of(3, shape_with_id(150, None)), &CharProps::default()).unwrap();
assert_eq!(d.next_shape_id(), 151);
}
#[test]
fn next_shape_id_preserves_flat_group_and_ungrouped_allocation() {
let mut d = Document::from_text("body");
assert_eq!(d.next_shape_id(), 1);
// Ungrouped shapes (including id 0).
d.insert_object(&Pos::body(0, 0), shape_with_id(0, None), &CharProps::default()).unwrap();
assert_eq!(d.next_shape_id(), 1);
d.insert_object(&Pos::body(0, 0), shape_with_id(3, None), &CharProps::default()).unwrap();
d.insert_object(&Pos::body(0, 0), shape_with_id(7, None), &CharProps::default()).unwrap();
assert_eq!(d.next_shape_id(), 8);
// Flat (1-level) group.
d.insert_object(&Pos::body(0, 0), group_of(vec![shape_with_id(12, None), shape_with_id(4, None)]), &CharProps::default()).unwrap();
assert_eq!(d.next_shape_id(), 13);
// At u32::MAX, overflow falls back to an unused non-zero id rather than reissuing u32::MAX.
d.insert_object(&Pos::body(0, 0), nested_group_of(2, shape_with_id(u32::MAX, None)), &CharProps::default()).unwrap();
let id = d.next_shape_id();
assert_ne!(id, 0);
for used in [3, 4, 7, 12, u32::MAX] {
assert_ne!(id, used);
}
assert_eq!(id, 1);
}
#[test]
fn next_shape_id_avoids_reissuing_u32_max_on_overflow() {
// Non-overflow boundary: u32::MAX - 1 still advances to u32::MAX.
let mut d = Document::from_text("body");
d.insert_object(&Pos::body(0, 0), shape_with_id(u32::MAX - 1, None), &CharProps::default()).unwrap();
assert_eq!(d.next_shape_id(), u32::MAX);
// Once u32::MAX is in use inside a nested group, allocator must not reissue any in-use id.
let hdr = d.add_part(PartKind::Header, vec![para_block(Paragraph::with_text("hdr", CharProps::default()))]);
let at_hdr = Pos { story: StoryRef::Part(hdr), path: Path::top(0), off: 0 };
d.insert_object(&Pos::body(0, 0), shape_with_id(1, None), &CharProps::default()).unwrap();
d.insert_object(&at_hdr, nested_group_of(2, shape_with_id(2, None)), &CharProps::default()).unwrap();
d.insert_object(&Pos::body(0, 0), nested_group_of(3, shape_with_id(u32::MAX, None)), &CharProps::default()).unwrap();
let in_use = [1, 2, u32::MAX - 1, u32::MAX];
let first = d.next_shape_id();
assert_ne!(first, 0);
assert!(!in_use.contains(&first), "reissued in-use shape id {first}");
assert_eq!(first, 3);
// Using the returned id advances to the next unused id rather than repeating it.
d.insert_object(&Pos::body(0, 0), nested_group_of(2, shape_with_id(first, None)), &CharProps::default()).unwrap();
let second = d.next_shape_id();
assert_ne!(second, 0);
assert_ne!(second, first);
assert!(!in_use.contains(&second), "reissued in-use shape id {second}");
assert_eq!(second, 4);
}
#[test]
fn next_shape_id_terminates_on_cyclic_nested_group_stories() {
// InlineObject::Group owns Vec<GroupChild> by value (and unsafe is forbidden), so a cyclic
// in-memory Group tree cannot be constructed in safe Rust; mirror #8068 by constructing a
// cyclic text-box story graph through nested groups instead.
let para_of = |t: &str| vec![para_block(Paragraph::with_text(t, CharProps::default()))];
let mut d = Document::from_text("body");
let a = d.add_part(PartKind::TextBox, para_of("a"));
let b = d.add_part(PartKind::TextBox, para_of("b"));
let at = |id| Pos { story: StoryRef::Part(id), path: Path::top(0), off: 0 };
d.insert_object(&Pos::body(0, 0), nested_group_of(2, shape_with_id(5, Some(a))), &CharProps::default()).unwrap();
d.insert_object(&at(a), nested_group_of(2, shape_with_id(10, Some(b))), &CharProps::default()).unwrap();
d.insert_object(&at(b), nested_group_of(2, shape_with_id(25, Some(a))), &CharProps::default()).unwrap();
assert_eq!(d.next_shape_id(), 26);
}
#[test]
fn next_shape_id_accounts_for_shapes_in_note_separators() {
let blocks_with = |obj: InlineObject| -> Blocks {
let mut p = Paragraph::with_text("sep", CharProps::default());
p.insert_object(0, obj, &CharProps::default()).unwrap();
vec![para_block(p)]
};
// A shape ID used only in a footnote separator story must not be reissued.
let mut d = Document::from_text("body");
d.footnote_separators.separator = Some(blocks_with(shape_with_id(1, None)));
assert_eq!(d.next_shape_id(), 2);
// Every footnote and endnote separator slot is walked, including nested groups and tables.
d.footnote_separators.continuation_separator = Some(blocks_with(nested_group_of(2, shape_with_id(2, None))));
d.footnote_separators.continuation_notice = Some(nested_tables(1, blocks_with(shape_with_id(5, None))));
assert_eq!(d.next_shape_id(), 6);
d.endnote_separators.separator = Some(blocks_with(shape_with_id(9, None)));
assert_eq!(d.next_shape_id(), 10);
d.endnote_separators.continuation_separator = Some(blocks_with(nested_group_of(3, shape_with_id(14, None))));
assert_eq!(d.next_shape_id(), 15);
// Overflow fallback also respects IDs held exclusively in note-separator stories.
d.endnote_separators.continuation_notice = Some(blocks_with(nested_group_of(2, shape_with_id(u32::MAX, None))));
let allocated = d.next_shape_id();
assert_ne!(allocated, 0);
for used in [1, 2, 5, 9, 14, u32::MAX] {
assert_ne!(allocated, used);
}
assert_eq!(allocated, 3);
}
+1 -2
View File
@@ -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());
+7 -28
View File
@@ -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());
-17
View File
@@ -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}");
}
+10 -65
View File
@@ -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() },
@@ -316,13 +315,7 @@ fn styles_and_lists_round_trip() {
#[test]
fn tracked_style_definition_change_round_trips() {
let mut d = Document::new();
d.revisions.push(Revision {
kind: RevisionKind::Format,
author: "Ana".into(),
date: "2026-10-17T10:00:00Z".into(),
move_name: None,
date_utc: None,
});
d.revisions.push(Revision { kind: RevisionKind::Format, author: "Ana".into(), date: "2026-10-17T10:00:00Z".into(), move_name: None });
std::sync::Arc::make_mut(&mut d.styles).upsert(Style {
id: "Mine".into(),
name: "Mine".into(),
@@ -1011,20 +1004,8 @@ fn toc_field_skips_nested_stories() {
#[test]
fn tracked_changes_round_trip() {
let mut d = Document::new();
d.revisions.push(Revision {
kind: RevisionKind::Insert,
author: "Alice".into(),
date: "2026-05-01T10:00:00Z".into(),
move_name: None,
date_utc: None,
});
d.revisions.push(Revision {
kind: RevisionKind::Delete,
author: "Bob".into(),
date: "2026-05-02T10:00:00Z".into(),
move_name: None,
date_utc: None,
});
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Alice".into(), date: "2026-05-01T10:00:00Z".into(), move_name: None });
d.revisions.push(Revision { kind: RevisionKind::Delete, author: "Bob".into(), date: "2026-05-02T10:00:00Z".into(), move_name: None });
d.settings.track_changes = true;
let ins = CharProps { ins: Some(0), ..Default::default() };
let del = CharProps { del: Some(1), bold: Some(true), ..Default::default() };
@@ -1052,20 +1033,8 @@ fn tracked_changes_round_trip() {
fn tracked_equations_round_trip() {
// Issue #6011: equations saved with tracked revision marks (w:ins / w:del) around math.
let mut d = Document::new();
d.revisions.push(Revision {
kind: RevisionKind::Insert,
author: "Alice".into(),
date: "2026-05-01T10:00:00Z".into(),
move_name: None,
date_utc: None,
});
d.revisions.push(Revision {
kind: RevisionKind::Delete,
author: "Bob".into(),
date: "2026-05-02T10:00:00Z".into(),
move_name: None,
date_utc: None,
});
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Alice".into(), date: "2026-05-01T10:00:00Z".into(), move_name: None });
d.revisions.push(Revision { kind: RevisionKind::Delete, author: "Bob".into(), date: "2026-05-02T10:00:00Z".into(), move_name: None });
d.settings.track_changes = true;
let ins = CharProps { ins: Some(0), ..Default::default() };
let del = CharProps { del: Some(1), ..Default::default() };
@@ -1119,20 +1088,8 @@ fn tracked_equations_round_trip() {
fn nested_omath_para_revisions_read() {
// Defensive reader check: w:ins and w:del nested inside m:oMathPara.
let mut d = Document::new();
d.revisions.push(Revision {
kind: RevisionKind::Insert,
author: "Ada".into(),
date: "2026-05-01T10:00:00Z".into(),
move_name: None,
date_utc: None,
});
d.revisions.push(Revision {
kind: RevisionKind::Delete,
author: "Charles".into(),
date: "2026-05-02T10:00:00Z".into(),
move_name: None,
date_utc: None,
});
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Ada".into(), date: "2026-05-01T10:00:00Z".into(), move_name: None });
d.revisions.push(Revision { kind: RevisionKind::Delete, author: "Charles".into(), date: "2026-05-02T10:00:00Z".into(), move_name: None });
let doc_xml = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math"><w:body><w:p><m:oMathPara><w:ins w:id="1" w:author="Ada" w:date="2026-05-01T10:00:00Z"><m:oMath><m:r><m:t>x+1</m:t></m:r></m:oMath></w:ins><w:del w:id="2" w:author="Charles" w:date="2026-05-02T10:00:00Z"><m:oMath><m:r><m:t>y-1</m:t></m:r></m:oMath></w:del></m:oMathPara></w:p></w:body></w:document>"#;
let base = wordcraft_docx::write(&d).unwrap();
let bytes = replace_part(&base, "word/document.xml", doc_xml.as_bytes());
@@ -1150,20 +1107,8 @@ fn tracked_paragraph_marks_round_trip() {
// Issue #229: an inserted / deleted paragraph mark is `w:ins` / `w:del` in the mark's
// `w:rPr` (ECMA-376 §17.13.5.16, §17.13.5.15), alone or with mark formatting.
let mut d = Document::new();
d.revisions.push(Revision {
kind: RevisionKind::Insert,
author: "Alice".into(),
date: "2026-05-01T10:00:00Z".into(),
move_name: None,
date_utc: None,
});
d.revisions.push(Revision {
kind: RevisionKind::Delete,
author: "Bob".into(),
date: "2026-05-02T10:00:00Z".into(),
move_name: None,
date_utc: None,
});
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Alice".into(), date: "2026-05-01T10:00:00Z".into(), move_name: None });
d.revisions.push(Revision { kind: RevisionKind::Delete, author: "Bob".into(), date: "2026-05-02T10:00:00Z".into(), move_name: None });
let mut split = Paragraph::with_text("Owned ALPHA ", CharProps::default());
split.mark.ins = Some(0);
let mut joined = Paragraph::with_text("Owned BETA", CharProps::default());
@@ -1917,7 +1862,7 @@ fn kitchen_sink() -> Document {
let f = d.add_part(PartKind::Footnote, vec![para_block(Paragraph::with_text("Note", CharProps::default()))]);
let c = d.add_part(PartKind::Comment, vec![para_block(Paragraph::with_text("Comment", CharProps::default()))]);
d.comments.insert(3, Comment { author: "X".into(), part: c, ..Default::default() });
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "A".into(), date: String::new(), move_name: None, date_utc: None });
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "A".into(), date: String::new(), move_name: None });
d.last_section.headers.default = Some(h);
let mut blocks: Blocks = Vec::new();
let mut p = para_runs(&[
@@ -37,7 +37,7 @@ fn section_metadata_survives_native_json_and_two_docx_save_reopen_cycles() {
assert!(xml.contains(r#"<w15:footnoteColumns w:val="3"/>"#), "cycle {cycle}: {xml}");
assert!(xml.contains(r#"w:chapStyle="1" w:chapSep="hyphen""#), "cycle {cycle}: {xml}");
assert!(xml.contains(r#"w:chapStyle="10" w:chapSep="colon""#), "cycle {cycle}: {xml}");
assert!(xml.contains("xmlns:w15=") && xml.contains("mc:Ignorable=\"w14 w15 wp14 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();
-20
View File
@@ -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}");
}
+1 -1
View File
@@ -41,7 +41,7 @@ fn sample() -> Document {
let foot = d.add_part(PartKind::Footnote, vec![para_block(Paragraph::with_text("Sown in May.", CharProps::default()))]);
let com = d.add_part(PartKind::Comment, vec![para_block(Paragraph::with_text("Too short?", CharProps::default()))]);
d.comments.insert(3, Comment { author: "Bo".into(), part: com, ..Default::default() });
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Ada".into(), date: String::new(), move_name: None, date_utc: None });
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Ada".into(), date: String::new(), move_name: None });
d.last_section.headers.default = Some(head);
let mut p = Paragraph::new();
+1 -139
View File
@@ -298,8 +298,6 @@ Review|Language|Translate|review.translate
Review|Language|Language|review.language
Review|Comments|New Comment|review.newComment
Review|Comments|Delete|review.deleteComment
Review|Comments|Delete All Comments in Document|review.deleteComment
Review|Comments|Delete All Resolved Comments|review.deleteComment
Review|Comments|Previous|review.previousComment
Review|Comments|Next|review.nextComment
Review|Comments|Show Comments|review.comments
@@ -534,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
@@ -640,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 => {
@@ -662,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>();
@@ -672,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<_>>(),
})
}
@@ -697,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();
+2 -27
View File
@@ -210,21 +210,14 @@ pub fn new_revision(s: &mut Session, kind: RevisionKind) -> u32 {
.iter()
.enumerate()
.rev()
.find(|(i, r)| r.kind == kind && r.author == s.author && r.instant() == date && r.move_name.is_none() && held != Some(*i as u32))
.find(|(i, r)| r.kind == kind && r.author == s.author && r.date == date && r.move_name.is_none() && held != Some(*i as u32))
{
return i as u32;
}
s.doc.revisions.push(made_revision(kind, s.author.clone(), date));
s.doc.revisions.push(Revision { kind, author: s.author.clone(), date, move_name: None });
(s.doc.revisions.len() - 1) as u32
}
/// A revision record for a change made at `utc` (ISO 8601, UTC): dated in local wall-clock time,
/// as Word writes `w:date`, with the UTC time beside it, so a save writes it as it is (#6851).
pub fn made_revision(kind: RevisionKind, author: String, utc: String) -> Revision {
let date = crate::io_ext::word_date(&utc, local_offset_secs).unwrap_or_else(|| utc.clone());
Revision::made_at(kind, author, date, utc)
}
/// Whether the paragraph at `path` is followed by another paragraph in the same container (so
/// its paragraph mark can be removed by joining the two).
pub fn has_next_para(s: &Session, story: StoryRef, path: &wordcraft_doc::Path) -> bool {
@@ -563,10 +556,6 @@ pub fn iso_from_unix_secs(secs: u64) -> String {
/// Seconds since the Unix epoch (UTC): the system clock, or the browser's on the web.
pub fn now_unix() -> u64 {
#[cfg(test)]
if let Some(now) = TEST_NOW.with(std::cell::Cell::get) {
return now;
}
#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
{
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
@@ -588,23 +577,9 @@ pub fn now_iso() -> String {
/// The local time zone's offset from UTC in seconds (east positive) at `unix`, daylight saving
/// included: the system's zone, or the browser's on the web. 0 (UTC) when it can't be found.
pub fn local_offset_secs(unix: u64) -> i64 {
#[cfg(test)]
if let Some(zone) = TEST_ZONE.with(std::cell::Cell::get) {
return zone(unix);
}
system_offset_secs(unix).clamp(-26 * 3600, 26 * 3600)
}
#[cfg(test)]
thread_local! {
/// The clock [`now_unix`] reads on this thread in place of the system's, so a test can make
/// edits at the instants it needs.
pub static TEST_NOW: std::cell::Cell<Option<u64>> = const { std::cell::Cell::new(None) };
/// The zone [`local_offset_secs`] gives on this thread in place of the system's. CI runs on
/// UTC, where local time is UTC, so a test sets a zone that isn't to tell them apart.
pub static TEST_ZONE: std::cell::Cell<Option<fn(u64) -> i64>> = const { std::cell::Cell::new(None) };
}
#[cfg(not(target_arch = "wasm32"))]
fn system_offset_secs(unix: u64) -> i64 {
use chrono::Offset;
+1 -1
View File
@@ -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()));
}
+1 -1
View File
@@ -35,7 +35,7 @@ pub fn specs() -> Vec<CommandSpec> {
vec![
CommandSpec::new("references.sources", "Manage Sources", "References › Citations & Bibliography", sources)
.params(r#"{"add"?: Source, "remove"?: tag, "import"?: path (a Word bibliography file, `b:Sources` / `Sources.xml`)} → list"#),
CommandSpec::new("references.citation", "Insert Citation", "References › Citations & Bibliography", citation).params(r#"{"tag"?: string, "source"?: Source (added, or edited when its tag exists, and cited when no tag is given), "pages"?: string}"#),
CommandSpec::new("references.citation", "Insert Citation", "References › Citations & Bibliography", citation).params(r#"{"tag"?: string, "source"?: Source (added if new), "pages"?: string}"#),
CommandSpec::new("references.citationStyle", "Style", "References › Citations & Bibliography", |s, v| {
let st = p::str(v, "style").unwrap_or("APA");
let st = find_style(st).ok_or_else(|| {
+25 -33
View File
@@ -37,7 +37,22 @@ fn auto_tag_base(src: &Source) -> String {
/// document's sources. `import` reads a Word bibliography file (`b:Sources`, #2640).
pub(super) fn sources(s: &mut Session, v: &Value) -> CmdResult {
if let Some(a) = v.get("add") {
add_source(s, a)?;
let mut src: Source = serde_json::from_value(a.clone()).map_err(|e| CmdError::Params(e.to_string()))?;
// A new source's tag is made from its author and year; an edit keeps the tag it has.
if src.tag.is_empty() {
src.tag = auto_tag(&s.doc, &src);
}
// Edit Source keeps the source's place in the list and refreshes its citations.
match s.doc.sources.iter().position(|x| x.tag == src.tag) {
Some(i) => {
if let Some(x) = s.doc.sources.get_mut(i) {
*x = src;
}
update_citations(s)?;
}
None => s.doc.sources.push(src),
}
s.touch();
}
if let Some(t) = p::str(v, "remove") {
s.doc.sources.retain(|x| x.tag != t);
@@ -48,28 +63,6 @@ pub(super) fn sources(s: &mut Session, v: &Value) -> CmdResult {
Ok(serde_json::to_value(&s.doc.sources).unwrap_or(Value::Null))
}
/// Adds a source, or edits the one with its tag, and returns that tag (#7443).
fn add_source(s: &mut Session, a: &Value) -> Result<String, CmdError> {
let mut src: Source = serde_json::from_value(a.clone()).map_err(|e| CmdError::Params(e.to_string()))?;
// A new source's tag is made from its author and year; an edit keeps the tag it has.
if src.tag.is_empty() {
src.tag = auto_tag(&s.doc, &src);
}
let tag = src.tag.clone();
// Edit Source keeps the source's place in the list and refreshes its citations.
match s.doc.sources.iter().position(|x| x.tag == src.tag) {
Some(i) => {
if let Some(x) = s.doc.sources.get_mut(i) {
*x = src;
}
update_citations(s)?;
}
None => s.doc.sources.push(src),
}
s.touch();
Ok(tag)
}
/// The largest bibliography sources file imported from disk.
#[cfg(not(target_arch = "wasm32"))]
const MAX_SOURCES_FILE: u64 = 32 << 20;
@@ -133,16 +126,15 @@ fn import_sources(s: &mut Session, path: &str) -> Result<(), CmdError> {
}
pub(super) fn citation(s: &mut Session, v: &Value) -> CmdResult {
// The source just added or edited is the one cited when no `tag` is given, wherever it sits
// in the list (#7443).
let added = match v.get("source") {
Some(a) => Some(add_source(s, a)?),
None => None,
};
let tag = match (p::str(v, "tag"), added) {
(Some(t), _) => t.to_string(),
(None, Some(t)) => t,
(None, None) => return Err(CmdError::Params("give `tag` or `source`".into())),
if v.get("source").is_some() {
sources(s, &json!({"add": v.get("source")}))?;
}
let tag = match p::str(v, "tag") {
Some(t) => t.to_string(),
None => match v.get("source") {
Some(_) => s.doc.sources.last().map(|x| x.tag.clone()).unwrap_or_default(),
None => return Err(CmdError::Params("give `tag` or `source`".into())),
},
};
let src = s.doc.sources.iter().find(|x| x.tag == tag).cloned().ok_or_else(|| CmdError::Params(format!("no source `{tag}`")))?;
let pages = p::str(v, "pages").unwrap_or("").to_string();
-16
View File
@@ -597,22 +597,6 @@ fn editing_author_and_year_keeps_the_tag_and_updates_the_citation_text() {
assert!(f[0].1.contains("Jones") && f[0].1.contains("2021"), "{:?}", f[0].1);
}
#[test]
fn citing_an_edited_source_that_is_not_last_cites_that_source() {
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("references.sources", &json!({"add": src_of("Alice, Ann", "2000")})).unwrap();
s.run("references.sources", &json!({"add": src_of("Bob, Ben", "2001")})).unwrap();
let mut edited = src_of("Alice Edited, Ann", "2000");
edited["tag"] = json!("Ali00");
let r = s.run("references.citation", &json!({"source": edited})).unwrap();
assert_eq!(r["tag"], "Ali00");
let tags: Vec<_> = s.doc.sources.iter().map(|x| x.tag.as_str()).collect();
assert_eq!(tags, ["Ali00", "Bob01"]);
let f = fields(&s);
assert_eq!(f[0].0, "CITATION Ali00");
assert!(f[0].1.contains("Alice Edited") && f[0].1.contains("2000"), "{:?}", f[0].1);
}
#[test]
fn a_new_sources_tag_is_three_letters_and_two_year_digits() {
let mut s = Session::new(wordcraft_doc::Document::new());
+6 -36
View File
@@ -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.
+1 -1
View File
@@ -20,7 +20,7 @@ pub const MAX_AUTHOR_CHARS: usize = 255;
/// carry an author.
pub fn normalize_author(name: &str) -> Result<String, CmdError> {
let name: String = name.trim().chars().filter(|c| !c.is_control()).take(MAX_AUTHOR_CHARS).collect();
let name = name.trim();
let name = name.trim_end();
if name.is_empty() {
return Err(CmdError::Params("`name` must not be blank".into()));
}
+2 -88
View File
@@ -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]
+2 -2
View File
@@ -53,11 +53,11 @@ impl Recorder<'_> {
if let Some(r) = self.rid {
return r;
}
let found = self.revisions.iter().rposition(|r| r.kind == RevisionKind::Format && r.author == self.author && r.instant() == self.date);
let found = self.revisions.iter().rposition(|r| r.kind == RevisionKind::Format && r.author == self.author && r.date == self.date);
let r = match found {
Some(i) => i as u32,
None => {
self.revisions.push(crate::cmd::made_revision(RevisionKind::Format, self.author.clone(), self.date.clone()));
self.revisions.push(Revision { kind: RevisionKind::Format, author: self.author.clone(), date: self.date.clone(), move_name: None });
self.revisions.len().saturating_sub(1) as u32
}
};
-95
View File
@@ -1,7 +1,5 @@
//! Character formatting (Home › Font).
use std::sync::{Arc, PoisonError};
use serde_json::{Value, json};
use wordcraft_doc::eq::{EncloseShape, EncloseStyle, Enclosure};
use wordcraft_doc::props::{Border, CharProps, Highlight, Rgb, TextColor, Underline, VertAlign};
@@ -10,44 +8,8 @@ use wordcraft_doc::{InlineObject, PartKind, Pos, RevisionKind, StoryRef};
use super::sel_result;
use super::tools::{is_turkic, lower_char, upper_char};
use crate::doc_state::{ColumnBlock, Selection};
use crate::{CmdError, CmdResult, CommandSpec, Session, p};
#[derive(Clone, PartialEq)]
struct StateKey {
document_id: u64,
rev: u64,
sel: Selection,
pending: Option<CharProps>,
pending_at: Option<Pos>,
column: Option<ColumnBlock>,
font_gen: u64,
}
/// Cached result of [`cached_state`] and the session inputs it depends on.
pub(crate) struct StateCache {
key: StateKey,
value: Arc<Value>,
}
impl StateCache {
pub(crate) fn rev(&self) -> u64 {
self.key.rev
}
}
fn state_key(s: &Session) -> StateKey {
StateKey {
document_id: s.document_id(),
rev: s.rev(),
sel: s.sel.clone(),
pending: s.pending.clone(),
pending_at: s.pending_at.clone(),
column: s.column.clone(),
font_gen: wordcraft_fonts::FontDb::global().generation(),
}
}
/// Word's font size list.
pub const SIZES: [f32; 17] = [8.0, 9.0, 10.0, 10.5, 11.0, 12.0, 14.0, 16.0, 18.0, 20.0, 22.0, 24.0, 26.0, 28.0, 36.0, 48.0, 72.0];
@@ -917,30 +879,8 @@ fn set(s: &mut Session, v: &Value) -> CmdResult {
apply(s, &|c| c.overlay(&props))
}
/// What the ribbon shows: the formatting at the selection (mixed values are null), cached per
/// document revision, selection, pending caret state, column selection, and font generation.
pub fn cached_state(s: &Session) -> Arc<Value> {
let key = state_key(s);
{
let cache = s.format_state.lock().unwrap_or_else(PoisonError::into_inner);
if let Some(cached) = cache.as_ref()
&& cached.key == key
{
return Arc::clone(&cached.value);
}
}
let value = Arc::new(compute_state(s));
let mut cache = s.format_state.lock().unwrap_or_else(PoisonError::into_inner);
*cache = Some(StateCache { key, value: Arc::clone(&value) });
value
}
/// What the ribbon shows: the formatting at the selection (mixed values are null).
pub fn state(s: &Session) -> Value {
(*cached_state(s)).clone()
}
fn compute_state(s: &Session) -> Value {
let all = resolved(s);
let first = all.first().cloned();
let same = |f: &dyn Fn(&ResolvedChar) -> Value| -> Value {
@@ -966,7 +906,6 @@ fn compute_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),
@@ -988,14 +927,6 @@ fn compute_state(s: &Session) -> Value {
})
}
/// The selection's uniform highlight colour (`Some(None)` when uniformly unhighlighted), or `None`
/// when the selection is mixed or empty.
pub fn uniform_highlight(s: &Session) -> Option<Option<Rgb>> {
let all = resolved(s);
let first = all.first()?.highlight;
all.iter().all(|r| r.highlight == first).then_some(first)
}
/// What Enclose Characters works on: the selected text (one full-width or up to two half-width
/// characters), or enclosed characters already there (selected, or beside the caret).
#[derive(Clone, Debug, PartialEq)]
@@ -1123,30 +1054,4 @@ mod tests {
assert_eq!(convert("one 3.14 apples and two 2.5 pears.", "sentence", true), "One 3.14 apples and two 2.5 pears.");
assert_eq!(convert("pi is 3.14. next sentence.", "sentence", true), "Pi is 3.14. Next sentence.");
}
#[test]
fn cached_state_hits_until_selection_format_or_pending_changes() {
use serde_json::json;
use std::sync::Arc;
let mut s = crate::Session::new(wordcraft_doc::Document::new());
let a = super::cached_state(&s);
let b = super::cached_state(&s);
assert!(Arc::ptr_eq(&a, &b), "unchanged session should reuse cached format state Arc");
s.run("text.insert", &json!({"text": "hello world"})).unwrap();
let c = super::cached_state(&s);
assert!(!Arc::ptr_eq(&b, &c), "text edit bumps rev and invalidates cache");
s.run("format.bold", &json!({})).unwrap();
let d = super::cached_state(&s);
assert!(!Arc::ptr_eq(&c, &d), "pending bold changes caret formatting");
assert_eq!(d["bold"], json!(true));
assert!(Arc::ptr_eq(&d, &super::cached_state(&s)));
s.run("select.text", &json!({"text": "hello"})).unwrap();
let e = super::cached_state(&s);
assert!(!Arc::ptr_eq(&d, &e), "selection change updates format state");
assert_eq!(e["bold"], json!(false));
}
}
-196
View File
@@ -27,7 +27,6 @@ pub fn specs() -> Vec<CommandSpec> {
r#"{"type"?: "indented|runIn", "columns"?: 1-4, "rightAlign"?: bool, "tabLeader"?: "dot|hyphen|underscore|none", "headings"?: bool (letter headings)} (replaces an existing index's settings)"#,
),
CommandSpec::new("references.updateIndex", "Update Index", "References › Index", |s, _| {
check_index_reachable(s)?;
super::citations::update_generated(s)?;
sel_result(s)
}),
@@ -136,63 +135,8 @@ fn index_field(s: &Session) -> Option<(usize, String)> {
})
}
/// Whether an INDEX field (a plain one or a range field, as Word files hold it) sits in the main
/// text's own paragraphs (`main`), or anywhere else a reader sees: a table cell, a text box, a
/// header or a footer in use. Stored headers and footers no page shows (a first-page header
/// while Different First Page is off) don't count. Only an index in the main text is rebuilt.
fn has_index(s: &Session, main: bool) -> bool {
s.doc.shown_stories().into_iter().any(|story| {
s.doc
.para_paths(story)
.iter()
.filter(|path| (story == StoryRef::Body && path.depth() == 0) == main)
.filter_map(|path| s.doc.para(story, path))
.any(|p| {
p.objects.iter().any(|o| {
matches!(o, InlineObject::Field { instr, .. } | InlineObject::FieldStart { instr, .. } if FieldCode::parse(instr).name == "INDEX")
})
})
})
}
/// Refuses Insert and Update Index when the document has an index they can't rebuild, even beside
/// one in the main text, rather than adding a second index or reporting an update that left it
/// unchanged.
fn check_index_reachable(s: &Session) -> Result<(), CmdError> {
if has_index(s, false) {
return Err(CmdError::Failed(
"the index is in a table, text box, header or footer, where it can't be updated; move it into the main text, then use Update Index"
.into(),
));
}
// A range-field index after text in its paragraph is not rebuilt either: Update Index only
// takes one that starts its paragraph.
if range_index_after_text(s) {
return Err(CmdError::Failed(
"the index follows text in its paragraph, where it can't be updated; put it at the start of its own paragraph in the main text".into(),
));
}
Ok(())
}
/// Whether a main-text range-field INDEX has text before it in its paragraph.
fn range_index_after_text(s: &Session) -> bool {
s.doc.body.iter().filter_map(|b| b.as_para()).any(|p| {
p.objects_with_offsets().any(|(off, o)| {
matches!(o, InlineObject::FieldStart { instr, .. } if FieldCode::parse(instr).name == "INDEX")
&& !p.text.get(..off).is_some_and(|t| t.chars().all(|c| c.is_whitespace() || c == wordcraft_doc::para::OBJ))
})
})
}
fn insert_index(s: &mut Session, v: &Value) -> CmdResult {
let instr = index_instr(v);
check_index_reachable(s)?;
// An index Word wrote as a range field is rebuilt by Update Index; Insert Index would add a
// second one beside it (#8034).
if index_field(s).is_none() && has_index(s, true) {
return Err(CmdError::Failed("the document already has an index; use Update Index to rebuild it".into()));
}
match index_field(s) {
Some((i, _)) => {
// Settings for the index that is there: a new field code, then rebuild it.
@@ -540,144 +484,4 @@ mod tests {
let (i, _) = index_field(&s).unwrap();
assert_eq!(s.doc.body[i + 2].as_para().unwrap().props.tabs.as_ref().unwrap()[0].leader, TabLeader::Hyphen);
}
/// #3670: an index in a table cell or a text box (as imported documents have it) can't be
/// rebuilt where it is, so Insert and Update Index say so, and Insert Index doesn't add a
/// second index at the caret.
#[test]
fn an_index_outside_the_main_text_is_refused_not_doubled() {
let indexes = |s: &Session| {
std::iter::once(StoryRef::Body)
.chain(s.doc.parts.keys().map(|k| StoryRef::Part(*k)))
.flat_map(|story| s.doc.para_paths(story).into_iter().filter_map(move |path| s.doc.para(story, &path).cloned()))
.flat_map(|p| p.objects)
.filter(|o| matches!(o, InlineObject::Field { instr, .. } | InlineObject::FieldStart { instr, .. } if FieldCode::parse(instr).name == "INDEX"))
.count()
};
for in_box in [false, true] {
let mut s = Session::new(wordcraft_doc::Document::from_text(
"Kilns are hot.
End.",
));
s.run("select.text", &json!({"text": "Kilns"})).unwrap();
s.run("references.markEntry", &json!({})).unwrap();
s.run("caret.docEnd", &json!({})).unwrap();
let at = if in_box {
s.run("insert.textBox", &json!({"text": "Box"})).unwrap();
let id = s.doc.parts.iter().find(|(_, p)| p.kind == wordcraft_doc::PartKind::TextBox).map(|(id, _)| *id).unwrap();
Pos { story: StoryRef::Part(id), path: Path::top(0), off: 0 }
} else {
s.run("insert.table", &json!({"rows": 1, "cols": 1})).unwrap();
let cell = s.doc.para_paths(StoryRef::Body).into_iter().find(|path| path.depth() > 0).unwrap();
Pos { story: StoryRef::Body, path: cell, off: 0 }
};
// A range field, as a Word file holds its index.
let p = s.doc.para_mut(at.story, &at.path).unwrap();
p.insert_object(0, InlineObject::FieldEnd, &CharProps::default()).unwrap();
p.insert_object(0, InlineObject::FieldStart { instr: r#"INDEX \h "A""#.into(), locked: false, dirty: false }, &CharProps::default())
.unwrap();
s.run("caret.docEnd", &json!({})).unwrap();
let r = s.run("references.index", &json!({"columns": 2}));
assert!(r.is_err(), "Insert Index with the index in a {}: {r:?}", if in_box { "text box" } else { "table" });
assert_eq!(indexes(&s), 1, "INDEX fields after Insert Index");
assert!(s.run("references.updateIndex", &json!({})).is_err(), "Update Index reports the index it can't rebuild");
}
}
/// #3670: an index in a table is refused even when the main text also has one, so the update
/// can't report success and leave the table's index as it was.
#[test]
fn an_index_in_a_table_is_refused_beside_one_in_the_main_text() {
let mut s = Session::new(wordcraft_doc::Document::from_text("Kilns are hot."));
s.run("select.text", &json!({"text": "Kilns"})).unwrap();
s.run("references.markEntry", &json!({})).unwrap();
s.run("caret.docEnd", &json!({})).unwrap();
s.run("references.index", &json!({})).unwrap();
s.run("insert.table", &json!({"rows": 1, "cols": 1})).unwrap();
let cell = s.doc.para_paths(StoryRef::Body).into_iter().find(|path| path.depth() > 0).unwrap();
let p = s.doc.para_mut(StoryRef::Body, &cell).unwrap();
p.insert_object(0, InlineObject::FieldEnd, &CharProps::default()).unwrap();
p.insert_object(0, InlineObject::FieldStart { instr: r#"INDEX \h "A""#.into(), locked: false, dirty: false }, &CharProps::default()).unwrap();
assert!(s.run("references.index", &json!({"columns": 2})).is_err());
assert!(s.run("references.updateIndex", &json!({})).is_err());
}
/// #3670: only the headers a page shows count. An INDEX in a first-page header is out of
/// reach while Different First Page is on, and doesn't block Insert Index while it is off.
#[test]
fn an_index_in_a_header_blocks_insert_only_while_the_header_is_shown() {
let with_header_index = |first: bool, title_page: bool| {
let mut d = wordcraft_doc::Document::from_text("Kilns are hot.");
let mut p = wordcraft_doc::Paragraph::new();
p.insert_object(0, InlineObject::FieldEnd, &CharProps::default()).unwrap();
p.insert_object(0, InlineObject::FieldStart { instr: r#"INDEX \h "A""#.into(), locked: false, dirty: false }, &CharProps::default())
.unwrap();
let id = d.add_part(wordcraft_doc::PartKind::Header, vec![std::sync::Arc::new(wordcraft_doc::Block::Para(p))]);
if first {
d.last_section.headers.first = Some(id);
} else {
d.last_section.headers.default = Some(id);
}
d.last_section.title_page = title_page;
let mut s = Session::new(d);
s.run("select.text", &json!({"text": "Kilns"})).unwrap();
s.run("references.markEntry", &json!({})).unwrap();
s.run("caret.docEnd", &json!({})).unwrap();
s
};
let body_has_index = |s: &Session| index_field(s).is_some();
// Linked (default) header: shown, so Insert Index is refused.
let mut s = with_header_index(false, false);
assert!(s.run("references.index", &json!({})).is_err());
assert!(!body_has_index(&s));
// First-page header with Different First Page off: hidden, so the body gets its index.
let mut s = with_header_index(true, false);
s.run("references.index", &json!({})).unwrap();
assert!(body_has_index(&s));
// The same header with Different First Page on is shown again.
let mut s = with_header_index(true, true);
assert!(s.run("references.index", &json!({})).is_err());
assert!(!body_has_index(&s));
}
/// An index Word wrote as a range field in the main text is rebuilt by Update Index; Insert
/// Index says so instead of adding a second one (#8034).
#[test]
fn insert_index_leaves_a_range_field_index_in_the_main_text_to_update_index() {
let mut s = Session::new(wordcraft_doc::Document::from_text("Kilns are hot."));
s.run("select.text", &json!({"text": "Kilns"})).unwrap();
s.run("references.markEntry", &json!({})).unwrap();
s.run("caret.docEnd", &json!({})).unwrap();
let at = s.doc.body.len();
let mut para = wordcraft_doc::para::Paragraph::new();
para.insert_object(0, InlineObject::FieldEnd, &CharProps::default()).unwrap();
para.insert_object(0, InlineObject::FieldStart { instr: r#"INDEX \h "A""#.into(), locked: false, dirty: false }, &CharProps::default())
.unwrap();
s.doc.insert_block(StoryRef::Body, &Path::top(at), wordcraft_doc::Block::Para(para)).unwrap();
let before = s.doc.body.len();
assert!(s.run("references.index", &json!({})).is_err());
assert_eq!(s.doc.body.len(), before, "no second index was added");
s.run("references.updateIndex", &json!({})).unwrap();
let text: String =
s.doc.body.iter().filter_map(|b| b.as_para()).map(|p| p.text.replace(wordcraft_doc::para::OBJ, "")).collect::<Vec<_>>().join(
"
",
);
assert!(text.contains("Kilns are hot."), "the text before the index survives: {text:?}");
assert!(text.contains("Kilns, 1"), "Update Index generated an entry: {text:?}");
}
#[test]
fn a_range_field_index_after_text_is_refused_not_reported_updated() {
let mut s = Session::new(wordcraft_doc::Document::from_text("Kilns are hot."));
s.run("select.text", &json!({"text": "Kilns"})).unwrap();
s.run("references.markEntry", &json!({})).unwrap();
let p = s.doc.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
let end = p.len();
p.insert_object(end, InlineObject::FieldEnd, &CharProps::default()).unwrap();
p.insert_object(end, InlineObject::FieldStart { instr: r#"INDEX \h "A""#.into(), locked: false, dirty: false }, &CharProps::default())
.unwrap();
assert!(s.run("references.updateIndex", &json!({})).is_err());
assert!(s.run("references.index", &json!({})).is_err());
}
}
+2 -24
View File
@@ -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.
+1 -1
View File
@@ -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 {
+1 -4
View File
@@ -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());
}
+3 -3
View File
@@ -56,7 +56,7 @@ pub fn cut_tracked(s: &mut Session) -> Result<bool, CmdError> {
if !s.doc.settings.track_changes || !s.doc.settings.track_moves || a == b || a.story != b.story || !move_sized(&s.clipboard_text) {
return Ok(false);
}
s.doc.revisions.push(crate::cmd::made_revision(RevisionKind::Delete, s.author.clone(), now_iso()));
s.doc.revisions.push(Revision::new(RevisionKind::Delete, s.author.clone(), now_iso()));
let rid = (s.doc.revisions.len() - 1) as u32;
let at = track_delete_as(s, &a, &b, rid)?.at;
s.sel = Selection::caret(at);
@@ -75,13 +75,13 @@ pub fn take_paste(s: &mut Session, frag: &Fragment) -> Option<u32> {
return None;
}
let src = s.doc.revisions.get(m.rev as usize).filter(|r| r.kind == RevisionKind::Delete && r.move_name.is_none())?;
let (date, date_utc) = (src.date.clone(), src.date_utc.clone());
let date = src.date.clone();
let taken: BTreeSet<&str> = s.doc.revisions.iter().filter_map(|r| r.move_name.as_deref()).collect();
let name = (1..).map(|n: u64| format!("move{n}")).find(|n| !taken.contains(n.as_str()))?;
if let Some(r) = s.doc.revisions.get_mut(m.rev as usize) {
r.move_name = Some(name.clone());
}
s.doc.revisions.push(Revision { kind: RevisionKind::Insert, author: s.author.clone(), date, move_name: Some(name), date_utc });
s.doc.revisions.push(Revision { kind: RevisionKind::Insert, author: s.author.clone(), date, move_name: Some(name) });
Some((s.doc.revisions.len() - 1) as u32)
}
+2 -2
View File
@@ -200,7 +200,7 @@ pub fn specs() -> Vec<CommandSpec> {
r#"{"color": "RRGGBB" | null, "paragraph"?: bool} (text selected inside one paragraph is shaded itself, as in Word; `paragraph: true` shades the paragraphs instead, as Borders and Shading › Apply to: Paragraph)"#,
),
CommandSpec::new("para.borders", "Borders", "Home › Paragraph", borders).params(
r#"{"kind": "bottom|top|left|right|none|all|outside|inside|horizontalLine", "width"?: pt, "color"?: "RRGGBB", "style"?: "single|double|dotted|dashed|thick|triple|dotDash|wave", "sides"?: Sides} where Sides = {"top"|"left"|"bottom"|"right"|"between": {"style"?, "width"?: pt, "color"?: "RRGGBB"} | null}: exactly these sides (others off), instead of `kind` (with whole table cells selected, `kind` borders the cells as a block instead of their paragraphs)"#,
r#"{"kind": "bottom|top|left|right|none|all|outside|inside|horizontalLine", "width"?: pt, "color"?: "RRGGBB", "style"?: "single|double|dotted|dashed|thick|triple|dotDash|wave", "sides"?: Sides} where Sides = {"top"|"left"|"bottom"|"right"|"between": {"style"?, "width"?: pt, "color"?: "RRGGBB"} | null}: exactly these sides (others off), instead of `kind`"#,
),
CommandSpec::new("para.sort", "Sort", "Home › Paragraph", sort).params(r#"{"descending"?: bool}"#),
CommandSpec::new("para.keepNext", "Keep with Next", "Home › Paragraph › Line and Page Breaks", |s, v| tog(s, v, |p| p.keep_next, |p, b| p.keep_next = Some(b)))
@@ -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;
-15
View File
@@ -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(&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)
}
+24 -98
View File
@@ -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, &para.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() {
@@ -102,10 +102,6 @@ pub(super) fn borders(s: &mut Session, v: &Value) -> CmdResult {
// A paragraph with a bottom border, like Word's Horizontal Line.
return fmt(s, &|p| p.borders = Some(Borders { bottom: Some(Border { width: 1.5, ..b }), ..Default::default() }));
}
// Whole table cells selected: the border goes on the cells, not their paragraphs (#7874).
if let Some(range) = s.cell_range().cloned() {
return crate::cmd::table::cell_block_borders(s, &range, kind, b);
}
fmt(s, &|p| {
let mut cur = p.borders.unwrap_or_default();
match kind {
+3 -16
View File
@@ -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
+1 -3
View File
@@ -33,9 +33,7 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("review.editComment", "Edit Comment", "Review › Comments", edit_comment)
.params(r#"{"id": non-negative 32-bit JSON integer, "text": string}"#)
.when(comments_change),
CommandSpec::new("review.deleteComment", "Delete", "Review › Comments", delete_comment).params(
r#"{"id"?: non-negative 32-bit JSON integer (omit to use the caret), "all"?: bool (every comment), "resolved"?: bool (every resolved comment, with its replies; wins over all)}"#,
),
CommandSpec::new("review.deleteComment", "Delete", "Review › Comments", delete_comment).params(r#"{"id"?: non-negative 32-bit JSON integer (omit to use the caret), "all"?: bool}"#),
CommandSpec::new("review.resolveComment", "Resolve", "Review › Comments", |s, v| {
validate_comment_id(v)?;
let id = p::u64(v, "id").map(|x| x as u32).or_else(|| comment_at_caret(s)).ok_or_else(|| CmdError::Params("`id` required".into()))?;
+1 -2
View File
@@ -608,11 +608,10 @@ pub(super) fn list_changes(s: &mut Session, _: &Value) -> CmdResult {
list.iter()
.map(|c| {
let rev = c.rev.and_then(|r| s.doc.revisions.get(r as usize));
// The date in UTC when it is known; a file's `w:date` without it is as read.
let mut v = json!({
"kind": c.kind, "start": pos_json(&c.a), "end": pos_json(&c.b),
"text": s.doc.copy_range(&c.a, &c.b).plain_text(),
"author": rev.map(|r| r.author.clone()), "date": rev.map(|r| r.instant().to_string()),
"author": rev.map(|r| r.author.clone()), "date": rev.map(|r| r.date.clone()),
});
if c.kind == "format" {
v["description"] = json!(fmt_revisions::describe(&c.props));
+7 -11
View File
@@ -163,17 +163,17 @@ fn remove_anchors(s: &mut Session, ids: &BTreeSet<u32>) -> Result<(), CmdError>
Ok(())
}
/// The comments and every reply below them, replies to replies included (#1345), each once. A
/// parent cycle from a hostile file ends the walk instead of looping.
fn threads_of(s: &Session, roots: impl IntoIterator<Item = u32>) -> Vec<u32> {
/// The comment and every reply below it, replies to replies included (#1345). A parent cycle
/// from a hostile file ends the walk instead of looping.
fn thread_of(s: &Session, id: u32) -> Vec<u32> {
let mut children: BTreeMap<u32, Vec<u32>> = BTreeMap::new();
for (k, c) in &s.doc.comments {
if let Some(parent) = c.parent {
children.entry(parent).or_default().push(*k);
}
}
let mut seen = BTreeSet::new();
let mut ids: Vec<u32> = roots.into_iter().filter(|id| seen.insert(*id)).collect();
let mut seen = BTreeSet::from([id]);
let mut ids = vec![id];
let mut i = 0;
while let Some(&at) = ids.get(i) {
for k in children.get(&at).into_iter().flatten() {
@@ -188,15 +188,11 @@ fn threads_of(s: &Session, roots: impl IntoIterator<Item = u32>) -> Vec<u32> {
pub(super) fn delete_comment(s: &mut Session, v: &Value) -> CmdResult {
validate_comment_id(v)?;
let ids: Vec<u32> = if p::bool(v, "resolved").unwrap_or(false) {
// Delete All Resolved Comments (#7818): each resolved comment goes with its replies.
let resolved: Vec<u32> = s.doc.comments.iter().filter(|(_, c)| c.resolved).map(|(k, _)| *k).collect();
threads_of(s, resolved)
} else if p::bool(v, "all").unwrap_or(false) {
let ids: Vec<u32> = if p::bool(v, "all").unwrap_or(false) {
s.doc.comments.keys().copied().collect()
} else {
let id = p::u64(v, "id").map(|x| x as u32).or_else(|| comment_at_caret(s)).ok_or_else(|| CmdError::Params("no comment here".into()))?;
threads_of(s, [id])
thread_of(s, id)
};
remove_anchors(s, &ids.iter().copied().collect())?;
for id in &ids {
-200
View File
@@ -549,135 +549,6 @@ fn selected(s: &Session) -> (usize, usize) {
(a.off, b.off)
}
/// Two edits an hour apart in the repeated hour as daylight saving time ends are two changes,
/// though both were made at 01:30 local time: each keeps its UTC time (#6851). Rejecting one at
/// the caret leaves the other pending. Saved as DOCX or Word XML, both are dated 01:30, as Word
/// dates them, with their UTC times beside it (`w16du:dateUtc`), so they reopen as two changes,
/// and a second save writes them as read.
#[test]
fn edits_in_the_repeated_hour_stay_separate_changes() {
use crate::cmd::{TEST_NOW, TEST_ZONE};
struct Reset;
impl Drop for Reset {
fn drop(&mut self) {
TEST_NOW.with(|c| c.set(None));
TEST_ZONE.with(|z| z.set(None));
}
}
let _reset = Reset;
TEST_ZONE.with(|z| z.set(Some(crate::io_ext::tests::new_york)));
let mut s = Session::new(Document::new());
s.view.proofing = false;
s.run("document.setText", &json!({"text": "Draft."})).unwrap();
s.run("review.trackChanges", &json!({"value": true})).unwrap();
s.run("caret.docEnd", &json!({})).unwrap();
// 1 November 2026, 01:30 EDT (05:30 UTC) and then 01:30 EST (06:30 UTC).
for (now, text) in [(1_793_511_000, " One"), (1_793_514_600, " Two")] {
TEST_NOW.with(|c| c.set(Some(now)));
s.run("text.insert", &json!({"text": text})).unwrap();
}
assert_eq!(change_spans(&mut s), [("insert".into(), 6, 10), ("insert".into(), 10, 14)]);
let utc = ["2026-11-01T05:30:00Z", "2026-11-01T06:30:00Z"];
let instants = |d: &Document| d.revisions.iter().map(|r| r.instant().to_string()).collect::<Vec<_>>();
assert_eq!(instants(&s.doc), utc);
let listed = s.run("review.changes", &json!({})).unwrap();
assert_eq!(listed.as_array().map(|l| l.iter().map(|c| c["date"].clone()).collect::<Vec<_>>()), Some(vec![json!(utc[0]), json!(utc[1])]));
let local = |d: &Document| d.revisions.iter().map(|r| r.date.clone()).collect::<Vec<_>>();
for name in ["repeated.docx", "repeated.xml"] {
let bytes = crate::io::save_bytes(name, &s.doc).unwrap();
let read = |bytes: &[u8]| if name.ends_with(".xml") { wordcraft_docx::read_xml(bytes) } else { wordcraft_docx::read(bytes) }.unwrap();
let written = read(&bytes);
assert_eq!(local(&written), ["2026-11-01T01:30:00Z"; 2], "{name}");
assert_eq!(instants(&written), utc, "{name}");
let mut opened = Session::new(crate::io::open_bytes(name, &bytes).unwrap());
opened.view.proofing = false;
assert_eq!(change_spans(&mut opened), [("insert".into(), 6, 10), ("insert".into(), 10, 14)], "{name}");
// Saved again, the changes are written as read: their local time doesn't move.
let again = read(&crate::io::save_bytes(name, &opened.doc).unwrap());
assert_eq!((local(&again), instants(&again)), (local(&written), instants(&written)), "{name}");
opened.run("caret.set", &json!({"pos": {"block": 0, "off": 12}})).unwrap();
opened.run("review.reject", &json!({})).unwrap();
assert_eq!(opened.doc.plain_text(wordcraft_doc::StoryRef::Body), "Draft. One", "{name}");
assert_eq!(change_spans(&mut opened), [("insert".into(), 6, 10)], "{name}: the earlier insertion is still pending");
}
assert_eq!(instants(&s.doc), utc, "saving leaves the session's changes as they were");
s.run("caret.set", &json!({"pos": {"block": 0, "off": 12}})).unwrap();
s.run("review.reject", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(wordcraft_doc::StoryRef::Body), "Draft. One");
assert_eq!(change_spans(&mut s), [("insert".into(), 6, 10)], "the earlier insertion is still pending");
}
/// A change made at 08:33 UTC at UTC+8 is dated 16:33 in a Word file, as Word dates it, and 08:33
/// UTC in an OpenDocument file, whose `dc:date` is an instant (#6851).
#[test]
fn a_new_change_is_dated_in_utc_in_opendocument() {
use crate::cmd::{TEST_NOW, TEST_ZONE};
struct Reset;
impl Drop for Reset {
fn drop(&mut self) {
TEST_NOW.with(|c| c.set(None));
TEST_ZONE.with(|z| z.set(None));
}
}
let _reset = Reset;
TEST_ZONE.with(|z| z.set(Some(|_| 8 * 3600)));
TEST_NOW.with(|c| c.set(Some(1_794_818_004)));
let mut s = Session::new(Document::new());
s.view.proofing = false;
s.run("document.setText", &json!({"text": "Draft."})).unwrap();
s.run("review.trackChanges", &json!({"value": true})).unwrap();
s.run("caret.docEnd", &json!({})).unwrap();
s.run("text.insert", &json!({"text": " One"})).unwrap();
let utc = "2026-11-16T08:33:24Z";
let dates = |d: &Document| d.revisions.iter().map(|r| r.date.clone()).collect::<Vec<_>>();
for (name, date) in [("new.odt", utc), ("new.fodt", utc), ("new.docx", "2026-11-16T16:33:24Z"), ("new.xml", "2026-11-16T16:33:24Z")] {
let opened = crate::io::open_bytes(name, &crate::io::save_bytes(name, &s.doc).unwrap()).unwrap();
assert_eq!(dates(&opened), [date], "{name}");
assert!(opened.revisions.iter().all(|r| r.instant() == utc), "{name}: {:?}", opened.revisions);
}
}
/// A tracked change read from a file keeps its `w:date` and `w16du:dateUtc` as read through open
/// and save in another zone (#6851): one without a UTC time (an older Word, another program), whose
/// zone WordCraft doesn't guess, and one written in UTC, where the two are the same.
#[test]
fn a_file_date_is_written_as_read() {
use crate::cmd::TEST_ZONE;
struct Reset;
impl Drop for Reset {
fn drop(&mut self) {
TEST_ZONE.with(|z| z.set(None));
}
}
let _reset = Reset;
TEST_ZONE.with(|z| z.set(Some(|_| 8 * 3600)));
let date = "2026-11-16T08:33:24Z";
for utc in [None, Some(date)] {
let mut doc = Document::from_text("Draft.");
let mut rev = wordcraft_doc::Revision::new(wordcraft_doc::RevisionKind::Insert, "Ada", date);
rev.date_utc = utc.map(String::from);
doc.revisions.push(rev);
doc.para_mut(wordcraft_doc::StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap().mark.ins = Some(0);
let dates = |d: &Document| d.revisions.iter().map(|r| (r.date.clone(), r.date_utc.clone())).collect::<Vec<_>>();
let want = vec![(date.to_string(), utc.map(String::from))];
for name in ["file.docx", "file.xml"] {
let bytes = crate::io::save_bytes(name, &doc).unwrap();
let opened = crate::io::open_bytes(name, &bytes).unwrap();
assert_eq!(dates(&opened), want, "{name} {utc:?}: opened");
let saved = crate::io::save_bytes(name, &opened).unwrap();
let again = if name.ends_with(".xml") { wordcraft_docx::read_xml(&saved) } else { wordcraft_docx::read(&saved) }.unwrap();
assert_eq!(dates(&again), want, "{name} {utc:?}: saved again");
}
}
}
/// Accept and Move to Next, Reject and Move to Next: the change at the caret is resolved and
/// the next one is selected; without `next` the caret stays where the change was.
#[test]
@@ -925,77 +796,6 @@ fn deleting_a_comment_in_a_parent_cycle_ends() {
assert!(s.doc.comments.is_empty());
}
/// Comments on "one", "two" and "three" with a reply on the first; the ids, in that order.
fn three_commented_words(s: &mut Session) -> [u64; 4] {
s.view.proofing = false;
s.run("document.setText", &json!({"text": "one two three"})).unwrap();
let on = |s: &mut Session, word: &str| {
s.run("select.text", &json!({"text": word})).unwrap();
s.run("review.newComment", &json!({"text": word})).unwrap()["id"].as_u64().unwrap()
};
let (one, two, three) = (on(s, "one"), on(s, "two"), on(s, "three"));
let reply = s.run("review.reply", &json!({"id": one, "text": "reply"})).unwrap()["id"].as_u64().unwrap();
[one, reply, two, three]
}
/// #7818: Review › Delete › Delete All Resolved Comments deletes each resolved comment with its
/// replies and their text, and keeps the open ones with their anchors; Undo brings them back.
#[test]
fn delete_all_resolved_comments_keeps_the_open_ones() {
let mut s = Session::new(Document::new());
let [one, reply, two, three] = three_commented_words(&mut s);
for id in [one, three] {
s.run("review.resolveComment", &json!({"id": id, "value": true})).unwrap();
}
let part = |s: &Session, id: u64| s.doc.comments[&(id as u32)].part;
let kept_part = part(&s, two);
let gone_parts: Vec<u32> = [one, reply, three].iter().map(|id| part(&s, *id)).collect();
// The caret sits in the open comment, which Delete alone would take.
s.run("select.text", &json!({"text": "two"})).unwrap();
let depth = s.undo_depth();
let out = s.run("review.deleteComment", &json!({"resolved": true})).unwrap();
let mut deleted: Vec<u64> = out["deleted"].as_array().unwrap().iter().filter_map(|v| v.as_u64()).collect();
let mut want = vec![one, reply, three];
deleted.sort_unstable();
want.sort_unstable();
assert_eq!(deleted, want, "the resolved comments and the reply below one of them");
assert_eq!(s.doc.comments.keys().map(|k| u64::from(*k)).collect::<Vec<_>>(), vec![two], "the open comment stays");
assert!(s.doc.parts.contains_key(&kept_part));
assert!(gone_parts.iter().all(|p| !s.doc.parts.contains_key(p)), "the deleted comments' text parts are gone");
assert_eq!(anchors(&s), vec![(wordcraft_doc::StoryRef::Body, two as u32); 2], "only the open comment's anchors are left");
assert_eq!(s.undo_depth(), depth + 1, "one undo step");
s.run("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc.comments.len(), 4);
assert_eq!(anchors(&s).len(), 6);
}
/// #7818: with nothing resolved, Delete All Resolved Comments leaves every comment.
#[test]
fn delete_all_resolved_comments_without_resolved_ones_keeps_all() {
let mut s = Session::new(Document::new());
three_commented_words(&mut s);
let out = s.run("review.deleteComment", &json!({"resolved": true})).unwrap();
assert_eq!(out["deleted"], json!([]));
assert_eq!(s.doc.comments.len(), 4);
assert_eq!(anchors(&s).len(), 6);
}
/// #7818: Review › Delete › Delete All Comments in Document deletes every comment, reply and
/// anchor, resolved or not.
#[test]
fn delete_all_comments_in_document_deletes_every_comment() {
let mut s = Session::new(Document::new());
let [one, ..] = three_commented_words(&mut s);
s.run("review.resolveComment", &json!({"id": one, "value": true})).unwrap();
s.run("review.deleteComment", &json!({"all": true})).unwrap();
assert!(s.doc.comments.is_empty());
assert!(s.doc.parts.is_empty(), "no comment text is left: {:?}", s.doc.parts.keys());
assert!(anchors(&s).is_empty());
}
/// A very long reply chain (as a hostile file could hold) is deleted in one pass over the
/// comments, not one pass per reply: 50,000 replies would otherwise freeze the app.
#[test]
+1 -1
View File
@@ -26,7 +26,7 @@ use clear::{cell_prefix, guard_delete, text_spans};
use convert::{formula, from_text, quick_table, sort_table, to_text};
pub use convert::{text_table_cells, text_table_lines};
use layout::{autofit, borders, fix_caret, properties, set_column_widths};
pub(crate) use layout::{cell_block_borders, sync_cell_widths, text_direction, touch_cells};
pub(crate) use layout::{sync_cell_widths, text_direction, touch_cells};
pub(crate) use select::{extend_selection, grow_select_all, select_cell_first, select_range};
use select::{select_cells, select_column};
pub use structure::split_targets;
+2 -10
View File
@@ -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}`"))),
};
-182
View File
@@ -279,185 +279,3 @@ pub(super) fn borders(s: &mut Session, v: &Value) -> CmdResult {
}
})
}
/// Home › Paragraph › Borders with whole cells selected (the table, rows, columns or a block of
/// cells): the border goes on the cells as one block, as in Word, not on the paragraphs in them
/// (#7874). `all` borders every cell, `outside` the block's edges, `inside` the lines between its
/// cells, `none` clears every side, and one side toggles along that edge of the block. Other kinds
/// change nothing.
pub(crate) fn cell_block_borders(s: &mut Session, range: &crate::CellRange, kind: &str, b: Border) -> CmdResult {
let nil = Border { style: BorderStyle::None, width: 0.0, color: None, space: 0.0 };
let b = Border { space: 0.0, ..b };
let one_side = ["top", "left", "bottom", "right"].iter().position(|k| *k == kind);
if one_side.is_none() && !matches!(kind, "all" | "none" | "outside" | "inside") {
return sel_result(s);
}
let t = s.doc.table(range.story, &range.table).ok_or_else(|| CmdError::Disabled("the selection isn't in a table".into()))?;
let (g0, g1) = range.cols;
let picked = with_merge_runs(t, range.cells(t));
// The selected cells' grid columns, row by row from the block's first row.
let r0 = picked.iter().map(|&(r, _)| r).min().unwrap_or(range.rows.0);
let mut spans: Vec<Vec<(usize, usize)>> = Vec::new();
for &(r, c) in &picked {
let i = r.saturating_sub(r0);
if spans.len() <= i {
spans.resize_with(i + 1, Vec::new);
}
spans[i].push(super::grid_cols(t, r, c));
}
// Whether a selected cell in row `r` covers any of grid columns `a..=z`.
let picked_in = |r: Option<usize>, (a, z): (usize, usize)| {
r.and_then(|r| r.checked_sub(r0)).and_then(|i| spans.get(i)).is_some_and(|row| row.iter().any(|&(sa, sz)| sa <= z && sz >= a))
};
// Each selected cell, and which of its sides (top, left, bottom, right) are on the block's edge:
// above and below, where no selected cell lies across that side (a row that skips the selected
// grid columns with `w:gridBefore` leaves a gap in the block). A row's first and last cells are
// on it too when the row skips grid columns (`w:gridBefore`, `w:gridAfter`): the layout draws
// those as the table's outer edge.
let cells: Vec<(usize, usize, [bool; 4])> = picked
.iter()
.map(|&(r, c)| {
let (a, z) = super::grid_cols(t, r, c);
let last = t.rows.get(r).map_or(0, |row| row.cells.len().saturating_sub(1));
(r, c, [!picked_in(r.checked_sub(1), (a, z)), a <= g0 || c == 0, !picked_in(Some(r + 1), (a, z)), z >= g1 || c >= last])
})
.collect();
// Whether cell (`r`, `c`) draws a line on side `i`, its own or one the table or its style gives it.
let resolved = wordcraft_layout::CellBorders::new(&s.doc, t);
let draws = |r: usize, c: usize, i: usize| side(&resolved.of(r, c), i).is_some_and(|x| x.is_visible());
// One side is taken off when a line already shows all along that edge, drawn by the cells
// there or by cells beyond them that span the whole side, as the button toggles.
let shown = one_side.is_some_and(|i| {
cells.iter().filter(|(_, _, edge)| edge[i]).all(|&(r, c, _)| {
if draws(r, c, i) {
return true;
}
let across = beside(t, r, c, i, (g0, g1));
if matches!(i, 1 | 3) {
// The cell beside it in the row has the same height.
return !across.is_empty() && across.into_iter().all(|(nr, nc)| draws(nr, nc, (i + 2) % 4));
}
// Above or below: the cells drawing the facing line must cover the side's grid
// columns within the block, so a row that skips columns there leaves it uncovered.
let (a, z) = super::grid_cols(t, r, c);
let drawing = across.into_iter().filter(|&(nr, nc)| draws(nr, nc, (i + 2) % 4)).map(|(nr, nc)| super::grid_cols(t, nr, nc));
covers(drawing.collect(), (a.max(g0), z.min(g1)))
})
});
// The sides to set: (row, cell, side, border).
let mut writes: Vec<(usize, usize, usize, Border)> = Vec::new();
for (r, c, edge) in cells {
for (i, on_edge) in edge.into_iter().enumerate() {
let new = match kind {
"all" => Some(b),
"none" => Some(nil),
"outside" if on_edge => Some(b),
"inside" if !on_edge => Some(b),
_ if one_side == Some(i) && on_edge => Some(if shown { nil } else { b }),
_ => None,
};
let Some(new) = new else { continue };
writes.push((r, c, i, new));
// Each cell draws its own sides, so a line on the block's edge is also the facing
// side of the cell beyond it: that gets the same border, or No Border would leave
// the neighbour's line showing.
if on_edge {
writes.extend(beside(t, r, c, i, (g0, g1)).into_iter().map(|(nr, nc)| (nr, nc, (i + 2) % 4, new)));
}
}
}
let t = s.doc.table_mut(range.story, &range.table)?;
for (r, c, i, new) in writes {
let Some(cl) = t.rows.get_mut(r).and_then(|row| row.cells.get_mut(c)) else { continue };
let mut cur = cl.props.borders.unwrap_or_default();
*side_mut(&mut cur, i) = Some(new);
cl.props.borders = Some(cur);
}
touch_cells(s, &range.table)?;
sel_result(s)
}
/// Whether the grid column spans `parts` (first, last) cover every column of `a..=z`.
fn covers(mut parts: Vec<(usize, usize)>, (a, z): (usize, usize)) -> bool {
parts.sort_unstable();
let mut next = a;
for (pa, pz) in parts {
if pa > next {
break;
}
next = next.max(pz + 1);
}
next > z
}
/// `cells` with the rest of each vertically merged cell's run: the merged cell is one cell over
/// its rows, though selecting it from its first row takes in only that row.
fn with_merge_runs(t: &Table, mut cells: Vec<(usize, usize)>) -> Vec<(usize, usize)> {
// The cell starting at grid column `g` of row `r`, when there is one.
let at = |r: usize, g: usize| t.cell_at_grid(r, g).filter(|&c| t.grid_col(r, c) == g);
let continues =
|r: usize, c: usize| t.rows.get(r).and_then(|row| row.cells.get(c)).is_some_and(|x| x.props.vmerge == wordcraft_doc::props::VMerge::Continue);
let mut seen: std::collections::HashSet<(usize, usize)> = cells.iter().copied().collect();
let mut i = 0;
while let Some(&(r, c)) = cells.get(i) {
i += 1;
let g = t.grid_col(r, c);
let below = at(r + 1, g).filter(|&nc| continues(r + 1, nc)).map(|nc| (r + 1, nc));
let above = r.checked_sub(1).filter(|_| continues(r, c)).and_then(|pr| at(pr, g).map(|pc| (pr, pc)));
for next in [below, above].into_iter().flatten() {
if seen.insert(next) {
cells.push(next);
}
}
}
cells
}
/// The cells across side `i` (top, left, bottom, right) of cell (`r`, `c`) whose facing edge lies
/// wholly on that line. Above and below, only cells within grid columns `cols` (the selected
/// block's), so a wider cell's edge beyond the block keeps its line.
fn beside(t: &Table, r: usize, c: usize, i: usize, (g0, g1): (usize, usize)) -> Vec<(usize, usize)> {
let Some(row) = t.rows.get(r) else { return Vec::new() };
match i {
1 => c.checked_sub(1).map(|p| vec![(r, p)]).unwrap_or_default(),
3 => {
if c + 1 < row.cells.len() {
vec![(r, c + 1)]
} else {
Vec::new()
}
}
_ => {
let nr = if i == 0 { r.checked_sub(1) } else { Some(r + 1) };
let Some((nr, next)) = nr.and_then(|nr| t.rows.get(nr).map(|x| (nr, x))) else { return Vec::new() };
let (a, z) = super::grid_cols(t, r, c);
(0..next.cells.len())
.filter(|&nc| {
let (na, nz) = super::grid_cols(t, nr, nc);
na <= z && nz >= a && na >= g0 && nz <= g1
})
.map(|nc| (nr, nc))
.collect()
}
}
}
/// Side `i` of `b`: top, left, bottom, right.
fn side(b: &Borders, i: usize) -> Option<Border> {
match i {
0 => b.top,
1 => b.left,
2 => b.bottom,
_ => b.right,
}
}
/// Side `i` of `b` to set: top, left, bottom, right.
fn side_mut(b: &mut Borders, i: usize) -> &mut Option<Border> {
match i {
0 => &mut b.top,
1 => &mut b.left,
2 => &mut b.bottom,
_ => &mut b.right,
}
}
-1
View File
@@ -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};
+3 -9
View File
@@ -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,
}
}
+1 -1
View File
@@ -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};
+1 -1
View File
@@ -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
+1 -46
View File
@@ -98,15 +98,6 @@ pub fn save(ext: &str, doc: &Document, opts: &crate::io::ExportOptions) -> Optio
}
}
/// A UTC date and time (a `Z` or an offset) as Word writes `w:date`: the wall-clock time in the
/// zone `zone` gives for an instant (seconds east of UTC), with a `Z` Word writes but doesn't
/// mean. Word read the UTC dates WordCraft wrote as local time, shifted by the user's offset from
/// UTC (#6851). None for anything else (no zone or no time of day, before 1970, unreadable).
pub(crate) fn word_date(date: &str, zone: impl Fn(u64) -> i64) -> Option<String> {
let utc = u64::try_from(chrono::DateTime::parse_from_rfc3339(date.trim()).ok()?.timestamp()).ok()?;
Some(crate::cmd::iso_from_unix_secs(utc.checked_add_signed(zone(utc))?))
}
/// How a page image is drawn: the printed page, headers and footers at full strength, tracked
/// changes marked as Track Changes Options mark them. One place for `file.exportPng`,
/// `file.strictReport`'s page check and a downloaded page image.
@@ -143,45 +134,9 @@ pub fn render_png(doc: &Document, page: usize, scale: f32, opts: &crate::io::Exp
}
#[cfg(test)]
pub(crate) mod tests {
mod tests {
use super::*;
/// New York in 2026: daylight saving time from 8 March 07:00 UTC to 1 November 06:00 UTC.
pub(crate) fn new_york(t: u64) -> i64 {
if (1_772_953_200..1_793_512_800).contains(&t) { -4 * 3600 } else { -5 * 3600 }
}
/// Word dates `w:date` in local wall-clock time with a `Z`; the change keeps UTC (#6851).
#[test]
fn word_dates_tracked_changes_in_local_time() {
let plus8 = |_| 8 * 3600;
// The issue's edit: 08:33:24 UTC at UTC+8, which Word showed as 8:33 AM.
assert_eq!(word_date("2026-11-16T08:33:24Z", plus8).as_deref(), Some("2026-11-16T16:33:24Z"));
// A date naming its offset is that instant, whatever the zone.
assert_eq!(word_date("2026-11-16T16:33:24+08:00", plus8).as_deref(), Some("2026-11-16T16:33:24Z"));
// West of UTC, the date can go back a day.
assert_eq!(word_date("2026-01-01T03:00:00Z", new_york).as_deref(), Some("2025-12-31T22:00:00Z"));
// The repeated hour: 05:30 and 06:30 UTC are both 01:30 in New York; `dateUtc` keeps them
// apart. Either side of a change of offset takes the offset at that instant.
assert_eq!(word_date("2026-11-01T05:30:00Z", new_york).as_deref(), Some("2026-11-01T01:30:00Z"));
assert_eq!(word_date("2026-11-01T06:30:00Z", new_york).as_deref(), Some("2026-11-01T01:30:00Z"));
assert_eq!(word_date("2026-11-01T04:30:00Z", new_york).as_deref(), Some("2026-11-01T00:30:00Z"));
assert_eq!(word_date("2026-11-01T07:30:00Z", new_york).as_deref(), Some("2026-11-01T02:30:00Z"));
assert_eq!(word_date("2026-03-08T06:30:00Z", new_york).as_deref(), Some("2026-03-08T01:30:00Z"));
assert_eq!(word_date("2026-03-08T07:30:00Z", new_york).as_deref(), Some("2026-03-08T03:30:00Z"));
// Anything else is left as it is: no zone, no time of day, before 1970, not a date.
for date in ["", "2026-11-16T08:33:24", "2026-11-16", "1969-12-31T23:00:00Z", "yesterday", "2026-13-01T00:00:00Z"] {
assert_eq!(word_date(date, plus8), None, "{date:?}");
}
// A hostile zone or a far date doesn't overflow.
for zone in [i64::MAX, i64::MIN] {
let _ = word_date("2026-11-16T08:33:24Z", |_| zone);
}
assert!(word_date("9999-12-31T23:59:59Z", plus8).is_some());
}
/// A page image is the printed page: headers and footers draw at full strength (#6267).
#[test]
fn a_page_image_draws_headers_at_full_strength() {
-2
View File
@@ -149,8 +149,6 @@ pub struct Session {
/// ([`Session::why_disabled`]): computed once per document, revision and author instead of
/// for every button on every frame.
protect_facts: std::sync::Mutex<Option<((u64, u64, String), crate::cmd::protect::Facts)>>,
/// Cached result of [`crate::cmd::format::cached_state`] and the state key it was made for.
pub(crate) format_state: std::sync::Mutex<Option<crate::cmd::format::StateCache>>,
/// How many times the document's body was replaced under the same [`Self::document_id`]
/// (`document.setText`, version restore, compare, Undo/Redo). It is the body's IME
/// replacement epoch: a composition must not survive the swap, even when the new body has
-1
View File
@@ -285,7 +285,6 @@ impl Session {
last_highlight: _,
// Keyed by document id and revision, so one cache serves every document.
protect_facts: _,
format_state: _,
// The input method talks to the window, whichever document it shows; the IME
// context is keyed by `document_id`.
ime_state_revision: _,
-37
View File
@@ -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 (&section, 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();
-1
View File
@@ -131,7 +131,6 @@ impl Session {
untitled,
made_rev,
protect_facts: std::sync::Mutex::new(None),
format_state: std::sync::Mutex::new(None),
ime_body_epoch,
ime_state_revision: None,
ime_state_seen: None,
-5
View File
@@ -113,7 +113,6 @@ impl Session {
autocap: _,
rev: _,
protect_facts: _,
format_state: _,
cache: _,
layout: _,
// The word being typed, like `column`: valid only while `sel` is where typing left it.
@@ -297,10 +296,6 @@ impl Session {
if facts.as_ref().is_some_and(|((_, r, _), _)| *r != rev) {
*facts = None;
}
let format_state = self.format_state.get_mut().unwrap_or_else(std::sync::PoisonError::into_inner);
if format_state.as_ref().is_some_and(|c| c.rev() != rev) {
*format_state = None;
}
}
/// [`crate::cmd::protect::Facts`] for the document as it is now, cached per revision.
+4 -515
View File
@@ -17,7 +17,6 @@ mod find_apostrophes;
mod fit_one_page;
mod font_sizes;
mod fonts;
mod home_borders_cells;
mod ime_noop;
mod page_number_formats_in_lists;
mod para_tools;
@@ -1125,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();
@@ -2694,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
@@ -4753,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);
}
@@ -6160,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();
@@ -7968,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;
@@ -10605,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);
}
@@ -10977,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"]);
@@ -11800,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.
@@ -15257,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]
@@ -15447,7 +14996,7 @@ fn sectioned_revision(delete: bool) -> Session {
run(&mut s, "caret.set", json!({"pos": {"block": 2, "off": 0}}));
run(&mut s, "para.style", json!({"style": "Heading1"}));
let kind = if delete { RevisionKind::Delete } else { RevisionKind::Insert };
s.doc.revisions.push(Revision { kind, author: "Ada".into(), date: String::new(), move_name: None, date_utc: None });
s.doc.revisions.push(Revision { kind, author: "Ada".into(), date: String::new(), move_name: None });
s.doc.last_section.margin_left = 72.0;
let mut sect = s.doc.last_section.clone();
sect.margin_left = 144.0;
@@ -15652,63 +15201,3 @@ fn a_range_paste_formatting_keeps_the_targets_link_and_tracked_marks() {
assert!(c.ins.is_some(), "Paste Formatting kept the insertion mark");
assert_eq!(c.bold, Some(true));
}
/// #8068: A text box reachable only inside nested shape groups survives mutating Session commands
/// (which call `prune_text_boxes`) and copy/paste adoption, while an unreachable box is pruned.
#[test]
fn nested_group_text_box_survives_mutating_session_commands() {
use wordcraft_doc::para::{GroupChild, InlineObject, ShapeKind};
use wordcraft_doc::{CharProps, Document, Paragraph, PartKind, Path, para_block};
let mut d = Document::from_text("body");
let para_of = |t: &str| vec![para_block(Paragraph::with_text(t, CharProps::default()))];
let nested_tb = d.add_part(PartKind::TextBox, para_of("nested group box"));
let orphan_tb = d.add_part(PartKind::TextBox, para_of("orphan box"));
let shape = InlineObject::Shape {
kind: ShapeKind::TextBox,
w: 50.0,
h: 20.0,
fill: None,
stroke: None,
stroke_width: 0.0,
float: Default::default(),
story: Some(nested_tb),
freeform: None,
effects: Default::default(),
extra: Default::default(),
};
let group = |obj: InlineObject| InlineObject::Group {
w: 100.0,
h: 100.0,
float: Default::default(),
ch_w: 100.0,
ch_h: 100.0,
children: vec![GroupChild { x: 0.0, y: 0.0, obj }],
canvas: None,
};
d.insert_object(&Pos::body(0, 0), group(group(shape)), &CharProps::default()).unwrap();
let mut s = Session::new(d);
run(&mut s, "caret.docEnd", json!({}));
run(&mut s, "text.insert", json!({"text": " edited"}));
assert!(s.doc.parts.contains_key(&nested_tb), "nested group text box must survive prune");
assert!(!s.doc.parts.contains_key(&orphan_tb), "unreachable text box must still be pruned");
assert_eq!(s.doc.plain_text(StoryRef::Part(nested_tb)), "nested group box");
let objs = &s.doc.para(StoryRef::Body, &Path::top(0)).unwrap().objects;
assert_eq!(objs.len(), 1);
assert_eq!(objs[0].text_boxes(), vec![nested_tb]);
// Copy/paste adopts the nested-group text box into a fresh story via text_box_slots() and survives prune.
run(&mut s, "select.all", json!({}));
run(&mut s, "edit.copy", json!({}));
run(&mut s, "caret.docEnd", json!({}));
run(&mut s, "edit.paste", json!({}));
let ids: Vec<u32> = s.doc.para(StoryRef::Body, &Path::top(0)).unwrap().objects.iter().flat_map(InlineObject::text_boxes).collect();
assert_eq!(ids.len(), 2, "original and pasted nested groups each hold a text box");
assert_ne!(ids[0], ids[1], "pasted nested group box gets its own story id");
for id in ids {
assert_eq!(s.doc.plain_text(StoryRef::Part(id)), "nested group box");
}
}
@@ -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\"");
}
@@ -1,259 +0,0 @@
//! #7874: Home › Paragraph › Borders with whole table cells selected borders the cells as a
//! block, as Word does, instead of each paragraph in them.
use std::sync::Arc;
use serde_json::json;
use wordcraft_doc::props::{Border, Borders};
use wordcraft_doc::{Block, Cell, Document, Paragraph, Path, Pos, StoryRef, Table, para_block};
use crate::{Selection, Session};
/// A document of a 3 x 3 table with text in every cell, the caret in the first cell.
fn doc() -> Session {
let mut t = Table::new(3, 3, 300.0);
for (r, row) in t.rows.iter_mut().enumerate() {
for (c, cell) in row.cells.iter_mut().enumerate() {
cell.blocks = Cell::with_text(&format!("c{r}{c}")).blocks;
}
}
let mut d = Document::new();
d.body = vec![Arc::new(Block::Table(t)), para_block(Paragraph::new())];
let mut s = Session::new(d);
s.sel = Selection::caret(Pos::new(StoryRef::Body, Path(vec![0, 0, 0, 0]), 0));
s
}
fn table(s: &Session) -> &Table {
s.doc.body.iter().find_map(|b| b.as_table()).unwrap()
}
fn cell_borders(s: &Session, r: usize, c: usize) -> Borders {
table(s).rows[r].cells[c].props.borders.unwrap_or_default()
}
/// Which sides of cell (`r`, `c`) the layout draws a line on, the table style's lines included:
/// top, left, bottom, right.
fn drawn(s: &Session, r: usize, c: usize) -> [bool; 4] {
let b = wordcraft_layout::cell_borders(&s.doc, table(s), r, c);
[b.top, b.left, b.bottom, b.right].map(|x| x.is_some_and(|x| x.is_visible()))
}
/// Which sides of cell (`r`, `c`) show a line: top, left, bottom, right.
fn shown(s: &Session, r: usize, c: usize) -> [bool; 4] {
let b = cell_borders(s, r, c);
[b.top, b.left, b.bottom, b.right].map(|x| x.is_some_and(|x| x.is_visible()))
}
/// Whether any paragraph in the table has borders of its own.
fn para_borders(s: &Session) -> bool {
table(s).rows.iter().flat_map(|r| &r.cells).flat_map(|c| &c.blocks).filter_map(|b| b.as_para()).any(|p| p.props.borders.is_some())
}
fn borders(s: &mut Session, kind: &str) {
s.run("para.borders", &json!({"kind": kind})).unwrap();
}
/// Select whole cells: rows `rows` and grid columns `cols` of the table.
fn select(s: &mut Session, rows: (usize, usize), cols: (usize, usize)) {
crate::cmd::table::select_range(s, StoryRef::Body, &Path(vec![0]), rows, cols).unwrap();
}
#[test]
fn all_borders_on_a_selected_table_borders_every_cell() {
let mut s = doc();
s.run("table.selectTable", &json!({})).unwrap();
borders(&mut s, "all");
for r in 0..3 {
for c in 0..3 {
assert_eq!(shown(&s, r, c), [true; 4], "cell ({r}, {c}) has a line on every side");
}
}
assert!(!para_borders(&s), "the paragraphs in the cells get no borders of their own");
// The line is the one asked for, with no paragraph spacing.
let top = cell_borders(&s, 1, 1).top.unwrap();
assert_eq!((top.width, top.space), (0.5, 0.0));
}
#[test]
fn outside_and_inside_borders_follow_the_selected_block() {
let mut s = doc();
// The top-left 2 x 2 cells.
select(&mut s, (0, 1), (0, 1));
borders(&mut s, "outside");
assert_eq!(shown(&s, 0, 0), [true, true, false, false]);
assert_eq!(shown(&s, 0, 1), [true, false, false, true]);
assert_eq!(shown(&s, 1, 0), [false, true, true, false]);
assert_eq!(shown(&s, 1, 1), [false, false, true, true]);
assert_eq!(table(&s).rows[2].cells[2].props.borders, None, "a cell outside the selection is left alone");
// The cells beyond the block share its edge lines: their facing sides get the same line.
assert_eq!(shown(&s, 0, 2), [false, true, false, false]);
assert_eq!(shown(&s, 2, 0), [true, false, false, false]);
borders(&mut s, "inside");
assert_eq!(shown(&s, 0, 0), [true; 4]);
assert_eq!(shown(&s, 1, 1), [true; 4]);
assert_eq!(shown(&s, 0, 2), [false, true, false, false], "Inside leaves the cells beyond the block alone");
assert!(!para_borders(&s));
}
#[test]
fn no_border_on_a_row_clears_the_lines_it_shares_with_the_rows_around_it() {
let mut s = doc();
s.run("table.selectTable", &json!({})).unwrap();
borders(&mut s, "all");
select(&mut s, (1, 1), (0, 2));
borders(&mut s, "none");
for c in 0..3 {
// Each cell draws its own sides, so the rows above and below must not keep the lines.
assert_eq!(shown(&s, 0, c), [true, true, false, true], "the row above keeps its other lines, cell (0, {c})");
assert_eq!(shown(&s, 1, c), [false; 4], "cell (1, {c})");
assert_eq!(shown(&s, 2, c), [false, true, true, true], "the row below keeps its other lines, cell (2, {c})");
}
}
#[test]
fn a_row_that_skips_grid_columns_has_its_first_cell_on_the_outside() {
let mut s = doc();
// The middle row starts at grid column 1 (`w:gridBefore`): two cells.
let tb = s.doc.table_mut(StoryRef::Body, &Path(vec![0])).unwrap();
tb.rows[1].cells.remove(0);
tb.rows[1].props.grid_before = 1;
s.run("table.selectTable", &json!({})).unwrap();
borders(&mut s, "none");
borders(&mut s, "outside");
assert_eq!(shown(&s, 1, 0), [false, true, false, false], "the row's first cell is on the table's left edge");
assert_eq!(shown(&s, 1, 1), [false, false, false, true]);
borders(&mut s, "none");
borders(&mut s, "inside");
assert_eq!(shown(&s, 1, 0), [true, false, true, true], "Inside leaves the row's outer edge without a line");
}
#[test]
fn one_side_toggles_along_the_block_edge_and_no_border_clears_the_cells() {
let mut s = doc();
// The middle row, with no line on it or around it.
select(&mut s, (1, 1), (0, 2));
borders(&mut s, "none");
borders(&mut s, "bottom");
for c in 0..3 {
assert_eq!(shown(&s, 1, c), [false, false, true, false], "cell (1, {c})");
}
borders(&mut s, "bottom");
for c in 0..3 {
assert_eq!(shown(&s, 1, c), [false; 4], "the second press takes the bottom line off cell (1, {c})");
}
borders(&mut s, "all");
borders(&mut s, "none");
let nil = |x: Option<Border>| x.is_some_and(|x| !x.is_visible());
for c in 0..3 {
let b = cell_borders(&s, 1, c);
assert!(
nil(b.top) && nil(b.left) && nil(b.bottom) && nil(b.right),
"No Border writes no line on every side of cell (1, {c}), over the table's own borders"
);
}
}
#[test]
fn a_caret_in_a_cell_still_borders_its_paragraph() {
let mut s = doc();
borders(&mut s, "all");
assert!(para_borders(&s), "without whole cells selected, the paragraph is bordered as before");
assert_eq!(table(&s).rows[0].cells[0].props.borders, None);
}
/// A line the table's style draws counts as shown: the first press of one side takes it off,
/// from the cells along the edge and the ones beyond it, and the second puts it back.
#[test]
fn one_side_takes_off_a_line_the_table_style_draws() {
let mut s = doc();
assert!(table(&s).rows[1].cells.iter().all(|c| c.props.borders.is_none()), "no cell has borders of its own");
assert!((0..3).all(|c| drawn(&s, 1, c)[2]), "Table Grid draws the middle row's bottom line");
select(&mut s, (1, 1), (0, 2));
borders(&mut s, "bottom");
for c in 0..3 {
assert!(!drawn(&s, 1, c)[2] && !drawn(&s, 2, c)[0], "the first press takes the line off cell (1, {c})");
assert!(drawn(&s, 1, c)[0], "the other sides keep the style's lines, cell (1, {c})");
}
borders(&mut s, "bottom");
assert!((0..3).all(|c| drawn(&s, 1, c)[2]), "the second press puts it back");
}
/// A column whose middle row skips it (`w:gridBefore`) is two blocks of cells: the cells above
/// and below the gap face it with an outer edge, not an inside one.
#[test]
fn a_column_with_a_skipped_middle_cell_has_outer_edges_at_the_gap() {
let mut s = doc();
let tb = s.doc.table_mut(StoryRef::Body, &Path(vec![0])).unwrap();
tb.rows[1].cells.remove(0);
tb.rows[1].props.grid_before = 1;
s.run("table.selectTable", &json!({})).unwrap();
borders(&mut s, "none");
// The first grid column: cells (0, 0) and (2, 0); the middle row has no cell there.
select(&mut s, (0, 2), (0, 0));
borders(&mut s, "outside");
assert_eq!(shown(&s, 0, 0), [true; 4], "Outside draws the bottom of the cell above the gap");
assert_eq!(shown(&s, 2, 0), [true; 4], "and the top of the cell below it");
borders(&mut s, "none");
borders(&mut s, "inside");
assert_eq!(shown(&s, 0, 0), [false; 4], "Inside has no line between cells that don't meet");
assert_eq!(shown(&s, 2, 0), [false; 4]);
}
/// A line drawn along only part of an edge isn't shown along it: the press completes it. Here
/// the selected cell spans the three cells below it, and only the first of them draws its top.
#[test]
fn one_side_completes_a_line_drawn_along_part_of_the_edge() {
let mut s = doc();
let nil = Border { style: wordcraft_doc::props::BorderStyle::None, width: 0.0, color: None, space: 0.0 };
let line = Border { style: wordcraft_doc::props::BorderStyle::Single, width: 0.5, color: None, space: 0.0 };
let tb = s.doc.table_mut(StoryRef::Body, &Path(vec![0])).unwrap();
tb.rows[0].cells.truncate(1);
tb.rows[0].cells[0].props.span = 3;
tb.rows[0].cells[0].props.borders = Some(Borders { bottom: Some(nil), ..Default::default() });
for (c, cell) in tb.rows[1].cells.iter_mut().enumerate() {
cell.props.borders = Some(Borders { top: Some(if c == 0 { line } else { nil }), ..Default::default() });
}
select(&mut s, (0, 0), (0, 2));
borders(&mut s, "bottom");
assert!(drawn(&s, 0, 0)[2], "the line goes all along the selected cell's bottom");
assert!((0..3).all(|c| drawn(&s, 1, c)[0]), "and along the tops of the cells below");
}
/// A cell merged over two rows is one cell: selected from its first row, No Border clears its
/// outline in the second row too.
#[test]
fn no_border_clears_all_of_a_vertically_merged_cell() {
use wordcraft_doc::props::VMerge;
let mut s = doc();
let tb = s.doc.table_mut(StoryRef::Body, &Path(vec![0])).unwrap();
tb.rows[0].cells[1].props.vmerge = VMerge::Restart;
tb.rows[1].cells[1].props.vmerge = VMerge::Continue;
s.run("table.selectTable", &json!({})).unwrap();
borders(&mut s, "all");
// The merged cell, as selecting it from its first row selects it.
select(&mut s, (0, 0), (1, 1));
borders(&mut s, "none");
assert_eq!(shown(&s, 0, 1), [false; 4]);
assert_eq!(shown(&s, 1, 1), [false; 4], "the merged cell's second row keeps no line");
assert!(shown(&s, 1, 0)[1] && shown(&s, 2, 1)[2], "the cells around it keep their other lines");
}
/// The cells below draw a line along only part of the edge when their row skips the rest of its
/// columns (`w:gridAfter`): the press completes it.
#[test]
fn one_side_completes_a_line_over_a_row_that_skips_columns() {
let mut s = doc();
let nil = Border { style: wordcraft_doc::props::BorderStyle::None, width: 0.0, color: None, space: 0.0 };
let line = Border { style: wordcraft_doc::props::BorderStyle::Single, width: 0.5, color: None, space: 0.0 };
let tb = s.doc.table_mut(StoryRef::Body, &Path(vec![0])).unwrap();
tb.rows[0].cells.truncate(1);
tb.rows[0].cells[0].props.span = 3;
tb.rows[0].cells[0].props.borders = Some(Borders { bottom: Some(nil), ..Default::default() });
tb.rows[1].cells.truncate(1);
tb.rows[1].props.grid_after = 2;
tb.rows[1].cells[0].props.borders = Some(Borders { top: Some(line), ..Default::default() });
select(&mut s, (0, 0), (0, 2));
borders(&mut s, "bottom");
assert!(drawn(&s, 0, 0)[2], "the selected cell's bottom gets the line all along it");
}
@@ -429,7 +429,6 @@ fn tracked_separator_session(slot: Slot) -> Session {
author: "Alice".into(),
date: String::new(),
move_name: None,
date_utc: None,
});
let props = wordcraft_doc::CharProps { ins: Some(0), ..Default::default() };
let p = wordcraft_doc::Paragraph::with_text("SEP", props);
+6 -16
View File
@@ -30,27 +30,17 @@ pub fn import_flat_on(bytes: &[u8], page: &SectionProps) -> Result<Document, Str
wordcraft_docx::from_shared_model(shared).map_err(|e| e.to_string())
}
/// The shared model an OpenDocument file is written from. ODF's `dc:date` is an instant (a `Z`
/// means UTC), so a tracked change is dated by its UTC time where it is known: its `date` is the
/// local wall-clock time Word writes in `w:date` (#6851).
fn odf_model(doc: &Document) -> Result<craft_wordmodel::Document, String> {
let mut shared = wordcraft_docx::to_shared_model(doc).map_err(|e| e.to_string())?;
for r in &mut shared.revisions {
if let Some(utc) = &r.date_utc {
r.date = utc.clone();
}
}
Ok(shared)
}
pub fn export(doc: &Document) -> Result<Vec<u8>, String> {
craft_odf::text::export(&odf_model(doc)?)
let shared = wordcraft_docx::to_shared_model(doc).map_err(|e| e.to_string())?;
craft_odf::text::export(&shared)
}
pub fn export_template(doc: &Document) -> Result<Vec<u8>, String> {
craft_odf::text::export_template(&odf_model(doc)?)
let shared = wordcraft_docx::to_shared_model(doc).map_err(|e| e.to_string())?;
craft_odf::text::export_template(&shared)
}
pub fn export_flat(doc: &Document) -> Result<Vec<u8>, String> {
craft_odf::text::export_flat(&odf_model(doc)?)
let shared = wordcraft_docx::to_shared_model(doc).map_err(|e| e.to_string())?;
craft_odf::text::export_flat(&shared)
}
-13
View File
@@ -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}");
}
+2 -4
View File
@@ -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(),
-3
View File
@@ -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;
}
+15 -80
View File
@@ -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 {
+4 -12
View File
@@ -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 => {
+3 -7
View File
@@ -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;
+1 -6
View File
@@ -51,7 +51,7 @@ pub use fields::FieldCtx;
pub use hit::VisualStep;
pub use missing::{MetafileTextLayout, layout_metafile_text};
pub use para::{LineEnd, ParaLayout};
pub use table::{CellBorders, autofit_widths, cell_borders, cell_margins, measure_table_columns};
pub use table::{autofit_widths, cell_margins, measure_table_columns};
mod boxes;
mod cache;
@@ -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>,
-25
View File
@@ -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;
+2 -60
View File
@@ -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");
}
}
}
+6 -12
View File
@@ -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;
}
+9 -22
View File
@@ -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);
}
}
+4 -13
View File
@@ -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;
+3 -4
View File
@@ -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;
}
+41 -115
View File
@@ -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;
@@ -350,95 +350,6 @@ fn region_borders(parts: &[(TablePart, Borders)], rows: (usize, usize), edges: (
wordcraft_doc::styles::part_borders(parts, rows, edges)
}
/// The table's outer and inside borders: the style's, overlaid by the table's own side by side.
fn table_borders(t: &Table, style: Option<&TableStyleProps>) -> Borders {
let mut tborders = style.and_then(|s| s.parts.borders).unwrap_or_default();
if let Some(own) = t.props.borders {
tborders.overlay(&own);
}
tborders
}
/// The borders the layout draws for cell `ci` of row `ri`, before a right-to-left table mirrors
/// them: the cell's own, then its row's table property exceptions, then the table style's
/// conditional parts it is in, then the table's outer or inside borders. Home › Borders toggles
/// on these, so a line the table style shows counts as shown (#7874). For many cells of one
/// table, [`CellBorders`] resolves the table's part once.
pub fn cell_borders(doc: &wordcraft_doc::Document, t: &Table, ri: usize, ci: usize) -> Borders {
CellBorders::new(doc, t).of(ri, ci)
}
/// [`cell_borders`] for the cells of one table: its style, borders and grid width resolved once.
pub struct CellBorders<'a> {
t: &'a Table,
style: Option<TableStyleProps>,
tborders: Borders,
ncols: usize,
}
impl<'a> CellBorders<'a> {
pub fn new(doc: &wordcraft_doc::Document, t: &'a Table) -> Self {
let style = t.props.style.as_deref().and_then(|id| doc.styles.table_style(id));
let tborders = table_borders(t, style.as_ref());
CellBorders { t, style, tborders, ncols: grid_cols(t).max(1) }
}
/// The borders cell `ci` of row `ri` draws, as [`cell_borders`] gives them.
pub fn of(&self, ri: usize, ci: usize) -> Borders {
let t = self.t;
let Some(cell) = t.rows.get(ri).and_then(|row| row.cells.get(ci)) else { return Borders::default() };
let (g, span) = (t.grid_col(ri, ci), cell.span());
let look = self.style.as_ref().map(|st| region_look(st, region_of(t, Some(st), ri, g, span, self.ncols)));
resolved_cell_borders(t, ri, ci, (g, span, self.ncols), look.as_ref().map(|l| l.borders.as_slice()), self.tborders)
}
}
/// [`cell_borders`] for cell `ci` of row `ri`, which starts at grid column `g` and is `span`
/// columns wide in a table of `ncols`, given its style `parts` and the table borders `tb`.
fn resolved_cell_borders(
t: &Table,
ri: usize,
ci: usize,
(g, span, ncols): (usize, usize, usize),
parts: Option<&[(TablePart, Borders)]>,
tb: Borders,
) -> Borders {
let nrows = t.rows.len();
let Some(row) = t.rows.get(ri) else { return Borders::default() };
// Effective borders: cell > table (outer vs inside).
let edge = |own: Option<Border>, outer: bool, outer_b: Option<Border>, inner_b: Option<Border>| own.or(if outer { outer_b } else { inner_b });
let cb = row.cells.get(ci).and_then(|c| c.props.borders).unwrap_or_default();
// A row's table property exceptions (`w:tblPrEx`) override the table's borders for its cells.
let row_borders = row.props.exceptions.as_ref().and_then(|e| e.borders).unwrap_or_default();
// A row that skips grid columns (`w:gridBefore`/`w:gridAfter`) has its edge at its own
// first and last cell.
let (first_g, last_g) = (g == row.first_grid(), g + span >= ncols.saturating_sub(row.grid_after()));
let rb = parts.map(|p| region_borders(p, (ri, nrows), (first_g, last_g))).unwrap_or_default();
Borders {
top: edge(cb.top.or(if ri == 0 { row_borders.top } else { row_borders.between }).or(rb.top), ri == 0, tb.top, tb.between),
bottom: edge(
cb.bottom.or(if ri + 1 == nrows { row_borders.bottom } else { row_borders.between }).or(rb.bottom),
ri + 1 == nrows,
tb.bottom,
tb.between,
),
left: edge(
cb.left.or(if first_g { row_borders.left } else { row_borders.inside_v }).or(if first_g { rb.left } else { rb.inside_v }),
first_g,
tb.left,
tb.inside_v,
),
right: edge(
cb.right.or(if last_g { row_borders.right } else { row_borders.inside_v }).or(if last_g { rb.right } else { rb.inside_v }),
last_g,
tb.right,
tb.inside_v,
),
between: None,
inside_v: None,
}
}
struct CellBox {
items: Vec<Placed>,
h: f32,
@@ -520,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;
@@ -553,7 +458,11 @@ fn table_frame(ctx: &mut Ctx, t: &Table, avail: f32, depth: usize, style: Option
// indent); earlier modes line the first cell's text up with it instead.
let margins_def = default_margins(t, style);
let indent = t.props.indent.unwrap_or(0.0);
let tborders = table_borders(t, style);
// The style's borders, overlaid by the table's own side by side.
let mut tborders = style.and_then(|s| s.parts.borders).unwrap_or_default();
if let Some(own) = t.props.borders {
tborders.overlay(&own);
}
let first_cell = t.rows.first().and_then(|r| r.cells.first());
// A right-to-left table (`w:bidiVisual`) mirrors: its first column stands at the right, its
// start alignment and indent are measured from the right margin, and each cell's start
@@ -568,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.
@@ -584,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 }
}
@@ -649,8 +543,40 @@ pub fn layout_table(ctx: &mut Ctx, story: StoryRef, t: &Table, path: &[u32], ava
let mut cpath = path.to_vec();
cpath.push(ri as u32);
cpath.push(ci as u32);
let parts = look.map(|l| l.borders.as_slice());
let mut borders = resolved_cell_borders(t, ri, ci, (g, span, ncols), parts, tborders);
// Effective borders: cell > table (outer vs inside).
let tb = tborders;
let edge =
|own: Option<Border>, outer: bool, outer_b: Option<Border>, inner_b: Option<Border>| own.or(if outer { outer_b } else { inner_b });
let cb = cell.props.borders.unwrap_or_default();
// A row's table property exceptions (`w:tblPrEx`) override the table's borders for its cells.
let row_borders = row.props.exceptions.as_ref().and_then(|e| e.borders).unwrap_or_default();
// A row that skips grid columns (`w:gridBefore`/`w:gridAfter`) has its edge at its own
// first and last cell.
let (first_g, last_g) = (g == row.first_grid(), g + span >= ncols.saturating_sub(row.grid_after()));
let rb = look.map(|l| region_borders(&l.borders, (ri, nrows), (first_g, last_g))).unwrap_or_default();
let mut borders = Borders {
top: edge(cb.top.or(if ri == 0 { row_borders.top } else { row_borders.between }).or(rb.top), ri == 0, tb.top, tb.between),
bottom: edge(
cb.bottom.or(if ri + 1 == nrows { row_borders.bottom } else { row_borders.between }).or(rb.bottom),
ri + 1 == nrows,
tb.bottom,
tb.between,
),
left: edge(
cb.left.or(if first_g { row_borders.left } else { row_borders.inside_v }).or(if first_g { rb.left } else { rb.inside_v }),
first_g,
tb.left,
tb.inside_v,
),
right: edge(
cb.right.or(if last_g { row_borders.right } else { row_borders.inside_v }).or(if last_g { rb.right } else { rb.inside_v }),
last_g,
tb.right,
tb.inside_v,
),
between: None,
inside_v: None,
};
// The logical start (left) and end (right) borders, drawn mirrored in an RTL table.
if rtl {
std::mem::swap(&mut borders.left, &mut borders.right);
@@ -1580,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 -743
View File
@@ -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();
@@ -2129,7 +2104,6 @@ fn a_deleted_list_items_number_is_drawn_as_deleted_text() {
author: "Ana".into(),
date: String::new(),
move_name: None,
date_utc: None,
});
let id = std::sync::Arc::make_mut(&mut d.numbering).add_list(wordcraft_doc::ListKind::Numbered);
d.format_paragraphs(&Pos::body(1, 0), &Pos::body(1, 3), &|p| p.numbering = Some(wordcraft_doc::props::NumRef { num: id, level: 0 })).unwrap();
@@ -3763,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();
@@ -3956,7 +3866,6 @@ fn a_tracked_paragraph_mark_shows_in_its_authors_colour() {
author: "Ana".into(),
date: String::new(),
move_name: None,
date_utc: None,
});
d.para_mut(wordcraft_doc::StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap().mark.ins = Some(0);
let l = lay(&d);
@@ -4829,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]
@@ -7616,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(&para(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(&para(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(&center_unconstrained);
let pl_center_overfull = first_pl(&para(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(&para(&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(&para(&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(&para(&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(&para(
&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();
@@ -14723,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]
@@ -17919,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."));
}

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