Compare commits

..
362 changed files with 3551 additions and 276272 deletions
+1 -12
View File
@@ -2,15 +2,4 @@
# (#6537) and `cargo fmt --check` still passed, so the gate could not see it. Normalise on add.
* text=auto
craft-i18n.rev text eol=lf
# These model sources and generated tables have byte hashes recorded in model/README.md.
# Keep checkout bytes stable even when core.autocrlf=true.
crates/validate/model/extract_content_model.py text eol=lf
crates/validate/model/generate_model.py text eol=lf
crates/validate/model/content_model_v2.json text eol=lf
crates/validate/model/content_model_v2_transitional.json text eol=lf
crates/validate/model/content_model_dml_v2.json text eol=lf
crates/validate/model/content_model_dml_v2_transitional.json text eol=lf
crates/validate/src/model.rs text eol=lf
crates/validate/model/extract_model_lf.py text eol=lf
craft-i18n.rev text eol=lf
-16
View File
@@ -1,16 +0,0 @@
-----BEGIN PGP PUBLIC KEY BLOCK-----
mDMEaulK1xYJKwYBBAHaRw8BAQdAqHJeDCjY6Hx5FTn/hW+aqu6V394ubLk0Zj3C
bftDwFm0IkFydENyYWZ0IExpbnV4IFJlbGVhc2UgU2lnbmluZyBLZXmIkwQTFgoA
OxYhBCt2dBtBSq1s0z5jEhOgBcC518PtBQJq6UrXAhsBBQsJCAcCAiICBhUKCQgL
AgQWAgMBAh4HAheAAAoJEBOgBcC518PtGeUA/RjvULBTLlccc+2wtJkfjSnCV+cf
PUMEGmW7XkZWkk51AP9w2A/WLv+79nREWEpZzI8LGK5EjrNazP+sY0l7j5rFCLgz
BGrpStcWCSsGAQQB2kcPAQEHQPl7XkQ1gWsvSPf/T9b4m/UHcjJjBpSOtpYlWR56
er5RiO8EGBYKACAWIQQrdnQbQUqtbNM+YxIToAXAudfD7QUCaulK1wIbAgCBCRAT
oAXAudfD7XYgBBkWCgAdFiEEVo3B9o+Prsx5fzx7AG2va7DvM04FAmrpStcACgkQ
AG2va7DvM07taQEA4d2VFkKRIP0g9TrE86KpnuXPap+LKqe0tfIxpdf9YxIA/0Wo
9H/iG8nH++nxC087p3HE0S+0UovxqkhXJLSr8B4JDOoA/iLRpqTdYmk6fVXMyPJo
SkOVuwZIGS6VgBdSQP0e2P2YAP41L5OoSvwdQIG3/uNrM+ieqpYeM597/hCLFs5A
ga/qCA==
=3wGQ
-----END PGP PUBLIC KEY BLOCK-----
-107
View File
@@ -1,107 +0,0 @@
{
"schema": "craft-nightly-release-policy/v3",
"repository": "storytold/wordcraft",
"repository_id": 1408489772,
"producer_workflow_id": 429734489,
"producer_workflow_path": ".github/workflows/nightly.yml",
"producer_tooling_revision": "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": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
"release_branch": "nightly-signer",
"manual_actors": [
"bflatastic",
"dylanmtaylor",
"echelon",
"FredApps",
"skylartaylor"
],
"max_age_seconds": 86400,
"candidate_policy": {
"schema": "craft-nightly-candidate-policy/v3",
"epoch": "wordcraft-nightly-20261124",
"repository": "storytold/wordcraft",
"branch": "main",
"required_workflows": [
{
"workflow_id": 380135788,
"workflow_path": ".github/workflows/ci.yml",
"jobs": [
{
"name": "gate / gate (ubuntu-24.04)",
"app_id": 15368,
"applicability": "required"
}
]
}
],
"sonar": {
"organization": "storytold",
"project": "storytold_wordcraft",
"app_id": 12526,
"check_name": "SonarCloud Code Analysis",
"details_url": "https://sonarcloud.io/dashboard?id=storytold_wordcraft&branch=main",
"issue_types": [
"VULNERABILITY"
],
"accepted_conditions": [
{
"metric": "new_security_rating",
"comparator": "GT",
"error_threshold": "1",
"maximum": "5"
}
],
"required_conditions": [
{
"metric": "new_reliability_rating",
"comparator": "GT",
"error_threshold": "1"
},
{
"metric": "new_maintainability_rating",
"comparator": "GT",
"error_threshold": "1"
},
{
"metric": "new_coverage",
"comparator": "LT",
"error_threshold": "80"
},
{
"metric": "new_duplicated_lines_density",
"comparator": "GT",
"error_threshold": "3"
},
{
"metric": "new_security_hotspots_reviewed",
"comparator": "LT",
"error_threshold": "100"
}
],
"debt": []
}
},
"max_artifact_bytes": 2147483648,
"automatic_signer_actors": [],
"platforms": {
"windows-x86_64": {
"unsigned_artifact_name": "nightly-unsigned-windows-x86_64",
"trust": {
"publisher_subject": "CN=Learning Machines Inc, O=Learning Machines Inc, L=Atlanta, S=Georgia, C=US"
}
},
"linux-x86_64": {
"unsigned_artifact_name": "nightly-unsigned-linux-x86_64",
"trust": {
"fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"
}
},
"macos-aarch64": {
"unsigned_artifact_name": "nightly-unsigned-macos-aarch64",
"trust": {
"apple_team_id": "DJ6XS33FX8"
}
}
}
}
-227
View File
@@ -1,227 +0,0 @@
name: Nightly build check
# Builds the unsigned WordCraft Nightly the way the producer does (packaging/linux/nightly.sh,
# packaging/windows/package.ps1 -Nightly, packaging/macos/nightly.sh) and checks each archive as the
# Launcher unpacks it. No secrets and no environment: the real Nightly is signed by the shared
# release-ref signer (craft-common-actions), which calls packaging/macos/nightly-sign.sh and the
# app's sign.ps1.
on:
# The platform runners are shared with release builds: pull requests run this only with the
# `full-ci` label, never by changed paths. `labeled` so adding it starts a run.
pull_request:
types: [opened, synchronize, reopened, labeled]
workflow_dispatch:
permissions:
contents: read
# A newer push to a labelled PR cancels its older run. Any event that will not build (no `full-ci`
# label, or another label added) gets a group of its own, so it never cancels a real build.
concurrency:
group: nightly-build-${{ github.event_name == 'pull_request' && contains(github.event.pull_request.labels.*.name, 'full-ci') && (github.event.action != 'labeled' || github.event.label.name == 'full-ci') && github.ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
linux:
name: Nightly tar (x86_64, unsigned)
if: >-
github.event_name == 'workflow_dispatch' ||
(contains(github.event.pull_request.labels.*.name, 'full-ci') &&
(github.event.action != 'labeled' || github.event.label.name == 'full-ci'))
runs-on: ubuntu-latest
timeout-minutes: 120
env:
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: 0
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Install the system libraries the GUI links
run: sudo apt-get update && sudo apt-get install -y pkg-config libxkbcommon-dev libwayland-dev libx11-dev libxcursor-dev libxrandr-dev libxi-dev libgtk-3-dev libfontconfig1-dev libfreetype-dev
- name: Check out craft-fonts
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@f5141455aac7b2eb4708aa259d8ffcdf10fde939
with:
ref: b076417b5880bd4154bd22f00695b1d28c6bea83
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@f5141455aac7b2eb4708aa259d8ffcdf10fde939
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
with:
toolchain: stable
- name: Prepare a Nightly identity for this commit
shell: bash
run: |
set -euo pipefail
base="$(python3 -c 'import tomllib; print(tomllib.load(open("Cargo.toml", "rb"))["workspace"]["package"]["version"].split("-")[0])')"
sha="$(git rev-parse HEAD)"
date="$(date -u +%Y-%m-%d)"
{
echo "WORDCRAFT_BUILD_SHA=$sha"
echo "WORDCRAFT_BUILD_DATE=$date"
echo "WORDCRAFT_VERSION=$base-nightly.${date//-/}.$GITHUB_RUN_NUMBER.$GITHUB_RUN_ATTEMPT.g${sha:0:12}"
echo "WORDCRAFT_BUILD_CHANNEL=nightly-v1"
echo "CARGO_TARGET_DIR=$RUNNER_TEMP/nightly-targets"
echo "DIST=$RUNNER_TEMP/nightly-dist"
echo "CRAFT_FONTS_DIR=$GITHUB_WORKSPACE/craft-fonts"
echo "CRAFT_FONTS_REQUIRED=1"
} >>"$GITHUB_ENV"
- name: Build the unsigned Nightly tar
run: bash packaging/linux/nightly.sh --arch x86_64
- name: Check the tar as the Launcher unpacks it, and ask its version
shell: bash
run: |
set -euo pipefail
work="$RUNNER_TEMP/nightly-check"
mkdir -p "$work"
archive="$DIST/wordcraft-$WORDCRAFT_VERSION-linux-x86_64-nightly.tar.gz"
# The launcher and the GUI it starts, the icon and the notices; the embedded fonts'
# OFL-*.txt licences appear when the build has CRAFT_FONTS_DIR.
core="$(tar -tzf "$archive" | sort | grep -Ev '^OFL-[A-Za-z0-9_.-]+\.txt$' | tr '\n' ' ')"
[ "$core" = "ATTRIBUTION.md LICENSE-APACHE LICENSE-MIT NOTICE README.md wordcraft wordcraft-bin wordcraft-nightly.png " ] \
|| { echo "unexpected members: $core"; exit 1; }
tar -xzf "$archive" -C "$work"
[ -x "$work/wordcraft" ] && [ ! -L "$work/wordcraft" ]
[ "$(stat -c %a "$work/wordcraft")" = 755 ]
[ -x "$work/wordcraft-bin" ] && [ ! -L "$work/wordcraft-bin" ]
mkdir -p "$work/home" "$work/profile"
chmod 700 "$work/home" "$work/profile"
out="$(env -i HOME="$work/home" PATH=/usr/bin:/bin "$work/wordcraft" --version 2>"$work/stderr")" \
|| { cat "$work/stderr"; exit 1; }
[ ! -s "$work/stderr" ]
[ "$out" = "WordCraft $WORDCRAFT_VERSION (nightly-v1)" ]
out="$(env -i HOME="$work/home" PATH=/usr/bin:/bin "$work/wordcraft" --launch-profile nightly-v1 --profile-root "$work/profile" --version)"
[ "$out" = "WordCraft $WORDCRAFT_VERSION (nightly-v1)" ]
[ "$(head -c 2 "$work/wordcraft")" = '#!' ]
echo "==> verified (unsigned): $out"
- name: Keep the unsigned archive
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: wordcraft-nightly-linux-x86_64-unsigned
path: ${{ runner.temp }}/nightly-dist/wordcraft-${{ env.WORDCRAFT_VERSION }}-linux-x86_64-nightly.tar.gz
if-no-files-found: error
retention-days: 7
compression-level: 0
windows:
name: Nightly ZIP (x86_64, unsigned)
if: >-
github.event_name == 'workflow_dispatch' ||
(contains(github.event.pull_request.labels.*.name, 'full-ci') &&
(github.event.action != 'labeled' || github.event.label.name == 'full-ci'))
runs-on: windows-latest
timeout-minutes: 150
env:
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: 0
defaults:
run:
shell: pwsh
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Check out craft-fonts
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@f5141455aac7b2eb4708aa259d8ffcdf10fde939
with:
ref: b076417b5880bd4154bd22f00695b1d28c6bea83
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@f5141455aac7b2eb4708aa259d8ffcdf10fde939
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
with:
toolchain: stable
targets: x86_64-pc-windows-msvc
- name: Prepare a Nightly identity for this commit
shell: bash
run: |
set -euo pipefail
base="$(python3 -c 'import tomllib; print(tomllib.load(open("Cargo.toml", "rb"))["workspace"]["package"]["version"].split("-")[0])')"
sha="$(git rev-parse HEAD)"
date="$(date -u +%Y-%m-%d)"
{
echo "WORDCRAFT_BUILD_SHA=$sha"
echo "WORDCRAFT_BUILD_DATE=$date"
echo "WORDCRAFT_VERSION=$base-nightly.${date//-/}.$GITHUB_RUN_NUMBER.$GITHUB_RUN_ATTEMPT.g${sha:0:12}"
echo "WORDCRAFT_BUILD_CHANNEL=nightly-v1"
echo "CARGO_TARGET_DIR=$RUNNER_TEMP/nightly-targets"
echo "DIST=$RUNNER_TEMP/nightly-dist"
echo "CRAFT_FONTS_DIR=$GITHUB_WORKSPACE/craft-fonts"
echo "CRAFT_FONTS_REQUIRED=1"
} >>"$GITHUB_ENV"
- name: Build the unsigned Nightly intermediate
run: ./packaging/windows/package.ps1 -Arch x64 -Nightly -BuildOnly -Target x86_64-pc-windows-msvc -TargetDir $env:CARGO_TARGET_DIR -Dist $env:DIST
- name: Run the packaging contracts (no signing material)
run: ./packaging/windows/nightly-package-tests.ps1 -FixtureRoot $env:RUNNER_TEMP
- name: Run the signing contracts (dummy keys, no signing)
run: ./packaging/windows/nightly-signing-tests.ps1 -FixtureRoot $env:RUNNER_TEMP
- name: Keep the unsigned intermediate
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: wordcraft-nightly-windows-x86_64-unsigned
path: ${{ runner.temp }}/nightly-dist/wordcraft-${{ env.WORDCRAFT_VERSION }}-windows-x86_64-nightly.unsigned.zip
if-no-files-found: error
retention-days: 7
compression-level: 0
macos:
name: Nightly .app (aarch64, unsigned)
if: >-
github.event_name == 'workflow_dispatch' ||
(contains(github.event.pull_request.labels.*.name, 'full-ci') &&
(github.event.action != 'labeled' || github.event.label.name == 'full-ci'))
runs-on: macos-15
timeout-minutes: 120
env:
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: 0
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Check out craft-fonts
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@f5141455aac7b2eb4708aa259d8ffcdf10fde939
with:
ref: b076417b5880bd4154bd22f00695b1d28c6bea83
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@f5141455aac7b2eb4708aa259d8ffcdf10fde939
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
with:
toolchain: stable
targets: aarch64-apple-darwin
- name: Prepare a Nightly identity for this commit
shell: bash
run: |
set -euo pipefail
base="$(python3 -c 'import tomllib; print(tomllib.load(open("Cargo.toml", "rb"))["workspace"]["package"]["version"].split("-")[0])')"
sha="$(git rev-parse HEAD)"
date="$(date -u +%Y-%m-%d)"
{
echo "WORDCRAFT_BUILD_SHA=$sha"
echo "WORDCRAFT_BUILD_DATE=$date"
echo "WORDCRAFT_VERSION=$base-nightly.${date//-/}.$GITHUB_RUN_NUMBER.$GITHUB_RUN_ATTEMPT.g${sha:0:12}"
echo "WORDCRAFT_BUILD_CHANNEL=nightly-v1"
echo "CARGO_TARGET_DIR=$RUNNER_TEMP/nightly-targets"
echo "DIST=$RUNNER_TEMP/nightly-dist"
echo "CRAFT_FONTS_DIR=$GITHUB_WORKSPACE/craft-fonts"
echo "CRAFT_FONTS_REQUIRED=1"
} >>"$GITHUB_ENV"
- name: Build the unsigned Nightly bundle
run: bash packaging/macos/nightly.sh --arch aarch64
- name: Check the archive and the bundle version
run: bash packaging/macos/nightly-verify.sh --expect unsigned --input "$DIST/wordcraft-$WORDCRAFT_VERSION-macos-aarch64-nightly.zip"
- name: Keep the unsigned archive
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: wordcraft-nightly-macos-aarch64-unsigned
path: ${{ runner.temp }}/nightly-dist/wordcraft-${{ env.WORDCRAFT_VERSION }}-macos-aarch64-nightly.zip
if-no-files-found: error
retention-days: 7
compression-level: 0
-72
View File
@@ -1,72 +0,0 @@
name: Dispatch release-ref nightly
# Transport only, never authorization. No checkout, payload parsing or release environment.
on:
workflow_run:
workflows: [WordCraft unsigned nightly]
types: [completed]
branches: [main]
permissions: {}
jobs:
dispatch:
# SOURCE PREPARATION: literal off until immutable shared tooling and policy qualification.
if: >-
false && github.repository == 'storytold/wordcraft' &&
github.event_name == 'workflow_run'
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
actions: write
steps:
- name: Dispatch only the exact completed producer run and attempt
shell: python
env:
GH_TOKEN: ${{ github.token }}
run: |
import json
import os
import urllib.request
def require(value, message):
if not value:
raise RuntimeError(message)
# These filters reduce noise; the protected signer-branch validator repeats admission
# against authenticated API metadata and required attestation/quality evidence.
require(os.environ.get('GITHUB_REPOSITORY') == 'storytold/wordcraft', 'wrong repository')
require(os.environ.get('GITHUB_EVENT_NAME') == 'workflow_run', 'wrong event')
with open(os.environ['GITHUB_EVENT_PATH'], encoding='utf-8') as stream:
event = json.load(stream)
require(event.get('action') == 'completed', 'producer is not complete')
require(event.get('repository', {}).get('full_name') == 'storytold/wordcraft', 'wrong event repository')
producer = event.get('workflow_run', {})
require(producer.get('head_repository', {}).get('full_name') == 'storytold/wordcraft', 'foreign producer')
require(producer.get('path') == '.github/workflows/nightly.yml', 'wrong producer path')
require(producer.get('head_branch') == 'main', 'wrong producer branch')
require(producer.get('status') == 'completed' and producer.get('conclusion') == 'success', 'producer did not succeed')
# First scheduled attempt only; reviewed manual/re-run authority belongs to release policy.
require(producer.get('event') == 'schedule', 'not an automatic scheduled producer')
run_id, attempt = producer.get('id'), producer.get('run_attempt')
require(type(run_id) is int and run_id > 0, 'invalid producer run id')
require(type(attempt) is int and attempt == 1, 'invalid automatic producer attempt')
body = json.dumps({'ref': 'refs/heads/nightly-signer', 'inputs': {
'producer_run_id': str(run_id), 'producer_run_attempt': str(attempt)
}}).encode('utf-8')
request = urllib.request.Request(
'https://api.github.com/repos/storytold/wordcraft/actions/workflows/nightly-sign.yml/dispatches',
data=body, method='POST', headers={
'Authorization': 'Bearer ' + os.environ['GH_TOKEN'],
'Accept': 'application/vnd.github+json',
'Content-Type': 'application/json',
'X-GitHub-Api-Version': '2022-11-28',
'User-Agent': 'wordcraft-nightly-dispatch'
})
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
raise RuntimeError('dispatch redirects are forbidden')
# One bounded request, no retry: duplicate transport is not publication authority.
with urllib.request.build_opener(NoRedirect()).open(request, timeout=20) as response:
require(response.status == 204, 'dispatch was not accepted')
print('Dispatched producer run/attempt to the release-ref validator; not a signing result.')
-45
View File
@@ -1,45 +0,0 @@
name: WordCraft release-ref nightly signer
# Enabled for supervised manual dispatch on the dedicated nightly-signer branch, which only ever
# fast-forwards to reviewed main commits (never the stable release branch).
# A reusable callee does not change context; this must be a real top-level signer-branch dispatch.
on:
workflow_dispatch:
inputs:
producer_run_id:
description: Exact untrusted producer Actions run ID
required: true
type: string
producer_run_attempt:
description: Exact untrusted producer Actions run attempt
required: true
type: string
permissions: {}
concurrency:
group: wordcraft-nightly-release
cancel-in-progress: false
jobs:
release:
# Actual context guards: official repository, manual dispatch, real nightly-signer branch.
if: >-
github.repository == 'storytold/wordcraft' &&
github.event_name == 'workflow_dispatch' &&
github.ref == 'refs/heads/nightly-signer' && github.ref_type == 'branch'
permissions:
contents: write
actions: read
checks: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
with:
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
app-name: wordcraft
producer_run_id: ${{ inputs.producer_run_id }}
producer_run_attempt: ${{ inputs.producer_run_attempt }}
# 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.
-34
View File
@@ -1,34 +0,0 @@
name: WordCraft unsigned nightly
# 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:
workflow_dispatch:
permissions:
contents: read
jobs:
unsigned:
# Actual context guards only; no inherited/platform secrets.
if: >-
github.repository == 'storytold/wordcraft' &&
github.ref == 'refs/heads/main' && github.ref_type == 'branch' &&
(github.event_name == 'schedule' || github.event_name == 'workflow_dispatch')
# Maximum for the reusable workflow. Its compiler narrows to contents/actions read;
# no OIDC, attestation write, release environment or platform secrets in compilation.
permissions:
contents: read
actions: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
with:
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
app-name: wordcraft
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
# One producer run builds every listed platform for one all-or-nothing release. The pin is the
# craft-common-actions main commit that merged the exact-analysis admission (#371, after #370,
# #369 and #364).
platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'
+2 -25
View File
@@ -5,9 +5,9 @@ name: Packaging lint
on:
push:
branches: [main, release]
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**", ".github/nightly-signing-policy.json", ".github/nightly-linux-signing-key.asc", "sonar-project.properties"]
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**"]
pull_request:
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**", ".github/nightly-signing-policy.json", ".github/nightly-linux-signing-key.asc", "sonar-project.properties"]
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**"]
workflow_dispatch:
permissions:
@@ -49,26 +49,3 @@ jobs:
- name: Build and check non-executable installer fixtures
shell: pwsh
run: ./packaging/windows/test-install-policy.ps1 -OutputDirectory (Join-Path $env:RUNNER_TEMP 'craft-install-policy-tests')
nightly-source-contract:
name: Nightly source contracts (no build or signing)
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
contents: read
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Enforce nightly serialization and synthetic packaging contracts
run: python3 packaging/nightly-tests.py
- name: Check the Arch Nightly handoff launcher (no build)
run: bash packaging/linux/nightly-arch-tar-test.sh
- name: Render and run the Nightly tar launcher (no build)
run: bash packaging/linux/nightly-package-test.sh
- name: Check the flat Nightly tar's shared template launcher (no build)
run: bash packaging/linux/nightly-tar-launch-test.sh
-4
View File
@@ -8,7 +8,3 @@ plan/
/.claude/
/target-*/
/craft-fonts/
/.nightly-tools
/.nightly-input
/craft-i18n
__pycache__/
+69
View File
@@ -0,0 +1,69 @@
# Accessibility
Source: `standards/app-accessibility.md` in [storytold/craft-contrib](https://github.com/storytold/craft-contrib/blob/main/standards/app-accessibility.md); do not edit this copy directly. Propose changes to the shared statement in [`storytold/craft-contrib`](https://github.com/storytold/craft-contrib).
We want people who use screen readers, braille displays, screen magnifiers, voice control, high contrast, large text, reduced motion, or keyboard navigation to be able to get their work done in the Craft applications.
## Supported environments and how accessibility works
The Craft applications draw their own interface in Rust with `egui` and expose accessibility information through **AccessKit**:
- **Windows:** UI Automation (for tools such as NVDA, JAWS, and Narrator)
- **macOS:** NSAccessibility (VoiceOver)
- **Linux and FreeBSD:** AT-SPI (Orca)
- **Web (WebAssembly):** Browser accessibility tree in modern evergreen browsers
- **Display and motion:** Light and dark themes, along with ongoing work to honour system high-contrast, text-scaling, and reduced-motion settings
- **Headless and command-line workflows:** Most Craft applications also ship a command-line and automation binary (`<app>-cli`) that can inspect and edit documents from a terminal without using the graphical interface; see [This application](#this-application) below
**Current status:** The Craft suite is in early-alpha development. We use WCAG 2.2 and W3C's [WCAG2ICT](https://www.w3.org/TR/wcag2ict-22/) as practical reference points for user needs ([RFC-0014](https://github.com/storytold/craft-contrib/blob/main/rfcs/0014-accessibility.md)), while manual testing with assistive technologies across every tool and surface is still in progress.
## Known limitations and workarounds
Shared framework improvements are tracked in [storytold/craft-libs#437](https://github.com/storytold/craft-libs/issues/437). Current suite-wide gaps include:
- **Custom drawn surfaces (canvases, pages, grids, timelines, node graphs, and layer lists):** Some custom-painted views do not yet publish complete `AccessKit` nodes, caret bounds for magnifiers, or editable states (for example, `AccessKit`'s Windows adapter reporting `Document` nodes as read-only, which can prevent typing echo in screen readers). *Workaround:* Use structured inspector panels where available, or run headless commands through `<app>-cli` when a task does not need direct canvas interaction.
- **Focus in menus, toolbars, and dialogs:** Some popups, menus, or keyboard access-key overlays may leave focus in the underlying document or not yet restore focus cleanly when dismissed. *Workaround:* Press `Escape` to close open popups, `Alt` or `F10` for menu/toolbar navigation, and `F6` to move between major regions where supported.
- **Unannounced state changes:** Shortcuts or background tasks that change state away from focus do not yet consistently announce updates through a live region.
- **Pointer-heavy interactions:** Certain timeline, node-wiring, or object-placement gestures do not yet have non-dragging keyboard alternatives.
See [This application](#this-application) below for repository-specific links and details.
## Reporting an accessibility barrier
If you run into an accessibility barrier, please open an issue using the link in [This application](#this-application) below (or let us know in the [ArtCraft Discord](https://discord.gg/artcraft) if GitHub's issue form gets in the way).
- **No personal disclosure needed:** You never have to disclose a disability or explain why you use assistive technology.
- **Screenshots and recordings are optional:** Plain-text descriptions are always welcome and sufficient.
- **Helpful details to share (when convenient):**
- What you were trying to do, what happened, and what you expected
- Application version (or commit) and operating system or browser
- Input method, display settings, or assistive technology and version (for example, NVDA, JAWS, Narrator, VoiceOver, Orca, screen magnifier, high contrast, text scaling, or keyboard-only)
## How we respond
- **Triage and labels:** Maintainers and triagers label barrier reports with `accessibility` and set priority during triage based on impact—barriers that block a core workflow are treated as high-priority bugs, and barriers that risk losing work are critical.
- **Assistive-technology verification (`needs screen reader test`):** Pull requests that fix a reported assistive-technology barrier or add custom accessibility-tree or focus behaviour are labelled `needs screen reader test` so someone using assistive technology can verify a build and share what they observed; if the barrier remains, we reopen the issue.
## Note for contributors and coding agents
`ACCESSIBILITY.md` is a user-facing overview, **not** an extra rule set or audit checklist for coding agents:
- **Follow `AGENTS.md` and [`standards/accessibility.md`](https://github.com/storytold/craft-contrib/blob/main/standards/accessibility.md) for engineering work,** and keep every pull request scoped strictly to its issue. Do not widen an unrelated change to audit or rework surrounding UI.
- **Design for the actual user need—do not overbuild or apply naive readings of standards.** Accessibility guidelines exist to support real workflows and give flexible ways to meet them. Understand what a criterion genuinely requires in context before changing UI: for example, a button whose label or icon is legible and whose focus or selection ring already has clear contrast does **not** need its resting fill or border restyled to hit a 3:1 ratio, and inherently spatial or freehand tools should not have artificial keyboard grids bolted onto them.
- **Preserve visual design and shared primitives.** Use shared theme tokens and shared widgets from `storytold/craft-libs` instead of inventing one-off styling, contrast overrides, focus shims, or live-region scaffolding inside an application.
- **Be candid in pull requests.** Automated accessibility-tree checks never prove a change works with a real screen reader; describe only what was actually verified.
## Ownership
Maintained by the `craft-app-team` maintainers in [`storytold`](https://github.com/storytold). Shared updates belong in [`storytold/craft-contrib`](https://github.com/storytold/craft-contrib); repository-specific facts follow below.
## This application
**WordCraft** (`storytold/wordcraft`) is an open-source word processor written in pure Rust.
- **Published application builds:** macOS, Windows, Linux, FreeBSD, and Web (WebAssembly)
- **Command-line and automation interface:** `wordcraft-cli` provides headless terminal and automation access for scripted workflows without the graphical interface
- **Report an accessibility barrier:** [Open an issue in `storytold/wordcraft`](https://github.com/storytold/wordcraft/issues/new)
- **Tracked accessibility issues:** [Open issues labelled `accessibility` in `storytold/wordcraft`](https://github.com/storytold/wordcraft/issues?q=is%3Aissue+state%3Aopen+label%3Aaccessibility)
- **Pull requests awaiting assistive-technology verification:** [Pull requests labelled `needs screen reader test` in `storytold/wordcraft`](https://github.com/storytold/wordcraft/pulls?q=is%3Apr+label%3A%22needs+screen+reader+test%22)
- **Contributor and agent rules for this repository:** [`AGENTS.md`](AGENTS.md)
+2 -43
View File
@@ -26,12 +26,6 @@ The UI icons are SVG files in `crates/ui-egui/icons/`, one row each below. Gener
| `assets/app-icon/hicolor/scalable/apps/ai.storyteller.wordcraft.svg` | WordCraft contributors | original artwork drawn in SVG (`assets/app-icon/wordcraft.svg`), rendered by `packaging/icons.sh` | MIT OR Apache-2.0 | Placeholder app icon until the WordCraft mascot drawing lands |
| `assets/app-icon/hicolor/48x48/apps/ai.storyteller.wordcraft.png` | WordCraft contributors | original artwork drawn in SVG (`assets/app-icon/wordcraft.svg`), rendered by `packaging/icons.sh` | MIT OR Apache-2.0 | Placeholder app icon until the WordCraft mascot drawing lands |
| `assets/app-icon/hicolor/512x512/apps/ai.storyteller.wordcraft.png` | WordCraft contributors | original artwork drawn in SVG (`assets/app-icon/wordcraft.svg`), rendered by `packaging/icons.sh` | MIT OR Apache-2.0 | Placeholder app icon until the WordCraft mascot drawing lands |
| `assets/app-icon/wordcraft-nightly.png` | WordCraft contributors | derived from `assets/app-icon/hicolor/256x256/apps/ai.storyteller.wordcraft.png` by `packaging/nightly-icons.py` (nightly field `#232c67`); input hashes and the recipe are in `assets/app-icon/nightly-provenance.json` | MIT OR Apache-2.0 | Nightly 256 px render; the icon the Linux Nightly tar ships |
| `assets/app-icon/wordcraft-nightly-1024.png` | WordCraft contributors | derived from `assets/app-icon/wordcraft-1024.png` by `packaging/nightly-icons.py` | MIT OR Apache-2.0 | 1024 px master the Nightly `.icns` is generated from |
| `assets/app-icon/wordcraft-nightly.ico` | WordCraft contributors | derived from `assets/app-icon/wordcraft.ico` by `packaging/nightly-icons.py` | MIT OR Apache-2.0 | Windows Nightly icon (16-256 px), embedded by `apps/wordcraft/build.rs` into the Nightly executable only |
| `assets/app-icon/wordcraft-nightly.icns` | WordCraft contributors | derived from `assets/app-icon/wordcraft.icns` by `packaging/nightly-icons.py` | MIT OR Apache-2.0 | macOS Nightly bundle icon (`CFBundleIconFile wordcraft-nightly`) |
| `assets/app-icon/nightly-provenance.json` | WordCraft contributors | original work for this repository | MIT OR Apache-2.0 | The exact inputs, palette and transform that produced the Nightly icon set |
| `assets/app-icon/README.md` | WordCraft contributors | original description of this repository's own icon artwork | MIT OR Apache-2.0 | Names the master, the sizes and the regeneration steps |
| `assets/fonts/Inter-Medium.ttf` | Rasmus Andersson / The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) | Open-source typeface (Latin UI/document font, carried over from DesignCraft) |
| `assets/fonts/Inter-Regular.ttf` | Rasmus Andersson / The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) | Open-source typeface (Latin UI/document font, carried over from DesignCraft) |
| `assets/fonts/Inter-SemiBold.ttf` | Rasmus Andersson / The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) | Open-source typeface (Latin UI/document font, carried over from DesignCraft) |
@@ -202,7 +196,7 @@ The UI icons are SVG files in `crates/ui-egui/icons/`, one row each below. Gener
| `crates/ui-egui/icons/insertLeft.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/insertRight.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/interfaceTheme.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/italic.svg` | WordCraft contributors | original: redrawn for #7694 | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/italic.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/justify.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/labels.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/language.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
@@ -339,7 +333,6 @@ The UI icons are SVG files in `crates/ui-egui/icons/`, one row each below. Gener
| `crates/ui-egui/icons/size.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/smartArt.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/smartArtColors.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/smartArtLayouts.svg` | WordCraft contributors | original: drawn for WordCraft in the style of the code-drawn icon set (#7149) | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/sort.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/sources.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/spaceAfter.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
@@ -359,8 +352,6 @@ The UI icons are SVG files in `crates/ui-egui/icons/`, one row each below. Gener
| `crates/ui-egui/icons/table.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/tableOfAuthorities.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/tableOfFigures.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/tableStyleOptions.svg` | WordCraft contributors | original: drawn for WordCraft in the style of the code-drawn icon set (#7149) | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/tableStyles.svg` | WordCraft contributors | original: drawn for WordCraft in the style of the code-drawn icon set (#7149) | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/textBox.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/textBoxLink.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/textBoxUnlink.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
@@ -378,7 +369,7 @@ The UI icons are SVG files in `crates/ui-egui/icons/`, one row each below. Gener
| `crates/ui-egui/icons/trackChanges.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/transform.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/translate.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/underline.svg` | WordCraft contributors | original: redrawn for #7694 | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/underline.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/undo.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/unlinkCitations.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
| `crates/ui-egui/icons/update.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
@@ -398,35 +389,3 @@ The UI icons are SVG files in `crates/ui-egui/icons/`, one row each below. Gener
| craft-fonts (optional build input, not files in this repo): BIZ UDPGothic, BIZ UDMincho, Shippori Mincho, Noto Sans CJK SC, Noto Sans Arabic | see https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md | embedded only when built with `CRAFT_FONTS_DIR` (all official releases) | OFL-1.1 | Japanese and Chinese UI, Japanese document fallback |
| craft-i18n (optional build input, not files in this repo): the interface translations | see https://github.com/storytold/craft-i18n/blob/main/ATTRIBUTION.md, which credits every translator of WordCraft's former in-repo catalogs (`crates/ui-egui/src/i18n/*.tsv`, migrated at `wordcraft@806a945`) | embedded only when built with `CRAFT_I18N_DIR`, at the commit in `craft-i18n.rev` (all official releases) | MIT OR Apache-2.0 | Interface languages other than English; clean-room translations from the English interface labels |
| craft-i18n Language data (optional build input, not files in this repo): the spelling word lists and hyphenation patterns (`language-data/`: the Moby Hyphenator II list and our patterns for English, `en-extra.txt`, `en-variants.txt`, `ru-extra.txt`, and the hyph-utf8 German, Polish, Portuguese and Italian patterns) | see the Language data section of https://github.com/storytold/craft-i18n/blob/main/ATTRIBUTION.md (authors, upstream sources with SHA-256, licences); moved there from `assets/hyphenation/` and `assets/spelling/` byte for byte | embedded by craft-proof (storytold/craft-libs) only when built with `CRAFT_I18N_DIR`, at the commit in `craft-i18n.rev` (all official releases) | Public Domain / CC0-1.0, MIT, BSD-3-Clause, MIT OR Apache-2.0 (per file; see NOTICE) | Spelling and hyphenation; without it English spelling falls back to an installed Hunspell English or craft-proof's built-in Moby list, and pattern hyphenation is off |
| `crates/validate/corpus/calibration/00-control.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: valid control |
| `crates/validate/corpus/calibration/01-not-zip.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; contains no picture; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: PKG-NOT-ZIP defect fixture |
| `crates/validate/corpus/calibration/02-dup-entry.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: PKG-DUP-ENTRY defect fixture |
| `crates/validate/corpus/calibration/03-case-collision.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: PKG-CASE-COLLISION defect fixture |
| `crates/validate/corpus/calibration/04-no-content-types.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: PKG-NO-CONTENT-TYPES defect fixture |
| `crates/validate/corpus/calibration/05-no-main.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: PKG-NO-MAIN defect fixture |
| `crates/validate/corpus/calibration/06-ct-undeclared.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: CT-UNDECLARED defect fixture |
| `crates/validate/corpus/calibration/07-ct-main-type.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: CT-MAIN-TYPE defect fixture |
| `crates/validate/corpus/calibration/08-xml-malformed-main.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: XML-MALFORMED (main part) defect fixture |
| `crates/validate/corpus/calibration/09-xml-malformed-unused.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: XML-MALFORMED (unreferenced part) defect fixture |
| `crates/validate/corpus/calibration/10-xml-undeclared-prefix.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: XML-UNDECLARED-PREFIX defect fixture |
| `crates/validate/corpus/calibration/11-rel-dup-id.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: REL-DUP-ID defect fixture |
| `crates/validate/corpus/calibration/12-rel-dangling.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: REL-DANGLING defect fixture |
| `crates/validate/corpus/calibration/13-rel-typed.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: REL-TYPED defect fixture |
| `crates/validate/corpus/calibration/14-comment-dup.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: ID-COMMENT-DUP defect fixture |
| `crates/validate/corpus/calibration/15-comment-ref.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: REF-COMMENT defect fixture |
| `crates/validate/corpus/calibration/16-docpr-dup.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: ID-DOCPR-DUP defect fixture |
| `crates/validate/corpus/calibration/17-bookmark-dup.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: ID-BOOKMARK-DUP defect fixture |
| `crates/validate/corpus/calibration/18-revision-dup.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: ID-REVISION-DUP defect fixture |
| `crates/validate/corpus/calibration/19-note-ref.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: REF-NOTE defect fixture |
| `crates/validate/corpus/calibration/20-header-ref.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: REF-HEADER defect fixture |
| `crates/validate/corpus/calibration/21-style-ref.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: REF-STYLE defect fixture |
| `crates/validate/corpus/calibration/22-fld-unbalanced.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: FLD-UNBALANCED defect fixture |
| `crates/validate/corpus/calibration/23-tc-no-p.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: STRUCT-TC-NO-P defect fixture |
| `crates/validate/corpus/calibration/24-deltext.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: STRUCT-DELTEXT defect fixture |
| `crates/validate/corpus/calibration/25-move-unpaired.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: STRUCT-MOVE-UNPAIRED defect fixture |
| `crates/validate/corpus/calibration/26-media-magic.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is a fixed JPEG-header stub defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: MEDIA-MAGIC defect fixture |
| `crates/validate/model/content_model_v2.json` | WordCraft contributors | generated by `crates/validate/model/extract_content_model.py` from the ECMA-376 Part 1 (5th ed.) Strict schemas (public specification; archive URL and SHA-256 in `crates/validate/model/README.md`); the schemas themselves are not copied | MIT OR Apache-2.0, like the code (element/type content models extracted from a public specification) | wordcraft-validate grammar tables: WML, Strict |
| `crates/validate/model/content_model_v2_transitional.json` | WordCraft contributors | generated by `crates/validate/model/extract_content_model.py` from the ECMA-376 Part 4 (5th ed.) Transitional schemas (public specification; archive URL and SHA-256 in `crates/validate/model/README.md`); the schemas themselves are not copied | MIT OR Apache-2.0, like the code (element/type content models extracted from a public specification) | wordcraft-validate grammar tables: WML, Transitional |
| `crates/validate/model/content_model_dml_v2.json` | WordCraft contributors | generated by `crates/validate/model/extract_content_model.py --profile dml` from the ECMA-376 Part 1 (5th ed.) Strict schemas (public specification; archive URL and SHA-256 in `crates/validate/model/README.md`); the schemas themselves are not copied | MIT OR Apache-2.0, like the code (element/type content models extracted from a public specification) | wordcraft-validate grammar tables: DrawingML, Strict |
| `crates/validate/model/content_model_dml_v2_transitional.json` | WordCraft contributors | generated by `crates/validate/model/extract_content_model.py --profile dml` from the ECMA-376 Part 4 (5th ed.) Transitional schemas (public specification; archive URL and SHA-256 in `crates/validate/model/README.md`); the schemas themselves are not copied | MIT OR Apache-2.0, like the code (element/type content models extracted from a public specification) | wordcraft-validate grammar tables: DrawingML, Transitional |
| `crates/validate/src/model.rs` | WordCraft contributors | generated by `crates/validate/model/generate_model.py` from the four `crates/validate/model/content_model_*.json` tables above and the `ST_NumberFormat` enumeration of the ECMA-376 Part 1 Strict `wml.xsd` | MIT OR Apache-2.0, like the code (data extracted from a public specification) | wordcraft-validate grammar tables compiled into the crate |
Generated
+120 -354
View File
File diff suppressed because it is too large Load Diff
+52 -59
View File
@@ -37,33 +37,26 @@ 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 = "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-proof = { package = "craft-proof", git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
craft-ssip = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
wordcraft-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 = "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" }
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
craft = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0", default-features = false }
craft-ui-test-kit = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
# foundation
kurbo = { version = "0.13", features = ["serde"] }
thiserror = "2"
# Command lines: clap derive types, with completions and man pages generated from them (RFC-0018).
clap = { version = "4", features = ["derive", "env"] }
clap_complete = "4"
clap_mangen = "0.2"
serde = { version = "1", features = ["derive", "rc"] }
serde_json = { version = "1", features = ["float_roundtrip"] }
quick-xml = "0.41"
zip = { version = "3", default-features = false, features = ["deflate"] }
log = "0.4"
# All date/time conversion goes through chrono (no hand-rolled calendar code beyond the 400-year range extension; AGENTS.md).
chrono = { version = "0.4.45", default-features = false, features = ["std"] }
@@ -88,28 +81,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 = "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-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0", default-features = false, features = ["write"] }
craft-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" }
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0", features = ["doc"] }
craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
craft-flow = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
craft-odf = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0", features = ["text"] }
craft-markdown = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
craft-html = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0", features = ["flow"] }
craft-latex = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0", features = ["detect"] }
craft-sheet = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
# 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"
@@ -177,27 +170,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 = "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" }
krilla = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49" }
hayro = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
emath = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
egui = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
-13
View File
@@ -66,16 +66,3 @@ _Avoid_: Tofu, box, notdef character
A picture the document refers to that the output cannot include: its part is absent, its data
cannot be decoded, its format is unsupported, or it is linked from outside the file.
_Avoid_: Broken image, dropped image
## Windows
**Document window**:
A top-level window showing one open document. A document can be shown in several document windows
at once (View › New Window); each window shows exactly one.
_Avoid_: Viewport (that is the framework's surface), root window, tab
**Save prompt**:
The question "Save changes?" asked when the last document window showing a document with unsaved
changes is about to close. It belongs to that window and appears there; while it is up, the other
windows wait.
_Avoid_: Close guard, save dialog, unsaved-changes dialog
+7 -18
View File
@@ -157,7 +157,7 @@ Command line:
```sh
wordcraft-cli convert report.docx report.pdf # docx, pdf, odt, rtf, html, md, tex, txt, png
wordcraft-cli convert report.docx report.pdf --strict # exit 1, no file, if a character or picture would be left out
wordcraft-cli convert report.docx report.pdf --strict # exit 3, no file, if a character or picture would be left out
wordcraft-cli text report.docx # plain text
wordcraft-cli inspect report.docx # structure as JSON
wordcraft-cli run --template sample \
@@ -165,27 +165,16 @@ wordcraft-cli run --template sample \
wordcraft-cli run --script job.json # the same from a file: commands, then save to docx and pdf
```
`wordcraft-cli` follows [RFC-0018](https://github.com/storytold/craft-contrib/blob/main/rfcs/0018-cli-conventions.md)
(command-line conventions); `wordcraft-cli --help` and `<subcommand> --help` are the reference for every flag. Exit status:
0 success, 1 the command failed, 2 a usage error (an unknown or repeated flag, a bad value, flags that conflict or that a
subcommand doesn't take, all checked before any file is opened), and 128 plus the signal number when a signal ends the
process. Errors are `error: <message>` on stderr; results are on stdout. `--version`/`-V` work on every subcommand and there
is no `version` subcommand. `WORDCRAFT_PASSWORD` is read by `--password` (a flag wins, an empty variable counts as unset,
and `--help` never shows its value); `WORDCRAFT_REGION` sets the paper. The Linux packages (deb, rpm and tar.gz) and the
FreeBSD package install the man pages and the bash, zsh and fish completions.
`convert --strict` (a `.pdf` or `.png` output only) and `render --strict` (a PNG of one page) refuse a silently incomplete render: they exit 1
`convert --strict` (a `.pdf` or `.png` output only) and `render --strict` (a PNG of one page) refuse a silently incomplete render: they exit 3
and write nothing if the output would draw a character no font has (an empty box) or leave out a
picture. Exit codes are 0 (written) and 1 (unreadable input or a strict refusal); `--strict` with another
output type is a usage error (2), checked before the input is read. On a strict refusal, stderr has one
`error: strict: …` line per kind, then one JSON line. (Before RFC-0018 a strict refusal exited 3; RFC-0018 has no code 3.)
`validate` exits 0 for PASS and 1 for FAIL, INCOMPLETE or a file it can't read: the verdict is the first line of the report
(`verdict` with `--json`).
picture. Exit codes are 0 (written), 1 (unreadable input, usage error, or `--strict` with another
output type, checked before the input is read) and 3 (strict refusal). On exit 3, stderr has one
`wordcraft-cli: strict: …` line per kind, then one JSON line:
```sh
wordcraft-cli convert in.docx out.pdf --strict
# error: strict: 1 character cannot be drawn: U+2D30 (×3)
# error: strict: 1 picture(s) left out: word/media/image2.bin (header2.xml): unsupported format
# wordcraft-cli: strict: 1 character cannot be drawn: U+2D30 (×3)
# wordcraft-cli: strict: 1 picture(s) left out: word/media/image2.bin (header2.xml): unsupported format
# {"schema":1,"strict":"failed","missing_glyphs":[{"cp":"U+2D30","count":3}],"missing_pictures":[{"part":"word/media/image2.bin","source_part":"word/header2.xml","reason":"unsupported_format"}],"truncated":false,"total_missing_glyphs":1,"total_missing_pictures":1,"glyphs_truncated":false,"pictures_truncated":false}
```
+628 -664
View File
File diff suppressed because one or more lines are too long
-9
View File
@@ -6,9 +6,6 @@ license.workspace = true
publish = false
description = "WordCraft command line: convert, inspect, render, run commands, MCP server"
[lib]
path = "src/lib.rs"
[[bin]]
name = "wordcraft-cli"
path = "src/main.rs"
@@ -22,17 +19,11 @@ wordcraft-engine = { workspace = true }
wordcraft-render = { workspace = true }
wordcraft-mcp = { workspace = true }
wordcraft-zotero = { workspace = true }
wordcraft-validate = { workspace = true }
serde_json = { workspace = true }
sys-locale = "0.3"
thiserror = { workspace = true }
clap = { workspace = true }
[dev-dependencies]
wordcraft-fonts = { workspace = true }
wordcraft-geom = { workspace = true, features = ["image"] }
image = { workspace = true }
craft-zip = { workspace = true }
# The completions and man pages (examples/man-and-completions.rs), generated from the clap definition.
clap_complete = { workspace = true }
clap_mangen = { workspace = true }
@@ -1,42 +0,0 @@
//! Writes wordcraft-cli's shell completions ([`clap_complete`]: bash, zsh, fish, elvish,
//! PowerShell) and man pages ([`clap_mangen`]: `wordcraft-cli.1` and one per subcommand, such as
//! `wordcraft-cli-run.1`) into a directory. The Linux and FreeBSD packages ship them
//! (see `packaging/`):
//!
//! ```sh
//! cargo run -p wordcraft-cli --example man-and-completions -- <out-dir>
//! ```
use std::path::Path;
use std::process::ExitCode;
use clap::ValueEnum;
use clap_complete::Shell;
fn main() -> ExitCode {
let mut args = std::env::args_os().skip(1);
let (Some(dir), None) = (args.next(), args.next()) else {
eprintln!("usage: man-and-completions <out-dir>");
return ExitCode::from(2);
};
let dir = Path::new(&dir);
match generate(dir) {
Ok(()) => ExitCode::SUCCESS,
Err(e) => {
eprintln!("error: {}: {e}", dir.display());
ExitCode::FAILURE
}
}
}
/// Also run by the tests.
pub(crate) fn generate(dir: &Path) -> std::io::Result<()> {
std::fs::create_dir_all(dir)?;
let mut cmd = wordcraft_cli::command();
for &shell in Shell::value_variants() {
clap_complete::generate_to(shell, &mut cmd, "wordcraft-cli", dir)?;
}
// A fresh command: `clap_complete::generate_to` built `cmd`, adding the `help` subcommand,
// which `clap_mangen` would otherwise give pages of its own (`wordcraft-cli-help-convert.1`).
clap_mangen::generate_to(wordcraft_cli::command(), dir)
}
-343
View File
@@ -1,343 +0,0 @@
//! The command line as clap derive types (RFC-0018). Values arrive typed, so the commands never validate a string; what
//! clap cannot say alone is a [`UsageError`], printed and exited like clap's own.
use std::ffi::OsString;
use std::path::PathBuf;
use clap::{ArgMatches, Args, CommandFactory, FromArgMatches, Parser, Subcommand, ValueEnum};
use serde_json::{Value, json};
/// The end of every subcommand's `--help`.
const EXIT_STATUS: &str = "Exit status:\n 0 success\n 1 the command failed (for `convert --strict` and `render --strict`, a refusal; for `validate`, a verdict other than PASS)\n 2 usage error\n\nA process ended by a signal exits 128 + the signal number (130 for Ctrl-C), as in the shell.";
/// The top-level `--help` ends with the environment and the exit status.
const TOP_NOTES: &str = "A password-protected Word file is opened with --password PASS, --password-file PATH or the WORDCRAFT_PASSWORD environment variable; a password given on the command line is readable by every other process, so the other two are better. A file opened with a password is written with it again, as the app does. Exports that cannot carry a password (pdf, html, txt) stay plain.\n\nPaper: documents created here, and HTML, Markdown and text files (which give no page size), use the system region's paper (A4, or Letter in the US and other Letter regions), read from LC_ALL / LC_PAPER / LANG or the platform. Set WORDCRAFT_REGION=en-US (or another tag) for the same output on every machine.\n\nEnvironment:\n WORDCRAFT_PASSWORD the password of a protected Word file, when neither --password nor --password-file is given\n WORDCRAFT_REGION the paper and region to use instead of the system's (a tag such as en-US)\n\nExit status:\n 0 success\n 1 the command failed (for `convert --strict` and `render --strict`, a refusal; for `validate`, a verdict other than PASS)\n 2 usage error\n\nA process ended by a signal exits 128 + the signal number (130 for Ctrl-C), as in the shell.";
/// WordCraft from the command line: convert, inspect, render, run commands, validate, serve MCP
#[derive(Parser, Debug)]
#[command(name = "wordcraft-cli", version, propagate_version = true, arg_required_else_help = true, after_help = TOP_NOTES)]
pub(crate) struct Cli {
#[command(subcommand)]
pub(crate) command: Command,
}
#[derive(Subcommand, Debug)]
pub(crate) enum Command {
/// Convert between formats (docx, doc [read], pdf, odt, rtf, html, md, tex, txt, json, png, xml)
///
/// `--update-fields` refreshes unlocked fields before saving (if protection blocks updates, they are skipped with a
/// warning). An .xml file is a Word XML Document (Flat OPC), or with `--format wordml2003` a Word 2003 XML Document.
/// `--markup` (Print Markup) puts comments beside each page and tracked changes in pdf/png, and a comment list in
/// html/md/txt. `--strict` (pdf or png output only) writes nothing and exits 1 if a character can't be drawn or a
/// picture is missing or undecodable; the report is on stderr, with one JSON line.
#[command(after_help = EXIT_STATUS)]
Convert(ConvertArgs),
/// Pages, words, paragraphs and properties (JSON)
#[command(after_help = EXIT_STATUS)]
Info(FileArgs),
/// The plain text
#[command(after_help = EXIT_STATUS)]
Text(FileArgs),
/// The document structure (JSON)
#[command(after_help = EXIT_STATUS)]
Inspect(FileArgs),
/// Render one page to a PNG
///
/// `--strict` writes nothing and exits 1 if a character on the page can't be drawn or a picture is missing or
/// undecodable (the report is on stderr, as for `convert --strict`).
#[command(after_help = EXIT_STATUS)]
Render(RenderArgs),
/// Run commands headlessly, then save
///
/// `--script` runs a JSON file (`-` is stdin) first: {"file"?, "template"?, "commands": [{"command": id, "params"?:
/// {…}} | id, …], "save"?: [OUT, …]}; save formats follow the extension (docx and pdf in one run); relative paths
/// resolve against the script's folder. `file.new` and `file.open` open another document and make it active; later
/// commands and the saves work on the active one; `view.switchWindows` lists the open documents and with {"id": N}
/// makes one active. PNG saves use `--page` (1-based, default 1) and `--scale` (default 2).
#[command(after_help = EXIT_STATUS)]
Run(RunArgs),
/// List every command
#[command(after_help = EXIT_STATUS)]
Commands(JsonArgs),
/// Feature-catalog parity
#[command(after_help = EXIT_STATUS)]
Parity(ParityArgs),
/// Structural integrity check
///
/// Exit 0 for PASS; 1 for FAIL, INCOMPLETE or a file that can't be read (the verdict is the first line of the report,
/// and `verdict` in `--json`).
#[command(after_help = EXIT_STATUS)]
Validate(ValidateArgs),
/// MCP server on stdio, with a headless session
///
/// Both roots are required: the agent's commands read files (open, insert text or picture, mail-merge data,
/// templates…) only inside the read root and write them (save, export, merge output…) only inside the write root,
/// links followed; the same folder may be both. `--connect` (bridge to the running app) is refused until the app
/// confines its control channel (#3695, #5819).
#[command(after_help = EXIT_STATUS)]
Mcp(McpArgs),
/// Run a Zotero command on a document (Zotero must be running)
///
/// The commands are addEditCitation, addEditBibliography, addNote, refresh, removeCodes and setDocPrefs; `--cmd`
/// runs first (for example `--cmd caret.docEnd`).
#[command(after_help = EXIT_STATUS)]
Zotero(ZoteroArgs),
}
/// How a password-protected Word file is opened.
#[derive(Args, Debug, Default)]
pub(crate) struct Password {
/// The password (readable by every other process on the machine; prefer --password-file)
#[arg(long, value_name = "PASS", env = "WORDCRAFT_PASSWORD", hide_env_values = true)]
pub(crate) password: Option<String>,
/// Read the password from this file (a trailing newline is dropped)
#[arg(long = "password-file", value_name = "PATH")]
pub(crate) password_file: Option<PathBuf>,
}
#[derive(Args, Debug)]
pub(crate) struct FileArgs {
/// The document
pub(crate) file: PathBuf,
#[command(flatten)]
pub(crate) open: Password,
}
#[derive(Clone, Copy, Debug, ValueEnum)]
pub(crate) enum XmlFormat {
/// A Word 2003 XML Document
Wordml2003,
/// A Word XML Document (Flat OPC), the default
Flatopc,
}
impl XmlFormat {
pub(crate) fn name(self) -> &'static str {
match self {
XmlFormat::Wordml2003 => "wordml2003",
XmlFormat::Flatopc => "flatopc",
}
}
}
#[derive(Args, Debug)]
pub(crate) struct ConvertArgs {
/// The document to read
pub(crate) input: PathBuf,
/// The file to write; its extension names the format
pub(crate) output: PathBuf,
/// Print Markup: comments beside each page and tracked changes
#[arg(long)]
pub(crate) markup: bool,
/// Refresh unlocked fields before saving
#[arg(long = "update-fields")]
pub(crate) update_fields: bool,
/// For pdf or png output: write nothing and fail if a character can't be drawn or a picture is missing
#[arg(long)]
pub(crate) strict: bool,
/// The kind of .xml file to write
#[arg(long, value_enum, value_name = "KIND")]
pub(crate) format: Option<XmlFormat>,
#[command(flatten)]
pub(crate) open: Password,
}
#[derive(Args, Debug)]
pub(crate) struct RenderArgs {
/// The document
pub(crate) input: PathBuf,
/// The PNG to write
pub(crate) output: PathBuf,
/// The page, from 1
#[arg(long, value_name = "N", value_parser = page, default_value = "1")]
pub(crate) page: u64,
/// Device pixels per point
#[arg(long, value_name = "S", allow_negative_numbers = true, value_parser = scale, default_value = "2")]
pub(crate) scale: f64,
/// Write nothing and fail if a character can't be drawn or a picture is missing
#[arg(long)]
pub(crate) strict: bool,
#[command(flatten)]
pub(crate) open: Password,
}
/// One `--cmd ID[=JSON]`.
#[derive(Clone, Debug)]
pub(crate) struct Cmd {
pub(crate) id: String,
pub(crate) params: Value,
}
fn cmd(text: &str) -> Result<Cmd, UsageError> {
match text.split_once('=') {
Some((id, p)) => {
let params = serde_json::from_str(p).map_err(|e| UsageError::CmdJson { id: id.to_owned(), why: e.to_string() })?;
Ok(Cmd { id: id.to_owned(), params })
}
None => Ok(Cmd { id: text.to_owned(), params: json!({}) }),
}
}
fn page(text: &str) -> Result<u64, UsageError> {
match text.parse::<u64>() {
Ok(0) => Err(UsageError::Page("invalid --page `0`: page numbers start at 1".to_owned())),
Ok(n) => Ok(n),
Err(_) => Err(UsageError::Page(format!("invalid --page `{text}`: not a valid integer"))),
}
}
fn scale(text: &str) -> Result<f64, UsageError> {
let n = text.parse::<f64>().map_err(|_| UsageError::Scale(format!("invalid --scale `{text}`: not a number")))?;
if n.is_finite() && n > 0.0 { Ok(n) } else { Err(UsageError::Scale(format!("invalid --scale `{text}`: scale must be a finite positive number"))) }
}
#[derive(Args, Debug)]
pub(crate) struct RunArgs {
/// Open this document first
#[arg(long, value_name = "F", conflicts_with = "template")]
pub(crate) file: Option<PathBuf>,
/// Start from this template
#[arg(long, value_name = "T")]
pub(crate) template: Option<String>,
/// A script to run first (`-` is stdin)
#[arg(long, value_name = "FILE")]
pub(crate) script: Option<PathBuf>,
/// Run one command, `ID` or `ID={json}`; repeatable
#[arg(long = "cmd", value_name = "ID={JSON}", value_parser = cmd)]
pub(crate) cmds: Vec<Cmd>,
/// Save the result here (the extension names the format)
#[arg(long, value_name = "OUT")]
pub(crate) save: Option<PathBuf>,
/// The page of a PNG save, from 1 (default 1)
#[arg(long, value_name = "N", value_parser = page)]
pub(crate) page: Option<u64>,
/// The scale of a PNG save (default 2)
#[arg(long, value_name = "S", allow_negative_numbers = true, value_parser = scale)]
pub(crate) scale: Option<f64>,
/// Print each command's result
#[arg(long)]
pub(crate) print: bool,
/// Who tracked changes and comments are by
#[arg(long, value_name = "NAME")]
pub(crate) author: Option<String>,
#[command(flatten)]
pub(crate) open: Password,
}
#[derive(Args, Debug)]
pub(crate) struct JsonArgs {
/// JSON alone on stdout
#[arg(long)]
pub(crate) json: bool,
}
#[derive(Args, Debug)]
pub(crate) struct ParityArgs {
/// Markdown instead of JSON
#[arg(long)]
pub(crate) markdown: bool,
}
#[derive(Args, Debug)]
pub(crate) struct ValidateArgs {
/// The document
pub(crate) file: PathBuf,
/// JSON alone on stdout
#[arg(long)]
pub(crate) json: bool,
}
#[derive(Args, Debug)]
pub(crate) struct McpArgs {
/// The folder the agent may read in (links followed); the same folder may be the write root
#[arg(long = "automation-read-root", value_name = "DIR", required_unless_present = "connect", value_parser = folder)]
pub(crate) read_root: Option<PathBuf>,
/// The folder the agent may write in (links followed)
#[arg(long = "automation-write-root", value_name = "DIR", required_unless_present = "connect", value_parser = folder)]
pub(crate) write_root: Option<PathBuf>,
/// Who tracked changes and comments are by
#[arg(long, value_name = "NAME")]
pub(crate) author: Option<String>,
/// Refused for now: the desktop app does not confine its control channel to automation roots yet
#[arg(long, value_name = "HOST:PORT")]
pub(crate) connect: Option<String>,
}
fn folder(text: &str) -> Result<PathBuf, UsageError> {
if text.is_empty() { Err(UsageError::EmptyFolder) } else { Ok(PathBuf::from(text)) }
}
#[derive(Args, Debug)]
pub(crate) struct ZoteroArgs {
/// The Zotero command (addEditCitation, addEditBibliography, addNote, refresh, removeCodes or setDocPrefs)
#[arg(value_parser = zotero_command)]
pub(crate) command: String,
/// The document
pub(crate) file: PathBuf,
/// Run one command first, `ID` or `ID={json}`; repeatable
#[arg(long = "cmd", value_name = "ID={JSON}", value_parser = cmd)]
pub(crate) cmds: Vec<Cmd>,
/// Save the document here afterwards
#[arg(long, value_name = "OUT")]
pub(crate) save: Option<PathBuf>,
/// Show the calls to and from Zotero on stderr
#[arg(long)]
pub(crate) trace: bool,
/// Zotero's port
#[arg(long, value_name = "P")]
pub(crate) port: Option<u16>,
}
fn zotero_command(text: &str) -> Result<String, UsageError> {
if wordcraft_zotero::Command::from_name(text).is_some() { Ok(text.to_owned()) } else { Err(UsageError::Zotero(text.to_owned())) }
}
/// A mistake in the command line that clap can't see by itself.
#[derive(Debug, PartialEq, thiserror::Error)]
pub(crate) enum UsageError {
#[error("{0}")]
Page(String),
#[error("{0}")]
Scale(String),
#[error("--cmd {id}: bad JSON params: {why}")]
CmdJson { id: String, why: String },
#[error("a folder is needed, not an empty name")]
EmptyFolder,
#[error("unknown Zotero command `{0}` (addEditCitation, addEditBibliography, addNote, refresh, removeCodes or setDocPrefs)")]
Zotero(String),
}
/// The clap definition of the whole command line (completions and man pages are generated from it).
pub fn command() -> clap::Command {
Cli::command()
}
/// Parse the arguments (without the program name). Help and the version come back as the `Err` clap uses for them.
pub(crate) fn parse(args: &[OsString]) -> Result<Cli, clap::Error> {
let matches = Cli::command().try_get_matches_from(std::iter::once(OsString::from("wordcraft-cli")).chain(args.iter().cloned()))?;
let mut cli = Cli::from_arg_matches(&matches)?;
if let Some((name, sub)) = matches.subcommand() {
password_precedence(&mut cli.command, sub, name);
}
Ok(cli)
}
/// `--password`, `--password-file`, then `WORDCRAFT_PASSWORD`: a password file named on the command line beats the
/// variable, which clap would otherwise read into `--password`.
fn password_precedence(command: &mut Command, sub: &ArgMatches, _name: &str) {
let open = match command {
Command::Convert(a) => &mut a.open,
Command::Info(a) | Command::Text(a) | Command::Inspect(a) => &mut a.open,
Command::Render(a) => &mut a.open,
Command::Run(a) => &mut a.open,
_ => return,
};
let from_env = sub.value_source("password") == Some(clap::parser::ValueSource::EnvVariable);
if from_env && open.password_file.is_some() {
open.password = None;
}
// A blank variable counts as unset.
if from_env && open.password.as_deref() == Some("") {
open.password = None;
}
}
+90
View File
@@ -0,0 +1,90 @@
//! Parse `--automation-read-root` / `--automation-write-root` before the server starts. A malformed
//! flag must not silently remove a root and leave the server unconfined.
use std::path::PathBuf;
pub struct AutomationArgs {
pub read_root: Option<PathBuf>,
pub write_root: Option<PathBuf>,
read_given: bool,
write_given: bool,
}
impl AutomationArgs {
pub fn new(read_root: Option<PathBuf>, write_root: Option<PathBuf>) -> Self {
Self { read_root, write_root, read_given: false, write_given: false }
}
/// Returns whether this argument is a root flag. A second occurrence of a flag is an error,
/// including when the two spellings (`--flag DIR`, `--flag=DIR`) are mixed.
pub fn consume(&mut self, arg: &str, args: &mut impl Iterator<Item = String>) -> Result<bool, String> {
let (flag, inline) = arg.split_once('=').map_or((arg, None), |(flag, value)| (flag, Some(value)));
let (root, given) = match flag {
"--automation-read-root" => (&mut self.read_root, &mut self.read_given),
"--automation-write-root" => (&mut self.write_root, &mut self.write_given),
_ => return Ok(false),
};
if *given {
return Err(format!("{flag} given twice"));
}
let value = match inline {
Some(value) => value.to_owned(),
None => {
let value = args.next().ok_or_else(|| format!("{flag} needs a folder"))?;
if value.starts_with('-') {
return Err(format!("{flag} needs a folder; use {flag}=<dir> for a folder starting with '-'"));
}
value
}
};
if value.is_empty() {
return Err(format!("{flag} needs a non-empty folder"));
}
*root = Some(value.into());
*given = true;
Ok(true)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn roots_are_taken_once_and_other_arguments_are_left() {
let mut roots = AutomationArgs::new(None, None);
let mut args = ["a folder".to_owned(), "report.docx".to_owned()].into_iter();
assert!(roots.consume("--automation-read-root", &mut args).unwrap());
assert!(roots.consume("--automation-write-root=out", &mut args).unwrap());
assert!(!roots.consume("--author", &mut args).unwrap());
assert_eq!(roots.read_root, Some("a folder".into()));
assert_eq!(roots.write_root, Some("out".into()));
assert_eq!(args.next().as_deref(), Some("report.docx"));
assert!(roots.consume("--automation-read-root=other", &mut args).is_err());
assert_eq!(roots.read_root, Some("a folder".into()));
}
#[test]
fn invalid_operands_leave_roots_unchanged() {
for flag in ["--automation-read-root", "--automation-write-root"] {
for operand in [None, Some(""), Some("--version"), Some("--connect"), Some("-folder")] {
let mut roots = AutomationArgs::new(Some("read".into()), Some("write".into()));
let mut args = operand.map(str::to_owned).into_iter();
assert!(roots.consume(flag, &mut args).is_err(), "{flag} {operand:?}");
assert_eq!(roots.read_root, Some("read".into()));
assert_eq!(roots.write_root, Some("write".into()));
}
let mut roots = AutomationArgs::new(None, None);
assert!(roots.consume(&format!("{flag}="), &mut std::iter::empty()).is_err());
}
}
#[test]
fn explicit_dash_folder_and_relative_dash_folder_are_valid() {
let mut roots = AutomationArgs::new(None, None);
assert!(roots.consume("--automation-read-root=-folder", &mut std::iter::empty()).unwrap());
assert!(roots.consume("--automation-write-root", &mut ["./-folder".to_owned()].into_iter()).unwrap());
assert_eq!(roots.read_root, Some("-folder".into()));
assert_eq!(roots.write_root, Some("./-folder".into()));
}
}
-609
View File
@@ -1,609 +0,0 @@
//! The subcommands: each takes its parsed arguments and the output streams, and returns the exit status.
use std::io::Write;
use std::path::Path;
use serde_json::{Value, json};
use wordcraft_engine::{CmdError, Session};
use crate::args::{self, Command, ConvertArgs, FileArgs, JsonArgs, McpArgs, ParityArgs, Password, RenderArgs, RunArgs, ValidateArgs, ZoteroArgs};
use crate::error::CliError;
use crate::script;
use crate::{Io, errln};
type Result<T> = std::result::Result<T, CliError>;
fn engine_error(e: impl std::fmt::Display) -> CliError {
CliError::Failed(escape_text(&e.to_string(), false))
}
/// Open a document for a subcommand. A password-protected Word file needs its password
/// ([`password_from`]). As in the app, a document opened with one is saved with it again, so
/// `convert` does not quietly write a copy the password no longer protects.
fn open(path: &Path, password: Option<&str>) -> Result<Session> {
// A file that gives no page size (HTML, Markdown, plain text) opens on the system region's
// paper, as in the app: A4 in Italy, Letter in the US (#1381).
let region = system_region();
let (doc, encrypted) = wordcraft_engine::io::open_path_in(path, password, &region).map_err(engine_error)?;
let mut s = session(doc);
s.path = Some(path.into());
if encrypted {
s.password = password.map(wordcraft_engine::io::Password::new);
}
Ok(s)
}
/// The password for a protected Word file: `--password`, `--password-file` or `WORDCRAFT_PASSWORD` (clap reads the
/// variable into `--password`; a blank one counts as unset). The file form exists because a password on a command line
/// is readable by every other process on the machine; a trailing newline is dropped so a file written by `echo` works.
/// Never logged, and never named in an error.
pub(crate) fn password_from(open: &Password) -> Result<Option<String>> {
if let Some(password) = &open.password {
return Ok(Some(password.clone()));
}
if let Some(path) = &open.password_file {
let raw =
std::fs::read_to_string(path).map_err(|e| CliError::Failed(escape_text(&format!("--password-file {}: {e}", path.display()), false)))?;
return Ok(Some(raw.trim_end_matches(['\r', '\n']).to_string()));
}
Ok(None)
}
/// A path the engine takes as text: output paths must be valid Unicode (only the opened file may not be, #1440).
fn unicode(path: &Path) -> Result<&str> {
path.to_str().ok_or_else(|| CliError::Failed(format!("{}: the file name is not valid Unicode", path.display().to_string().escape_debug())))
}
/// A headless session in the system region: every way the CLI starts one gives `file.new` the
/// same paper (#1381).
fn session(doc: wordcraft_doc::Document) -> Session {
let mut s = Session::new(doc);
s.system_region = system_region();
s
}
/// The system region, read as the app reads it (locale variables, else the platform's locale).
fn system_region() -> wordcraft_engine::Region {
wordcraft_engine::Region::from_locale_vars(|name| std::env::var(name).ok(), sys_locale::get_locale)
}
/// The body text for `text`: the plain-text export, so list items keep their bullet or number label.
fn listed_text(doc: &wordcraft_doc::Document) -> std::result::Result<String, String> {
let bytes = wordcraft_engine::io::save_bytes("out.txt", doc)?;
Ok(String::from_utf8_lossy(&bytes).replace("\r\n", "\n"))
}
/// `--author NAME`: the author recorded on tracked changes and comments (`file.setAuthor`).
/// The command also checks whether the open document is protected: this name determines which
/// named editing exceptions the session can use, so the flag must not bypass that check.
fn set_author(s: &mut Session, name: &str) -> std::result::Result<(), String> {
s.run("file.setAuthor", &json!({"name": name})).map(|_| ()).map_err(|e| escape_text(&format!("--author: {e}"), false))
}
/// `mcp`'s headless backend: a session confined to `roots`, its author `author` when given. The caller confines the
/// process to the same roots first (`confine_process`), which a test must not do.
fn headless_mcp(
roots: std::sync::Arc<wordcraft_engine::file_access::AutomationRoots>,
author: Option<&str>,
) -> std::result::Result<wordcraft_mcp::Headless, String> {
let mut headless = wordcraft_mcp::Headless::default().with_automation_roots(Some(roots));
if let Some(name) = author {
set_author(&mut headless.session, name)?;
}
Ok(headless)
}
/// A failed `--strict` export: a strict refusal becomes [`CliError::Strict`] carrying what stderr
/// shows (each line of the report as `error: …`, then its JSON on one line, from
/// `file.strictReport` for `page` of a page image, else the PDF); any other error is an ordinary
/// failure.
fn refusal(s: &mut Session, e: wordcraft_engine::CmdError, markup: bool, page: Option<u64>) -> CliError {
if !matches!(&e, wordcraft_engine::CmdError::Failed(m) if m.starts_with("strict: ")) {
return engine_error(e);
}
let mut params = json!({"markup": markup});
if let Some(page) = page {
params["page"] = json!(page);
}
CliError::Strict(match s.run("file.strictReport", &params).map_err(|e| e.to_string()) {
Ok(json) => {
let mut text = String::new();
for line in report_lines(&json) {
text += &format!("error: {}\n", escape_peer(&line));
}
text + &json_line_safe(&json.to_string())
}
Err(e) => format!("error: strict: refused, and the report could not be made: {}", escape_text(&e, false)),
})
}
/// The report's human lines, from its JSON (the engine's `StrictReport::lines`).
fn report_lines(json: &Value) -> Vec<String> {
wordcraft_engine::strict::lines_from_json(json)
}
/// Explicitly update unlocked fields in a session before saving the document.
///
/// If field updates are disabled by document protection (`CmdError::Disabled`), logs a warning to
/// stderr and continues conversion rather than aborting. Other command failures are converted to
/// [`CliError`] via [`engine_error`].
///
/// # Arguments
///
/// * `s` - The active document [`Session`] whose unlocked fields should be refreshed.
///
/// # Errors
///
/// Returns `Err(CliError)` if the command fails with an error other than `CmdError::Disabled`.
fn update_fields(s: &mut Session, io: &mut Io) -> Result<()> {
if let Err(e) = s.run("references.updateFields", &json!({})) {
if matches!(e, CmdError::Disabled(_)) {
errln!(io, "warning: {e}");
} else {
return Err(engine_error(e));
}
}
Ok(())
}
/// At most 400 characters of `s`, for traces.
fn clip(s: &str) -> String {
match s.char_indices().nth(400) {
Some((i, _)) => format!("{}…", s.get(..i).unwrap_or(s)),
None => s.to_string(),
}
}
/// Text from another program (Zotero, or whatever answered on its port) for one diagnostic
/// line: backslashes, control characters (newline, escape, C1…), line separators and bidi
/// overrides are shown as escapes (`\\`, `\n`, `\u{1b}`), so it can't end its line, drive the
/// terminal or pass for other output.
fn escape_peer(s: &str) -> String {
escape_text(s, true)
}
/// Whether `c` must not reach a terminal as itself: a control character, a line or paragraph
/// separator, a bidi control, or one that shows nothing (soft hyphen, zero-width characters, word
/// joiners, the byte order mark, tag characters), which can hide or reorder what a line says.
fn is_unsafe_char(c: char) -> bool {
c.is_control()
|| matches!(
c,
'\u{00ad}'
| '\u{061c}'
| '\u{200b}'..='\u{200f}'
| '\u{2028}'..='\u{202e}'
| '\u{2060}'..='\u{2064}'
| '\u{2066}'..='\u{2069}'
| '\u{feff}'
| '\u{e0000}'..='\u{e007f}'
)
}
/// [`escape_peer`], with backslashes escaped only when `backslash` (error messages quote Windows
/// paths, and a backslash can't forge or hide anything).
fn escape_text(s: &str, backslash: bool) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
match c {
'\\' if backslash => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
c if is_unsafe_char(c) => out.extend(c.escape_unicode()),
c => out.push(c),
}
}
out
}
/// A JSON line safe to print: serde escapes control characters below U+0020 but not the other
/// characters [`is_unsafe_char`] names, which a crafted file could put in a report. They become
/// `\uXXXX` escapes (a surrogate pair above U+FFFF), so the line parses to the same value and
/// can't drive or spoof a terminal.
fn json_line_safe(json: &str) -> String {
let mut out = String::with_capacity(json.len());
for c in json.chars() {
if is_unsafe_char(c) {
for unit in c.encode_utf16(&mut [0u16; 2]) {
out.push_str(&format!("\\u{unit:04x}"));
}
} else {
out.push(c);
}
}
out
}
fn parity_markdown(p: &Value) -> String {
let mut s = String::from(
"# WordCraft feature parity\n\nGenerated by `cargo xtask parity` (`wordcraft-cli parity --markdown`): the word-processor feature catalog (`crates/engine/src/catalog.rs`) compared with the live command registry.\n\n",
);
s += &format!(
"**{} of {} catalog features have commands ({}%).**\n\n| Tab | Live | Total |\n|---|---|---|\n",
p["live"], p["total"], p["percent"]
);
for t in p["tabs"].as_array().cloned().unwrap_or_default() {
s += &format!("| {} | {} | {} |\n", t["tab"].as_str().unwrap_or(""), t["live"], t["total"]);
}
s += "\n## Missing\n\n";
for t in p["tabs"].as_array().cloned().unwrap_or_default() {
let m = t["missing"].as_array().cloned().unwrap_or_default();
if m.is_empty() {
continue;
}
s += &format!("### {}\n\n", t["tab"].as_str().unwrap_or(""));
for x in m {
s += &format!("- {}\n", x.as_str().unwrap_or(""));
}
s += "\n";
}
s
}
/// Write a `validate` report for people: the verdict, then one line per finding
/// (`SEVERITY RULE [part] message`), then the coverage notes.
fn write_validate_report(o: &mut dyn Write, report: &wordcraft_validate::Report) -> std::io::Result<()> {
o.write_all(render_validate_report(report).as_bytes())
}
/// Render a `validate` report for people. Document-controlled text — a ZIP entry name flowing into
/// a finding part or coverage note — is escaped so a name cannot end its line or drive the
/// terminal; printable text, including Unicode, is left as written.
///
/// The `--json` form is not escaped by hand; it is the validator's own `serde_json` serialization.
/// `serde_json` escapes `U+0000`–`U+001F`, `"` and `\`; C1 controls such as `U+009B` and the bidi
/// embeddings/overrides (`U+202A`–`U+202E`, `U+2066`–`U+2069`) are emitted raw. So a control or bidi
/// run carried by a ZIP entry name survives into the JSON text; JSON is only safe because a
/// *parser* takes the string value as data. If that text is printed directly to a terminal, the raw
/// C1/bidi run reaches the terminal exactly as it would from any other text, so the JSON form is
/// not a terminal-safe rendering. Only the human report below escapes those characters, and it does
/// so to defend the terminal; keeping the JSON byte-for-byte the validator's own serialization is
/// why its escaping is left to `serde_json`.
fn render_validate_report(report: &wordcraft_validate::Report) -> String {
let mut out = format!("{}\n", verdict_label(report.verdict));
for f in &report.findings {
let severity = severity_label(f.severity);
match &f.part {
Some(part) => out.push_str(&format!("{severity} {} [{}] {}\n", f.rule, escape_report_text(part), escape_report_text(&f.message))),
None => out.push_str(&format!("{severity} {} {}\n", f.rule, escape_report_text(&f.message))),
}
}
for note in &report.coverage_notes {
out.push_str(&format!("note: {}\n", escape_report_text(note)));
}
out
}
/// Escape the control and invisible-formatting characters that could spoof a report line, in the
/// same escape *form* `escape_debug` uses (`\u{1b}`, `\n`); printable characters (including Unicode)
/// are left untouched. The *selection* is a hand-picked set ([`is_invisible_format`] plus
/// `char::is_control`), not `escape_debug`'s full non-printable set: it omits, for example, the
/// U+E0000 tag block, U+FFF9–U+FFFB and the Hangul fillers. None of those can end a line or drive a
/// terminal, which is the threat this guards against. Backslash is not escaped, so a name that
/// literally contains the text `\u{1b}` prints exactly like an escaped ESC and the output is not
/// injective.
fn escape_report_text(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
if c.is_control() || is_invisible_format(c) {
out.extend(c.escape_debug());
} else {
out.push(c);
}
}
out
}
/// Invisible Unicode formatting characters and line/paragraph separators: no glyph, but they can
/// alter how a terminal renders the rest of the line (`char::is_control` covers C0/C1 controls).
fn is_invisible_format(c: char) -> bool {
matches!(
c,
'\u{00ad}' | '\u{061c}' | '\u{180e}' | '\u{200b}'..='\u{200f}' | '\u{2028}'..='\u{202e}' | '\u{2060}'..='\u{206f}' | '\u{feff}'
)
}
/// Map a validation verdict enum to its human-readable uppercase display label.
fn verdict_label(v: wordcraft_validate::Verdict) -> &'static str {
match v {
wordcraft_validate::Verdict::Pass => "PASS",
wordcraft_validate::Verdict::Fail => "FAIL",
wordcraft_validate::Verdict::Incomplete => "INCOMPLETE",
}
}
/// Map a validation severity enum to its human-readable uppercase display label.
fn severity_label(s: wordcraft_validate::Severity) -> &'static str {
match s {
wordcraft_validate::Severity::Corrupt => "CORRUPT",
wordcraft_validate::Severity::Error => "ERROR",
wordcraft_validate::Severity::Warning => "WARNING",
}
}
/// Why `mcp --connect` is refused: the running app would not confine the agent's file access.
// lean: refused outright; allow it once the app confines its control channel and reports both roots.
const MCP_CONNECT_REFUSED: &str = "mcp: --connect is refused for now: the desktop app does not confine its control \
channel to automation roots yet (storytold/wordcraft#3695, #5819). Use the headless server: wordcraft-cli mcp \
--automation-read-root DIR --automation-write-root DIR";
/// Run one parsed subcommand; the result is the exit status.
pub(crate) fn dispatch(command: Command, io: &mut Io) -> Result<u8> {
match command {
Command::Convert(a) => convert(a, io).map(|()| 0),
Command::Info(a) => info(a, io).map(|()| 0),
Command::Text(a) => text(a, io).map(|()| 0),
Command::Inspect(a) => inspect(a, io).map(|()| 0),
Command::Render(a) => render(a, io).map(|()| 0),
Command::Run(a) => run_script(a, io).map(|()| 0),
Command::Commands(a) => commands(a, io).map(|()| 0),
Command::Parity(a) => parity(a, io).map(|()| 0),
Command::Validate(a) => validate(a, io),
Command::Mcp(a) => mcp(a, io).map(|()| 0),
Command::Zotero(a) => zotero(a, io).map(|()| 0),
}
}
/// Write to stdout and flush. A closed stdout comes back as [`CliError::StdoutClosed`] instead of a panic.
fn write_stdout(io: &mut Io, write: impl FnOnce(&mut dyn Write) -> std::io::Result<()>) -> Result<()> {
write(&mut *io.out)?;
io.out.flush()?;
Ok(())
}
fn convert(a: ConvertArgs, io: &mut Io) -> Result<()> {
let o = unicode(&a.output)?.to_owned();
// Before the input is opened: a wrong output type is a usage error, not a file error.
let to_png = o.to_ascii_lowercase().ends_with(".png");
if a.strict && !(to_png || o.to_ascii_lowercase().ends_with(".pdf")) {
return Err(CliError::Usage("convert: --strict needs a .pdf or .png output".into()));
}
let password = password_from(&a.open)?;
let mut s = open(&a.input, password.as_deref())?;
if a.update_fields {
update_fields(&mut s, io)?;
}
let r = if to_png {
s.run("file.exportPng", &json!({"path": o, "page": 1, "markup": a.markup, "strict": a.strict}))
} else {
let mut params = json!({"path": o, "markup": a.markup, "strict": a.strict});
if let Some(f) = a.format {
params["format"] = json!(f.name());
}
s.run("file.save", &params)
};
if let Err(e) = r {
return Err(if a.strict { refusal(&mut s, e, a.markup, to_png.then_some(1)) } else { engine_error(e) });
}
errln!(io, "wrote {o}");
Ok(())
}
fn open_file(a: &FileArgs) -> Result<Session> {
let password = password_from(&a.open)?;
open(&a.file, password.as_deref())
}
fn info(a: FileArgs, io: &mut Io) -> Result<()> {
let mut s = open_file(&a)?;
let info = serde_json::to_string_pretty(&s.run("file.info", &json!({})).map_err(engine_error)?).unwrap_or_default();
write_stdout(io, |o| writeln!(o, "{info}"))
}
fn text(a: FileArgs, io: &mut Io) -> Result<()> {
let s = open_file(&a)?;
let text = listed_text(&s.doc)?;
write_stdout(io, |o| writeln!(o, "{text}"))
}
fn inspect(a: FileArgs, io: &mut Io) -> Result<()> {
let mut s = open_file(&a)?;
let tree = serde_json::to_string_pretty(&s.run("document.inspect", &json!({})).map_err(engine_error)?).unwrap_or_default();
write_stdout(io, |o| writeln!(o, "{tree}"))
}
fn render(a: RenderArgs, io: &mut Io) -> Result<()> {
let o = unicode(&a.output)?.to_owned();
let password = password_from(&a.open)?;
let mut s = open(&a.input, password.as_deref())?;
let mut params = json!({"path": o, "page": a.page, "scale": a.scale, "strict": a.strict});
if a.strict {
// The check and its report must see the page as it is written.
params["markup"] = json!(false);
}
let r = match s.run("file.exportPng", &params) {
Ok(r) => r,
Err(e) if a.strict => return Err(refusal(&mut s, e, false, Some(a.page))),
Err(e) => return Err(engine_error(e)),
};
write_stdout(io, |o| writeln!(o, "{r}"))
}
fn load_run_script(path: Option<&Path>) -> Result<Option<script::Script>> {
path.map(|p| script::load(p).map_err(engine_error)).transpose()
}
fn run_script(a: RunArgs, io: &mut Io) -> Result<()> {
let password = password_from(&a.open)?;
let script = load_run_script(a.script.as_deref())?;
// A source named on the command line wins over both of the script's.
let (mut from_file, mut from_template) = (a.file.clone(), a.template.clone());
if from_file.is_none() && from_template.is_none() {
from_file = script.as_ref().and_then(|loaded| loaded.file.as_deref().map(std::path::PathBuf::from));
from_template = script.as_ref().and_then(|loaded| loaded.template.clone());
}
let mut s = match (from_file, from_template) {
(Some(f), _) => open(&f, password.as_deref())?,
// Both go through `file.new`, which puts a blank document on the region's paper (#3152).
// `file.new` opens beside the session's first document, which is then closed: the
// run starts with one open document.
(None, t) => {
let mut s = session(wordcraft_doc::Document::new());
let first = s.document_id();
let params = t.map_or_else(|| json!({}), |t| json!({"template": t}));
s.run("file.new", &params).map_err(engine_error)?;
s.close_document(first).map_err(engine_error)?;
s
}
};
if let Some(name) = &a.author {
set_author(&mut s, name).map_err(CliError::Failed)?;
}
for (n, (id, params)) in script.iter().flat_map(|c| c.commands.iter()).enumerate() {
let r = s.run(id, params).map_err(|e| engine_error(format!("command {} ({id}): {e}", n + 1)))?;
if a.print {
write_stdout(io, |o| writeln!(o, "{id}: {r}"))?;
}
}
for args::Cmd { id, params } in &a.cmds {
let r = s.run(id, params).map_err(|e| engine_error(format!("{id}: {e}")))?;
if a.print {
write_stdout(io, |o| writeln!(o, "{id}: {r}"))?;
}
}
let mut outputs: Vec<String> = script.iter().flat_map(|c| c.save.iter().cloned()).collect();
if let Some(save) = &a.save {
outputs.push(unicode(save)?.to_owned());
}
// Check every output can be made before writing any, so a bad one leaves no half-done job.
for out in &outputs {
let parent = Path::new(out).parent().filter(|p| !p.as_os_str().is_empty());
if let Some(p) = parent.filter(|p| !p.is_dir()) {
return Err(format!("{out}: folder {} does not exist", p.display()).into());
}
if Path::new(out).is_dir() {
return Err(format!("{out}: is a folder, not a file").into());
}
if !out.to_ascii_lowercase().ends_with(".png") {
wordcraft_engine::io::save_bytes(out, &s.doc).map_err(engine_error)?;
}
}
for out in outputs {
let r = if out.to_ascii_lowercase().ends_with(".png") {
let mut v = json!({"path": out});
if let Some(n) = a.page {
v["page"] = json!(n);
}
if let Some(k) = a.scale {
v["scale"] = json!(k);
}
s.run("file.exportPng", &v)
} else {
s.run("file.save", &json!({"path": out}))
};
r.map_err(engine_error)?;
errln!(io, "wrote {out}");
}
Ok(())
}
fn commands(a: JsonArgs, io: &mut Io) -> Result<()> {
let s = session(wordcraft_doc::Document::new());
if a.json {
let list = serde_json::to_string_pretty(&s.registry.describe()).unwrap_or_default();
write_stdout(io, |o| writeln!(o, "{list}"))
} else {
write_stdout(io, |o| {
for c in s.registry.all() {
writeln!(o, "{:<32} {:<36} {:<24} {}", c.id, c.label, c.shortcut, c.location)?;
}
writeln!(o, "{:<32} Structural integrity check", "validate")
})
}
}
fn parity(a: ParityArgs, io: &mut Io) -> Result<()> {
let s = session(wordcraft_doc::Document::new());
let p = wordcraft_engine::catalog::parity(&s.registry);
if a.markdown {
write_stdout(io, |o| write!(o, "{}", parity_markdown(&p)))
} else {
write_stdout(io, |o| writeln!(o, "{}", serde_json::to_string_pretty(&p).unwrap_or_default()))
}
}
fn mcp(a: McpArgs, io: &mut Io) -> Result<()> {
if a.connect.is_some() {
return Err(MCP_CONNECT_REFUSED.into());
}
// Shared rule 18 (#7124): an agent entry point never runs unconfined. clap requires both roots.
let roots = wordcraft_engine::file_access::AutomationRoots::new(a.read_root.as_deref(), a.write_root.as_deref())
.map_err(|e| CliError::Failed(format!("mcp: {e}")))?;
let Some(roots) = roots.filter(|r| r.read_root().is_some() && r.write_root().is_some()) else {
return Err(CliError::Usage("mcp: give both --automation-read-root DIR and --automation-write-root DIR".into()));
};
// Every thread of this process, not only the server's: nothing reaches past the roots.
wordcraft_engine::file_access::confine_process(roots.clone());
let show = |root: Option<&Path>| root.map_or_else(|| "none".to_string(), |r| r.display().to_string());
errln!(io, "files confined: read root {}, write root {}", show(roots.read_root()), show(roots.write_root()));
let backend: Box<dyn wordcraft_mcp::Backend> = Box::new(headless_mcp(roots, a.author.as_deref()).map_err(CliError::Failed)?);
let mut server = wordcraft_mcp::Server::new(backend);
let stdin = std::io::stdin();
// A client that closes our stdout has hung up: `serve` returns BrokenPipe and we end cleanly.
Ok(server.serve(stdin.lock(), &mut *io.out)?)
}
fn zotero(a: ZoteroArgs, io: &mut Io) -> Result<()> {
let command =
wordcraft_zotero::Command::from_name(&a.command).ok_or_else(|| CliError::Usage(format!("unknown Zotero command `{}`", a.command)))?;
let mut s = open(&a.file, None)?;
for args::Cmd { id, params } in &a.cmds {
s.run(id, params).map_err(|e| engine_error(format!("{id}: {e}")))?;
}
let mut opts = wordcraft_zotero::client::Options::default();
if let Some(p) = a.port {
opts.addr.set_port(p);
}
let mut bridge = wordcraft_zotero::Bridge::new();
let mut host = wordcraft_zotero::Headless::default();
let mut trace = Vec::new();
let out = wordcraft_zotero::client::run_command(&opts, command, &mut |call| {
let r = bridge.handle(&mut s, &mut host, call);
if a.trace {
trace.push(format!("← {} {}", escape_peer(&call.method), escape_peer(&clip(&Value::Array(call.args.clone()).to_string()))));
trace.push(format!("→ {}", escape_peer(&clip(&String::from_utf8_lossy(&wordcraft_zotero::wire::encode_reply(&r))))));
}
r
})
.map_err(engine_error)?;
for line in &trace {
errln!(io, "{line}");
}
for alert in &host.alerts {
errln!(io, "Zotero: {}", escape_peer(alert));
}
errln!(io, "{} calls, {}", out.calls, if out.completed { "completed" } else { "ended without completing (cancelled?)" });
if let Some(o) = &a.save {
let o = unicode(o)?;
s.run("file.save", &json!({"path": o})).map_err(engine_error)?;
errln!(io, "wrote {o}");
}
Ok(())
}
/// `validate`: 0 for PASS, 1 for any other verdict or a file that can't be read (RFC-0018 rule 1.2 has no other code;
/// the verdict is in the report).
fn validate(a: ValidateArgs, io: &mut Io) -> Result<u8> {
let report =
wordcraft_validate::validate_path(&a.file).map_err(|e| CliError::Failed(escape_text(&format!("{}: {e}", a.file.display()), false)))?;
let written = if a.json {
let json = serde_json::to_string_pretty(&report).unwrap_or_default();
write_stdout(io, |o| writeln!(o, "{json}"))
} else {
write_stdout(io, |o| write_validate_report(o, &report))
};
match written {
// A reader closing early must not turn a FAIL or INCOMPLETE verdict into PASS.
Ok(()) | Err(CliError::StdoutClosed) => {}
Err(error) => return Err(error),
}
Ok(match report.verdict {
wordcraft_validate::Verdict::Pass => 0,
wordcraft_validate::Verdict::Fail | wordcraft_validate::Verdict::Incomplete => 1,
})
}
#[cfg(test)]
#[path = "tests.rs"]
mod tests;
-37
View File
@@ -1,37 +0,0 @@
//! What stops a command, and how each case exits.
/// Why a CLI run stopped early.
#[derive(Debug, PartialEq, thiserror::Error)]
pub enum CliError {
/// The command failed (exit 1); the text is already safe to print.
#[error("{0}")]
Failed(String),
/// A mistake in the command line found after parsing (exit 2).
#[error("{0}")]
Usage(String),
/// A strict export refused (exit 1): the report's lines, then its JSON line, ready for stderr.
#[error("{0}")]
Strict(String),
/// Whoever read stdout closed it (`wordcraft-cli commands --json | head`): nobody is left to write to, so a quiet
/// exit 0 (`validate` keeps its verdict's status).
#[error("stdout closed")]
StdoutClosed,
}
impl From<String> for CliError {
fn from(e: String) -> Self {
CliError::Failed(e)
}
}
impl From<&str> for CliError {
fn from(e: &str) -> Self {
CliError::Failed(e.into())
}
}
impl From<std::io::Error> for CliError {
fn from(e: std::io::Error) -> Self {
if e.kind() == std::io::ErrorKind::BrokenPipe { CliError::StdoutClosed } else { CliError::Failed(e.to_string()) }
}
}
-88
View File
@@ -1,88 +0,0 @@
//! Headless WordCraft (`wordcraft-cli`). [`run`] is the whole program, so it can be tested in-process as well as
//! through the binary; `wordcraft-cli --help` lists the subcommands. The conventions are RFC-0018's: exit 0, 1 (a
//! command failed) or 2 (a usage error), results on stdout, `error: <message>` on stderr.
mod args;
mod commands;
mod error;
mod script;
use std::ffi::OsString;
use std::io::Write;
use error::CliError;
pub use args::command;
/// Where a command writes: results to `out`, diagnostics and progress to `err`.
pub(crate) struct Io<'a> {
pub(crate) out: &'a mut dyn Write,
pub(crate) err: &'a mut dyn Write,
}
/// Writes a line of progress or a warning; a closed stderr is not worth an error.
macro_rules! errln {
($io:expr, $($arg:tt)*) => {
drop(writeln!($io.err, $($arg)*))
};
}
pub(crate) use errln;
/// The Launcher's Nightly bootstrap belongs to the desktop app: a CLI must not accept it, in the
/// separate-token or `=` form, so a mis-routed launch fails loudly instead of editing stable data.
fn launcher_profile_flag(args: &[OsString]) -> bool {
args.iter().any(|arg| {
let arg = arg.to_string_lossy();
arg == "--launch-profile" || arg == "--profile-root" || arg.starts_with("--launch-profile=") || arg.starts_with("--profile-root=")
})
}
/// Run the CLI on its arguments (without the program name), writing results to `out` and diagnostics to `err`.
/// Returns the process exit code: 0 on success, 1 when a command failed, 2 for a usage error. Help and the version go
/// to `out`, exit 0.
pub fn run<I, T>(args: I, out: &mut dyn Write, err: &mut dyn Write) -> i32
where
I: IntoIterator<Item = T>,
T: Into<OsString>,
{
let args: Vec<OsString> = args.into_iter().map(Into::into).collect();
if launcher_profile_flag(&args) {
let _ = writeln!(err, "error: --launch-profile and --profile-root are the desktop app's Nightly bootstrap, not a CLI option");
return 2;
}
// Help and the version (`help`, `-h`, `<subcommand> --help`, `-V`) come back as errors too.
let cli = match args::parse(&args) {
Ok(cli) => cli,
Err(e) => {
let to: &mut dyn Write = if e.use_stderr() { err } else { out };
let _ = write!(to, "{}", e.render());
return e.exit_code();
}
};
let mut io = Io { out, err };
// Language packs installed in the suite's font store are used; `proof.installPack` installs
// only while the person has turned downloading on in the app.
wordcraft_engine::packs::use_font_store(false);
if let Some(source) = wordcraft_engine::packs::index_override() {
errln!(io, "Language packs come from a test source: {source}");
}
match commands::dispatch(cli.command, &mut io) {
Ok(code) => i32::from(code),
// A reader that stopped early (a closed pipe) ends the program quietly, as ripgrep does.
Err(CliError::StdoutClosed) => 0,
Err(CliError::Usage(e)) => {
errln!(io, "error: {e}");
2
}
// The report's lines already start with `error:`.
Err(CliError::Strict(report)) => {
errln!(io, "{report}");
1
}
Err(e) => {
errln!(io, "error: {e}");
1
}
}
}
+918 -5
View File
@@ -1,9 +1,922 @@
//! The `wordcraft-cli` program: [`wordcraft_cli::run`] with the process's streams.
//! `wordcraft-cli`: WordCraft from the command line.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
mod automation_args;
mod script;
use std::ffi::{OsStr, OsString};
use std::fmt;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::ExitCode;
fn main() -> ExitCode {
let args: Vec<_> = std::env::args_os().skip(1).collect();
let code = wordcraft_cli::run(args, &mut std::io::stdout(), &mut std::io::stderr());
ExitCode::from(u8::try_from(code).unwrap_or(1))
use serde_json::{Value, json};
use wordcraft_engine::{CmdError, Session};
const USAGE: &str = "\
wordcraft-cli — WordCraft from the command line
USAGE:
wordcraft-cli convert <in> <out> [--markup] [--update-fields] [--strict] [--format wordml2003|flatopc]
convert between formats (docx, doc [read], pdf, odt, rtf, html, md, tex, txt, json, png,
xml); --update-fields refreshes unlocked fields before saving
(if protection blocks updates, they are skipped with a warning);
an .xml file is a Word XML Document (Flat OPC), or with
--format wordml2003 a Word 2003 XML Document;
--markup (Print Markup): comments beside each page and
tracked changes in pdf/png, a comment list in html/md/txt;
--strict (pdf or png output only) writes nothing and exits 3
if a character can't be drawn or a picture is missing or
undecodable; the report is on stderr, with one JSON line
wordcraft-cli info <file> pages, words, paragraphs, properties (JSON)
wordcraft-cli text <file> plain text
wordcraft-cli inspect <file> document structure (JSON)
wordcraft-cli render <file> <out.png> [--page N] [--scale S] [--strict]
--strict writes nothing and exits 3 if a character on the
page can't be drawn or a picture is missing or undecodable
(report on stderr, as for convert --strict)
wordcraft-cli run [--file F | --template T] [--script FILE|-] [--cmd 'id={json}' …]
[--save OUT] [--page N] [--scale S] [--print] [--author NAME]
run commands headlessly, then save (--author names
who tracked changes and comments are by).
PNG saves use --page (1-based, default 1) and --scale (default 2).
--script runs a JSON file (- is stdin) first:
{\"file\"?, \"template\"?, \"commands\": [{\"command\": id,
\"params\"?: {…}} | id, …], \"save\"?: [OUT, …]}; save
formats follow the extension (docx and pdf in one run);
relative paths resolve against the script's folder.
file.new and file.open open another document and
make it active; later commands and the saves work on
the active one; view.switchWindows lists the open
documents and with {\"id\": N} makes one active
wordcraft-cli commands [--json] list every command
wordcraft-cli parity [--markdown] feature-catalog parity
wordcraft-cli mcp --automation-read-root DIR --automation-write-root DIR [--author NAME]
MCP server on stdio, with a headless session.
Both roots are required: the agent's commands read
files (open, insert text or picture, mail-merge data,
templates…) only inside the read root and write them
(save, export, merge output…) only inside the write
root, links followed; the same folder may be both.
--connect HOST:PORT (bridge to the running app) is
refused until the app confines its control channel
(#3695, #5819).
wordcraft-cli zotero <command> <file> [--cmd 'id={json}' …] [--save OUT] [--trace] [--port P]
run a Zotero command on a document (Zotero must be
running): addEditCitation, addEditBibliography,
addNote, refresh, removeCodes, setDocPrefs
(--cmd runs first, e.g. --cmd caret.docEnd)
wordcraft-cli [<command>] -h | --help this help
wordcraft-cli --version
A password-protected Word file is opened with --password PASS, --password-file PATH or the
WORDCRAFT_PASSWORD environment variable; a password given on the command line is readable by
every other process, so the other two are better. A file opened with a password is written with
it again, as the app does. Exports that cannot carry a password (pdf, html, txt) stay plain.
Paper: documents created here, and HTML, Markdown and text files (which give no page size), use
the system region's paper (A4, or Letter in the US and other Letter regions), read from
LC_ALL / LC_PAPER / LANG or the platform. Set WORDCRAFT_REGION=en-US (or another tag) for the
same output on every machine.
";
/// The subcommands, in `USAGE` order; `--help` or `-h` after any of them prints `USAGE` (#968).
const SUBCOMMANDS: &[&str] = &["convert", "info", "text", "inspect", "render", "run", "commands", "parity", "mcp", "zotero"];
fn wants_help(cmd: &str, rest: &[String]) -> bool {
SUBCOMMANDS.contains(&cmd) && rest.iter().any(|a| a == "--help" || a == "-h")
}
/// A failure whose message may carry text from a file or from the engine's reading of one (a
/// picture's part name, a parse error quoting the input): control, bidi and invisible characters
/// are escaped, so it can't forge or spoof a line (the CLI's own messages, which have line breaks
/// on purpose, are not routed through here). Backslashes stay: messages quote Windows paths.
fn engine_error(e: impl fmt::Display) -> Failure {
Failure::Error(escape_text(&e.to_string(), false))
}
/// The error every subcommand gives when a required path is not there.
fn missing_argument() -> Failure {
format!("missing argument\n\n{USAGE}").into()
}
/// Open a document for a subcommand. A password-protected Word file needs its password
/// ([`password_from`]). As in the app, a document opened with one is saved with it again, so
/// `convert` does not quietly write a copy the password no longer protects.
fn open(path: &Path, password: Option<&str>) -> Result<Session, Failure> {
// A file that gives no page size (HTML, Markdown, plain text) opens on the system region's
// paper, as in the app: A4 in Italy, Letter in the US (#1381).
let region = system_region();
let (doc, encrypted) = wordcraft_engine::io::open_path_in(path, password, &region).map_err(engine_error)?;
let mut s = session(doc);
s.path = Some(path.into());
if encrypted {
s.password = password.map(wordcraft_engine::io::Password::new);
}
Ok(s)
}
/// The commands that open a file, and which positional argument it is, excluding option values.
/// `run` opens the value of `--file`.
const OPENS_FILE: &[(&str, usize)] = &[("convert", 0), ("info", 0), ("text", 0), ("inspect", 0), ("render", 0), ("zotero", 1)];
/// The arguments as text. Only the file the command opens may have a name that isn't valid Unicode,
/// such as a Latin-1 one (#1440): it comes back as the path to open, and lossy among the arguments.
/// Any other such argument is an error naming it.
fn text_args<S: AsRef<OsStr>>(raw: &[S]) -> Result<(Vec<String>, Option<PathBuf>), String> {
let args: Vec<String> = raw.iter().map(|a| a.as_ref().to_string_lossy().into_owned()).collect();
let cmd = args.first().map(String::as_str).unwrap_or("");
let specs = match cmd {
"convert" => CONVERT_OPTIONS,
"render" => RENDER_OPTIONS,
"zotero" => ZOTERO_OPTIONS,
_ => PASSWORD_OPTIONS,
};
let file_at = match OPENS_FILE.iter().find(|(c, _)| *c == cmd) {
Some((_, n)) => positional_indices(args.get(1..).unwrap_or_default(), specs).get(*n).map(|i| i + 1),
None if cmd == "run" => args.iter().position(|a| a == "--file").map(|i| i + 1),
None => None,
};
// `run --script FILE` may also name its script with such a file name.
let script_at = if cmd == "run" { args.iter().position(|a| a == "--script").map(|i| i + 1) } else { None };
let mut file = None;
for (i, a) in raw.iter().map(AsRef::as_ref).enumerate() {
if a.to_str().is_none() {
if Some(i) != file_at && Some(i) != script_at {
return Err(format!("argument {} is not valid Unicode: {}", i + 1, a.to_string_lossy()));
}
if Some(i) == file_at {
file = Some(PathBuf::from(a));
}
}
}
Ok((args, file))
}
/// The password for a protected Word file: `--password`, `--password-file`, or
/// `WORDCRAFT_PASSWORD`, in that order. The file form exists because a password on a command line
/// is readable by every other process on the machine; a trailing newline is dropped so a file
/// written by `echo` works. Never logged, and never named in an error.
fn password_from(args: &[String]) -> Result<Option<String>, String> {
if let Some(password) = arg_value(args, "--password") {
return Ok(Some(password));
}
if let Some(path) = arg_value(args, "--password-file") {
let raw = std::fs::read_to_string(&path).map_err(|e| format!("--password-file {path}: {e}"))?;
return Ok(Some(raw.trim_end_matches(['\r', '\n']).to_string()));
}
Ok(std::env::var("WORDCRAFT_PASSWORD").ok().filter(|p| !p.is_empty()))
}
/// The positional arguments, skipping every option's value so an option value is never read as a
/// path. Uses the same option specifications as [`validate_options`].
fn positionals<'a>(args: &'a [String], specs: &[OptionSpec]) -> Vec<&'a String> {
positional_indices(args, specs).into_iter().filter_map(|i| args.get(i)).collect()
}
/// Keep the original indices too, so [`text_args`] can open a positional path by its native name.
fn positional_indices(args: &[String], specs: &[OptionSpec]) -> Vec<usize> {
let mut out = Vec::new();
let mut i = 0;
while let Some(arg) = args.get(i) {
let takes_value =
arg.starts_with("--") && specs.iter().any(|s| s.name == arg && s.takes_value) && args.get(i + 1).is_some_and(|v| !v.starts_with("--"));
if takes_value {
i += 2;
} else {
if !arg.starts_with("--") {
out.push(i);
}
i += 1;
}
}
out
}
/// A headless session in the system region: every way the CLI starts one gives `file.new` the
/// same paper (#1381).
fn session(doc: wordcraft_doc::Document) -> Session {
let mut s = Session::new(doc);
s.system_region = system_region();
s
}
/// The system region, read as the app reads it (locale variables, else the platform's locale).
fn system_region() -> wordcraft_engine::Region {
wordcraft_engine::Region::from_locale_vars(|name| std::env::var(name).ok(), sys_locale::get_locale)
}
/// The body text for `text`: the plain-text export, so list items keep their bullet or number label.
fn listed_text(doc: &wordcraft_doc::Document) -> Result<String, String> {
let bytes = wordcraft_engine::io::save_bytes("out.txt", doc)?;
Ok(String::from_utf8_lossy(&bytes).replace("\r\n", "\n"))
}
/// `--author NAME`: the author recorded on tracked changes and comments (`file.setAuthor`).
/// The command also checks whether the open document is protected: this name determines which
/// named editing exceptions the session can use, so the flag must not bypass that check.
fn set_author(s: &mut Session, name: &str) -> Result<(), String> {
s.run("file.setAuthor", &json!({"name": name})).map(|_| ()).map_err(|e| escape_text(&format!("--author: {e}"), false))
}
/// `mcp`'s headless backend: a session confined to `roots`, its author `author` when given. The caller confines the
/// process to the same roots first (`confine_process`), which a test must not do.
fn headless_mcp(
roots: std::sync::Arc<wordcraft_engine::file_access::AutomationRoots>,
author: Option<&str>,
) -> Result<wordcraft_mcp::Headless, String> {
let mut headless = wordcraft_mcp::Headless::default().with_automation_roots(Some(roots));
if let Some(name) = author {
set_author(&mut headless.session, name)?;
}
Ok(headless)
}
fn arg_value(args: &[String], name: &str) -> Option<String> {
args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).cloned()
}
enum OptionArg<'a> {
Absent,
Duplicate,
MissingValue,
Value(&'a str),
}
fn find_option_arg<'a>(args: &'a [String], name: &str) -> OptionArg<'a> {
let mut matches = args.iter().enumerate().filter(|(_, a)| *a == name);
let Some((i, _)) = matches.next() else {
return OptionArg::Absent;
};
if matches.next().is_some() {
return OptionArg::Duplicate;
}
match args.get(i + 1) {
None => OptionArg::MissingValue,
Some(val) if val.starts_with("--") => OptionArg::MissingValue,
Some(val) => OptionArg::Value(val.as_str()),
}
}
fn parse_page_arg(command: &str, args: &[String]) -> Result<Option<u64>, String> {
match find_option_arg(args, "--page") {
OptionArg::Absent => Ok(None),
OptionArg::Duplicate => Err(format!("{command}: duplicate --page option")),
OptionArg::MissingValue => Err(format!("{command}: --page requires a value")),
OptionArg::Value(val) => {
let n = val.parse::<u64>().map_err(|_| format!("{command}: invalid --page `{val}`: not a valid integer"))?;
if n == 0 {
return Err(format!("{command}: invalid --page `0`: page numbers start at 1"));
}
Ok(Some(n))
}
}
}
fn parse_scale_arg(command: &str, args: &[String]) -> Result<Option<f64>, String> {
match find_option_arg(args, "--scale") {
OptionArg::Absent => Ok(None),
OptionArg::Duplicate => Err(format!("{command}: duplicate --scale option")),
OptionArg::MissingValue => Err(format!("{command}: --scale requires a value")),
OptionArg::Value(val) => {
let scale = val.parse::<f64>().map_err(|_| format!("{command}: invalid --scale `{val}`: not a number"))?;
if !scale.is_finite() || scale <= 0.0 {
return Err(format!("{command}: invalid --scale `{val}`: scale must be a finite positive number"));
}
Ok(Some(scale))
}
}
}
#[derive(Clone, Copy)]
struct OptionSpec {
name: &'static str,
takes_value: bool,
}
fn validate_options(command: &str, args: &[String], specs: &[OptionSpec]) -> Result<(), String> {
let mut i = 0;
while let Some(arg) = args.get(i) {
if let Some(name) = arg.strip_prefix("--") {
let Some(spec) = specs.iter().find(|spec| spec.name == arg) else {
return Err(format!("{command}: unknown option --{name}"));
};
if spec.takes_value && args.get(i + 1).is_some_and(|value| !value.starts_with("--")) {
i += 2;
} else {
i += 1;
}
} else {
i += 1;
}
}
Ok(())
}
/// Take `--automation-read-root` / `--automation-write-root` (each `--flag DIR` or `--flag=DIR`,
/// once) out of `args`, and open the roots, which must be existing folders. Returns the arguments
/// that are left. A malformed root flag is an error, never a root silently left out.
fn automation_roots(
command: &str,
args: &[String],
) -> Result<(Option<std::sync::Arc<wordcraft_engine::file_access::AutomationRoots>>, Vec<String>), String> {
let mut found = automation_args::AutomationArgs::new(None, None);
let mut left = Vec::new();
let mut it = args.iter().cloned();
while let Some(arg) = it.next() {
if !found.consume(&arg, &mut it).map_err(|e| format!("{command}: {e}"))? {
left.push(arg);
}
}
let roots = wordcraft_engine::file_access::AutomationRoots::new(found.read_root.as_deref(), found.write_root.as_deref())
.map_err(|e| format!("{command}: {e}"))?;
Ok((roots, left))
}
/// The password a protected Word file is opened with: `--password` (which any other process on
/// the machine can read from the command line), `--password-file`, or `WORDCRAFT_PASSWORD`.
const PASSWORD_OPTIONS: &[OptionSpec] =
&[OptionSpec { name: "--password", takes_value: true }, OptionSpec { name: "--password-file", takes_value: true }];
const CONVERT_OPTIONS: &[OptionSpec] = &[
OptionSpec { name: "--markup", takes_value: false },
OptionSpec { name: "--format", takes_value: true },
OptionSpec { name: "--update-fields", takes_value: false },
OptionSpec { name: "--strict", takes_value: false },
OptionSpec { name: "--password", takes_value: true },
OptionSpec { name: "--password-file", takes_value: true },
];
const RENDER_OPTIONS: &[OptionSpec] = &[
OptionSpec { name: "--strict", takes_value: false },
OptionSpec { name: "--page", takes_value: true },
OptionSpec { name: "--scale", takes_value: true },
OptionSpec { name: "--password", takes_value: true },
OptionSpec { name: "--password-file", takes_value: true },
];
const RUN_OPTIONS: &[OptionSpec] = &[
OptionSpec { name: "--file", takes_value: true },
OptionSpec { name: "--password", takes_value: true },
OptionSpec { name: "--password-file", takes_value: true },
OptionSpec { name: "--template", takes_value: true },
OptionSpec { name: "--cmd", takes_value: true },
OptionSpec { name: "--script", takes_value: true },
OptionSpec { name: "--save", takes_value: true },
OptionSpec { name: "--page", takes_value: true },
OptionSpec { name: "--scale", takes_value: true },
OptionSpec { name: "--print", takes_value: false },
OptionSpec { name: "--author", takes_value: true },
];
const COMMANDS_OPTIONS: &[OptionSpec] = &[OptionSpec { name: "--json", takes_value: false }];
const PARITY_OPTIONS: &[OptionSpec] = &[OptionSpec { name: "--markdown", takes_value: false }];
/// Why `mcp` won't start unconfined (shared rule 18, #7124).
const MCP_NEEDS_ROOTS: &str = "mcp: give both --automation-read-root DIR and --automation-write-root DIR: an agent's \
commands may read only inside the read root and write only inside the write root (the same folder may be both)";
/// Why `mcp --connect` is refused: the running app would not confine the agent's file access.
// lean: refused outright; allow it once the app confines its control channel and reports both roots.
const MCP_CONNECT_REFUSED: &str = "mcp: --connect is refused for now: the desktop app does not confine its control \
channel to automation roots yet (storytold/wordcraft#3695, #5819). Use the headless server: wordcraft-cli mcp \
--automation-read-root DIR --automation-write-root DIR";
const MCP_OPTIONS: &[OptionSpec] = &[OptionSpec { name: "--connect", takes_value: true }, OptionSpec { name: "--author", takes_value: true }];
const ZOTERO_OPTIONS: &[OptionSpec] = &[
OptionSpec { name: "--cmd", takes_value: true },
OptionSpec { name: "--save", takes_value: true },
OptionSpec { name: "--trace", takes_value: false },
OptionSpec { name: "--port", takes_value: true },
];
/// Why a CLI run stopped early.
#[derive(Debug, PartialEq)]
enum Failure {
/// A real error, reported on stderr with a failing exit status.
Error(String),
/// Whoever read stdout closed it (`wordcraft-cli commands --json | head`): there is nobody left
/// to write to, so stop quietly and exit 0 like other command-line tools.
StdoutClosed,
/// `convert --strict` refused: the text for stderr (the report's lines, then its JSON line).
/// Exit status 3.
Strict(String),
}
impl fmt::Display for Failure {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Failure::Error(e) => f.write_str(e),
Failure::StdoutClosed => f.write_str("stdout closed"),
Failure::Strict(report) => f.write_str(report),
}
}
}
impl From<String> for Failure {
fn from(e: String) -> Self {
Failure::Error(e)
}
}
impl From<&str> for Failure {
fn from(e: &str) -> Self {
Failure::Error(e.into())
}
}
impl From<std::io::Error> for Failure {
fn from(e: std::io::Error) -> Self {
if e.kind() == std::io::ErrorKind::BrokenPipe { Failure::StdoutClosed } else { Failure::Error(e.to_string()) }
}
}
/// Write to stdout through one locked handle and flush. Unlike `println!`, a closed stdout comes
/// back as an error (`Failure::StdoutClosed`) instead of a panic.
fn write_stdout(write: impl FnOnce(&mut std::io::StdoutLock<'static>) -> std::io::Result<()>) -> Result<(), Failure> {
let mut out = std::io::stdout().lock();
write(&mut out)?;
out.flush()?;
Ok(())
}
/// The operand after `--script`, by its real name (it may not be valid Unicode).
fn script_operand<S: AsRef<OsStr>>(raw: &[S]) -> Option<PathBuf> {
let at = raw.iter().position(|a| a.as_ref() == OsStr::new("--script"))?;
raw.get(at + 1).map(|a| PathBuf::from(a.as_ref()))
}
/// A failed `--strict` export: a strict refusal becomes [`Failure::Strict`] carrying what stderr
/// shows (each line of the report as `wordcraft-cli: …`, then its JSON on one line, from
/// `file.strictReport` for `page` of a page image, else the PDF); any other error is an ordinary
/// failure.
fn refusal(s: &mut Session, e: wordcraft_engine::CmdError, markup: bool, page: Option<u64>) -> Failure {
if !matches!(&e, wordcraft_engine::CmdError::Failed(m) if m.starts_with("strict: ")) {
return engine_error(e);
}
let mut params = json!({"markup": markup});
if let Some(page) = page {
params["page"] = json!(page);
}
Failure::Strict(match s.run("file.strictReport", &params).map_err(|e| e.to_string()) {
Ok(json) => {
let mut text = String::new();
for line in report_lines(&json) {
text += &format!("wordcraft-cli: {}\n", escape_peer(&line));
}
text + &json_line_safe(&json.to_string())
}
Err(e) => format!("wordcraft-cli: strict: refused, and the report could not be made: {}", escape_text(&e, false)),
})
}
/// The report's human lines, from its JSON (the engine's `StrictReport::lines`).
fn report_lines(json: &Value) -> Vec<String> {
wordcraft_engine::strict::lines_from_json(json)
}
/// Explicitly update unlocked fields in a session before saving the document.
///
/// If field updates are disabled by document protection (`CmdError::Disabled`), logs a warning to
/// stderr and continues conversion rather than aborting. Other command failures are converted to
/// [`Failure`] via [`engine_error`].
///
/// # Arguments
///
/// * `s` - The active document [`Session`] whose unlocked fields should be refreshed.
///
/// # Errors
///
/// Returns `Err(Failure)` if the command fails with an error other than `CmdError::Disabled`.
fn update_fields(s: &mut Session) -> Result<(), Failure> {
if let Err(e) = s.run("references.updateFields", &json!({})) {
if matches!(e, CmdError::Disabled(_)) {
eprintln!("wordcraft-cli: warning: {e}");
} else {
return Err(engine_error(e));
}
}
Ok(())
}
/// `convert <in> <out>`: `rest` is the command line after `convert`, `open` opens the input.
fn run_convert(rest: &[String], open: impl Fn(&str, Option<&str>) -> Result<Session, Failure>) -> Result<(), Failure> {
validate_options("convert", rest, CONVERT_OPTIONS)?;
// `--format wordml2003` (or `flatopc`) picks the kind of `.xml` file; its value isn't a path.
let format = match find_option_arg(rest, "--format") {
OptionArg::Absent => None,
OptionArg::Duplicate => return Err("convert: duplicate --format option".into()),
OptionArg::MissingValue => return Err("convert: --format requires a value".into()),
OptionArg::Value(value) => Some(value),
};
let paths = positionals(rest, CONVERT_OPTIONS);
let (i, o) = (paths.first().ok_or_else(missing_argument)?.to_string(), paths.get(1).ok_or_else(missing_argument)?.to_string());
let markup = rest.iter().any(|a| a == "--markup");
let strict = rest.iter().any(|a| a == "--strict");
// Before the input is opened: a wrong output type is a usage error, not a file error.
let to_png = o.to_ascii_lowercase().ends_with(".png");
if strict && !(to_png || o.to_ascii_lowercase().ends_with(".pdf")) {
return Err("convert: --strict needs a .pdf or .png output".into());
}
let password = password_from(rest)?;
let mut s = open(&i, password.as_deref())?;
if rest.iter().any(|a| a == "--update-fields") {
update_fields(&mut s)?;
}
let r = if to_png {
s.run("file.exportPng", &json!({"path": o, "page": 1, "markup": markup, "strict": strict}))
} else {
let mut params = json!({"path": o, "markup": markup, "strict": strict});
if let Some(f) = format {
params["format"] = json!(f);
}
s.run("file.save", &params)
};
if let Err(e) = r {
return Err(if strict { refusal(&mut s, e, markup, to_png.then_some(1)) } else { engine_error(e) });
}
eprintln!("wrote {o}");
Ok(())
}
fn load_run_script(rest: &[String], script_path: Option<&Path>) -> Result<Option<script::Script>, Failure> {
match arg_value(rest, "--script") {
Some(path) if !path.starts_with("--") => {
let source = script_path.unwrap_or(Path::new(&path));
Ok(Some(script::load(source).map_err(engine_error)?))
}
_ if rest.iter().any(|arg| arg == "--script") => Err("run: --script requires a value".into()),
_ => Ok(None),
}
}
fn run_source_paths(rest: &[String], script: Option<&script::Script>) -> (Option<String>, Option<String>) {
// A source named on the command line wins over both of the script's.
let (mut from_file, mut from_template) = (arg_value(rest, "--file"), arg_value(rest, "--template"));
if from_file.is_none() && from_template.is_none() {
from_file = script.and_then(|loaded| loaded.file.clone());
from_template = script.and_then(|loaded| loaded.template.clone());
}
(from_file, from_template)
}
/// Run the subcommand named by `args` (the command line after the program name). Files named
/// there are opened by their real names, which may not be valid Unicode.
fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
let script_path = script_operand(args);
let (args, file) = text_args(args)?;
// Opens the file by its real name, which its text in `args` may have lost, and with the
// password of a protected document (`password_from`).
let open = |text: &str, password: Option<&str>| open(file.as_deref().unwrap_or(Path::new(text)), password);
let cmd = args.first().map(String::as_str).unwrap_or("");
let rest: Vec<String> = args.iter().skip(1).cloned().collect();
// Before options are checked or files and folders opened.
if wants_help(cmd, &rest) {
return write_stdout(|o| write!(o, "{USAGE}"));
}
match cmd {
"convert" => run_convert(&rest, open),
"info" => {
validate_options("info", &rest, PASSWORD_OPTIONS)?;
let paths = positionals(&rest, PASSWORD_OPTIONS);
let password = password_from(&rest)?;
let mut s = open(paths.first().ok_or_else(missing_argument)?, password.as_deref())?;
let info = serde_json::to_string_pretty(&s.run("file.info", &json!({})).map_err(engine_error)?).unwrap_or_default();
write_stdout(|o| writeln!(o, "{info}"))
}
"text" => {
validate_options("text", &rest, PASSWORD_OPTIONS)?;
let paths = positionals(&rest, PASSWORD_OPTIONS);
let password = password_from(&rest)?;
let s = open(paths.first().ok_or_else(missing_argument)?, password.as_deref())?;
let text = listed_text(&s.doc)?;
write_stdout(|o| writeln!(o, "{text}"))
}
"inspect" => {
validate_options("inspect", &rest, PASSWORD_OPTIONS)?;
let paths = positionals(&rest, PASSWORD_OPTIONS);
let password = password_from(&rest)?;
let mut s = open(paths.first().ok_or_else(missing_argument)?, password.as_deref())?;
let tree = serde_json::to_string_pretty(&s.run("document.inspect", &json!({})).map_err(engine_error)?).unwrap_or_default();
write_stdout(|o| writeln!(o, "{tree}"))
}
"render" => {
validate_options("render", &rest, RENDER_OPTIONS)?;
let paths = positionals(&rest, RENDER_OPTIONS);
let password = password_from(&rest)?;
let (Some(i), Some(o)) = (paths.first(), paths.get(1)) else {
return Err(missing_argument());
};
let (i, o) = (i.to_string(), o.to_string());
let page = parse_page_arg("render", &rest)?.unwrap_or(1);
let scale = parse_scale_arg("render", &rest)?.unwrap_or(2.0);
let mut s = open(&i, password.as_deref())?;
let strict = rest.iter().any(|a| a == "--strict");
let mut params = json!({"path": o, "page": page, "scale": scale, "strict": strict});
if strict {
// The check and its report must see the page as it is written.
params["markup"] = json!(false);
}
let r = match s.run("file.exportPng", &params) {
Ok(r) => r,
Err(e) if strict => return Err(refusal(&mut s, e, false, Some(page))),
Err(e) => return Err(engine_error(e)),
};
write_stdout(|o| writeln!(o, "{r}"))
}
"run" => {
for (i, arg) in rest.iter().enumerate() {
if arg == "--cmd" && rest.get(i + 1).is_none_or(|value| value.starts_with("--")) {
return Err("--cmd needs a value".into());
}
}
validate_options("run", &rest, RUN_OPTIONS)?;
let page = parse_page_arg("run", &rest)?;
let scale = parse_scale_arg("run", &rest)?;
let password = password_from(&rest)?;
let script = load_run_script(&rest, script_path.as_deref())?;
let (from_file, from_template) = run_source_paths(&rest, script.as_ref());
let mut s = match (from_file, from_template) {
(Some(f), _) => open(&f, password.as_deref())?,
// Both go through `file.new`, which puts a blank document on the region's paper (#3152).
// `file.new` opens beside the session's first document, which is then closed: the
// run starts with one open document.
(None, t) => {
let mut s = session(wordcraft_doc::Document::new());
let first = s.document_id();
let params = t.map_or_else(|| json!({}), |t| json!({"template": t}));
s.run("file.new", &params).map_err(engine_error)?;
s.close_document(first).map_err(engine_error)?;
s
}
};
if let Some(name) = arg_value(&rest, "--author") {
set_author(&mut s, &name)?;
}
let print = rest.iter().any(|a| a == "--print");
for (n, (id, params)) in script.iter().flat_map(|c| c.commands.iter()).enumerate() {
let r = s.run(id, params).map_err(|e| engine_error(format!("command {} ({id}): {e}", n + 1)))?;
if print {
write_stdout(|o| writeln!(o, "{id}: {r}"))?;
}
}
let mut i = 0;
while i < rest.len() {
if rest.get(i).map(String::as_str) == Some("--cmd") {
let spec = rest.get(i + 1).filter(|value| !value.starts_with("--")).ok_or("--cmd needs a value")?;
let (id, params) = match spec.split_once('=') {
Some((id, p)) => {
(id.to_string(), serde_json::from_str::<Value>(p).map_err(|e| engine_error(format!("{id}: bad JSON params: {e}")))?)
}
None => (spec.clone(), json!({})),
};
let r = s.run(&id, &params).map_err(|e| engine_error(format!("{id}: {e}")))?;
if print {
write_stdout(|o| writeln!(o, "{id}: {r}"))?;
}
i += 2;
} else {
i += 1;
}
}
let outputs: Vec<String> = script.iter().flat_map(|c| c.save.iter().cloned()).chain(arg_value(&rest, "--save")).collect();
// Check every output can be made before writing any, so a bad one leaves no half-done job.
for out in &outputs {
let parent = Path::new(out).parent().filter(|p| !p.as_os_str().is_empty());
if let Some(p) = parent.filter(|p| !p.is_dir()) {
return Err(format!("{out}: folder {} does not exist", p.display()).into());
}
if Path::new(out).is_dir() {
return Err(format!("{out}: is a folder, not a file").into());
}
if !out.to_ascii_lowercase().ends_with(".png") {
wordcraft_engine::io::save_bytes(out, &s.doc).map_err(engine_error)?;
}
}
for out in outputs {
let r = if out.to_ascii_lowercase().ends_with(".png") {
let mut v = json!({"path": out});
if let Some(n) = page {
v["page"] = json!(n);
}
if let Some(k) = scale {
v["scale"] = json!(k);
}
s.run("file.exportPng", &v)
} else {
s.run("file.save", &json!({"path": out}))
};
r.map_err(engine_error)?;
eprintln!("wrote {out}");
}
Ok(())
}
"commands" => {
validate_options("commands", &rest, COMMANDS_OPTIONS)?;
let s = session(wordcraft_doc::Document::new());
if rest.iter().any(|a| a == "--json") {
let list = serde_json::to_string_pretty(&s.registry.describe()).unwrap_or_default();
write_stdout(|o| writeln!(o, "{list}"))
} else {
write_stdout(|o| {
for c in s.registry.all() {
writeln!(o, "{:<32} {:<36} {:<24} {}", c.id, c.label, c.shortcut, c.location)?;
}
Ok(())
})
}
}
"parity" => {
validate_options("parity", &rest, PARITY_OPTIONS)?;
let s = session(wordcraft_doc::Document::new());
let p = wordcraft_engine::catalog::parity(&s.registry);
if rest.iter().any(|a| a == "--markdown") {
write_stdout(|o| write!(o, "{}", parity_markdown(&p)))
} else {
write_stdout(|o| writeln!(o, "{}", serde_json::to_string_pretty(&p).unwrap_or_default()))
}
}
"mcp" => {
let (roots, rest) = automation_roots("mcp", &rest)?;
// Refused with or without a value, before the option check, so `--connect=…` gets this refusal rather than
// "unknown option": a bare trailing `--connect` must not slip past either.
if rest.iter().any(|a| a == "--connect" || a.starts_with("--connect=")) {
return Err(MCP_CONNECT_REFUSED.into());
}
validate_options("mcp", &rest, MCP_OPTIONS)?;
// Shared rule 18 (#7124): an agent entry point never runs unconfined.
let Some(roots) = roots.filter(|r| r.read_root().is_some() && r.write_root().is_some()) else {
return Err(MCP_NEEDS_ROOTS.into());
};
// Every thread of this process, not only the server's: nothing reaches past the roots.
wordcraft_engine::file_access::confine_process(roots.clone());
let show = |root: Option<&std::path::Path>| root.map_or_else(|| "none".to_string(), |r| r.display().to_string());
eprintln!("wordcraft-cli: files confined: read root {}, write root {}", show(roots.read_root()), show(roots.write_root()));
let backend: Box<dyn wordcraft_mcp::Backend> = Box::new(headless_mcp(roots, arg_value(&rest, "--author").as_deref())?);
let mut server = wordcraft_mcp::Server::new(backend);
let stdin = std::io::stdin();
// A client that closes our stdout has hung up: `serve` returns BrokenPipe and we end cleanly.
Ok(server.serve(stdin.lock(), std::io::stdout())?)
}
"zotero" => {
validate_options("zotero", &rest, ZOTERO_OPTIONS)?;
let paths = positionals(&rest, ZOTERO_OPTIONS);
let (Some(name), Some(file)) = (paths.first(), paths.get(1)) else {
return Err(missing_argument());
};
let command = wordcraft_zotero::Command::from_name(name).ok_or_else(|| format!("unknown Zotero command `{name}`\n\n{USAGE}"))?;
let mut s = open(file, None)?;
for spec in rest.iter().zip(rest.iter().skip(1)).filter(|(a, _)| *a == "--cmd").map(|(_, v)| v) {
let (id, params) = match spec.split_once('=') {
Some((id, p)) => {
(id.to_string(), serde_json::from_str::<Value>(p).map_err(|e| engine_error(format!("{id}: bad JSON params: {e}")))?)
}
None => (spec.clone(), json!({})),
};
s.run(&id, &params).map_err(|e| engine_error(format!("{id}: {e}")))?;
}
let mut opts = wordcraft_zotero::client::Options::default();
if let Some(p) = arg_value(&rest, "--port") {
opts.addr.set_port(p.parse().map_err(|_| format!("bad port `{p}`"))?);
}
let trace = rest.iter().any(|a| a == "--trace");
let mut bridge = wordcraft_zotero::Bridge::new();
let mut host = wordcraft_zotero::Headless::default();
let out = wordcraft_zotero::client::run_command(&opts, command, &mut |call| {
let r = bridge.handle(&mut s, &mut host, call);
if trace {
eprintln!("← {} {}", escape_peer(&call.method), escape_peer(&clip(&Value::Array(call.args.clone()).to_string())));
eprintln!("→ {}", escape_peer(&clip(&String::from_utf8_lossy(&wordcraft_zotero::wire::encode_reply(&r)))));
}
r
})
.map_err(engine_error)?;
for a in &host.alerts {
eprintln!("Zotero: {}", escape_peer(a));
}
eprintln!("{} calls, {}", out.calls, if out.completed { "completed" } else { "ended without completing (cancelled?)" });
if let Some(o) = arg_value(&rest, "--save") {
s.run("file.save", &json!({"path": o})).map_err(engine_error)?;
eprintln!("wrote {o}");
}
Ok(())
}
"--version" | "-V" => write_stdout(|o| writeln!(o, "wordcraft-cli {}", env!("CARGO_PKG_VERSION"))),
"" | "help" | "--help" | "-h" => write_stdout(|o| write!(o, "{USAGE}")),
other => Err(format!("unknown command `{other}`\n\n{USAGE}").into()),
}
}
/// At most 400 characters of `s`, for traces.
fn clip(s: &str) -> String {
match s.char_indices().nth(400) {
Some((i, _)) => format!("{}…", s.get(..i).unwrap_or(s)),
None => s.to_string(),
}
}
/// Text from another program (Zotero, or whatever answered on its port) for one diagnostic
/// line: backslashes, control characters (newline, escape, C1…), line separators and bidi
/// overrides are shown as escapes (`\\`, `\n`, `\u{1b}`), so it can't end its line, drive the
/// terminal or pass for other output.
fn escape_peer(s: &str) -> String {
escape_text(s, true)
}
/// Whether `c` must not reach a terminal as itself: a control character, a line or paragraph
/// separator, a bidi control, or one that shows nothing (soft hyphen, zero-width characters, word
/// joiners, the byte order mark, tag characters), which can hide or reorder what a line says.
fn is_unsafe_char(c: char) -> bool {
c.is_control()
|| matches!(
c,
'\u{00ad}'
| '\u{061c}'
| '\u{200b}'..='\u{200f}'
| '\u{2028}'..='\u{202e}'
| '\u{2060}'..='\u{2064}'
| '\u{2066}'..='\u{2069}'
| '\u{feff}'
| '\u{e0000}'..='\u{e007f}'
)
}
/// [`escape_peer`], with backslashes escaped only when `backslash` (error messages quote Windows
/// paths, and a backslash can't forge or hide anything).
fn escape_text(s: &str, backslash: bool) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
match c {
'\\' if backslash => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
c if is_unsafe_char(c) => out.extend(c.escape_unicode()),
c => out.push(c),
}
}
out
}
/// A JSON line safe to print: serde escapes control characters below U+0020 but not the other
/// characters [`is_unsafe_char`] names, which a crafted file could put in a report. They become
/// `\uXXXX` escapes (a surrogate pair above U+FFFF), so the line parses to the same value and
/// can't drive or spoof a terminal.
fn json_line_safe(json: &str) -> String {
let mut out = String::with_capacity(json.len());
for c in json.chars() {
if is_unsafe_char(c) {
for unit in c.encode_utf16(&mut [0u16; 2]) {
out.push_str(&format!("\\u{unit:04x}"));
}
} else {
out.push(c);
}
}
out
}
fn parity_markdown(p: &Value) -> String {
let mut s = String::from(
"# WordCraft feature parity\n\nGenerated by `cargo xtask parity` (`wordcraft-cli parity --markdown`): the word-processor feature catalog (`crates/engine/src/catalog.rs`) compared with the live command registry.\n\n",
);
s += &format!(
"**{} of {} catalog features have commands ({}%).**\n\n| Tab | Live | Total |\n|---|---|---|\n",
p["live"], p["total"], p["percent"]
);
for t in p["tabs"].as_array().cloned().unwrap_or_default() {
s += &format!("| {} | {} | {} |\n", t["tab"].as_str().unwrap_or(""), t["live"], t["total"]);
}
s += "\n## Missing\n\n";
for t in p["tabs"].as_array().cloned().unwrap_or_default() {
let m = t["missing"].as_array().cloned().unwrap_or_default();
if m.is_empty() {
continue;
}
s += &format!("### {}\n\n", t["tab"].as_str().unwrap_or(""));
for x in m {
s += &format!("- {}\n", x.as_str().unwrap_or(""));
}
s += "\n";
}
s
}
fn main() -> ExitCode {
let args: Vec<OsString> = std::env::args_os().skip(1).collect();
// Language packs installed in the suite's font store are used; `proof.installPack` installs
// only while the person has turned downloading on in the app.
wordcraft_engine::packs::use_font_store(false);
if let Some(source) = wordcraft_engine::packs::index_override() {
eprintln!("wordcraft-cli: Language packs come from a test source: {source}");
}
match run(&args) {
Ok(()) | Err(Failure::StdoutClosed) => ExitCode::SUCCESS,
Err(Failure::Error(e)) => {
eprintln!("wordcraft-cli: {e}");
ExitCode::FAILURE
}
Err(Failure::Strict(report)) => {
eprintln!("{report}");
ExitCode::from(3)
}
}
}
#[cfg(test)]
mod tests;
+397 -373
View File
@@ -1,303 +1,10 @@
use super::*;
use crate::launcher_profile_flag;
use std::ffi::{OsStr, OsString};
use std::io::Read;
use std::path::PathBuf;
/// A failed in-process run: the exit code and what stderr said (without its `error: ` prefix).
#[derive(Debug, PartialEq)]
struct Fail {
code: i32,
text: String,
}
impl std::fmt::Display for Fail {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.text)
}
}
/// Run the whole CLI in this process, as the binary does.
fn exec<S: AsRef<OsStr>>(args: &[S]) -> (i32, String, String) {
let (mut out, mut err) = (Vec::new(), Vec::new());
let code = crate::run(args.iter().map(|a| a.as_ref().to_owned()), &mut out, &mut err);
(code, String::from_utf8_lossy(&out).into_owned(), String::from_utf8_lossy(&err).into_owned())
}
/// `Ok` for exit 0, else the exit code and message.
fn run<S: AsRef<OsStr>>(args: &[S]) -> std::result::Result<(), Fail> {
let (code, _, err) = exec(args);
if code == 0 { Ok(()) } else { Err(Fail { code, text: err.trim_end().strip_prefix("error: ").unwrap_or(err.trim_end()).to_owned() }) }
}
fn args(values: &[&str]) -> Vec<String> {
values.iter().map(|value| (*value).into()).collect()
}
/// A usage error: exit 2, the message on stderr, nothing on stdout, and no work done.
fn usage(argv: &[&str]) -> String {
let (code, out, err) = exec(argv);
assert_eq!((code, out.as_str()), (2, ""), "{argv:?}: {err}");
err
}
#[test]
fn page_and_scale_are_checked_before_any_file_is_opened() {
for sub in [vec!["render", "missing.docx", "out.png"], vec!["run", "--template", "sample", "--save", "out.png"]] {
let with = |extra: &[&str]| usage(&[&sub[..], extra].concat());
for missing in [&["--page"][..], &["--scale"], &["--page", "--scale", "2"], &["--scale", "--page", "1"]] {
with(missing);
}
assert!(with(&["--page", "banana"]).contains("invalid --page `banana`: not a valid integer"));
assert!(with(&["--page", "0"]).contains("invalid --page `0`: page numbers start at 1"));
with(&["--page", "-1"]);
assert!(with(&["--scale", "banana"]).contains("invalid --scale `banana`: not a number"));
for bad in ["0", "-2", "NaN", "inf"] {
assert!(with(&["--scale", bad]).contains(&format!("invalid --scale `{bad}`: scale must be a finite positive number")));
}
with(&["--page", "1", "--page", "2"]);
with(&["--scale", "1", "--scale", "2"]);
}
}
#[test]
fn unknown_repeated_and_conflicting_options_are_usage_errors_before_file_access() {
assert!(usage(&["info", "missing.docx", "--passwrod", "x"]).contains("--passwrod"));
assert!(usage(&["render", "missing.docx", "out.png", "--sclae", "2"]).contains("--sclae"));
assert!(usage(&["zotero", "refresh", "missing.docx", "--prot", "1"]).contains("--prot"));
usage(&["convert", "missing.docx", "out.xml", "--format"]);
usage(&["convert", "missing.docx", "out.xml", "--format", "--markup"]);
usage(&["convert", "missing.docx", "out.xml", "--format", "flatopc", "--format", "wordml2003"]);
assert!(usage(&["convert", "missing.docx", "out.xml", "--format", "docx"]).contains("wordml2003"));
usage(&["convert", "missing.docx"]);
usage(&["convert", "a.docx", "b.docx", "c.docx"]);
usage(&["run", "--file", "a.docx", "--template", "blank"]);
usage(&["info"]);
usage(&["frobnicate"]);
assert!(usage(&["convert", "missing.docx", "out.docx", "--strict"]).contains("--strict needs a .pdf or .png output"));
// A valid single value reaches file access, rather than an option error.
let (code, _, err) = exec(&["convert", "missing.docx", "out.xml", "--format", "flatopc"]);
assert_eq!(code, 1);
assert!(err.starts_with("error: missing.docx:"), "{err}");
}
#[test]
fn cmd_and_script_values_are_checked_by_the_parser() {
for argv in [
vec!["run", "--cmd"],
vec!["run", "--cmd", "--save", "out.docx"],
vec!["run", "--cmd", "caret.docEnd", "--cmd", "--print"],
vec!["run", "--cmd", "--bogus"],
vec!["run", "--script", "--cmd", "caret.docEnd"],
] {
usage(&argv);
}
assert!(usage(&["run", "--cmd", "text.insert={nope"]).contains("bad JSON params"));
assert_eq!(run(&args(&["run", "--cmd", "caret.docEnd", "--cmd", "caret.docStart"])), Ok(()));
}
#[test]
fn the_author_flag_names_the_headless_session() {
let mut s = Session::new(wordcraft_doc::Document::new());
assert!(set_author(&mut s, " Claude (copyedit) ").is_ok());
assert_eq!(s.author, "Claude (copyedit)");
assert!(set_author(&mut s, " ").is_err_and(|e| e.starts_with("--author:")));
assert_eq!(run(&args(&["run", "--author", "Claude", "--cmd", "review.trackChanges={\"value\":true}"])), Ok(()));
// The flag goes through the same protection check as the command.
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("review.restrict", &json!({"mode": "readOnly"})).unwrap();
let before = s.author.clone();
assert!(set_author(&mut s, "Claude").is_err());
assert_eq!(s.author, before);
assert!(s.run("file.setAuthor", &json!({"name": "Claude"})).is_err());
}
#[test]
fn the_password_comes_from_an_option_or_a_file_and_never_shows_in_an_error() {
let open = |password: Option<&str>, file: Option<&str>| Password { password: password.map(Into::into), password_file: file.map(PathBuf::from) };
assert_eq!(password_from(&open(None, None)), Ok(None));
assert_eq!(password_from(&open(Some("s3cret"), None)), Ok(Some("s3cret".into())));
// `--password` wins over the file.
assert_eq!(password_from(&open(Some("a"), Some("/nonexistent"))), Ok(Some("a".into())));
let path = std::env::temp_dir().join(format!("wordcraft-cli-password-test-{}.txt", std::process::id()));
std::fs::write(&path, "s3cret\r\n").unwrap();
let got = password_from(&open(None, path.to_str()));
std::fs::remove_file(&path).ok();
assert_eq!(got, Ok(Some("s3cret".into())), "only the trailing newline is lost");
let err = password_from(&open(None, Some("/nonexistent/secret.txt"))).unwrap_err().to_string();
assert!(err.contains("--password-file"), "{err}");
}
/// A password file on the command line beats the variable, a blank variable is unset, and `--help` shows neither value.
#[test]
fn the_password_variable_is_read_by_the_flag_and_hidden() {
let parse = |argv: &[&str]| crate::args::parse(&argv.iter().map(OsString::from).collect::<Vec<_>>());
let help = parse(&["info", "--help"]).unwrap_err().render().to_string();
assert!(help.contains("WORDCRAFT_PASSWORD") || help.contains("--password"), "{help}");
let Err(e) = parse(&["info", "--password"]) else { panic!("a missing value must not parse") };
assert_eq!(e.exit_code(), 2);
let top = parse(&["--help"]).unwrap_err().render().to_string();
assert!(top.contains("WORDCRAFT_PASSWORD") && top.contains("WORDCRAFT_REGION") && top.contains("Exit status"), "{top}");
}
#[test]
fn mcp_needs_both_roots_and_refuses_connect() {
let scratch = Scratch::new("entry");
let base = scratch.0.clone();
std::fs::create_dir_all(base.join("in")).unwrap();
std::fs::create_dir_all(base.join("out")).unwrap();
let read = format!("--automation-read-root={}", base.join("in").display());
let write = format!("--automation-write-root={}", base.join("out").display());
for given in [vec![], vec![read.clone()], vec![write.clone()], vec!["--author".to_string(), "Claude".to_string()]] {
let line = [vec!["mcp".to_string()], given].concat();
let err = usage(&line.iter().map(String::as_str).collect::<Vec<_>>());
assert!(err.contains("--automation-read-root") || err.contains("--automation-write-root"), "{line:?}: {err}");
}
let missing = usage(&["mcp", "--automation-read-root", "a", "--automation-read-root=b", "--automation-write-root", "c"]);
assert!(missing.contains("--automation-read-root"), "{missing}");
usage(&["mcp", "--automation-read-root=", "--automation-write-root=x"]);
// A folder that does not exist is an error, not a server that quietly runs unconfined.
let (code, _, err) = exec(&["mcp", "--automation-read-root", "/definitely/not/a/folder", "--automation-write-root", "/definitely/not/a/folder"]);
assert_eq!(code, 1);
assert!(err.starts_with("error: mcp: cannot open the automation read root"), "{err}");
// `--connect` is refused whether or not it has roots, before anything connects (#3695, #5819).
let dir = base.to_string_lossy().into_owned();
for line in [
args(&["mcp", "--connect", "127.0.0.1:9"]),
args(&["mcp", "--connect=127.0.0.1:9", "--author", "Claude"]),
args(&["mcp", "--connect", "127.0.0.1:9", "--automation-read-root", &dir, "--automation-write-root", &dir]),
] {
let (code, _, err) = exec(&line);
assert_eq!(code, 1, "{line:?}");
assert!(err.contains("--connect") && err.contains("#3695") && err.contains("#5819"), "{line:?}: {err}");
}
}
#[test]
fn every_file_opening_subcommand_reaches_the_open_with_a_non_unicode_name_but_not_an_output() {
#[cfg(unix)]
{
use std::os::unix::ffi::OsStringExt;
let latin1 = || OsString::from_vec(b"/definitely/not/caf\xe9.docx".to_vec());
for argv in [
vec![OsString::from("convert"), latin1(), "out.pdf".into()],
vec!["info".into(), latin1()],
vec!["text".into(), latin1()],
vec!["inspect".into(), latin1()],
vec!["render".into(), latin1(), "out.png".into()],
vec!["run".into(), "--file".into(), latin1()],
vec!["zotero".into(), "refresh".into(), latin1()],
] {
let (code, _, err) = exec(&argv);
assert_eq!(code, 1, "{argv:?}: {err}");
assert!(err.contains("No such file"), "{argv:?}: {err}");
}
// An output the engine takes as text must be Unicode: a failure, and nothing opened.
let out = OsString::from_vec(b"caf\xe9.png".to_vec());
let (code, _, err) = exec(&["render".into(), OsString::from("in.docx"), out]);
assert_eq!(code, 1);
assert!(err.contains("not valid Unicode"), "{err}");
// Elsewhere clap refuses it as usage.
assert_eq!(exec(&["run".into(), OsString::from("--template"), OsString::from_vec(b"caf\xe9".to_vec())]).0, 2);
}
}
/// `validate`: PASS is 0; FAIL, INCOMPLETE and a file that can't be read are 1 (RFC-0018 rule 1.2); usage is 2.
#[test]
fn validate_exits_0_for_pass_1_for_anything_else_and_2_for_usage() {
let dir = script_dir("validate-exit");
let good = dir.join("good.docx");
run(&args(&["run", "--template", "sample", "--save", &good.to_string_lossy()])).unwrap();
let good = good.to_string_lossy().into_owned();
let (code, out, _) = exec(&["validate", &good]);
assert_eq!((code, out.lines().next()), (0, Some("PASS")));
let (code, out, _) = exec(&["validate", "--json", &good]);
assert_eq!(code, 0);
assert!(out.contains("\"verdict\""), "{out}");
let broken = dir.join("broken.docx");
std::fs::write(&broken, b"not a zip").unwrap();
let (code, out, _) = exec(&["validate".to_string(), broken.to_string_lossy().into_owned()]);
assert_eq!(code, 1, "{out}");
assert!(out.starts_with("FAIL") || out.starts_with("INCOMPLETE"), "{out}");
let (code, _, err) = exec(&["validate", "/definitely/not/there.docx"]);
assert_eq!(code, 1);
assert!(err.starts_with("error: /definitely/not/there.docx:"), "{err}");
usage(&["validate"]);
usage(&["validate", &good, &good]);
usage(&["validate", &good, "--bogus"]);
}
#[test]
fn help_and_version_go_to_stdout_with_exit_0() {
for argv in [vec!["--version"], vec!["-V"], vec!["--help"], vec!["-h"], vec!["help"], vec!["convert", "--help"], vec!["help", "validate"]] {
let (code, out, err) = exec(&argv);
assert_eq!((code, err.as_str()), (0, ""), "{argv:?}");
assert!(out.contains("wordcraft-cli"), "{argv:?}: {out}");
}
let (_, out, _) = exec(&["--version"]);
assert_eq!(out.trim(), format!("wordcraft-cli {}", env!("CARGO_PKG_VERSION")));
// The version is not a subcommand; with no arguments the help is shown as an error, exit 2.
usage(&["version"]);
assert_eq!(exec::<&str>(&[]).0, 2);
// Every subcommand's help ends with the exit status.
for sub in crate::command().get_subcommands().map(|c| c.get_name().to_owned()).filter(|n| n != "help") {
let (code, out, _) = exec(&[sub.as_str(), "--help"]);
assert_eq!(code, 0, "{sub}");
assert!(out.contains("Exit status"), "{sub}: {out}");
}
}
#[test]
fn the_launcher_bootstrap_exits_2_before_anything_runs() {
let err = usage(&["--launch-profile=nightly-v1", "info", "x.docx"]);
assert!(err.starts_with("error: --launch-profile and --profile-root"), "{err}");
}
#[test]
fn a_closed_stdout_ends_quietly_and_other_write_errors_fail() {
struct Closed(std::io::ErrorKind);
impl Write for Closed {
fn write(&mut self, _: &[u8]) -> std::io::Result<usize> {
Err(self.0.into())
}
fn flush(&mut self) -> std::io::Result<()> {
Err(self.0.into())
}
}
let mut err = Vec::new();
assert_eq!(crate::run(["commands"], &mut Closed(std::io::ErrorKind::BrokenPipe), &mut err), 0);
assert!(err.is_empty());
assert_eq!(crate::run(["commands"], &mut Closed(std::io::ErrorKind::PermissionDenied), &mut err), 1);
assert!(String::from_utf8_lossy(&err).starts_with("error: "));
}
#[test]
fn convert_strict_and_render_strict_refusals_exit_1() {
// A document whose text can't be drawn is a refusal: exit 1 with the report on stderr and no file.
let dir = script_dir("strict-exit");
let out = dir.join("out.pdf");
let (code, _, err) = exec(&["convert", "/definitely/not/there.docx", &out.to_string_lossy(), "--strict"]);
assert_eq!(code, 1, "{err}");
assert!(!out.exists());
}
/// The desktop app's Nightly bootstrap is never a CLI option, in either spelling.
#[test]
fn the_launcher_profile_bootstrap_is_refused_in_both_forms() {
for argv in [
&["--launch-profile", "nightly-v1", "--profile-root", "/nightly/profiles/wordcraft", "--version"][..],
&["--launch-profile=nightly-v1", "--profile-root=/nightly/profiles/wordcraft"][..],
&["--profile-root", "/nightly/profiles/wordcraft"][..],
] {
let argv: Vec<std::ffi::OsString> = argv.iter().map(std::ffi::OsString::from).collect();
assert!(launcher_profile_flag(&argv), "{argv:?}");
}
for argv in [&["--version"][..], &["proof.check", "--launch-profiles"][..], &["--profile-roots"][..]] {
let argv: Vec<std::ffi::OsString> = argv.iter().map(std::ffi::OsString::from).collect();
assert!(!launcher_profile_flag(&argv), "{argv:?}");
}
}
#[test]
fn peer_text_stays_on_one_visible_line() {
let alert = "Done.\nwrote /etc/passwd\r\u{1b}[2J\u{9b}31m\u{202e}txt.exe\\n\tok é";
@@ -307,12 +14,127 @@ fn peer_text_stays_on_one_visible_line() {
assert_eq!(escape_peer("Citation (Doe, 2020) — “ok”"), "Citation (Doe, 2020) — “ok”");
}
#[test]
fn validators_accept_only_the_documented_options() {
assert!(validate_options("info", &args(&["file.docx"]), PASSWORD_OPTIONS).is_ok());
assert!(validate_options("render", &args(&["in.docx", "out.png", "--page", "2", "--scale", "1.5"]), RENDER_OPTIONS).is_ok());
assert!(validate_options("run", &args(&["--cmd", "text.insert={}", "--cmd", "edit.undo", "--print"]), RUN_OPTIONS).is_ok());
assert!(validate_options("commands", &args(&["--json"]), COMMANDS_OPTIONS).is_ok());
assert!(validate_options("parity", &args(&["--markdown"]), PARITY_OPTIONS).is_ok());
assert!(validate_options("mcp", &args(&["--connect", "127.0.0.1:9000"]), MCP_OPTIONS).is_ok());
assert!(validate_options("render", &args(&["in.docx", "out.png", "--page"]), RENDER_OPTIONS).is_ok());
assert!(
validate_options(
"zotero",
&args(&["refresh", "in.docx", "--cmd", "caret.docEnd", "--save", "out.docx", "--trace", "--port", "23119"]),
ZOTERO_OPTIONS
)
.is_ok()
);
}
#[test]
fn an_option_value_is_never_read_as_a_path() {
// `--password`'s value sits between the paths and would be taken for one without
// `positionals`, so `render` would write its picture over a file called after the password.
assert_eq!(positionals(&args(&["in.docx", "--password", "secret", "out.png"]), RENDER_OPTIONS), vec!["in.docx", "out.png"]);
assert_eq!(positionals(&args(&["in.docx", "out.png", "--page", "2"]), RENDER_OPTIONS), vec!["in.docx", "out.png"]);
// A bare flag takes no value, so the next argument stays a path.
assert_eq!(positionals(&args(&["--print", "in.docx"]), RUN_OPTIONS), vec!["in.docx"]);
// `convert` is the one with a value-taking flag between the two paths.
assert_eq!(positionals(&args(&["in.docx", "--format", "flatopc", "out.docx"]), CONVERT_OPTIONS), vec!["in.docx", "out.docx"]);
}
#[test]
fn the_password_comes_from_an_option_a_file_or_the_environment() {
assert_eq!(password_from(&args(&["f.docx"])), Ok(None));
assert_eq!(password_from(&args(&["f.docx", "--password", "s3cret"])), Ok(Some("s3cret".into())));
// `--password` wins over the other two sources.
assert_eq!(password_from(&args(&["--password", "a", "--password-file", "/nonexistent"])), Ok(Some("a".into())));
}
#[test]
fn a_password_file_loses_only_its_trailing_newline() {
let path = std::env::temp_dir().join("wordcraft-cli-password-test.txt");
std::fs::write(&path, "s3cret\r\n").unwrap();
let got = password_from(&args(&["f.docx", "--password-file", &path.to_string_lossy()]));
std::fs::remove_file(&path).ok();
assert_eq!(got, Ok(Some("s3cret".into())));
}
#[test]
fn a_missing_password_file_is_named_without_the_password() {
let err = password_from(&args(&["f.docx", "--password-file", "/nonexistent/secret.txt"])).unwrap_err();
assert!(err.contains("--password-file"), "{err}");
}
#[test]
fn unknown_options_are_rejected_before_file_access() {
assert_eq!(run(&args(&["info", "missing.docx", "--passwrod", "x"])), Err("info: unknown option --passwrod".into()));
assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--sclae", "2"])), Err("render: unknown option --sclae".into()));
assert_eq!(run(&args(&["zotero", "refresh", "missing.docx", "--prot", "1"])), Err("zotero: unknown option --prot".into()));
}
#[test]
fn convert_rejects_malformed_format_options_before_file_access() {
for (options, error) in [
(vec!["--format"], "convert: --format requires a value"),
(vec!["--format", "--markup"], "convert: --format requires a value"),
(vec!["--format", "flatopc", "--format", "wordml2003"], "convert: duplicate --format option"),
] {
let mut argv = args(&["convert", "missing.docx", "out.xml"]);
argv.extend(args(&options));
assert_eq!(run(&argv), Err(error.into()), "{options:?}");
}
// A valid single value reaches file access, rather than a format-option error.
let error = run(&args(&["convert", "missing.docx", "out.xml", "--format", "flatopc"])).unwrap_err().to_string();
assert!(error.starts_with("missing.docx:"), "{error}");
}
#[test]
fn help_or_h_after_a_subcommand_asks_for_the_usage() {
for cmd in SUBCOMMANDS {
assert!(wants_help(cmd, &args(&["in.docx", "--help"])), "{cmd}");
assert!(wants_help(cmd, &args(&["-h"])), "{cmd}");
assert!(!wants_help(cmd, &args(&["in.docx", "--hepl"])), "{cmd}");
}
assert!(!wants_help("frobnicate", &args(&["--help"])));
}
#[test]
fn usage_lists_exactly_the_subcommands() {
let listed: Vec<&str> = USAGE
.lines()
.filter_map(|line| line.strip_prefix(" wordcraft-cli ")?.split_whitespace().next())
.filter(|word| !word.starts_with(['-', '[']))
.collect();
assert_eq!(listed, SUBCOMMANDS);
}
#[test]
fn text_keeps_bullet_and_number_labels() {
let doc = wordcraft_engine::io::open_bytes("lists.md", b"- alpha\n- beta\n\n1. first\n2. second\n").unwrap();
assert_eq!(listed_text(&doc).unwrap(), "\u{2022}\talpha\n\u{2022}\tbeta\n1.\tfirst\n2.\tsecond");
}
#[test]
fn author_flag_names_the_headless_session() {
assert!(validate_options("run", &args(&["--author", "Claude (copyedit)", "--cmd", "edit.undo"]), RUN_OPTIONS).is_ok());
assert!(validate_options("mcp", &args(&["--author", "Claude"]), MCP_OPTIONS).is_ok());
let mut s = Session::new(wordcraft_doc::Document::new());
assert!(set_author(&mut s, " Claude (copyedit) ").is_ok());
assert_eq!(s.author, "Claude (copyedit)");
assert!(set_author(&mut s, " ").is_err_and(|e| e.starts_with("--author:")));
assert!(run(&args(&["run", "--author", "Claude", "--cmd", "review.trackChanges={\"value\":true}"])).is_ok());
// The flag goes through the same protection check as the command.
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("review.restrict", &json!({"mode": "readOnly"})).unwrap();
let before = s.author.clone();
assert!(set_author(&mut s, "Claude").is_err());
assert_eq!(s.author, before);
assert!(s.run("file.setAuthor", &json!({"name": "Claude"})).is_err());
}
#[test]
fn author_flag_cannot_claim_a_named_exception_after_protection() {
use wordcraft_doc::{CharProps, InlineObject, StoryRef};
@@ -331,6 +153,88 @@ fn author_flag_cannot_claim_a_named_exception_after_protection() {
assert!(s.run("text.insert", &json!({"text": "Changed"})).is_err());
}
#[test]
fn automation_root_flags_are_taken_out_of_the_mcp_arguments() {
let base = std::env::temp_dir().join(format!("wc-cli-roots-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
std::fs::create_dir_all(base.join("in")).unwrap();
std::fs::create_dir_all(base.join("out")).unwrap();
let (read, write) = (base.join("in").to_string_lossy().into_owned(), base.join("out").to_string_lossy().into_owned());
let (roots, left) =
automation_roots("mcp", &args(&["--automation-read-root", &read, "--author", "Claude", &format!("--automation-write-root={write}")]))
.unwrap();
let roots = roots.unwrap();
assert_eq!(left, args(&["--author", "Claude"]));
assert!(roots.read_root().is_some() && roots.write_root().is_some());
assert!(validate_options("mcp", &left, MCP_OPTIONS).is_ok());
// A root left out grants none of its access.
let (roots, _) = automation_roots("mcp", &args(&["--automation-read-root", &read])).unwrap();
let roots = roots.unwrap();
assert!(roots.write_root().is_none());
assert!(roots.check(&format!("{write}/x.docx"), wordcraft_engine::file_access::Access::Write).unwrap_err().contains("write authority is absent"));
// No flags: nothing is confined and the arguments pass through.
let (roots, left) = automation_roots("mcp", &args(&["--connect", "127.0.0.1:9"])).unwrap();
assert!(roots.is_none());
assert_eq!(left, args(&["--connect", "127.0.0.1:9"]));
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn automation_root_flags_reject_bad_operands_and_missing_folders() {
for bad in [
args(&["--automation-read-root"]),
args(&["--automation-read-root", "--author"]),
args(&["--automation-write-root="]),
args(&["--automation-read-root", "a", "--automation-read-root=b"]),
] {
assert!(automation_roots("mcp", &bad).is_err(), "{bad:?}");
}
let e = automation_roots("mcp", &args(&["--automation-read-root", "/definitely/not/a/folder"])).err().unwrap();
assert!(e.starts_with("mcp: cannot open the automation read root"), "{e}");
// Through the command line: an error, not a server that quietly runs unconfined.
assert!(run(&args(&["mcp", "--automation-write-root", "/definitely/not/a/folder"])).is_err());
}
#[cfg(unix)]
#[test]
fn only_the_opened_file_may_be_other_than_unicode() {
use std::os::unix::ffi::OsStringExt;
let latin1 = || OsString::from_vec(b"caf\xe9.docx".to_vec());
let ok = |raw: Vec<OsString>| text_args(&raw).unwrap().1;
assert_eq!(ok(vec!["zotero".into(), "refresh".into(), latin1()]), Some(PathBuf::from(latin1())));
assert_eq!(ok(vec!["render".into(), latin1(), "out.png".into(), "--page".into(), "2".into()]), Some(PathBuf::from(latin1())));
assert_eq!(ok(vec!["render".into(), "--page".into(), "2".into(), latin1(), "out.png".into()]), Some(PathBuf::from(latin1())));
assert_eq!(ok(vec!["convert".into(), "--format".into(), "flatopc".into(), latin1(), "out.xml".into()]), Some(PathBuf::from(latin1())));
assert_eq!(ok(vec!["info".into(), "--password".into(), "secret".into(), latin1()]), Some(PathBuf::from(latin1())));
assert_eq!(ok(vec!["zotero".into(), "--port".into(), "23119".into(), "refresh".into(), latin1()]), Some(PathBuf::from(latin1())));
assert_eq!(ok(vec!["run".into(), "--print".into(), "--file".into(), latin1()]), Some(PathBuf::from(latin1())));
assert_eq!(ok(vec!["info".into(), "in.docx".into()]), None);
// Every command that opens a file reaches the open with it (no such file here), so
// `OPENS_FILE` and the commands' own arguments agree.
let missing = || OsString::from_vec(b"/definitely/not/caf\xe9.docx".to_vec());
let mut opening: Vec<Vec<OsString>> = OPENS_FILE
.iter()
.map(|(cmd, n)| [vec![(*cmd).into()], vec![OsString::from("refresh"); *n], vec![missing(), "out.png".into()]].concat())
.collect();
opening.push(vec!["run".into(), "--file".into(), missing()]);
for raw in opening {
let e = run(&raw).unwrap_err().to_string();
assert!(e.contains("No such file"), "{raw:?}: {e}");
}
for (raw, n) in [
(vec!["zotero".into(), latin1(), "in.docx".into()], 2),
(vec!["render".into(), "in.docx".into(), latin1()], 3),
(vec!["render".into(), "--page".into(), latin1(), "in.docx".into(), "out.png".into()], 3),
(vec!["run".into(), "--save".into(), latin1()], 3),
(vec!["commands".into(), latin1()], 2),
] {
assert_eq!(text_args(&raw).unwrap_err(), format!("argument {n} is not valid Unicode: caf\u{FFFD}.docx"));
}
}
/// An exclusively created scratch folder, removed on drop even when an assertion fails.
struct Scratch(PathBuf);
@@ -357,6 +261,65 @@ impl Drop for Scratch {
}
}
/// Shared rule 18 (#7124): every agent entry point, a subcommand that serves a client's requests
/// rather than running what the person typed and exiting, refuses to start without both
/// automation roots. Each subcommand has a row, so a new one fails here until it is classified,
/// and a new agent entry point fails until it refuses.
#[test]
fn every_agent_entry_point_refuses_to_start_without_both_roots() {
enum Kind {
Agent,
NotAgent(&'static str),
}
use Kind::{Agent, NotAgent};
let table = [
("convert", NotAgent("converts the files named on its command line, then exits")),
("info", NotAgent("reads the one file named on its command line, then exits")),
("text", NotAgent("reads the one file named on its command line, then exits")),
("inspect", NotAgent("reads the one file named on its command line, then exits")),
("render", NotAgent("renders the file named on its command line, then exits")),
("run", NotAgent("runs the commands and script named on its command line, then exits")),
("commands", NotAgent("lists the commands; touches no file")),
("parity", NotAgent("prints the feature catalog; touches no file")),
("mcp", Agent),
("zotero", NotAgent("runs one named Zotero command; Zotero's replies edit citations and name no file")),
];
assert_eq!(table.iter().map(|(name, _)| *name).collect::<Vec<_>>(), SUBCOMMANDS);
let scratch = Scratch::new("entry");
let base = scratch.0.clone();
std::fs::create_dir_all(base.join("in")).unwrap();
std::fs::create_dir_all(base.join("out")).unwrap();
let read = format!("--automation-read-root={}", base.join("in").display());
let write = format!("--automation-write-root={}", base.join("out").display());
for (name, kind) in table {
if let NotAgent(why) = kind {
assert!(!why.is_empty(), "{name}: say why it is not an agent entry point");
continue;
}
for given in [vec![], vec![read.clone()], vec![write.clone()], vec!["--author".to_string(), "Claude".to_string()]] {
let line = [vec![name.to_string()], given].concat();
let e = run(&line).unwrap_err().to_string();
assert!(e.contains("--automation-read-root") && e.contains("--automation-write-root"), "{line:?}: {e}");
}
}
}
/// The desktop app doesn't confine its control channel to roots yet (#3695, #5819), so the bridge
/// to it is refused, with roots or without, before anything connects.
#[test]
fn mcp_connect_is_refused_until_the_app_confines_its_control_channel() {
let dir = std::env::temp_dir().to_string_lossy().into_owned();
for line in [
args(&["mcp", "--connect", "127.0.0.1:9"]),
args(&["mcp", "--connect", "127.0.0.1:9", "--author", "Claude"]),
args(&["mcp", "--connect", "127.0.0.1:9", "--automation-read-root", &dir, "--automation-write-root", &dir]),
] {
let e = run(&line).unwrap_err().to_string();
assert!(e.contains("--connect") && e.contains("#3695") && e.contains("#5819"), "{line:?}: {e}");
}
}
/// `mcp`'s headless session takes `--author` as the session's author, and refuses a blank one as `run` does.
#[test]
fn mcp_headless_session_takes_the_author_flag() {
@@ -368,6 +331,120 @@ fn mcp_headless_session_takes_the_author_flag() {
assert_eq!(unnamed.session.author, wordcraft_mcp::Headless::default().session.author, "no flag keeps the default author");
}
/// `--connect` is refused whether or not it has a value, written apart or as `--connect=…`, even with both roots valid.
#[test]
fn mcp_connect_is_refused_without_a_value_too() {
let scratch = Scratch::new("connect-bare");
let dir = scratch.0.to_string_lossy().into_owned();
let roots = ["--automation-read-root", &dir, "--automation-write-root", &dir];
for tail in [vec!["--connect"], vec!["--connect", "--author", "Claude"], vec!["--connect=127.0.0.1:9"], vec!["--connect="]] {
let line = args(&[&["mcp"][..], &roots, &tail].concat());
let e = run(&line).unwrap_err().to_string();
assert!(e.contains("--connect") && e.contains("#3695") && e.contains("#5819"), "{line:?}: {e}");
}
}
#[test]
fn render_rejects_missing_or_invalid_page_and_scale() {
// Missing operands
assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--page"])), Err("render: --page requires a value".into()));
assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--scale"])), Err("render: --scale requires a value".into()));
assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--page", "--scale", "2"])), Err("render: --page requires a value".into()));
assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--scale", "--page", "1"])), Err("render: --scale requires a value".into()));
// Non-numeric operands
assert_eq!(
run(&args(&["render", "missing.docx", "out.png", "--page", "banana"])),
Err("render: invalid --page `banana`: not a valid integer".into())
);
assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--scale", "banana"])), Err("render: invalid --scale `banana`: not a number".into()));
// Out-of-range values
assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--page", "0"])), Err("render: invalid --page `0`: page numbers start at 1".into()));
assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--page", "-1"])), Err("render: invalid --page `-1`: not a valid integer".into()));
assert_eq!(
run(&args(&["render", "missing.docx", "out.png", "--scale", "0"])),
Err("render: invalid --scale `0`: scale must be a finite positive number".into())
);
assert_eq!(
run(&args(&["render", "missing.docx", "out.png", "--scale", "-2"])),
Err("render: invalid --scale `-2`: scale must be a finite positive number".into())
);
assert_eq!(
run(&args(&["render", "missing.docx", "out.png", "--scale", "NaN"])),
Err("render: invalid --scale `NaN`: scale must be a finite positive number".into())
);
assert_eq!(
run(&args(&["render", "missing.docx", "out.png", "--scale", "inf"])),
Err("render: invalid --scale `inf`: scale must be a finite positive number".into())
);
// Duplicate options
assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--page", "1", "--page", "2"])), Err("render: duplicate --page option".into()));
assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--scale", "1", "--scale", "2"])), Err("render: duplicate --scale option".into()));
}
#[test]
fn run_rejects_missing_or_invalid_page_and_scale() {
// Missing operands
assert_eq!(run(&args(&["run", "--template", "sample", "--save", "out.png", "--page"])), Err("run: --page requires a value".into()));
assert_eq!(run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale"])), Err("run: --scale requires a value".into()));
assert_eq!(
run(&args(&["run", "--template", "sample", "--save", "out.png", "--page", "--scale", "2"])),
Err("run: --page requires a value".into())
);
assert_eq!(
run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale", "--page", "1"])),
Err("run: --scale requires a value".into())
);
// Non-numeric operands
assert_eq!(
run(&args(&["run", "--template", "sample", "--save", "out.png", "--page", "banana"])),
Err("run: invalid --page `banana`: not a valid integer".into())
);
assert_eq!(
run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale", "banana"])),
Err("run: invalid --scale `banana`: not a number".into())
);
// Out-of-range values
assert_eq!(
run(&args(&["run", "--template", "sample", "--save", "out.png", "--page", "0"])),
Err("run: invalid --page `0`: page numbers start at 1".into())
);
assert_eq!(
run(&args(&["run", "--template", "sample", "--save", "out.png", "--page", "-1"])),
Err("run: invalid --page `-1`: not a valid integer".into())
);
assert_eq!(
run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale", "0"])),
Err("run: invalid --scale `0`: scale must be a finite positive number".into())
);
assert_eq!(
run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale", "-1"])),
Err("run: invalid --scale `-1`: scale must be a finite positive number".into())
);
assert_eq!(
run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale", "NaN"])),
Err("run: invalid --scale `NaN`: scale must be a finite positive number".into())
);
assert_eq!(
run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale", "inf"])),
Err("run: invalid --scale `inf`: scale must be a finite positive number".into())
);
// Duplicate options
assert_eq!(
run(&args(&["run", "--template", "sample", "--save", "out.png", "--page", "1", "--page", "2"])),
Err("run: duplicate --page option".into())
);
assert_eq!(
run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale", "1", "--scale", "2"])),
Err("run: duplicate --scale option".into())
);
}
#[test]
fn render_and_run_valid_options_and_defaults_produce_files() {
let dir = std::env::temp_dir().join(format!("wc-cli-render-{}", std::process::id()));
@@ -517,6 +594,33 @@ fn command_line_template_wins_over_the_scripts_file() {
assert!(std::fs::read_to_string(&b).unwrap().contains("FROM FILE"));
}
#[test]
fn cmd_value_missing_is_reported() {
let missing = std::env::temp_dir().join(format!(
"wc-cli-missing-cmd-{}-{}.docx",
std::process::id(),
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_nanos()
));
assert!(!missing.exists());
let missing = missing.to_string_lossy();
for argv in [
vec!["run", "--cmd"],
vec!["run", "--cmd", "--save", "out.docx"],
vec!["run", "--cmd", "caret.docEnd", "--cmd", "--print"],
vec!["run", "--cmd", "--bogus"],
vec!["run", "--cmd", "--file", &missing],
] {
assert_eq!(run(&args(&argv)), Err("--cmd needs a value".into()), "{argv:?}");
}
assert!(run(&args(&["run", "--cmd", "caret.docEnd", "--cmd", "caret.docStart"])).is_ok());
}
#[test]
fn script_value_missing_is_reported() {
let e = run(&args(&["run", "--script", "--cmd", "caret.docEnd"])).unwrap_err().to_string();
assert!(e.contains("--script requires a value"), "{e}");
}
#[test]
fn script_reads_from_a_stream_and_caps_its_size() {
let s = script::load_from(&br#"{"commands":["caret.docEnd"],"save":["o.docx"]}"#[..], "-", None).unwrap();
@@ -579,86 +683,6 @@ fn script_parse_resolves_paths_against_the_base() {
assert_eq!(s.commands.len(), 1);
}
/// Finding 4: `validate` is in `OPENS_FILE`, so a file name that is not valid Unicode reaches the
/// validator by its preserved path rather than being rejected as a bad argument.
/// APFS refuses invalid UTF-8 file names, so macOS covers native path handling without creating one.
#[cfg(all(unix, not(target_os = "macos")))]
#[test]
fn validate_accepts_a_file_name_that_is_not_unicode() {
use std::os::unix::ffi::OsStringExt;
let dir = std::env::temp_dir().join(format!("wc-cli-validate-nonutf8-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let doc = wordcraft_doc::Document::from_text("Bonjour");
let bytes = wordcraft_engine::io::save_bytes("x.docx", &doc).unwrap();
let mut name = dir.as_os_str().to_os_string().into_vec();
name.extend_from_slice(b"/caf\xe9.docx");
let path = PathBuf::from(OsString::from_vec(name));
std::fs::write(&path, bytes).unwrap();
let raw = vec![OsString::from("validate"), path.into_os_string()];
assert_eq!(run(&raw), Ok(()), "a non-Unicode path validates and reports PASS");
let _ = std::fs::remove_dir_all(dir);
}
/// A real `.docx` archive with `extra` parts added: content types, package relationships, the main
/// document and an empty main relationships part. Used to drive `validate_bytes` from real bytes so
/// a document-controlled entry name is shown to reach the report the way production does.
fn validate_fixture_zip(extra: &[(&str, &[u8])]) -> Vec<u8> {
let mut w = craft_zip::Writer::new();
w.add(
"[Content_Types].xml",
br#"<?xml version="1.0"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/></Types>"#,
craft_zip::Compression::Stored,
)
.unwrap();
w.add(
"_rels/.rels",
br#"<?xml version="1.0"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#,
craft_zip::Compression::Stored,
)
.unwrap();
w.add(
"word/document.xml",
br#"<?xml version="1.0"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body/></w:document>"#,
craft_zip::Compression::Stored,
)
.unwrap();
for (name, bytes) in extra {
w.add(name, bytes, craft_zip::Compression::Stored).unwrap();
}
w.finish().unwrap()
}
/// Finding 5: document-controlled text (a ZIP entry name) is escaped in the human report, while the
/// JSON form keeps serde's escaping. The input is a real archive whose entry name carries a control
/// character, so the test shows the name actually reaches the escaped fields (part and message).
#[test]
fn human_report_escapes_document_controlled_text() {
let evil = "word/evil\u{1b}[2J.bin";
let printable = "word/café—naïve.bin";
let zip = validate_fixture_zip(&[(evil, b"x"), (printable, b"x")]);
let report = wordcraft_validate::validate_bytes(&zip);
// The undeclared part carries the raw control character in its part field and its message.
let finding = report
.findings
.iter()
.find(|f| f.rule == "CT-UNDECLARED" && f.part.as_deref() == Some(evil))
.unwrap_or_else(|| panic!("expected CT-UNDECLARED at the control-character name: {:#?}", report.findings));
assert!(finding.message.contains(evil), "the name reaches the message too: {:?}", finding.message);
let human = render_validate_report(&report);
assert!(!human.contains('\u{1b}'), "no raw escape survives the human report: {human:?}");
assert!(human.contains("\\u{1b}"), "{human:?}");
assert!(human.contains("[2J"), "the surrounding name text is kept as written: {human:?}");
// Printable Unicode in a name is left as written.
assert!(human.contains(printable), "printable Unicode must be untouched: {human:?}");
// JSON output is unchanged by the human escaping: serde still emits the control character as
// its own JSON escape.
let json = serde_json::to_string(&report).unwrap();
assert!(json.contains("\\u001b"), "{json}");
}
#[test]
fn invisible_characters_are_escaped_and_json_lines_still_parse_back() {
let hidden = "a\u{ad}b\u{200b}c\u{200d}d\u{2060}e\u{2064}f\u{feff}g\u{e0041}h\u{e007f}i\u{85}j\u{202e}k";
+2 -64
View File
@@ -1,5 +1,5 @@
//! Readers closing stdout early must not panic (#508). Listing and MCP stop quietly;
//! validation retains its verdict exit status.
//! A reader that closes stdout early (`wordcraft-cli commands --json | head`) must end the CLI
//! quietly with exit 0, never with a panic (#508).
use std::io::{Read, Write};
use std::process::{Command, Stdio};
@@ -47,65 +47,3 @@ fn mcp_server_ends_cleanly_when_its_client_closes_stdout() {
assert!(out.status.success(), "status {:?}, stderr: {stderr}", out.status);
assert!(!stderr.contains("panicked"), "stderr: {stderr}");
}
/// A closed reader preserves validation's verdict for both report formats, including INCOMPLETE.
#[test]
fn validate_closed_stdout_preserves_verdict() {
let corpus = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../crates/validate/corpus/calibration");
let sparse = std::env::temp_dir().join(format!("wordcraft-validate-closed-stdout-{}.docx", std::process::id()));
// The validator checks metadata before reading inputs over its 512 MiB limit.
std::fs::File::create(&sparse).unwrap().set_len((512 << 20) + 1).unwrap();
let pass = sparse.with_file_name(format!("wordcraft-validate-closed-stdout-pass-{}.docx", std::process::id()));
let bytes = wordcraft_engine::io::save_bytes("pass.docx", &wordcraft_doc::Document::from_text("Control")).unwrap();
std::fs::write(&pass, bytes).unwrap();
let mut results = Vec::new();
for (fixture, expected) in [(pass.clone(), 0), (corpus.join("14-comment-dup.docx"), 1), (sparse.clone(), 1)] {
for json in [false, true] {
let mut open = cli();
open.arg("validate").arg(&fixture);
if json {
open.arg("--json");
}
let open = open.output().unwrap();
// Close the only reader before spawning, so even a short report reliably gets BrokenPipe.
let (reader, writer) = std::io::pipe().unwrap();
drop(reader);
let mut closed = cli();
closed.arg("validate").arg(&fixture).stdout(writer);
if json {
closed.arg("--json");
}
results.push((fixture.clone(), json, expected, open, closed.output().unwrap()));
}
}
std::fs::remove_file(sparse).unwrap();
std::fs::remove_file(pass).unwrap();
for (fixture, json, expected, open, closed) in results {
assert_eq!(open.status.code(), Some(expected), "{}, json={json}: {open:?}", fixture.display());
assert_eq!(closed.status.code(), Some(expected), "{}, json={json}: {closed:?}", fixture.display());
assert!(!String::from_utf8_lossy(&closed.stderr).contains("panicked"), "{closed:?}");
}
}
/// Other report-write failures are status 1 (RFC-0018: there is no 3); a child-only file-size limit forces EFBIG on stdout.
#[test]
fn validate_stdout_write_error_is_io_status() {
let fixture = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../crates/validate/corpus/calibration/14-comment-dup.docx");
let stdout = std::env::temp_dir().join(format!("wordcraft-validate-stdout-error-{}", std::process::id()));
let mut results = Vec::new();
for json in [false, true] {
// Ignore SIGXFSZ so the write returns an error rather than terminating the CLI.
let mut command = Command::new("/bin/sh");
command.args(["-c", "trap '' XFSZ; ulimit -f 0 || exit 99; exec \"$@\"", "sh", env!("CARGO_BIN_EXE_wordcraft-cli"), "validate"]);
command.arg(&fixture).stdout(std::fs::File::create(&stdout).unwrap());
if json {
command.arg("--json");
}
results.push((json, command.output().unwrap()));
}
std::fs::remove_file(stdout).unwrap();
for (json, output) in results {
assert_eq!(output.status.code(), Some(1), "json={json}: {output:?}");
assert!(!String::from_utf8_lossy(&output.stderr).contains("panicked"), "{output:?}");
}
}
+6 -6
View File
@@ -3,7 +3,7 @@
use std::process::{Command, Output};
const SUBCOMMANDS: [&str; 11] = ["convert", "info", "text", "inspect", "render", "run", "commands", "parity", "validate", "mcp", "zotero"];
const SUBCOMMANDS: [&str; 10] = ["convert", "info", "text", "inspect", "render", "run", "commands", "parity", "mcp", "zotero"];
fn cli(args: &[&str]) -> Output {
// `output()` gives the child no stdin, so `mcp` can't wait for a client.
@@ -14,7 +14,7 @@ fn assert_prints_usage(args: &[&str]) {
let out = cli(args);
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(out.status.success(), "{args:?}: status {:?}, stderr: {stderr}", out.status);
assert!(String::from_utf8_lossy(&out.stdout).contains("wordcraft-cli"), "{args:?}: stdout: {}", String::from_utf8_lossy(&out.stdout));
assert!(String::from_utf8_lossy(&out.stdout).starts_with("wordcraft-cli — "), "{args:?}: stdout: {}", String::from_utf8_lossy(&out.stdout));
assert!(stderr.is_empty(), "{args:?}: stderr: {stderr}");
}
@@ -39,9 +39,9 @@ fn help_comes_before_opening_files_and_folders() {
#[test]
fn misspelled_options_and_unknown_commands_still_fail() {
let out = cli(&["info", "--hepl"]);
assert_eq!(out.status.code(), Some(2));
assert!(String::from_utf8_lossy(&out.stderr).contains("--hepl"));
assert!(!out.status.success());
assert!(String::from_utf8_lossy(&out.stderr).contains("info: unknown option --hepl"));
let out = cli(&["frobnicate", "--help"]);
assert_eq!(out.status.code(), Some(2));
assert!(String::from_utf8_lossy(&out.stderr).contains("frobnicate"));
assert!(!out.status.success());
assert!(String::from_utf8_lossy(&out.stderr).contains("unknown command `frobnicate`"));
}
-1
View File
@@ -3,7 +3,6 @@ mod closed_stdout;
mod convert_fields;
mod convert_region;
mod help;
mod man_and_completions;
mod mcp_roots;
#[cfg(all(unix, not(target_os = "macos")))]
mod non_utf8_args;
@@ -1,55 +0,0 @@
//! The clap definition is consistent, and every shell's completions and every man page
//! (`examples/man-and-completions.rs`) can be generated from it.
use clap::ValueEnum;
use clap_complete::Shell;
// The example itself, so the test writes the files exactly as the packages get them.
#[allow(dead_code)]
#[path = "../../examples/man-and-completions.rs"]
mod example;
#[test]
fn command_is_consistent() {
wordcraft_cli::command().debug_assert();
}
#[test]
fn completions_generate_for_every_shell() {
for &shell in Shell::value_variants() {
let mut out = Vec::new();
clap_complete::generate(shell, &mut wordcraft_cli::command(), "wordcraft-cli", &mut out);
assert!(!out.is_empty(), "{shell}");
}
}
#[test]
fn man_pages_render_for_the_command_and_every_subcommand() {
let cmd = wordcraft_cli::command();
for page in std::iter::once(&cmd).chain(cmd.get_subcommands()) {
let mut out = Vec::new();
clap_mangen::Man::new(page.clone()).render(&mut out).unwrap();
assert!(!out.is_empty(), "{}", page.get_name());
}
}
/// The example writes the five completion files under the names `packaging/linux/package.sh` and
/// `packaging/freebsd/package.sh` install, `wordcraft-cli.1` and a page per subcommand, and no
/// pages for the `help` subcommand.
#[test]
fn the_example_writes_the_files_the_packages_install() {
let dir = std::env::temp_dir().join(format!("wc-cli-{}-man-and-completions", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
example::generate(&dir).unwrap();
let mut written: Vec<String> = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().file_name().into_string().unwrap()).collect();
written.sort();
let completions = ["wordcraft-cli.bash", "_wordcraft-cli", "wordcraft-cli.fish", "wordcraft-cli.elv", "_wordcraft-cli.ps1"];
let subcommands = ["commands", "convert", "info", "inspect", "mcp", "parity", "render", "run", "text", "validate", "zotero"];
let mut expected: Vec<String> = completions.map(String::from).into();
expected.push("wordcraft-cli.1".into());
expected.extend(subcommands.iter().map(|s| format!("wordcraft-cli-{s}.1")));
expected.sort();
assert_eq!(written, expected);
std::fs::remove_dir_all(&dir).unwrap();
}
+7 -9
View File
@@ -67,19 +67,17 @@ fn any_other_such_argument_is_an_error_naming_it() {
let (dir, file) = folder("error");
let out_name = dir.join(OsString::from_vec(b"caf\xe9.md".to_vec())).into_os_string();
let cmd = OsString::from_vec(b"text.insert={\"text\":\"\xe9\"}".to_vec());
// An output the engine takes as text: a failure (1), naming it; the other arguments are usage errors (2).
for (args, code, shown) in [
(vec!["convert".into(), file.clone(), out_name.clone()], 1, out_name.clone()),
(vec!["run".into(), "--file".into(), file.clone(), "--cmd".into(), cmd.clone()], 2, cmd),
(vec![OsString::from_vec(b"t\xe9xt".to_vec()), file.clone()], 2, OsString::from_vec(b"t\xe9xt".to_vec())),
for (args, n) in [
(vec!["convert".into(), file.clone(), out_name.clone()], 3),
(vec!["run".into(), "--file".into(), file.clone(), "--cmd".into(), cmd], 5),
(vec![OsString::from_vec(b"t\xe9xt".to_vec()), file.clone()], 1),
] {
let out = cli(&args);
let stderr = String::from_utf8_lossy(&out.stderr);
let shown = shown.to_string_lossy();
let shown = args[n - 1].to_string_lossy();
assert!(shown.contains('\u{FFFD}'));
assert_eq!(out.status.code(), Some(code), "{args:?}: stderr: {stderr}");
assert!(stderr.starts_with("error: "), "{args:?}: {stderr}");
assert!(stderr.contains("not valid Unicode") || stderr.contains("invalid UTF-8") || stderr.contains(&*shown), "{args:?}: {stderr}");
assert_eq!(out.status.code(), Some(1), "{args:?}: stderr: {stderr}");
assert_eq!(stderr, format!("wordcraft-cli: argument {n} is not valid Unicode: {shown}\n"), "{args:?}");
}
assert!(!std::path::Path::new(&out_name).exists());
let _ = std::fs::remove_dir_all(dir);
+26 -27
View File
@@ -1,4 +1,4 @@
//! `convert --strict` (#6005): exit 1 and a report when a PDF or PNG would silently lack a
//! `convert --strict` (#6005): exit 3 and a report when a PDF or PNG would silently lack a
//! character or a picture, nothing written; exit 0 otherwise.
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
@@ -145,9 +145,9 @@ fn an_uncovered_code_point_fails_strict_with_a_report_and_no_file() {
for out in ["out.pdf", "out.png"] {
let out = d.join(out);
let r = convert(&input, &out, true);
assert_eq!(r.status.code(), Some(1), "{}", stderr(&r));
assert_eq!(r.status.code(), Some(3), "{}", stderr(&r));
let text = stderr(&r);
assert!(text.contains(&format!("error: strict: 1 character cannot be drawn: {cp} (×3)")), "{text}");
assert!(text.contains(&format!("wordcraft-cli: strict: 1 character cannot be drawn: {cp} (×3)")), "{text}");
let json = report_json(&r);
assert_eq!(json["schema"], 1);
assert_eq!(json["strict"], "failed");
@@ -186,7 +186,7 @@ fn a_corrupt_header_picture_fails_strict_naming_the_part_and_the_header() {
for out in ["out.pdf", "out.png"] {
let out = d.join(out);
let r = convert(&input, &out, true);
assert_eq!(r.status.code(), Some(1), "{}", stderr(&r));
assert_eq!(r.status.code(), Some(3), "{}", stderr(&r));
let text = stderr(&r);
assert!(text.contains("word/media/image2.bin (header2.xml): unsupported format"), "{text}");
let json = report_json(&r);
@@ -218,7 +218,7 @@ fn an_external_picture_target_is_never_fetched_and_is_reported_under_strict() {
assert_eq!(lenient.status.code(), Some(0), "{}", stderr(&lenient));
let out = d.join("strict.pdf");
let strict = convert(&input, &out, true);
assert_eq!(strict.status.code(), Some(1), "{}", stderr(&strict));
assert_eq!(strict.status.code(), Some(3), "{}", stderr(&strict));
let json = report_json(&strict);
assert_eq!(json["missing_pictures"][0]["reason"], "external_target");
assert!(stderr(&strict).contains("external target"));
@@ -246,19 +246,19 @@ fn bad_input_exits_1_with_the_usual_message_with_and_without_strict() {
assert_eq!(plain.status.code(), Some(1), "{}", stderr(&plain));
assert_eq!(strict.status.code(), Some(1), "{}", stderr(&strict));
assert_eq!(stderr(&plain), stderr(&strict));
assert!(stderr(&plain).starts_with("error: "), "{}", stderr(&plain));
assert!(stderr(&plain).starts_with("wordcraft-cli: "), "{}", stderr(&plain));
assert!(!d.join("a.pdf").exists() && !d.join("b.pdf").exists());
}
std::fs::remove_dir_all(d).unwrap();
}
#[test]
fn strict_with_another_output_type_exits_2_before_the_input_is_read() {
fn strict_with_another_output_type_exits_1_before_the_input_is_read() {
let d = dir("wrong-output");
let missing = d.join("does-not-exist.docx");
for out in ["out.docx", "out.txt", "out.odt"] {
let r = convert(&missing, &d.join(out), true);
assert_eq!(r.status.code(), Some(2));
assert_eq!(r.status.code(), Some(1));
let text = stderr(&r);
assert!(text.contains("--strict needs a .pdf or .png output"), "{text}");
assert!(!d.join(out).exists());
@@ -291,11 +291,11 @@ fn render_strict_refuses_an_uncovered_character_on_the_page_with_no_stdout_or_fi
let input = two_page_input(&d, &format!("a{c}b"));
let out = d.join("p1.png");
let r = render(&input, &out, &["--strict"]);
assert_eq!(r.status.code(), Some(1), "{}", stderr(&r));
assert_eq!(r.status.code(), Some(3), "{}", stderr(&r));
assert!(r.stdout.is_empty(), "{}", String::from_utf8_lossy(&r.stdout));
assert!(!out.exists());
let text = stderr(&r);
assert!(text.contains(&format!("error: strict: 1 character cannot be drawn: {cp} (×1)")), "{text}");
assert!(text.contains(&format!("wordcraft-cli: strict: 1 character cannot be drawn: {cp} (×1)")), "{text}");
assert_eq!(report_json(&r)["missing_glyphs"][0]["cp"], cp.as_str());
eprintln!("{text}");
@@ -323,7 +323,7 @@ fn render_strict_refuses_a_corrupt_header_picture_and_bad_input_still_exits_1()
std::fs::write(&input, docx_with_header_picture(b"corrupt bytes, not a picture")).unwrap();
let out = d.join("out.png");
let r = render(&input, &out, &["--strict"]);
assert_eq!(r.status.code(), Some(1), "{}", stderr(&r));
assert_eq!(r.status.code(), Some(3), "{}", stderr(&r));
assert!(r.stdout.is_empty());
assert!(stderr(&r).contains("word/media/image2.bin (header2.xml)"), "{}", stderr(&r));
assert!(!out.exists());
@@ -341,16 +341,16 @@ fn a_picture_target_with_a_newline_and_a_bidi_override_cannot_forge_a_report_lin
let d = dir("escape");
let input = d.join("in.docx");
// XML character references put a newline and U+202E in the target.
std::fs::write(&input, docx_with_external_picture("http://example.invalid/a&#10;error: strict: forged&#x202E;gnp.png")).unwrap();
std::fs::write(&input, docx_with_external_picture("http://example.invalid/a&#10;wordcraft-cli: strict: forged&#x202E;gnp.png")).unwrap();
let out = d.join("out.pdf");
let r = convert(&input, &out, true);
assert_eq!(r.status.code(), Some(1), "{}", stderr(&r));
assert_eq!(r.status.code(), Some(3), "{}", stderr(&r));
let text = stderr(&r);
let lines: Vec<&str> = text.lines().collect();
// One human line for the picture, then the JSON line.
assert_eq!(lines.len(), 2, "{text}");
assert!(lines[0].starts_with("error: strict: 1 picture(s) left out: "), "{text}");
assert!(lines[0].contains("\\nerror: strict: forged\\u{202e}gnp.png"), "{text}");
assert!(lines[0].starts_with("wordcraft-cli: strict: 1 picture(s) left out: "), "{text}");
assert!(lines[0].contains("\\nwordcraft-cli: strict: forged\\u{202e}gnp.png"), "{text}");
assert!(!text.contains('\u{202e}'), "the raw bidi override reached the terminal");
// The JSON keeps the raw value, escaped by the JSON encoder.
let json = report_json(&r);
@@ -363,14 +363,14 @@ fn a_picture_target_with_a_newline_and_a_bidi_override_cannot_forge_a_report_lin
fn run_with_strict_cannot_forge_an_error_line_either() {
let d = dir("run-escape");
let input = d.join("in.docx");
std::fs::write(&input, docx_with_external_picture("http://example.invalid/a&#10;error: strict: forged&#x1B;[2J&#x202E;gnp.png")).unwrap();
std::fs::write(&input, docx_with_external_picture("http://example.invalid/a&#10;wordcraft-cli: strict: forged&#x1B;[2J&#x202E;gnp.png")).unwrap();
let out = d.join("out.pdf");
let cmd = format!("file.exportPdf={}", serde_json::json!({"path": out, "strict": true}));
let r = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli")).arg("run").arg("--file").arg(&input).arg("--cmd").arg(cmd).output().unwrap();
assert_eq!(r.status.code(), Some(1));
let text = stderr(&r);
assert_eq!(text.lines().count(), 1, "{text}");
assert!(text.contains("\\nerror: strict: forged") && text.contains("\\u{202e}"), "{text}");
assert!(text.contains("\\nwordcraft-cli: strict: forged") && text.contains("\\u{202e}"), "{text}");
assert!(!text.contains('\u{1b}') && !text.contains('\u{202e}'), "{text:?}");
assert!(!out.exists());
std::fs::remove_dir_all(d).unwrap();
@@ -378,20 +378,19 @@ fn run_with_strict_cannot_forge_an_error_line_either() {
#[test]
fn usage_errors_keep_their_line_breaks() {
// Errors go to stderr (clap's message, then its usage), exit 2.
// Errors go to stderr with the usage after a blank line (`missing argument`, `unknown command`).
for args in [&["frobnicate"][..], &["convert"][..]] {
let r = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli")).args(args).output().unwrap();
let text = stderr(&r);
assert_eq!(r.status.code(), Some(2), "{args:?}: {text}");
assert!(text.lines().count() > 2, "{args:?}: {text}");
assert!(text.lines().any(|l| l.starts_with("Usage:")), "{args:?}: {text}");
assert_eq!(r.status.code(), Some(1), "{args:?}: {text}");
assert!(text.lines().count() > 3, "{args:?}: {text}");
assert!(text.lines().any(|l| l == "USAGE:"), "{args:?}: {text}");
assert!(!text.contains("\\n"), "{args:?}: {text}");
}
// No arguments at all prints the help (on stderr, as clap does for a missing subcommand), exit 2.
// No arguments at all prints the usage as help, on stdout.
let r = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli")).output().unwrap();
assert_eq!(r.status.code(), Some(2));
let all = format!("{}{}", String::from_utf8_lossy(&r.stdout), stderr(&r));
assert!(all.lines().count() > 3 && all.lines().any(|l| l.starts_with("Usage:")), "{all}");
assert!(all.lines().count() > 3 && all.lines().any(|l| l == "USAGE:"), "{all}");
}
/// A minimal EMF (88-byte header, 100 mm square frame) with one EMR_EXTTEXTOUTW record showing
@@ -445,7 +444,7 @@ fn a_character_in_a_metafile_pictures_text_fails_strict_like_the_pages_own() {
for out in ["out.pdf", "out.png"] {
let out = d.join(out);
let r = convert(&input, &out, true);
assert_eq!(r.status.code(), Some(1), "{}", stderr(&r));
assert_eq!(r.status.code(), Some(3), "{}", stderr(&r));
assert_eq!(report_json(&r)["missing_glyphs"][0]["cp"], cp.as_str(), "{}", stderr(&r));
assert!(!out.exists(), "{} was written", out.display());
// Without --strict it converts, the character a hollow box.
@@ -455,7 +454,7 @@ fn a_character_in_a_metafile_pictures_text_fails_strict_like_the_pages_own() {
}
let out = d.join("p1.png");
let r = render(&input, &out, &["--strict"]);
assert_eq!(r.status.code(), Some(1), "{}", stderr(&r));
assert_eq!(r.status.code(), Some(3), "{}", stderr(&r));
assert!(r.stdout.is_empty() && !out.exists());
assert_eq!(report_json(&r)["missing_glyphs"][0]["cp"], cp.as_str());
// Text the faces cover passes.
@@ -480,7 +479,7 @@ fn a_metafile_page_background_fails_strict_for_png_but_not_for_pdf() {
std::fs::write(&input, serde_json::to_vec(&doc).unwrap()).unwrap();
let png = d.join("out.png");
let r = convert(&input, &png, true);
assert_eq!(r.status.code(), Some(1), "{}", stderr(&r));
assert_eq!(r.status.code(), Some(3), "{}", stderr(&r));
let json = report_json(&r);
assert_eq!(json["missing_pictures"][0]["part"], "bg.emf", "{}", stderr(&r));
assert_eq!(json["missing_pictures"][0]["source_part"], "background");
+6 -6
View File
@@ -37,9 +37,9 @@ use std::rc::Rc;
use std::sync::Arc;
use std::sync::Mutex;
use craft::host::{FileError, Files, PendingPick, PickId, PickRequest, Picked, WriteIntent};
use craft::host::{FileError, Files, PickId, PickRequest, Picked, WriteIntent};
use craft::platform::browser_files::BrowserFiles;
use craft::platform::open::{DroppedFile, IntakeSender};
use craft::platform::open::{DropTarget, DroppedFile, IntakeSender};
use craft::web_host::web::{FileData, Host, Message};
use wordcraft_ui_egui::{Services, WordApp};
@@ -131,7 +131,7 @@ fn deliver_open(intake: &IntakeSender, name: &str, data: &FileData) {
return;
}
let file = DroppedFile { path: None, name, bytes: Some(Arc::from(array.to_vec())) };
intake.dropped(vec![file]);
intake.dropped(vec![file], DropTarget::Elsewhere);
}
/// The files of a hosted page: reads go to the browser's files, but a save goes to the host page,
@@ -167,8 +167,8 @@ impl Files for HostedFiles {
}
}
fn pending_pick(&self) -> Option<PendingPick> {
self.inner.pending_pick()
fn pick_pending(&self) -> bool {
self.inner.pick_pending()
}
fn read(&self, path: &Path) -> Result<Vec<u8>, FileError> {
@@ -192,7 +192,7 @@ impl Files for HostedFiles {
let answer = match sent {
// A Save As or first Save makes the page hold the document as this file: the answer
// names it, and the next Save posts the name with `save_as` false.
Ok(()) if request.save_as => Picked::Saved { path: PathBuf::from(&name), file_type: None },
Ok(()) if request.save_as => Picked::Paths(vec![PathBuf::from(&name)]),
// An overwrite of the opened file, or a copy: the document's file stays as it is.
Ok(()) => Picked::Downloaded(name),
Err(error) => Picked::Failed(error),
+3 -3
View File
@@ -10,7 +10,7 @@ use craft::host::{Files, Host, Wake};
use craft::platform::appearance::SystemReader;
use craft::platform::browser_files::BrowserFiles;
use craft::platform::clipboard::{Clipboard, ClipboardError, EventClipboard, Flavor, LateOffers, TEXT};
use craft::platform::open::{DroppedFile, FileIntake, IntakeSender};
use craft::platform::open::{DropTarget, DroppedFile, FileIntake, IntakeSender};
use craft::print::spool::Spool;
use craft::settings::SharedSettings;
use craft::ui::InstallSpec;
@@ -227,7 +227,7 @@ impl eframe::App for WebShell {
match f.bytes_async().await {
Ok(bytes) => {
let file = DroppedFile { path: None, name, bytes: Some(Arc::from(bytes)) };
sender.dropped(vec![file]);
sender.dropped(vec![file], DropTarget::Elsewhere);
}
Err(e) => log::error!("couldn't read dropped file {name}: {e}"),
}
@@ -412,7 +412,7 @@ fn guard_unload(dirty: Rc<Cell<bool>>, files: Arc<BrowserFiles>) -> Result<(), S
let window = web_sys::window().ok_or("no window")?;
let on_unload = wasm_bindgen::closure::Closure::<dyn FnMut(web_sys::BeforeUnloadEvent)>::new(move |e: web_sys::BeforeUnloadEvent| {
// A save still in the browser's picker hasn't written anything yet.
if dirty.get() || files.pending_pick().is_some() {
if dirty.get() || files.pick_pending() {
e.prevent_default();
// Older browsers ask only when `returnValue` is set.
e.set_return_value("unsaved changes");
-6
View File
@@ -25,9 +25,6 @@ eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "
egui = { workspace = true }
serde_json = { workspace = true }
log = { workspace = true }
# The nightly launch profile's refusal dialog (a native message box, like the app's other OS errors).
rfd = { workspace = true }
thiserror = { workspace = true }
# The suite's shared libraries: the runtime hooks (`ui`, `ui-app`), file dialogs, the control
# channel's arguments, the GPU choice, printing, settings and window placement, the OS appearance
# reader and the system clipboard.
@@ -71,6 +68,3 @@ xkbcommon-dl = { version = "0.4.2", features = ["x11"] }
# The update helper: a copy of this program started with `--finish-update`
# (`craft::update::self_update::finish`).
craft = { workspace = true, features = ["update"] }
# The nightly Windows identity: an explicit AppUserModelID, so Nightly gets its own taskbar
# button instead of sharing the stable app's (#16335's rule for the suite).
winsafe = { version = "=0.0.29", default-features = false, features = ["user", "shell"] }
+5 -43
View File
@@ -1,63 +1,25 @@
//! Windows only: embed the app icon and version info (VERSIONINFO) into `wordcraft.exe`, so it
//! shows in Explorer, the taskbar, the Start menu and Alt-Tab.
//!
//! The build channel (`WORDCRAFT_BUILD_CHANNEL`) is decided here, before any code is compiled: a
//! nightly-v1 build gets its own cfg, its own icon and its exact feed version in VERSIONINFO.
//! On every other target this does nothing but that. A missing resource compiler is a warning, so
//! a cross-compile from macOS or Linux still links, unless `WORDCRAFT_REQUIRE_WINRES=1` turns it
//! On every other target this does nothing. A missing resource compiler is a warning, so a
//! cross-compile from macOS or Linux still links, unless `WORDCRAFT_REQUIRE_WINRES=1` turns it
//! into an error (for release builds).
#[path = "src/build_channel.rs"]
mod build_channel;
fn main() {
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-env-changed=WORDCRAFT_BUILD_CHANNEL");
println!("cargo:rustc-check-cfg=cfg(wordcraft_nightly_v1)");
let nightly = match std::env::var("WORDCRAFT_BUILD_CHANNEL").as_deref() {
Ok("nightly-v1") => {
println!("cargo:rustc-cfg=wordcraft_nightly_v1");
true
}
// An empty value (an unset CI input) means the default stable build.
Ok("stable" | "") | Err(std::env::VarError::NotPresent) => false,
_ => {
eprintln!("unsupported WORDCRAFT_BUILD_CHANNEL (expected stable or nightly-v1)");
std::process::exit(1);
}
};
println!("cargo:rerun-if-changed=../../assets/app-icon/wordcraft.ico");
println!("cargo:rerun-if-changed=../../assets/app-icon/wordcraft-nightly.ico");
println!("cargo:rerun-if-env-changed=WORDCRAFT_REQUIRE_WINRES");
println!("cargo:rerun-if-env-changed=WORDCRAFT_VERSION");
let built_version = if nightly {
match std::env::var("WORDCRAFT_VERSION") {
Ok(version) if build_channel::is_nightly_version(&version) => version,
_ => {
eprintln!("nightly-v1 requires an explicit WORDCRAFT_VERSION feed identity");
std::process::exit(1);
}
}
} else {
std::env::var("CARGO_PKG_VERSION").unwrap_or_default()
};
println!("cargo:rustc-env=WORDCRAFT_BUILT_VERSION={built_version}");
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") {
return;
}
let mut res = winresource::WindowsResource::new();
res.set_icon(build_channel::windows_icon_path(nightly))
.set("ProductName", if nightly { "WordCraft Nightly" } else { "WordCraft" })
.set("FileDescription", if nightly { "WordCraft Nightly word processor" } else { "WordCraft word processor" })
res.set_icon("../../assets/app-icon/wordcraft.ico")
.set("ProductName", "WordCraft")
.set("FileDescription", "WordCraft word processor")
.set("CompanyName", "Learning Machines LLC")
.set("LegalCopyright", "Copyright (c) the WordCraft authors. MIT OR Apache-2.0.")
.set("OriginalFilename", "wordcraft.exe")
.set("InternalName", "wordcraft");
if nightly {
// The Launcher verifies the PE ProductVersion against the exact feed identity, not FileVersion.
res.set("ProductVersion", &built_version);
}
if let Err(e) = res.compile() {
if std::env::var_os("WORDCRAFT_REQUIRE_WINRES").is_some() {
eprintln!("embedding Windows resources failed: {e}");
-54
View File
@@ -1,54 +0,0 @@
//! The build-time nightly identity shared by the build script and its pure regression tests.
pub fn is_nightly_version(version: &str) -> bool {
let Some((base, suffix)) = version.split_once("-nightly.") else { return false };
let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
let base: Vec<_> = base.split('.').collect();
let parts: Vec<_> = suffix.split('.').collect();
base.len() == 3
&& base.iter().all(|s| digits(s))
&& parts.len() == 4
&& parts[0].len() == 8
&& digits(parts[0])
&& digits(parts[1])
&& digits(parts[2])
&& parts[3].strip_prefix('g').is_some_and(|sha| sha.len() == 12 && sha.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)))
}
pub fn windows_icon_path(nightly: bool) -> &'static str {
if nightly { "../../assets/app-icon/wordcraft-nightly.ico" } else { "../../assets/app-icon/wordcraft.ico" }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn windows_resource_uses_the_flavor_specific_icon_without_changing_stable() {
assert_eq!(windows_icon_path(false), "../../assets/app-icon/wordcraft.ico");
assert_eq!(windows_icon_path(true), "../../assets/app-icon/wordcraft-nightly.ico");
}
#[test]
fn explicit_feed_identity_is_required_for_a_nightly_build() {
assert!(is_nightly_version("0.18.1-nightly.20261124.17.1.gabcdef012345"));
for invalid in [
"",
"0.18.1",
"0.18.1-nightly",
"0.18.1-nightly.20261124",
"0.18.1-nightly.20261124.17.1.gABCDEF012345",
"0.18.1-nightly.20261124.17.1.gabcdef012345\n",
] {
assert!(!is_nightly_version(invalid), "{invalid:?}");
}
}
#[test]
fn version_cannot_inject_a_path_or_an_extra_build_directive() {
for invalid in [
"../0.18.1-nightly.20261124.1.1.gabcdef012345",
"0.18.1-nightly.20261124.1.1.gabcdef012345/other",
"0.18.1-nightly.20261124.1.1.gabcdef012345\ncargo:rustc-cfg=other",
] {
assert!(!is_nightly_version(invalid));
}
}
}
-72
View File
@@ -1,72 +0,0 @@
//! 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;
#[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
}
/// The Launcher's version line: `WordCraft <version> (nightly-v1)` for a nightly build.
pub fn version(flavor: BuildFlavor, stable: &str) -> String {
match flavor {
BuildFlavor::Stable => stable.to_owned(),
BuildFlavor::NightlyV1 => format!("WordCraft {stable} (nightly-v1)"),
}
}
/// A plain `--version` / `-V`: the only arguments, answered before any startup work.
pub fn version_query(args: &[OsString]) -> bool {
matches!(args, [arg] if arg == "--version" || arg == "-V")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_a_nightly_desktop_refusal_requests_a_native_dialog() {
assert!(needs_native_error(BuildFlavor::NightlyV1, true));
assert!(!needs_native_error(BuildFlavor::NightlyV1, false));
assert!(!needs_native_error(BuildFlavor::Stable, true));
assert!(!needs_native_error(BuildFlavor::Stable, false));
}
#[test]
fn 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_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");
assert_eq!(version(BuildFlavor::NightlyV1, "0.18.1"), "WordCraft 0.18.1 (nightly-v1)");
assert!(version_query(&["--version".into()]));
assert!(version_query(&["-V".into()]));
assert!(!version_query(&["--".into(), "--version".into()]));
assert!(!version_query(&[]));
}
}
-163
View File
@@ -123,167 +123,4 @@ mod tests {
assert!(supplied.exists());
let _ = std::fs::remove_dir_all(&dir);
}
const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
fn boot() -> (u16, Receiver<ControlRequest>, Control) {
let options = ControlOptions { token: Some(TOKEN.to_string()), ..ControlOptions::default() };
let (rx, control) = start(&options, 0, host(), None).unwrap();
let port = control.listening.addr.port();
(port, rx, control)
}
/// Answer the next request that reaches the UI with `ok`, and return it.
fn answer(rx: &Receiver<ControlRequest>) -> ControlRequest {
let req = rx.recv_timeout(std::time::Duration::from_secs(5)).unwrap();
let _ = req.reply.send(serde_json::json!({"ok": true, "result": {}}));
req
}
/// One connection, several lines.
struct Conn(std::io::BufReader<std::net::TcpStream>, std::net::TcpStream);
impl Conn {
fn open(port: u16) -> Self {
let s = std::net::TcpStream::connect(("127.0.0.1", port)).unwrap();
s.set_read_timeout(Some(std::time::Duration::from_secs(5))).unwrap();
Self(std::io::BufReader::new(s.try_clone().unwrap()), s)
}
fn send(&mut self, line: &str) {
use std::io::Write;
writeln!(self.1, "{line}").unwrap();
}
fn recv(&mut self) -> serde_json::Value {
use std::io::BufRead;
let mut r = String::new();
let n = self.0.read_line(&mut r).expect("read reply line");
assert!(n > 0, "unexpected EOF while waiting for reply");
serde_json::from_str(&r).expect("reply is valid JSON")
}
fn call(&mut self, line: &str) -> serde_json::Value {
self.send(line);
self.recv()
}
/// The server closed the connection.
fn closed(&mut self) -> bool {
use std::io::BufRead;
let mut r = String::new();
match self.0.read_line(&mut r) {
Ok(0) => true,
Err(e) => matches!(
e.kind(),
std::io::ErrorKind::ConnectionReset
| std::io::ErrorKind::ConnectionAborted
| std::io::ErrorKind::NotConnected
| std::io::ErrorKind::BrokenPipe
),
_ => false,
}
}
}
/// Post-#7101 adaptation of `the_key_on_each_request` (#124, tracked under #7317 / #7720):
/// `craft::automation::server` replaced the legacy per-request `"key"` field with one-time
/// per-connection token authentication (`docs/control-protocol.md`, Token).
#[test]
fn a_connection_authenticates_once_with_the_token_and_unauthenticated_requests_are_refused() {
let (port, rx, control) = boot();
// Authenticate once per connection with `params.token`.
let mut c = Conn::open(port);
let auth_resp = c.call(&format!(r#"{{"id":1,"method":"auth","params":{{"token":"{TOKEN}"}}}}"#));
assert_eq!(auth_resp, serde_json::json!({"id": 1, "ok": true, "result": {"authenticated": true}}));
// Subsequent requests on the authenticated connection carry no token and reach the UI.
c.send(r#"{"id":7,"method":"document.inspect","params":{"text":true}}"#);
let req = answer(&rx);
assert_eq!((req.method.as_str(), &req.params), ("document.inspect", &serde_json::json!({"text": true})));
let r = c.recv();
assert_eq!((&r["ok"], &r["id"]), (&serde_json::json!(true), &serde_json::json!(7)));
c.send(r#"{"id":8,"method":"document.inspect","params":{"text":false}}"#);
let req = answer(&rx);
assert_eq!((req.method.as_str(), &req.params), ("document.inspect", &serde_json::json!({"text": false})));
let r = c.recv();
assert_eq!((&r["ok"], &r["id"]), (&serde_json::json!(true), &serde_json::json!(8)));
drop(c);
// An unauthenticated connection is refused and closed without reaching the UI.
let mut unauth = Conn::open(port);
let r = unauth.call(r#"{"id":9,"method":"document.inspect"}"#);
assert_eq!(r, serde_json::json!({"id": 9, "ok": false, "error": "authentication required"}));
assert!(unauth.closed());
assert!(rx.try_recv().is_err(), "unauthenticated request must not reach the UI");
drop(unauth);
// Legacy pre-#7101 per-request `"key"` does not bypass `auth` and closes the connection.
let mut legacy = Conn::open(port);
let r = legacy.call(&format!(r#"{{"id":10,"key":"{TOKEN}","method":"document.inspect","params":{{"text":true}}}}"#));
assert_eq!(r, serde_json::json!({"id": 10, "ok": false, "error": "authentication required"}));
assert!(legacy.closed());
assert!(rx.try_recv().is_err(), "legacy per-request key must not reach the UI");
drop(legacy);
control.shut_down();
}
/// Post-#7101 adaptation of `params_key_is_only_a_secret_for_auth` (#124, tracked under #7317 / #7729):
/// `craft::automation::server` replaced legacy `"key"` / `params.key` secrets with one-time
/// per-connection `auth` using `params.token` (`docs/control-protocol.md`, Token).
#[test]
fn params_token_is_only_a_secret_for_auth() {
let (port, rx, control) = boot();
// Neither `params.token` on a non-`auth` method nor legacy `params.key` on
// `document.inspect` or `auth` authenticates.
for (id, line) in [
(1, format!(r#"{{"id":1,"method":"document.inspect","params":{{"token":"{TOKEN}"}}}}"#)),
(2, format!(r#"{{"id":2,"method":"document.inspect","params":{{"key":"{TOKEN}"}}}}"#)),
(3, format!(r#"{{"id":3,"method":"auth","params":{{"key":"{TOKEN}"}}}}"#)),
] {
let mut c = Conn::open(port);
assert_eq!(c.call(&line), serde_json::json!({"id": id, "ok": false, "error": "authentication required"}));
assert!(c.closed());
}
assert!(rx.try_recv().is_err(), "refused requests must not reach the UI");
// Authenticate once with `params.token`; `params.key` and `params.token` on subsequent
// non-`auth` methods are forwarded untouched as ordinary parameters.
let mut c = Conn::open(port);
let auth_resp = c.call(&format!(r#"{{"id":1,"method":"auth","params":{{"token":"{TOKEN}"}}}}"#));
assert_eq!(auth_resp, serde_json::json!({"id": 1, "ok": true, "result": {"authenticated": true}}));
c.send(r#"{"id":2,"method":"ui.key","params":{"key":"Enter"}}"#);
let req = answer(&rx);
assert_eq!((req.method.as_str(), &req.params), ("ui.key", &serde_json::json!({"key": "Enter"})));
let r = c.recv();
assert_eq!((&r["ok"], &r["id"]), (&serde_json::json!(true), &serde_json::json!(2)));
c.send(r#"{"id":3,"method":"document.inspect","params":{"token":"ordinary"}}"#);
let req = answer(&rx);
assert_eq!((req.method.as_str(), &req.params), ("document.inspect", &serde_json::json!({"token": "ordinary"})));
let r = c.recv();
assert_eq!((&r["ok"], &r["id"]), (&serde_json::json!(true), &serde_json::json!(3)));
drop(c);
control.shut_down();
}
/// Post-#7101 adaptation of `a_wrong_key_is_refused_and_closed` (#124, tracked under #7317):
/// wrong, short, and long `params.token` values are refused and close the connection without
/// reaching the UI.
#[test]
fn a_wrong_token_is_refused_and_closed() {
let (port, rx, control) = boot();
let wrong = TOKEN.replace('0', "1");
let long = format!("{TOKEN}0");
for token in ["nope", wrong.as_str(), &TOKEN[..63], long.as_str()] {
let mut c = Conn::open(port);
let resp = c.call(&format!(r#"{{"id":1,"method":"auth","params":{{"token":"{token}"}}}}"#));
assert_eq!(resp, serde_json::json!({"id": 1, "ok": false, "error": "authentication required"}), "{token}");
assert!(c.closed(), "{token}");
}
assert!(rx.try_recv().is_err(), "refused auth attempts must not reach the UI");
control.shut_down();
}
}
-17
View File
@@ -54,23 +54,6 @@ pub fn identity() -> AppIdentity {
mod tests {
use super::*;
/// Every type the button claims is included in identity, and plain text/Markdown are never claimed.
#[test]
fn xdg_mime_sets_every_word_type_in_one_call() {
let id = identity();
assert_eq!(id.desktop_id, "ai.storyteller.wordcraft.desktop");
assert_eq!(id.registered_name, "WordCraft");
for t in [
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"application/msword",
"application/rtf",
"application/vnd.oasis.opendocument.text",
] {
assert!(id.mime_types.iter().any(|a| a == t), "{t}");
}
assert!(!id.mime_types.iter().any(|a| a == "text/plain" || a == "text/markdown"), "plain text and Markdown are never claimed");
}
/// Every type the button claims is one the desktop entry declares, or desktops ignore it.
#[test]
fn the_desktop_entry_declares_every_claimed_type() {
-229
View File
@@ -1,229 +0,0 @@
//! 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::OsString;
use std::path::{Component, Path, PathBuf};
use std::sync::OnceLock;
pub const VERSION: &str = "nightly-v1";
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Profile {
Stable,
NightlyV1(PathBuf),
}
impl Profile {
pub fn is_nightly(&self) -> bool {
matches!(self, Self::NightlyV1(_))
}
pub fn root(&self) -> Option<&Path> {
match self {
Self::Stable => None,
Self::NightlyV1(root) => Some(root),
}
}
}
#[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()),
}
}
/// 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 `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::*;
use std::cell::Cell;
fn args(values: &[&str]) -> Vec<OsString> {
values.iter().map(OsString::from).collect()
}
fn absolute() -> &'static str {
super::launcher_root()
}
fn nightly() -> Vec<OsString> {
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"])
}
#[test]
fn stable_arguments_and_directory_policy_are_unchanged() {
for argv in [args(&[]), args(&["--control", "7981", "a.docx"]), args(&["--", "--launch-profile", "file.docx"])] {
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 exact_version_and_root_are_parsed_without_reinterpreting_file_names() {
let mut argv = nightly();
argv.extend(args(&["--profile-root", "letter with spaces.docx"]));
let launch = parse(argv).unwrap();
assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute())));
assert_eq!(launch.args, args(&["--", "--profile-root", "letter with spaces.docx"]));
}
#[test]
fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() {
for argv in [
args(&["--launch-profile", VERSION]),
args(&["--profile-root", absolute()]),
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]),
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(argv).is_err());
}
}
/// #7849: `/nightly-data/...` carries no drive prefix and so is not absolute on Windows, and `C:\...`
/// is one relative name on Unix. A launch that carries the other platform's root spelling is refused
/// instead of run against a directory this platform never meant.
#[test]
fn a_root_absolute_only_in_the_other_platforms_spelling_is_refused() {
let foreign = if cfg!(windows) { "/nightly-data/profiles/wordcraft" } else { r"C:\NightlyData\profiles\wordcraft" };
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 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"] {
for form in [pair, reversed] {
let mut argv = args(form);
argv.push(flag.into());
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());
}
}
+28 -307
View File
@@ -14,16 +14,9 @@
#[cfg(target_os = "linux")]
mod appimage_env;
#[cfg(test)]
mod build_channel;
mod build_flavor;
mod control_server;
mod default_apps;
mod launch_profile;
mod nightly_session;
mod prefs;
mod process_identity;
mod profile_root;
mod region;
use std::path::PathBuf;
@@ -38,7 +31,7 @@ use craft::platform::appearance::SystemReader;
use craft::platform::clipboard::{Clipboard, ClipboardImage, SystemClipboard};
use craft::platform::default_app::{DefaultApp, DefaultAppError};
use craft::platform::logs::{self, LogNames, crash};
use craft::platform::open::{DroppedFile, FileIntake, IntakeSender};
use craft::platform::open::{DropTarget, DroppedFile, FileIntake, IntakeSender};
use craft::print::spool::Spool;
use craft::settings::SharedSettings;
use craft::ui::InstallSpec;
@@ -65,9 +58,6 @@ struct App {
spool: Spool,
/// The control server, when `--control` started one; it removes the token file it made.
control: Option<control_server::Control>,
/// The app binary's last step as the app leaves, run once at the end of `finish` (a Nightly
/// quit ends the process inside AppKit's terminate, after eframe's `on_exit`).
exit: Option<Box<dyn FnOnce()>>,
}
impl App {
@@ -105,12 +95,7 @@ impl App {
if let Some(control) = self.control.take() {
control.shut_down();
}
if !launch_profile::current().is_nightly() {
self.app.start_pending_update();
}
if let Some(exit) = self.exit.take() {
exit();
}
self.app.start_pending_update();
}
}
@@ -121,7 +106,7 @@ impl eframe::App for App {
// Once per frame, before any pass; the files stay in `raw` for the runtime's own reading.
let files = dropped_files(raw);
if !files.is_empty() {
self.drops.dropped(files);
self.drops.dropped(files, DropTarget::Elsewhere);
}
embed::before_input(ctx, |out| self.app.frame_input(out));
}
@@ -217,12 +202,10 @@ type MakeDefault = Box<dyn Fn() -> Result<DefaultApp, DefaultAppError>>;
/// What the app takes from its host beyond the runtime: File › Print through the system spooler,
/// personal templates (#2852, made on first save in `Templates` in the settings folder), and making
/// WordCraft the default app for Word documents (#295; macOS has no way to, so no button there).
fn services(spool: Spool, intake: FileIntake, nightly: bool) -> Services {
// Nightly never claims the stable app's file associations: the button would rewrite the same
// OS registration the stable WordCraft owns.
fn services(spool: Spool, intake: FileIntake) -> Services {
#[cfg(any(unix, windows))]
let make_default_app = (!cfg!(target_os = "macos") && !nightly)
.then(|| -> MakeDefault { Box::new(|| craft::platform::default_app::make_default(&default_apps::identity())) });
let make_default_app =
(!cfg!(target_os = "macos")).then(|| -> MakeDefault { Box::new(|| craft::platform::default_app::make_default(&default_apps::identity())) });
#[cfg(not(any(unix, windows)))]
let make_default_app: Option<MakeDefault> = None;
Services {
@@ -273,35 +256,11 @@ fn build_sha() -> &'static str {
option_env!("WORDCRAFT_BUILD_SHA").map(|s| s.get(..8).unwrap_or(s)).unwrap_or("dev")
}
/// Split the command line at its first `--`: the options before it, the documents after it. The
/// Launcher's nightly hand-off arrives as `--` followed by the file names (`launch_profile::parse`
/// puts that separator first), so it is dropped here rather than opened as a document.
fn split_at_delimiter(args: Vec<String>) -> (Vec<String>, Vec<String>) {
match args.iter().position(|a| a == "--") {
Some(i) => {
let mut options = args;
let files = options.split_off(i + 1);
options.pop();
(options, files)
}
None => (args, Vec::new()),
}
}
/// The documents to open, in the order the command line gave them: the words before `--` that the flag
/// loop kept, then the ones after it. The separator moves no document, and the Launcher, which sends
/// none before it, opens just its own file names in order.
fn documents_to_open(before: Vec<String>, after: Vec<String>) -> Vec<String> {
let mut documents = before;
documents.extend(after);
documents
}
/// The arguments as text, and apart the files whose names aren't valid Unicode, such as a Latin-1
/// one (#1440). A `--control` port, a token or a token file that isn't is an error.
fn text_args(arguments: Vec<std::ffi::OsString>) -> (Vec<String>, Vec<std::path::PathBuf>) {
fn text_args() -> (Vec<String>, Vec<std::path::PathBuf>) {
let (mut args, mut files) = (Vec::new(), Vec::new());
for (i, a) in arguments.into_iter().enumerate() {
for (i, a) in std::env::args_os().skip(1).enumerate() {
match a.into_string() {
Ok(a) => args.push(a),
Err(a) if args.last().is_some_and(|p| matches!(p.as_str(), "--control" | "--control-token" | "--control-token-file")) => {
@@ -359,106 +318,18 @@ fn complain(message: std::fmt::Arguments<'_>) {
let _ = std::io::Write::write_fmt(&mut std::io::stderr(), format_args!("wordcraft: {message}\n"));
}
fn initialize_nightly_process_identity() -> Result<(), process_identity::IdentityError> {
process_identity::initialize(
build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1,
wordcraft_ui_egui::os_window::id_for(wordcraft_ui_egui::os_window::LaunchIdentity::NightlyV1),
)
}
/// Whether a refusal may also open a native message box. Standard error always carries the reason;
/// this only adds a box where one renders without the app's event loop. Never on macOS: rfd's alert
/// there needs the AppKit run loop this start has not reached, so a refused nightly launch hung in
/// an invisible modal instead of exiting (GridCraft Mac smoke, 2026-11-26).
fn refusal_dialog(flavor: build_flavor::BuildFlavor, desktop_session: bool, macos: bool) -> bool {
build_flavor::needs_native_error(flavor, desktop_session) && !macos
}
/// Tell the person why a Launcher launch was refused: on standard error always, and with a native
/// message box on a desktop session whose modal renders without the app's run loop (Windows,
/// X11/Wayland) — a Launcher start has no terminal to read standard error from, and on macOS a modal
/// before the event loop never appears.
fn report_launch_profile_error(error: &str) {
complain(format_args!("launch profile: {error}"));
let desktop_session = cfg!(windows)
|| cfg!(target_os = "macos")
|| (cfg!(target_os = "linux") && ["DISPLAY", "WAYLAND_DISPLAY"].into_iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty())));
if refusal_dialog(build_flavor::COMPILED, desktop_session, cfg!(target_os = "macos")) {
if let Err(identity) = initialize_nightly_process_identity() {
complain(format_args!("launch profile: {identity}"));
return;
}
let _ = rfd::MessageDialog::new()
.set_title("WordCraft Nightly")
.set_description(error)
.set_level(rfd::MessageLevel::Error)
.set_buttons(rfd::MessageButtons::Ok)
.show();
}
}
/// Select the immutable launch profile before any startup service or side effect.
fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
// The 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`, 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 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);
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) = launch_profile::install(early.profile).and_then(|()| wordcraft_ui_egui::os_window::select_identity(identity)) {
report_launch_profile_error(&error);
std::process::exit(2);
}
// One data root for everything the app keeps: preferences, window place, logs, recovery,
// fonts, templates, dictionaries and control token files all come from it.
if let Some(root) = launch_profile::current().root()
&& let Err(error) = wordcraft_control_key::use_settings_dir(root.to_path_buf())
{
report_launch_profile_error(&error);
std::process::exit(2);
}
Some(early.args)
}
/// Parses the command line, installs logging and the panic hook, restores preferences and window
/// geometry, opens requested documents or the Start screen, starts the control server when
/// asked, and runs the eframe event loop.
fn main() -> eframe::Result {
// Windows: the print helper is a copy of this program that runs one job in its own process.
// It reads only its own job folder, so it runs before the launch profile is parsed: a Nightly
// wants a profile on every start, and the helper must print without one.
#[cfg(windows)]
if let Some(code) = craft::print::spool::isolated::helper_main() {
std::process::exit(code);
}
let Some(arguments) = prepare_launch() else { return Ok(()) };
// Windows: the update helper is a copy of this program started with `--finish-update`.
// A Nightly never updates itself: the Launcher owns its updates.
#[cfg(windows)]
if !launch_profile::current().is_nightly()
&& let Some(result) = craft::update::self_update::finish(&wordcraft_ui_egui::UPDATE_APP, &arguments)
{
if let Some(result) = craft::update::self_update::finish(&wordcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::<Vec<_>>()) {
std::process::exit(i32::from(result.is_err()));
}
// Linux: before anything reads another program's AppImage variables, or a thread starts (#5653).
@@ -479,16 +350,11 @@ fn main() -> eframe::Result {
log::error!("couldn't start again without another program's AppImage variables, so the self-update is off in this window: {e}");
}
let mut flags = ControlOptions::default();
let mut files = Vec::new();
let mut sample = false;
let (args, other_files) = text_args(arguments);
// The Launcher's own hand-off: `--` ends the options, so nothing after it is read as one and
// the separator itself never becomes a document.
let (args, after_separator) = split_at_delimiter(args);
// Only macOS (Finder / LaunchServices) adds these, and only to the options: a Finder launch carries
// no separator for them to sit after, and the Launcher starts the app itself, so a document whose
// name merely looks like one of these (`-NSNotes.docx`) is still opened (#7849 review).
let (args, other_files) = text_args();
// Only macOS (Finder / LaunchServices) adds these; elsewhere `-NS…` could be a real file name.
let args = if cfg!(target_os = "macos") { without_launch_args(args) } else { args };
let mut documents: Vec<String> = Vec::new();
let mut bad_control: Option<Option<String>> = None;
let mut missing_value: Option<&'static str> = None;
let mut args = args.into_iter().peekable();
@@ -522,7 +388,6 @@ fn main() -> eframe::Result {
},
"--sample" => sample = true,
"--version" => {
// A nightly build reported its channel line before this parser ran.
println!("wordcraft {} ({})", env!("CARGO_PKG_VERSION"), build_sha());
return Ok(());
}
@@ -531,12 +396,9 @@ fn main() -> eframe::Result {
let _ = std::io::Write::write_all(&mut std::io::stdout(), USAGE.as_bytes());
return Ok(());
}
_ => documents.push(a),
_ => files.push(a),
}
}
// After the loop, so a document before `--` opens before the ones after it (a stable launch's
// `a.docx -- b.docx` used to be reversed when the Launcher's list was the one collected first).
let files = documents_to_open(documents, after_separator);
// After the loop, so `--version` later on the line still wins.
if let Some(port) = bad_control {
let got = port.map(|p| format!(", got {p:?}")).unwrap_or_default();
@@ -560,13 +422,6 @@ fn main() -> eframe::Result {
complain(format_args!("--control needs a port number from 1 to 65535, got \"0\""));
std::process::exit(2);
}
// Nightly runs the Launcher's documents only: no control server, token file or automation
// switch, and none inherited from a stable launch's environment.
if launch_profile::current().is_nightly() && (control.port.is_some() || control.token.is_some() || control.token_file.is_some()) {
complain(format_args!("a WordCraft Nightly window does not start a control server; open documents through ArtCraft Launcher"));
std::process::exit(2);
}
let nightly = launch_profile::current().is_nightly();
let settings_dir = wordcraft_control_key::settings_dir();
// The log file lives in the settings directory, next to the preferences; opened after the
// arguments, so `--version` leaves no file behind. Records logged until now are written to it
@@ -585,16 +440,10 @@ fn main() -> eframe::Result {
None => logger.stderr_only(),
}
}
// A Nightly window always carries its own id; a stable one keeps the Flatpak sandbox's id
// when it runs inside one (so docks match the flatpak's desktop file).
let app_id = match launch_profile::current().root() {
Some(_) => wordcraft_ui_egui::os_window::app_id().to_string(),
None => std::env::var("FLATPAK_ID").ok().filter(|id| !id.is_empty()).unwrap_or_else(|| wordcraft_ui_egui::os_window::APP_ID.to_string()),
};
let mut options = eframe::NativeOptions {
viewport: egui::ViewportBuilder::default()
.with_title(wordcraft_ui_egui::os_window::name_for(wordcraft_ui_egui::os_window::identity()))
.with_app_id(app_id)
.with_title("WordCraft")
.with_app_id("ai.storyteller.wordcraft")
.with_inner_size([1440.0, 920.0])
.with_min_inner_size(wordcraft_ui_egui::window_geometry::MIN_SIZE)
.with_drag_and_drop(true)
@@ -655,33 +504,9 @@ fn main() -> eframe::Result {
let _apple_events = craft::platform::open::apple_events::install(sender);
#[cfg(not(target_os = "macos"))]
drop(sender);
// Nightly's own health record: one owner per profile, cleared only by a controlled return.
let (nightly_record, health_unavailable) = match nightly_session::Session::begin_with_health(
launch_profile::current().root(),
env!("WORDCRAFT_BUILT_VERSION"),
option_env!("WORDCRAFT_BUILD_SHA"),
) {
Ok(pair) => pair,
Err(error) => {
log::warn!("Nightly session health is unavailable: {error}");
(None, launch_profile::current().is_nightly())
}
};
let session_health_warning: Option<String> = health_unavailable.then(|| {
"WordCraft Nightly could not record session health in its private profile. You can still edit, but abnormal-exit detection is unavailable."
.to_string()
});
let previous_nightly_unclean = nightly_record.as_ref().is_some_and(nightly_session::Session::previous_unclean);
let nightly_watch: nightly_session::Shared = Arc::new(Mutex::new(nightly_record));
let unclean_notice_shown = Arc::new(std::sync::atomic::AtomicBool::new(false));
// The window body and its exit hook each take a clone of the flag; the return path keeps the
// other, so a start that created no window can still finish the record.
let session_for_exit = nightly_watch.clone();
let noticed_for_exit = unclean_notice_shown.clone();
let noticed_in_window = unclean_notice_shown.clone();
let exit_settings = settings.clone();
let result = eframe::run_native(
wordcraft_ui_egui::os_window::name_for(wordcraft_ui_egui::os_window::identity()),
"WordCraft",
options,
Box::new(move |cc| {
let ctx = cc.egui_ctx.clone();
@@ -703,7 +528,7 @@ fn main() -> eframe::Result {
);
let shell = ShellInfo::current().backend(if x11 { Backend::X11 } else { Backend::from_env() });
let spec = InstallSpec::new(shell, Arc::new(SystemWindows))
.app_id(wordcraft_ui_egui::os_window::app_id())
.app_id("ai.storyteller.wordcraft")
.system(SystemReader::start(wake))
.clipboard(Clipboard::new(SystemClipboard::new().decoder(decode_png)))
.placement(placement);
@@ -722,31 +547,19 @@ fn main() -> eframe::Result {
prefs::load_user_dictionary(&mut session, &settings, path);
}
let spool = Spool::new(host.jobs_shared().clone());
let mut app = WordApp::new(session, services(spool.clone(), intake, nightly)).with_host(host).with_settings(settings.clone());
let mut app = WordApp::new(session, services(spool.clone(), intake)).with_host(host).with_settings(settings.clone());
// PLAN: writer note 9 puts `with_settings` after `with_control`; it comes first here because
// the region check below reads the saved region the settings apply.
if std::env::var("WORDCRAFT_FILE_DIALOG").is_ok_and(|v| v.trim().eq_ignore_ascii_case("builtin")) {
app = app.with_fallback_chooser(true);
}
if nightly {
// The Launcher installs Nightly; Help › Check for Updates says so instead.
app.use_launcher_updates();
} else {
app.set_startup_update_check(true);
// After the preferences, so the reason it gives is in the interface language.
if updates_unsafe {
app.disable_self_update();
}
app.set_startup_update_check(true);
// After the preferences, so the reason it gives is in the interface language.
if updates_unsafe {
app.disable_self_update();
}
// Language packs from the suite's font store; an Install click is the person's own.
// Nightly keeps its own store in the profile, so a pack installed there is not a
// change to the stable apps' shared fonts.
match launch_profile::current().root() {
Some(root) => wordcraft_engine::packs::use_font_store_in(root.join("FontStore"), true),
None => {
wordcraft_engine::packs::use_font_store(true);
}
}
wordcraft_engine::packs::use_font_store(true);
// A region chosen in File › Options replaces the system's for the first blank
// document too (#838).
if !sample && app.session.prefs.region.is_some() {
@@ -763,8 +576,7 @@ fn main() -> eframe::Result {
}
}
let mut control_server = None;
if !nightly
&& let Some(port) = control.port
if let Some(port) = control.port
&& let Some((rx, started)) =
control_server::start(&control, port, WindowHost::of(&ctx), wordcraft_control_key::settings_dir().as_deref())
{
@@ -786,32 +598,9 @@ fn main() -> eframe::Result {
for f in other_files {
open_non_unicode(&mut app, &f);
}
// The personal agent files, the session record and the control token all live in the
// profile; the app's own services are built with the nightly rule in mind.
if let Some(warning) = &session_health_warning {
app.status_long(warning.clone());
}
if previous_nightly_unclean {
app.status_long(
"The previous WordCraft Nightly session did not finish normally. You can report a problem from Help › About. No diagnostics have been sent.",
);
noticed_in_window.store(true, std::sync::atomic::Ordering::Relaxed);
}
Ok(Box::new(App {
app,
panels,
drops,
settings,
spool,
control: control_server,
exit: Some(Box::new(move || {
nightly_session::finish_once(&session_for_exit, noticed_for_exit.load(std::sync::atomic::Ordering::Relaxed));
})),
}))
Ok(Box::new(App { app, panels, drops, settings, spool, control: control_server }))
}),
);
// The exit hook has run; this is the no-op fallback for a start that created no window.
nightly_session::finish_once(&nightly_watch, unclean_notice_shown.load(std::sync::atomic::Ordering::Relaxed));
// The app is dropped by now: whatever it saved on the way out is in the store.
if let Err(e) = exit_settings.lock().flush() {
log::warn!("preferences: {e}");
@@ -1013,8 +802,8 @@ mod smoke {
let (intake, sender) = FileIntake::new(Wake::new(|| {}));
let drops = intake.sender();
let session = Session::new(wordcraft_doc::Document::new());
let app = WordApp::new(session, services(spool.clone(), intake, false)).with_host(host).with_settings(settings.clone());
Run { app: App { app, panels, drops, settings, spool, control: None, exit: None }, frames, ctx, sender }
let app = WordApp::new(session, services(spool.clone(), intake)).with_host(host).with_settings(settings.clone());
Run { app: App { app, panels, drops, settings, spool, control: None }, frames, ctx, sender }
}
/// One frame as eframe runs it: the input hook once, the logic once, the UI per pass.
@@ -1078,7 +867,7 @@ mod smoke {
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("dropped.txt");
std::fs::write(&path, "Dropped words").unwrap();
run.sender.dropped(vec![DroppedFile { path: Some(path), name: "dropped.txt".into(), bytes: None }]);
run.sender.dropped(vec![DroppedFile { path: Some(path), name: "dropped.txt".into(), bytes: None }], DropTarget::Elsewhere);
run.settle();
assert!(run.app.app.session.doc.plain_text(wordcraft_doc::StoryRef::Body).contains("Dropped words"), "the dropped file opened");
let _ = std::fs::remove_dir_all(dir);
@@ -1119,71 +908,3 @@ mod smoke {
}
}
}
#[cfg(test)]
mod command_line_tests {
use super::{documents_to_open, split_at_delimiter};
/// The argv the Launcher starts a nightly with, as `prepare_launch` hands it on. The root is the one this
/// platform would pass: `/nightly-data/...` has no drive prefix, so on Windows `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));
super::launch_profile::parse(argv).unwrap().args.iter().map(|a| a.to_string_lossy().into_owned()).collect()
}
#[test]
fn the_launchers_separator_is_never_a_document() {
let (options, files) = split_at_delimiter(launcher_argv(&[]));
assert!(options.is_empty(), "{options:?}");
assert!(files.is_empty(), "the separator must not reach the documents: {files:?}");
}
#[test]
fn documents_after_the_separator_are_kept_in_order() {
let (options, files) = split_at_delimiter(launcher_argv(&["a.file"]));
assert!(options.is_empty(), "{options:?}");
assert_eq!(files, ["a.file"]);
let (_, files) = split_at_delimiter(launcher_argv(&["a.file", "--version", "--sample"]));
assert_eq!(files, ["a.file", "--version", "--sample"], "after -- every word is a document");
// A real document path, as Windows hands one on: kept whole, in order, backslashes and spaces intact.
let (_, files) = split_at_delimiter(launcher_argv(&[r"C:\Users\user\Holiday letter.docx", "a.file"]));
assert_eq!(files, [r"C:\Users\user\Holiday letter.docx", "a.file"], "a real path after -- stays a document, in order");
}
/// A document whose name looks like a LaunchServices option is one only after the separator: the strip
/// for macOS runs on the options, after the split, so `-- -NSNotes.docx report.docx` opens both.
#[test]
fn a_document_named_like_a_launch_argument_survives_the_separator() {
let (options, after) = split_at_delimiter(["-psn_0_12345", "--", "-NSNotes.docx", "report.docx"].map(String::from).to_vec());
assert!(super::without_launch_args(options).is_empty(), "the option before the separator goes");
let hazard: Vec<String> = ["-NSNotes.docx", "report.docx"].map(String::from).to_vec();
assert!(super::without_launch_args(hazard).is_empty(), "before the split the strip takes the document and the one after it");
assert_eq!(documents_to_open(Vec::new(), after), ["-NSNotes.docx", "report.docx"], "what follows the separator is opened, in order");
}
/// A stable line that carries its own separator: `a.file` before `--` opens before `b.file` after it.
/// The flag loop keeps `a.file` (its `_` arm, one push) and `documents_to_open` puts the two lists
/// back in command-line order; the reverse, appending the loop's list to the separator's, opened them
/// backwards (found in review of #7849).
#[test]
fn documents_before_the_separator_keep_their_place_before_the_ones_after_it() {
let (options, after) = split_at_delimiter(["--sample", "a.file", "--", "b.file"].map(String::from).to_vec());
assert_eq!(options, ["--sample", "a.file"], "--sample is a switch and a.file is left for the loop");
assert_eq!(documents_to_open(vec!["a.file".into()], after), ["a.file", "b.file"]);
let (_, after) = split_at_delimiter(launcher_argv(&["b.file"]));
assert_eq!(documents_to_open(Vec::new(), after), ["b.file"], "the Launcher sends nothing before the separator");
}
#[test]
fn a_refusal_never_blocks_on_a_modal_before_the_event_loop_on_macos() {
use crate::build_flavor::BuildFlavor;
assert!(super::refusal_dialog(BuildFlavor::NightlyV1, true, false), "a desktop refusal still shows the box where one renders");
assert!(!super::refusal_dialog(BuildFlavor::NightlyV1, true, true), "macOS has no run loop yet: the modal would hang");
assert!(!super::refusal_dialog(BuildFlavor::NightlyV1, false, false), "a headless session has no box");
assert!(!super::refusal_dialog(BuildFlavor::Stable, true, false), "only a nightly refusal explains itself in a box");
}
}
-266
View File
@@ -1,266 +0,0 @@
//! App-private Nightly session health, not telemetry or a Launcher protocol.
//! A live owner holds a separate persistent lease; secondary launches never rewrite its record.
//! Dropping the guard does not clear the marker. Only the app's controlled return path does.
use std::fs::{File, OpenOptions};
use std::io::{self, Read};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, PoisonError};
const RECORD: &str = "nightly-session.json";
const LEASE: &str = "nightly-session.lock";
const MAX_METADATA_BYTES: usize = 256;
pub struct Session {
_lease: File,
path: PathBuf,
own_record: Vec<u8>,
previous_unclean: bool,
}
fn regular_or_missing(path: &Path) -> io::Result<bool> {
match std::fs::symlink_metadata(path) {
Ok(metadata) if metadata.file_type().is_file() && !metadata.file_type().is_symlink() => Ok(true),
Ok(_) => Err(io::Error::other("Nightly session state must be a regular file, not an alias or directory")),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
Err(error) => Err(error),
}
}
/// Write `bytes` to `path` through a fresh temporary file in the same folder and a rename: the
/// destination entry is replaced, never followed, so a link planted at `path` is not written
/// through. The file is synced and the folder is synced after the rename.
fn write_no_follow(path: &Path, bytes: &[u8]) -> io::Result<()> {
static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
let directory = path.parent().ok_or_else(|| io::Error::other("the session record has no folder"))?;
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let temporary = directory.join(format!(".{name}.{}-{}", std::process::id(), NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)));
let mut file = OpenOptions::new().write(true).create_new(true).open(&temporary)?;
let written = std::io::Write::write_all(&mut file, bytes).and_then(|()| file.sync_all());
drop(file);
if let Err(error) = written {
let _ = std::fs::remove_file(&temporary);
return Err(error);
}
if let Err(error) = std::fs::rename(&temporary, path) {
let _ = std::fs::remove_file(&temporary);
return Err(error);
}
if let Ok(directory) = File::open(directory) {
let _ = directory.sync_all();
}
Ok(())
}
/// The owner's session, shared by the app's exit hook (macOS: a quit ends the process inside
/// AppKit's terminate) and the code after the event loop.
pub type Shared = Arc<Mutex<Option<Session>>>;
/// The controlled return ([`Session::finish`]) by whichever path comes first; later calls do nothing.
pub fn finish_once(shared: &Shared, unclean_notice_shown: bool) {
let watch = shared.lock().unwrap_or_else(PoisonError::into_inner).take();
if let Some(watch) = watch
&& let Err(error) = watch.finish(unclean_notice_shown)
{
log::warn!("Nightly session state was left intact: {error}");
}
}
impl Session {
/// The warning belongs to this window: a busy secondary has no health-record coverage,
/// while Stable and a lease-owning Nightly window preserve their existing result.
pub fn begin_with_health(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result<(Option<Self>, bool)> {
let watch = Self::begin(root, version, commit)?;
let unavailable = root.is_some() && watch.is_none();
Ok((watch, unavailable))
}
/// `None` is stable or another owner of this profile. Neither case touches the record.
/// The supplied root must already be the validated private Nightly profile.
pub fn begin(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result<Option<Self>> {
let Some(root) = root else { return Ok(None) };
if version.is_empty() || version.len() > MAX_METADATA_BYTES || commit.is_some_and(|value| value.len() > MAX_METADATA_BYTES) {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "Nightly session provenance is missing or too large"));
}
let lease_path = root.join(LEASE);
regular_or_missing(&lease_path)?;
let lease = OpenOptions::new().read(true).write(true).create(true).truncate(false).open(lease_path)?;
match lease.try_lock() {
Ok(()) => {}
Err(std::fs::TryLockError::WouldBlock) => return Ok(None),
Err(std::fs::TryLockError::Error(error)) => return Err(error),
}
let path = root.join(RECORD);
let previous_unclean = regular_or_missing(&path)?;
let own_record = serde_json::to_vec(&serde_json::json!({
"schema_version": 1,
"channel": "nightly-v1",
"version": version,
"commit": commit.filter(|value| !value.is_empty()),
}))?;
write_no_follow(&path, &own_record)?;
Ok(Some(Self { _lease: lease, path, own_record, previous_unclean }))
}
pub fn previous_unclean(&self) -> bool {
self.previous_unclean
}
/// Controlled return. If an earlier session's interruption was detected but no window showed
/// it yet, the record is left for the next owner to report; otherwise this is [`Self::complete`].
pub fn finish(self, unclean_notice_shown: bool) -> io::Result<()> {
if self.previous_unclean && !unclean_notice_shown {
return Ok(());
}
self.complete()
}
/// Controlled event-loop completion includes a handled startup error, not only exit 0.
/// An unwind, abort, forced exit or killed process never calls this method.
pub fn complete(self) -> io::Result<()> {
if !regular_or_missing(&self.path)? {
return Ok(());
}
let mut current = Vec::new();
File::open(&self.path)?.take(self.own_record.len() as u64 + 1).read_to_end(&mut current)?;
if current != self.own_record {
return Err(io::Error::other("Nightly session state changed; leaving it intact"));
}
std::fs::remove_file(&self.path)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicU64, Ordering};
struct Fixture(PathBuf);
impl Fixture {
fn new() -> Self {
static NEXT: AtomicU64 = AtomicU64::new(0);
loop {
let path =
std::env::temp_dir().join(format!("wordcraft-nightly-session-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
match std::fs::create_dir(&path) {
Ok(()) => return Self(path),
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
Err(error) => panic!("cannot create owned fixture: {error}"),
}
}
}
}
impl Drop for Fixture {
fn drop(&mut self) {
std::fs::remove_dir_all(&self.0).unwrap();
}
}
#[test]
fn busy_secondary_reports_unavailable_without_replacing_the_owner_record() {
let fixture = Fixture::new();
let (stable, warning) = Session::begin_with_health(None, "stable", None).unwrap();
assert!(stable.is_none() && !warning);
let (first, warning) = Session::begin_with_health(Some(&fixture.0), "nightly", Some("owned-commit")).unwrap();
assert!(!warning);
let first = first.unwrap();
let record = std::fs::read(fixture.0.join(RECORD)).unwrap();
let (secondary, warning) = Session::begin_with_health(Some(&fixture.0), "secondary", None).unwrap();
assert!(secondary.is_none() && warning, "a secondary window cannot claim recorded exit/crash coverage");
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record);
first.complete().unwrap();
assert!(!fixture.0.join(RECORD).exists());
}
#[test]
fn controlled_completion_is_clean_but_an_unfinished_owner_is_reported_next_time() {
let fixture = Fixture::new();
let first = Session::begin(Some(&fixture.0), "first", Some("recorded-commit")).unwrap().unwrap();
assert!(!first.previous_unclean());
let own = std::fs::read(fixture.0.join(RECORD)).unwrap();
assert!(Session::begin(Some(&fixture.0), "secondary", None).unwrap().is_none());
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), own, "a busy secondary must not replace the owner's record");
first.complete().unwrap();
assert!(!fixture.0.join(RECORD).exists());
let unimportant = Session::begin(Some(&fixture.0), "second", None).unwrap().unwrap();
assert!(!unimportant.previous_unclean());
drop(unimportant); // Unwind/abnormal-path ownership release, not a controlled completion.
let next = Session::begin(Some(&fixture.0), "third", None).unwrap().unwrap();
assert!(next.previous_unclean());
next.complete().unwrap();
assert!(!fixture.0.join(RECORD).exists());
}
#[test]
fn an_interruption_no_window_showed_survives_a_handled_startup_failure() {
let fixture = Fixture::new();
drop(Session::begin(Some(&fixture.0), "crashed", None).unwrap().unwrap());
// The window never started: no notice was shown.
let failed = Session::begin(Some(&fixture.0), "startup-failed", None).unwrap().unwrap();
assert!(failed.previous_unclean());
failed.finish(false).unwrap();
// The next start still sees the interruption and shows it.
let next = Session::begin(Some(&fixture.0), "next", None).unwrap().unwrap();
assert!(next.previous_unclean());
next.finish(true).unwrap();
assert!(!fixture.0.join(RECORD).exists(), "a session that showed the notice clears its record");
let clean = Session::begin(Some(&fixture.0), "clean", None).unwrap().unwrap();
assert!(!clean.previous_unclean());
clean.finish(false).unwrap();
assert!(!fixture.0.join(RECORD).exists());
}
#[test]
fn the_exit_hook_and_the_return_path_finish_the_session_once() {
let fixture = Fixture::new();
let shared: Shared = Arc::new(Mutex::new(Session::begin(Some(&fixture.0), "quitting", None).unwrap()));
// The exit hook (macOS quit: the only path that runs there).
finish_once(&shared, false);
assert!(!fixture.0.join(RECORD).exists(), "a quit that ran the exit hook is a clean exit");
// Elsewhere the return path runs too, by then possibly after a successor took the profile.
let successor = Session::begin(Some(&fixture.0), "successor", None).unwrap().unwrap();
assert!(!successor.previous_unclean());
let record = std::fs::read(fixture.0.join(RECORD)).unwrap();
finish_once(&shared, false);
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record, "the second finish must not touch a successor's record");
successor.complete().unwrap();
}
#[test]
fn cleanup_never_removes_an_unknown_changed_record() {
let fixture = Fixture::new();
let watch = Session::begin(Some(&fixture.0), "nightly", None).unwrap().unwrap();
std::fs::write(fixture.0.join(RECORD), b"replacement owned by someone else").unwrap();
assert!(watch.complete().is_err());
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), b"replacement owned by someone else");
}
#[test]
fn provenance_is_bounded_and_never_collects_documents_paths_or_diagnostics() {
let fixture = Fixture::new();
assert!(Session::begin(Some(&fixture.0), &"x".repeat(MAX_METADATA_BYTES + 1), None).is_err());
assert_eq!(std::fs::read_dir(&fixture.0).unwrap().count(), 0);
assert!(Session::begin(None, "", None).unwrap().is_none(), "stable has no session-health side effects");
let watch = Session::begin(Some(&fixture.0), "nightly", None).unwrap().unwrap();
let data: serde_json::Value = serde_json::from_slice(&std::fs::read(fixture.0.join(RECORD)).unwrap()).unwrap();
let fields = data.as_object().unwrap().keys().map(String::as_str).collect::<std::collections::BTreeSet<_>>();
assert_eq!(fields, ["schema_version", "channel", "version", "commit"].into_iter().collect());
assert!(data["commit"].is_null(), "missing provenance must not be invented");
watch.complete().unwrap();
}
#[test]
#[cfg(unix)]
fn reserved_state_aliases_do_not_modify_external_files() {
let fixture = Fixture::new();
let external = fixture.0.join("stable-document");
std::fs::write(&external, b"stable bytes").unwrap();
for name in [LEASE, RECORD] {
let alias = fixture.0.join(name);
std::os::unix::fs::symlink(&external, &alias).unwrap();
assert!(Session::begin(Some(&fixture.0), "nightly", None).is_err());
assert_eq!(std::fs::read(&external).unwrap(), b"stable bytes");
std::fs::remove_file(alias).unwrap();
}
}
}
+2 -4
View File
@@ -15,11 +15,9 @@ use wordcraft_ui_egui::prefs::{Prefs, import_legacy_window, legacy_ui_json};
/// The most of an old `ui.json` read for its window entry; the file is a few kilobytes.
const LEGACY_LIMIT: u64 = 8 << 20;
/// Whether this run reads and writes preferences. `WORDCRAFT_NO_PREFS` turns them off; a Nightly
/// profile always keeps its own, so an inherited developer switch cannot leave the app with no
/// preferences folder at all.
/// Whether this run reads and writes preferences. `WORDCRAFT_NO_PREFS` turns them off.
pub fn enabled() -> bool {
crate::launch_profile::current().is_nightly() || std::env::var_os("WORDCRAFT_NO_PREFS").is_none()
std::env::var_os("WORDCRAFT_NO_PREFS").is_none()
}
/// `custom-dictionary.txt` in the settings folder: the words Add to Dictionary kept (#40).
-70
View File
@@ -1,70 +0,0 @@
//! Set the immutable nightly Windows identity before any native window or COM service.
//! Stable deliberately leaves its implicit shortcut/path identity unchanged.
use std::sync::OnceLock;
#[derive(Clone, Debug, thiserror::Error)]
pub enum IdentityError {
#[error("{0}")]
Configuration(String),
}
pub fn initialize(nightly: bool, app_id: &str) -> Result<(), IdentityError> {
configure(nightly && cfg!(windows), app_id, |id| {
static RESULT: OnceLock<Result<(), String>> = OnceLock::new();
RESULT
.get_or_init(|| {
#[cfg(windows)]
{
winsafe::SetCurrentProcessExplicitAppUserModelID(id)
.map_err(|error| format!("cannot set the nightly Windows identity: {error}"))?;
let actual = winsafe::GetCurrentProcessExplicitAppUserModelID()
.map_err(|error| format!("cannot read back the nightly Windows identity: {error}"))?;
if actual != id {
return Err("the native Windows identity did not match the selected nightly channel".into());
}
Ok(())
}
#[cfg(not(windows))]
{
let _ = id;
Ok(())
}
})
.clone()
})
.map_err(IdentityError::Configuration)
}
fn configure(explicit_nightly: bool, app_id: &str, set: impl FnOnce(&str) -> Result<(), String>) -> Result<(), String> {
if explicit_nightly { set(app_id) } else { Ok(()) }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn stable_does_not_call_the_explicit_identity_api() {
configure(false, "nightly-id", |_| panic!("stable identity must remain implicit")).unwrap();
}
#[test]
fn nightly_applies_the_supplied_identity_once() {
let calls = std::cell::Cell::new(0);
configure(true, "nightly-id", |id| {
assert_eq!(id, "nightly-id");
calls.set(calls.get() + 1);
Ok(())
})
.unwrap();
assert_eq!(calls.get(), 1);
}
#[test]
fn native_identity_failure_is_returned_instead_of_starting_a_window() {
let started = std::cell::Cell::new(false);
let result = configure(true, "nightly-id", |_| Err("native identity refused".into())).map(|()| started.set(true));
assert_eq!(result.unwrap_err(), "native identity refused");
assert!(!started.get());
}
}
-535
View File
@@ -1,535 +0,0 @@
//! 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/`,
//! `custom-dictionary.txt` and the control token files. The suite's shared font store
//! (`Craft Fonts` / `craft-fonts`, which also holds installed Language packs) is the one other
//! per-user folder the app writes, and Nightly points it at the profile too
//! (`wordcraft_engine::packs::use_font_store_in`). Every stable location of either is fenced here.
use std::ffi::OsString;
use std::path::{Component, Path, PathBuf};
/// 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";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Platform {
Windows,
Linux,
Mac,
}
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()),
}
}
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}")),
}
}
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());
}
}
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");
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"));
}
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::*;
use std::collections::BTreeMap;
use std::sync::atomic::{AtomicU64, Ordering};
struct Fixture {
root: PathBuf,
env: BTreeMap<String, OsString>,
exe: PathBuf,
}
impl Fixture {
fn new() -> Self {
static NEXT: AtomicU64 = AtomicU64::new(0);
let root = loop {
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}"),
}
};
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 Fixture {
fn drop(&mut self) {
// Only the directory successfully created by this fixture is owned for removal.
std::fs::remove_dir_all(&self.root).unwrap();
}
}
#[test]
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 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);
}
#[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);
}
#[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());
}
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");
}
#[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");
}
}
-39
View File
@@ -1,39 +0,0 @@
# WordCraft app icon
A **page and pen**: a sheet of paper with a folded corner and ruled lines, with a fountain pen
lying across its lower right, on the app's blue field. It is drawn in the canvas palette the app's
own artwork uses (`#3b5bdb` field, `#efe9dc` paper, `#0b0b0c` ink).
`wordcraft.svg` is the canonical master: a full-bleed 512-unit tile with a rounded square
(`rx=112`) and no border. Windows and Linux use the tile as it is; the macOS renders sit on
Apple's grid, an 824/1024 body with a transparent margin.
## Files
- `wordcraft.svg`: canonical master (also the hicolor scalable icon).
- `wordcraft-1024.png`: 1024 px full-bleed render.
- `wordcraft-macos-512.png`: the padded macOS render (Dock, window icon; embedded by the app).
- `wordcraft.icns`: macOS bundle icon (`CFBundleIconFile`), padded frames.
- `wordcraft.ico`: Windows icon, 16–256 px, embedded in `wordcraft.exe` by
`apps/wordcraft/build.rs`.
- `hicolor/<size>/apps/ai.storyteller.wordcraft.png` (16–512) and `hicolor/scalable/...svg`:
Linux icon theme.
## Regenerate
Replace `wordcraft.svg`, then run `packaging/icons.sh`. It needs `resvg`, plus `iconutil` on macOS;
`cargo run -p xtask -- ico` packs the Windows icon.
## Nightly channel
The Nightly icons keep the drawing, its alpha and the macOS padding exactly as the stable renders
have them. Only the background contribution changes: from the app blue to the deeper Nightly
background `#232c67`. There is no letter badge, crescent or other mark; the app and the Launcher
name the channel in text.
`packaging/nightly-icons.py` derives the four files from the committed stable renders (the `.ico`
frames, the `.icns` slots, the 256 px hicolor render and the padded 512 px macOS master) and
records their hashes in [`nightly-provenance.json`](nightly-provenance.json). `--check` re-derives
them and compares. The three smallest macOS slots (16, 32 and 64 px) are box-filtered from the
padded master; every other frame is the same size as the stable frame it comes from, so nothing is
upscaled. The stable files are not modified.
-72
View File
@@ -1,72 +0,0 @@
{
"title": "WordCraft nightly deep-background icons",
"author": "@skylartaylor",
"license": "MIT OR Apache-2.0",
"source_commit": null,
"inputs": [
{
"path": "assets/app-icon/hicolor/256x256/apps/ai.storyteller.wordcraft.png",
"sha256": "7c1791408282d01e8c5d0cb1f4080971eaa412c60518694a1cec1e60b23c7406",
"purpose": "Windows/Linux native256 master"
},
{
"path": "assets/app-icon/wordcraft.ico",
"sha256": "53a23dcf66260f44d87d4d143d633395f3e967f391eda47e6e9cc3a52f820225",
"purpose": "nine full-bleed frames, 16-256 px"
},
{
"path": "assets/app-icon/wordcraft.icns",
"sha256": "02ac9dcb7ee06858416c7ef70ca2b359cad38dbef4a0b526bb1f28953d90170f",
"purpose": "padded macOS frames, 32-1024 px"
},
{
"path": "assets/app-icon/wordcraft-macos-512.png",
"sha256": "5a8a4476c1fb67123f803a8ab7a7a0dbd9912675ae54d695c17e74454913ceae",
"purpose": "padded macOS master (box-filtered down to the 16/32/64 px slots, never upscaled)"
}
],
"method": {
"kind": "derived from the project-owned stable renders by a committed, reproducible script",
"original_palette": {
"ink": "#0b0b0c",
"paper": "#efe9dc",
"background": "#3b5bdb"
},
"nightly_background": "#232c67",
"transform": "Decompose every pixel in the stable three-colour palette (ink, paper, background) and rebuild it with the Nightly background, keeping the ink and paper weights, alpha and padding. Clamped and renormalised where an antialiased pixel falls outside the triangle. No crescent, letter or badge.",
"generator": "packaging/nightly-icons.py",
"generator_sha256": "7a31bc6d3a00d991cf4fd6b1f2ce06b3bdc9201525d207ba84a935a877ee8e4a",
"reproduce": "python3 packaging/nightly-icons.py --check"
},
"outputs": {
"assets/app-icon/wordcraft-nightly.png": "43a002255f6db703599de99224cd47274905b8742d92f91d0f7c41c8cb5656e2",
"assets/app-icon/wordcraft-nightly.ico": "f4bb314bb6c8c131c7250e441407be5e22e645579881f0a80fe7bd963adda54a",
"assets/app-icon/wordcraft-nightly-1024.png": "36e21d31b852ac222c787ee27af45667882353eb9b1c3bfb62a9038c17843b25",
"assets/app-icon/wordcraft-nightly.icns": "0b359aa7f07fda079298a97215da207486ca092bbe9c6b277a5de3d3fbc4f9ef"
},
"ico_frame_sizes": [
16,
20,
24,
32,
40,
48,
64,
128,
256
],
"icns_png_slots": {
"icp4": 16,
"icp5": 32,
"icp6": 64,
"ic07": 128,
"ic08": 256,
"ic13": 256,
"ic09": 512,
"ic14": 512,
"ic10": 1024,
"ic11": 32,
"ic12": 64
},
"validation": "Every output is re-derived from the committed inputs by the committed script (--check) and compared by SHA-256; the frames' pixel dimensions and the containers' members are checked while deriving; the foreground and padding were compared visually against the stable renders. Native Explorer/Finder qualification is unrun."
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.1 KiB

-2
View File
@@ -209,7 +209,5 @@ real_name = "Helen Kwok"
[people.ashokram-si]
real_name = "Ashok Ram"
[people.reubgr]
real_name = "Reuben Grinberg"
[people.benandez]
sync_github_name = true
+1 -33
View File
@@ -4,34 +4,14 @@
use std::path::{Path, PathBuf};
/// The folder the desktop app chose before any of its state was read: a Launcher-selected
/// Nightly profile (`launch_profile`). Set once, at startup, before the first [`settings_dir`]
/// call; tests and the CLI leave it unset.
static CHOSEN: std::sync::OnceLock<PathBuf> = std::sync::OnceLock::new();
/// Point [`settings_dir`] at `dir` for this process. Fails when a folder was already chosen.
pub fn use_settings_dir(dir: PathBuf) -> Result<(), String> {
CHOSEN.set(dir).map_err(|_| "the settings folder was already selected".into())
}
/// The app's settings folder (preferences, logs, token files): macOS
/// `~/Library/Application Support/WordCraft`, Windows `%APPDATA%\WordCraft`, otherwise
/// `$XDG_CONFIG_HOME/wordcraft` or `~/.config/wordcraft`.
/// A folder chosen by the app through [`use_settings_dir`] wins: it is a launch decision, not
/// an environment variable a child or a wrapper might have inherited. `WORDCRAFT_PROFILE_DIR`
/// overrides the entire folder for isolated runs otherwise.
/// `WORDCRAFT_PROFILE_DIR` overrides the entire folder for isolated runs.
pub fn settings_dir() -> Option<PathBuf> {
if let Some(path) = CHOSEN.get() {
return Some(path.clone());
}
if let Some(path) = std::env::var_os("WORDCRAFT_PROFILE_DIR").filter(|p| !p.is_empty()) {
return Some(PathBuf::from(path));
}
platform_settings_dir()
}
/// The platform's own folder, when nothing chose one (see [`settings_dir`]).
fn platform_settings_dir() -> Option<PathBuf> {
if cfg!(target_os = "macos") {
std::env::var_os("HOME").map(|h| PathBuf::from(h).join("Library/Application Support/WordCraft"))
} else if cfg!(windows) {
@@ -87,18 +67,6 @@ mod tests {
assert_eq!(parse_instance_id("app=ai.storyteller.wordcraft\n"), None);
}
#[test]
fn a_chosen_folder_wins_over_the_environment() {
// The chosen folder is process-wide and set once, so this test only reads the rule when
// nothing chose one (the crate's own tests and the CLI never do).
if CHOSEN.get().is_none() {
assert_eq!(settings_dir(), super::platform_settings_dir());
assert!(use_settings_dir(PathBuf::from("/chosen/profile")).is_ok());
assert_eq!(settings_dir().as_deref(), Some(std::path::Path::new("/chosen/profile")));
assert!(use_settings_dir(PathBuf::from("/other")).is_err(), "the folder is selected once");
}
}
#[test]
fn key_file_per_instance() {
let dir = Path::new("/settings/wordcraft");
+24 -230
View File
@@ -7,7 +7,7 @@ use std::sync::Arc;
use serde::{Deserialize, Serialize};
use crate::para::{InlineObject, OBJ, Run};
use crate::para::{InlineObject, Run};
use crate::props::{CharProps, ParaProps};
use crate::{Block, Blocks, DocError, Document, Paragraph, Part, PartKind, Path, Pos, Result, para_block};
use crate::{Table, table::MAX_TABLE_DEPTH};
@@ -26,41 +26,8 @@ pub struct Fragment {
}
impl Fragment {
/// Text box story IDs referenced by the fragment's objects in document order, falling
/// back to the parts map's keys if no inline objects reference them.
fn text_box_ids(&self) -> Vec<u32> {
let mut ids = Vec::new();
for b in &self.blocks {
each_para(b, 0, &mut |p| {
for o in &p.objects {
for id in o.text_boxes() {
if self.parts.get(&id).is_some_and(|part| part.kind == crate::PartKind::TextBox) {
ids.push(id);
}
}
}
});
}
if ids.is_empty() {
ids.extend(self.parts.iter().filter(|(_, p)| p.kind == crate::PartKind::TextBox).map(|(id, _)| *id));
}
ids
}
/// The plain text representation of the fragment's body, falling back to text box part stories
/// when the body text has no real text (empty or only whitespace/object markers).
pub fn plain_text(&self) -> String {
let d = self.to_document();
let text = d.plain_text(crate::StoryRef::Body);
let has_body_text = text.chars().any(|c| !c.is_whitespace() && c != OBJ);
if !has_body_text && !self.parts.is_empty() {
let parts: Vec<String> =
self.text_box_ids().into_iter().map(|id| d.plain_text(crate::StoryRef::Part(id))).filter(|s| !s.is_empty()).collect();
if !parts.is_empty() {
return parts.join("\n");
}
}
text
self.to_document().plain_text(crate::StoryRef::Body)
}
/// The fragment as the body of a new document (default styles).
pub fn to_document(&self) -> Document {
@@ -100,20 +67,9 @@ impl Fragment {
found
}
/// The text a copy puts on the clipboard: [`Self::plain_text`] with symbol-font characters
/// (Wingdings…) as their Unicode equivalents. Falls back to text box part stories when body
/// text has no real text (empty or only whitespace/object markers).
/// (Wingdings…) as their Unicode equivalents.
pub fn clipboard_text(&self) -> String {
let d = self.to_document();
let text = d.shown_text(crate::StoryRef::Body);
let has_body_text = text.chars().any(|c| !c.is_whitespace() && c != OBJ);
if !has_body_text && !self.parts.is_empty() {
let parts: Vec<String> =
self.text_box_ids().into_iter().map(|id| d.shown_text(crate::StoryRef::Part(id))).filter(|s| !s.is_empty()).collect();
if !parts.is_empty() {
return parts.join("\n");
}
}
text
self.to_document().shown_text(crate::StoryRef::Body)
}
/// Add `piece` at the end, followed by a paragraph mark unless it already ends with one: how
/// Word's Spike collects what it cuts. The piece's text box stories get ids after this
@@ -647,48 +603,6 @@ fn remap_media_block(b: &mut Block, map: &BTreeMap<String, String>) {
});
}
/// Visit `(index, item)` in forward (`!last`) or reverse (`last`) order, returning the first `Some`.
fn find_in_slice<T>(slice: &[T], last: bool, mut f: impl FnMut(usize, &T) -> Option<Path>) -> Option<Path> {
if last { slice.iter().enumerate().rev().find_map(|(i, x)| f(i, x)) } else { slice.iter().enumerate().find_map(|(i, x)| f(i, x)) }
}
/// First (`last == false`) or last (`last == true`) paragraph path inside `blk`,
/// matching [`crate::text_walk::walk`] order and bounded by [`crate::PARA_WALK_DEPTH`].
fn edge_para_in_block(blk: &Block, prefix: &mut Vec<u32>, depth: usize, last: bool) -> Option<Path> {
if depth > crate::PARA_WALK_DEPTH {
return None;
}
match blk {
Block::Para(_) => Some(Path(prefix.clone())),
Block::Table(t) => find_in_slice(&t.rows, last, |r, row| {
find_in_slice(&row.cells, last, |c, cell| {
prefix.push(r as u32);
prefix.push(c as u32);
let found = find_in_slice(&cell.blocks, last, |bi, b| {
prefix.push(bi as u32);
let res = edge_para_in_block(b, prefix, depth + 1, last);
prefix.pop();
res
});
prefix.pop();
prefix.pop();
found
})
}),
}
}
/// Trim a paragraph to the offset range `from..to`, optionally clearing section breaks.
fn trim_para(para: &Paragraph, from: usize, to: usize, clear_section: bool) -> Paragraph {
let mut p = para.clone();
let _ = p.delete(to.min(p.len()), p.len());
let _ = p.delete(0, from.min(p.len()));
if clear_section {
p.section = None;
}
p
}
impl Document {
/// Convert notes between footnotes and endnotes: footnotes (`foot`) become endnotes and
/// endnotes (`end`) footnotes, both at once to swap them. Each note's kind changes, as do its
@@ -1426,22 +1340,6 @@ impl Document {
out
}
/// Copy paragraphs in linear document order between `a` and `b` inclusive (#5906).
fn copy_para_range(&self, a: &Pos, b: &Pos) -> Vec<Block> {
let (a, b) = order(a, b);
let mut out = Vec::new();
for p in self.paths_between(&a, &b) {
if let Some(para) = self.para(a.story, &p) {
let from = if p == a.path { a.off } else { 0 };
let to = if p == b.path { b.off } else { para.len() };
let clear = p == b.path && b.off < para.len();
out.push(Block::Para(trim_para(para, from, to, clear)));
}
}
out
}
/// Copy blocks spanning `a..b`, preserving whole tables when covered across containers (#5906).
fn copy_blocks(&self, a: &Pos, b: &Pos) -> Vec<Block> {
let (a, b) = order(a, b);
let mut out = Vec::new();
@@ -1454,17 +1352,21 @@ impl Document {
let Some(blk) = bl.get(i) else { break };
match &**blk {
Block::Para(p) => {
let mut p = p.clone();
let to = if i == b.path.last() { b.off } else { p.len() };
let from = if i == a.path.last() { a.off } else { 0 };
let clear = i == b.path.last() && to < p.len();
out.push(Block::Para(trim_para(p, from, to, clear)));
let _ = p.delete(to.min(p.len()), p.len());
let _ = p.delete(0, from.min(p.len()));
if i == b.path.last() && to < self.para(a.story, &b.path).map(Paragraph::len).unwrap_or(0) {
p.section = None;
}
out.push(Block::Para(p));
}
Block::Table(_) => out.push((**blk).clone()),
Block::Table(t) => out.push(Block::Table(t.clone())),
}
}
return out;
}
// Across the cells of a whole table: the table itself, not its cells' paragraphs (#1744).
if let Some(tp) = self.whole_table(&a, &b)
&& let Some(blk) = self.block(a.story, &tp)
@@ -1472,92 +1374,17 @@ impl Document {
out.push(blk.clone());
return out;
}
// Find the lowest common ancestor container.
let common = a.path.0.iter().zip(&b.path.0).take_while(|(x, y)| x == y).count();
let level = common.saturating_sub(common % 3);
let prefix = a.path.0.get(..level).unwrap_or_default().to_vec();
let block_path = |i: usize| {
let mut v = prefix.clone();
v.push(i as u32);
Path(v)
};
let (Some(&ia), Some(&ib)) = (a.path.0.get(level), b.path.0.get(level)) else {
return self.copy_para_range(&a, &b);
};
let (ia, ib) = (ia as usize, ib as usize);
if ia >= ib {
return self.copy_para_range(&a, &b);
}
let Some(bl) = self.container(a.story, &block_path(ia)) else {
return self.copy_para_range(&a, &b);
};
let edge_para = |i: usize, last: bool| -> Option<Path> {
let blk = bl.get(i)?;
if matches!(&**blk, Block::Para(_)) {
return None;
}
let mut pre = block_path(i).0;
edge_para_in_block(blk, &mut pre, level / 3, last)
};
let walked = |i: usize| bl.get(i).is_some_and(|b| !deeper_than_walk(b, level / 3));
let a_covers = if a.path.0.len() == level + 1 {
a.off == 0
} else {
a.path.0.len() > level + 1 && a.off == 0 && walked(ia) && edge_para(ia, false).as_ref() == Some(&a.path)
};
let b_at_end = self.para(b.story, &b.path).is_some_and(|p| p.len() == b.off);
let b_covers = if b.path.0.len() == level + 1 {
b_at_end
} else {
b.path.0.len() > level + 1 && walked(ib) && edge_para(ib, true).as_ref() == Some(&b.path) && b_at_end
};
// Start block ia:
if a_covers {
if let Some(blk) = bl.get(ia) {
out.push((**blk).clone());
}
} else if a.path.0.len() == level + 1 {
if let Some(blk) = bl.get(ia)
&& let Block::Para(p) = &**blk
{
out.push(Block::Para(trim_para(p, a.off, p.len(), false)));
}
} else if let Some(last_in_a) = edge_para(ia, true) {
let end_pos = Pos { story: a.story, path: last_in_a.clone(), off: self.para(a.story, &last_in_a).map_or(0, Paragraph::len) };
out.extend(self.copy_para_range(&a, &end_pos));
}
// Blocks strictly between ia and ib: whole blocks
for i in ia + 1..ib {
if let Some(blk) = bl.get(i) {
out.push((**blk).clone());
for p in self.paths_between(&a, &b) {
if let Some(para) = self.para(a.story, &p) {
let mut q = para.clone();
let to = if p == b.path { b.off } else { q.len() };
let from = if p == a.path { a.off } else { 0 };
let _ = q.delete(to.min(q.len()), q.len());
let _ = q.delete(0, from.min(q.len()));
q.section = None;
out.push(Block::Para(q));
}
}
// End block ib:
if b_covers {
if let Some(blk) = bl.get(ib) {
out.push((**blk).clone());
}
} else if b.path.0.len() == level + 1 {
if let Some(blk) = bl.get(ib)
&& let Block::Para(p) = &**blk
{
let clear = b.off < p.len();
out.push(Block::Para(trim_para(p, 0, b.off, clear)));
}
} else if let Some(first_in_b) = edge_para(ib, false) {
let start_pos = Pos { story: b.story, path: first_in_b, off: 0 };
out.extend(self.copy_para_range(&start_pos, &b));
}
out
}
@@ -1682,12 +1509,9 @@ impl Document {
if blocks.is_empty() {
return Ok(pos.clone());
}
let Some(dest_para) = self.para_at(pos) else {
if self.para_at(pos).is_none() {
return Err(DocError::BadPath(pos.path.to_string()));
};
let is_dest_empty = dest_para.is_empty();
let table_para = table_style_para(self, pos);
let destination_shading = self.styles.resolve_para_in(&dest_para.props, table_para.as_ref()).shading;
}
let mut parts = frag.parts.clone();
if !media_remap.is_empty() {
for b in &mut blocks {
@@ -1714,7 +1538,6 @@ impl Document {
&& let Some(Block::Para(src)) = blocks.first()
{
let src = src.clone();
let src_shading = self.styles.resolve_para(&src.props).shading;
let target = self.para_mut(pos.story, &pos.path)?;
let tail = target.split_off(pos.off)?;
let added = src.len();
@@ -1725,13 +1548,6 @@ impl Document {
target.append(src);
target.append(tail);
target.props = keep;
// Paragraph shading is the pasted text's background (HTML container backgrounds
// become paragraph shading), so an empty unshaded destination takes the source's.
// A paste without a paragraph mark into an existing paragraph leaves the
// destination paragraph's formatting unchanged (#6157).
if is_dest_empty && destination_shading.is_none() {
target.props.shading = src_shading;
}
target.section = sect;
return Ok(Pos { off: pos.off + added, ..pos.clone() });
}
@@ -1743,28 +1559,13 @@ impl Document {
let mut idx = left.last() + 1;
match first {
Block::Para(p) => {
let src_shading = self.styles.resolve_para(&p.props).shading;
let l = self.para_mut(pos.story, &left)?;
let keep = l.props.clone();
let keep_empty = keep.is_empty();
let keep_shading = keep.shading;
let mut p2 = p;
let pprops = p2.props.clone();
p2.section = None;
l.append(p2);
l.props = if keep_empty { pprops } else { keep };
if destination_shading.is_some() {
// When adopting a source paragraph style into an empty destination,
// preserve the destination background as a direct override so the
// source style's shading does not win over it (#6157).
if keep_empty && l.props.style.is_some() {
l.props.shading = destination_shading;
} else {
l.props.shading = keep_shading;
}
} else if is_dest_empty && !keep_empty && l.props.shading.is_none() {
l.props.shading = src_shading;
}
l.props = if keep.is_empty() { pprops } else { keep };
}
t @ Block::Table(_) => {
self.insert_block(pos.story, &left.with_last(idx), t)?;
@@ -1805,13 +1606,6 @@ impl Document {
}
}
/// Paragraph formatting of the table style enclosing `pos`, if any.
fn table_style_para(doc: &Document, pos: &Pos) -> Option<ParaProps> {
let (tp, _, _) = pos.path.cell()?;
let id = doc.table(pos.story, &tp)?.props.style.as_deref()?;
Some(doc.styles.table_style(id)?.para.clone())
}
/// Take the drop cap (and its options) off a paragraph's properties.
fn clear_drop_cap(props: &mut crate::props::ParaProps) {
props.drop_cap = None;
-330
View File
@@ -118,182 +118,6 @@ fn copy_paste_round_trip() {
assert!(d.plain_text(StoryRef::Body).starts_with("XYalpha"));
}
/// Shading a pasted paragraph gets from its style is kept as direct shading on an empty unshaded destination (#6157).
#[test]
fn paste_keeps_source_style_shading() {
let mut d = doc(&[""]);
Arc::make_mut(&mut d.styles).upsert(crate::Style {
id: "SourceShaded".into(),
name: "Source Shaded".into(),
kind: crate::StyleKind::Paragraph,
based_on: Some("Normal".into()),
para: ParaProps { shading: Some(crate::Rgb(0x33, 0x33, 0x33)), ..Default::default() },
..Default::default()
});
let mut src = Paragraph::with_text("X", CharProps::default());
src.props.style = Some("SourceShaded".into());
let one = Fragment { blocks: vec![Block::Para(src)], ..Default::default() };
d.insert_fragment(&Pos::body(0, 0), &one).unwrap();
let p = d.para(StoryRef::Body, &Path::top(0)).unwrap();
assert_eq!(p.props.shading, Some(crate::Rgb(0x33, 0x33, 0x33)), "source style shading is kept on empty destination");
}
/// A one-line paste without a paragraph mark into a non-empty paragraph leaves destination shading unshaded (#6157).
#[test]
fn single_block_paste_into_non_empty_paragraph_leaves_destination_unshaded() {
let mut d = doc(&["plain"]);
Arc::make_mut(&mut d.styles).upsert(crate::Style {
id: "SourceShaded".into(),
name: "Source Shaded".into(),
kind: crate::StyleKind::Paragraph,
based_on: Some("Normal".into()),
para: ParaProps { shading: Some(crate::Rgb(0x33, 0x33, 0x33)), ..Default::default() },
..Default::default()
});
let mut src = Paragraph::with_text("X", CharProps::default());
src.props.style = Some("SourceShaded".into());
let one = Fragment { blocks: vec![Block::Para(src)], ..Default::default() };
d.insert_fragment(&Pos::body(0, 5), &one).unwrap();
let p = d.para(StoryRef::Body, &Path::top(0)).unwrap();
assert_eq!(p.props.shading, None, "one-line paste without a paragraph mark must not shade destination paragraph");
}
/// An empty destination with direct properties keeps the first pasted paragraph's style shading (#6157).
#[test]
fn multi_block_paste_keeps_source_style_shading() {
let mut d = doc(&[""]);
Arc::make_mut(&mut d.styles).upsert(crate::Style {
id: "SourceShaded".into(),
name: "Source Shaded".into(),
kind: crate::StyleKind::Paragraph,
based_on: Some("Normal".into()),
para: ParaProps { shading: Some(crate::Rgb(0x33, 0x33, 0x33)), ..Default::default() },
..Default::default()
});
let mut a = Paragraph::with_text("A", CharProps::default());
a.props.style = Some("SourceShaded".into());
let b = Paragraph::with_text("B", CharProps::default());
let frag = Fragment { blocks: vec![Block::Para(a), Block::Para(b)], ..Default::default() };
d.para_mut(StoryRef::Body, &Path::top(0)).unwrap().props.align = Some(crate::props::Align::Center);
d.insert_fragment(&Pos::body(0, 0), &frag).unwrap();
let p = d.para(StoryRef::Body, &Path::top(0)).unwrap();
assert_eq!(p.props.shading, Some(crate::Rgb(0x33, 0x33, 0x33)), "first pasted paragraph keeps its style shading");
}
/// The destination's resolved (default) shading is not replaced by the source's direct shading (#6157).
#[test]
fn multi_block_paste_keeps_destination_default_shading() {
let mut d = doc(&["plain"]);
Arc::make_mut(&mut d.styles).default_para.shading = Some(crate::Rgb(0x22, 0x22, 0x22));
let mut a = Paragraph::with_text("A", CharProps::default());
a.props.shading = Some(crate::Rgb(0x11, 0x11, 0x11));
let b = Paragraph::with_text("B", CharProps::default());
let frag = Fragment { blocks: vec![Block::Para(a), Block::Para(b)], ..Default::default() };
d.insert_fragment(&Pos::body(0, 5), &frag).unwrap();
let p = d.para(StoryRef::Body, &Path::top(0)).unwrap();
assert_eq!(p.props.shading, None, "source direct shading must not override the destination default");
assert_eq!(d.styles.resolve_para(&p.props).shading, Some(crate::Rgb(0x22, 0x22, 0x22)));
}
/// An empty destination with inherited shading keeps its shading when pasting a differently shaded source style (#6157).
#[test]
fn multi_block_paste_keeps_destination_inherited_shading_over_source_style() {
let mut d = doc(&["plain"]);
Arc::make_mut(&mut d.styles).default_para.shading = Some(crate::Rgb(0x22, 0x22, 0x22));
Arc::make_mut(&mut d.styles).upsert(crate::Style {
id: "SourceShaded".into(),
name: "Source Shaded".into(),
kind: crate::StyleKind::Paragraph,
based_on: Some("Normal".into()),
para: ParaProps { shading: Some(crate::Rgb(0x33, 0x33, 0x33)), ..Default::default() },
..Default::default()
});
let mut a = Paragraph::with_text("A", CharProps::default());
a.props.style = Some("SourceShaded".into());
let b = Paragraph::with_text("B", CharProps::default());
let frag = Fragment { blocks: vec![Block::Para(a), Block::Para(b)], ..Default::default() };
d.insert_fragment(&Pos::body(0, 5), &frag).unwrap();
let p = d.para(StoryRef::Body, &Path::top(0)).unwrap();
assert_eq!(p.props.shading, Some(crate::Rgb(0x22, 0x22, 0x22)), "destination inherited shading is preserved as a direct override");
assert_eq!(
d.styles.resolve_para(&p.props).shading,
Some(crate::Rgb(0x22, 0x22, 0x22)),
"resolved shading must match the destination background, not the source style"
);
}
/// Multi-block paste into an empty unshaded destination keeps a shaded source style without
/// duplicating its color into direct paragraph shading (#6157).
#[test]
fn multi_block_paste_into_empty_destination_keeps_source_style_without_direct_shading() {
let mut d = doc(&[""]);
Arc::make_mut(&mut d.styles).upsert(crate::Style {
id: "SourceShaded".into(),
name: "Source Shaded".into(),
kind: crate::StyleKind::Paragraph,
based_on: Some("Normal".into()),
para: ParaProps { shading: Some(crate::Rgb(0x33, 0x33, 0x33)), ..Default::default() },
..Default::default()
});
let mut a = Paragraph::with_text("A", CharProps::default());
a.props.style = Some("SourceShaded".into());
let mut b = Paragraph::with_text("B", CharProps::default());
b.props.style = Some("SourceShaded".into());
let frag = Fragment { blocks: vec![Block::Para(a), Block::Para(b)], ..Default::default() };
d.insert_fragment(&Pos::body(0, 0), &frag).unwrap();
for idx in [0, 1] {
let p = d.para(StoryRef::Body, &Path::top(idx)).unwrap();
assert_eq!(p.props.style.as_deref(), Some("SourceShaded"));
assert_eq!(p.props.shading, None, "paragraph {idx} inherits from its style without redundant direct shading");
assert_eq!(d.styles.resolve_para(&p.props).shading, Some(crate::Rgb(0x33, 0x33, 0x33)));
}
}
/// Paragraph shading inherited from an enclosing table's style is preserved as destination shading (#6157).
#[test]
fn paste_keeps_destination_table_style_shading() {
let mut d = doc(&["outside"]);
Arc::make_mut(&mut d.styles).upsert(crate::Style {
id: "ShadedGrid".into(),
name: "Shaded Grid".into(),
kind: crate::StyleKind::Table,
para: ParaProps { shading: Some(crate::Rgb(0x22, 0x22, 0x22)), ..Default::default() },
..Default::default()
});
Arc::make_mut(&mut d.styles).upsert(crate::Style {
id: "SourceShaded".into(),
name: "Source Shaded".into(),
kind: crate::StyleKind::Paragraph,
based_on: Some("Normal".into()),
para: ParaProps { shading: Some(crate::Rgb(0x44, 0x44, 0x44)), ..Default::default() },
..Default::default()
});
let mut t = Table::new(1, 2, 200.0);
t.props.style = Some("ShadedGrid".into());
d.insert_block(StoryRef::Body, &Path::top(0), Block::Table(t)).unwrap();
// Single-block paste into cell (0, 0): table-style paragraph shading is not overridden.
let mut src = Paragraph::with_text("cell1", CharProps::default());
src.props.shading = Some(crate::Rgb(0x1e, 0x1e, 0x1e));
let one = Fragment { blocks: vec![Block::Para(src)], ..Default::default() };
let cell0 = Pos { story: StoryRef::Body, path: Path(vec![0, 0, 0, 0]), off: 0 };
d.insert_fragment(&cell0, &one).unwrap();
let p0 = d.para(StoryRef::Body, &cell0.path).unwrap();
assert_eq!(p0.props.shading, None);
let tp = &d.styles.table_style("ShadedGrid").unwrap().para;
assert_eq!(d.styles.resolve_para_in(&p0.props, Some(tp)).shading, Some(crate::Rgb(0x22, 0x22, 0x22)));
// Multi-block paste with a differently shaded source style into empty cell (0, 1).
let mut a = Paragraph::with_text("A", CharProps::default());
a.props.style = Some("SourceShaded".into());
let b = Paragraph::with_text("B", CharProps::default());
let multi = Fragment { blocks: vec![Block::Para(a), Block::Para(b)], ..Default::default() };
let cell1 = Pos { story: StoryRef::Body, path: Path(vec![0, 0, 1, 0]), off: 0 };
d.insert_fragment(&cell1, &multi).unwrap();
let p1 = d.para(StoryRef::Body, &cell1.path).unwrap();
assert_eq!(d.styles.resolve_para_in(&p1.props, Some(tp)).shading, Some(crate::Rgb(0x22, 0x22, 0x22)));
}
/// The first paragraph of the deepest cell, following the first table at each level.
fn deepest(d: &Document) -> Path {
let (mut path, mut blocks) = (Vec::new(), &d.body);
@@ -480,33 +304,6 @@ fn fragment_without_parts_never_shows_an_unrelated_story() {
assert_eq!(got[2], None, "a header isn't a text box");
}
#[test]
fn fragment_extracts_text_box_stories_in_object_order() {
let mut p = Paragraph::new();
p.insert_object(0, box_shape(Some(20)), &CharProps::default()).unwrap();
p.insert_object(p.text.len(), box_shape(Some(10)), &CharProps::default()).unwrap();
let mut parts = BTreeMap::new();
parts.insert(
10,
crate::Part {
kind: PartKind::TextBox,
blocks: vec![para_block(Paragraph::with_text("Second", CharProps::default()))],
body: Default::default(),
},
);
parts.insert(
20,
crate::Part {
kind: PartKind::TextBox,
blocks: vec![para_block(Paragraph::with_text("First", CharProps::default()))],
body: Default::default(),
},
);
let f = Fragment { blocks: vec![Block::Para(p)], parts, ..Default::default() };
assert_eq!(f.plain_text(), "First\nSecond");
assert_eq!(f.clipboard_text(), "First\nSecond");
}
#[test]
fn self_nested_text_box_paste_is_bounded() {
let mut d = doc(&["x"]);
@@ -1226,130 +1023,3 @@ fn split_paragraph_keeps_the_drop_cap_on_the_first_paragraph_only() {
d.split_paragraph(&Pos::body(0, 0)).unwrap();
assert_eq!((drop_cap(&d, 0), drop_cap(&d, 1)), (cap.clone(), cap));
}
/// #5906: Copying a range spanning from inside a table to an outside paragraph preserves the table.
#[test]
fn copy_range_preserves_table_structure_across_blocks() {
let mut d = Document::new();
let mut t = Table::new(2, 2, 200.0);
t.rows[0].cells[0].blocks = vec![para_block(Paragraph::with_text("A1", CharProps::default()))];
t.rows[0].cells[1].blocks = vec![para_block(Paragraph::with_text("B1", CharProps::default()))];
t.rows[1].cells[0].blocks = vec![para_block(Paragraph::with_text("A2", CharProps::default()))];
t.rows[1].cells[1].blocks = vec![para_block(Paragraph::with_text("B2", CharProps::default()))];
d.body = vec![Arc::new(Block::Table(t)), Arc::new(Block::Para(Paragraph::with_text("Trailing", CharProps::default())))];
let start = d.start_of(StoryRef::Body);
let end = d.end_of(StoryRef::Body);
let frag = d.copy_range(&start, &end);
assert_eq!(frag.blocks.len(), 2, "expected table and trailing paragraph, got {:?}", frag.blocks);
let Block::Table(tbl) = &frag.blocks[0] else { panic!("first block should be Table") };
assert_eq!(tbl.rows.len(), 2, "copied table row count");
assert_eq!(tbl.cols(), 2, "copied table col count");
let c00 = tbl.rows[0].cells[0].blocks.first().and_then(|b| match &**b {
Block::Para(p) => Some(p.text.as_str()),
_ => None,
});
assert_eq!(c00, Some("A1"), "cell (0, 0) text");
let Block::Para(trail) = &frag.blocks[1] else { panic!("second block should be Para") };
assert_eq!(trail.text.as_str(), "Trailing");
}
/// #5906: Copying a range enclosing a table between paragraphs preserves the table block.
#[test]
fn copy_range_preserves_table_between_paragraphs() {
let mut d = Document::new();
let mut t = Table::new(2, 2, 200.0);
t.rows[0].cells[0].blocks = vec![para_block(Paragraph::with_text("A1", CharProps::default()))];
t.rows[0].cells[1].blocks = vec![para_block(Paragraph::with_text("B1", CharProps::default()))];
t.rows[1].cells[0].blocks = vec![para_block(Paragraph::with_text("A2", CharProps::default()))];
t.rows[1].cells[1].blocks = vec![para_block(Paragraph::with_text("B2", CharProps::default()))];
d.body = vec![
Arc::new(Block::Para(Paragraph::with_text("Intro", CharProps::default()))),
Arc::new(Block::Table(t)),
Arc::new(Block::Para(Paragraph::with_text("Outro", CharProps::default()))),
];
let start = Pos { story: StoryRef::Body, path: Path(vec![0]), off: 0 };
let end = d.end_of(StoryRef::Body);
let frag = d.copy_range(&start, &end);
assert_eq!(frag.blocks.len(), 3, "expected intro, table, and outro, got {:?}", frag.blocks);
assert!(matches!(&frag.blocks[0], Block::Para(p) if p.text == "Intro"));
let Block::Table(tbl) = &frag.blocks[1] else { panic!("second block should be Table") };
assert_eq!(tbl.rows.len(), 2, "copied table row count");
assert_eq!(tbl.cols(), 2, "copied table col count");
assert!(matches!(&frag.blocks[2], Block::Para(p) if p.text == "Outro"));
}
/// #5906: Copy range across cells inside a table preserves all traversed paragraphs in linear order.
#[test]
fn copy_range_linear_cross_cells_preserves_all_traversed_paragraphs() {
let mut d = Document::new();
let mut t = Table::new(3, 3, 300.0);
for (r, row) in t.rows.iter_mut().enumerate() {
for (c, cell) in row.cells.iter_mut().enumerate() {
cell.blocks = vec![para_block(Paragraph::with_text(&format!("R{r}C{c}"), CharProps::default()))];
}
}
d.body = vec![Arc::new(Block::Table(t))];
// Start at (0, 1) offset 1 ("0C1"), end at (1, 1) offset 3 ("R1C")
let a = Pos { story: StoryRef::Body, path: Path(vec![0, 0, 1, 0]), off: 1 };
let b = Pos { story: StoryRef::Body, path: Path(vec![0, 1, 1, 0]), off: 3 };
let frag = d.copy_range(&a, &b);
assert_eq!(frag.blocks.len(), 4, "all 4 traversed cells in linear order");
let texts: Vec<&str> = frag
.blocks
.iter()
.filter_map(|b| match b {
Block::Para(p) => Some(p.text.as_str()),
_ => None,
})
.collect();
assert_eq!(texts, vec!["0C1", "R0C2", "R1C0", "R1C"]);
}
/// #5906: Copy range from paragraph before table into non-corner cell preserves all traversed text in linear order.
#[test]
fn copy_range_from_para_before_table_to_non_corner_cell() {
let mut d = Document::new();
let mut t = Table::new(3, 3, 300.0);
for (r, row) in t.rows.iter_mut().enumerate() {
for (c, cell) in row.cells.iter_mut().enumerate() {
cell.blocks = vec![para_block(Paragraph::with_text(&format!("R{r}C{c}"), CharProps::default()))];
}
}
d.body = vec![Arc::new(Block::Para(Paragraph::with_text("LeadingText", CharProps::default()))), Arc::new(Block::Table(t))];
let a = Pos { story: StoryRef::Body, path: Path(vec![0]), off: 7 };
let b = Pos { story: StoryRef::Body, path: Path(vec![1, 1, 1, 0]), off: 3 };
let frag = d.copy_range(&a, &b);
let texts: Vec<&str> = frag
.blocks
.iter()
.filter_map(|b| match b {
Block::Para(p) => Some(p.text.as_str()),
_ => None,
})
.collect();
assert_eq!(texts, vec!["Text", "R0C0", "R0C1", "R0C2", "R1C0", "R1C"]);
}
/// #5906: Copy range from non-corner cell into following paragraph preserves all traversed text in linear order.
#[test]
fn copy_range_from_cell_into_para_after_table() {
let mut d = Document::new();
let mut t = Table::new(2, 2, 200.0);
t.rows[0].cells[0].blocks = vec![para_block(Paragraph::with_text("Hello", CharProps::default()))];
t.rows[0].cells[1].blocks = vec![para_block(Paragraph::with_text("World", CharProps::default()))];
t.rows[1].cells[0].blocks = vec![para_block(Paragraph::with_text("Foo", CharProps::default()))];
t.rows[1].cells[1].blocks = vec![para_block(Paragraph::with_text("Bar", CharProps::default()))];
d.body = vec![Arc::new(Block::Table(t)), Arc::new(Block::Para(Paragraph::with_text("Trailing", CharProps::default())))];
let a = Pos { story: StoryRef::Body, path: Path(vec![0, 0, 1, 0]), off: 1 };
let b = Pos { story: StoryRef::Body, path: Path(vec![1]), off: 5 };
let frag = d.copy_range(&a, &b);
let texts: Vec<&str> = frag
.blocks
.iter()
.filter_map(|b| match b {
Block::Para(p) => Some(p.text.as_str()),
_ => None,
})
.collect();
assert_eq!(texts, vec!["orld", "Foo", "Bar", "Trail"]);
}
+1 -42
View File
@@ -110,17 +110,7 @@ fn unmodelled_settings_survive_a_save_and_owned_ones_follow_the_model() {
assert!(!s.contains("trackRevisions"), "{s}");
assert_eq!(s.matches("compatibilityMode").count(), 1, "{s}");
assert!(s.contains("mailMerge"), "{s}");
let rel_id = s
.split("<w:dataSource")
.nth(1)
.and_then(|after| after.split("r:id=\"").nth(1))
.and_then(|after| after.split('"').next())
.expect("dataSource r:id");
let rels = text(&files, "word/_rels/settings.xml.rels");
let expected_rel = format!(
r#"<Relationship Id="{rel_id}" Type="{REL}/mailMergeSource" Target="file:///__wordcraft_missing_source__/letters.xlsx" TargetMode="External"/>"#
);
assert!(rels.contains(&expected_rel), "missing matching relationship for {rel_id}: {rels}");
assert!(text(&files, "word/_rels/settings.xml.rels").contains("file:///__wordcraft_missing_source__/letters.xlsx"));
// The privacy options are the model's (#1062): written once each, and gone when turned off.
assert_eq!(s.matches("removePersonalInformation").count(), 1, "{s}");
assert_eq!(s.matches("removeDateAndTime").count(), 1, "{s}");
@@ -142,37 +132,6 @@ fn unmodelled_settings_survive_a_save_and_owned_ones_follow_the_model() {
assert_eq!(text(&save(&again), "word/settings.xml"), s);
}
#[test]
fn changed_zoom_survives_merged_settings_and_reads_back_as_page_width() {
let old_zoom = r#"<w:zoom w:percent="120"/>"#;
let updated_zoom = r#"<w:zoom w:val="bestFit" w:percent="145"/>"#;
for original in [SETTINGS.to_string(), SETTINGS.replace(old_zoom, "")] {
let mut doc = wordcraft_docx::read(&with_settings(&original)).unwrap();
assert!(doc.passthrough.contains_key("wordcraft:settings.orig"));
doc.settings.zoom = Some(wordcraft_doc::Zoom { percent: 145, fit: Some(wordcraft_doc::ZoomFit::PageWidth) });
let bytes = wordcraft_docx::write(&doc).unwrap();
let settings = text(&unzip(&bytes), "word/settings.xml");
assert_eq!(settings.matches("<w:zoom ").count(), 1, "{settings}");
assert!(settings.contains(updated_zoom), "{settings}");
// The retained root and unrelated child bytes still belong to the original file.
let root_end = original.find("><w:").unwrap() + 1;
assert!(settings.starts_with(&original[..root_end]), "{settings}");
for kept in [
r#"<w:proofState w:spelling="clean" w:grammar="clean"/>"#,
r#"<w:docVars><w:docVar w:name="ClauseSet" w:val="B"/></w:docVars>"#,
r#"<w:rsids><w:rsidRoot w:val="00A1B2C3"/><w:rsid w:val="00A1B2C3"/></w:rsids>"#,
] {
assert!(settings.contains(kept), "{kept} lost: {settings}");
}
assert!(pos(&settings, "<w:zoom ") < pos(&settings, "<w:proofState"));
let again = wordcraft_docx::read(&bytes).unwrap();
let zoom = again.settings.zoom.unwrap();
assert_eq!(zoom.percent, 145);
assert!(matches!(zoom.fit, Some(wordcraft_doc::ZoomFit::PageWidth)));
assert_eq!(text(&save(&again), "word/settings.xml"), settings);
}
}
#[test]
fn settings_written_by_wordcraft_keep_no_original() {
let doc = wordcraft_doc::Document::new();
-1
View File
@@ -33,7 +33,6 @@ pub mod packs;
pub mod page;
pub mod para;
pub mod paste;
pub mod paste_cells;
pub mod phonetic;
pub mod protect;
pub mod references;
+6 -38
View File
@@ -35,32 +35,6 @@ pub fn selected_member(s: &Session) -> Option<(Pos, usize, &InlineObject)> {
Some((pos, m.index, &c.obj))
}
/// The canvas member whose text box story the caret is in (when no inner object is selected):
/// the canvas's position, the member's index and the member.
pub fn text_box_member(s: &Session) -> Option<(Pos, usize, &InlineObject)> {
if super::objects::selected(s).is_some() {
return None;
}
let StoryRef::Part(id) = s.sel.focus.story else { return None };
if !s.doc.parts.get(&id).is_some_and(|p| p.kind == PartKind::TextBox) {
return None;
}
let after = s.doc.text_box_anchor(id)?;
let pos = Pos { off: after.off.checked_sub(wordcraft_doc::para::OBJ.len_utf8())?, ..after };
let InlineObject::Group { children, canvas: Some(_), .. } = s.doc.para_at(&pos)?.object_at(pos.off)? else {
return None;
};
let (index, c) =
children.iter().enumerate().find(|(_, c)| pickable(c) && matches!(&c.obj, InlineObject::Shape { story: Some(sid), .. } if *sid == id))?;
Some((pos, index, &c.obj))
}
/// The canvas member object commands act on: one picked with `select.member`, or the text box
/// member whose text the caret is in.
pub(crate) fn active_member(s: &Session) -> Option<(Pos, usize, &InlineObject)> {
selected_member(s).or_else(|| text_box_member(s))
}
/// Whether a member can be picked on its own: a picture, shape or text box that is drawn (a
/// group inside a canvas isn't, nor a hidden member).
pub fn pickable(c: &GroupChild) -> bool {
@@ -321,13 +295,7 @@ pub(crate) fn member_command(s: &mut Session, id: &str, _: &Value) -> Option<Cmd
let replaces = (id.starts_with("text.") && id != "text.overtype")
|| matches!(
id,
"edit.paste"
| "edit.pasteText"
| "edit.pasteMerge"
| "edit.pasteNestedTable"
| "edit.pasteSpecial"
| "edit.pasteClipboardItem"
| "edit.pasteAllClipboard"
"edit.paste" | "edit.pasteText" | "edit.pasteMerge" | "edit.pasteSpecial" | "edit.pasteClipboardItem" | "edit.pasteAllClipboard"
);
if !replaces && !matches!(id, "edit.cut" | "edit.copy") {
return None;
@@ -382,7 +350,7 @@ fn remove_member(s: &mut Session, pos: &Pos, index: usize) -> Result<(), CmdErro
/// Move or Resize with a member picked: `x`/`y` (the page point of its top-left, as dragging its
/// frame gives it) and the size become its place and size in the canvas. `None`: no member.
pub(crate) fn member_bounds(s: &mut Session, v: &Value) -> Option<CmdResult> {
let (pos, index, obj) = active_member(s)?;
let (pos, index, obj) = selected_member(s)?;
let (w0, h0, _) = obj.frame()?;
let min = super::objects::min_size(obj);
let to = match (p::f32(v, "x"), p::f32(v, "y")) {
@@ -413,7 +381,7 @@ pub(crate) fn member_bounds(s: &mut Session, v: &Value) -> Option<CmdResult> {
/// Nudge with a member picked: it moves inside the canvas. `None`: no member.
pub(crate) fn member_nudge(s: &mut Session, dx: f32, dy: f32) -> Option<CmdResult> {
let (pos, index, _) = active_member(s)?;
let (pos, index, _) = selected_member(s)?;
Some(edit_member(s, &pos, index, |_, (sx, sy), c| {
c.x = (c.x + dx / sx).clamp(-MAX_SIDE, MAX_SIDE);
c.y = (c.y + dy / sy).clamp(-MAX_SIDE, MAX_SIDE);
@@ -438,10 +406,10 @@ fn edit_member(s: &mut Session, pos: &Pos, index: usize, f: impl FnOnce(wordcraf
Ok(json!({"object": member, "pos": super::pos_json(pos), "member": index}))
}
/// Change the active member's own object (Shape Format, Size, Rotate, Alt Text) when `pos` is its
/// canvas. `None`: no active member there.
/// Change the picked member's own object (Shape Format, Size, Rotate, Alt Text) when `pos` is its
/// canvas. `None`: no member picked there.
pub(crate) fn edit_member_object(s: &mut Session, pos: &Pos, f: impl Fn(&mut InlineObject)) -> Option<Result<InlineObject, CmdError>> {
let (at, index, _) = active_member(s).filter(|(at, ..)| at == pos)?;
let (at, index, _) = selected_member(s).filter(|(at, ..)| at == pos)?;
let mut out = None;
let r = edit_canvas(s, &at, |_, _, children| {
if let Some(c) = children.get_mut(index) {
-13
View File
@@ -182,9 +182,6 @@ pub(crate) fn dispatch(s: &mut Session, id: &str, mutates: bool, run: fn(&mut Se
_ if cells && (id.starts_with("table.") || matches!(id, "text.tab" | "text.backTab")) => run(s, v),
// Copy and Cut of whole cells take a table of them (#1744).
"edit.copy" | "edit.cut" if cells => run(s, v),
// Paste can lay a copied table over the selected cells. Let it inspect the selection
// before the ordinary column replacement deletes it.
"edit.paste" if cells => run(s, v),
"edit.copy" => copy(s, &segs),
"edit.cut" => {
let r = copy(s, &segs)?;
@@ -212,16 +209,6 @@ pub(crate) fn dispatch(s: &mut Session, id: &str, mutates: bool, run: fn(&mut Se
}
}
/// Delete the pieces of a selected cell rectangle for an ordinary Paste replacement.
pub(super) fn delete_cell_segments(s: &mut Session) -> Result<(), CmdError> {
if s.cell_range().is_some()
&& let Some(segments) = s.column_segments().map(<[(Pos, Pos)]>::to_vec)
{
delete(s, &segments)?;
}
Ok(())
}
/// Copy: one paragraph per block row (formatting kept); the plain text joins rows with newlines.
fn copy(s: &mut Session, segs: &[(Pos, Pos)]) -> CmdResult {
let mut blocks = Vec::new();
+6 -62
View File
@@ -39,7 +39,7 @@ fn has_text_sel(s: &Session) -> Option<&'static str> {
if s.sel.is_collapsed() { Some("nothing is selected") } else { None }
}
/// Something to cut: text, an object, or whole table cells (an empty cell's selection has no length, #1744).
/// Something to cut: text, or whole table cells (an empty cell's selection has no length, #1744).
fn has_sel(s: &Session) -> Option<&'static str> {
if s.sel.is_collapsed() && s.cell_range().is_none() { Some("nothing is selected") } else { None }
}
@@ -73,7 +73,7 @@ pub fn specs() -> Vec<CommandSpec> {
.key("Mod+Y / Mod+Shift+Z")
.pure(),
CommandSpec::new("edit.cut", "Cut", "Home › Clipboard", cut).key("Mod+X").when(has_sel),
CommandSpec::new("edit.copy", "Copy", "Home › Clipboard", copy).key("Mod+C / Mod+Insert").pure().when(has_sel),
CommandSpec::new("edit.copy", "Copy", "Home › Clipboard", copy).key("Mod+C / Mod+Insert").pure(),
// Word's Spike (Ctrl+F3, Ctrl+Shift+F3; ⌘ on the Mac): the AutoText entry "Spike", so Quick
// Parts and AutoText insert it without emptying it, as in Word.
CommandSpec::new("edit.spike", "Spike", "Editing", spike).key("Mod+F3").when(has_text_sel),
@@ -89,8 +89,6 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("edit.paste", "Paste", "Home › Clipboard", paste)
.key("Mod+V / Shift+Insert")
.params(r#"{"text"?: string, "html"?: string, "rtf"?: string, "privateClipboard"?: bool}"#),
CommandSpec::new("edit.pasteNestedTable", "Paste as Nested Table", "Home › Clipboard › Paste", paste_nested)
.params(r#"{"text"?: string, "html"?: string, "rtf"?: string, "privateClipboard"?: bool} (a copied table with the caret in a table cell nests in that cell; Paste instead inserts its rows or overwrites the cells from the caret's)"#),
CommandSpec::new("edit.pasteText", "Paste: Keep Text Only", "Home › Clipboard › Paste", paste_text)
.params(r#"{"text"?: string}"#)
.key("Mod+Shift+Alt+V"),
@@ -187,7 +185,6 @@ pub fn specs() -> Vec<CommandSpec> {
]
}
/// Copy the selected text, object, or table cells to the clipboard.
fn copy(s: &mut Session, _: &Value) -> CmdResult {
let whole = super::table::selected_table(s);
copy_with(s, whole.as_ref())
@@ -221,7 +218,6 @@ pub(crate) fn copy_result(s: &mut Session) -> Value {
(s.clipboard_html, s.clipboard_rtf) = match &s.clipboard {
Some(f) => {
let mut d = f.to_document();
d.styles = s.doc.styles.clone();
if d.media.is_empty() {
d.media = s.doc.media.clone();
}
@@ -245,7 +241,6 @@ pub(crate) fn copy_result(s: &mut Session) -> Value {
r
}
/// Cut the selection, selected object, or whole table cells to the clipboard and remove it from the document.
fn cut(s: &mut Session, _: &Value) -> CmdResult {
let whole = super::table::selected_table(s);
let r = copy_with(s, whole.as_ref())?;
@@ -306,25 +301,8 @@ fn insert_spike(s: &mut Session, _: &Value) -> CmdResult {
/// else another program's HTML or RTF (#687). The system clipboard's text has none, so it pastes
/// as Keep Text Only does.
fn paste(s: &mut Session, v: &Value) -> CmdResult {
let pasted = super::paste::paste_content(s, v)?;
if let super::paste::Pasted::Fragment(frag) = &pasted
&& super::paste_cells::paste_over_selection(s, frag)?
{
return sel_result(s);
}
super::column::delete_cell_segments(s)?;
match pasted {
super::paste::Pasted::Fragment(frag) => super::paste::insert(s, frag)?,
super::paste::Pasted::Text(text) => super::paste::insert_text(s, &text)?,
}
sel_result(s)
}
/// Paste as Nested Table: like Paste, but a copied table goes inside the cell the caret is in
/// instead of laying its rows or cells over the table (#6739).
fn paste_nested(s: &mut Session, v: &Value) -> CmdResult {
match super::paste::paste_content(s, v)? {
super::paste::Pasted::Fragment(frag) => super::paste::insert_as_is(s, frag)?,
super::paste::Pasted::Fragment(frag) => super::paste::insert(s, frag)?,
super::paste::Pasted::Text(text) => super::paste::insert_text(s, &text)?,
}
sel_result(s)
@@ -466,17 +444,11 @@ fn paste_clip_item(s: &mut Session, v: &Value) -> CmdResult {
/// Every collected item, in the order they were copied (one undo step).
fn paste_all_clips(s: &mut Session, _: &Value) -> CmdResult {
let all: Vec<Fragment> = s.clip_history.items.iter().rev().map(|x| x.fragment.clone()).collect();
let multiple = all.len() > 1;
let mut r = sel_result(s)?;
for f in all {
if multiple {
// Insert each item at the end of the last one. Cell paste can overwrite a
// previous item or insert rows ahead of it.
super::paste::insert_as_is(s, f)?;
} else {
return paste_clip(s, f);
}
r = paste_clip(s, f)?;
}
sel_result(s)
Ok(r)
}
fn paste_text(s: &mut Session, v: &Value) -> CmdResult {
@@ -955,32 +927,4 @@ mod shortcut_tests {
}
}
}
#[test]
fn copy_format_web_alias_respects_user_removal_and_reassignment() {
use craft_keymap::{Binding, Chord, CommandRef, Overrides, Policy};
let mut commands = super::super::registry().all().to_vec();
commands.iter_mut().find(|c| c.id == "edit.copyFormat").unwrap().shortcut = copy_format_shortcut(true);
let registry = Registry::new(commands);
let mut keymap = crate::keymap::registry_keymap(&registry, &Overrides::default());
let copy_cmd = CommandRef::new("edit.copyFormat");
let bold_cmd = CommandRef::new("format.bold");
let chord = Chord::parse("Mod+Alt+Shift+C").unwrap();
let binding = Binding::parse("Mod+Alt+Shift+C").unwrap();
assert!(keymap.bindings(&copy_cmd).iter().any(|b| b.trigger.chord == chord));
assert!(keymap.remove(&copy_cmd, &binding));
assert_eq!(keymap.holder(&chord), None);
keymap.assign(&bold_cmd, binding, Policy::Steal).unwrap();
assert_eq!(keymap.holder(&chord).as_ref().map(|c| c.id.as_str()), Some("format.bold"));
assert_eq!(keymap.holder(&Chord::parse("Mod+Shift+C").unwrap()).as_ref().map(|c| c.id.as_str()), Some("edit.copyFormat"));
let overrides = keymap.overrides().clone();
let restored = crate::keymap::registry_keymap(&registry, &overrides);
assert_eq!(restored.holder(&chord).as_ref().map(|c| c.id.as_str()), Some("format.bold"));
assert_eq!(restored.holder(&Chord::parse("Mod+Shift+C").unwrap()).as_ref().map(|c| c.id.as_str()), Some("edit.copyFormat"));
}
}
-22
View File
@@ -398,28 +398,6 @@ mod tests {
assert!(!page_text(&mut s).contains("{ AUTHOR }"));
}
/// #980: F11 is full screen, as people expect of a desktop app; the field walk keeps Word's
/// other keys, Alt+F1 and Alt+Shift+F1 (and Shift+F11).
#[test]
fn f11_is_full_screen_and_alt_f1_walks_fields() {
let s = Session::new(wordcraft_doc::Document::new());
let keymap = crate::keymap::registry_keymap(&s.registry, s.keymap());
let chord = |c: &str| craft_keymap::Chord::parse(c).unwrap();
let key = |k: &str| keymap.holder(&chord(k)).map(|c| c.id);
assert_eq!(key("F11").as_deref(), Some("view.fullScreen"));
assert_eq!(key("Alt+F1").as_deref(), Some("fields.next"));
assert_eq!(key("Alt+Shift+F1").as_deref(), Some("fields.previous"));
assert_eq!(key("Shift+F11").as_deref(), Some("fields.previous"));
assert_eq!(key("Mod+F11").as_deref(), Some("fields.lock"));
let shortcut = s.registry.get("view.fullScreen").map(|c| c.shortcut);
if cfg!(target_os = "macos") {
assert_eq!(shortcut, Some("Mod+Ctrl+F / F11"));
assert_eq!(key("Mod+Ctrl+F").as_deref(), Some("view.fullScreen"));
} else {
assert_eq!(shortcut, Some("F11"));
}
}
/// Editing a code changes the instruction and the result; lock keeps a result through updates;
/// unlink turns the field into its text in one undo step; Alt+F1/Shift+F11 walk the fields.
#[test]
+2 -2
View File
@@ -32,11 +32,11 @@ pub(crate) use select::all_objects;
pub(crate) use select::{edit_obj, has_shape_or_canvas};
#[cfg(test)]
use select::{has_group, holds_ink, obj_size, with_obj};
pub use select::{min_size, object_selection, picked_objects, selected, selected_all, selected_or_text_box, target_objects};
pub use select::{min_size, object_selection, picked_objects, selected, selected_all};
#[cfg(test)]
use shape::can_link;
pub(crate) use shape::set_text_body;
pub use shape::{text_box_target, text_box_targets};
pub use shape::text_box_target;
pub use specs::specs;
#[cfg(test)]
+5 -5
View File
@@ -1,4 +1,4 @@
use super::select::{edit_float, min_size, movable_story, obj_size, select_object, selected_or_text_box, with_obj};
use super::select::{edit_float, min_size, movable_story, obj_size, select_object, selected, with_obj};
use super::{CmdError, CmdResult, Float, InlineObject, Pos, Selection, Session, StoryRef, Value, Wrap, json, p};
/// Largest object offset or move, points.
@@ -9,7 +9,7 @@ pub(super) fn bounds(s: &mut Session, v: &Value) -> CmdResult {
if let Some(r) = crate::cmd::canvas::member_bounds(s, v) {
return r;
}
let (pos, obj) = selected_or_text_box(s).ok_or_else(|| CmdError::Disabled("no picture or shape selected".into()))?;
let (pos, obj) = selected(s).ok_or_else(|| CmdError::Disabled("no picture or shape selected".into()))?;
let to = match (p::f32(v, "x"), p::f32(v, "y")) {
(Some(x), Some(y)) => Some((x, y)),
(None, None) => None,
@@ -88,7 +88,7 @@ fn move_in_text(s: &mut Session, pos: Pos, to: &Pos) -> Result<Pos, CmdError> {
/// (x, y), or for an In Line with Text object put it at the text position `to`, leaving the
/// original in place and the clipboard alone. The copy is selected.
pub(super) fn copy_to(s: &mut Session, v: &Value) -> CmdResult {
let (pos, obj) = selected_or_text_box(s).ok_or_else(|| CmdError::Disabled("no picture or shape selected".into()))?;
let (pos, obj) = selected(s).ok_or_else(|| CmdError::Disabled("no picture or shape selected".into()))?;
let len = wordcraft_doc::para::OBJ.len_utf8();
let end = Pos { off: pos.off + len, ..pos.clone() };
if let Some(to) = text_target(v, &obj)? {
@@ -219,7 +219,7 @@ fn move_object_once(s: &mut Session, pos: &Pos, page: usize, x: f32, y: f32, (w,
/// column / paragraph that keeps it where it is, so it can be moved by an offset.
pub(super) fn unalign(s: &mut Session) -> Result<(), CmdError> {
use wordcraft_doc::para::Anchor;
let (pos, obj) = selected_or_text_box(s).ok_or_else(|| CmdError::Disabled("no picture or shape selected".into()))?;
let (pos, obj) = selected(s).ok_or_else(|| CmdError::Disabled("no picture or shape selected".into()))?;
let Some((_, _, float)) = obj.frame() else { return Ok(()) };
if float.h_align.is_none() && float.v_align.is_none() {
return Ok(());
@@ -260,7 +260,7 @@ pub fn moves_with_text(f: &Float) -> bool {
/// object's vertical position to its paragraph or to the page, keeping it where it is now.
pub(super) fn move_with_text(s: &mut Session, with_text: bool) -> CmdResult {
use wordcraft_doc::para::Anchor;
let (pos, obj) = selected_or_text_box(s).ok_or_else(|| CmdError::Disabled("no picture or shape selected".into()))?;
let (pos, obj) = selected(s).ok_or_else(|| CmdError::Disabled("no picture or shape selected".into()))?;
let Some((_, _, float)) = obj.frame() else { return Err(CmdError::Disabled("select a floating picture or shape first".into())) };
if moves_with_text(float) == with_text {
return Ok(json!({"object": serde_json::to_value(&obj).unwrap_or(Value::Null)}));
+18 -48
View File
@@ -1,5 +1,5 @@
use super::select::{edit_obj, is_shape_or_canvas, obj_size, selected, target_objects, with_obj};
use super::{CmdError, CmdResult, InlineObject, Pos, Rgb, Session, Value, Wrap, json, p};
use super::select::{obj_size, selected, with_obj};
use super::{CmdError, CmdResult, InlineObject, Rgb, Session, Value, Wrap, p};
use wordcraft_doc::picfx::PicFx;
/// `picture.crop`: the crop, and optionally the new display size, as one edit. With a size, a
@@ -70,15 +70,19 @@ pub fn cropped_original_size(s: &Session, o: &InlineObject) -> Option<(f32, f32)
Some((orig.w * part(crop[0], crop[2]), orig.h * part(crop[1], crop[3])))
}
fn planned_size(s: &Session, o: &InlineObject, v: &Value) -> Result<(f32, f32), CmdError> {
/// Size: `scale` is a percentage of the current size, or with `original` of what the crop leaves
/// of the original size (`original` alone gives that back: the Size dialog's Reset); then `width`
/// and `height`, where one alone keeps the proportions unless `lockAspect` is false.
pub(super) fn size(s: &mut Session, v: &Value) -> CmdResult {
let (_, o) = selected(s).ok_or_else(|| CmdError::Disabled("no object".into()))?;
let lock = p::bool(v, "lockAspect").unwrap_or(true);
let (w0, h0) = obj_size(o);
let (w0, h0) = obj_size(&o);
let (mut w, mut h) = (w0, h0);
let scale = p::f32(v, "scale");
let original = p::bool(v, "original").unwrap_or(false);
if original {
let (ow, oh) =
cropped_original_size(s, o).ok_or_else(|| CmdError::Disabled("only a picture whose image can be read has an original size".into()))?;
cropped_original_size(s, &o).ok_or_else(|| CmdError::Disabled("only a picture whose image can be read has an original size".into()))?;
let k = scale.unwrap_or(100.0) / 100.0;
(w, h) = (ow * k, oh * k);
} else if let Some(sc) = scale {
@@ -114,55 +118,21 @@ fn planned_size(s: &Session, o: &InlineObject, v: &Value) -> Result<(f32, f32),
// Sides set in proportion (from the original, or from a size whose sides both have a length)
// fit the limits together. Otherwise each side the call sets fits on its own, and a side it
// leaves as it was keeps its size, a straight line's 0 too.
if keep && (original || (w0 > 0.0 && h0 > 0.0 && (w, h) != (w0, h0))) {
Ok(fit_size(w, h, true))
let (w, h) = if keep && (original || (w0 > 0.0 && h0 > 0.0 && (w, h) != (w0, h0))) {
fit_size(w, h, true)
} else {
let (fw, fh) = fit_size(w, h, false);
let left = |new: f32, old: f32| !original && new == old;
Ok((if left(w, w0) { w } else { fw }, if left(h, h0) { h } else { fh }))
}
}
fn size_matching(s: &mut Session, v: &Value, pred: impl Fn(&InlineObject) -> bool, empty_msg: &str) -> CmdResult {
let targets = target_objects(s, pred);
if targets.is_empty() {
return Err(CmdError::Disabled(empty_msg.into()));
}
let planned: Vec<(Pos, f32, f32)> =
targets.into_iter().map(|(pos, o)| planned_size(s, &o, v).map(|(w, h)| (pos, w, h))).collect::<Result<Vec<_>, _>>()?;
(if left(w, w0) { w } else { fw }, if left(h, h0) { h } else { fh })
};
// Any drawing: a group's members scale with its frame (its child space is kept); a chart or
// SmartArt graphic lays itself out again at the new size.
let theme = s.doc.settings.theme_colors.clone();
let mut last = Value::Null;
for (pos, w, h) in &planned {
let o = edit_obj(s, pos, |o| {
o.set_size(*w, *h);
crate::cmd::chart::redraw(o, &theme);
crate::cmd::smart_art::redraw(o, &theme);
})?;
last = serde_json::to_value(o).unwrap_or(Value::Null);
}
Ok(json!({"object": last, "count": planned.len()}))
}
/// Size: `scale` is a percentage of the current size, or with `original` of what the crop leaves
/// of the original size (`original` alone gives that back: the Size dialog's Reset); then `width`
/// and `height`, where one alone keeps the proportions unless `lockAspect` is false.
pub(super) fn size(s: &mut Session, v: &Value) -> CmdResult {
size_matching(
s,
v,
|o| match o {
InlineObject::Graphic { graphic, .. } => graphic.chart.is_some() || graphic.smart_art.is_some(),
_ => o.is_drawing(),
},
"no object",
)
}
/// Shape Size: resizes only selected shapes, text boxes, and drawing canvases (or the active text box).
pub(super) fn shape_size(s: &mut Session, v: &Value) -> CmdResult {
size_matching(s, v, is_shape_or_canvas, "no shape selected")
with_obj(s, |o| {
o.set_size(w, h);
crate::cmd::chart::redraw(o, &theme);
crate::cmd::smart_art::redraw(o, &theme);
})
}
/// An object size within 1–4000 pt. With `keep`, both sides scale by one factor, the one nearest
+22 -104
View File
@@ -7,18 +7,16 @@ pub(super) fn has_picture(s: &Session) -> Option<&'static str> {
}
}
/// Guard returning `None` when a picture, shape, or active text box is selected.
pub(super) fn has_object(s: &Session) -> Option<&'static str> {
if selected_or_text_box(s).is_some() { None } else { Some("select a picture or shape first") }
if selected(s).is_some() { None } else { Some("select a picture or shape first") }
}
/// Guard returning `None` when a floating picture, shape, or active text box is selected.
pub(super) fn has_floating(s: &Session) -> Option<&'static str> {
// A canvas member moves inside its canvas.
if crate::cmd::canvas::active_member(s).is_some() {
if crate::cmd::canvas::selected_member(s).is_some() {
return None;
}
match selected_or_text_box(s) {
match selected(s) {
Some((_, InlineObject::Graphic { .. })) => Some(FROZEN),
Some((_, o)) if o.is_floating() => None,
_ => Some("select a floating picture or shape first"),
@@ -57,18 +55,10 @@ pub(super) fn has_movable(s: &Session) -> Option<&'static str> {
}
}
/// Guard returning `None` when at least one selected target (or active text box) is movable.
pub(super) fn has_any_movable(s: &Session) -> Option<&'static str> {
if !target_objects(s, |o| !matches!(o, InlineObject::Graphic { .. }) && o.is_drawing()).is_empty() {
return None;
}
has_movable(s)
}
/// `has_movable` for what places an object in the text (wrapping, position, alignment, Move with
/// Text): not for a member inside a drawing canvas, which the canvas places.
/// Text): not for a member picked inside a drawing canvas, which the canvas places.
pub(super) fn has_placeable(s: &Session) -> Option<&'static str> {
if crate::cmd::canvas::active_member(s).is_some() {
if crate::cmd::canvas::selected_member(s).is_some() {
return Some("a shape inside a drawing canvas is placed by the canvas");
}
has_movable(s)
@@ -92,33 +82,25 @@ pub(super) fn has_group(s: &Session) -> Option<&'static str> {
}
}
/// Whether `o` is a shape, text box, or drawing canvas.
pub(crate) fn is_shape_or_canvas(o: &InlineObject) -> bool {
matches!(o, InlineObject::Shape { .. }) || o.is_canvas()
}
/// Shape Fill and Shape Outline: any selected shape or Drawing Canvas, or the active text box.
/// Shape Fill and Shape Outline: a shape, or a Drawing Canvas's background and border.
pub(crate) fn has_shape_or_canvas(s: &Session) -> Option<&'static str> {
if target_objects(s, is_shape_or_canvas).is_empty() { Some("select a shape first") } else { None }
match selected(s) {
Some((_, o)) if o.is_canvas() => None,
_ => has_shape(s),
}
}
pub(super) fn can_group(s: &Session) -> Option<&'static str> {
if picked_objects(s).len() >= 2 { None } else { Some("select two or more pictures or shapes first (Shift+click)") }
}
/// Guard returning `None` when a shape or active text box is selected.
pub(super) fn has_shape(s: &Session) -> Option<&'static str> {
match selected_or_text_box(s) {
match selected(s) {
Some((_, InlineObject::Shape { .. })) => None,
_ => Some("select a shape first"),
}
}
/// Guard returning `None` when any selected object (or the active text box) is a shape.
pub(super) fn has_any_shape(s: &Session) -> Option<&'static str> {
if target_objects(s, |o| matches!(o, InlineObject::Shape { .. })).is_empty() { Some("select a shape first") } else { None }
}
/// The selection when it is exactly one picture, shape or text box (its U+FFFC), rather than
/// text: what clicking an object selects.
pub fn object_selection(s: &Session) -> Option<(Pos, &InlineObject)> {
@@ -205,51 +187,8 @@ pub(super) fn alt_text(s: &mut Session, v: &Value) -> CmdResult {
})
}
/// Returns the selected inline object, or the active text box containing the caret (including
/// a text box member inside a Drawing Canvas; never an enclosing group or canvas).
pub fn selected_or_text_box(s: &Session) -> Option<(Pos, InlineObject)> {
if let Some((pos, o)) = selected(s) {
return Some((pos, o));
}
if let Some((pos, _, member)) = crate::cmd::canvas::text_box_member(s) {
return Some((pos, member.clone()));
}
let (pos, id) = super::shape::text_box_target(s)?;
let o = s.doc.para_at(&pos)?.object_at(pos.off)?;
matches!(o, InlineObject::Shape { story: Some(sid), .. } if *sid == id).then(|| (pos, o.clone()))
}
/// Most objects one multi-object command changes.
pub(crate) const MAX_TARGET_OBJECTS: usize = 10_000;
/// Selected objects matching `pred` (in the selection range or added with `select.addObject`),
/// or — when nothing is selected — the active text box containing the caret if it matches `pred`.
pub fn target_objects(s: &Session, pred: impl Fn(&InlineObject) -> bool) -> Vec<(Pos, InlineObject)> {
if let Some((pos, _, member)) = crate::cmd::canvas::active_member(s) {
return if pred(member) { vec![(pos, member.clone())] } else { Vec::new() };
}
let mut out: Vec<(Pos, InlineObject)> = selected_all(s, MAX_TARGET_OBJECTS).into_iter().filter(|(_, o)| pred(o)).collect();
for pos in picked_objects(s) {
if !out.iter().any(|(p, _)| p == &pos)
&& let Some(o) = s.doc.para_at(&pos).and_then(|q| q.object_at(pos.off))
&& pred(o)
{
out.push((pos, o.clone()));
}
}
if out.is_empty()
&& selected(s).is_none()
&& let Some((pos, o)) = selected_or_text_box(s)
&& pred(&o)
{
out.push((pos, o));
}
out
}
/// Mutates the selected picture or shape, or the active text box containing the caret.
pub(super) fn with_obj(s: &mut Session, f: impl Fn(&mut InlineObject)) -> CmdResult {
let (pos, _) = selected_or_text_box(s).ok_or_else(|| CmdError::Disabled("no picture or shape selected".into()))?;
let (pos, _) = selected(s).ok_or_else(|| CmdError::Disabled("no picture or shape selected".into()))?;
let o = edit_obj(s, &pos, f)?;
Ok(json!({"object": serde_json::to_value(o).unwrap_or(Value::Null)}))
}
@@ -276,38 +215,17 @@ pub(super) fn edit_float(s: &mut Session, pos: &Pos, f: impl Fn(&mut Float)) ->
})
}
fn apply_float(o: &mut InlineObject, f: impl Fn(&mut Float)) {
if let Some(float) = o.float_mut() {
let was_inline = float.wrap == Wrap::Inline;
f(float);
// Word's distance from text for a newly wrapped object: 0.125" at the sides.
if was_inline && float.wrap != Wrap::Inline && float.dist == 0.0 {
float.dist = 9.0;
}
}
}
pub(super) fn with_float(s: &mut Session, f: impl Fn(&mut Float)) -> CmdResult {
with_obj(s, |o| apply_float(o, &f))
}
/// Mutates `Float` on all selected targets matching `pred` (or the active text box if it matches).
pub(super) fn with_floats_matching(s: &mut Session, pred: impl Fn(&InlineObject) -> bool, f: impl Fn(&mut Float)) -> CmdResult {
let targets = target_objects(s, pred);
if targets.is_empty() {
return Err(CmdError::Disabled("no picture or shape selected".into()));
}
let mut last = Value::Null;
for (pos, _) in &targets {
let o = edit_obj(s, pos, |o| apply_float(o, &f))?;
last = serde_json::to_value(o).unwrap_or(Value::Null);
}
Ok(json!({"object": last, "count": targets.len()}))
}
/// Mutates `Float` on all selected movable objects (or the active text box).
pub(super) fn with_movable_floats(s: &mut Session, f: impl Fn(&mut Float)) -> CmdResult {
with_floats_matching(s, |o| !matches!(o, InlineObject::Graphic { .. }) && o.is_drawing(), f)
with_obj(s, |o| {
if let Some(float) = o.float_mut() {
let was_inline = float.wrap == Wrap::Inline;
f(float);
// Word's distance from text for a newly wrapped object: 0.125" at the sides.
if was_inline && float.wrap != Wrap::Inline && float.dist == 0.0 {
float.dist = 9.0;
}
}
})
}
/// The selected pictures, shapes, text boxes and groups: the one the selection holds, then
+22 -41
View File
@@ -1,37 +1,16 @@
use super::select::{all_objects, edit_obj, picked_objects, selected, target_objects};
use super::select::{all_objects, edit_obj, picked_objects, selected, selected_all};
use super::{CmdError, CmdResult, InlineObject, Pos, Rgb, Session, StoryRef, TextBody, Value, json, p};
pub(super) const NO_TEXT_BOX: &str = "select a text box first";
pub(super) fn has_text_box(s: &Session) -> Option<&'static str> {
if text_box_targets(s).is_empty() { Some(NO_TEXT_BOX) } else { None }
if text_box_target(s).is_some() { None } else { Some(NO_TEXT_BOX) }
}
fn is_text_box(s: &Session, id: u32) -> bool {
s.doc.parts.get(&id).is_some_and(|p| p.kind == wordcraft_doc::PartKind::TextBox)
}
/// Target text boxes for Shape Format › Text commands: all selected text boxes (including
/// those added with `select.addObject` or the active canvas text box member), falling back
/// to the text box containing the caret when no object is selected.
pub fn text_box_targets(s: &Session) -> Vec<(Pos, u32)> {
let mut targets: Vec<(Pos, u32)> = target_objects(s, |o| matches!(o, InlineObject::Shape { story: Some(id), .. } if is_text_box(s, *id)))
.into_iter()
.filter_map(|(pos, o)| match o {
InlineObject::Shape { story: Some(id), .. } => Some((pos, id)),
_ => None,
})
.collect();
if targets.is_empty()
&& selected(s).is_none()
&& picked_objects(s).is_empty()
&& let Some(t) = text_box_target(s)
{
targets.push(t);
}
targets
}
/// The text box the Shape Format › Text commands work on: the selected one, or the one whose
/// text the caret is in. Its U+FFFC's position and its story.
pub fn text_box_target(s: &Session) -> Option<(Pos, u32)> {
@@ -49,22 +28,15 @@ pub fn text_box_target(s: &Session) -> Option<(Pos, u32)> {
Some((Pos { off, ..after }, id))
}
/// Change the target text boxes' text direction, alignment or link.
/// Change the target text box's text direction, alignment or link.
pub(crate) fn set_text_body(s: &mut Session, f: impl Fn(&mut TextBody)) -> CmdResult {
let targets = text_box_targets(s);
if targets.is_empty() {
return Err(CmdError::Disabled(NO_TEXT_BOX.into()));
}
let mut last_id = 0;
let mut last_body = TextBody::default();
for (pos, id) in targets {
let part = s.doc.parts.get_mut(&id).ok_or_else(|| CmdError::Failed("text box vanished".into()))?;
f(&mut part.body);
(last_id, last_body) = (id, part.body);
// Its paragraph is laid out again.
edit_obj(s, &pos, |_| {})?;
}
Ok(json!({"textBox": last_id, "body": last_body}))
let (pos, id) = text_box_target(s).ok_or_else(|| CmdError::Disabled(NO_TEXT_BOX.into()))?;
let part = s.doc.parts.get_mut(&id).ok_or_else(|| CmdError::Failed("text box vanished".into()))?;
f(&mut part.body);
let body = part.body;
// Its paragraph is laid out again.
edit_obj(s, &pos, |_| {})?;
Ok(json!({"textBox": id, "body": body}))
}
pub(super) fn can_link(s: &Session) -> Option<&'static str> {
@@ -109,6 +81,9 @@ pub(super) fn link_text_box(s: &mut Session, v: &Value) -> CmdResult {
Ok(json!({"textBox": from, "next": to}))
}
/// Most shapes one `shape.effects` changes.
const MAX_EFFECT_SHAPES: usize = 10_000;
/// `shape.effects`: set or clear the shadow, glow and soft edges of the selected shapes.
pub(super) fn shape_effects(s: &mut Session, v: &Value) -> CmdResult {
use wordcraft_doc::effects::{Glow, Shadow, ShapeEffects};
@@ -158,13 +133,19 @@ pub(super) fn shape_effects(s: &mut Session, v: &Value) -> CmdResult {
Some(n @ Value::Number(_)) => Some(n.as_f64().map(|x| x as f32)),
Some(_) => return Err(CmdError::Params("`softEdge`: a radius in points or null".into())),
};
// The shapes in the selection, those added with `select.addObject`, or the active text box.
let targets = target_objects(s, |o| matches!(o, InlineObject::Shape { .. }));
// The shapes in the selection and those added to it (Shift+click).
let mut targets: Vec<Pos> =
selected_all(s, MAX_EFFECT_SHAPES).into_iter().filter(|(_, o)| matches!(o, InlineObject::Shape { .. })).map(|(pos, _)| pos).collect();
for pos in picked_objects(s) {
if !targets.contains(&pos) && matches!(s.doc.para_at(&pos).and_then(|q| q.object_at(pos.off)), Some(InlineObject::Shape { .. })) {
targets.push(pos);
}
}
if targets.is_empty() {
return Err(CmdError::Disabled("no shape selected".into()));
}
let mut last = ShapeEffects::default();
for (pos, _) in &targets {
for pos in &targets {
let o = edit_obj(s, pos, |o| {
if let InlineObject::Shape { effects, float, .. } = o {
let mut e = *effects;
+32 -113
View File
@@ -1,40 +1,14 @@
use super::arrange::{MAX_OFFSET, bounds, copy_to, move_with_text, unalign};
use super::group::{add_object, group, ungroup};
use super::picture::{adjust, adjust_media, clear_lum, crop, original_media, recolor, relook, remove_background, reset, shape_size, size};
use super::picture::{adjust, adjust_media, clear_lum, crop, original_media, recolor, relook, remove_background, reset, size};
use super::select::{
all_objects, alt_text, can_group, edit_obj, has_any_movable, has_any_shape, has_floating, has_group, has_movable, has_object, has_picture,
has_placeable, has_shape, has_shape_or_canvas, has_sizable, is_shape_or_canvas, obj_size, objects_list, selected_or_text_box, target_objects,
with_float, with_floats_matching, with_movable_floats, with_obj,
all_objects, alt_text, can_group, edit_obj, has_floating, has_group, has_movable, has_object, has_picture, has_placeable, has_shape,
has_shape_or_canvas, has_sizable, obj_size, objects_list, selected, with_float, with_obj,
};
use super::shape::{NO_TEXT_BOX, can_link, has_text_box, link_text_box, set_text_body, shape_effects, text_box_target};
use super::{CmdError, CommandSpec, InlineObject, Pos, Rgb, Selection, Spin, TextVert, VAlign, Wrap, WrapText, json, p, sel_result};
use wordcraft_doc::picfx::PicFx;
fn run_rotation(s: &mut crate::Session, v: &serde_json::Value, pred: impl Fn(&InlineObject) -> bool) -> crate::CmdResult {
let deg = p::req_f32(v, "degrees")?;
let (fh, fv) = (p::bool(v, "flipH"), p::bool(v, "flipV"));
with_floats_matching(s, pred, |f| {
let cur = f.spin();
f.set_spin(Spin::new(deg, fh.unwrap_or(cur.flip_h), fv.unwrap_or(cur.flip_v)));
})
}
/// Returns the section properties of the target object's anchor story (including text boxes anchored
/// in a later body section or header/footer), falling back to `page::sect`.
fn target_sect(s: &crate::Session) -> wordcraft_doc::SectionProps {
if let Some((pos, _)) = selected_or_text_box(s) {
let i = match pos.story {
wordcraft_doc::StoryRef::Body => s.doc.section_index_of(pos.path.0.first().copied().unwrap_or(0) as usize),
wordcraft_doc::StoryRef::Part(id) => crate::cmd::page::section_of_part(s, id),
};
if let Some((_, sp)) = s.doc.sections().get(i) {
return (*sp).clone();
}
}
crate::cmd::page::sect(s)
}
/// Returns all command specifications for objects (pictures, shapes, text boxes, and drawing canvases).
pub fn specs() -> Vec<CommandSpec> {
vec![
CommandSpec::new("picture.size", "Size", "Picture Format › Size", size)
@@ -212,15 +186,20 @@ pub fn specs() -> Vec<CommandSpec> {
"right" => Spin::new(90.0, false, false),
other => return Err(CmdError::Params(format!("unknown direction `{other}`"))),
};
with_movable_floats(s, |f| f.set_spin(f.spin().within(by)))
with_float(s, |f| f.set_spin(f.spin().within(by)))
})
.params(r#"{"direction": "right|left|flipVertical|flipHorizontal"} (turns 90° or mirrors the selected picture, shape or text box; its pixels are kept)"#)
.when(has_any_movable),
.when(has_movable),
CommandSpec::new("arrange.rotation", "Rotation", "Layout › Arrange", |s, v| {
run_rotation(s, v, |o| !matches!(o, InlineObject::Graphic { .. }) && o.is_drawing())
let deg = p::req_f32(v, "degrees")?;
let (fh, fv) = (p::bool(v, "flipH"), p::bool(v, "flipV"));
with_float(s, |f| {
let cur = f.spin();
f.set_spin(Spin::new(deg, fh.unwrap_or(cur.flip_h), fv.unwrap_or(cur.flip_v)));
})
})
.params(r#"{"degrees": number, "flipH"?: bool, "flipV"?: bool} (the exact angle, clockwise, of the selected picture, shape or text box; normalised to 0–360)"#)
.when(has_any_movable),
.when(has_movable),
CommandSpec::new("arrange.wrap", "Wrap Text", "Layout › Arrange", |s, v| {
let wrap: Wrap = serde_json::from_value(v.get("wrap").cloned().unwrap_or(json!("square"))).map_err(|e| CmdError::Params(e.to_string()))?;
with_float(s, |f| f.wrap = wrap)
@@ -240,8 +219,8 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("arrange.position", "Position", "Layout › Arrange", |s, v| {
let preset = p::str(v, "preset").unwrap_or("middleCenter").to_string();
let (x, y) = (p::f32(v, "x"), p::f32(v, "y"));
let sect = target_sect(s);
let size = selected_or_text_box(s).map(|(_, o)| obj_size(&o)).unwrap_or((72.0, 72.0));
let sect = crate::cmd::page::sect(s);
let size = selected(s).map(|(_, o)| obj_size(&o)).unwrap_or((72.0, 72.0));
with_float(s, |f| {
if f.wrap == Wrap::Inline {
f.wrap = Wrap::Square;
@@ -262,8 +241,8 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("arrange.sendBackward", "Send Backward", "Layout › Arrange", |s, _| with_float(s, |f| f.wrap = Wrap::BehindText)).when(has_placeable),
CommandSpec::new("arrange.align", "Align", "Layout › Arrange", |s, v| {
let h = p::str(v, "value").unwrap_or("center").to_string();
let tw = target_sect(s).text_width();
let w = selected_or_text_box(s).map(|(_, o)| obj_size(&o).0).unwrap_or(72.0);
let tw = crate::cmd::page::sect(s).text_width();
let w = selected(s).map(|(_, o)| obj_size(&o).0).unwrap_or(72.0);
with_float(s, |f| {
if f.wrap == Wrap::Inline {
f.wrap = Wrap::Square;
@@ -318,91 +297,31 @@ pub fn specs() -> Vec<CommandSpec> {
.params(r#"{"index"?: n}"#)
.pure(),
CommandSpec::new("shape.outline", "Shape Outline", "Shape Format › Shape Styles", |s, v| {
let color = match v.get("color") {
None => None,
Some(serde_json::Value::Null) => Some(None),
Some(_) => {
let hex = p::str(v, "color")
.and_then(Rgb::parse)
.ok_or_else(|| CmdError::Params("`color`: \"RRGGBB\" or null".into()))?;
Some(Some(hex))
}
};
let c = p::str(v, "color").and_then(Rgb::parse);
let w = p::f32(v, "width").map(|w| w.clamp(0.0, 72.0));
let dash = match v.get("dash") {
None => None,
Some(val) => {
let d = val.as_str().ok_or_else(|| {
CmdError::Params(
"`dash`: \"solid|dot|dash|lgDash|dashDot|lgDashDot|lgDashDotDot|sysDash|sysDot|sysDashDot|sysDashDotDot\"".into(),
)
})?;
let parsed = wordcraft_doc::line_dash::LineDash::from_ooxml(d);
if d != "solid" && parsed.is_solid() {
return Err(CmdError::Params(format!("unknown `dash` preset `{d}`")));
with_obj(s, |o| {
if let InlineObject::Shape { stroke, stroke_width, extra, .. } = o {
*stroke = c;
// A colour chosen here replaces an outline gradient from a file.
extra.outline_fill = None;
if let Some(w) = w {
*stroke_width = w;
}
} else if let Some(style) = crate::cmd::canvas::style_mut(o) {
style.stroke = c;
if let Some(w) = w {
style.stroke_width = w;
}
Some(parsed)
}
};
let cap = match v.get("cap") {
None => None,
Some(val) => {
let c = val.as_str().ok_or_else(|| CmdError::Params("`cap`: \"flat|rnd|sq\"".into()))?;
let parsed = wordcraft_doc::connector::LineCap::from_ooxml(c);
if c != "flat" && parsed.is_flat() {
return Err(CmdError::Params(format!("unknown `cap` style `{c}`")));
}
Some(parsed)
}
};
let targets = target_objects(s, is_shape_or_canvas);
if targets.is_empty() {
return Err(CmdError::Disabled("no shape selected".into()));
}
let mut last = serde_json::Value::Null;
for (pos, _) in &targets {
let o = edit_obj(s, pos, |o| {
if let InlineObject::Shape { stroke, stroke_width, extra, .. } = o {
if let Some(c) = color {
*stroke = c;
// A colour chosen here replaces an outline gradient from a file.
extra.outline_fill = None;
}
if let Some(w) = w {
*stroke_width = w;
}
if let Some(d) = dash.clone() {
extra.dash = d;
}
if let Some(cp) = cap {
extra.cap = cp;
}
} else if let Some(style) = crate::cmd::canvas::style_mut(o) {
if let Some(c) = color {
style.stroke = c;
}
if let Some(w) = w {
style.stroke_width = w;
}
}
})?;
last = serde_json::to_value(o).unwrap_or(serde_json::Value::Null);
}
Ok(json!({"object": last, "count": targets.len()}))
})
})
.params(r#"{"color"?: "RRGGBB" | null, "width"?: pt, "dash"?: "solid|dot|dash|lgDash|dashDot|lgDashDot|lgDashDotDot|sysDash|sysDot|sysDashDot|sysDashDotDot", "cap"?: "flat|rnd|sq"} (a selected drawing canvas: its border)"#)
.params(r#"{"color": "RRGGBB" | null, "width"?: pt} (a selected drawing canvas: its border)"#)
.when(has_shape_or_canvas),
CommandSpec::new("shape.size", "Size", "Shape Format › Size", shape_size)
.params(r#"{"width"?: pt, "height"?: pt, "lockAspect"?: bool, "scale"?: percent} (resizes the selected shapes, text boxes, and drawing canvases, or the active text box)"#)
.when(has_shape_or_canvas),
CommandSpec::new("shape.rotation", "Rotation", "Shape Format › Arrange", |s, v| run_rotation(s, v, is_shape_or_canvas))
.params(r#"{"degrees": number, "flipH"?: bool, "flipV"?: bool} (rotates the selected shapes, text boxes, and drawing canvases, or the active text box)"#)
.when(has_shape_or_canvas),
CommandSpec::new("shape.effects", "Shape Effects", "Shape Format › Shape Styles", shape_effects)
.params(
r#"{"shadow"?: preset|{"preset"?, "color"?: "RRGGBB", "transparency"?: %, "blur"?: pt, "distance"?: pt, "angle"?: deg}|null, "glow"?: pt|{"color"?: "RRGGBB", "size"?: pt, "transparency"?: %}|null, "softEdge"?: pt|null} (shadow presets: offsetBottomRight, offsetBottom, offsetBottomLeft, offsetRight, offsetCenter, offsetLeft, offsetTopRight, offsetTop, offsetTopLeft; an omitted key is left as it is; applies to every shape in the selection)"#,
)
.when(has_any_shape),
.when(has_shape),
CommandSpec::new("shape.change", "Change Shape", "Shape Format › Insert Shapes", |s, v| {
let kind: wordcraft_doc::para::ShapeKind = serde_json::from_value(v.get("kind").cloned().unwrap_or(json!("rectangle"))).map_err(|e| CmdError::Params(e.to_string()))?;
with_obj(s, |o| {
-448
View File
@@ -1797,451 +1797,3 @@ fn only_ink_members_pin_a_group() {
}
assert!(!holds_ink(&group), "a group of charts is not pinned");
}
/// Issue #5896: shape.outline can remove the frame (color: null), change width without
/// erasing stroke color, set dash and cap, and acts on a text box while typing inside it.
#[test]
fn shape_outline_and_fill_on_text_box() {
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("insert.textBox", &json!({"text": "A text box with a frame"})).unwrap();
// While typing inside the text box:
// 1. shape.outline with {"color": null} removes the frame (stroke is None).
s.run("shape.outline", &json!({"color": null})).unwrap();
let (pos, _id) = text_box_target(&s).unwrap();
let o = s.doc.para_at(&pos).unwrap().object_at(pos.off).unwrap();
let InlineObject::Shape { stroke, .. } = o else { panic!("{o:?}") };
assert_eq!(*stroke, None, "frame removed");
// 2. shape.outline can restore the frame with color, width, dash and cap:
s.run("shape.outline", &json!({"color": "156082", "width": 1.5, "dash": "dash", "cap": "rnd"})).unwrap();
let o = s.doc.para_at(&pos).unwrap().object_at(pos.off).unwrap();
let InlineObject::Shape { stroke, stroke_width, extra, .. } = o else { panic!("{o:?}") };
assert_eq!(*stroke, Some(Rgb(0x15, 0x60, 0x82)));
assert_eq!(*stroke_width, 1.5);
assert_eq!(extra.dash, wordcraft_doc::line_dash::LineDash::Dash);
assert_eq!(extra.cap, wordcraft_doc::connector::LineCap::Round);
// 3. Changing only the width preserves the stroke color:
s.run("shape.outline", &json!({"width": 3.0})).unwrap();
let o = s.doc.para_at(&pos).unwrap().object_at(pos.off).unwrap();
let InlineObject::Shape { stroke, stroke_width, .. } = o else { panic!("{o:?}") };
assert_eq!(*stroke, Some(Rgb(0x15, 0x60, 0x82)), "color kept when width changed");
assert_eq!(*stroke_width, 3.0);
// 4. Malformed non-null colors are rejected before mutation:
assert!(matches!(s.run("shape.outline", &json!({"color": 123})), Err(CmdError::Params(_))));
assert!(matches!(s.run("shape.outline", &json!({"color": "not-a-hex"})), Err(CmdError::Params(_))));
let o = s.doc.para_at(&pos).unwrap().object_at(pos.off).unwrap();
let InlineObject::Shape { stroke, .. } = o else { panic!("{o:?}") };
assert_eq!(*stroke, Some(Rgb(0x15, 0x60, 0x82)), "color preserved on error");
// 5. Unlocked size edits preserve the other dimension:
s.run("picture.size", &json!({"width": 100.0, "height": 80.0, "lockAspect": false})).unwrap();
s.run("picture.size", &json!({"width": 250.0, "lockAspect": false})).unwrap();
let o = s.doc.para_at(&pos).unwrap().object_at(pos.off).unwrap();
let (w, h) = obj_size(o);
assert_eq!((w, h), (250.0, 80.0), "height preserved on width edit");
s.run("picture.size", &json!({"height": 150.0, "lockAspect": false})).unwrap();
let o = s.doc.para_at(&pos).unwrap().object_at(pos.off).unwrap();
let (w, h) = obj_size(o);
assert_eq!((w, h), (250.0, 150.0), "width preserved on height edit");
// 6. shape.effects targets the active text box when typing inside it:
s.run("shape.effects", &json!({"shadow": "offsetBottomRight"})).unwrap();
let o = s.doc.para_at(&pos).unwrap().object_at(pos.off).unwrap();
let InlineObject::Shape { effects, .. } = o else { panic!("{o:?}") };
assert!(effects.shadow.is_some(), "shadow applied to text box");
// 7. arrange.bounds targets the active text box when typing inside it:
let caret_sel = s.sel.clone();
s.run("arrange.bounds", &json!({"width": 300.0, "height": 180.0})).unwrap();
let o = s.doc.para_at(&pos).unwrap().object_at(pos.off).unwrap();
let (w, h) = obj_size(o);
assert_eq!((w, h), (300.0, 180.0), "bounds applied to active text box");
// Restore typing caret inside text box so selected(&s) is None:
s.sel = caret_sel.clone();
assert!(selected(&s).is_none(), "caret is inside text box, no outer object selected");
// arrange.moveWithText targets the active text box once it is floating:
assert!(s.run("arrange.moveWithText", &json!({"value": true})).is_err(), "inline text box cannot move with text");
s.run("arrange.wrap", &json!({"wrap": "square"})).unwrap();
s.sel = caret_sel;
assert!(selected(&s).is_none(), "caret restored inside text box");
s.run("arrange.moveWithText", &json!({"value": false})).unwrap();
let o = s.doc.para_at(&pos).unwrap().object_at(pos.off).unwrap();
let (_, _, float) = o.frame().unwrap();
assert_eq!(float.v_rel, wordcraft_doc::para::Anchor::Page, "moveWithText targets active floating text box");
// 8. When a picture is selected, shape.fill, shape.effects, and shape.outline do not target the text box:
let data = super::super::insert::base64_encode(&png(10, 10));
s.run("insert.picture", &json!({"data": data})).unwrap();
assert!(matches!(s.run("shape.fill", &json!({"color": "FF0000"})), Err(CmdError::Disabled(_))));
assert!(matches!(s.run("shape.effects", &json!({"shadow": "none"})), Err(CmdError::Disabled(_))));
assert!(matches!(s.run("shape.outline", &json!({"color": "FF0000"})), Err(CmdError::Disabled(_))));
// 9. fit_size normalizes NaN and clamps below 1 pt to 1 pt:
assert_eq!(super::picture::fit_size(f32::NAN, 0.0, false), (1.0, 1.0));
assert_eq!(super::picture::fit_size(-50.0, 0.0, false), (1.0, 1.0));
}
/// Issue #5896: `arrange.align` and `arrange.position` use the active text box's own
/// dimensions when invoked from a typing caret inside it, matching explicit object selection.
#[test]
fn arrange_align_and_position_on_active_text_box() {
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("insert.textBox", &json!({"text": "Sized text box"})).unwrap();
let caret_sel = s.sel.clone();
let (pos, _) = text_box_target(&s).unwrap();
s.run("picture.size", &json!({"width": 250.0, "height": 140.0, "lockAspect": false})).unwrap();
let float_xy = |s: &Session| {
let o = s.doc.para_at(&pos).unwrap().object_at(pos.off).unwrap();
let (_, _, f) = o.frame().unwrap();
(f.x, f.y)
};
for value in ["center", "right"] {
s.run("select.objects", &json!({"index": 0})).unwrap();
s.run("arrange.align", &json!({"value": "left"})).unwrap();
s.run("arrange.align", &json!({"value": value})).unwrap();
let from_selected = float_xy(&s).0;
s.sel = caret_sel.clone();
assert!(selected(&s).is_none(), "caret inside text box for align {value}");
s.run("arrange.align", &json!({"value": "left"})).unwrap();
s.run("arrange.align", &json!({"value": value})).unwrap();
let from_caret = float_xy(&s).0;
assert_eq!(from_caret, from_selected, "align {value} matches explicit selection");
}
for preset in ["middleCenter", "bottomRight"] {
s.run("select.objects", &json!({"index": 0})).unwrap();
s.run("arrange.position", &json!({"preset": "topLeft"})).unwrap();
s.run("arrange.position", &json!({"preset": preset})).unwrap();
let from_selected = float_xy(&s);
s.sel = caret_sel.clone();
assert!(selected(&s).is_none(), "caret inside text box for position {preset}");
s.run("arrange.position", &json!({"preset": "topLeft"})).unwrap();
s.run("arrange.position", &json!({"preset": preset})).unwrap();
let from_caret = float_xy(&s);
assert_eq!(from_caret, from_selected, "position {preset} matches explicit selection");
}
}
/// Issue #5896 P2: typing inside a canvas text box routes Fill, Outline, Effects, Size, and
/// Rotation to that text box member (leaving the canvas and siblings untouched), keeps
/// canvas-owned placement commands disabled, and keeps commands disabled inside a regular group.
#[test]
fn typing_in_canvas_text_box_formats_member_not_canvas() {
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("insert.canvas", &json!({"width": 400, "height": 300, "fill": "FFF2CC", "outline": "1F4E79"})).unwrap();
s.run("insert.shape", &json!({"kind": "rectangle", "width": 100, "height": 40})).unwrap();
s.run("select.objects", &json!({"index": 0})).unwrap();
let tb_res = s.run("insert.textBox", &json!({"text": "Canvas note"})).unwrap();
let tb_id = tb_res["story"].as_u64().unwrap() as u32;
assert_eq!(s.sel.focus.story, StoryRef::Part(tb_id));
assert!(selected(&s).is_none());
assert!(crate::cmd::canvas::selected_member(&s).is_none());
s.run("shape.fill", &json!({"color": "FF0000"})).unwrap();
s.run("shape.outline", &json!({"color": null})).unwrap();
let canvas_mid = all_objects(&s).into_iter().next().unwrap().1;
let InlineObject::Group { children: mid_children, .. } = &canvas_mid else { panic!("{canvas_mid:?}") };
assert!(matches!(&mid_children[1].obj, InlineObject::Shape { stroke: None, .. }));
assert_eq!(canvas_mid.canvas_style().and_then(|st| st.stroke), Rgb::parse("1F4E79"));
s.run("shape.outline", &json!({"color": "00AA00", "width": 2.0, "dash": "dash", "cap": "rnd"})).unwrap();
s.run("shape.effects", &json!({"shadow": "offsetBottomRight"})).unwrap();
s.run("picture.size", &json!({"width": 180.0, "height": 90.0, "lockAspect": false})).unwrap();
s.run("arrange.rotation", &json!({"degrees": 15.0})).unwrap();
let canvas = all_objects(&s).into_iter().next().unwrap().1;
let InlineObject::Group { w: cw, h: ch, float: cf, children, canvas: Some(style), .. } = &canvas else {
panic!("expected canvas: {canvas:?}");
};
assert_eq!((*cw, *ch, cf.spin().deg), (400.0, 300.0, 0.0));
assert_eq!(style.fill, Rgb::parse("FFF2CC").map(wordcraft_doc::fill::Fill::solid));
assert_eq!(style.stroke, Rgb::parse("1F4E79"));
assert_eq!(style.stroke_width, 0.75);
assert_eq!(obj_size(&children[0].obj), (100.0, 40.0), "sibling shape size untouched");
let InlineObject::Shape { effects: sib_fx, .. } = &children[0].obj else { panic!() };
assert!(sib_fx.shadow.is_none(), "sibling shape effects untouched");
let InlineObject::Shape { w, h, fill, stroke, stroke_width, float, effects, extra, story, .. } = &children[1].obj else {
panic!("expected text box member");
};
assert_eq!(*story, Some(tb_id));
assert_eq!((*w, *h), (180.0, 90.0));
assert_eq!(*fill, Rgb::parse("FF0000").map(wordcraft_doc::fill::Fill::solid));
assert_eq!(*stroke, Rgb::parse("00AA00"));
assert_eq!(*stroke_width, 2.0);
assert_eq!(extra.dash, wordcraft_doc::line_dash::LineDash::Dash);
assert_eq!(extra.cap, wordcraft_doc::connector::LineCap::Round);
assert!(effects.shadow.is_some());
assert_eq!(float.spin().deg, 15.0);
for (cmd, params) in [
("arrange.wrap", json!({"wrap": "square"})),
("arrange.align", json!({"value": "center"})),
("arrange.position", json!({"preset": "middleCenter"})),
("arrange.moveWithText", json!({"value": true})),
("arrange.copyTo", json!({"x": 50.0, "y": 50.0})),
] {
assert!(matches!(s.run(cmd, &params), Err(CmdError::Disabled(_))), "{cmd} stays disabled for canvas member");
}
// Regular group: typing inside a grouped text box leaves shape commands disabled without modifying the group.
let mut g = Session::new(wordcraft_doc::Document::new());
g.run("insert.shape", &json!({"kind": "rectangle"})).unwrap();
g.run("arrange.wrap", &json!({"wrap": "square"})).unwrap();
g.sel = Selection::caret(g.doc.end_of(StoryRef::Body));
let grouped_tb_id = g.run("insert.textBox", &json!({"text": "Grouped note"})).unwrap()["story"].as_u64().unwrap() as u32;
g.run("arrange.wrap", &json!({"wrap": "square"})).unwrap();
g.run("select.objects", &json!({"index": 0})).unwrap();
g.run("select.addObject", &json!({"index": 1})).unwrap();
g.run("arrange.group", &json!({})).unwrap();
g.sel = Selection::caret(g.doc.end_of(StoryRef::Part(grouped_tb_id)));
let before_group = all_objects(&g).into_iter().next().unwrap().1;
for (cmd, params) in [
("shape.fill", json!({"color": "FF0000"})),
("shape.outline", json!({"color": null})),
("shape.effects", json!({"shadow": "offsetBottomRight"})),
("picture.size", json!({"width": 180.0, "lockAspect": false})),
("arrange.rotation", json!({"degrees": 15.0})),
] {
assert!(matches!(g.run(cmd, &params), Err(CmdError::Disabled(_))), "{cmd} disabled inside regular group");
}
assert_eq!(all_objects(&g).into_iter().next().unwrap().1, before_group);
}
/// Issue #5896: `shape.outline` rejects unknown or non-string `dash` and `cap` parameters
/// instead of silently falling back to Solid / Flat.
#[test]
fn shape_outline_rejects_unknown_dash_and_cap() {
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("insert.shape", &json!({"kind": "rectangle"})).unwrap();
s.run("shape.outline", &json!({"color": "156082", "width": 2.0, "dash": "dash", "cap": "rnd"})).unwrap();
for bad in
[json!({"cap": "round"}), json!({"dash": "dotted"}), json!({"cap": 42}), json!({"dash": false}), json!({"dash": null}), json!({"cap": null})]
{
assert!(matches!(s.run("shape.outline", &bad), Err(CmdError::Params(_))), "expected Params error for {bad}");
}
let (_, o) = selected(&s).unwrap();
let InlineObject::Shape { stroke, stroke_width, extra, .. } = o else { panic!("{o:?}") };
assert_eq!(stroke, Rgb::parse("156082"));
assert_eq!(stroke_width, 2.0);
assert_eq!(extra.dash, wordcraft_doc::line_dash::LineDash::Dash);
assert_eq!(extra.cap, wordcraft_doc::connector::LineCap::Round);
}
/// Issue #5896: with multiple shapes selected, Line and Layout commands update every selected target.
#[test]
fn multi_shape_selection_updates_outline_and_layout_on_all() {
let mut s = Session::new(wordcraft_doc::Document::new());
let id0 = s.run("insert.textBox", &json!({"text": "First", "width": 120.0, "height": 60.0})).unwrap()["story"].as_u64().unwrap() as u32;
s.run("arrange.wrap", &json!({"wrap": "square"})).unwrap();
s.sel = Selection::caret(s.doc.end_of(StoryRef::Body));
let id1 = s.run("insert.textBox", &json!({"text": "Second", "width": 200.0, "height": 90.0})).unwrap()["story"].as_u64().unwrap() as u32;
s.run("arrange.wrap", &json!({"wrap": "square"})).unwrap();
s.run("select.objects", &json!({"index": 0})).unwrap();
s.run("select.addObject", &json!({"index": 1})).unwrap();
s.run("shape.outline", &json!({"color": "156082", "width": 2.5, "dash": "lgDash", "cap": "sq"})).unwrap();
s.run("picture.size", &json!({"width": 160.0, "lockAspect": false})).unwrap();
s.run("arrange.rotation", &json!({"degrees": 30.0})).unwrap();
s.run("shape.alignText", &json!({"anchor": "ctr"})).unwrap();
s.run("shape.textDirection", &json!({"dir": "vert"})).unwrap();
assert_eq!(picked_objects(&s).len(), 2, "multi-selection preserved across formatting and layout");
let objs = all_objects(&s);
assert_eq!(objs.len(), 2);
for (idx, ((_, o), expected_h)) in objs.iter().zip([60.0, 90.0]).enumerate() {
let InlineObject::Shape { w, h, stroke, stroke_width, float, extra, .. } = o else { panic!("{o:?}") };
assert_eq!((*w, *h), (160.0, expected_h), "box {idx} kept its own height");
assert_eq!(*stroke, Rgb::parse("156082"), "box {idx} stroke");
assert_eq!(*stroke_width, 2.5, "box {idx} stroke width");
assert_eq!(extra.dash, wordcraft_doc::line_dash::LineDash::LongDash, "box {idx} dash");
assert_eq!(extra.cap, wordcraft_doc::connector::LineCap::Square, "box {idx} cap");
assert_eq!(float.spin().deg, 30.0, "box {idx} rotation");
}
for id in [id0, id1] {
let body = s.doc.parts.get(&id).unwrap().body;
assert_eq!(body.anchor, VAlign::Center);
assert_eq!(body.vert, TextVert::Vert);
}
s.run("shape.outline", &json!({"color": null})).unwrap();
for (_, o) in all_objects(&s) {
let InlineObject::Shape { stroke, .. } = o else { panic!("{o:?}") };
assert_eq!(stroke, None);
}
}
/// Issue #5896: "No line", dash preset, and line cap set via `shape.outline` survive a DOCX save/open round trip.
#[test]
fn shape_outline_no_line_dash_and_cap_round_trip_docx() {
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("insert.textBox", &json!({"text": "Borderless"})).unwrap();
s.run("shape.outline", &json!({"color": null})).unwrap();
s.sel = Selection::caret(s.doc.end_of(StoryRef::Body));
s.run("insert.shape", &json!({"kind": "rectangle"})).unwrap();
s.run("shape.outline", &json!({"color": "156082", "width": 2.25, "dash": "dashDot", "cap": "rnd"})).unwrap();
s.sel = Selection::caret(s.doc.end_of(StoryRef::Body));
s.run("insert.shape", &json!({"kind": "ellipse"})).unwrap();
s.run("shape.outline", &json!({"color": "C00000", "width": 1.5, "dash": "sysDot", "cap": "sq"})).unwrap();
let bytes = crate::io::save_bytes("out.docx", &s.doc).unwrap();
let mut s2 = Session::new(wordcraft_doc::Document::new());
s2.run("file.open", &json!({"path": "out.docx", "data": crate::cmd::insert::base64_encode(&bytes)})).unwrap();
let objs = all_objects(&s2);
assert_eq!(objs.len(), 3);
let InlineObject::Shape { stroke: tb_stroke, story, .. } = &objs[0].1 else { panic!("{:?}", objs[0]) };
assert!(story.is_some());
assert_eq!(*tb_stroke, None, "No line preserved through DOCX round trip");
let InlineObject::Shape { stroke, stroke_width, extra, .. } = &objs[1].1 else { panic!("{:?}", objs[1]) };
assert_eq!(*stroke, Rgb::parse("156082"));
assert!((*stroke_width - 2.25).abs() < 0.05, "width {stroke_width}");
assert_eq!(extra.dash, wordcraft_doc::line_dash::LineDash::DashDot);
assert_eq!(extra.cap, wordcraft_doc::connector::LineCap::Round);
let InlineObject::Shape { stroke, stroke_width, extra, .. } = &objs[2].1 else { panic!("{:?}", objs[2]) };
assert_eq!(*stroke, Rgb::parse("C00000"));
assert!((*stroke_width - 1.5).abs() < 0.05, "width {stroke_width}");
assert_eq!(extra.dash, wordcraft_doc::line_dash::LineDash::SystemDot);
assert_eq!(extra.cap, wordcraft_doc::connector::LineCap::Square);
}
/// Issue #5896: mixed multi-selections enable `shape.fill`, `shape.outline`, `shape.effects`,
/// `shape.alignText`, and `shape.textDirection` whenever at least one selected target matches.
#[test]
fn mixed_object_multi_selection_enables_shape_and_text_box_commands() {
// Picture selected first + rectangle added via select.addObject.
let mut s = Session::new(wordcraft_doc::Document::new());
let data = super::super::insert::base64_encode(&png(12, 12));
s.run("insert.picture", &json!({"data": data, "width": 60})).unwrap();
s.sel = Selection::caret(s.doc.end_of(StoryRef::Body));
s.run("insert.shape", &json!({"kind": "rectangle"})).unwrap();
s.run("select.objects", &json!({"index": 0})).unwrap();
s.run("select.addObject", &json!({"index": 1})).unwrap();
s.run("shape.fill", &json!({"color": "00AA00"})).unwrap();
s.run("shape.outline", &json!({"color": "FF0000", "dash": "dash"})).unwrap();
s.run("shape.effects", &json!({"shadow": "offsetBottomRight"})).unwrap();
assert!(matches!(s.run("shape.alignText", &json!({"anchor": "b"})), Err(CmdError::Disabled(_))));
assert!(matches!(s.run("shape.textDirection", &json!({"dir": "vert"})), Err(CmdError::Disabled(_))));
let objs = all_objects(&s);
assert!(matches!(&objs[0].1, InlineObject::Image { .. }));
let InlineObject::Shape { fill, stroke, effects, extra, .. } = &objs[1].1 else { panic!("{:?}", objs[1]) };
assert_eq!(*fill, Rgb::parse("00AA00").map(wordcraft_doc::fill::Fill::solid));
assert_eq!(*stroke, Rgb::parse("FF0000"));
assert_eq!(extra.dash, wordcraft_doc::line_dash::LineDash::Dash);
assert!(effects.shadow.is_some());
// Plain shape selected first + text box added via select.addObject.
let mut s2 = Session::new(wordcraft_doc::Document::new());
s2.run("insert.shape", &json!({"kind": "rectangle"})).unwrap();
s2.sel = Selection::caret(s2.doc.end_of(StoryRef::Body));
let tb_id = s2.run("insert.textBox", &json!({"text": "Mixed box"})).unwrap()["story"].as_u64().unwrap() as u32;
s2.run("select.objects", &json!({"index": 0})).unwrap();
s2.run("select.addObject", &json!({"index": 1})).unwrap();
s2.run("shape.alignText", &json!({"anchor": "b"})).unwrap();
s2.run("shape.textDirection", &json!({"dir": "vert270"})).unwrap();
let body = s2.doc.parts.get(&tb_id).unwrap().body;
assert_eq!(body.anchor, VAlign::Bottom);
assert_eq!(body.vert, TextVert::Vert270);
}
/// Issue #5896: `arrange.align` and `arrange.position` inside an active text box anchored in
/// a later section use that anchor section's margins rather than section 0's.
#[test]
fn arrange_align_and_position_use_text_box_anchor_section() {
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
s.run("layout.margins", &json!({"left": 144.0, "right": 144.0})).unwrap();
let sect1_tw = crate::cmd::page::sect(&s).text_width();
let sect0_tw = s.doc.sections()[0].1.text_width();
assert!(sect1_tw < sect0_tw, "section 1 has narrower text area");
s.run("insert.textBox", &json!({"text": "Section 1 box", "width": 100.0, "height": 50.0})).unwrap();
s.run("arrange.align", &json!({"value": "right"})).unwrap();
let (pos, o) = selected_or_text_box(&s).unwrap();
let (_, _, f) = o.frame().unwrap();
assert!((f.x - (sect1_tw - 100.0)).abs() < 0.01, "aligned to section 1 right margin ({} vs {})", f.x, sect1_tw - 100.0);
s.run("arrange.position", &json!({"preset": "topRight"})).unwrap();
let o2 = s.doc.para_at(&pos).unwrap().object_at(pos.off).unwrap();
let (_, _, f2) = o2.frame().unwrap();
assert!((f2.x - (sect1_tw - 100.0)).abs() < 0.01, "positioned to section 1 right margin ({} vs {})", f2.x, sect1_tw - 100.0);
}
/// Issue #5896: bulk rotation commands stay enabled when a chart is primary selection and a
/// movable shape is added via `select.addObject`.
#[test]
fn chart_primary_with_added_shape_allows_rotation() {
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("insert.chart", &json!({"type": "column"})).unwrap();
s.sel = Selection::caret(s.doc.end_of(StoryRef::Body));
s.run("insert.shape", &json!({"kind": "rectangle"})).unwrap();
s.run("select.objects", &json!({"index": 0})).unwrap();
s.run("select.addObject", &json!({"index": 1})).unwrap();
s.run("arrange.rotation", &json!({"degrees": 45.0})).unwrap();
s.run("arrange.rotate", &json!({"direction": "right"})).unwrap();
let objs = all_objects(&s);
let (_, _, chart_f) = objs[0].1.frame().unwrap();
let (_, _, shape_f) = objs[1].1.frame().unwrap();
assert_eq!(chart_f.spin().deg, 0.0);
assert_eq!(shape_f.spin().deg, 135.0);
}
/// Issue #5896: `shape.size` and `shape.rotation` only change shapes/canvases in a mixed
/// Picture + Chart + Shape selection, while generic `picture.size` keeps resizing all targets.
#[test]
fn shape_size_and_rotation_only_affect_shapes_in_mixed_selection() {
let mut s = Session::new(wordcraft_doc::Document::new());
let data = super::super::insert::base64_encode(&png(12, 12));
s.run("insert.picture", &json!({"data": data})).unwrap();
s.run("picture.size", &json!({"width": 60.0, "height": 40.0, "lockAspect": false})).unwrap();
s.run("arrange.rotation", &json!({"degrees": 10.0})).unwrap();
s.sel = Selection::caret(s.doc.end_of(StoryRef::Body));
s.run("insert.chart", &json!({"type": "column"})).unwrap();
let (chart_w0, chart_h0, _) = all_objects(&s)[1].1.frame().unwrap();
s.sel = Selection::caret(s.doc.end_of(StoryRef::Body));
s.run("insert.shape", &json!({"kind": "rectangle", "width": 150.0, "height": 80.0})).unwrap();
s.run("select.objects", &json!({"index": 0})).unwrap();
s.run("select.addObject", &json!({"index": 1})).unwrap();
s.run("select.addObject", &json!({"index": 2})).unwrap();
s.run("shape.size", &json!({"width": 210.0, "lockAspect": false})).unwrap();
s.run("shape.rotation", &json!({"degrees": 45.0})).unwrap();
assert_eq!(picked_objects(&s).len(), 3, "multi-selection preserved across shape.size and shape.rotation");
let objs = all_objects(&s);
let (pw, ph, pf) = objs[0].1.frame().unwrap();
assert_eq!((pw, ph, pf.spin().deg), (60.0, 40.0, 10.0), "picture untouched by shape.size/rotation");
let (cw, ch, _) = objs[1].1.frame().unwrap();
assert_eq!((cw, ch), (chart_w0, chart_h0), "chart untouched by shape.size");
let (sw, sh, sf) = objs[2].1.frame().unwrap();
assert_eq!((sw, sh, sf.spin().deg), (210.0, 80.0, 45.0), "shape updated");
// Generic picture.size continues to resize every sizable object in the selection.
s.run("picture.size", &json!({"width": 180.0, "lockAspect": false})).unwrap();
let objs2 = all_objects(&s);
assert_eq!(objs2[0].1.frame().unwrap().0, 180.0);
assert_eq!(objs2[1].1.frame().unwrap().0, 180.0);
assert_eq!(objs2[2].1.frame().unwrap().0, 180.0);
}
+1 -1
View File
@@ -224,7 +224,7 @@ fn manual_hyphenation(s: &mut Session, v: &Value) -> CmdResult {
Ok(best.map(|(_, v)| v).unwrap_or_else(|| json!({"done": true})))
}
pub(crate) fn section_of_part(s: &Session, id: u32) -> usize {
fn section_of_part(s: &Session, id: u32) -> usize {
let sections = s.doc.sections();
for (i, (_, sp)) in sections.iter().enumerate() {
if [sp.headers.default, sp.headers.first, sp.headers.even, sp.footers.default, sp.footers.first, sp.footers.even].contains(&Some(id)) {
+14 -64
View File
@@ -49,12 +49,10 @@ fn clip_text(s: &Session, v: &Value) -> Option<String> {
}
}
/// Whether the string starts with an RTF file header.
fn looks_like_rtf(t: &str) -> bool {
t.trim_start().starts_with("{\\rtf")
}
/// Whether the string looks like an HTML fragment.
fn looks_like_html(t: &str) -> bool {
let t = t.trim_start();
t.starts_with('<') && (t.contains("</") || t.contains("/>"))
@@ -67,53 +65,18 @@ fn owns_clipboard(v: &Value) -> bool {
p::bool(v, "privateClipboard").unwrap_or(true)
}
/// Accommodate macOS arboard wrapping: `<html><head>...</head><body>...</body></html>`.
fn extract_body(html: &str) -> Option<&str> {
let lower = html.to_ascii_lowercase();
let body_start = lower.find("<body")?;
let after_body = html.get(body_start..)?;
let tag_end_rel = after_body.find('>')?;
let tag_end = body_start.checked_add(tag_end_rel)?.checked_add(1)?;
let end = lower.rfind("</body>")?;
if tag_end <= end { html.get(tag_end..end) } else { None }
}
/// Whether the supplied HTML string matches WordCraft's session clipboard HTML,
/// accounting for macOS arboard wrapping.
fn html_matches_clipboard(h: &str, clip: &str) -> bool {
if h == clip {
return true;
}
if clip.is_empty() {
return false;
}
extract_body(h).is_some_and(|body| body == clip || body.trim() == clip.trim())
}
/// Whether the clipboard payload matches WordCraft's session clipboard copy, so the session's
/// formatted fragment can be used.
pub(crate) fn matches_session_clipboard(s: &Session, v: &Value) -> bool {
let text = p::str(v, "text").map(|t| t.replace("\r\n", "\n"));
let html = p::str(v, "html");
let rtf = p::str(v, "rtf");
let has_rich = html.is_some_and(|h| !h.is_empty()) || rtf.is_some_and(|r| !r.is_empty());
let html_matches = html.is_none_or(|h| html_matches_clipboard(h, &s.clipboard_html));
let rtf_matches = rtf.is_none_or(|r| r == s.clipboard_rtf);
owns_clipboard(v)
&& s.clipboard.as_ref().is_some_and(|f| {
text.as_ref().is_none_or(|t| f.clipboard_text() == *t || (t.is_empty() && has_rich))
&& html_matches
&& rtf_matches
&& (text.is_some() || has_rich || (html.is_none() && rtf.is_none()))
})
}
/// The source for a format, if the clipboard has it.
fn source(s: &Session, v: &Value, fmt: &str) -> Option<String> {
let non_empty = |t: String| if t.is_empty() { None } else { Some(t) };
match fmt {
"formatted" if matches_session_clipboard(s, v) => Some(String::new()),
"formatted" if owns_clipboard(v) => {
let f = s.clipboard.as_ref()?;
// System clipboard text that isn't our own copy means someone else copied since.
match p::str(v, "text") {
Some(t) if f.clipboard_text() != t.replace("\r\n", "\n") => None,
_ => Some(String::new()),
}
}
"formatted" => None,
"rtf" => p::str(v, "rtf").map(str::to_string).or_else(|| clip_text(s, v).filter(|t| looks_like_rtf(t))).and_then(non_empty),
"html" => p::str(v, "html").map(str::to_string).or_else(|| clip_text(s, v).filter(|t| looks_like_html(t))).and_then(non_empty),
@@ -326,15 +289,17 @@ pub fn paste_content(s: &mut Session, v: &Value) -> Result<Pasted, CmdError> {
}
fn clipboard_content(s: &mut Session, v: &Value) -> Result<Pasted, CmdError> {
if matches_session_clipboard(s, v)
let text = p::str(v, "text").map(|t| t.replace("\r\n", "\n"));
if owns_clipboard(v)
&& let Some(f) = &s.clipboard
&& text.as_ref().is_none_or(|t| f.clipboard_text() == *t)
&& (text.is_some() || (p::str(v, "html").is_none() && p::str(v, "rtf").is_none()))
{
return Ok(Pasted::Fragment(f.clone()));
}
if let Some(f) = rich_fragment(s, v) {
return Ok(Pasted::Fragment(f));
}
let text = p::str(v, "text").map(|t| t.replace("\r\n", "\n"));
match text {
Some(t) if !t.is_empty() => Ok(Pasted::Text(t)),
_ => Err(CmdError::Failed("the clipboard is empty".into())),
@@ -400,19 +365,8 @@ pub fn merge_formatting(s: &Session, frag: &mut Fragment) {
}
}
/// Paste `frag` at the selection. A copied table pasted with the caret in a table cell goes the way
/// Word's Paste does it (rows inserted or cells overwritten, #6739; see [`super::paste_cells`]);
/// anything else is [`insert_as_is`].
pub fn insert(s: &mut Session, frag: Fragment) -> Result<(), CmdError> {
if super::paste_cells::paste_cells(s, &frag)? {
return Ok(());
}
insert_as_is(s, frag)
}
/// Replace the selection with `frag`, marking it as an insertion under Track Changes. A table pasted
/// with the caret in a cell nests in that cell (Word's Paste as Nested Table).
pub fn insert_as_is(s: &mut Session, mut frag: Fragment) -> Result<(), CmdError> {
/// Replace the selection with `frag`, marking it as an insertion under Track Changes.
pub fn insert(s: &mut Session, mut frag: Fragment) -> Result<(), CmdError> {
// The pasted text keeps its own formatting; what Backspace carried over is not for after it (#6518).
s.forget_carried();
super::controls::prepare_edit(s)?;
@@ -438,11 +392,7 @@ pub fn insert_as_is(s: &mut Session, mut frag: Fragment) -> Result<(), CmdError>
});
}
}
let before_props = track.then(|| s.doc.para_at(&at).map(|p| p.props.clone())).flatten();
let end = s.doc.insert_fragment(&at, &frag)?;
if track && let Some(before) = before_props {
crate::cmd::fmt_revisions::record_para_props(s, at.story, &at.path, &before)?;
}
// The paragraph marks the paste added are inserted too, so rejecting it joins the
// paragraphs again. The last paragraph ends with the original mark and keeps it.
if let Some(r) = rid
-267
View File
@@ -1,267 +0,0 @@
//! Paste with the caret inside a table cell (#6739). Word does not nest a copied table there (that
//! is its Paste as Nested Table, `edit.pasteNestedTable` here); observed black-box with synthetic
//! tables:
//!
//! - a copied table (or whole rows) whose caret is in the first column of a table of the same
//! width: its rows are inserted above the caret's row;
//! - otherwise the copied cells overwrite the cells from the caret's cell rightwards and down,
//! adding the rows and columns they need (new cells empty).
//!
//! With a cell selection, Paste overwrites from its top-left, including when the copy is wider
//! than the selection.
//!
//! Pasted cells take the destination's cell formatting (Word's default keeps the source's; not
//! done yet). What this does not cover falls back to the old behaviour, a nested table (see
//! [`paste_cells`]).
use wordcraft_doc::edit::Fragment;
use wordcraft_doc::props::VMerge;
use wordcraft_doc::table::{MAX_COLS, MAX_ROWS};
use wordcraft_doc::{Block, Cell, InlineObject, Path, Pos, Row, StoryRef, Table};
use crate::{CmdError, Selection, Session};
/// The fragment's table when it is one table and nothing else (empty paragraphs around it aside).
fn lone_table(frag: &Fragment) -> Option<&Table> {
let mut table = None;
for b in &frag.blocks {
match b {
Block::Table(t) if table.is_none() => table = Some(t),
Block::Para(p) if p.is_empty() && p.objects.is_empty() => {}
_ => return None,
}
}
table
}
/// The width of a rectangular table that can be pasted cell by cell. Merges, offsets,
/// objects and content control wrappers require preserving the table structure.
fn plain_source(t: &Table) -> Option<usize> {
let cols = t.rows.first()?.cells.len();
let simple = |c: &Cell| {
c.span() == 1
&& c.props.vmerge == VMerge::None
&& !c.blocks.is_empty()
&& c.controls.is_empty()
&& c.blocks.iter().all(|b| matches!(&**b, Block::Para(p) if p.objects.is_empty() && p.section.is_none()))
};
let ok = cols > 0
&& t.controls.is_empty()
&& t.rows.iter().all(|r| {
r.cells.len() == cols
&& r.first_grid() == 0
&& r.grid_after() == 0
&& r.props.exceptions.is_none()
&& r.controls.is_empty()
&& r.cells.iter().all(simple)
});
ok.then_some(cols)
}
/// Whether the destination table's rows are a plain grid: one cell per grid column, no merges,
/// offsets or row exceptions.
fn plain_destination(t: &Table) -> bool {
let cols = t.grid.len();
cols > 0
&& t.rows.iter().all(|r| {
r.cells.len() == cols
&& r.first_grid() == 0
&& r.grid_after() == 0
&& r.props.exceptions.is_none()
&& r.cells.iter().all(|c| c.span() == 1 && c.props.vmerge == VMerge::None)
})
}
/// How deep [`has_control`] looks into tables nested in a cell; a deeper cell counts as holding a
/// control, so a hostile document can't make the walk recurse without bound.
const MAX_CONTROL_DEPTH: usize = 16;
/// Whether a cell holds a content control, or a control's start or end in its text, at any depth
/// of nested tables, or a text box anchor (whose story may hold one): overwriting the cell
/// replaces all of its blocks, which could remove a locked control (the caret's own cell is
/// checked by the caller's edit rules).
fn has_control(c: &Cell) -> bool {
cell_has_control(c, 0)
}
fn cell_has_control(c: &Cell, depth: usize) -> bool {
if !c.controls.is_empty() || depth > MAX_CONTROL_DEPTH {
return true;
}
c.blocks.iter().any(|b| match &**b {
// A text box (or a group holding one) anchored here has its own story, which may hold a locked
// control; it is not walked, so a cell with one counts as holding a control.
Block::Para(p) => {
p.objects.iter().any(|o| matches!(o, InlineObject::ControlStart { .. } | InlineObject::ControlEnd) || !o.text_boxes().is_empty())
}
Block::Table(t) => {
!t.controls.is_empty() || t.rows.iter().any(|r| !r.controls.is_empty() || r.cells.iter().any(|c| cell_has_control(c, depth + 1)))
}
})
}
/// What a paste into a cell does with the copied table `src` at (`row0`, `col0`) of `dest`.
enum Plan {
/// Insert the copy's rows above `row0`.
InsertRows,
/// Lay the copy's cells over the table from the cell.
Overwrite,
}
/// How `src` goes into `dest` at (`row0`, `col0`), or `None` when it can't be laid over it (the
/// paste nests the table instead).
fn plan(dest: &Table, src: &Table, src_cols: usize, row0: usize, col0: usize, allow_row_insertion: bool) -> Option<Plan> {
if !plain_destination(dest) || col0 >= dest.grid.len() || row0 >= dest.rows.len() {
return None;
}
let (src_rows, dest_cols) = (src.rows.len(), dest.grid.len());
// A one-column table is a layout wrapper more often than a grid: a wider copy nests in it.
if dest_cols == 1 && src_cols > 1 {
return None;
}
// Word inserts whole rows above the caret's row when the caret is in the first column and
// the rows are as wide as the table; a one-column table can't tell rows from a cell.
if allow_row_insertion && col0 == 0 && src_cols == dest_cols && dest_cols > 1 {
return (dest.rows.len().saturating_add(src_rows) <= MAX_ROWS).then_some(Plan::InsertRows);
}
if dest.rows.len().max(row0.saturating_add(src_rows)) > MAX_ROWS || dest_cols.max(col0.saturating_add(src_cols)) > MAX_COLS {
return None;
}
// A wrapper may open before the first overwritten row or cell and close after the last.
// Use ordinary paste for wrapped grids so an overwrite cannot bypass a structural control.
if !dest.controls.is_empty() || dest.rows.iter().any(|row| !row.controls.is_empty() || row.cells.iter().any(|cell| !cell.controls.is_empty())) {
return None;
}
let hit = |r: usize| dest.rows.get(r).is_some_and(|row| row.cells.iter().skip(col0).take(src_cols).any(has_control));
(!(row0..row0.saturating_add(src_rows).min(dest.rows.len())).any(hit)).then_some(Plan::Overwrite)
}
/// Overwrite cells from the top-left of a selection while it still identifies a rectangle.
pub(super) fn paste_over_selection(s: &mut Session, frag: &Fragment) -> Result<bool, CmdError> {
let Some(range) = s.cell_range() else { return Ok(false) };
if s.doc.settings.track_changes || s.doc.control_at(&s.sel.ordered().0).is_some() {
return Ok(false);
}
let Some(src) = lone_table(frag) else { return Ok(false) };
let Some(src_cols) = plain_source(src) else { return Ok(false) };
let (row, col) = (range.rows.0, range.cols.0);
let story = range.story;
let table = range.table.clone();
let Some(dest) = s.doc.table(story, &table) else { return Ok(false) };
let Some(edit) = plan(dest, src, src_cols, row, col, false) else { return Ok(false) };
apply_plan(s, src, story, &table, row, col, edit)?;
s.column = None;
s.goal_x = None;
s.pending = None;
Ok(true)
}
/// A copied table pasted with the caret in a table cell, as Word's default Paste does it.
/// `false` (nothing done; the caller pastes as before, nesting the table) when:
/// - the selection is not a caret in a cell, or the clipboard is not one table;
/// - Track Changes is on (the cell edits aren't tracked here);
/// - the copied table has merged cells, ragged rows, empty cells, pictures or other objects,
/// a paragraph with a section break, or a control wrapping the table, a row or a cell;
/// - the destination table has merged cells or offset rows, or an overwrite would affect a
/// destination with structural wrappers or a cell containing a control in its blocks;
/// - the caret is in a content control that shows its placeholder (the ordinary paste replaces
/// the placeholder);
/// - the destination has one column and the copy more (a layout wrapper), or the paste would pass
/// the limits on a table's rows or columns.
pub fn paste_cells(s: &mut Session, frag: &Fragment) -> Result<bool, CmdError> {
if s.doc.settings.track_changes || !s.sel.is_collapsed() || s.cell_range().is_some() {
return Ok(false);
}
let Some(src) = lone_table(frag) else { return Ok(false) };
let Some(src_cols) = plain_source(src) else { return Ok(false) };
let Some((tp, row0, col0)) = s.sel.focus.path.cell() else { return Ok(false) };
let Some(dest) = s.doc.table(s.sel.focus.story, &tp) else { return Ok(false) };
if plan(dest, src, src_cols, row0, col0, true).is_none() {
return Ok(false);
}
// A caret in a control that shows its placeholder: the edit rules would select the
// placeholder to replace it, which the row insertion would not do. The ordinary paste does.
// This also covers a caret at the edge of such a control (drop-down, check box): rows used to
// be inserted there, now the table nests. Overwrite already declined for cells with controls.
if s.doc.control_at(&s.sel.focus).is_some_and(|r| r.control.showing_placeholder) {
return Ok(false);
}
// Pasting ends Backspace's carried formatting, as in the ordinary paste path.
s.forget_carried();
// Protection: the edit rules may move the caret (to where typing goes) or refuse.
if super::controls::prepare_edit(s)?.is_some() {
// Normalizing the caret can enter a control and select its placeholder.
// Let ordinary paste replace that selection.
return Ok(false);
}
let at = s.sel.focus.clone();
let Some((tp, row0, col0)) = at.path.cell() else { return Ok(false) };
let story = at.story;
let Some(dest) = s.doc.table(story, &tp) else { return Ok(false) };
let Some(edit) = plan(dest, src, src_cols, row0, col0, true) else { return Ok(false) };
apply_plan(s, src, story, &tp, row0, col0, edit)?;
Ok(true)
}
fn apply_plan(s: &mut Session, src: &Table, story: StoryRef, tp: &Path, row0: usize, col0: usize, plan: Plan) -> Result<(), CmdError> {
let t = s.doc.table_mut(story, tp)?;
let first = match plan {
Plan::InsertRows => insert_source_rows(t, src, row0),
Plan::Overwrite => overwrite_cells(t, src, row0, col0),
};
super::table::touch_cells(s, tp)?;
let mut path = tp.0.clone();
path.extend([first.0 as u32, first.1 as u32, 0]);
s.sel = Selection::caret(Pos { story, path: Path(path), off: 0 });
Ok(())
}
/// Insert the rows of `src` above row `at` of `t` (same column count), formatted as that row.
/// Returns the (row, cell) of the first pasted cell.
fn insert_source_rows(t: &mut Table, src: &Table, at: usize) -> (usize, usize) {
let Some(template) = t.rows.get(at) else { return (at, 0) };
let new_rows: Vec<Row> = src
.rows
.iter()
.map(|sr| {
let mut row = Row { props: template.props.clone(), ..Row::default() };
row.props.header = false;
row.cells = template
.cells
.iter()
.zip(&sr.cells)
.map(|(dc, sc)| {
let mut c = Cell::empty();
c.props = dc.props.clone();
c.blocks = sc.blocks.clone();
c
})
.collect();
row
})
.collect();
t.rows.splice(at..at, new_rows);
(at, 0)
}
/// Lay the cells of `src` over those of `t` from (`row0`, column `col0`), adding the rows and
/// columns they need. Returns the (row, cell) of the first pasted cell.
fn overwrite_cells(t: &mut Table, src: &Table, row0: usize, col0: usize) -> (usize, usize) {
let src_cols = src.rows.first().map_or(0, |r| r.cells.len());
while t.grid.len() < col0.saturating_add(src_cols) && t.grid.len() < MAX_COLS {
t.insert_col(t.grid.len());
}
while t.rows.len() < row0.saturating_add(src.rows.len()) && t.rows.len() < MAX_ROWS {
let at = t.rows.len();
t.insert_row(at, at.saturating_sub(1));
}
for (i, sr) in src.rows.iter().enumerate() {
let Some(row) = t.rows.get_mut(row0 + i) else { break };
for (j, sc) in sr.cells.iter().enumerate() {
if let Some(dc) = row.cells.get_mut(col0 + j) {
dc.blocks = sc.blocks.clone();
}
}
}
(row0, col0)
}
-84
View File
@@ -1122,87 +1122,3 @@ mod spelling_navigation_tests {
}
}
}
/// #6086 review: A pre-existing table whose cell paragraphs and runs are all redlined (including an
/// empty cell with a deleted/inserted paragraph mark) is not a structural table revision; Accept
/// All / Reject All and whole-table selection resolution must preserve the table shell.
#[test]
fn preexisting_table_with_redlined_cell_content_preserves_table_shell() {
use std::sync::Arc;
use wordcraft_doc::{Block, CharProps, Paragraph, Path, Pos, Revision, RevisionKind, StoryRef, table::Table};
struct Cleanup(std::path::PathBuf);
impl Drop for Cleanup {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
let dir = std::env::temp_dir().join(format!("wc-review-preexisting-tbl-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let _cleanup = Cleanup(dir.clone());
let make_redlined_table = |del: bool| -> Document {
let mut d = Document::new();
let kind = if del { RevisionKind::Delete } else { RevisionKind::Insert };
d.revisions.push(Revision::new(kind, "Alice", "2026-11-24T00:00:00Z"));
let rev = Some(0);
let mark_props = if del { CharProps { del: rev, ..Default::default() } } else { CharProps { ins: rev, ..Default::default() } };
let mut p0 = Paragraph::with_text("Cell text", mark_props.clone());
p0.mark = mark_props.clone();
let mut p1 = Paragraph::new();
p1.mark = mark_props;
let mut t = Table::new(1, 2, 240.0);
t.rows[0].cells[0].blocks = vec![Arc::new(Block::Para(p0))];
t.rows[0].cells[1].blocks = vec![Arc::new(Block::Para(p1))];
d.body = vec![Arc::new(Block::Table(t)), Arc::new(Block::Para(Paragraph::new()))];
d
};
let assert_shell_preserved = |doc: &Document, label: &str| {
let tables: Vec<&Table> = doc.body.iter().filter_map(|b| b.as_table()).collect();
assert_eq!(tables.len(), 1, "{label}: pre-existing table shell must remain");
assert_eq!(tables[0].rows.len(), 1, "{label}: row count must remain 1");
assert_eq!(tables[0].rows[0].cells.len(), 2, "{label}: cell count must remain 2");
assert_eq!(tables[0].rows[0].cells[0].blocks[0].as_para().unwrap().plain_text(), "", "{label}: cell 0 text cleared");
assert_eq!(tables[0].rows[0].cells[1].blocks[0].as_para().unwrap().plain_text(), "", "{label}: cell 1 stays empty");
};
for (del, all_cmd, sel_cmd, label) in [
(true, "review.acceptAll", "review.accept", "deleted cell content + Accept"),
(false, "review.rejectAll", "review.reject", "inserted cell content + Reject"),
] {
let doc = make_redlined_table(del);
// Global Accept All / Reject All in memory.
let mut s_all = Session::new(doc.clone());
s_all.run(all_cmd, &json!({})).unwrap();
assert_shell_preserved(&s_all.doc, &format!("{label} (in-memory all)"));
assert!(s_all.run("review.changes", &json!({})).unwrap().as_array().unwrap().is_empty());
// Whole-body selection Accept / Reject.
let mut s_body = Session::new(doc.clone());
s_body.run("select.all", &json!({})).unwrap();
s_body.run(sel_cmd, &json!({})).unwrap();
assert_shell_preserved(&s_body.doc, &format!("{label} (whole-body sel)"));
// Whole-table selection Accept / Reject.
let mut s_tbl = Session::new(doc.clone());
s_tbl.sel = crate::Selection {
anchor: Pos { story: StoryRef::Body, path: Path(vec![0, 0, 0, 0]), off: 0 },
focus: Pos { story: StoryRef::Body, path: Path(vec![0, 0, 1, 0]), off: 0 },
};
s_tbl.run(sel_cmd, &json!({})).unwrap();
assert_shell_preserved(&s_tbl.doc, &format!("{label} (whole-table sel)"));
// DOCX save/open round-trip followed by Accept All / Reject All.
let path = dir.join(format!("preexisting-{del}.docx"));
crate::io::save_path(&path, &doc).unwrap();
let reopened = crate::io::open_path(&path).unwrap();
let mut s_rt = Session::new(reopened);
s_rt.run(all_cmd, &json!({})).unwrap();
assert_shell_preserved(&s_rt.doc, &format!("{label} (DOCX round-trip all)"));
assert!(s_rt.run("review.changes", &json!({})).unwrap().as_array().unwrap().is_empty());
}
}
+12 -3
View File
@@ -9,9 +9,11 @@ use wordcraft_doc::para::InlineObject;
use wordcraft_doc::props::Rgb;
use wordcraft_doc::wordart::GradStop;
use super::objects::{edit_obj, target_objects};
use super::objects::{edit_obj, picked_objects, selected_all};
use crate::{CmdError, CmdResult, CommandSpec, Session, p};
/// Most shapes one command fills (a selection over a whole document).
const MAX_FILL_SHAPES: usize = 10_000;
/// Most stops read from a command (the fill keeps at most `MAX_STOPS` after sanitizing).
const MAX_PARAM_STOPS: usize = 64;
@@ -66,9 +68,16 @@ fn shape_fill(s: &mut Session, v: &Value) -> CmdResult {
Ok(serde_json::json!({"object": last, "count": targets.len()}))
}
/// The shapes and canvases in the selection, those added with `select.addObject`, or the active text box.
/// The shapes and canvases in the selection and those added to it (Shift+click).
fn targets(s: &Session) -> Vec<Pos> {
target_objects(s, |o| matches!(o, InlineObject::Shape { .. }) || o.is_canvas()).into_iter().map(|(pos, _)| pos).collect()
let fillable = |o: &InlineObject| matches!(o, InlineObject::Shape { .. }) || o.is_canvas();
let mut out: Vec<Pos> = selected_all(s, MAX_FILL_SHAPES).into_iter().filter(|(_, o)| fillable(o)).map(|(pos, _)| pos).collect();
for pos in picked_objects(s) {
if !out.contains(&pos) && s.doc.para_at(&pos).and_then(|q| q.object_at(pos.off)).is_some_and(fillable) {
out.push(pos);
}
}
out
}
fn color(v: &Value) -> Result<Rgb, CmdError> {
+100 -459
View File
@@ -1,5 +1,3 @@
use std::collections::BTreeMap;
use super::{
Arc, Block, CharProps, CmdError, CmdResult, Document, InlineObject, Paragraph, RevisionKind, Selection, Session, StoryRef, Value, json, p,
para_block,
@@ -29,17 +27,13 @@ impl CompareOptions {
}
}
/// Context and tracking counters for diffing document blocks and paragraph contents.
/// Context and tracking counters for diffing paragraph contents.
struct DiffCtx<'a> {
ins: u32,
del: u32,
opts: &'a CompareOptions,
author: &'a str,
date: &'a str,
budget: &'a mut u64,
char_fallbacks: &'a mut usize,
table_fallbacks: &'a mut usize,
changes: usize,
plain_revised: bool,
}
@@ -53,9 +47,7 @@ const MAX_CHAR_DIFF: usize = 2000;
/// headers and footers, footnotes, text boxes, fields) are accepted and listed in the result.
/// When character-level comparison is requested (`"level": "character"`) but any paragraph exceeds
/// [`MAX_CHAR_DIFF`] characters, it falls back to word-level diff for that paragraph, surfaces the
/// fallback count in `"characterFallback"`, and includes `"level"` in `"notHonoured"`. When a
/// same-text table has media changes but an incompatible layout or exceeds [`wordcraft_doc::table::MAX_TABLE_DEPTH`],
/// structural table replacement is deferred and `"tables"` is listed in `"notHonoured"`.
/// fallback count in `"characterFallback"`, and includes `"level"` in `"notHonoured"`.
pub(super) fn compare(s: &mut Session, v: &Value) -> CmdResult {
// A revised side given as plain text carries no real runs or properties; one opened from a
// path does. The diff takes the revised formatting only in the latter case.
@@ -88,57 +80,91 @@ pub(super) fn compare(s: &mut Session, v: &Value) -> CmdResult {
["moves", "comments", "headersFooters", "footnotes", "textBoxes", "fields"].into_iter().filter(|k| v.get(*k).is_some()).collect();
let author = p::str(v, "author").map(str::trim).filter(|a| !a.is_empty()).map(str::to_string).unwrap_or_else(|| s.author.clone());
let date = crate::cmd::now_iso();
// Adopt media referenced by the revised body and reachable text boxes into the original
// document: identical bytes reuse the original's key (deduplicated by content), while
// replaced or new media receives a fresh key in s.doc.media so both media parts are
// preserved in the result (#6086). Unreferenced media in uncompared parts (e.g. headers
// and footers) is not imported.
let mut revised = revised;
let mut raw_media = std::mem::take(&mut revised.media);
let mut media_map = BTreeMap::new();
let old: Vec<Arc<Block>> = s.doc.body.clone();
let new: Vec<Arc<Block>> = if revised.parts.values().any(|p| p.kind == wordcraft_doc::PartKind::TextBox) {
let mut frag = revised.body_fragment();
for b in &mut frag.blocks {
remap_block_media(b, &mut |k| adopt_media_key(&mut s.doc, &mut raw_media, &mut media_map, k));
}
for part in frag.parts.values_mut() {
for b in &mut part.blocks {
remap_block_media(Arc::make_mut(b), &mut |k| adopt_media_key(&mut s.doc, &mut raw_media, &mut media_map, k));
}
}
// The revised document's text boxes get stories of their own in the result, so its
// boxes never show a story of the original's (or none at all).
s.doc.adopt_fragment(&frag).into_iter().map(Arc::new).collect()
s.doc.adopt_fragment(&revised.body_fragment()).into_iter().map(Arc::new).collect()
} else {
for b in &mut revised.body {
remap_block_media(Arc::make_mut(b), &mut |k| adopt_media_key(&mut s.doc, &mut raw_media, &mut media_map, k));
}
revised.body
revised.body.clone()
};
s.doc.revisions.push(wordcraft_doc::Revision { kind: RevisionKind::Insert, author: author.clone(), date: date.clone(), move_name: None });
let ins = (s.doc.revisions.len() - 1) as u32;
s.doc.revisions.push(wordcraft_doc::Revision { kind: RevisionKind::Delete, author: author.clone(), date: date.clone(), move_name: None });
let del = (s.doc.revisions.len() - 1) as u32;
let key = |b: &Arc<Block>| match &**b {
Block::Para(p) => opts.key(&p.plain_text()),
// Tables match as a whole, by their text.
Block::Table(_) => format!("\u{0}table\u{0}{}", opts.key(&block_text(b, 0))),
};
let mut budget = MAX_COMPARE_CELLS;
let mut char_fallbacks = 0usize;
let mut table_fallbacks = 0usize;
let (out, changes) = {
let mut ctx = DiffCtx {
ins,
del,
opts: &opts,
author: &author,
date: &date,
budget: &mut budget,
char_fallbacks: &mut char_fallbacks,
table_fallbacks: &mut table_fallbacks,
changes: 0,
plain_revised,
};
let out = diff_blocks(&mut s.doc, &old, &new, &mut ctx, 0);
(out, ctx.changes)
};
let ops = lcs_ops(&old.iter().map(key).collect::<Vec<_>>(), &new.iter().map(key).collect::<Vec<_>>(), &mut budget);
let mut ctx = DiffCtx { ins, del, opts: &opts, budget: &mut budget, char_fallbacks: &mut char_fallbacks, plain_revised };
let mut out: Vec<Arc<Block>> = Vec::new();
let (mut i, mut j) = (0usize, 0usize);
let mut changes = 0usize;
let mut k = 0;
while k < ops.len() {
match ops.get(k) {
Some(Op::Same) => {
let (a, b) = (old.get(i), new.get(j));
// The revised block, with its formatting changes tracked.
if let (Some(Block::Para(pa)), Some(Block::Para(pb))) = (a.map(|x| &**x), b.map(|x| &**x)) {
if !same_objects(&s.doc, pa, pb) {
// Same text, but objects (text boxes, pictures…) differ: diffed, so the
// original's objects aren't lost.
out.push(para_block(word_diff(&s.doc, pa, pb, &mut ctx)));
changes += 1;
i += 1;
j += 1;
k += 1;
continue;
}
let mut p = pb.clone();
if opts.formatting && pa.text == pb.text {
let before = s.doc.revisions.len();
crate::cmd::fmt_revisions::compare_formatting(pa, &mut p, &mut s.doc.revisions, &author, &date);
if s.doc.revisions.len() > before || p != *pb {
changes += 1;
}
}
out.push(para_block(p));
} else if let Some(x) = b.or(a) {
out.push(x.clone());
}
i += 1;
j += 1;
k += 1;
}
Some(_) => {
// A run of deletions and insertions: changed paragraphs pair up and are diffed
// word by word (or by character); the rest are deleted or inserted whole.
let run = ops.get(k..).unwrap_or_default().iter().take_while(|o| **o != Op::Same).count();
let dels = ops.get(k..k + run).unwrap_or_default().iter().filter(|o| **o == Op::Del).count();
let inss = run - dels;
for x in 0..dels.max(inss) {
let (a, b) = (if x < dels { old.get(i + x) } else { None }, if x < inss { new.get(j + x) } else { None });
match (a.map(|x| &**x), b.map(|x| &**x)) {
(Some(Block::Para(pa)), Some(Block::Para(pb))) => out.push(para_block(word_diff(&s.doc, pa, pb, &mut ctx))),
_ => {
if let Some(x) = a {
out.push(Arc::new(mark_block(x, &|c| c.del = Some(del), 0)));
}
if let Some(x) = b {
out.push(Arc::new(mark_block(x, &|c| c.ins = Some(ins), 0)));
}
}
}
changes += 1;
}
i += dels;
j += inss;
k += run.max(1);
}
None => break,
}
}
s.doc.body = out;
s.doc.ensure_nonempty();
s.note_body_replaced();
@@ -159,14 +185,6 @@ pub(super) fn compare(s: &mut Session, v: &Value) -> CmdResult {
not_honoured.push("level");
}
}
if table_fallbacks > 0 {
log::warn!(
"compare: {table_fallbacks} table(s) with media changes could not be compared cell by cell due to incompatible layout or nesting depth"
);
if !not_honoured.contains(&"tables") {
not_honoured.push("tables");
}
}
s.sel = Selection::caret(s.doc.start_of(StoryRef::Body));
Ok(json!({
"changes": changes,
@@ -176,401 +194,37 @@ pub(super) fn compare(s: &mut Session, v: &Value) -> CmdResult {
}))
}
/// Compare two block slices (`old` vs `new`) at table nesting `depth`, emitting tracked changes.
fn diff_blocks(doc: &mut Document, old: &[Arc<Block>], new: &[Arc<Block>], ctx: &mut DiffCtx<'_>, depth: usize) -> Vec<Arc<Block>> {
let key = |b: &Arc<Block>| match &**b {
Block::Para(p) => ctx.opts.key(&p.plain_text()),
// Tables match as a whole, by their text.
Block::Table(_) => format!("\u{0}table\u{0}{}", ctx.opts.key(&block_text(b, depth))),
};
let ops = lcs_ops(&old.iter().map(key).collect::<Vec<_>>(), &new.iter().map(key).collect::<Vec<_>>(), ctx.budget);
let mut out: Vec<Arc<Block>> = Vec::new();
let (mut i, mut j, mut k) = (0usize, 0usize, 0usize);
while k < ops.len() {
match ops.get(k) {
Some(Op::Same) => {
let (a, b) = (old.get(i), new.get(j));
// The revised block, with its formatting and object changes tracked.
if let (Some(Block::Para(pa)), Some(Block::Para(pb))) = (a.map(|x| &**x), b.map(|x| &**x)) {
if !same_objects(doc, pa, pb) {
// Same text, but objects (text boxes, pictures…) differ: diffed, so the
// original's objects aren't lost.
out.push(para_block(word_diff(doc, pa, pb, ctx)));
ctx.changes = ctx.changes.saturating_add(1);
} else {
let mut p = pb.clone();
if ctx.opts.formatting && pa.text == pb.text {
let before = doc.revisions.len();
crate::cmd::fmt_revisions::compare_formatting(pa, &mut p, &mut doc.revisions, ctx.author, ctx.date);
if doc.revisions.len() > before || p != *pb {
ctx.changes = ctx.changes.saturating_add(1);
}
}
out.push(para_block(p));
}
} else if let (Some(Block::Table(ta)), Some(Block::Table(tb))) = (a.map(|x| &**x), b.map(|x| &**x)) {
diff_matched_table(doc, (a, ta), (b, tb), ctx, depth, &mut out);
} else if let Some(x) = b.or(a) {
out.push(x.clone());
}
i += 1;
j += 1;
k += 1;
}
Some(_) => {
// A run of deletions and insertions: changed paragraphs pair up and are diffed
// word by word (or by character); the rest are deleted or inserted whole.
let run = ops.get(k..).unwrap_or_default().iter().take_while(|o| **o != Op::Same).count();
let dels = ops.get(k..k + run).unwrap_or_default().iter().filter(|o| **o == Op::Del).count();
let inss = run - dels;
for x in 0..dels.max(inss) {
let (a, b) = (if x < dels { old.get(i + x) } else { None }, if x < inss { new.get(j + x) } else { None });
match (a.map(|x| &**x), b.map(|x| &**x)) {
(Some(Block::Para(pa)), Some(Block::Para(pb))) => out.push(para_block(word_diff(doc, pa, pb, ctx))),
_ => {
if let Some(x) = a {
out.push(Arc::new(mark_block(x, &|c| c.del = Some(ctx.del))));
}
if let Some(x) = b {
out.push(Arc::new(mark_block(x, &|c| c.ins = Some(ctx.ins))));
}
}
}
ctx.changes = ctx.changes.saturating_add(1);
}
i += dels;
j += inss;
k += run.max(1);
}
None => break,
}
}
out
}
/// Emit a matched (`Op::Same`) table pair into `out`. Layout-only or media-identical matches keep
/// the revised table as on `main`; tables with media differences are diffed cell by cell when
/// compatible and within [`wordcraft_doc::table::MAX_TABLE_DEPTH`], or otherwise preserve the
/// original table and its media and record a `"tables"` fallback in `notHonoured` without
/// emitting duplicate table shells.
fn diff_matched_table(
doc: &mut Document,
(a, ta): (Option<&Arc<Block>>, &wordcraft_doc::table::Table),
(b, tb): (Option<&Arc<Block>>, &wordcraft_doc::table::Table),
ctx: &mut DiffCtx<'_>,
depth: usize,
out: &mut Vec<Arc<Block>>,
) {
if ta == tb || table_media_keys(ta) == table_media_keys(tb) {
if let Some(x) = b.or(a) {
out.push(x.clone());
}
} else if depth < wordcraft_doc::table::MAX_TABLE_DEPTH && same_table_cells(ta, tb, ctx) {
out.push(Arc::new(Block::Table(diff_table(doc, ta, tb, ctx, depth))));
} else {
if let Some(x) = a.or(b) {
out.push(x.clone());
}
*ctx.table_fallbacks = ctx.table_fallbacks.saturating_add(1);
}
}
/// Whether two tables have compatible grid widths, content controls, row counts, cell counts,
/// spans and vertical merges so their properties and cells can be diffed 1-to-1 without losing
/// untrackable layout changes.
fn same_table_cells(a: &wordcraft_doc::table::Table, b: &wordcraft_doc::table::Table, ctx: &DiffCtx<'_>) -> bool {
let track_fmt = ctx.opts.formatting && !ctx.plain_revised;
(!track_fmt || a.grid == b.grid)
&& a.controls == b.controls
&& a.rows.len() == b.rows.len()
&& a.rows.iter().zip(&b.rows).all(|(ra, rb)| {
ra.controls == rb.controls
&& ra.props.grid_before == rb.props.grid_before
&& ra.props.grid_after == rb.props.grid_after
&& ra.cells.len() == rb.cells.len()
&& ra
.cells
.iter()
.zip(&rb.cells)
.all(|(ca, cb)| ca.controls == cb.controls && ca.span() == cb.span() && ca.props.vmerge == cb.props.vmerge)
})
}
/// Strip revision bookkeeping from table properties for formatting comparison.
fn strip_table_props(t: &wordcraft_doc::props::TableProps) -> wordcraft_doc::props::TableProps {
wordcraft_doc::props::TableProps { fmt_change: None, ..t.clone() }
}
/// Strip revision bookkeeping from row properties (and any nested row table-property exceptions).
fn strip_row_props(r: &wordcraft_doc::props::RowProps) -> wordcraft_doc::props::RowProps {
wordcraft_doc::props::RowProps { fmt_change: None, exceptions: r.exceptions.as_deref().map(|e| Box::new(strip_table_props(e))), ..r.clone() }
}
/// Strip revision bookkeeping and structural merge fields from cell properties.
fn strip_cell_props(c: &wordcraft_doc::props::CellProps) -> wordcraft_doc::props::CellProps {
wordcraft_doc::props::CellProps { fmt_change: None, span: 0, vmerge: wordcraft_doc::props::VMerge::None, ..c.clone() }
}
/// Build a formatting [`wordcraft_doc::props::PropChange`] when formatting tracking is active and
/// `old` differs from `new`.
fn fmt_prop_change<T: PartialEq>(doc: &mut Document, ctx: &DiffCtx<'_>, old: T, new: &T) -> Option<Box<wordcraft_doc::props::PropChange<T>>> {
if !ctx.opts.formatting || ctx.plain_revised || old == *new {
return None;
}
let fmt_rev = format_revision(doc, ctx.author, ctx.date);
wordcraft_doc::props::PropChange::boxed(fmt_rev, old)
}
/// Like [`fmt_prop_change`], also counting a container-level formatting change in `ctx.changes`.
fn record_prop_change<T: PartialEq>(doc: &mut Document, ctx: &mut DiffCtx<'_>, old: T, new: &T) -> Option<Box<wordcraft_doc::props::PropChange<T>>> {
let ch = fmt_prop_change(doc, ctx, old, new);
if ch.is_some() {
ctx.changes = ctx.changes.saturating_add(1);
}
ch
}
/// Record a cell-property change when formatting tracking is active or the cell's background
/// picture changed (`#6086`), so replaced cell media stays rejectable even with `formatting: false`.
fn record_cell_change(
doc: &mut Document,
ctx: &mut DiffCtx<'_>,
ca: &wordcraft_doc::props::CellProps,
cb: &wordcraft_doc::props::CellProps,
) -> Option<Box<wordcraft_doc::props::PropChange<wordcraft_doc::props::CellProps>>> {
let old = strip_cell_props(ca);
let new = strip_cell_props(cb);
if ctx.plain_revised || (!ctx.opts.formatting && ca.picture == cb.picture) || old == new {
return None;
}
let fmt_rev = format_revision(doc, ctx.author, ctx.date);
ctx.changes = ctx.changes.saturating_add(1);
wordcraft_doc::props::PropChange::boxed(fmt_rev, old)
}
/// Diff two compatible tables cell by cell, tracking table, row, and cell property differences
/// alongside cell content edits.
fn diff_table(
doc: &mut Document,
a: &wordcraft_doc::table::Table,
b: &wordcraft_doc::table::Table,
ctx: &mut DiffCtx<'_>,
depth: usize,
) -> wordcraft_doc::table::Table {
let mut t = b.clone();
t.props = strip_table_props(&t.props);
t.props.fmt_change = record_prop_change(doc, ctx, strip_table_props(&a.props), &t.props);
for (ra, rb) in a.rows.iter().zip(&mut t.rows) {
rb.props = strip_row_props(&rb.props);
rb.props.fmt_change = record_prop_change(doc, ctx, strip_row_props(&ra.props), &rb.props);
for (ca, cb) in ra.cells.iter().zip(&mut rb.cells) {
cb.props.fmt_change = None;
cb.props.fmt_change = record_cell_change(doc, ctx, &ca.props, &cb.props);
if ca.blocks != cb.blocks {
cb.blocks = diff_blocks(doc, &ca.blocks, &cb.blocks, ctx, depth + 1);
if cb.blocks.is_empty() {
cb.blocks.push(para_block(Paragraph::new()));
}
}
}
}
t
}
/// Find or create the formatting revision entry for `author` and `date`.
fn format_revision(doc: &mut Document, author: &str, date: &str) -> u32 {
if let Some(i) = doc.revisions.iter().rposition(|r| r.kind == RevisionKind::Format && r.author == author && r.date == date) {
return u32::try_from(i).unwrap_or(u32::MAX);
}
doc.revisions.push(wordcraft_doc::Revision { kind: RevisionKind::Format, author: author.to_string(), date: date.to_string(), move_name: None });
u32::try_from(doc.revisions.len().saturating_sub(1)).unwrap_or(u32::MAX)
}
/// Adopt `old_key` from `raw_media` into `doc` on first use, reusing the existing buffer without
/// cloning when uniquely owned, and memoizing the resulting media key in `media_map`.
fn adopt_media_key(
doc: &mut Document,
raw_media: &mut BTreeMap<String, Arc<Vec<u8>>>,
media_map: &mut BTreeMap<String, String>,
old_key: &str,
) -> Option<String> {
if let Some(k) = media_map.get(old_key) {
return Some(k.clone());
}
let data = raw_media.remove(old_key)?;
let ext = old_key.rsplit_once('.').map(|(_, e)| e).unwrap_or("bin");
let new_key = doc.add_media(Arc::unwrap_or_clone(data), ext);
media_map.insert(old_key.to_string(), new_key.clone());
Some(new_key)
}
/// Rewrites media keys in an inline object and all nested group children via `map`, returning
/// whether any media key changed.
pub(super) fn remap_object_media(root: &mut InlineObject, map: &mut dyn FnMut(&str) -> Option<String>) -> bool {
let mut changed = false;
let mut todo = vec![root];
while let Some(o) = todo.pop() {
match o {
InlineObject::Image { media, .. } => {
if let Some(k) = map(media)
&& k != *media
{
*media = k;
changed = true;
}
}
InlineObject::Graphic { graphic, .. } => {
let mut any = false;
for i in &graphic.items {
if let wordcraft_doc::graphic::GraphicItem::Image { media, .. } = i
&& map(media).is_some_and(|k| k != *media)
{
any = true;
}
}
if any {
for i in &mut Arc::make_mut(graphic).items {
if let wordcraft_doc::graphic::GraphicItem::Image { media, .. } = i
&& let Some(k) = map(media.as_str())
{
*media = k;
}
}
changed = true;
}
}
InlineObject::Group { children, .. } => {
for c in children {
todo.push(&mut c.obj);
}
}
_ => {}
}
}
changed
}
/// Rewrites media keys in all paragraphs and table cells within `b` via `map`.
fn remap_block_media(b: &mut Block, map: &mut dyn FnMut(&str) -> Option<String>) {
let mut todo = vec![b];
while let Some(b) = todo.pop() {
match b {
Block::Para(p) => {
let mut changed = false;
for o in &mut p.objects {
changed |= remap_object_media(o, map);
}
if changed {
p.touch();
}
}
Block::Table(t) => {
for row in &mut t.rows {
for cell in &mut row.cells {
if let Some(pic) = &mut cell.props.picture
&& let Some(k) = map(&pic.media)
{
pic.media = k;
}
todo.extend(cell.blocks.iter_mut().map(Arc::make_mut));
}
}
}
}
}
}
/// Collects media keys referenced by `root` and any nested graphic/group children iteratively.
fn collect_object_media<'a>(root: &'a InlineObject, out: &mut Vec<&'a str>) {
let mut todo = vec![root];
while let Some(o) = todo.pop() {
match o {
InlineObject::Image { media, .. } => out.push(media.as_str()),
InlineObject::Graphic { graphic, .. } => {
for item in &graphic.items {
if let wordcraft_doc::graphic::GraphicItem::Image { media, .. } = item {
out.push(media.as_str());
}
}
}
InlineObject::Group { children, .. } => {
for child in children.iter().rev() {
todo.push(&child.obj);
}
}
_ => {}
}
}
}
/// Collects media keys referenced by `table` across all cell pictures, paragraphs, and nested
/// tables in document order without recursion.
fn table_media_keys(table: &wordcraft_doc::table::Table) -> Vec<&str> {
enum Item<'a> {
Table(&'a wordcraft_doc::table::Table),
Block(&'a Block),
}
let mut keys = Vec::new();
let mut todo = vec![Item::Table(table)];
while let Some(item) = todo.pop() {
match item {
Item::Table(t) => {
for row in t.rows.iter().rev() {
for cell in row.cells.iter().rev() {
for block in cell.blocks.iter().rev() {
todo.push(Item::Block(block));
}
if let Some(pic) = &cell.props.picture {
keys.push(pic.media.as_str());
}
}
}
}
Item::Block(Block::Para(p)) => {
for o in &p.objects {
collect_object_media(o, &mut keys);
}
}
Item::Block(Block::Table(nested)) => {
todo.push(Item::Table(nested));
}
}
}
keys
}
/// A block's text (a table's cells in order), for matching blocks.
fn block_text(b: &Block, depth: usize) -> String {
match b {
Block::Para(p) => p.plain_text(),
Block::Table(t) if depth < wordcraft_doc::table::MAX_TABLE_DEPTH => {
Block::Table(t) if depth < 16 => {
t.rows.iter().flat_map(|r| r.cells.iter()).flat_map(|c| c.blocks.iter()).map(|x| block_text(x, depth + 1)).collect::<Vec<_>>().join("\t")
}
Block::Table(_) => String::new(),
}
}
/// Returns a copy of `b` with all text runs and paragraph marks across all nested table cells
/// updated by `f` iteratively, without recursion or depth truncation.
fn mark_block(b: &Block, f: &dyn Fn(&mut CharProps)) -> Block {
let mut out = b.clone();
let mut todo = vec![&mut out];
while let Some(blk) = todo.pop() {
match blk {
Block::Para(p) => {
let len = p.len();
let _ = p.format(0, len, f);
f(&mut p.mark);
p.touch();
}
Block::Table(t) => {
/// Returns a copy of `b` with all text runs and paragraph marks (or nested table cells) updated by `f`.
fn mark_block(b: &Block, f: &dyn Fn(&mut CharProps), depth: usize) -> Block {
match b {
Block::Para(p) => {
let mut p = p.clone();
let len = p.len();
let _ = p.format(0, len, f);
f(&mut p.mark);
Block::Para(p)
}
Block::Table(t) => {
let mut t = t.clone();
if depth < 16 {
for c in t.rows.iter_mut().flat_map(|r| r.cells.iter_mut()) {
todo.extend(c.blocks.iter_mut().map(Arc::make_mut));
c.blocks = c.blocks.iter().map(|x| Arc::new(mark_block(x, f, depth + 1))).collect();
}
}
Block::Table(t)
}
}
out
}
#[derive(Clone, Copy, Debug, PartialEq)]
@@ -919,7 +573,7 @@ fn para_exceeds_char_limit(p: &Paragraph, limit: usize) -> bool {
/// to `ctx.opts.characters`. When character-level diff is requested but either paragraph exceeds
/// [`MAX_CHAR_DIFF`] characters, falls back to word-level diff and increments `ctx.char_fallbacks`
/// so callers can discover the fallback.
fn word_diff(doc: &mut Document, a: &Paragraph, b: &Paragraph, ctx: &mut DiffCtx<'_>) -> Paragraph {
fn word_diff(doc: &Document, a: &Paragraph, b: &Paragraph, ctx: &mut DiffCtx<'_>) -> Paragraph {
let chars = if ctx.opts.characters {
if para_exceeds_char_limit(a, MAX_CHAR_DIFF) || para_exceeds_char_limit(b, MAX_CHAR_DIFF) {
*ctx.char_fallbacks = ctx.char_fallbacks.saturating_add(1);
@@ -933,14 +587,11 @@ fn word_diff(doc: &mut Document, a: &Paragraph, b: &Paragraph, ctx: &mut DiffCtx
let plain_revised = ctx.plain_revised;
let (ta, tb) = (tokens(a, chars), tokens(b, chars));
let (mut a_props, mut b_props) = (SideProps::new(a), SideProps::new(b));
let (ka, kb): (Vec<_>, Vec<_>) = {
let key = |t: &Tok<'_>| match t {
Tok::Text(t, _) => Key::Text(ctx.opts.key(t)),
Tok::Obj(o, _) => obj_key(doc, o),
};
(ta.iter().map(&key).collect(), tb.iter().map(&key).collect())
let key = |t: &Tok<'_>| match t {
Tok::Text(t, _) => Key::Text(ctx.opts.key(t)),
Tok::Obj(o, _) => obj_key(doc, o),
};
let ops = lcs_ops(&ka, &kb, ctx.budget);
let ops = lcs_ops(&ta.iter().map(key).collect::<Vec<_>>(), &tb.iter().map(key).collect::<Vec<_>>(), ctx.budget);
// Only at character granularity: a matched whole word almost never happens by coincidence,
// but a matched single character very often does (digits, punctuation), so only there does
// a short interior match need folding back into its surrounding edit.
@@ -952,7 +603,6 @@ fn word_diff(doc: &mut Document, a: &Paragraph, b: &Paragraph, ctx: &mut DiffCtx
// revised side, which carries no paragraph properties of its own, falls back to the original's,
// stripped the same way, so pre-existing revision state never leaks into the rebuilt paragraph.
p.props = if plain_revised && b.props.is_empty() { a.props.formatting() } else { b.props.formatting() };
p.props.fmt_change = fmt_prop_change(doc, ctx, a.props.formatting(), &p.props);
// The paragraph mark (the formatting typing into the paragraph's end would get) is the revised
// paragraph's when it comes from a document, and the original's when the revised side is plain
// text and has no mark of its own. Its own revision bookkeeping (`ins`, `del`, `fmt_change`)
@@ -962,7 +612,6 @@ fn word_diff(doc: &mut Document, a: &Paragraph, b: &Paragraph, ctx: &mut DiffCtx
} else {
CharProps { ins: None, del: None, fmt_change: None, ..b.mark.clone() }
};
p.mark.fmt_change = fmt_prop_change(doc, ctx, a.mark.formatting(), &p.mark.formatting());
let fallback = a.runs.first().map(|r| CharProps { ins: None, del: None, fmt_change: None, ..r.props.clone() }).unwrap_or_default();
let fallback_b = b.runs.first().map(|r| CharProps { ins: None, del: None, fmt_change: None, ..r.props.clone() }).unwrap_or_default();
let (mut i, mut j) = (0, 0);
@@ -972,18 +621,10 @@ fn word_diff(doc: &mut Document, a: &Paragraph, b: &Paragraph, ctx: &mut DiffCtx
// Equal as compared (perhaps up to case or spacing): the revised text, but the
// formatting of the run it stands for. For a document revised side that is the
// revised run, as issue #3749 prescribes ("Copy unchanged tokens from the revised
// paragraph with their own properties"), recording a formatting revision when
// `ctx.opts.formatting` is enabled so Reject All restores the original formatting;
// a plain-text revised side has no runs to speak of, so the original run's
// formatting is kept instead.
let old_props = output_props(&mut a_props, ta.get(i), &fallback);
let props = if plain_revised {
old_props
} else {
let mut p_b = output_props(&mut b_props, tb.get(j), &fallback_b);
p_b.fmt_change = fmt_prop_change(doc, ctx, old_props.formatting(), &p_b.formatting());
p_b
};
// paragraph with their own properties"); a plain-text revised side has no runs to
// speak of, so the original run's formatting is kept instead.
let props =
if plain_revised { output_props(&mut a_props, ta.get(i), &fallback) } else { output_props(&mut b_props, tb.get(j), &fallback_b) };
put(&mut p, tb.get(j), &props);
i += 1;
j += 1;
-786
View File
@@ -558,792 +558,6 @@ fn compare_keeps_text_boxes_of_the_original() {
}
}
struct TempTestDir(std::path::PathBuf);
impl TempTestDir {
fn new(prefix: &str) -> Self {
static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let dir = std::env::temp_dir().join(format!("{prefix}-{}-{id}", std::process::id()));
std::fs::create_dir_all(&dir).expect("create temp test dir");
Self(dir)
}
fn path(&self, name: &str) -> std::path::PathBuf {
self.0.join(name)
}
}
impl Drop for TempTestDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
/// #6086: When base and revised have an embedded image at identical size and extents,
/// but the media bytes were replaced, Compare must emit a tracked deletion of the base
/// image and tracked insertion of the revised image, and keep both media parts in the
/// result package.
#[test]
fn compare_detects_replaced_image_bytes_with_unchanged_extents() {
let tmp = TempTestDir::new("wc-compare-img-replace");
let make_doc = |bytes: Vec<u8>| -> Document {
let mut d = Document::new();
let key = d.add_media(bytes, "png");
let mut p = Paragraph::new();
let img = InlineObject::Image {
media: key,
w: 120.0,
h: 80.0,
alt: "photo".into(),
float: Default::default(),
crop: [0.0; 4],
fx: Default::default(),
ole: None,
};
p.insert_object(0, img, &CharProps::default()).unwrap();
d.body = vec![Arc::new(Block::Para(p))];
d
};
let base_png = vec![0x89, b'P', b'N', b'G', 1, 1, 1, 1];
let rev_png = vec![0x89, b'P', b'N', b'G', 2, 2, 2, 2];
let base_doc = make_doc(base_png.clone());
let rev_doc = make_doc(rev_png.clone());
let path = tmp.path("revised.docx");
crate::io::save_path(&path, &rev_doc).unwrap();
let mut s = Session::new(base_doc);
let r = s.run("review.compare", &json!({"path": path.to_string_lossy(), "showIn": "new"})).unwrap();
assert!(r["changes"].as_u64().unwrap() >= 1, "an image byte change must be detected as a change");
let p = s.doc.body[0].as_para().expect("body has paragraph");
assert_eq!(p.objects.len(), 2, "paragraph must have both deleted and inserted images");
let objs: Vec<(usize, &InlineObject)> = p.objects_with_offsets().collect();
assert_eq!(objs.len(), 2, "paragraph must have two objects with offsets");
let (off_del, del_img) = objs[0];
let (off_ins, ins_img) = objs[1];
let (InlineObject::Image { media: m_del, .. }, InlineObject::Image { media: m_ins, .. }) = (del_img, ins_img) else {
panic!("both objects must be images");
};
assert_ne!(m_del, m_ins, "deleted and inserted images must have distinct media keys");
assert!(p.props_of_char(off_del).del.is_some(), "base image must have del revision mark");
assert!(p.props_of_char(off_ins).ins.is_some(), "revised image must have ins revision mark");
assert_eq!(s.doc.media.get(m_del).map(|b| &**b), Some(&base_png));
assert_eq!(s.doc.media.get(m_ins).map(|b| &**b), Some(&rev_png));
// And saving to DOCX and reading back preserves both media files in the package.
let out_path = tmp.path("out.docx");
crate::io::save_path(&out_path, &s.doc).unwrap();
let back = crate::io::open_path(&out_path).unwrap();
assert!(back.media.values().any(|b| **b == base_png), "result package must contain base image bytes");
assert!(back.media.values().any(|b| **b == rev_png), "result package must contain revised image bytes");
// Identical image bytes at identical size: no changes emitted.
let base_doc_same = make_doc(base_png.clone());
let same_path = tmp.path("same.docx");
crate::io::save_path(&same_path, &make_doc(base_png.clone())).unwrap();
let mut s_same = Session::new(base_doc_same);
let r_same = s_same.run("review.compare", &json!({"path": same_path.to_string_lossy(), "showIn": "new"})).unwrap();
assert_eq!(r_same["changes"], 0, "comparing identical image bytes must emit no changes");
// Extensionless media in revised document adopts with .bin extension fallback and preserves payload.
let extless_bytes = vec![0xFF, 0xD8, 0xFF, 0xE0, 1, 2, 3, 4];
let mut rev_doc_extless = Document::new();
rev_doc_extless.media.insert("rawimage".into(), Arc::new(extless_bytes.clone()));
let mut p_extless = Paragraph::new();
p_extless
.insert_object(
0,
InlineObject::Image {
media: "rawimage".into(),
w: 120.0,
h: 80.0,
alt: "photo".into(),
float: Default::default(),
crop: [0.0; 4],
fx: Default::default(),
ole: None,
},
&CharProps::default(),
)
.unwrap();
rev_doc_extless.body = vec![Arc::new(Block::Para(p_extless))];
let extless_path = tmp.path("extless.json");
crate::io::save_path(&extless_path, &rev_doc_extless).unwrap();
let mut s_extless = Session::new(make_doc(base_png));
let _ = s_extless.run("review.compare", &json!({"path": extless_path.to_string_lossy(), "showIn": "new"})).unwrap();
let bin_entry = s_extless.doc.media.iter().find(|(k, _)| k.ends_with(".bin"));
assert!(bin_entry.is_some(), "extensionless media falls back to bin extension");
assert_eq!(bin_entry.map(|(_, b)| &***b), Some(&extless_bytes[..]));
// Media inside deeply nested groups is remapped iteratively without recursion limits.
let mut deep_obj = InlineObject::Image {
media: "deep_img.png".into(),
w: 50.0,
h: 50.0,
alt: "".into(),
float: Default::default(),
crop: [0.0; 4],
fx: Default::default(),
ole: None,
};
for _ in 0..20 {
deep_obj = InlineObject::Group {
w: 50.0,
h: 50.0,
float: Default::default(),
ch_w: 50.0,
ch_h: 50.0,
children: vec![wordcraft_doc::para::GroupChild { x: 0.0, y: 0.0, obj: deep_obj }],
canvas: None,
};
}
let mut map: std::collections::BTreeMap<String, String> = std::collections::BTreeMap::new();
map.insert("deep_img.png".into(), "image99.png".into());
super::compare::remap_object_media(&mut deep_obj, &mut |k| map.get(k).cloned());
let mut cur = &deep_obj;
while let InlineObject::Group { children, .. } = cur {
cur = &children[0].obj;
}
if let InlineObject::Image { media, .. } = cur {
assert_eq!(media, "image99.png", "media inside 20-level group must be remapped");
} else {
panic!("innermost object must be Image");
}
}
/// #6086: When an image replacement in a same-text paragraph triggers `word_diff`, matched text,
/// paragraph mark, and paragraph formatting changes must also record `fmt_change` revisions when
/// `formatting` is enabled so Reject All restores both the original formatting and the original
/// image, while Accept All keeps the revised formatting and revised image.
#[test]
fn compare_replaced_image_in_paragraph_tracks_matched_formatting_for_reject() {
let tmp = TempTestDir::new("wc-compare-img-para-fmt");
let base_png = vec![0x89, b'P', b'N', b'G', 7, 7, 7, 7];
let rev_png = vec![0x89, b'P', b'N', b'G', 8, 8, 8, 8];
let make_para_doc = |bytes: Vec<u8>, bold: Option<bool>, align: Option<wordcraft_doc::props::Align>, mark_italic: Option<bool>| -> Document {
let mut d = Document::new();
let key = d.add_media(bytes, "png");
let mut p = Paragraph::with_text("Logo", CharProps { bold, ..Default::default() });
p.props.align = align;
p.mark = CharProps { italic: mark_italic, ..Default::default() };
let at = p.len();
p.insert_object(
at,
InlineObject::Image {
media: key,
w: 120.0,
h: 80.0,
alt: "logo".into(),
float: Default::default(),
crop: [0.0; 4],
fx: Default::default(),
ole: None,
},
&CharProps::default(),
)
.unwrap();
d.body = vec![Arc::new(Block::Para(p))];
d
};
let base_doc = make_para_doc(base_png.clone(), None, None, None);
let rev_doc = make_para_doc(rev_png.clone(), Some(true), Some(wordcraft_doc::props::Align::Center), Some(true));
let rev_path = tmp.path("rev.docx");
crate::io::save_path(&rev_path, &rev_doc).unwrap();
let mut s = Session::new(base_doc.clone());
let r = s.run("review.compare", &json!({"path": rev_path.to_string_lossy(), "showIn": "new"})).unwrap();
assert_eq!(r["changes"], 1);
let p = s.doc.body[0].as_para().expect("compared paragraph");
assert_eq!(p.props_of_char(0).bold, Some(true), "matched text carries revised bold");
assert!(p.props_of_char(0).fmt_change.is_some(), "matched text carries formatting revision");
assert_eq!(p.props.align, Some(wordcraft_doc::props::Align::Center));
assert!(p.props.fmt_change.is_some(), "paragraph properties carry formatting revision");
assert_eq!(p.mark.italic, Some(true));
assert!(p.mark.fmt_change.is_some(), "paragraph mark carries formatting revision");
let objs: Vec<(usize, &InlineObject)> = p.objects_with_offsets().collect();
assert_eq!(objs.len(), 2);
assert!(p.props_of_char(objs[0].0).del.is_some());
assert!(p.props_of_char(objs[1].0).ins.is_some());
// Round-trip through DOCX before resolving both ways.
let cmp_path = tmp.path("compared.docx");
crate::io::save_path(&cmp_path, &s.doc).unwrap();
let reopened = crate::io::open_path(&cmp_path).unwrap();
let mut accepted = Session::new(reopened.clone());
accepted.run("review.acceptAll", &json!({})).unwrap();
let p_acc = accepted.doc.body[0].as_para().unwrap();
assert_eq!(p_acc.props_of_char(0).bold, Some(true));
assert!(p_acc.props_of_char(0).fmt_change.is_none());
assert_eq!(p_acc.props.align, Some(wordcraft_doc::props::Align::Center));
assert_eq!(p_acc.mark.italic, Some(true));
let objs_acc: Vec<(usize, &InlineObject)> = p_acc.objects_with_offsets().collect();
assert_eq!(objs_acc.len(), 1);
let InlineObject::Image { media: m_acc, .. } = objs_acc[0].1 else { panic!("expected image") };
assert_eq!(accepted.doc.media.get(m_acc).map(|b| &**b), Some(&rev_png));
let mut rejected = Session::new(reopened);
rejected.run("review.rejectAll", &json!({})).unwrap();
let p_rej = rejected.doc.body[0].as_para().unwrap();
assert_ne!(p_rej.props_of_char(0).bold, Some(true), "Reject All must restore original non-bold text");
assert!(p_rej.props_of_char(0).fmt_change.is_none());
assert_eq!(p_rej.props.align, None, "Reject All must restore original paragraph alignment");
assert_ne!(p_rej.mark.italic, Some(true), "Reject All must restore original paragraph mark");
let objs_rej: Vec<(usize, &InlineObject)> = p_rej.objects_with_offsets().collect();
assert_eq!(objs_rej.len(), 1);
let InlineObject::Image { media: m_rej, .. } = objs_rej[0].1 else { panic!("expected image") };
assert_eq!(rejected.doc.media.get(m_rej).map(|b| &**b), Some(&base_png), "Reject All must restore original image");
// With formatting disabled, image del/ins marks remain while formatting revisions are omitted.
let mut s_no_fmt = Session::new(base_doc);
let r_no_fmt = s_no_fmt.run("review.compare", &json!({"path": rev_path.to_string_lossy(), "showIn": "new", "formatting": false})).unwrap();
assert_eq!(r_no_fmt["changes"], 1);
let p_nf = s_no_fmt.doc.body[0].as_para().unwrap();
assert!(p_nf.props_of_char(0).fmt_change.is_none());
assert!(p_nf.props.fmt_change.is_none());
assert!(p_nf.mark.fmt_change.is_none());
let objs_nf: Vec<(usize, &InlineObject)> = p_nf.objects_with_offsets().collect();
assert_eq!(objs_nf.len(), 2);
assert!(p_nf.props_of_char(objs_nf[0].0).del.is_some());
assert!(p_nf.props_of_char(objs_nf[1].0).ins.is_some());
}
/// #6086: Replaced image bytes inside a table whose text is unchanged must be tracked in the
/// cell paragraph (not silently applied unmarked), survive DOCX save/reopen, and resolve to the
/// revised or original image under Accept All and Reject All.
#[test]
fn compare_detects_replaced_image_bytes_inside_unchanged_text_table() {
let tmp = TempTestDir::new("wc-compare-tbl-img-replace");
let make_table_doc = |bytes: Vec<u8>| -> Document {
let mut d = Document::new();
let key = d.add_media(bytes, "png");
let mut p = Paragraph::with_text("Logo", CharProps::default());
let at = p.len();
p.insert_object(
at,
InlineObject::Image {
media: key,
w: 120.0,
h: 80.0,
alt: "logo".into(),
float: Default::default(),
crop: [0.0; 4],
fx: Default::default(),
ole: None,
},
&CharProps::default(),
)
.unwrap();
let mut t = wordcraft_doc::table::Table::new(1, 1, 200.0);
t.rows[0].cells[0].blocks = vec![Arc::new(Block::Para(p))];
d.body = vec![Arc::new(Block::Table(t)), Arc::new(Block::Para(Paragraph::new()))];
d
};
fn cell_para(doc: &Document) -> &Paragraph {
let t = doc.body[0].as_table().expect("body holds 1x1 table");
assert_eq!(doc.body.iter().filter(|b| b.as_table().is_some()).count(), 1, "body keeps one table");
assert_eq!(t.rows.len(), 1);
assert_eq!(t.rows[0].cells.len(), 1);
t.rows[0].cells[0].blocks[0].as_para().expect("cell holds paragraph")
}
let base_png = vec![0x89, b'P', b'N', b'G', 10, 20, 30, 40];
let rev_png = vec![0x89, b'P', b'N', b'G', 50, 60, 70, 80];
let orphan_hdr_png = vec![0x89, b'P', b'N', b'G', 99, 98, 97, 96];
let base_doc = make_table_doc(base_png.clone());
let mut rev_doc = make_table_doc(rev_png.clone());
// Attach an uncompared header part referencing media that nothing in the body uses.
let hdr_key = rev_doc.add_media(orphan_hdr_png.clone(), "png");
let mut hdr_para = Paragraph::new();
hdr_para
.insert_object(
0,
InlineObject::Image {
media: hdr_key,
w: 40.0,
h: 40.0,
alt: "hdr".into(),
float: Default::default(),
crop: [0.0; 4],
fx: Default::default(),
ole: None,
},
&CharProps::default(),
)
.unwrap();
let hdr_part = rev_doc.add_part(wordcraft_doc::PartKind::Header, vec![Arc::new(Block::Para(hdr_para))]);
rev_doc.last_section.headers.default = Some(hdr_part);
let rev_path = tmp.path("tbl-rev.docx");
crate::io::save_path(&rev_path, &rev_doc).unwrap();
let mut s = Session::new(base_doc);
let r = s.run("review.compare", &json!({"path": rev_path.to_string_lossy(), "showIn": "new"})).unwrap();
assert_eq!(r["changes"], 1, "replaced image inside unchanged-text table must count as 1 change");
assert!(
!s.doc.media.values().any(|b| **b == orphan_hdr_png),
"unreferenced media from uncompared revised header parts must not stay in result media"
);
let check_tracked_cell = |doc: &Document| {
let p = cell_para(doc);
assert_eq!(p.plain_text(), "Logo");
let objs: Vec<(usize, &InlineObject)> = p.objects_with_offsets().collect();
assert_eq!(objs.len(), 2, "table cell must hold deleted base image and inserted revised image");
let (off_del, InlineObject::Image { media: m_del, .. }) = objs[0] else { panic!("expected base image") };
let (off_ins, InlineObject::Image { media: m_ins, .. }) = objs[1] else { panic!("expected revised image") };
assert_ne!(m_del, m_ins);
assert!(p.props_of_char(0).del.is_none() && p.props_of_char(0).ins.is_none(), "`Logo` text stays unmarked");
assert!(p.props_of_char(off_del).del.is_some(), "base table image must carry del mark");
assert!(p.props_of_char(off_ins).ins.is_some(), "revised table image must carry ins mark");
assert_eq!(doc.media.get(m_del).map(|b| &**b), Some(&base_png));
assert_eq!(doc.media.get(m_ins).map(|b| &**b), Some(&rev_png));
};
check_tracked_cell(&s.doc);
// Save compared result to DOCX and reopen: change marks and both payloads survive.
let cmp_path = tmp.path("tbl-cmp.docx");
crate::io::save_path(&cmp_path, &s.doc).unwrap();
let reopened = crate::io::open_path(&cmp_path).unwrap();
check_tracked_cell(&reopened);
// Accept All on reopened DOCX -> saves and reopens with only the revised image unmarked.
let mut accepted = Session::new(reopened.clone());
accepted.run("review.acceptAll", &json!({})).unwrap();
let acc_path = tmp.path("tbl-acc.docx");
crate::io::save_path(&acc_path, &accepted.doc).unwrap();
let acc_back = crate::io::open_path(&acc_path).unwrap();
let p_acc = cell_para(&acc_back);
assert_eq!(p_acc.plain_text(), "Logo");
let objs_acc: Vec<(usize, &InlineObject)> = p_acc.objects_with_offsets().collect();
assert_eq!(objs_acc.len(), 1, "Accept All must leave one image in the table cell");
let (off_acc, InlineObject::Image { media: m_acc, .. }) = objs_acc[0] else { panic!("expected image") };
assert!(p_acc.props_of_char(off_acc).ins.is_none() && p_acc.props_of_char(off_acc).del.is_none());
assert_eq!(acc_back.media.get(m_acc).map(|b| &**b), Some(&rev_png), "Accept All must keep revised image bytes");
// Reject All on reopened DOCX -> saves and reopens with only the original image unmarked.
let mut rejected = Session::new(reopened);
rejected.run("review.rejectAll", &json!({})).unwrap();
let rej_path = tmp.path("tbl-rej.docx");
crate::io::save_path(&rej_path, &rejected.doc).unwrap();
let rej_back = crate::io::open_path(&rej_path).unwrap();
let p_rej = cell_para(&rej_back);
assert_eq!(p_rej.plain_text(), "Logo");
let objs_rej: Vec<(usize, &InlineObject)> = p_rej.objects_with_offsets().collect();
assert_eq!(objs_rej.len(), 1, "Reject All must restore one image in the table cell");
let (off_rej, InlineObject::Image { media: m_rej, .. }) = objs_rej[0] else { panic!("expected image") };
assert!(p_rej.props_of_char(off_rej).ins.is_none() && p_rej.props_of_char(off_rej).del.is_none());
assert_eq!(rej_back.media.get(m_rej).map(|b| &**b), Some(&base_png), "Reject All must recover base image bytes");
// Identical image bytes inside an unchanged-text table: 0 changes and 1 unmarked image.
let same_tbl_path = tmp.path("tbl-same.docx");
crate::io::save_path(&same_tbl_path, &make_table_doc(base_png.clone())).unwrap();
let mut s_same = Session::new(make_table_doc(base_png));
let r_same = s_same.run("review.compare", &json!({"path": same_tbl_path.to_string_lossy(), "showIn": "new"})).unwrap();
assert_eq!(r_same["changes"], 0, "identical table image bytes must emit 0 changes");
assert_eq!(cell_para(&s_same.doc).objects.len(), 1);
}
/// #6086: Same-text tables up to `MAX_TABLE_DEPTH` recurse cell by cell for replaced media;
/// layout-only matches keep a single table as on `main`, while incompatible layouts or nesting
/// beyond `MAX_TABLE_DEPTH` with replaced media defer structural table changes and report `"tables"`
/// in `notHonoured` without leaving duplicate table shells.
#[test]
fn compare_table_image_replacement_handles_layout_fallbacks_and_max_depth() {
let tmp = TempTestDir::new("wc-compare-tbl-depth");
let base_png = vec![0x89, b'P', b'N', b'G', 10, 20, 30, 40];
let rev_png = vec![0x89, b'P', b'N', b'G', 50, 60, 70, 80];
let assert_single_table = |doc: &Document, want_rows: usize, want_cols: usize, label: &str| {
let tables: Vec<&wordcraft_doc::table::Table> = doc.body.iter().filter_map(|b| b.as_table()).collect();
assert_eq!(tables.len(), 1, "{label}: must keep a single table");
assert_eq!(tables[0].rows.len(), want_rows, "{label}: row count");
assert_eq!(tables[0].rows[0].cells.len(), want_cols, "{label}: col count");
};
// Reshaped tables (1x2 vs 2x1) with identical joined cell text and replaced image bytes:
// cannot diff 1-to-1 by cell, so structural table replacement is deferred with a single table
// and `"tables"` is reported in `notHonoured`.
let mut base_1x2 = Document::new();
let k1 = base_1x2.add_media(base_png.clone(), "png");
let mut p_c0 = Paragraph::with_text("Logo", CharProps::default());
let at_c0 = p_c0.len();
p_c0.insert_object(
at_c0,
InlineObject::Image {
media: k1,
w: 120.0,
h: 80.0,
alt: "logo".into(),
float: Default::default(),
crop: [0.0; 4],
fx: Default::default(),
ole: None,
},
&CharProps::default(),
)
.unwrap();
let mut t_1x2 = wordcraft_doc::table::Table::new(1, 2, 200.0);
t_1x2.rows[0].cells[0].blocks = vec![Arc::new(Block::Para(p_c0))];
t_1x2.rows[0].cells[1].blocks = vec![Arc::new(Block::Para(Paragraph::with_text("Caption", CharProps::default())))];
base_1x2.body = vec![Arc::new(Block::Table(t_1x2)), Arc::new(Block::Para(Paragraph::new()))];
let mut rev_2x1 = Document::new();
let k2 = rev_2x1.add_media(rev_png.clone(), "png");
let mut p_r0 = Paragraph::with_text("Logo", CharProps::default());
let at_r0 = p_r0.len();
p_r0.insert_object(
at_r0,
InlineObject::Image {
media: k2,
w: 120.0,
h: 80.0,
alt: "logo".into(),
float: Default::default(),
crop: [0.0; 4],
fx: Default::default(),
ole: None,
},
&CharProps::default(),
)
.unwrap();
let mut t_2x1 = wordcraft_doc::table::Table::new(2, 1, 200.0);
t_2x1.rows[0].cells[0].blocks = vec![Arc::new(Block::Para(p_r0))];
t_2x1.rows[1].cells[0].blocks = vec![Arc::new(Block::Para(Paragraph::with_text("Caption", CharProps::default())))];
rev_2x1.body = vec![Arc::new(Block::Table(t_2x1)), Arc::new(Block::Para(Paragraph::new()))];
let reshaped_path = tmp.path("tbl-reshaped.docx");
crate::io::save_path(&reshaped_path, &rev_2x1).unwrap();
let mut s_reshaped = Session::new(base_1x2);
let r_reshaped = s_reshaped.run("review.compare", &json!({"path": reshaped_path.to_string_lossy(), "showIn": "new"})).unwrap();
assert_eq!(r_reshaped["changes"], 0);
assert!(
r_reshaped["notHonoured"].as_array().unwrap().iter().any(|v| v == "tables"),
"incompatible reshaped table with replaced media must report `tables` in notHonoured"
);
let assert_table_image = |doc: &Document, expected: &[u8], label: &str| {
let t = doc.body.iter().find_map(|b| b.as_table()).expect("table");
let p = t.rows[0].cells[0].blocks[0].as_para().expect("cell para");
let objs: Vec<(usize, &InlineObject)> = p.objects_with_offsets().collect();
assert_eq!(objs.len(), 1, "{label}: expected single image");
let InlineObject::Image { media, .. } = objs[0].1 else { panic!("{label}: expected image") };
assert_eq!(doc.media.get(media).map(|b| b.as_slice()), Some(expected), "{label}: image payload");
};
assert_single_table(&s_reshaped.doc, 1, 2, "reshaped table compare");
assert_table_image(&s_reshaped.doc, &base_png, "reshaped table compare");
for cmd in ["review.acceptAll", "review.rejectAll"] {
let mut s_res = Session::new(s_reshaped.doc.clone());
s_res.run(cmd, &json!({})).unwrap();
assert_single_table(&s_res.doc, 1, 2, cmd);
assert_table_image(&s_res.doc, &base_png, cmd);
}
// Equal cell count but changed spans ([1, 2] vs [2, 1]):
// - with identical image (layout-only match): keeps single table with 0 changes and no fallback flag;
// - with replaced image: defers structural replacement and reports `tables` in notHonoured.
let make_span_doc = |spans: [u32; 2], bytes: Vec<u8>| -> Document {
let mut d = Document::new();
let k = d.add_media(bytes, "png");
let mut p = Paragraph::with_text("Logo", CharProps::default());
let at = p.len();
p.insert_object(
at,
InlineObject::Image {
media: k,
w: 120.0,
h: 80.0,
alt: "logo".into(),
float: Default::default(),
crop: [0.0; 4],
fx: Default::default(),
ole: None,
},
&CharProps::default(),
)
.unwrap();
let mut t = wordcraft_doc::table::Table::new(1, 3, 300.0);
t.rows[0].cells.truncate(2);
t.rows[0].cells[0].props.span = spans[0];
t.rows[0].cells[0].blocks = vec![Arc::new(Block::Para(p))];
t.rows[0].cells[1].props.span = spans[1];
t.rows[0].cells[1].blocks = vec![Arc::new(Block::Para(Paragraph::with_text("Caption", CharProps::default())))];
d.body = vec![Arc::new(Block::Table(t)), Arc::new(Block::Para(Paragraph::new()))];
d
};
let span_same_path = tmp.path("tbl-span-same.docx");
crate::io::save_path(&span_same_path, &make_span_doc([2, 1], base_png.clone())).unwrap();
let mut s_span_same = Session::new(make_span_doc([1, 2], base_png.clone()));
let r_span_same = s_span_same.run("review.compare", &json!({"path": span_same_path.to_string_lossy(), "showIn": "new"})).unwrap();
assert_eq!(r_span_same["changes"], 0, "layout-only span match keeps old single-table behavior");
assert!(!r_span_same["notHonoured"].as_array().unwrap().iter().any(|v| v == "tables"));
assert_single_table(&s_span_same.doc, 1, 2, "layout-only span match");
let span_diff_path = tmp.path("tbl-span-diff.docx");
crate::io::save_path(&span_diff_path, &make_span_doc([2, 1], rev_png.clone())).unwrap();
let mut s_span_diff = Session::new(make_span_doc([1, 2], base_png.clone()));
let r_span_diff = s_span_diff.run("review.compare", &json!({"path": span_diff_path.to_string_lossy(), "showIn": "new"})).unwrap();
assert_eq!(r_span_diff["changes"], 0);
assert!(r_span_diff["notHonoured"].as_array().unwrap().iter().any(|v| v == "tables"));
assert_single_table(&s_span_diff.doc, 1, 2, "incompatible span with replaced media");
assert_table_image(&s_span_diff.doc, &base_png, "incompatible span with replaced media");
let t_span = s_span_diff.doc.body[0].as_table().unwrap();
assert_eq!([t_span.rows[0].cells[0].span(), t_span.rows[0].cells[1].span()], [1, 2]);
// Nested tables up to MAX_TABLE_DEPTH (18 levels, leaf at depth 17) recursively retain one
// table per nesting level and track replaced image bytes at the leaf.
let make_nested_table_doc = |levels: usize, bytes: Vec<u8>| -> Document {
let mut d = Document::new();
let k = d.add_media(bytes, "png");
let mut p = Paragraph::with_text("Deep", CharProps::default());
let at = p.len();
p.insert_object(
at,
InlineObject::Image {
media: k,
w: 50.0,
h: 50.0,
alt: "deep".into(),
float: Default::default(),
crop: [0.0; 4],
fx: Default::default(),
ole: None,
},
&CharProps::default(),
)
.unwrap();
let mut blk = Block::Para(p);
for _ in 0..levels {
let mut t = wordcraft_doc::table::Table::new(1, 1, 200.0);
// Every OOXML table cell containing a nested table ends with a trailing paragraph.
t.rows[0].cells[0].blocks = vec![Arc::new(blk), Arc::new(Block::Para(Paragraph::new()))];
blk = Block::Table(t);
}
d.body = vec![Arc::new(blk), Arc::new(Block::Para(Paragraph::new()))];
d
};
let deep_path = tmp.path("tbl-deep.docx");
crate::io::save_path(&deep_path, &make_nested_table_doc(wordcraft_doc::table::MAX_TABLE_DEPTH, rev_png.clone())).unwrap();
let mut s_deep = Session::new(make_nested_table_doc(wordcraft_doc::table::MAX_TABLE_DEPTH, base_png.clone()));
let r_deep = s_deep.run("review.compare", &json!({"path": deep_path.to_string_lossy(), "showIn": "new"})).unwrap();
assert_eq!(r_deep["changes"], 1, "replaced image at MAX_TABLE_DEPTH must still be tracked");
assert!(!r_deep["notHonoured"].as_array().unwrap().iter().any(|v| v == "tables"));
let mut cur_blocks = &s_deep.doc.body;
for level in 0..wordcraft_doc::table::MAX_TABLE_DEPTH {
let lvl_tables: Vec<&wordcraft_doc::table::Table> = cur_blocks.iter().filter_map(|b| b.as_table()).collect();
assert_eq!(lvl_tables.len(), 1, "level {level} must retain one recursively diffed table");
cur_blocks = &lvl_tables[0].rows[0].cells[0].blocks;
}
let leaf_p = cur_blocks[0].as_para().expect("innermost cell holds leaf paragraph");
assert_eq!(leaf_p.plain_text(), "Deep");
let leaf_objs: Vec<(usize, &InlineObject)> = leaf_p.objects_with_offsets().collect();
assert_eq!(leaf_objs.len(), 2, "leaf at MAX_TABLE_DEPTH holds both deleted and inserted images");
let (off_d, InlineObject::Image { media: md, .. }) = leaf_objs[0] else { panic!("expected base leaf image") };
let (off_i, InlineObject::Image { media: mi, .. }) = leaf_objs[1] else { panic!("expected revised leaf image") };
assert!(leaf_p.props_of_char(off_d).del.is_some() && leaf_p.props_of_char(off_d).ins.is_none());
assert!(leaf_p.props_of_char(off_i).ins.is_some() && leaf_p.props_of_char(off_i).del.is_none());
assert_eq!(s_deep.doc.media.get(md).map(|b| &**b), Some(&base_png));
assert_eq!(s_deep.doc.media.get(mi).map(|b| &**b), Some(&rev_png));
// Beyond MAX_TABLE_DEPTH (19 nested tables, reaching depth == MAX_TABLE_DEPTH): defers structural
// replacement (single table, no duplicate empty shell) and reports `tables` in notHonoured.
let over_depth_path = tmp.path("tbl-over-depth.docx");
crate::io::save_path(&over_depth_path, &make_nested_table_doc(wordcraft_doc::table::MAX_TABLE_DEPTH + 1, rev_png.clone())).unwrap();
let mut s_over = Session::new(make_nested_table_doc(wordcraft_doc::table::MAX_TABLE_DEPTH + 1, base_png.clone()));
let r_over = s_over.run("review.compare", &json!({"path": over_depth_path.to_string_lossy(), "showIn": "new"})).unwrap();
assert_eq!(r_over["changes"], 0);
assert!(
r_over["notHonoured"].as_array().unwrap().iter().any(|v| v == "tables"),
"tables beyond MAX_TABLE_DEPTH with replaced media must report `tables` in notHonoured"
);
let mut over_blocks = &s_over.doc.body;
for _ in 0..wordcraft_doc::table::MAX_TABLE_DEPTH {
let lvl_tables: Vec<&wordcraft_doc::table::Table> = over_blocks.iter().filter_map(|b| b.as_table()).collect();
assert_eq!(lvl_tables.len(), 1);
over_blocks = &lvl_tables[0].rows[0].cells[0].blocks;
}
let cap_tables: Vec<&wordcraft_doc::table::Table> = over_blocks.iter().filter_map(|b| b.as_table()).collect();
assert_eq!(cap_tables.len(), 1, "at depth == MAX_TABLE_DEPTH, keeps single table without duplicate shell");
let over_leaf_p = cap_tables[0].rows[0].cells[0].blocks[0].as_para().expect("over-depth leaf para");
let over_leaf_objs: Vec<(usize, &InlineObject)> = over_leaf_p.objects_with_offsets().collect();
assert_eq!(over_leaf_objs.len(), 1, "over-depth table preserves single original image");
let InlineObject::Image { media: m_over, .. } = over_leaf_objs[0].1 else { panic!("expected over-depth image") };
assert_eq!(s_over.doc.media.get(m_over).map(|b| &**b), Some(&base_png));
}
/// #6086: Compatible tables with replaced media track table, row, and cell property differences
/// via undoable `fmt_change` revisions; image-free layout-only grid differences keep the old
/// single-table behavior without emitting two tables, and changed grid widths combined with
/// replaced media defer structural replacement when `formatting` is enabled (reporting `"tables"`
/// in `notHonoured`) while tracking the replaced media when `formatting` is false.
#[test]
fn compare_unchanged_text_table_tracks_table_row_cell_props_and_grid_widths() {
let tmp = TempTestDir::new("wc-compare-tbl-props");
let base_png = vec![0x89, b'P', b'N', b'G', 11, 22, 33, 44];
let rev_png = vec![0x89, b'P', b'N', b'G', 55, 66, 77, 88];
let make_styled_table_doc = |bytes: Vec<u8>, styled: bool, width: f32| -> Document {
let mut d = Document::new();
let k = d.add_media(bytes, "png");
let mut p = Paragraph::with_text("Logo", CharProps::default());
let at = p.len();
p.insert_object(
at,
InlineObject::Image {
media: k,
w: 100.0,
h: 60.0,
alt: "logo".into(),
float: Default::default(),
crop: [0.0; 4],
fx: Default::default(),
ole: None,
},
&CharProps::default(),
)
.unwrap();
let mut t = wordcraft_doc::table::Table::new(1, 1, width);
if styled {
t.props.align = Some(wordcraft_doc::props::Align::Center);
t.rows[0].props.cant_split = true;
t.rows[0].cells[0].props.shading = Some(wordcraft_doc::props::Rgb(0xEE, 0xFF, 0xDD));
}
t.rows[0].cells[0].blocks = vec![Arc::new(Block::Para(p))];
d.body = vec![Arc::new(Block::Table(t)), Arc::new(Block::Para(Paragraph::new()))];
d
};
let rev_styled_path = tmp.path("rev-styled.docx");
crate::io::save_path(&rev_styled_path, &make_styled_table_doc(rev_png.clone(), true, 200.0)).unwrap();
let mut s = Session::new(make_styled_table_doc(base_png.clone(), false, 200.0));
let r = s.run("review.compare", &json!({"path": rev_styled_path.to_string_lossy(), "showIn": "new"})).unwrap();
assert_eq!(r["changes"], 4, "table, row, cell property changes + replaced cell image count as 4 changes");
assert!(!r["notHonoured"].as_array().unwrap().iter().any(|v| v == "tables"));
let t = s.doc.body[0].as_table().unwrap();
assert!(t.props.fmt_change.is_some(), "table property change recorded");
assert!(t.rows[0].props.fmt_change.is_some(), "row property change recorded");
assert!(t.rows[0].cells[0].props.fmt_change.is_some(), "cell property change recorded");
let cmp_styled_path = tmp.path("cmp-styled.docx");
crate::io::save_path(&cmp_styled_path, &s.doc).unwrap();
let reopened = crate::io::open_path(&cmp_styled_path).unwrap();
let mut accepted = Session::new(reopened.clone());
accepted.run("review.acceptAll", &json!({})).unwrap();
let t_acc = accepted.doc.body[0].as_table().unwrap();
assert_eq!(t_acc.props.align, Some(wordcraft_doc::props::Align::Center));
assert!(t_acc.rows[0].props.cant_split);
assert_eq!(t_acc.rows[0].cells[0].props.shading, Some(wordcraft_doc::props::Rgb(0xEE, 0xFF, 0xDD)));
let mut rejected = Session::new(reopened);
rejected.run("review.rejectAll", &json!({})).unwrap();
let t_rej = rejected.doc.body[0].as_table().unwrap();
assert_eq!(t_rej.props.align, None, "Reject All restores original table alignment");
assert!(!t_rej.rows[0].props.cant_split, "Reject All restores original row cant_split");
assert_eq!(t_rej.rows[0].cells[0].props.shading, None, "Reject All restores original cell shading");
let p_rej = t_rej.rows[0].cells[0].blocks[0].as_para().unwrap();
let objs_rej: Vec<(usize, &InlineObject)> = p_rej.objects_with_offsets().collect();
assert_eq!(objs_rej.len(), 1);
let InlineObject::Image { media: m_rej, .. } = objs_rej[0].1 else { panic!("expected image") };
assert_eq!(rejected.doc.media.get(m_rej).map(|b| &**b), Some(&base_png));
// Layout/formatting-only differences with identical media keep single-table behavior.
let rev_fmt_only_path = tmp.path("rev-fmt-only.docx");
crate::io::save_path(&rev_fmt_only_path, &make_styled_table_doc(base_png.clone(), true, 200.0)).unwrap();
let mut s_no_fmt = Session::new(make_styled_table_doc(base_png.clone(), false, 200.0));
let r_no_fmt =
s_no_fmt.run("review.compare", &json!({"path": rev_fmt_only_path.to_string_lossy(), "showIn": "new", "formatting": false})).unwrap();
assert_eq!(r_no_fmt["changes"], 0);
assert_eq!(s_no_fmt.doc.body.iter().filter(|b| b.as_table().is_some()).count(), 1);
// Image-free table with identical cell text and only a changed column width:
// keeps the old single-table behavior without emitting two tables or empty shells.
let make_grid_doc = |width: f32| -> Document {
let mut d = Document::new();
let mut t = wordcraft_doc::table::Table::new(1, 1, width);
t.rows[0].cells[0].blocks = vec![Arc::new(Block::Para(Paragraph::with_text("Cell", CharProps::default())))];
d.body = vec![Arc::new(Block::Table(t)), Arc::new(Block::Para(Paragraph::new()))];
d
};
let grid_path = tmp.path("rev-grid.docx");
crate::io::save_path(&grid_path, &make_grid_doc(260.0)).unwrap();
let mut s_grid = Session::new(make_grid_doc(200.0));
let r_grid = s_grid.run("review.compare", &json!({"path": grid_path.to_string_lossy(), "showIn": "new"})).unwrap();
assert_eq!(r_grid["changes"], 0, "image-free grid width match keeps old single-table behavior");
assert!(!r_grid["notHonoured"].as_array().unwrap().iter().any(|v| v == "tables"));
let assert_single_grid_table = |doc: &Document| {
let tables: Vec<&wordcraft_doc::table::Table> = doc.body.iter().filter_map(|b| b.as_table()).collect();
assert_eq!(tables.len(), 1, "must keep a single table with no duplicate empty shell");
assert_eq!(tables[0].grid, vec![260.0]);
let p = tables[0].rows[0].cells[0].blocks[0].as_para().unwrap();
assert_eq!(p.plain_text(), "Cell");
assert!(p.runs.iter().all(|r| r.props.ins.is_none() && r.props.del.is_none()));
};
assert_single_grid_table(&s_grid.doc);
for cmd in ["review.acceptAll", "review.rejectAll"] {
let mut s_res = Session::new(s_grid.doc.clone());
s_res.run(cmd, &json!({})).unwrap();
assert_single_grid_table(&s_res.doc);
}
let cmp_grid_path = tmp.path("cmp-grid.docx");
crate::io::save_path(&cmp_grid_path, &s_grid.doc).unwrap();
let reopened_grid = crate::io::open_path(&cmp_grid_path).unwrap();
for cmd in ["review.acceptAll", "review.rejectAll"] {
let mut s_res = Session::new(reopened_grid.clone());
s_res.run(cmd, &json!({})).unwrap();
assert_single_grid_table(&s_res.doc);
}
// Replaced image + changed column grid width:
// - with formatting enabled: incompatible grid width defers structural change and reports `tables`;
// - with formatting disabled: tracks the replaced image in the single table.
let grid_img_path = tmp.path("rev-grid-img.docx");
crate::io::save_path(&grid_img_path, &make_styled_table_doc(rev_png.clone(), false, 260.0)).unwrap();
let mut s_grid_img = Session::new(make_styled_table_doc(base_png.clone(), false, 200.0));
let r_grid_img = s_grid_img.run("review.compare", &json!({"path": grid_img_path.to_string_lossy(), "showIn": "new"})).unwrap();
assert_eq!(r_grid_img["changes"], 0);
assert!(r_grid_img["notHonoured"].as_array().unwrap().iter().any(|v| v == "tables"));
assert_eq!(s_grid_img.doc.body.iter().filter(|b| b.as_table().is_some()).count(), 1);
let t_grid_img = s_grid_img.doc.body[0].as_table().unwrap();
assert_eq!(t_grid_img.grid, vec![200.0], "unsupported grid+media fallback preserves original table grid");
let assert_grid_base_img = |doc: &Document, label: &str| {
let p = doc.body[0].as_table().unwrap().rows[0].cells[0].blocks[0].as_para().unwrap();
let objs: Vec<(usize, &InlineObject)> = p.objects_with_offsets().collect();
assert_eq!(objs.len(), 1, "{label}");
let InlineObject::Image { media, .. } = objs[0].1 else { panic!("expected image") };
assert_eq!(doc.media.get(media).map(|b| &**b), Some(&base_png), "{label}");
};
assert_grid_base_img(&s_grid_img.doc, "unsupported grid+media fallback preserves original image");
let mut s_grid_img_kept = Session::new(s_grid_img.doc.clone());
s_grid_img_kept.run("review.rejectAll", &json!({})).unwrap();
assert_grid_base_img(&s_grid_img_kept.doc, "unsupported grid+media rejectAll keeps original image");
let mut s_grid_img_nf = Session::new(make_styled_table_doc(base_png.clone(), false, 200.0));
let r_grid_img_nf =
s_grid_img_nf.run("review.compare", &json!({"path": grid_img_path.to_string_lossy(), "showIn": "new", "formatting": false})).unwrap();
assert_eq!(r_grid_img_nf["changes"], 1, "with formatting false, replaced image inside grid-changed table is tracked");
assert!(!r_grid_img_nf["notHonoured"].as_array().unwrap().iter().any(|v| v == "tables"));
assert_eq!(s_grid_img_nf.doc.body.iter().filter(|b| b.as_table().is_some()).count(), 1);
let mut s_grid_img_rej = Session::new(s_grid_img_nf.doc.clone());
s_grid_img_rej.run("review.rejectAll", &json!({})).unwrap();
let p_grid_rej = s_grid_img_rej.doc.body[0].as_table().unwrap().rows[0].cells[0].blocks[0].as_para().unwrap();
let objs_grid_rej: Vec<(usize, &InlineObject)> = p_grid_rej.objects_with_offsets().collect();
assert_eq!(objs_grid_rej.len(), 1);
let InlineObject::Image { media: m_grid_rej, .. } = objs_grid_rej[0].1 else { panic!("expected image") };
assert_eq!(s_grid_img_rej.doc.media.get(m_grid_rej).map(|b| &**b), Some(&base_png));
}
#[test]
fn compare_with_a_revised_file_keeps_its_text_boxes_backed() {
// Text boxes in both documents, the revised one from a file: every anchor in the result
+1 -16
View File
@@ -443,22 +443,7 @@ impl Session {
crate::cmd::outline::after_command(self, sel_before, self.rev != rev_before);
// Extra selected objects last until something else is edited or selected; formatting
// them keeps them selected, as in Word.
let keeps_multi_select = matches!(id, "select.addObject" | "arrange.ungroup")
|| (self.sel == *sel_before
&& matches!(
id,
"shape.fill"
| "shape.effects"
| "shape.outline"
| "shape.size"
| "shape.rotation"
| "picture.size"
| "arrange.rotate"
| "arrange.rotation"
| "shape.alignText"
| "shape.textDirection"
));
if !keeps_multi_select && (spec.mutates || self.sel != *sel_before) {
if !matches!(id, "select.addObject" | "arrange.ungroup" | "shape.fill" | "shape.effects") && (spec.mutates || self.sel != *sel_before) {
self.also_selected.clear();
}
// A canvas member stays picked while its canvas does and nothing else is selected.
+4 -653
View File
@@ -20,7 +20,6 @@ mod fonts;
mod ime_noop;
mod page_number_formats_in_lists;
mod para_tools;
mod paste_table_in_cell;
mod revision_checks;
mod typing;
mod wordart;
@@ -1663,9 +1662,10 @@ fn copying_puts_rtf_on_the_clipboard() {
assert!(r["rtf"].as_str().is_some_and(|t| t.starts_with("{\\rtf1") && t.contains("bold")), "{r}");
assert_eq!(text(&s).lines().next(), Some("plain "));
// Nothing selected: Copy is refused, so nothing is copied.
// Nothing selected: nothing copied, no RTF.
run(&mut s, "caret.docEnd", json!({}));
assert!(s.run("edit.copy", &json!({})).is_err(), "Copy with nothing selected");
let r = run(&mut s, "edit.copy", json!({}));
assert!(r.get("rtf").is_none(), "{r}");
}
#[test]
@@ -2070,205 +2070,6 @@ fn paste_keeps_source_formatting_from_other_programs() {
assert_eq!(props_at(&s, 4).italic, Some(true));
}
/// Verify that pasting syntax-highlighted code from VS Code retains syntax colors and font styling
/// without inheriting dark background shading strips from outer container elements (#6157).
#[test]
fn pasted_code_from_vscode_has_syntax_colors_and_no_character_shading() {
// #6157: VS Code wraps copied code in an outer div with `background-color: #1e1e1e`.
// In Word and per CSS (background-color does not inherit), pasting into a document keeps the
// syntax colors and mono font without painting dark character shading strips over the runs.
let mut s = s();
let vscode_html = r#"<div style="color: #d4d4d4;background-color: #1e1e1e;font-family: Consolas, 'Courier New', monospace;font-weight: normal;font-size: 14px;line-height: 19px;white-space: pre;"><div><span style="color: #569cd6;">const</span><span style="color: #d4d4d4;"> x = </span><span style="color: #b5cea8;">1</span><span style="color: #d4d4d4;">;</span></div></div>"#;
run(&mut s, "edit.paste", json!({"text": "const x = 1;", "html": vscode_html}));
assert_eq!(text(&s), "const x = 1;");
let p = s.doc.para_at(&s.sel.focus).unwrap();
for r in &p.runs {
assert_eq!(r.props.shading, None, "character should have no shading from container div");
}
assert_eq!(p.props.shading, Some(wordcraft_doc::Rgb(0x1e, 0x1e, 0x1e)), "container background is kept as paragraph shading");
assert!(p.runs.iter().any(|r| r.props.color == Some(wordcraft_doc::TextColor::Rgb(wordcraft_doc::Rgb(0x56, 0x9c, 0xd6)))));
}
/// A multi-block paste keeps the first pasted paragraph's shading when the destination has its own properties (#6157).
#[test]
fn multi_block_paste_keeps_first_paragraph_shading() {
let mut s = s();
run(&mut s, "para.align", json!({"value": "center"}));
let html = r#"<div style="background-color:#1e1e1e"><p>one</p><p>two</p></div>"#;
run(&mut s, "edit.paste", json!({"text": "one\ntwo", "html": html}));
assert_eq!(text(&s), "one\ntwo");
let p = s.doc.body.first().and_then(|b| b.as_para()).unwrap();
assert_eq!(p.props.shading, Some(wordcraft_doc::Rgb(0x1e, 0x1e, 0x1e)), "first pasted paragraph keeps its shading");
}
/// A destination paragraph whose style shades keeps that shading when a shaded paragraph is pasted (#6157).
#[test]
fn paste_keeps_destination_style_shading() {
let mut s = s();
Arc::make_mut(&mut s.doc.styles).upsert(wordcraft_doc::Style {
id: "Shaded".into(),
name: "Shaded".into(),
kind: wordcraft_doc::StyleKind::Paragraph,
based_on: Some("Normal".into()),
para: wordcraft_doc::props::ParaProps { shading: Some(wordcraft_doc::Rgb(0x22, 0x22, 0x22)), ..Default::default() },
..Default::default()
});
run(&mut s, "para.style", json!({"style": "Shaded"}));
let html = r#"<div style="background-color:#1e1e1e"><span>text</span></div>"#;
run(&mut s, "edit.paste", json!({"text": "text", "html": html}));
let p = s.doc.body.first().and_then(|b| b.as_para()).unwrap();
assert_eq!(p.props.shading, None, "source shading must not override the destination style");
assert_eq!(
s.doc.styles.resolve_para(&p.props).shading,
Some(wordcraft_doc::Rgb(0x22, 0x22, 0x22)),
"destination style shading remains effective"
);
}
/// Multi-line VS Code paste keeps removable paragraph shading rather than stuck character shading,
/// so Shading › No Color, Clear All Formatting, and Merge Formatting all clear the dark background (#6157).
#[test]
fn pasted_code_from_vscode_shading_is_removable() {
let vscode_html = concat!(
r#"<div style="color: #d4d4d4;background-color: #1e1e1e;font-family: Consolas, 'Courier New', monospace;font-size: 14px;white-space: pre;">"#,
r#"<div><span style="color: #569cd6;">const</span><span style="color: #d4d4d4;"> a = 1;</span></div>"#,
r#"<div><span style="color: #569cd6;">const</span><span style="color: #d4d4d4;"> b = 2;</span></div>"#,
r#"</div>"#,
);
let plain = "const a = 1;\nconst b = 2;";
// Home › Paragraph › Shading › No Color removes the dark background across all pasted lines.
let mut s = self::s();
run(&mut s, "edit.paste", json!({"text": plain, "html": vscode_html}));
assert_eq!(s.doc.body.len(), 2);
for b in &s.doc.body {
let p = b.as_para().unwrap();
assert_eq!(p.props.shading, Some(wordcraft_doc::Rgb(0x1e, 0x1e, 0x1e)));
assert!(p.runs.iter().all(|r| r.props.shading.is_none()));
}
run(&mut s, "select.all", json!({}));
run(&mut s, "para.shading", json!({"color": null}));
for b in &s.doc.body {
let p = b.as_para().unwrap();
assert_eq!(p.props.shading, None, "Shading › No Color clears the container background");
assert!(p.runs.iter().all(|r| r.props.shading.is_none()));
}
// Clear All Formatting clears both the dark paragraph shading and light syntax colors.
let mut s = self::s();
run(&mut s, "edit.paste", json!({"text": plain, "html": vscode_html}));
run(&mut s, "select.all", json!({}));
run(&mut s, "format.clear", json!({}));
for b in &s.doc.body {
let p = b.as_para().unwrap();
assert_eq!(p.props.shading, None);
assert!(p.runs.iter().all(|r| r.props.shading.is_none() && r.props.color.is_none()));
}
// Paste › Merge Formatting drops the dark container background and light text colors up front.
let mut s = self::s();
run(&mut s, "edit.pasteMerge", json!({"text": plain, "html": vscode_html}));
for b in &s.doc.body {
let p = b.as_para().unwrap();
assert_eq!(p.props.shading, None);
assert!(p.runs.iter().all(|r| r.props.shading.is_none() && r.props.color.is_none()));
}
}
/// Copying a paragraph shaded via its style writes `background-color` to the clipboard HTML (#6157).
#[test]
fn copy_exports_style_inherited_paragraph_shading_to_clipboard_html() {
let mut s = s();
Arc::make_mut(&mut s.doc.styles).upsert(wordcraft_doc::Style {
id: "CodeBlock".into(),
name: "Code Block".into(),
kind: wordcraft_doc::StyleKind::Paragraph,
based_on: Some("Normal".into()),
para: wordcraft_doc::props::ParaProps { shading: Some(wordcraft_doc::Rgb(0x1e, 0x1e, 0x1e)), ..Default::default() },
..Default::default()
});
run(&mut s, "document.setText", json!({"text": "const x = 1;"}));
run(&mut s, "para.style", json!({"style": "CodeBlock"}));
run(&mut s, "select.all", json!({}));
let r = run(&mut s, "edit.copy", json!({}));
let html = r["html"].as_str().unwrap_or_default();
assert!(html.contains("background-color:#1E1E1E"), "clipboard HTML carries style paragraph shading: {html}");
let mut dst = self::s();
run(&mut dst, "edit.paste", json!({"text": "const x = 1;", "html": html, "privateClipboard": false}));
let p = dst.doc.body.first().and_then(|b| b.as_para()).unwrap();
assert_eq!(p.props.shading, Some(wordcraft_doc::Rgb(0x1e, 0x1e, 0x1e)));
}
/// Pasting a single inline-highlighted word into the middle of an unshaded paragraph keeps run
/// shading on that word alone and leaves the destination paragraph unshaded (#6157).
#[test]
fn pasting_inline_highlighted_word_mid_paragraph_keeps_run_shading_only() {
for (html, want) in [
(r#"<span style="background-color:yellow">word</span>"#, wordcraft_doc::Rgb(0xff, 0xff, 0x00)),
(r"<mark>word</mark>", wordcraft_doc::Rgb(0xff, 0xff, 0x00)),
(r#"<code style="background-color:#eeeeee">word</code>"#, wordcraft_doc::Rgb(0xee, 0xee, 0xee)),
] {
let mut s = self::s();
run(&mut s, "document.setText", json!({"text": "before after"}));
run(&mut s, "select.range", json!({"anchor": {"block": 0, "off": 7}, "focus": {"block": 0, "off": 7}}));
run(&mut s, "edit.paste", json!({"text": "word", "html": html}));
assert_eq!(text(&s), "before word after", "{html}");
let p = s.doc.body.first().and_then(|b| b.as_para()).unwrap();
assert_eq!(p.props.shading, None, "destination paragraph stays unshaded: {html}");
assert_eq!(p.props_of_char(0).shading, None, "{html}");
assert_eq!(p.props_of_char(7).shading, Some(want), "pasted word keeps run shading: {html}");
assert_eq!(p.props_of_char(12).shading, None, "{html}");
}
}
/// Pasting a container-wrapped one-line snippet (no paragraph break) into the middle of a
/// paragraph leaves the destination paragraph unshaded (#6157).
#[test]
fn container_wrapped_one_line_paste_mid_paragraph_leaves_paragraph_unshaded() {
let mut s = self::s();
run(&mut s, "document.setText", json!({"text": "Call now."}));
run(&mut s, "select.range", json!({"anchor": {"block": 0, "off": 5}, "focus": {"block": 0, "off": 5}}));
let vscode_html = r#"<div style="color: #d4d4d4;background-color: #1e1e1e;font-family: Consolas, 'Courier New', monospace;font-size: 14px;white-space: pre;"><span style="color: #569cd6;">foo</span></div>"#;
run(&mut s, "edit.paste", json!({"text": "foo", "html": vscode_html}));
assert_eq!(text(&s), "Call foo now.");
let p = s.doc.body.first().and_then(|b| b.as_para()).unwrap();
assert_eq!(p.props.shading, None, "destination paragraph stays unshaded");
assert_eq!(p.props_of_char(0).shading, None);
assert_eq!(p.props_of_char(5).shading, None);
}
/// Under Track Changes, rejecting a paste restores the destination paragraph formatting (#6157).
#[test]
fn tracked_paste_reject_restores_destination_paragraph_shading() {
let mut s = self::s();
run(&mut s, "document.setText", json!({"text": "Call now."}));
run(&mut s, "review.trackChanges", json!({"enabled": true}));
run(&mut s, "select.range", json!({"anchor": {"block": 0, "off": 5}, "focus": {"block": 0, "off": 5}}));
let vscode_html = r#"<div style="color: #d4d4d4;background-color: #1e1e1e;font-family: Consolas, 'Courier New', monospace;font-size: 14px;white-space: pre;"><span style="color: #569cd6;">foo</span></div>"#;
run(&mut s, "edit.paste", json!({"text": "foo", "html": vscode_html}));
assert_eq!(text(&s), "Call foo now.");
let p = s.doc.body.first().and_then(|b| b.as_para()).unwrap();
assert_eq!(p.props.shading, None);
run(&mut s, "review.rejectAll", json!({}));
assert_eq!(text(&s), "Call now.");
let p_after = s.doc.body.first().and_then(|b| b.as_para()).unwrap();
assert_eq!(p_after.props.shading, None, "rejecting paste leaves paragraph unshaded");
// Also verify that pasting into an empty paragraph under Track Changes restores the empty
// paragraph's unshaded state on Reject All.
let mut s2 = self::s();
run(&mut s2, "review.trackChanges", json!({"enabled": true}));
run(&mut s2, "edit.paste", json!({"text": "foo", "html": vscode_html}));
assert_eq!(text(&s2), "foo");
let p2 = s2.doc.body.first().and_then(|b| b.as_para()).unwrap();
assert_eq!(p2.props.shading, Some(wordcraft_doc::Rgb(0x1e, 0x1e, 0x1e)));
run(&mut s2, "review.rejectAll", json!({}));
assert_eq!(text(&s2), "");
let p2_after = s2.doc.body.first().and_then(|b| b.as_para()).unwrap();
assert_eq!(p2_after.props.shading, None, "rejecting paste into empty paragraph clears paragraph shading");
}
/// A CF_HTML ("HTML Format") clipboard payload around `html`, with the byte offsets Windows writes.
fn cf_html(html: &str) -> String {
let n = "Version:1.0\r\nStartHTML:0000000000\r\nEndHTML:0000000000\r\nStartFragment:0000000000\r\nEndFragment:0000000000\r\n".len();
@@ -2616,122 +2417,6 @@ fn copy_whole_table_pastes_a_table() {
assert_eq!(body_table_cells(&s), vec![want.clone(), want]);
}
/// #5906: Copying select-all in a document starting with a table must preserve the table.
#[test]
fn select_all_in_document_starting_with_table_preserves_table() {
let mut s = s();
run(&mut s, "insert.table", json!({"rows": 2, "cols": 2}));
run(&mut s, "text.insert", json!({"text": "A1"}));
run(&mut s, "select.all", json!({"whole": true}));
run(&mut s, "edit.copy", json!({}));
let clip = s.clipboard.as_ref().unwrap();
assert!(
clip.blocks.iter().any(|b| matches!(b, wordcraft_doc::Block::Table(_))),
"copying select-all in a document starting with a table must preserve table structure, got {:?}",
clip.blocks
);
let table = clip
.blocks
.iter()
.find_map(|b| match b {
wordcraft_doc::Block::Table(t) => Some(t),
_ => None,
})
.expect("table block in clipboard");
assert_eq!(table.rows.len(), 2, "copied table row count");
assert_eq!(table.cols(), 2, "copied table col count");
let c00 = table.rows[0].cells[0].blocks.first().and_then(|b| match &**b {
wordcraft_doc::Block::Para(p) => Some(p.text.as_str()),
_ => None,
});
assert_eq!(c00, Some("A1"), "cell (0, 0) text");
}
/// #5906: Cut and Spike across table cells with non-corner endpoints must preserve every removed character.
#[test]
fn cut_and_spike_across_table_cells_preserves_every_removed_character() {
// 1. Test Spike then insertSpike
{
let mut s = s();
run(&mut s, "insert.table", json!({"rows": 3, "cols": 3}));
for (i, text) in ["R0C0", "R0C1", "R0C2", "R1C0", "R1C1", "R1C2", "R2C0", "R2C1", "R2C2"].iter().enumerate() {
if i > 0 {
run(&mut s, "text.tab", json!({}));
}
run(&mut s, "text.insert", json!({"text": text}));
}
// Set linear text range across non-corner cells: (0, 1) off 1 ("0C1") through (1, 1) off 3 ("R1C").
// Traversed in linear document order: (0, 1) "0C1", (0, 2) "R0C2", (1, 0) "R1C0", (1, 1) "R1C".
s.sel = crate::Selection {
anchor: wordcraft_doc::Pos { story: wordcraft_doc::StoryRef::Body, path: wordcraft_doc::Path(vec![0, 0, 1, 0]), off: 1 },
focus: wordcraft_doc::Pos { story: wordcraft_doc::StoryRef::Body, path: wordcraft_doc::Path(vec![0, 1, 1, 0]), off: 3 },
};
s.column = None;
run(&mut s, "edit.spike", json!({}));
// Verify the table content after spike:
// (0, 1) has "R" remaining, (0, 2) emptied, (1, 0) emptied, (1, 1) has "1" remaining.
let cells_after = body_table_cells(&s);
assert_eq!(
cells_after,
vec![vec!["R0C0".to_string(), "R".into(), "".into(), "".into(), "1".into(), "R1C2".into(), "R2C0".into(), "R2C1".into(), "R2C2".into(),]]
);
// Paste the spike at the end of the document: all 4 removed pieces must be present.
run(&mut s, "caret.docEnd", json!({}));
run(&mut s, "edit.insertSpike", json!({}));
let texts = body_texts(&s);
assert!(
texts.iter().any(|t| t == "0C1")
&& texts.iter().any(|t| t == "R0C2")
&& texts.iter().any(|t| t == "R1C0")
&& texts.iter().any(|t| t == "R1C"),
"every removed character must be preserved and inserted from spike, got: {:?}",
texts
);
}
// 2. Test Cut then paste
{
let mut s = s();
run(&mut s, "insert.table", json!({"rows": 3, "cols": 3}));
for (i, text) in ["R0C0", "R0C1", "R0C2", "R1C0", "R1C1", "R1C2", "R2C0", "R2C1", "R2C2"].iter().enumerate() {
if i > 0 {
run(&mut s, "text.tab", json!({}));
}
run(&mut s, "text.insert", json!({"text": text}));
}
s.sel = crate::Selection {
anchor: wordcraft_doc::Pos { story: wordcraft_doc::StoryRef::Body, path: wordcraft_doc::Path(vec![0, 0, 1, 0]), off: 1 },
focus: wordcraft_doc::Pos { story: wordcraft_doc::StoryRef::Body, path: wordcraft_doc::Path(vec![0, 1, 1, 0]), off: 3 },
};
s.column = None;
run(&mut s, "edit.cut", json!({}));
let cells_after_cut = body_table_cells(&s);
assert_eq!(
cells_after_cut,
vec![vec!["R0C0".to_string(), "R".into(), "".into(), "".into(), "1".into(), "R1C2".into(), "R2C0".into(), "R2C1".into(), "R2C2".into(),]]
);
run(&mut s, "caret.docEnd", json!({}));
run(&mut s, "edit.paste", json!({}));
let texts_cut = body_texts(&s);
assert!(
texts_cut.iter().any(|t| t == "0C1")
&& texts_cut.iter().any(|t| t == "R0C2")
&& texts_cut.iter().any(|t| t == "R1C0")
&& texts_cut.iter().any(|t| t == "R1C"),
"every removed character must be preserved and inserted from cut, got: {:?}",
texts_cut
);
}
}
/// #1744: Select Table → Cut removes the whole table, and one Undo brings it back.
#[test]
fn cut_whole_table_removes_it_and_undoes() {
@@ -2950,20 +2635,6 @@ fn tracked_cut_of_a_table_or_row_marks_text_deleted() {
assert_eq!(body_table_final(&s), full);
}
/// Cut and Copy are off with nothing selected (the ribbon buttons read this) and on with text selected.
#[test]
fn cut_and_copy_are_disabled_without_a_selection() {
let mut s = Session::new(wordcraft_doc::Document::new());
run(&mut s, "text.insert", json!({"text": "Hello"}));
for id in ["edit.cut", "edit.copy"] {
assert!(s.why_disabled(id).is_some(), "{id} with a caret only");
}
run(&mut s, "select.text", json!({"text": "Hello"}));
for id in ["edit.cut", "edit.copy"] {
assert!(s.why_disabled(id).is_none(), "{id} with a selection");
}
}
/// #1744 review: Cut of a table, or of cells, holding a content control locked against deletion
/// is refused and changes nothing in the document; the copy is made first, so the clipboard
/// holds the table, as for any refused Cut.
@@ -3329,19 +3000,11 @@ fn tables_nest_only_as_deep_as_a_json_save_reads() {
let e = s.run("insert.table", &json!({"rows": 1, "cols": 1})).unwrap_err();
assert!(e.to_string().contains(&format!("{MAX_TABLE_DEPTH} deep")), "{e}");
assert_eq!(s.doc, before);
// Paste as Nested Table is the path the depth guard sits on: the table's text comes as paragraphs.
run(&mut s, "edit.pasteNestedTable", json!({"text": "b", "html": "<table><tr><td>b</td></tr></table>"}));
run(&mut s, "edit.paste", json!({"text": "b", "html": "<table><tr><td>b</td></tr></table>"}));
let cell = s.sel.focus.path.clone();
let blocks: Vec<_> = (0..).map_while(|i| s.doc.block(StoryRef::Body, &cell.with_last(i))).collect();
assert!(blocks.iter().all(|b| b.as_table().is_none()), "no table below the limit");
assert!(blocks.iter().any(|b| b.as_para().is_some_and(|p| p.text.contains('b'))), "the pasted text is there");
// Paste lays a one-cell table over the cell (#6739): no new level either.
run(&mut s, "edit.paste", json!({"text": "c", "html": "<table><tr><td>c</td></tr></table>"}));
let cell = s.sel.focus.path.clone();
let blocks: Vec<_> = (0..).map_while(|i| s.doc.block(StoryRef::Body, &cell.with_last(i))).collect();
assert!(blocks.iter().all(|b| b.as_table().is_none()), "no table below the limit");
assert!(blocks.iter().any(|b| b.as_para().is_some_and(|p| p.text.contains('c'))), "the pasted text is there");
assert_eq!(s.sel.focus.path.depth(), MAX_TABLE_DEPTH);
}
/// #3618: a text box story sits two JSON levels below the body, and its deepest cell still reads
@@ -6176,318 +5839,6 @@ fn copy_paste_text_box_makes_an_independent_copy() {
assert_eq!(s.doc.parts.len(), parts);
}
/// Copying and pasting a selected custom text box duplicates its dimensions, styling, and text
/// while giving the copy an independent story ID.
#[test]
fn copy_and_paste_selected_custom_text_box_duplicates_dimensions_styling_and_text() {
let mut s = s();
let id = run(
&mut s,
"insert.textBox",
json!({
"text": "Custom content",
"width": 180.0,
"height": 90.0
}),
)["story"]
.as_u64()
.unwrap() as u32;
// Apply custom styling (fill and outline).
run(&mut s, "select.range", json!({"anchor": Pos::body(0, 0), "focus": Pos::body(0, 3)}));
run(&mut s, "shape.fill", json!({"color": "FFEEDD"}));
run(&mut s, "shape.outline", json!({"color": "112233", "width": 2.5}));
let para = s.doc.para(StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap();
let orig_obj = para.objects[0].clone();
let wordcraft_doc::InlineObject::Shape { w, h, stroke_width, fill, stroke, .. } = &orig_obj else { panic!("not a shape") };
assert_eq!((*w, *h), (180.0, 90.0));
assert_eq!(*stroke_width, 2.5);
assert!(fill.is_some());
assert!(stroke.is_some());
// Copy selected custom text box (non-collapsed, object_selection, #5785, #5859).
run(&mut s, "select.range", json!({"anchor": Pos::body(0, 0), "focus": Pos::body(0, 3)}));
assert!(crate::cmd::objects::object_selection(&s).is_some());
let copy_res = run(&mut s, "edit.copy", json!({}));
assert_eq!(copy_res["text"], "Custom content");
assert_eq!(s.clipboard_text, "Custom content");
assert!(s.clipboard.is_some());
// Move caret after original and paste.
run(&mut s, "caret.set", json!({"pos": Pos::body(0, 3)}));
run(&mut s, "edit.paste", json!({}));
let para = s.doc.para(StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap();
assert_eq!(para.objects.len(), 2);
let pasted = &para.objects[1];
let wordcraft_doc::InlineObject::Shape { w: pw, h: ph, stroke_width: psw, fill: pfill, stroke: pstroke, story: pstory, .. } = pasted else {
panic!("pasted not a shape");
};
assert_eq!((*pw, *ph), (180.0, 90.0), "dimensions duplicated");
assert_eq!(*psw, 2.5, "stroke width duplicated");
assert_eq!(pfill, fill, "fill duplicated");
assert_eq!(pstroke, stroke, "stroke duplicated");
assert!(pstory.is_some());
assert_ne!(pstory.unwrap(), id, "independent story ID");
assert_eq!(s.doc.plain_text(StoryRef::Part(pstory.unwrap())), "Custom content", "inner text duplicated");
// Cut the pasted text box by selecting it (non-collapsed, object_selection).
run(&mut s, "select.range", json!({"anchor": Pos::body(0, 3), "focus": Pos::body(0, 6)}));
assert!(crate::cmd::objects::object_selection(&s).is_some());
let cut_res = run(&mut s, "edit.cut", json!({}));
assert_eq!(cut_res["text"], "Custom content");
let para = s.doc.para(StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap();
assert_eq!(para.objects.len(), 1);
assert_eq!(para.objects[0].text_box(), Some(id));
// Paste it back.
run(&mut s, "edit.paste", json!({}));
let para = s.doc.para(StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap();
assert_eq!(para.objects.len(), 2);
// Copy and paste a shape without text.
run(&mut s, "caret.set", json!({"pos": Pos::body(0, 6)}));
run(&mut s, "insert.shape", json!({"kind": "star", "width": 64.0, "height": 48.0}));
run(&mut s, "shape.fill", json!({"color": "00FF00"}));
run(&mut s, "select.range", json!({"anchor": Pos::body(0, 6), "focus": Pos::body(0, 9)}));
run(&mut s, "edit.copy", json!({}));
assert!(s.clipboard.is_some());
run(&mut s, "caret.set", json!({"pos": Pos::body(0, 9)}));
run(&mut s, "edit.paste", json!({}));
let para = s.doc.para(StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap();
assert_eq!(para.objects.len(), 4);
let star_copy = &para.objects[3];
let wordcraft_doc::InlineObject::Shape { kind, w, h, fill, .. } = star_copy else { panic!("not a shape") };
assert_eq!(*kind, wordcraft_doc::para::ShapeKind::Star);
assert_eq!((*w, *h), (64.0, 48.0));
assert!(fill.is_some());
}
/// Cut and Copy with a bare caret beside an object (collapsed selection) change nothing (#5859).
#[test]
fn cut_and_copy_with_bare_caret_beside_object_change_nothing() {
let mut s = s();
let id = run(&mut s, "insert.textBox", json!({"text": "Box content"}))["story"].as_u64().unwrap() as u32;
// 1. Bare caret immediately before the object (Pos::body(0, 0)).
run(&mut s, "caret.set", json!({"pos": Pos::body(0, 0)}));
assert!(s.sel.is_collapsed());
assert!(crate::cmd::objects::object_selection(&s).is_none());
let copy_res = run(&mut s, "edit.copy", json!({}));
assert_eq!(copy_res["text"], "", "copy on bare caret returns empty text");
assert!(s.clipboard.is_none(), "clipboard remains unset");
let cut_res = s.run("edit.cut", &json!({}));
assert!(matches!(cut_res, Err(crate::CmdError::Disabled(_))), "cut on bare caret is disabled");
let para = s.doc.para(StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap();
assert_eq!(para.objects.len(), 1, "object was not deleted");
assert_eq!(para.objects[0].text_box(), Some(id));
// 2. Bare caret immediately after the object (Pos::body(0, 3)).
run(&mut s, "caret.set", json!({"pos": Pos::body(0, 3)}));
assert!(s.sel.is_collapsed());
assert!(crate::cmd::objects::object_selection(&s).is_none());
let copy_res = run(&mut s, "edit.copy", json!({}));
assert_eq!(copy_res["text"], "", "copy on bare caret returns empty text");
assert!(s.clipboard.is_none(), "clipboard remains unset");
let cut_res = s.run("edit.cut", &json!({}));
assert!(matches!(cut_res, Err(crate::CmdError::Disabled(_))), "cut on bare caret is disabled");
let para = s.doc.para(StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap();
assert_eq!(para.objects.len(), 1, "object was not deleted");
assert_eq!(para.objects[0].text_box(), Some(id));
}
/// Fallback plain text / clipboard text when paragraphs contain text boxes (#5785).
#[test]
fn fallback_plain_text_extracts_text_box_story_when_body_contains_paragraph_marks() {
let mut f = wordcraft_doc::edit::Fragment::default();
let mut p = wordcraft_doc::Paragraph::new();
p.text = format!("{}\n", wordcraft_doc::para::OBJ);
let mut part_p = wordcraft_doc::Paragraph::new();
part_p.text = "Box text".to_string();
let part = wordcraft_doc::Part {
kind: wordcraft_doc::PartKind::TextBox,
blocks: vec![std::sync::Arc::new(wordcraft_doc::Block::Para(part_p))],
body: Default::default(),
};
f.blocks = vec![wordcraft_doc::Block::Para(p)];
f.parts.insert(100, part);
assert_eq!(f.plain_text(), "Box text");
assert_eq!(f.clipboard_text(), "Box text");
}
/// Pasting formatted content with matching RTF but mismatched HTML from an external app prefers HTML (#5785).
#[test]
fn paste_content_prefers_external_html_when_rtf_matches_session_clipboard() {
let mut s = s();
run(&mut s, "insert.textBox", json!({"text": "Internal text"}));
run(&mut s, "select.range", json!({"anchor": Pos::body(0, 0), "focus": Pos::body(0, 3)}));
run(&mut s, "edit.copy", json!({}));
let my_rtf = s.clipboard_rtf.clone();
let external_html = "<p>External rich text</p>";
let pasted_res = crate::cmd::paste::paste_content(&mut s, &json!({"html": external_html, "rtf": my_rtf}));
assert!(matches!(pasted_res, Ok(crate::cmd::paste::Pasted::Fragment(_))));
if let Ok(crate::cmd::paste::Pasted::Fragment(frag)) = pasted_res {
assert_eq!(frag.plain_text(), "External rich text");
}
}
/// Pasting with no text payload or empty text but matching HTML and RTF uses WordCraft's session clipboard
/// fragment, preserving custom text box parts (#5785, #5859).
#[test]
fn paste_content_uses_session_clipboard_when_html_and_rtf_match_without_text() {
let mut s = s();
run(&mut s, "insert.textBox", json!({"text": "Internal text box"}));
run(&mut s, "select.range", json!({"anchor": Pos::body(0, 0), "focus": Pos::body(0, 3)}));
run(&mut s, "edit.copy", json!({}));
let my_html = s.clipboard_html.clone();
let my_rtf = s.clipboard_rtf.clone();
assert!(!my_html.is_empty());
assert!(!my_rtf.is_empty());
assert!(s.clipboard.as_ref().is_some_and(|f| !f.parts.is_empty()));
let pasted_res = crate::cmd::paste::paste_content(&mut s, &json!({"html": my_html, "rtf": my_rtf}));
assert!(matches!(pasted_res, Ok(crate::cmd::paste::Pasted::Fragment(_))));
if let Ok(crate::cmd::paste::Pasted::Fragment(frag)) = pasted_res {
assert_eq!(frag.parts.len(), 1, "session text box parts preserved");
assert_eq!(frag.plain_text(), "Internal text box");
}
let pasted_with_empty_text = crate::cmd::paste::paste_content(&mut s, &json!({"text": "", "html": my_html, "rtf": my_rtf}));
assert!(matches!(pasted_with_empty_text, Ok(crate::cmd::paste::Pasted::Fragment(_))));
if let Ok(crate::cmd::paste::Pasted::Fragment(frag)) = pasted_with_empty_text {
assert_eq!(frag.parts.len(), 1, "session text box parts preserved with empty text");
assert_eq!(frag.plain_text(), "Internal text box");
}
let avail = crate::cmd::paste::available(&s, &json!({"text": "", "html": my_html, "rtf": my_rtf}));
assert!(avail.contains(&"formatted"), "formatted format is available for pasteSpecial when text is empty but rich formats match");
let paste_special_res = s.run("edit.pasteSpecial", &json!({"as": "formatted", "text": "", "html": my_html, "rtf": my_rtf}));
assert!(paste_special_res.is_ok(), "pasteSpecial as formatted succeeds with empty text and matching rich formats");
}
/// On macOS, arboard wraps HTML in `<html><head>…</head><body>…</body></html>`, so the
/// round-tripped HTML never equals what WordCraft stored. The session clipboard must still be
/// recognised when RTF matches or HTML matches after unwrapping (#5859).
#[test]
fn paste_content_uses_session_clipboard_when_macos_wraps_html() {
let mut s = s();
run(&mut s, "insert.textBox", json!({"text": "Internal text box"}));
run(&mut s, "select.range", json!({"anchor": Pos::body(0, 0), "focus": Pos::body(0, 3)}));
run(&mut s, "edit.copy", json!({}));
let my_rtf = s.clipboard_rtf.clone();
assert!(!my_rtf.is_empty());
assert!(s.clipboard.as_ref().is_some_and(|f| !f.parts.is_empty()));
// Simulate macOS wrapping: HTML is wrapped by arboard, RTF is raw.
let wrapped_html =
format!("<html><head><meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\"></head><body>{}</body></html>", s.clipboard_html);
assert_ne!(wrapped_html, s.clipboard_html, "wrapped HTML differs from stored");
// With empty text (front-end path for shapes/text-boxes without text), session clipboard matched.
let pasted = crate::cmd::paste::paste_content(&mut s, &json!({"text": "", "html": wrapped_html, "rtf": my_rtf}));
assert!(matches!(pasted, Ok(crate::cmd::paste::Pasted::Fragment(_))));
if let Ok(crate::cmd::paste::Pasted::Fragment(frag)) = pasted {
assert_eq!(frag.parts.len(), 1, "session text box parts preserved despite wrapped HTML");
assert_eq!(frag.plain_text(), "Internal text box");
}
// With non-empty text that matches, session clipboard matched via main's text rule.
let my_text = s.clipboard_text.clone();
let pasted_text = crate::cmd::paste::paste_content(&mut s, &json!({"text": my_text, "html": wrapped_html, "rtf": my_rtf}));
assert!(matches!(pasted_text, Ok(crate::cmd::paste::Pasted::Fragment(_))));
if let Ok(crate::cmd::paste::Pasted::Fragment(frag)) = pasted_text {
assert_eq!(frag.parts.len(), 1, "session text box parts preserved with text match");
}
// Paste Special as formatted is available despite wrapped HTML.
let avail = crate::cmd::paste::available(&s, &json!({"text": my_text, "html": wrapped_html, "rtf": my_rtf}));
assert!(avail.contains(&"formatted"), "formatted format is available for pasteSpecial when HTML is wrapped on macOS");
}
/// Pasting external RTF when HTML matches WordCraft's session clipboard does not return the old
/// session fragment with its custom parts (#5785, #5859).
#[test]
fn paste_content_does_not_use_session_clipboard_when_html_matches_but_rtf_differs() {
let mut s = s();
run(&mut s, "insert.textBox", json!({"text": "Internal text box"}));
run(&mut s, "select.range", json!({"anchor": Pos::body(0, 0), "focus": Pos::body(0, 3)}));
run(&mut s, "edit.copy", json!({}));
let my_html = s.clipboard_html.clone();
let external_rtf = "{\\rtf1\\ansi External rich text}";
let pasted_res = crate::cmd::paste::paste_content(&mut s, &json!({"html": my_html, "rtf": external_rtf}));
assert!(matches!(pasted_res, Ok(crate::cmd::paste::Pasted::Fragment(_))));
if let Ok(crate::cmd::paste::Pasted::Fragment(frag)) = pasted_res {
assert!(frag.parts.is_empty(), "session text box parts not reused when RTF differs");
}
}
/// Pasting external RTF when plain text matches WordCraft's session clipboard does not return the
/// old session fragment with its custom parts, even when privateClipboard is omitted (#5785, #5859).
#[test]
fn paste_content_does_not_use_session_clipboard_when_text_matches_but_rtf_differs() {
let mut s = s();
run(&mut s, "insert.textBox", json!({"text": "Internal text box"}));
run(&mut s, "select.range", json!({"anchor": Pos::body(0, 0), "focus": Pos::body(0, 3)}));
run(&mut s, "edit.copy", json!({}));
let my_text = s.clipboard_text.clone();
let external_rtf = "{\\rtf1\\ansi External rich text}";
let pasted_res = crate::cmd::paste::paste_content(&mut s, &json!({"text": my_text, "rtf": external_rtf}));
assert!(matches!(pasted_res, Ok(crate::cmd::paste::Pasted::Fragment(_))));
if let Ok(crate::cmd::paste::Pasted::Fragment(frag)) = pasted_res {
assert!(frag.parts.is_empty(), "session text box parts not reused when RTF differs");
}
let avail = crate::cmd::paste::available(&s, &json!({"text": my_text, "rtf": external_rtf}));
assert!(!avail.contains(&"formatted"), "formatted is unavailable when supplied RTF differs");
}
/// When another app copies different RTF (`privateClipboard: false`), plain text matching
/// WordCraft's session clipboard does not return the old session fragment (#5785, #5859).
#[test]
fn paste_content_does_not_use_session_clipboard_when_another_app_copied_rtf() {
let mut s = s();
run(&mut s, "insert.textBox", json!({"text": "Internal text box"}));
run(&mut s, "select.range", json!({"anchor": Pos::body(0, 0), "focus": Pos::body(0, 3)}));
run(&mut s, "edit.copy", json!({}));
let my_text = s.clipboard_text.clone();
let external_rtf = "{\\rtf1\\ansi External rich text}";
let pasted_res = crate::cmd::paste::paste_content(&mut s, &json!({"privateClipboard": false, "text": my_text, "rtf": external_rtf}));
assert!(matches!(pasted_res, Ok(crate::cmd::paste::Pasted::Fragment(_))));
if let Ok(crate::cmd::paste::Pasted::Fragment(frag)) = pasted_res {
assert!(frag.parts.is_empty(), "session text box parts not reused when another app copied");
}
}
/// The public `edit.paste` command does not reuse session text box parts when supplied RTF differs,
/// even when privateClipboard is omitted (#5859).
#[test]
fn paste_command_does_not_use_session_clipboard_when_text_matches_but_rtf_differs() {
let mut s = s();
run(&mut s, "insert.textBox", json!({"text": "Internal text box"}));
run(&mut s, "select.range", json!({"anchor": Pos::body(0, 0), "focus": Pos::body(0, 3)}));
run(&mut s, "edit.copy", json!({}));
let my_text = s.clipboard_text.clone();
let external_rtf = "{\\rtf1\\ansi External rich text}";
run(&mut s, "caret.docEnd", json!({}));
run(&mut s, "edit.paste", json!({"text": my_text, "rtf": external_rtf}));
assert_eq!(s.doc.parts.len(), 1, "no second text box part created from session fragment");
assert!(s.doc.plain_text(StoryRef::Body).contains("External rich text"));
}
#[test]
fn word_count_includes_text_boxes_by_default() {
let mut s = s();
@@ -1,532 +0,0 @@
//! #6739: a copied table pasted with the caret in a table cell does what Word's Paste does (rows
//! inserted above, or cells overwritten from the caret's), and nests only when asked to.
use std::sync::Arc;
use serde_json::json;
use wordcraft_doc::edit::Fragment;
use wordcraft_doc::{Block, Cell, Document, Paragraph, Path, Pos, StoryRef, Table, para_block};
use crate::cmd::table::cell_text;
use crate::{Selection, Session};
/// A table of `rows` x `cols` cells whose texts are `<prefix><row><col>` (from 1), 100 pt wide cells.
fn table(prefix: &str, rows: usize, cols: usize) -> Table {
let mut t = Table::new(rows, cols, 100.0 * cols as f32);
for (r, row) in t.rows.iter_mut().enumerate() {
for (c, cell) in row.cells.iter_mut().enumerate() {
cell.blocks = Cell::with_text(&format!("{prefix}{}{}", r + 1, c + 1)).blocks;
}
}
t
}
/// A document of the 3 x 3 table d11..d33 and an empty paragraph, the caret in cell (`row`, `col`).
fn dest(row: usize, col: usize) -> Session {
let mut d = Document::new();
d.body = vec![Arc::new(Block::Table(table("d", 3, 3))), para_block(Paragraph::new())];
let mut s = Session::new(d);
s.sel = Selection::caret(Pos::new(StoryRef::Body, Path(vec![0, row as u32, col as u32, 0]), 0));
s
}
fn copy(s: &mut Session, t: Table) {
s.clipboard = Some(Fragment { blocks: vec![Block::Table(t)], ..Default::default() });
}
fn paste(s: &mut Session) {
s.run("edit.paste", &json!({})).unwrap();
}
fn t0(s: &Session) -> &Table {
s.doc.body[0].as_table().expect("the table")
}
/// The texts of the table's rows, a nested table shown as `[nested]`.
fn grid(t: &Table) -> Vec<Vec<String>> {
t.rows
.iter()
.map(|r| r.cells.iter().map(|c| if c.blocks.iter().any(|b| b.as_table().is_some()) { "[nested]".into() } else { cell_text(c) }).collect())
.collect()
}
fn rows(spec: &[&str]) -> Vec<Vec<String>> {
spec.iter().map(|r| r.split(',').map(str::to_string).collect()).collect()
}
fn nested(t: &Table) -> bool {
t.rows.iter().flat_map(|r| &r.cells).any(|c| c.blocks.iter().any(|b| b.as_table().is_some()))
}
#[test]
fn paste_all_keeps_tables_in_copy_order_inside_the_cell() {
for col in [0, 1] {
let mut s = dest(1, col);
for prefix in ["first", "second"] {
copy(&mut s, table(prefix, 1, 3));
let frag = s.clipboard.as_ref().unwrap();
s.clip_history.push(frag, &frag.clipboard_text());
}
s.run("edit.pasteAllClipboard", &json!({})).unwrap();
let pasted: Vec<_> = t0(&s).rows[1].cells[col].blocks.iter().filter_map(|b| b.as_table()).map(|t| cell_text(&t.rows[0].cells[0])).collect();
assert_eq!(pasted, ["first11", "second11"]);
}
}
#[test]
fn a_copied_table_over_selected_cells_overwrites_from_the_top_left() {
for (source_cols, expected) in
[(2, rows(&["s11,s12,d13", "s21,s22,d23", "d31,d32,d33"])), (3, rows(&["s11,s12,s13", "s21,s22,s23", "d31,d32,d33"]))]
{
let mut s = dest(1, 1);
crate::cmd::table::extend_selection(&mut s, Pos::new(StoryRef::Body, Path(vec![0, 0, 0, 0]), 0));
let range = s.cell_range().unwrap();
assert_eq!((range.rows, range.cols, range.stream), ((0, 1), (0, 1), false));
copy(&mut s, table("s", 2, source_cols));
paste(&mut s);
assert_eq!(grid(t0(&s)), expected, "source width {source_cols}");
assert_eq!(s.sel, Selection::caret(Pos::new(StoryRef::Body, Path(vec![0, 0, 0, 0]), 0)));
assert!(s.cell_range().is_none());
s.run("edit.undo", &json!({})).unwrap();
assert_eq!(grid(t0(&s)), grid(&table("d", 3, 3)));
s.run("edit.redo", &json!({})).unwrap();
assert_eq!(grid(t0(&s)), expected);
let reopened = wordcraft_docx::read(&wordcraft_docx::write(&s.doc).unwrap()).unwrap();
assert_eq!(grid(reopened.body[0].as_table().unwrap()), expected);
}
}
#[test]
fn plain_text_paste_still_replaces_a_cell_rectangle() {
let mut s = dest(0, 0);
crate::cmd::table::extend_selection(&mut s, Pos::new(StoryRef::Body, Path(vec![0, 1, 1, 0]), 0));
s.run("edit.paste", &json!({"text": "replacement"})).unwrap();
assert_eq!(grid(t0(&s)), rows(&["replacement,,d13", ",,d23", "d31,d32,d33"]));
}
#[test]
fn a_whole_table_with_the_caret_in_the_first_column_inserts_its_rows_above() {
for (row, want) in [
(1, rows(&["d11,d12,d13", "s11,s12,s13", "s21,s22,s23", "s31,s32,s33", "d21,d22,d23", "d31,d32,d33"])),
(0, rows(&["s11,s12,s13", "s21,s22,s23", "s31,s32,s33", "d11,d12,d13", "d21,d22,d23", "d31,d32,d33"])),
] {
let mut s = dest(row, 0);
copy(&mut s, table("s", 3, 3));
paste(&mut s);
assert_eq!(grid(t0(&s)), want, "caret in row {row}");
assert!(!nested(t0(&s)));
assert_eq!(s.doc.body.iter().filter(|b| b.as_table().is_some()).count(), 1);
}
}
#[test]
fn a_whole_table_with_the_caret_further_right_overwrites_cells_and_grows_the_table() {
let mut s = dest(1, 2);
copy(&mut s, table("s", 3, 3));
paste(&mut s);
let want = rows(&["d11,d12,d13,,", "d21,d22,s11,s12,s13", "d31,d32,s21,s22,s23", ",,s31,s32,s33"]);
assert_eq!(grid(t0(&s)), want);
assert_eq!(t0(&s).grid.len(), 5);
assert!(t0(&s).rows.iter().all(|r| r.cells.len() == 5));
// The last cell of the last row: the table grows two columns and two rows.
let mut s = dest(2, 2);
copy(&mut s, table("s", 3, 3));
paste(&mut s);
let want = rows(&["d11,d12,d13,,", "d21,d22,d23,,", "d31,d32,s11,s12,s13", ",,s21,s22,s23", ",,s31,s32,s33"]);
assert_eq!(grid(t0(&s)), want);
}
#[test]
fn cells_copied_from_part_of_a_table_overwrite_from_the_caret_in_any_column() {
// Two cells of one column (Word: s12, s22 into the cells below the caret).
let mut s = dest(1, 0);
copy(&mut s, table("s", 2, 1));
paste(&mut s);
assert_eq!(grid(t0(&s)), rows(&["d11,d12,d13", "s11,d22,d23", "s21,d32,d33"]));
// At the last row a row is added.
let mut s = dest(2, 0);
copy(&mut s, table("s", 2, 1));
paste(&mut s);
assert_eq!(grid(t0(&s)), rows(&["d11,d12,d13", "d21,d22,d23", "s11,d32,d33", "s21,,"]));
// Two columns wide, from the middle column: it fits the table.
let mut s = dest(0, 1);
copy(&mut s, table("s", 2, 2));
paste(&mut s);
assert_eq!(grid(t0(&s)), rows(&["d11,s11,s12", "d21,s21,s22", "d31,d32,d33"]));
}
#[test]
fn one_copied_cell_replaces_the_cell_it_is_pasted_in() {
for (r, c) in [(0, 0), (1, 2), (2, 2)] {
let mut s = dest(r, c);
copy(&mut s, table("s", 1, 1));
paste(&mut s);
let mut want = grid(&table("d", 3, 3));
want[r][c] = "s11".into();
assert_eq!(grid(t0(&s)), want, "cell ({r}, {c})");
}
}
#[test]
fn the_caret_goes_to_the_first_pasted_cell() {
let mut s = dest(1, 0);
copy(&mut s, table("s", 3, 3));
paste(&mut s);
assert_eq!(s.sel.focus.path, Path(vec![0, 1, 0, 0]));
assert!(s.sel.is_collapsed());
}
#[test]
fn paste_as_nested_table_nests_the_table_in_the_cell() {
let mut s = dest(1, 0);
copy(&mut s, table("s", 3, 3));
s.run("edit.pasteNestedTable", &json!({})).unwrap();
let t = t0(&s);
assert_eq!(t.rows.len(), 3, "no rows inserted");
assert!(t.rows[1].cells[0].blocks.iter().any(|b| b.as_table().is_some()), "a table nests in the cell");
assert_eq!(cell_text(&t.rows[1].cells[1]), "d22");
}
#[test]
fn pasting_a_wrapped_table_keeps_its_source_controls() {
use wordcraft_doc::{ContentControl, ControlKind};
for on_row in [false, true] {
// A same-width copy can insert rows at column zero or overwrite cells further right.
for col in [0, 1] {
let mut s = dest(1, col);
let mut source = table("s", 2, 3);
let controls = if on_row { &mut source.rows[0].controls } else { &mut source.controls };
let mut wrapper = ContentControl::new(ControlKind::RichText);
wrapper.tag = "source wrapper".into();
controls.open.push(wrapper);
controls.close = 1;
let expected = controls.clone();
copy(&mut s, source);
paste(&mut s);
let pasted = t0(&s).rows[1].cells[col]
.blocks
.iter()
.find_map(|b| b.as_table())
.unwrap_or_else(|| panic!("the wrapped source should nest (row wrapper: {on_row}, column: {col})"));
let controls = if on_row { &pasted.rows[0].controls } else { &pasted.controls };
assert_eq!(controls, &expected, "row wrapper: {on_row}, column: {col}");
}
}
}
#[test]
fn what_cannot_be_laid_over_the_cells_nests_as_before() {
let nests = |s: &mut Session| {
paste(s);
assert!(nested(t0(s)), "nested");
assert_eq!(t0(s).rows.len(), 3);
};
// Merged cells in the copy.
let mut merged = table("s", 2, 3);
merged.rows[0].cells[0].props.span = 2;
merged.rows[0].cells.remove(1);
let mut s = dest(1, 0);
copy(&mut s, merged);
nests(&mut s);
// Ragged rows in the copy.
let mut ragged = table("s", 2, 3);
ragged.rows[1].cells.pop();
let mut s = dest(1, 0);
copy(&mut s, ragged);
nests(&mut s);
// More columns than a table may have.
let mut s = dest(1, 2);
copy(&mut s, table("s", 1, 62));
nests(&mut s);
// A table inside a copied cell.
let mut inner = table("s", 1, 1);
inner.rows[0].cells[0].blocks = vec![Arc::new(Block::Table(table("n", 1, 1)))];
let mut s = dest(1, 0);
copy(&mut s, inner);
nests(&mut s);
// Merged cells in the destination.
let mut s = dest(1, 0);
if let Some(Block::Table(t)) = s.doc.body.get_mut(0).map(Arc::make_mut) {
t.rows[1].cells[0].props.span = 2;
t.rows[1].cells.remove(1);
}
copy(&mut s, table("s", 1, 1));
nests(&mut s);
// A copied cell without any block (hostile fragment): nothing to lay over the cell.
let mut hollow = table("s", 1, 1);
hollow.rows[0].cells[0].blocks.clear();
let mut s = dest(1, 0);
copy(&mut s, hollow);
let _ = s.run("edit.paste", &json!({}));
assert_eq!(t0(&s).rows.len(), 3, "nothing laid over the cells");
// A wider copy into a one-column table (a layout wrapper) nests instead of widening it.
let mut s = dest(1, 0);
s.doc.body[0] = Arc::new(Block::Table(table("w", 3, 1)));
copy(&mut s, table("s", 2, 3));
paste(&mut s);
assert!(nested(t0(&s)));
assert_eq!(t0(&s).grid.len(), 1);
// A content control in a cell the copy would overwrite.
let mut s = dest(1, 0);
if let Some(Block::Table(t)) = s.doc.body.get_mut(0).map(Arc::make_mut) {
t.rows[2].cells[0].controls.close = 1;
}
copy(&mut s, table("s", 3, 1));
nests(&mut s);
// Row exceptions on the destination.
let mut s = dest(1, 0);
if let Some(Block::Table(t)) = s.doc.body.get_mut(0).map(Arc::make_mut) {
t.rows[0].props.exceptions = Some(Default::default());
}
copy(&mut s, table("s", 1, 1));
nests(&mut s);
// Track Changes on.
let mut s = dest(1, 0);
s.doc.settings.track_changes = true;
copy(&mut s, table("s", 3, 3));
nests(&mut s);
}
#[test]
fn hostile_shapes_never_panic() {
// An empty table, a table with empty rows, 30,000 columns and 30,000 rows in a copy.
let mut wide = table("s", 1, 1);
wide.grid = vec![1.0; 30_000];
wide.rows[0].cells = (0..30_000).map(|_| Cell::empty()).collect();
let mut tall = table("s", 1, 2);
tall.rows = (0..30_000).map(|_| tall.rows[0].clone()).collect();
let mut no_rows = table("s", 1, 1);
no_rows.rows.clear();
let mut no_cells = table("s", 1, 1);
no_cells.rows[0].cells.clear();
// 30,000 columns and empty tables can't be laid over the cells: they nest (the old path).
for t in [wide, no_rows, no_cells] {
for (r, c) in [(0, 0), (2, 2)] {
let mut s = dest(r, c);
copy(&mut s, t.clone());
let _ = s.run("edit.paste", &json!({}));
assert_eq!((t0(&s).rows.len(), t0(&s).grid.len()), (3, 3), "unchanged table");
}
}
// 30,000 rows are laid over the cells: rows are added up to the limit, never past it.
for (r, c) in [(0, 0), (2, 1)] {
let mut s = dest(r, c);
copy(&mut s, tall.clone());
s.run("edit.paste", &json!({})).unwrap();
assert_eq!(t0(&s).rows.len(), r + 30_000);
assert!(t0(&s).rows.iter().all(|row| row.cells.len() == t0(&s).grid.len()));
}
// More rows than a table may have nest instead.
let mut huge = table("s", 1, 2);
huge.rows = (0..wordcraft_doc::table::MAX_ROWS).map(|_| huge.rows[0].clone()).collect();
let mut s = dest(1, 1);
copy(&mut s, huge);
let _ = s.run("edit.paste", &json!({}));
assert_eq!(t0(&s).rows.len(), 3);
// A caret path that is not a cell of the table.
let mut s = dest(0, 0);
s.sel = Selection::caret(Pos::new(StoryRef::Body, Path(vec![0, 9, 9, 0]), 0));
copy(&mut s, table("s", 1, 1));
let _ = s.run("edit.paste", &json!({}));
assert_eq!(t0(&s).rows.len(), 3);
}
#[test]
fn a_copied_table_with_empty_paragraphs_around_it_is_laid_over_the_cells_too() {
let mut s = dest(1, 0);
s.clipboard = Some(Fragment {
blocks: vec![Block::Para(Paragraph::new()), Block::Table(table("s", 1, 3)), Block::Para(Paragraph::new())],
..Default::default()
});
paste(&mut s);
assert_eq!(grid(t0(&s)), rows(&["d11,d12,d13", "s11,s12,s13", "d21,d22,d23", "d31,d32,d33"]));
}
#[test]
fn undo_takes_the_paste_back_in_one_step_and_redo_does_it_again() {
for (row, col) in [(1, 0), (1, 2)] {
let mut s = dest(row, col);
let before = t0(&s).clone();
copy(&mut s, table("s", 3, 3));
paste(&mut s);
let after = t0(&s).clone();
assert_ne!(after, before);
s.run("edit.undo", &json!({})).unwrap();
assert_eq!(t0(&s), &before, "one undo restores the table ({row}, {col})");
s.run("edit.redo", &json!({})).unwrap();
assert_eq!(t0(&s), &after);
}
}
#[test]
fn the_pasted_rows_survive_saving_and_reopening_as_docx() {
let mut s = dest(1, 0);
copy(&mut s, table("s", 3, 3));
paste(&mut s);
let bytes = crate::io::save_bytes("t.docx", &s.doc).unwrap();
let back = crate::io::open_bytes("t.docx", &bytes).unwrap();
let t = back.body.iter().find_map(|b| b.as_table()).expect("a table");
assert_eq!(grid(t), grid(t0(&s)));
let mut s = dest(1, 2);
copy(&mut s, table("s", 3, 3));
paste(&mut s);
let back = crate::io::open_bytes("t.docx", &crate::io::save_bytes("t.docx", &s.doc).unwrap()).unwrap();
let t = back.body.iter().find_map(|b| b.as_table()).expect("a table");
assert_eq!((t.rows.len(), t.grid.len()), (4, 5));
assert_eq!(grid(t), grid(t0(&s)));
}
#[test]
fn a_paste_into_a_cell_of_a_table_inside_a_cell_works_on_that_table() {
let mut inner_host = table("o", 1, 1);
inner_host.rows[0].cells[0].blocks = vec![Arc::new(Block::Table(table("d", 3, 3))), para_block(Paragraph::new())];
let mut d = Document::new();
d.body = vec![Arc::new(Block::Table(inner_host)), para_block(Paragraph::new())];
let mut s = Session::new(d);
// Body table 0, row 0, cell 0, its block 0 (the inner table), row 1, cell 0, block 0.
s.sel = Selection::caret(Pos::new(StoryRef::Body, Path(vec![0, 0, 0, 0, 1, 0, 0]), 0));
copy(&mut s, table("s", 3, 3));
paste(&mut s);
let inner = t0(&s).rows[0].cells[0].blocks[0].as_table().expect("the inner table").clone();
assert_eq!(grid(&inner).len(), 6);
assert!(!nested(&inner));
}
/// A locked control in a table nested in a cell the copy would overwrite is not deleted: the
/// paste nests instead (#6739 review).
#[test]
fn a_locked_control_in_a_nested_table_of_an_overwritten_cell_is_kept() {
use wordcraft_doc::{ContentControl, ControlKind, ControlLock};
let mut s = dest(0, 0);
let mut inner = table("n", 1, 1);
let mut ctl = ContentControl::new(ControlKind::RichText);
ctl.lock = ControlLock::SdtContentLocked;
inner.rows[0].cells[0].controls.open.push(ctl);
inner.rows[0].cells[0].controls.close = 1;
if let Some(Block::Table(t)) = s.doc.body.get_mut(0).map(Arc::make_mut) {
t.rows[1].cells[0].blocks = vec![Arc::new(Block::Table(inner)), para_block(Paragraph::new())];
}
let before = t0(&s).rows[1].cells[0].clone();
// Copy one cell, caret above the cell with the nested table: it would be overwritten.
copy(&mut s, table("s", 2, 1));
paste(&mut s);
let kept = |t: &Table| t.rows.iter().flat_map(|r| &r.cells).any(|c| c.blocks == before.blocks);
assert!(kept(t0(&s)), "the cell with the locked control survives");
}
/// A caret in a control that shows its placeholder: no rows are inserted above the caret's row;
/// the table nests in the cell as the ordinary paste does (#6739 review).
#[test]
fn a_control_showing_its_placeholder_gets_the_ordinary_paste_not_inserted_rows() {
let mut s = dest(1, 0);
s.run("developer.plainText", &json!({})).unwrap();
let before = s.doc.body[0].as_table().map(|t| t.rows.len());
copy(&mut s, table("s", 3, 3));
paste(&mut s);
assert_eq!(t0(&s).rows.len(), before.unwrap_or(0), "no rows inserted above the caret's row");
assert!(nested(t0(&s)), "the table nests in the cell");
}
#[test]
fn paste_from_before_a_block_control_replaces_its_placeholder() {
let mut s = dest(1, 0);
let start = s.sel.focus.clone();
s.run("developer.plainText", &json!({})).unwrap();
let range = s.doc.control_at(&s.sel.focus).unwrap();
assert_eq!(range.start, start);
assert!(range.control.showing_placeholder);
let placeholder = s.doc.para_at(&start).unwrap().text[range.content_start().off..range.end.off].to_owned();
assert!(!placeholder.is_empty());
s.doc.control_mut(&start).unwrap().block = true;
s.sel = Selection::caret(start);
copy(&mut s, table("s", 1, 3));
paste(&mut s);
assert_eq!(t0(&s).rows.len(), 3);
assert!(nested(t0(&s)));
assert!(!cell_text(&t0(&s).rows[1].cells[0]).contains(&placeholder));
}
/// A locked control in a text box anchored in a cell the copy would overwrite is not lost: the
/// paste nests instead (#6739 review).
#[test]
fn a_locked_control_in_a_text_box_of_an_overwritten_cell_is_kept() {
use wordcraft_doc::para::ShapeKind;
use wordcraft_doc::{ContentControl, ControlKind, ControlLock, InlineObject, PartKind};
let mut s = dest(0, 0);
let mut ctl = ContentControl::new(ControlKind::RichText);
ctl.lock = ControlLock::SdtContentLocked;
let mut inner = Paragraph::with_text("Locked", Default::default());
inner.insert_object(0, InlineObject::ControlStart { control: Box::new(ctl) }, &Default::default()).unwrap();
let end = inner.text.chars().count();
inner.insert_object(end, InlineObject::ControlEnd, &Default::default()).unwrap();
let id = s.doc.add_part(PartKind::TextBox, vec![para_block(inner)]);
let shape = InlineObject::Shape {
kind: ShapeKind::TextBox,
w: 72.0,
h: 36.0,
fill: None,
stroke: None,
stroke_width: 0.75,
float: Default::default(),
story: Some(id),
freeform: None,
effects: Default::default(),
extra: Default::default(),
};
let mut anchor = Paragraph::with_text("Box", Default::default());
anchor.insert_object(0, shape, &Default::default()).unwrap();
if let Some(Block::Table(t)) = s.doc.body.get_mut(0).map(Arc::make_mut) {
t.rows[1].cells[0].blocks = vec![para_block(anchor)];
}
let before = t0(&s).rows[1].cells[0].blocks.clone();
// One column of two cells from the caret in the top cell: the cell with the box is overwritten.
copy(&mut s, table("s", 2, 1));
paste(&mut s);
let kept = |t: &Table| t.rows.iter().flat_map(|r| &r.cells).any(|c| c.blocks == before);
assert!(kept(t0(&s)), "the cell anchoring the text box survives");
assert!(nested(t0(&s)), "the table nests in the cell instead");
}
/// A row-level content control on a row the copy would overwrite is not bypassed: the paste nests
/// instead (#6739 review).
#[test]
fn a_row_level_control_on_an_overwritten_row_declines_the_overwrite() {
use wordcraft_doc::{ContentControl, ControlKind, ControlLock};
let mut s = dest(0, 0);
let mut ctl = ContentControl::new(ControlKind::RichText);
ctl.lock = ControlLock::SdtContentLocked;
if let Some(Block::Table(t)) = s.doc.body.get_mut(0).map(Arc::make_mut) {
t.rows[1].controls.open.push(ctl);
t.rows[1].controls.close = 1;
}
let before = grid(t0(&s));
copy(&mut s, table("s", 2, 1));
paste(&mut s);
assert_eq!(grid(t0(&s))[1], before[1], "the row under the control is not overwritten");
assert!(nested(t0(&s)), "the table nests in the cell instead");
}
#[test]
fn an_overwrite_inside_a_spanning_row_control_preserves_the_row() {
use wordcraft_doc::{ContentControl, ControlKind, ControlLock};
let mut s = dest(1, 1);
let mut control = ContentControl::new(ControlKind::RichText);
control.lock = ControlLock::SdtContentLocked;
let destination = s.doc.table_mut(StoryRef::Body, &Path(vec![0])).unwrap();
destination.rows[0].controls.open.push(control);
destination.rows[2].controls.close = 1;
copy(&mut s, table("s", 1, 1));
paste(&mut s);
let table = t0(&s);
let cell = &table.rows[1].cells[1];
assert!(cell_text(cell).lines().any(|line| line == "d22"));
assert!(cell.blocks.iter().any(|block| block.as_table().is_some()));
assert_eq!(table.rows[0].controls.open[0].lock, ControlLock::SdtContentLocked);
assert_eq!(table.rows[2].controls.close, 1);
}
+2 -18
View File
@@ -30,7 +30,7 @@ pub use face::{FALLBACK_FAMILY, FaceRef, FontFace, bundled};
use fallback_data::{Coverage, RUN_FALLBACK_CACHE_CHARS, SYS_FALLBACK_MAX_FILE, file_coverage, ranges_hold};
#[cfg(not(target_arch = "wasm32"))]
use fallback_data::{CoverageIndex, SysFallback};
use fallback_data::{DiagramFallbackCache, FallbackCache, RunFallbackCache};
use fallback_data::{FallbackCache, RunFallbackCache};
#[cfg(not(target_arch = "wasm32"))]
use names::CatalogEntry;
pub use names::{LocalName, base_style, name_language_matches, system_font_dirs};
@@ -56,13 +56,6 @@ pub struct FontDb {
/// (Thai, #59) got slower with every font loaded.
fallbacks: RwLock<FallbackCache>,
run_fallbacks: RwLock<RunFallbackCache>,
diagram_fallbacks: RwLock<DiagramFallbackCache>,
#[cfg(test)]
diagram_searches: std::sync::atomic::AtomicU64,
#[cfg(test)]
diagram_search_hook: Mutex<Option<Box<dyn FnOnce(&FontDb) + Send>>>,
#[cfg(test)]
diagram_publish_hook: Mutex<Option<Box<dyn FnOnce(&FontDb) + Send>>>,
#[cfg(not(target_arch = "wasm32"))]
catalog: RwLock<Vec<CatalogEntry>>,
/// Fonts the user added at run time, and the folder they are stored in (#582).
@@ -126,13 +119,6 @@ impl FontDb {
hinters: Mutex::new(HashMap::new()),
fallbacks: RwLock::new(FallbackCache::default()),
run_fallbacks: RwLock::new(RunFallbackCache::default()),
diagram_fallbacks: RwLock::new(DiagramFallbackCache::default()),
#[cfg(test)]
diagram_searches: std::sync::atomic::AtomicU64::new(0),
#[cfg(test)]
diagram_search_hook: Mutex::new(None),
#[cfg(test)]
diagram_publish_hook: Mutex::new(None),
#[cfg(not(target_arch = "wasm32"))]
catalog: RwLock::new(Vec::new()),
user: RwLock::new(user::UserFonts::default()),
@@ -161,10 +147,8 @@ impl FontDb {
self.sys.lock().unwrap_or_else(std::sync::PoisonError::into_inner).enabled = on;
}
// Misses remembered while it was off may be found now.
self.generation.fetch_add(1, Ordering::AcqRel);
*self.fallbacks.write().unwrap_or_else(std::sync::PoisonError::into_inner) = FallbackCache::default();
self.fallbacks.write().unwrap_or_else(std::sync::PoisonError::into_inner).map.clear();
*self.run_fallbacks.write().unwrap_or_else(std::sync::PoisonError::into_inner) = RunFallbackCache::default();
*self.diagram_fallbacks.write().unwrap_or_else(std::sync::PoisonError::into_inner) = DiagramFallbackCache::default();
#[cfg(target_arch = "wasm32")]
let _ = on;
}
-171
View File
@@ -396,147 +396,6 @@ impl FontFace {
pub fn is_east_asian(&self) -> bool {
self.skrifa().is_some_and(|f| east_asian_font(&f))
}
/// Is this a serif face? Checks family name conventions (e.g. Mincho, Song, Times vs Sans, Gothic, Arial),
/// falling back to the OS/2 family class and Panose serif style.
pub fn is_serif(&self) -> bool {
if is_explicit_sans(&self.family) {
return false;
}
if is_explicit_serif(&self.family) {
return true;
}
use skrifa::raw::TableProvider;
if let Some(sk) = self.skrifa()
&& let Ok(os2) = sk.os2()
{
let class_id = (os2.s_family_class() >> 8) as u8;
if (1..=5).contains(&class_id) || class_id == 7 {
return true;
}
if class_id == 8 {
return false;
}
let panose = os2.panose_10();
if panose[0] == 2 {
let serif_style = panose[1];
if (2..=10).contains(&serif_style) {
return true;
}
if (11..=15).contains(&serif_style) {
return false;
}
}
}
false
}
}
/// Tokens identifying known sans-serif font families by naming convention (#5672).
const SANS_TOKENS: &[&str] = &[
"sans",
"gothic",
"hei",
"yahei",
"simhei",
"zenhei",
"heiti",
"meiryo",
"pingfang",
"dotum",
"gulim",
"malgun",
"arial",
"calibri",
"aptos",
"carlito",
"inter",
"helvetica",
"segoe",
"tahoma",
"verdana",
];
/// Tokens identifying known serif font families by naming convention (#5672).
const SERIF_TOKENS: &[&str] = &[
"serif",
"mincho",
"song",
"songti",
"simsun",
"nsimsun",
"fangsong",
"ming",
"mingti",
"batang",
"sun",
"times",
"cambria",
"georgia",
"garamond",
"palatino",
"century",
"bookman",
"baskerville",
"caladea",
"tinos",
];
/// Split a font family name into lowercased tokens along non-alphanumeric boundaries,
/// camelCase / acronym transitions, and letter-to-digit/digit-to-letter boundaries (#5672).
fn font_name_tokens(name: &str) -> Vec<String> {
let mut tokens = Vec::new();
let mut current = String::new();
let mut prev_char: Option<char> = None;
let mut chars = name.chars().peekable();
while let Some(c) = chars.next() {
if !c.is_alphanumeric() {
if !current.is_empty() {
tokens.push(std::mem::take(&mut current).to_ascii_lowercase());
}
prev_char = None;
continue;
}
let next_lower = chars.peek().is_some_and(|n| n.is_lowercase());
let is_split = if let Some(prev) = prev_char {
(prev.is_lowercase() && c.is_uppercase())
|| (prev.is_uppercase() && c.is_uppercase() && next_lower)
|| (prev.is_alphabetic() && c.is_numeric())
|| (prev.is_numeric() && c.is_alphabetic())
} else {
false
};
if is_split && !current.is_empty() {
tokens.push(std::mem::take(&mut current).to_ascii_lowercase());
}
current.push(c);
prev_char = Some(c);
}
if !current.is_empty() {
tokens.push(current.to_ascii_lowercase());
}
let flattened: String = name.chars().filter(|c| c.is_alphanumeric()).collect::<String>().to_ascii_lowercase();
if !flattened.is_empty() && !tokens.iter().any(|t| t == &flattened) {
tokens.push(flattened);
}
tokens
}
/// Does a family name explicitly identify a sans-serif font by whole tokens?
fn is_explicit_sans(name: &str) -> bool {
let tokens = font_name_tokens(name);
tokens.iter().any(|t| SANS_TOKENS.contains(&t.as_str()))
}
/// Does a family name explicitly identify a serif font by whole tokens?
fn is_explicit_serif(name: &str) -> bool {
let tokens = font_name_tokens(name);
tokens.iter().any(|t| SERIF_TOKENS.contains(&t.as_str()))
}
pub(super) static NEXT_ID: AtomicU32 = AtomicU32::new(1);
@@ -601,33 +460,3 @@ impl OutlinePen for FlipPen {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn whole_token_serif_sans_matching() {
// #5672: Whole tokens match rather than bare substrings ("hei", "sun").
assert!(!is_explicit_sans("Heisei Mincho"), "Heisei Mincho must not match sans 'hei'");
assert!(is_explicit_serif("Heisei Mincho"), "Heisei Mincho is serif");
assert!(!is_explicit_serif("Sunflower"), "Sunflower must not match serif 'sun'");
assert!(!is_explicit_sans("Sunflower"));
assert!(is_explicit_sans("SimHei"));
assert!(is_explicit_sans("STHeiti"));
assert!(is_explicit_sans("BIZ UDPGothic"));
assert!(is_explicit_sans("MS PGothic"));
assert!(is_explicit_sans("Microsoft YaHei"));
assert!(is_explicit_sans("WenQuanYi Zen Hei"));
assert!(is_explicit_sans("Source Sans 3"));
assert!(is_explicit_serif("SimSun"));
assert!(is_explicit_serif("NSimSun"));
assert!(is_explicit_serif("BIZ UDPMincho"));
assert!(is_explicit_serif("MS PMincho"));
assert!(is_explicit_serif("Shippori Mincho"));
assert!(is_explicit_serif("Source Serif 4"));
}
}
+21 -195
View File
@@ -1,9 +1,7 @@
use super::face::{FALLBACK_FAMILY, FontFace};
#[cfg(not(target_arch = "wasm32"))]
use super::fallback_data::{CoverageIndex, IndexedFile, SYS_MISSES_MAX, SYSTEM_FALLBACKS, file_stamp, ranges_hold, read_fallback_file};
use super::fallback_data::{
DiagramFallbackKey, FALLBACK_CACHE_MAX, RTL_FALLBACKS, RUN_FALLBACK_CACHE_CHARS, RUN_FALLBACK_CACHE_MAX, arabic_block, fallback_order,
};
use super::fallback_data::{FALLBACK_CACHE_MAX, RTL_FALLBACKS, RUN_FALLBACK_CACHE_CHARS, RUN_FALLBACK_CACHE_MAX, arabic_block, fallback_order};
use super::{Arc, FontDb};
#[cfg(not(target_arch = "wasm32"))]
use super::{HashMap, Ordering};
@@ -31,35 +29,28 @@ impl FontDb {
Some(if styled.family.eq_ignore_ascii_case(&base.family) && styled.covers(c) && styled.id != exclude { styled } else { base })
}
/// The fallback search, cached per (character, excluded face) until loaded faces or font
/// generation change.
/// The fallback search, cached per (character, excluded face) until more faces load.
fn cached_fallback(&self, c: char, exclude: u32) -> Option<Arc<FontFace>> {
let generation = self.generation();
let n = self.read_faces().len();
{
let cache = self.fallbacks.read().unwrap_or_else(std::sync::PoisonError::into_inner);
if cache.faces == n
&& cache.generation == generation
&& let Some(hit) = cache.map.get(&(c, exclude))
{
return hit.clone();
}
}
let (found, n) = self.search_fallback(c, exclude);
// Keyed by the face count and generation the answer was chosen from (a system fallback may
// have loaded fonts, and another thread may have loaded or changed fonts since: an answer
// from before that change is returned but not cached under the new state).
if n != self.read_faces().len() || generation != self.generation() {
// Keyed by the face count the answer was chosen from (a system fallback may have loaded
// fonts, and another thread may have loaded more since: an answer from before that load
// is returned but not cached under the new count).
if n != self.read_faces().len() {
return found;
}
let mut cache = self.fallbacks.write().unwrap_or_else(std::sync::PoisonError::into_inner);
if n != self.read_faces().len() || generation != self.generation() {
return found;
}
if cache.faces != n || cache.generation != generation || cache.map.len() >= FALLBACK_CACHE_MAX {
if cache.faces != n || cache.map.len() >= FALLBACK_CACHE_MAX {
cache.map.clear();
cache.faces = n;
cache.generation = generation;
}
cache.map.insert((c, exclude), found.clone());
found
@@ -160,36 +151,23 @@ impl FontDb {
set.sort_unstable();
set.dedup();
let key = (set, exclude, bold, italic);
let generation = self.generation();
let n = self.read_faces().len();
{
let cache = self.run_fallbacks.read().unwrap_or_else(std::sync::PoisonError::into_inner);
if cache.faces == n
&& cache.generation == generation
&& let Some(hit) = cache.map.get(&key)
{
return hit.clone();
}
}
// Keyed by the face count and generation the search last looked at, not the state after it:
// a face loaded or changed meanwhile by another thread (one its search, a family named by a
// document, or a user font change) must not be overwritten with a stale answer.
// Keyed by the face count the search last looked at, not the count after it: a face loaded
// meanwhile by another thread (one its search, or a family named by a document) must make
// a miss count as stale, not as the answer for the new count.
let (found, n) = self.search_run(&key.0, exclude, bold, italic);
if n != self.read_faces().len() || generation != self.generation() {
return found;
}
let mut cache = self.run_fallbacks.write().unwrap_or_else(std::sync::PoisonError::into_inner);
if n != self.read_faces().len() || generation != self.generation() {
return found;
}
if cache.faces != n
|| cache.generation != generation
|| cache.map.len() >= RUN_FALLBACK_CACHE_MAX
|| cache.chars.saturating_add(key.0.len()) > RUN_FALLBACK_CACHE_CHARS
{
if cache.faces != n || cache.map.len() >= RUN_FALLBACK_CACHE_MAX || cache.chars.saturating_add(key.0.len()) > RUN_FALLBACK_CACHE_CHARS {
cache.map.clear();
cache.faces = n;
cache.generation = generation;
cache.chars = 0;
}
cache.chars = cache.chars.saturating_add(key.0.len());
@@ -235,11 +213,7 @@ impl FontDb {
(true, false) => "Bold",
_ => "Italic",
};
let before_style = self.read_faces().len();
let styled = self.face(&base.family, style);
if before_style == checked {
checked = self.read_faces().len();
}
let face = if styled.family.eq_ignore_ascii_case(&base.family) && chars.iter().all(|c| styled.covers(*c)) && styled.id != exclude {
styled
} else {
@@ -260,140 +234,11 @@ impl FontDb {
(found, faces.len())
}
/// First face covering all characters in `chars`, preferring faces matching `prefer_serif`
/// (so a diagram maintains a consistent fallback face across its nodes matching the
/// diagram's primary style, #5672). Does not alter body text fallback ordering. Cached until
/// the loaded faces or font database generation changes, so page redraws do not repeat system scans.
pub fn fallback_for_diagram(&self, chars: &[char], exclude: u32, prefer_serif: bool) -> Option<Arc<FontFace>> {
if chars.is_empty() {
return None;
}
let mut set: Vec<char> = chars.to_vec();
set.sort_unstable();
set.dedup();
let key: DiagramFallbackKey = (set, exclude, prefer_serif);
let generation = self.generation();
let n = self.read_faces().len();
{
let cache = self.diagram_fallbacks.read().unwrap_or_else(std::sync::PoisonError::into_inner);
if cache.faces == n
&& cache.generation == generation
&& let Some(hit) = cache.map.get(&key)
{
return hit.clone();
}
}
// Keyed by the face count and generation the search last looked at, not the state after it:
// a face loaded or added meanwhile (for instance via `add_font`) must not be shadowed by
// caching an older answer under the newer face count.
let (found, n) = self.search_diagram(&key.0, exclude, prefer_serif);
if n != self.read_faces().len() || generation != self.generation() || key.0.len() > RUN_FALLBACK_CACHE_CHARS {
return found;
}
#[cfg(test)]
if let Some(hook) = self.diagram_publish_hook.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take() {
hook(self);
}
let mut cache = self.diagram_fallbacks.write().unwrap_or_else(std::sync::PoisonError::into_inner);
if n != self.read_faces().len() || generation != self.generation() {
return found;
}
if cache.faces != n
|| cache.generation != generation
|| cache.map.len() >= RUN_FALLBACK_CACHE_MAX
|| cache.chars.saturating_add(key.0.len()) > RUN_FALLBACK_CACHE_CHARS
{
cache.map.clear();
cache.faces = n;
cache.generation = generation;
cache.chars = 0;
}
cache.chars = cache.chars.saturating_add(key.0.len());
cache.map.insert(key, found.clone());
found
}
/// The face covering a diagram's missing character set, and the face count it was chosen from.
/// Prefers faces matching `prefer_serif`; when the best loaded face has a mismatched serif
/// classification, checks system font candidates and retains the loaded face only when no
/// matching candidate covers the full set (#5672).
fn search_diagram(&self, chars: &[char], exclude: u32, prefer_serif: bool) -> (Option<Arc<FontFace>>, usize) {
#[cfg(test)]
self.diagram_searches.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
#[cfg_attr(target_arch = "wasm32", allow(unused_mut))]
let (mut base, mut checked) = self.loaded_diagram_covering(chars, exclude, prefer_serif);
#[cfg(not(target_arch = "wasm32"))]
if base.is_none() || base.as_ref().is_some_and(|f| f.is_serif() != prefer_serif) {
for c in chars {
if self.read_faces().iter().any(|f| f.id != exclude && f.covers(*c) && f.is_serif() == prefer_serif) {
continue;
}
if self.system_fallback_matching(*c, Some((exclude, prefer_serif))) {
let (cand, cand_checked) = self.loaded_diagram_covering(chars, exclude, prefer_serif);
let matching = cand.as_ref().is_some_and(|f| f.is_serif() == prefer_serif);
if let Some(f) = cand {
base = Some(f);
checked = cand_checked;
} else if base.is_none() {
checked = cand_checked;
}
if matching {
break;
}
}
}
if base.as_ref().is_none_or(|f| f.is_serif() != prefer_serif) {
self.indexed_run_fallback_matching(chars, Some((exclude, prefer_serif)));
let (cand, cand_checked) = self.loaded_diagram_covering(chars, exclude, prefer_serif);
if let Some(f) = cand {
base = Some(f);
checked = cand_checked;
} else if base.is_none() {
checked = cand_checked;
}
}
}
#[cfg(test)]
if let Some(hook) = self.diagram_search_hook.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take() {
hook(self);
}
(base, checked)
}
/// The first face covering every char in `chars`, preferring matching `prefer_serif`,
/// and the number of loaded faces it was chosen from.
fn loaded_diagram_covering(&self, chars: &[char], exclude: u32, prefer_serif: bool) -> (Option<Arc<FontFace>>, usize) {
let faces = self.read_faces();
let rtl = chars.iter().any(|c| crate::is_rtl(*c) || arabic_block(*c));
let complex = chars.iter().copied().find(|c| crate::needs_layout_tables(*c));
let mut candidates: Vec<&Arc<FontFace>> = faces.iter().filter(|f| f.id != exclude && chars.iter().all(|c| f.covers(*c))).collect();
let rank = |f: &FontFace| {
if rtl { RTL_FALLBACKS.iter().position(|n| f.family.eq_ignore_ascii_case(n)).unwrap_or(RTL_FALLBACKS.len()) } else { 0 }
};
let shaping = |f: &FontFace| match complex {
Some(c) => (!f.has_layout_tables(), crate::fallback_rank(c, &f.family)),
None => (false, 0),
};
let serif_mismatch = |f: &FontFace| f.is_serif() != prefer_serif;
candidates.sort_by_cached_key(|f| {
(rank(f), shaping(f), serif_mismatch(f), !f.family.eq_ignore_ascii_case(FALLBACK_FAMILY), f.italic, (f.weight - 400.0).abs() as i32)
});
(candidates.first().map(|f| (*f).clone()), faces.len())
}
/// Load a system font covering `c` (preferred fallback families first, then any cataloged
/// file under 40 MB, both found through the coverage index). Returns true if one was loaded.
/// Misses are remembered.
#[cfg(not(target_arch = "wasm32"))]
fn system_fallback(&self, c: char) -> bool {
self.system_fallback_matching(c, None)
}
/// Like [`Self::system_fallback`], optionally requiring the covering face to not be `exclude`
/// and to match `prefer_serif` (so a loaded mismatched face does not short-circuit the search
/// before a matching installed candidate is checked, #5672).
#[cfg(not(target_arch = "wasm32"))]
fn system_fallback_matching(&self, c: char, style: Option<(u32, bool)>) -> bool {
if c.is_control() || c.is_whitespace() {
return false;
}
@@ -403,9 +248,7 @@ impl FontDb {
return false;
}
}
let covered = |db: &FontDb| {
db.read_faces().iter().any(|f| f.covers(c) && style.is_none_or(|(exclude, prefer_serif)| f.id != exclude && f.is_serif() == prefer_serif))
};
let covered = |db: &FontDb| db.read_faces().iter().any(|f| f.covers(c));
let cataloged: Vec<String> = self.read_catalog().iter().map(|e| e.family.clone()).collect();
let rtl = crate::is_rtl(c) || arabic_block(c);
let preferred = RTL_FALLBACKS.iter().filter(|_| rtl);
@@ -427,20 +270,14 @@ impl FontDb {
return true;
}
}
if style.is_none() {
if self.indexed_fallback(c) {
return true;
}
} else if self.load_indexed_matching(&[c], false, style) {
if self.indexed_fallback(c) {
return true;
}
if style.is_none() || !self.read_faces().iter().any(|f| f.covers(c)) {
let mut sys = self.sys.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
if sys.misses.len() >= SYS_MISSES_MAX {
sys.misses.clear();
}
sys.misses.insert(c);
let mut sys = self.sys.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
if sys.misses.len() >= SYS_MISSES_MAX {
sys.misses.clear();
}
sys.misses.insert(c);
false
}
@@ -487,7 +324,7 @@ impl FontDb {
/// now covers `c`.
#[cfg(not(target_arch = "wasm32"))]
fn indexed_fallback(&self, c: char) -> bool {
self.load_indexed_matching(&[c], false, None)
self.load_indexed(&[c], false)
}
/// Load the family of the first cataloged font file (in path order) that maps every char of a
@@ -495,17 +332,10 @@ impl FontDb {
/// before the Regular.
#[cfg(not(target_arch = "wasm32"))]
fn indexed_run_fallback(&self, chars: &[char]) {
self.indexed_run_fallback_matching(chars, None);
}
/// Like [`Self::indexed_run_fallback`], optionally requiring a loaded face matching
/// `(exclude, prefer_serif)` to stop scanning (#5672).
#[cfg(not(target_arch = "wasm32"))]
fn indexed_run_fallback_matching(&self, chars: &[char], style: Option<(u32, bool)>) {
if !self.sys.lock().unwrap_or_else(std::sync::PoisonError::into_inner).enabled || chars.iter().any(|c| c.is_control()) {
return;
}
self.load_indexed_matching(chars, true, style);
self.load_indexed(chars, true);
}
/// Load the cataloged font files (in path order) that map every char of `chars`, reading the
@@ -514,12 +344,8 @@ impl FontDb {
/// of it isn't loaded yet). A collection's faces only together may map them: the search then
/// goes on. Returns whether a loaded face now covers them all.
#[cfg(not(target_arch = "wasm32"))]
fn load_indexed_matching(&self, chars: &[char], whole_family: bool, style: Option<(u32, bool)>) -> bool {
let covered = |db: &FontDb| {
db.read_faces().iter().any(|f| {
style.is_none_or(|(exclude, prefer_serif)| f.id != exclude && f.is_serif() == prefer_serif) && chars.iter().all(|c| f.covers(*c))
})
};
fn load_indexed(&self, chars: &[char], whole_family: bool) -> bool {
let covered = |db: &FontDb| db.read_faces().iter().any(|f| chars.iter().all(|c| f.covers(*c)));
let cps: Vec<u32> = chars.iter().map(|c| u32::from(*c)).collect();
let maps_all = |ranges: &[(u32, u32)]| cps.iter().all(|cp| ranges_hold(ranges, *cp));
let mut index = self.coverage_index();
+1 -18
View File
@@ -281,7 +281,6 @@ pub(super) fn arabic_block(c: char) -> bool {
#[derive(Default)]
pub(super) struct FallbackCache {
pub(super) faces: usize,
pub(super) generation: u64,
pub(super) map: HashMap<(char, u32), Option<Arc<FontFace>>>,
}
@@ -289,31 +288,15 @@ pub(super) struct FallbackCache {
pub(super) type RunFallbackKey = (Vec<char>, u32, bool, bool);
/// [`FontDb::fallback_for_run`] results: (sorted, deduplicated chars, excluded face, bold,
/// italic) → face, valid while the loaded face count is `faces` and [`FontDb::generation`] is
/// `generation`.
/// italic) → face, valid while the loaded face count is `faces`.
#[derive(Default)]
pub(super) struct RunFallbackCache {
pub(super) faces: usize,
pub(super) generation: u64,
/// Chars held in the keys (bounds memory: hostile runs can be long).
pub(super) chars: usize,
pub(super) map: HashMap<RunFallbackKey, Option<Arc<FontFace>>>,
}
/// What a diagram-level fallback lookup is keyed by: sorted, deduplicated chars, excluded face,
/// serif preference.
pub(super) type DiagramFallbackKey = (Vec<char>, u32, bool);
/// [`FontDb::fallback_for_diagram`] results, valid while the loaded face count and generation match.
#[derive(Default)]
pub(super) struct DiagramFallbackCache {
pub(super) faces: usize,
pub(super) generation: u64,
/// Chars held in the keys (bounds memory: diagram text can be long).
pub(super) chars: usize,
pub(super) map: HashMap<DiagramFallbackKey, Option<Arc<FontFace>>>,
}
/// Most cached run-level fallbacks, and most chars in their keys, before the cache is reset.
pub(super) const RUN_FALLBACK_CACHE_MAX: usize = 4096;
-199
View File
@@ -893,202 +893,3 @@ fn catalog_postscript_names() {
assert!(!has(&db.families(), "SysfontSans-Bold"));
std::fs::remove_dir_all(dir).unwrap();
}
/// Diagram fallback matches the primary font's serif/sans classification while body-text
/// fallback preserves loaded order (#5672), and changing user fonts invalidates run fallbacks.
#[test]
fn fallback_order_matches_primary_font_serif_nature() {
// #5672: When picking fallback faces for diagrams, sans-serif primary fonts prefer sans-serif
// fallback fonts, and serif primary fonts prefer serif fallback fonts. Body text fallback
// order remains unaffected.
use crate::fontdb::fallback_data::fallback_order;
let dir = font_dir("serif-sans-fallback");
std::fs::write(dir.join("TestMincho.ttf"), mapping("SourceSans3-Regular.ttf", "Test Mincho 1", 0xF_0010, 0xF_0011)).unwrap();
std::fs::write(dir.join("TestGothic.ttf"), mapping("SourceSans3-Regular.ttf", "Test Gothic 1", 0xF_0010, 0xF_0011)).unwrap();
let db = FontDb::with_font_dirs(vec![dir.clone()]);
db.set_system_fallback(false);
let mincho = db.face("Test Mincho 1", "Regular");
let gothic = db.face("Test Gothic 1", "Regular");
assert!(mincho.is_serif(), "Mincho is serif");
assert!(!gothic.is_serif(), "Gothic is sans");
let sans_primary = db.face("Source Sans 3", "Regular");
let serif_primary = db.face("Source Serif 4", "Regular");
// Diagram fallback: matches serif/sans nature of primary font.
let diag_run = ['\u{F0010}', '\u{F0011}'];
let diag_sans = db.fallback_for_diagram(&diag_run, sans_primary.id(), sans_primary.is_serif()).unwrap();
assert_eq!(diag_sans.family, "Test Gothic 1", "sans-serif diagram prefers sans-serif fallback (Gothic)");
let diag_serif = db.fallback_for_diagram(&diag_run, serif_primary.id(), serif_primary.is_serif()).unwrap();
assert_eq!(diag_serif.family, "Test Mincho 1", "serif diagram prefers serif fallback (Mincho)");
// Body text fallback: fallback_order is not altered by the primary font's serif/sans nature.
let faces = db.read_faces();
let for_sans = fallback_order(&faces, sans_primary.id(), false, None);
let for_serif = fallback_order(&faces, serif_primary.id(), false, None);
let mincho_sans = for_sans.iter().position(|f| f.family == "Test Mincho 1").unwrap();
let gothic_sans = for_sans.iter().position(|f| f.family == "Test Gothic 1").unwrap();
let mincho_serif = for_serif.iter().position(|f| f.family == "Test Mincho 1").unwrap();
let gothic_serif = for_serif.iter().position(|f| f.family == "Test Gothic 1").unwrap();
assert_eq!(mincho_sans < gothic_sans, mincho_serif < gothic_serif, "body text fallback order does not invert between sans and serif primaries");
drop(faces);
// Replacing a user font with another of the same face count invalidates both fallbacks and run_fallbacks.
db.install_font("UserGothic.ttf", &mapping("SourceSans3-Regular.ttf", "User1 Gothic1", 0xF_0001, 0xF_0002)).unwrap();
let run = ['\u{F0001}', '\u{F0002}'];
let first_char = db.fallback_for('\u{F0001}', serif_primary.id()).unwrap();
assert_eq!(first_char.family, "User1 Gothic1");
assert_eq!(db.fallbacks.read().unwrap().generation, db.generation());
let first = db.fallback_for_run(&run, serif_primary.id(), false, false).unwrap();
assert_eq!(first.family, "User1 Gothic1");
let face_count = db.read_faces().len();
db.remove_user_font("User1 Gothic1").unwrap();
db.install_font("UserMincho.ttf", &mapping("SourceSans3-Regular.ttf", "User2 Mincho2", 0xF_0001, 0xF_0002)).unwrap();
assert_eq!(db.read_faces().len(), face_count);
let updated_char = db.fallback_for('\u{F0001}', serif_primary.id()).unwrap();
assert_eq!(updated_char.family, "User2 Mincho2");
assert_eq!(db.fallbacks.read().unwrap().generation, db.generation());
let updated = db.fallback_for_run(&run, serif_primary.id(), false, false).unwrap();
assert_eq!(updated.family, "User2 Mincho2");
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn diagram_fallback_checks_system_fonts_when_loaded_face_mismatches_serif() {
let dir = font_dir("diag-mismatch");
let regular = "SourceSans3-Regular.ttf";
// Put a preferred non-covering family ("Malgun Gothic") and an alphabetically earlier serif
// font ("AA Sys Mincho") in the directory alongside the matching sans CJK candidate
// ("Sys Gothic 11"). Neither the non-covering preferred family nor the earlier serif font may
// short-circuit the search just because a mismatched loaded face already covers the chars.
std::fs::write(dir.join("00_MalgunGothic.ttf"), mapping(regular, "Malgun Gothic", 0x0041, 0x005A)).unwrap();
std::fs::write(dir.join("AA_SysMincho.ttf"), mapping(regular, "AA Sys Mincho", 0xF_0020, 0xF_0021)).unwrap();
std::fs::write(dir.join("SysGothic.ttf"), mapping(regular, "Sys Gothic 11", 0xF_0020, 0xF_0021)).unwrap();
let db = FontDb::with_font_dirs(vec![dir.clone()]);
// Pre-load a serif font covering the same characters into db as a document font.
db.add_document_fonts(vec![(mapping(regular, "Load Mincho 1", 0xF_0020, 0xF_0021), "Load Mincho 1".to_string())]);
let mincho = db.face("Load Mincho 1", "Regular");
assert!(mincho.is_serif());
// 1. Single-character sans-serif diagram: loaded face is serif (mismatched), so search_diagram
// must check past Malgun Gothic (non-covering preferred family) and AA Sys Mincho (earlier
// serif cataloged file) to find & load "Sys Gothic 11" (sans-serif).
let single = ['\u{F0020}'];
let sans = db.fallback_for_diagram(&single, 0, false).unwrap();
assert_eq!(sans.family, "Sys Gothic 11", "sans diagram checks system fonts to find matching sans candidate");
assert!(!sans.is_serif());
// 2. Multi-character run also resolves to the matching sans candidate.
let run = ['\u{F0020}', '\u{F0021}'];
let sans_run = db.fallback_for_diagram(&run, 0, false).unwrap();
assert_eq!(sans_run.family, "Sys Gothic 11");
// 3. When no matching candidate covers the run, retain the mismatched loaded face.
let uncataloged_run = ['\u{F0020}'];
let retained = db.fallback_for_diagram(&uncataloged_run, sans.id(), false).unwrap();
assert_eq!(retained.family, "Load Mincho 1", "retains loaded face when no matching candidate covers the run");
db.remove_document_fonts(&["Load Mincho 1"]);
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn diagram_fallback_caches_a_mismatched_loaded_face_after_system_search() {
let dir = font_dir("diag-fallback-cache");
let regular = "SourceSans3-Regular.ttf";
std::fs::write(dir.join("CacheGothic.ttf"), mapping(regular, "Cache Gothic1", 0xF_0030, 0xF_0031)).unwrap();
let db = FontDb::with_font_dirs(vec![dir.clone()]);
db.add_document_fonts(vec![(mapping(regular, "Loaded Gothic", 0xF_0030, 0xF_0031), "Loaded Gothic".to_string())]);
let primary = db.face("Source Serif 4", "Regular");
let run = ['\u{F0030}', '\u{F0031}'];
let first = db.fallback_for_diagram(&run, primary.id(), true).unwrap();
assert_eq!(first.family, "Loaded Gothic", "retain the loaded mismatched face when no serif face covers the run");
let reads = db.coverage.lock().unwrap().reads;
assert!(reads > 0, "the initial search reaches the system-font coverage index");
assert_eq!(db.diagram_searches.load(std::sync::atomic::Ordering::Relaxed), 1);
assert_eq!(db.fallback_for_diagram(&run, primary.id(), true).unwrap().id(), first.id());
assert_eq!(db.diagram_searches.load(std::sync::atomic::Ordering::Relaxed), 1, "the redraw reuses the diagram fallback");
assert_eq!(db.coverage.lock().unwrap().reads, reads);
db.install_font("UserMincho.ttf", &mapping(regular, "User Mincho 1", 0xF_0030, 0xF_0031)).unwrap();
assert_eq!(db.fallback_for_diagram(&run, primary.id(), true).unwrap().family, "User Mincho 1");
assert_eq!(db.diagram_searches.load(std::sync::atomic::Ordering::Relaxed), 2, "adding a user font invalidates the cached result");
let face_count = db.read_faces().len();
db.remove_user_font("User Mincho 1").unwrap();
db.install_font("UserMincho.ttf", &mapping(regular, "User Mincho 2", 0xF_0030, 0xF_0031)).unwrap();
assert_eq!(db.read_faces().len(), face_count);
assert_eq!(db.fallback_for_diagram(&run, primary.id(), true).unwrap().family, "User Mincho 2");
assert_eq!(db.diagram_searches.load(std::sync::atomic::Ordering::Relaxed), 3, "generation invalidates the cache when face count stays unchanged");
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn diagram_fallback_skips_stale_cache_publish_when_add_font_arrives_between_selection_and_publication() {
let dir = font_dir("diag-concurrent-add-font");
let regular = "SourceSans3-Regular.ttf";
let italic = "SourceSans3-It.ttf";
let db = FontDb::with_font_dirs(vec![dir.clone()]);
let primary = db.face("Source Sans 3", "Regular");
assert!(!primary.is_serif());
// 1. A matching sans face arrives via `add_font` (no generation bump) after `search_diagram`
// selects the loaded mismatched serif face and before `search_diagram` returns its count.
assert!(db.add_font(mapping(regular, "Load Mincho A", 0xF_0040, 0xF_0041)) > 0);
let arriving_a = mapping(regular, "New Gothic AA", 0xF_0040, 0xF_0041);
*db.diagram_search_hook.lock().unwrap() = Some(Box::new(move |db| {
assert!(db.add_font(arriving_a) > 0);
}));
let gen_before = db.generation();
let run_a = ['\u{F0040}', '\u{F0041}'];
let first_a = db.fallback_for_diagram(&run_a, primary.id(), false).unwrap();
assert_eq!(first_a.family, "Load Mincho A");
assert_eq!(db.generation(), gen_before, "add_font does not change generation");
assert_ne!(
db.diagram_fallbacks.read().unwrap().faces,
db.read_faces().len(),
"stale selection from before add_font must not be cached under the newer face count"
);
let second_a = db.fallback_for_diagram(&run_a, primary.id(), false).unwrap();
assert_eq!(second_a.family, "New Gothic AA", "subsequent lookup sees the newly added matching face");
assert_eq!(db.diagram_fallbacks.read().unwrap().faces, db.read_faces().len());
let searches_after_a = db.diagram_searches.load(std::sync::atomic::Ordering::Relaxed);
assert_eq!(db.fallback_for_diagram(&run_a, primary.id(), false).unwrap().id(), second_a.id());
assert_eq!(db.diagram_searches.load(std::sync::atomic::Ordering::Relaxed), searches_after_a);
// 2. Fast-path match (no system search): an upright sans face arrives via `add_font` after
// `loaded_diagram_covering` picks an italic sans face and before `search_diagram` returns.
assert!(db.add_font(mapping(italic, "Load Gothic C", 0xF_0060, 0xF_0061)) > 0);
let arriving_c = mapping(regular, "New Gothic CC", 0xF_0060, 0xF_0061);
*db.diagram_search_hook.lock().unwrap() = Some(Box::new(move |db| {
assert!(db.add_font(arriving_c) > 0);
}));
let run_c = ['\u{F0060}', '\u{F0061}'];
let first_c = db.fallback_for_diagram(&run_c, primary.id(), false).unwrap();
assert_eq!(first_c.family, "Load Gothic C");
assert_eq!(db.generation(), gen_before);
assert_ne!(db.diagram_fallbacks.read().unwrap().faces, db.read_faces().len());
let second_c = db.fallback_for_diagram(&run_c, primary.id(), false).unwrap();
assert_eq!(second_c.family, "New Gothic CC", "fast-path selection also avoids caching under a newer face count");
// 3. A matching sans face arrives via `add_font` after `search_diagram` returns and before
// `diagram_fallbacks.write()` publishes the entry.
assert!(db.add_font(mapping(regular, "Load Mincho B", 0xF_0050, 0xF_0051)) > 0);
let arriving_b = mapping(regular, "New Gothic BB", 0xF_0050, 0xF_0051);
*db.diagram_publish_hook.lock().unwrap() = Some(Box::new(move |db| {
assert!(db.add_font(arriving_b) > 0);
}));
let run_b = ['\u{F0050}', '\u{F0051}'];
let first_b = db.fallback_for_diagram(&run_b, primary.id(), false).unwrap();
assert_eq!(first_b.family, "Load Mincho B");
assert_eq!(db.generation(), gen_before);
assert_ne!(db.diagram_fallbacks.read().unwrap().faces, db.read_faces().len());
let second_b = db.fallback_for_diagram(&run_b, primary.id(), false).unwrap();
assert_eq!(second_b.family, "New Gothic BB");
let _ = std::fs::remove_dir_all(dir);
}
+1 -18
View File
@@ -481,21 +481,6 @@ impl FontDb {
added
}
/// Remove document fonts added for `families`: their faces leave the font list
/// and cached fallback choices are forgotten ([`FontDb::generation`]).
#[cfg(any(test, feature = "test-support"))]
pub fn remove_document_fonts(&self, families: &[&str]) {
let ids: Vec<u32> = {
let faces = self.read_faces();
faces.iter().filter(|f| families.iter().any(|name| f.named(name))).map(|f| f.id).collect()
};
if ids.is_empty() {
return;
}
self.faces.write().unwrap_or_else(|e| e.into_inner()).retain(|f| !ids.contains(&f.id));
self.fonts_changed();
}
/// Check the faces in `sfnt` and add the new ones, recording them as a user font.
fn add_user_faces(&self, name: &str, sfnt: Vec<u8>, path: Option<PathBuf>) -> Result<UserFont, UserFontError> {
if self.read_user().fonts.len() >= MAX_USER_FONTS {
@@ -558,10 +543,8 @@ impl FontDb {
/// Forget cached fallback choices and tell watchers ([`FontDb::generation`]).
fn fonts_changed(&self) {
self.fallbacks.write().unwrap_or_else(|e| e.into_inner()).map.clear();
self.generation.fetch_add(1, Ordering::AcqRel);
*self.fallbacks.write().unwrap_or_else(|e| e.into_inner()) = super::FallbackCache::default();
*self.run_fallbacks.write().unwrap_or_else(|e| e.into_inner()) = super::RunFallbackCache::default();
*self.diagram_fallbacks.write().unwrap_or_else(std::sync::PoisonError::into_inner) = super::DiagramFallbackCache::default();
}
/// Remove the user fonts that added `family` (a typographic or legacy family name): their
-51
View File
@@ -1207,54 +1207,3 @@ fn latex_export_keeps_repeated_spaces() {
let d = crate::import("tex", tex.as_bytes()).unwrap().unwrap();
assert_eq!(para_texts(&d), vec!["a b c".to_string()]);
}
/// Container `background-color` imports and round-trips as paragraph shading (including mixed
/// inline highlights and blank lines), while inline `<span style="background-color:...">` and
/// `<mark>` highlights remain character shading (#6157).
#[test]
fn html_container_shading_is_paragraph_shading_while_inline_highlight_stays_on_runs() {
let html = concat!(
r#"<div style="background-color:#1e1e1e"><p><span style="color:#569cd6">const</span> x = 1;</p></div>"#,
r#"<p><span style="background-color:#ffff00">highlighted</span></p>"#,
r#"<p><mark>marked</mark></p>"#,
r#"<div style="background-color:#1e1e1e"><p>text <code style="background-color:#eeeeee">x</code></p></div>"#,
r#"<div style="background-color:#1e1e1e"><div>a</div><div>&nbsp;</div><div>b</div></div>"#,
);
let doc = crate::html::import(html);
assert_eq!(doc.body.len(), 7);
let Block::Para(code) = &*doc.body[0] else { panic!("expected code paragraph") };
assert_eq!(code.props.shading, Some(wordcraft_doc::Rgb(0x1e, 0x1e, 0x1e)));
assert!(code.runs.iter().all(|r| r.props.shading.is_none()), "container background must not leak to runs");
let Block::Para(span_hl) = &*doc.body[1] else { panic!("expected highlighted paragraph") };
assert_eq!(span_hl.props.shading, None, "inline span highlight must not become paragraph shading");
assert_eq!(span_hl.runs.first().and_then(|r| r.props.shading), Some(wordcraft_doc::Rgb(0xff, 0xff, 0x00)));
let Block::Para(mark_hl) = &*doc.body[2] else { panic!("expected mark paragraph") };
assert_eq!(mark_hl.props.shading, None, "inline <mark> must not become paragraph shading");
assert_eq!(mark_hl.runs.first().and_then(|r| r.props.shading), Some(wordcraft_doc::Rgb(0xff, 0xff, 0x00)));
let Block::Para(mixed) = &*doc.body[3] else { panic!("expected mixed paragraph") };
assert_eq!(mixed.props.shading, Some(wordcraft_doc::Rgb(0x1e, 0x1e, 0x1e)));
assert_eq!(mixed.props_of_char(0).shading, None, "unhighlighted text in shaded container has no run shading");
assert_eq!(mixed.props_of_char(5).shading, Some(wordcraft_doc::Rgb(0xee, 0xee, 0xee)), "inline <code> keeps its own run shading");
for idx in [4, 5, 6] {
let Block::Para(line) = &*doc.body[idx] else { panic!("expected block {idx}") };
assert_eq!(line.props.shading, Some(wordcraft_doc::Rgb(0x1e, 0x1e, 0x1e)), "line {idx} (blank included) keeps container shading");
}
for exported in [crate::html::export(&doc), crate::html::export_fragment(&doc)] {
let back = crate::html::import(&exported);
let Block::Para(p0) = &*back.body[0] else { panic!("expected paragraph 0") };
let Block::Para(p1) = &*back.body[1] else { panic!("expected paragraph 1") };
let Block::Para(p2) = &*back.body[2] else { panic!("expected paragraph 2") };
assert_eq!(p0.props.shading, Some(wordcraft_doc::Rgb(0x1e, 0x1e, 0x1e)), "{exported}");
assert!(p0.runs.iter().all(|r| r.props.shading.is_none()), "{exported}");
assert_eq!(p1.props.shading, None, "{exported}");
assert_eq!(p1.runs.first().and_then(|r| r.props.shading), Some(wordcraft_doc::Rgb(0xff, 0xff, 0x00)), "{exported}");
assert_eq!(p2.props.shading, None, "<p><mark>x</mark></p> round-trips as run shading: {exported}");
assert_eq!(p2.runs.first().and_then(|r| r.props.shading), Some(wordcraft_doc::Rgb(0xff, 0xff, 0x00)), "{exported}");
}
}
+8 -189
View File
@@ -1,8 +1,7 @@
use super::ctx::{Ctx, Joining, page_anchored};
use super::ctx::{Ctx, page_anchored};
use super::floats::{
ObjFrame, ObjectPlacement, WrapArea, align_in, float_rect, floating, left_out_objects, place_objects, rel_exclusions, wrap_area,
};
use super::flow::again;
use super::page::PageFrame;
use super::placed::Placed;
use super::table_flow::below;
@@ -263,19 +262,12 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
let frames = !matches!(story, StoryRef::Part(id) if ctx.doc.parts.get(&id).is_some_and(|p| p.kind == wordcraft_doc::PartKind::TextBox));
// The bottom of the last paragraph's lines.
let mut prev_end = 0.0f32;
// Where the last paragraph, whose mark is hidden, ended: the next one goes on from there.
let mut joint: Option<Joint> = None;
let outer_joined = ctx.joined;
for (i, b) in blocks.iter().enumerate() {
last_top = y;
let mut path = prefix.to_vec();
path.push(i as u32);
match &**b {
Block::Para(p) => {
// A paragraph after one whose mark is hidden goes on from that one's last line
// (Word, #3986; see `Joint`); one that shows nothing passes the place on.
let (mark_hidden, shows_nothing, taken) = Joint::arrive(ctx, &mut joint, (i, p), (width, frames), table);
let p = taken.as_ref().map_or(p, |t| &t.para);
let label = ctx.next_label(p);
let listed = label.is_some();
let mut pl = ctx.para_labelled(p, width, table, &[], label.clone());
@@ -314,10 +306,8 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
});
// Paragraph-relative floats start above the effective space before, as in the
// body path. Keep text and wrap exclusions relative to the text's actual top.
// A paragraph going on from a shared line has its origin at that line's top.
let para_top = taken.as_ref().map_or(y, |t| t.joint.top);
let para_top = y;
y += if i == 0 { before } else { before.max(0.0) };
TakenUp::start(taken.as_ref(), &mut y, &mut excl);
// Floating objects anchored here: place them, then wrap the text around them.
// One left out of the layout (hidden, or deleted in the final text) takes no room.
let mut floats = HashMap::new();
@@ -364,11 +354,10 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
if !rel.is_empty() {
pl = ctx.para_labelled(p, width, table, &rel, label);
}
TakenUp::clear(taken.as_ref(), &mut excl);
// Bordered paragraphs: room for their borders, those of a group joined in one box.
let cell = table.map(|t| &t.para);
let (above, below) = (joined(ctx.doc, blocks, i, i.checked_sub(1), cell), joined(ctx.doc, blocks, i, Some(i + 1), cell));
let mut edges = Edges::own(&pl, 0, pl.lines.len()).sharing(&pl);
let mut edges = Edges::own(&pl, 0, pl.lines.len());
if above {
edges.top = 0.0;
}
@@ -381,7 +370,6 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
edges.up = (y + lead - prev_end).max(0.0);
}
prev_end = push_para(&mut items, (story, &path), &pl, (0, pl.lines.len()), (0.0, y + lead), width, edges);
joint = Joint::after(&pl, (0, pl.lines.len()), i, (0.0, y + lead), edges.bottom).filter(|_| mark_hidden && !shows_nothing).or(joint);
// Pictures, shapes and text boxes: drawn, their areas and text boxes' text.
if !p.objects.is_empty() {
let at = ObjFrame {
@@ -424,9 +412,7 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
let last = i + 1 == blocks.len();
let normal = || pl.rp.style == "Normal" || ctx.doc.styles.get(&pl.rp.style).is_none();
let after = if last && (pl.rp.after_auto || (in_cell && ctxl && normal())) { 0.0 } else { pl.rp.space_after };
y += edges.top + pl.height + edges.bottom;
// One going on from the line of the paragraph before ends below that line (#3986).
y = TakenUp::end(taken.as_ref(), ctx, (y, after), outer_joined);
y += edges.top + pl.height + edges.bottom + after;
prev_after = after;
prev_after_auto = pl.rp.after_auto;
prev_listed = listed;
@@ -459,7 +445,6 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
y = y.max(legacy_header_reach(y, &legacy_reach));
let floats_bottom = float_tables.iter().map(|r| r.bottom()).fold(float_objects_bottom, f32::max);
ctx.hide_deleted = outer_hide;
ctx.joined = outer_joined;
BoxLayout { items, height: y.max(0.0), floats_bottom, last_top: last_top.max(0.0), table_areas, page_table_wraps }
}
@@ -715,162 +700,6 @@ impl Edges {
joined: [false; 2],
}
}
/// A paragraph going on from the line of the one before, whose mark is hidden (#3986), takes
/// no room for its borders on that line, nor below it when that line is all it has: the
/// shared line shows the first paragraph's shading and borders (Word).
pub(crate) fn sharing(mut self, pl: &ParaLayout) -> Edges {
if pl.shares_line() {
self.top = 0.0;
if pl.lines.len() <= 1 {
self.bottom = 0.0;
}
}
self
}
}
/// Where a paragraph whose mark is hidden ends (#3986). Word shows it on one line with the next
/// paragraph: that one's text goes on from where this one's ends, beside it on its last line.
/// Paragraphs that show nothing (an empty one with a hidden mark, say) pass the place on.
#[derive(Clone, Copy, Debug)]
pub(crate) struct Joint {
/// The block that goes on from here.
pub(crate) next: usize,
/// The page (the count of pages) and column of the last line (body text only).
pub(crate) page: usize,
pub(crate) col: usize,
/// The last line's top, height and baseline (from its top), the left edge of its column and
/// the x its text ends at.
pub(crate) top: f32,
pub(crate) height: f32,
baseline: f32,
left: f32,
end: f32,
/// The room under the line for the paragraph's bottom border: what follows the shared line
/// starts below it.
room: f32,
}
impl Joint {
/// After lines `l0..l1` of paragraph layout `pl`, block `block`, the first of them at `y` in
/// a column whose left edge is at `x`, with `room` under them for its bottom border.
pub(crate) fn after(pl: &ParaLayout, (l0, l1): (usize, usize), block: usize, (x, y): (f32, f32), room: f32) -> Option<Joint> {
let li = l1.checked_sub(1)?;
let (first, last) = (pl.lines.get(l0)?, pl.lines.get(li)?);
// Right-to-left text runs the other way: its lines aren't joined.
if pl.rp.bidi || !last.vis.is_empty() {
return None;
}
let end = pl.x_of(li, pl.text_len)?;
let (top, height, baseline) = (y + last.top - first.top, last.height, last.baseline - last.top);
Some(Joint { next: block + 1, page: 0, col: 0, top, height, baseline, left: x, end: x + end, room })
}
/// Paragraph `p`, block `i`, arriving at `joint`: whether its mark is hidden, whether it shows
/// nothing, and how it goes on from the place the one before left (if that one's mark was hidden).
fn arrive(
ctx: &mut Ctx,
joint: &mut Option<Joint>,
(i, p): (usize, &Paragraph),
(width, frames): (f32, bool),
table: Option<&para::CellText>,
) -> (bool, bool, Option<TakenUp>) {
let chr = table.map(|t| &t.chr);
let mark_hidden = ctx.mark_hidden(p, chr);
let shows_nothing = mark_hidden && ctx.text_hidden(p, chr);
let came = joint.take().filter(|j| j.next == i);
*joint = came.filter(|_| shows_nothing).map(|j| Joint { next: i + 1, ..j });
let taken = came.filter(|_| !shows_nothing).and_then(|j| j.take_up(ctx, p, (width, frames), table));
(mark_hidden, shows_nothing, taken)
}
/// The bottom of the shared line, with the room for the first paragraph's bottom border.
pub(crate) fn bottom(&self) -> f32 {
self.top + self.height + self.room
}
/// How the next paragraph `q`, laid out `width` wide, goes on from here: how far below the
/// shared line's top it starts (its first line's text sits on this paragraph's baseline, not
/// above it), and the areas it keeps clear of: its first line, this paragraph's text, down to
/// the bottom of that line only; its later lines, the rest of the shared line (a heading's,
/// taller than the text going on from it), with the room for its bottom border (Word).
pub(crate) fn fit(&self, ctx: &mut Ctx, q: &Paragraph, width: f32, table: Option<&para::CellText>) -> (f32, Vec<WrapArea>) {
let eq = ctx.eq_count;
let probe = again(ctx, eq, |ctx| ctx.para_labelled(q, width, table, &[], None));
let (gap, height) = probe.lines.first().map_or((0.0, self.height), |l| ((self.baseline - (l.baseline - l.top)).max(0.0), l.height));
let rect = Rect::new(self.left, self.top, (self.end - self.left).max(0.0), (gap + height - 0.01).max(0.01));
let mut areas = vec![(rect, false, None, WrapText::Right, false)];
// Just below the first row as the line breaker tests it: the breaker tests every row at
// its estimate (`row_est`), not at the line's height, so the first row never meets this
// area and every later row, starting lower, does and moves below it. The probe's own first
// line can be taller than the real one (a large word that wraps off the narrower shared
// line), so its height can't be used here.
let below = self.top + gap + probe.row_est + 0.01;
if self.bottom() > below {
areas.push((Rect::new(self.left, below, width.max(0.01), self.bottom() - below), true, None, WrapText::BothSides, false));
}
(gap, areas)
}
/// The areas [`Joint::fit`] gave taken out of `excl` again, the paragraph laid out.
pub(crate) fn unfit(areas: &[WrapArea], excl: &mut Vec<WrapArea>) {
for area in areas {
if let Some(k) = excl.iter().position(|a| a.0 == area.0 && a.1 == area.1 && a.2.is_none() && a.3 == area.3) {
excl.remove(k);
}
}
}
/// Paragraph `p` of a box `width` wide going on from here, unless a page break comes before
/// it, it runs right to left or it is a text frame (`frames`: placed apart, sharing no line):
/// without its space before, as [`Joint::fit`] lays it out.
fn take_up(self, ctx: &mut Ctx, p: &Paragraph, (width, frames): (f32, bool), table: Option<&para::CellText>) -> Option<TakenUp> {
let own = ctx.doc.styles.resolve_para_in(&p.props, table.map(|t| &t.para));
if own.page_break_before || own.bidi || (frames && own.frame.is_some()) {
return None;
}
let mut para = p.clone();
para.props.space_before = Some(0.0);
para.props.space_before_auto = Some(false);
ctx.joined = Some(Joining::new(para.rev, 0.0));
let (gap, areas) = self.fit(ctx, &para, width, table);
Some(TakenUp { joint: self, para, gap, areas })
}
}
/// A paragraph of a box going on from a [`Joint`]: the paragraph without its space before, how
/// far below the shared line's top it starts and the areas its lines keep clear of.
struct TakenUp {
joint: Joint,
para: Paragraph,
gap: f32,
areas: Vec<WrapArea>,
}
impl TakenUp {
/// Where it starts: `y` below the shared line's top, its lines keeping clear of that line.
fn start(taken: Option<&TakenUp>, y: &mut f32, excl: &mut Vec<WrapArea>) {
let Some(t) = taken else { return };
*y = t.joint.top + t.gap;
excl.extend(t.areas.iter().cloned());
}
/// Its lines laid out: the areas they kept clear of come out of `excl`.
fn clear(taken: Option<&TakenUp>, excl: &mut Vec<WrapArea>) {
if let Some(t) = taken {
Joint::unfit(&t.areas, excl);
}
}
/// Where what follows a paragraph ending at `y`, with `after` its space after, starts: below
/// the shared line at least, with the first paragraph's bottom border. With the copy laid
/// out, the paragraph's own layouts are its own again (`outer`).
fn end(taken: Option<&TakenUp>, ctx: &mut Ctx, (y, after): (f32, f32), outer: Option<Joining>) -> f32 {
let Some(t) = taken else { return y + after };
ctx.joined = outer;
y.max(t.joint.bottom()) + after
}
}
/// Paragraph lines plus their shading and borders; returns the bottom of the lines. The
@@ -888,21 +717,12 @@ pub(crate) fn push_para(
return y;
};
let h = last.top + last.height - first.top;
let lines = Placed::Lines { story, path: Path(path.to_vec()), para: pl.clone(), l0, l1, x, y, turn: TextDirection::Horizontal };
// The line a paragraph shares with the one before, whose mark is hidden, shows that one's
// shading and borders: this one's start on its own next line, without a top border (Word, #3986).
let shared = l0 == 0 && pl.shares_line();
let Some(own) = pl.lines.get(if shared { 1 } else { l0 }).filter(|_| !shared || l1 > 1) else {
items.push(lines);
return y + h;
};
let (y_own, e) = if shared { (y + own.top - first.top, Edges { top: 0.0, up: 0.0, ..e }) } else { (y, e) };
// Indents are logical: a right-to-left paragraph's start indent (and hanging indent) is on the right.
let start = pl.rp.indent_left.min(pl.rp.indent_left + pl.rp.indent_first);
let (li, ri) = if pl.rp.bidi { (pl.rp.indent_right, start) } else { (start, pl.rp.indent_right) };
let left = x + li;
let right = x + width - ri;
let (top, bottom) = (y_own - e.top - e.up, y + h + e.bottom);
let (top, bottom) = (y - e.top - e.up, y + h + e.bottom);
// The outer edges of the side borders.
let sides = pl.rp.borders.unwrap_or_default();
let (lx, rx) = (left - border_room(sides.left), right + border_room(sides.right));
@@ -911,7 +731,7 @@ pub(crate) fn push_para(
let (sl, sr) = (lx.min(left - pad), rx.max(right + pad));
items.push(Placed::Fill { rect: Rect::new(sl, top, sr - sl, bottom - top), color: c });
}
items.push(lines);
items.push(Placed::Lines { story, path: Path(path.to_vec()), para: pl.clone(), l0, l1, x, y, turn: TextDirection::Horizontal });
if let Some(b) = &pl.rp.borders {
// All four lines lie beyond their distance from the text (`lx`, `rx`: the side lines'
// outer edges); `box_rules` runs the top and bottom over the side lines to those edges.
@@ -919,10 +739,9 @@ pub(crate) fn push_para(
let (cl, cr) = (lx + half(b.left), rx - half(b.right));
let tb = b.top.filter(|t| e.top > 0.0 && t.is_visible());
let bb = b.bottom.filter(|t| e.bottom > 0.0 && t.is_visible());
let ty = tb.map_or(top, |t| y_own - t.space - t.width / 2.0);
let ty = tb.map_or(top, |t| y - t.space - t.width / 2.0);
let by = bb.map_or(bottom, |t| y + h + t.space + t.width / 2.0);
// Open at the top where it goes on over the shared line.
box_rules(items, (cl, ty, cr, by), [tb, bb, b.left, b.right], [e.joined[0] || shared, e.joined[1]]);
box_rules(items, (cl, ty, cr, by), [tb, bb, b.left, b.right], e.joined);
}
y + h
}
-3
View File
@@ -27,9 +27,6 @@ pub(crate) struct Key {
pub(crate) sref: u64,
/// The word being typed in this paragraph, left without a spelling squiggle.
pub(crate) typing: Option<(usize, usize)>,
/// A copy of the paragraph going on from the line of the one before (`ctx::Joining`): its
/// space before and whether it shares that line ([`ParaEnv::joined`](crate::para::ParaEnv)).
pub(crate) joined: Option<(u32, bool)>,
}
/// Memoised paragraph layouts.
+4 -82
View File
@@ -51,9 +51,6 @@ pub(crate) struct Ctx<'a> {
/// Empty body paragraphs with hidden marks or continuous section breaks, in order:
/// they take no room (see [`place_para`]).
pub(crate) quiet_marks: Vec<usize>,
/// The paragraph being laid out as going on from the line of the one before, whose mark is
/// hidden: its list number is counted but not drawn (#3986).
pub(crate) joined: Option<Joining>,
/// Empty paragraphs closing a continuous section right after another section's mark, in
/// order: each takes its line while it fits, then stays at the page's bottom (#3907).
pub(crate) stacked_marks: Vec<usize>,
@@ -82,31 +79,6 @@ pub(crate) struct Ctx<'a> {
pub(crate) header_repeats: usize,
}
/// A paragraph going on from the line of the one before, whose mark is hidden (#3986): a copy of
/// the document's, which keeps its revision, given the space before that puts its text on that
/// line's baseline.
#[derive(Clone, Copy, Debug)]
pub(crate) struct Joining {
/// The paragraph's revision.
pub(crate) rev: u64,
/// The space before the copy is given.
before: f32,
/// Whether it still shares that line: not once its first line has moved on to the next
/// column or page, where it is laid out as on its own (the copy's space before kept).
pub(crate) shares: bool,
}
impl Joining {
pub(crate) fn new(rev: u64, before: f32) -> Self {
Joining { rev, before, shares: true }
}
/// What tells the copy's layouts apart from each other and from the paragraph's own.
fn key(self) -> (u32, bool) {
(self.before.to_bits(), self.shares)
}
}
struct ParaEnvInput<'a> {
width: f32,
label: Option<(String, Level)>,
@@ -115,7 +87,6 @@ struct ParaEnvInput<'a> {
eq_number: u32,
typing_word: Option<(usize, usize)>,
fitted: &'a [(usize, f32)],
joined: bool,
}
/// A header or footer (`story`) laid out for page `number` of a section (`sect`, `mirror`): its
@@ -256,31 +227,12 @@ impl Ctx<'_> {
grid: para::Grid::default(),
fit_objects: false,
fitted: &[],
joined: false,
};
let pl = Arc::new(para::layout_para(&p, &env));
self.numbers.insert(n, pl.clone());
pl
}
/// Whether `p` is laid out going on from the line of the paragraph before, sharing it (#3986).
fn shares_line(&self, p: &Paragraph) -> bool {
self.joined.is_some_and(|j| j.rev == p.rev && j.shares)
}
/// Whether `p`'s paragraph mark is hidden, with hidden text not shown: Word then shows the
/// paragraph on one line with the next one (#3986). A section's closing mark never joins.
pub(crate) fn mark_hidden(&self, p: &Paragraph, table_chr: Option<&CharProps>) -> bool {
!self.opts.show_hidden && p.section.is_none() && self.doc.styles.resolve_char_in(p.props.style.as_deref(), table_chr, &p.mark).hidden
}
/// Whether `p` shows none of its text (it has none, or all of it is hidden and not shown).
pub(crate) fn text_hidden(&self, p: &Paragraph, table_chr: Option<&CharProps>) -> bool {
p.text.is_empty()
|| (!self.opts.show_hidden
&& p.runs.iter().all(|r| r.len == 0 || self.doc.styles.resolve_char_in(p.props.style.as_deref(), table_chr, &r.props).hidden))
}
/// The list label of `p`, advancing the list counters: call it once per paragraph, in
/// document order (only for paragraphs that will show).
/// Whether `p` gets a list label ([`Ctx::next_label`] is `Some`), without counting it.
@@ -317,16 +269,7 @@ impl Ctx<'_> {
let typing = key.typing;
let pl = Arc::new(para::layout_para(
p,
&self.para_env(ParaEnvInput {
width,
label,
table,
exclusions,
eq_number,
typing_word: typing,
fitted: &fitted,
joined: self.shares_line(p),
}),
&self.para_env(ParaEnvInput { width, label, table, exclusions, eq_number, typing_word: typing, fitted: &fitted }),
));
self.cache.paras.insert(key, pl.clone());
pl
@@ -359,16 +302,7 @@ impl Ctx<'_> {
self.cache.misses += 1;
let pl = Arc::new(para::layout_para(
p,
&self.para_env(ParaEnvInput {
width,
label,
table: None,
exclusions: &[],
eq_number,
typing_word: None,
fitted: &[],
joined: self.shares_line(p),
}),
&self.para_env(ParaEnvInput { width, label, table: None, exclusions: &[], eq_number, typing_word: None, fitted: &[] }),
));
self.cache.paras.insert(key, pl.clone());
Some(pl)
@@ -396,16 +330,7 @@ impl Ctx<'_> {
let typing = key.typing;
let m = measure(&para::layout_para(
p,
&self.para_env(ParaEnvInput {
width,
label,
table,
exclusions: &[],
eq_number,
typing_word: typing,
fitted: &fitted,
joined: self.shares_line(p),
}),
&self.para_env(ParaEnvInput { width, label, table, exclusions: &[], eq_number, typing_word: typing, fitted: &fitted }),
));
self.cache.measures.insert(key, m);
m
@@ -490,7 +415,6 @@ impl Ctx<'_> {
hide_deleted: self.hide_deleted,
sref: if self.fields.styleref.is_some() && styleref::has_styleref(p) { self.fields.styleref_key(p) } else { 0 },
typing: self.opts.typing_word.filter(|t| t.rev == p.rev).map(|t| (t.start, t.end)),
joined: self.joined.filter(|j| j.rev == p.rev).map(Joining::key),
};
(key, eq_number)
}
@@ -511,7 +435,7 @@ impl Ctx<'_> {
}
fn para_env<'b>(&'b self, input: ParaEnvInput<'b>) -> para::ParaEnv<'b> {
let ParaEnvInput { width, label, table, exclusions, eq_number, typing_word, fitted, joined } = input;
let ParaEnvInput { width, label, table, exclusions, eq_number, typing_word, fitted } = input;
para::ParaEnv {
doc: self.doc,
width,
@@ -530,7 +454,6 @@ impl Ctx<'_> {
grid: self.grid,
fit_objects: self.boxes.inside(),
fitted,
joined,
}
}
}
@@ -602,7 +525,6 @@ mod tests {
track_totals: false,
pct_base: None,
quiet_marks: Vec::new(),
joined: None,
stacked_marks: Vec::new(),
mirror: false,
table_keys: Vec::new(),
+11 -108
View File
@@ -10,63 +10,8 @@ pub(super) fn graphic_draws(doc: &Document, g: &Graphic, rect: Rect, alpha: f32)
let (sx, sy) = (scale_of(rect.w, g.w), scale_of(rect.h, g.h));
let k = (sx + sy) / 2.0;
let inside = |r: &[f32; 4]| Rect::new(rect.x + r[0] * sx, rect.y + r[1] * sy, r[2] * sx, r[3] * sy);
let joins = |c: char| c.is_whitespace() || wordcraft_doc::math_linear::is_combining(c);
let db = wordcraft_fonts::FontDb::global();
// A graphic (SmartArt diagram or chart) should maintain a consistent fallback font family
// across all its text nodes (#5672). Collect all characters across the graphic that each
// item's primary font lacks, and find one fallback face that covers them all (or, when
// unrelated symbols need another face, one fallback face that covers all missing East Asian
// characters). The serif/sans preference comes from the first text item with a missing
// character (or the first with a missing East Asian character on the East Asian-only retry),
// so mixed-style graphics follow that leading label's style across nodes.
let mut text_resolved: Vec<Option<wordcraft_fonts::word::Resolved>> = Vec::with_capacity(g.items.len());
let mut diagram_chars: Vec<char> = Vec::new();
let mut cjk_chars: Vec<char> = Vec::new();
let mut primary_face: Option<FaceRef> = None;
let mut cjk_primary_face: Option<FaceRef> = None;
for it in &g.items {
if let GraphicItem::Text { text, font, bold, .. } = it {
let family = font.as_deref().filter(|f| !f.is_empty()).unwrap_or(&doc.settings.minor_font);
let resolved = wordcraft_fonts::word::resolve(family, *bold, false);
let primary = resolved.face;
for c in text.chars() {
if !joins(c) && !primary.covers(c) {
if primary_face.is_none() {
primary_face = Some(primary);
}
diagram_chars.push(c);
if crate::para::is_east_asian(c) {
if cjk_primary_face.is_none() {
cjk_primary_face = Some(primary);
}
cjk_chars.push(c);
}
}
}
text_resolved.push(Some(resolved));
} else {
text_resolved.push(None);
}
}
let diagram_fallback = if !diagram_chars.is_empty() {
let prefer_serif = primary_face.is_some_and(|p| p.get().is_serif());
let exclude = primary_face.map_or(0, |p| p.id());
db.fallback_for_diagram(&diagram_chars, exclude, prefer_serif).or_else(|| {
if !cjk_chars.is_empty() {
let cjk_prefer_serif = cjk_primary_face.is_some_and(|p| p.get().is_serif());
let cjk_exclude = cjk_primary_face.map_or(0, |p| p.id());
db.fallback_for_diagram(&cjk_chars, cjk_exclude, cjk_prefer_serif)
} else {
None
}
})
} else {
None
};
let mut out = Vec::with_capacity(g.items.len());
for (i, it) in g.items.iter().enumerate() {
for it in &g.items {
match it {
GraphicItem::Shape { rect: r, kind, fill, stroke, stroke_width } => out.push(Draw::Shape {
rect: inside(r),
@@ -97,16 +42,12 @@ pub(super) fn graphic_draws(doc: &Document, g: &Graphic, rect: Rect, alpha: f32)
let (cx, cy) = (at.x + at.w / 2.0, at.y + at.h / 2.0);
let quarter = ((angle / 90.0).round() as i64).rem_euclid(2) == 1;
let level = if quarter { Rect::new(cx - at.h / 2.0, cy - at.w / 2.0, at.h, at.w) } else { at };
let resolved = text_resolved.get(i).copied().flatten();
let items = text_glyphs(doc, level, it, alpha, k, resolved, diagram_fallback.as_ref());
let items = text_glyphs(doc, level, it, alpha, k);
if !items.is_empty() {
out.push(Draw::Rotated { cx, cy, spin: Spin::new(*angle, false, false), items });
}
}
GraphicItem::Text { rect: r, .. } => {
let resolved = text_resolved.get(i).copied().flatten();
out.extend(text_glyphs(doc, inside(r), it, alpha, k, resolved, diagram_fallback.as_ref()));
}
GraphicItem::Text { rect: r, .. } => out.extend(text_glyphs(doc, inside(r), it, alpha, k)),
GraphicItem::Image { rect: r, media } => out.push(Draw::Image {
rect: inside(r),
media: media.clone(),
@@ -350,28 +291,18 @@ pub fn seg_path(segs: &[PathSeg]) -> BezPath {
/// in body text: one draw per run of a face, in reading order. Empty when there is nothing to draw,
/// or the item's rectangle or size isn't a finite number (a degenerate scale: `r` itself is always
/// finite, as [`Rect::new`] makes it).
fn text_glyphs(
doc: &Document,
r: Rect,
it: &GraphicItem,
alpha: f32,
k: f32,
resolved: Option<wordcraft_fonts::word::Resolved>,
diagram_fallback: Option<&std::sync::Arc<wordcraft_fonts::FontFace>>,
) -> Vec<Draw> {
fn text_glyphs(doc: &Document, r: Rect, it: &GraphicItem, alpha: f32, k: f32) -> Vec<Draw> {
let GraphicItem::Text { rect, text, size, color, bold, align, font, .. } = it else { return Vec::new() };
let size = *size * k;
if !rect.iter().chain([&size]).all(|v| v.is_finite()) {
return Vec::new();
}
let family = font.as_deref().filter(|f| !f.is_empty()).unwrap_or(&doc.settings.minor_font);
let size = size.clamp(1.0, 400.0);
let resolved = resolved.unwrap_or_else(|| {
let family = font.as_deref().filter(|f| !f.is_empty()).unwrap_or(&doc.settings.minor_font);
wordcraft_fonts::word::resolve(family, *bold, false)
});
let resolved = wordcraft_fonts::word::resolve(family, *bold, false);
let primary = resolved.face;
let scale = |f: FaceRef| size / f.upem.max(1.0) as f32;
let runs: Vec<_> = face_runs(text, primary, *bold, diagram_fallback)
let runs: Vec<_> = face_runs(text, primary, *bold)
.into_iter()
.map(|(face, s)| (face, s, wordcraft_fonts::shape(face.get(), s, &[], |c| c)))
.filter(|(_, _, shaped)| !shaped.is_empty())
@@ -418,12 +349,7 @@ fn text_glyphs(
/// fallback face. A run the primary lacks takes one face covering all of it when one does (so a
/// Chinese label doesn't mix serif and sans glyphs), else each character its own fallback. Spaces
/// and combining marks stay in the run before them; a character no face has stays in `primary`.
fn face_runs<'a>(
text: &'a str,
primary: FaceRef,
bold: bool,
diagram_fallback: Option<&std::sync::Arc<wordcraft_fonts::FontFace>>,
) -> Vec<(FaceRef, &'a str)> {
fn face_runs(text: &str, primary: FaceRef, bold: bool) -> Vec<(FaceRef, &str)> {
let joins = |c: char| c.is_whitespace() || wordcraft_doc::math_linear::is_combining(c);
// (start, end, drawn by `primary`)
let mut spans: Vec<(usize, usize, bool)> = Vec::new();
@@ -444,25 +370,7 @@ fn face_runs<'a>(
continue;
}
let chars: Vec<char> = s.chars().filter(|c| !joins(*c)).collect();
let df_face_for = |df: &std::sync::Arc<wordcraft_fonts::FontFace>, covered: &[char]| {
if bold {
let styled = db.face(&df.family, "Bold");
if styled.family.eq_ignore_ascii_case(&df.family) && covered.iter().all(|c| styled.covers(*c)) {
return FaceRef::of(&styled);
}
}
FaceRef::of(df)
};
// A single SmartArt or chart diagram maintains a consistent fallback face across its labels (#5672).
if let Some(df) = diagram_fallback
&& chars.iter().all(|c| df.covers(*c))
{
out.push((df_face_for(df, &chars), s));
continue;
}
if diagram_fallback.is_none_or(|df| !chars.iter().any(|c| df.covers(*c)))
&& let Some(f) = db.fallback_for_run(&chars, primary.id(), bold, false)
{
if let Some(f) = db.fallback_for_run(&chars, primary.id(), bold, false) {
out.push((FaceRef::of(&f), s));
continue;
}
@@ -470,13 +378,8 @@ fn face_runs<'a>(
// in one run.
let mut run: Option<(FaceRef, usize)> = None;
for (i, c) in s.char_indices() {
let face = if joins(c) {
None
} else if let Some(df) = diagram_fallback.filter(|df| df.covers(c)) {
Some(df_face_for(df, &[c]))
} else {
Some(db.fallback_styled(c, primary.id(), bold, false).map(|f| FaceRef::of(&f)).unwrap_or(primary))
};
let face =
if joins(c) { None } else { Some(db.fallback_styled(c, primary.id(), bold, false).map(|f| FaceRef::of(&f)).unwrap_or(primary)) };
match (run, face) {
(Some((cur, from)), Some(f)) if f.id() != cur.id() => {
out.extend(s.get(from..i).map(|t| (cur, t)));
+5 -96
View File
@@ -1,6 +1,6 @@
use super::boxes::{BoxInput, BoxLayout, Edges, Joint, joined, layout_box, push_para};
use super::boxes::{BoxInput, BoxLayout, Edges, joined, layout_box, push_para};
use super::cache::has_page_number_fields;
use super::ctx::{Ctx, Joining};
use super::ctx::Ctx;
use super::floats::{
FloatAnchor, LateFloats, ObjFrame, ObjectPlacement, anchor_floats, body_wraps, continued_exclusions, fitting, late_floats, place_late,
place_objects,
@@ -15,89 +15,9 @@ use super::{
#[cfg(test)]
use crate::WRAP_RELAYS;
/// A body paragraph. One after a paragraph whose mark is hidden goes on from that one's last line,
/// as Word shows them, on one line (#3986): see [`Joint`].
pub(crate) fn place_para(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block: usize, body_top: f32) {
let joint = pb.joint.take().filter(|j| !pb.web && j.next == block && j.page == pb.pages.len() && j.col == pb.col);
let mark_hidden = ctx.mark_hidden(p, None);
// Nothing of it is shown: the place passes on to the paragraph after it.
if mark_hidden && ctx.text_hidden(p, None) {
place_para_alone(ctx, pb, p, block, body_top);
pb.joint = joint.map(|mut j| {
j.next = block + 1;
j
});
return;
}
let goes_on = joint.filter(|_| {
p.section.is_none()
&& ctx.quiet_marks.binary_search(&block).is_err()
&& ctx.stacked_marks.binary_search(&block).is_err()
&& !ctx.doc.styles.resolve_para(&p.props).page_break_before
&& !ctx.doc.styles.resolve_para(&p.props).bidi
});
match goes_on {
Some(j) => place_para_joined(ctx, pb, p, (block, body_top), j),
None => place_para_alone(ctx, pb, p, block, body_top),
}
if mark_hidden {
let path = Path::top(block);
pb.joint = pb.page().and_then(|page| {
page.items.iter().rev().find_map(|it| match it {
Placed::Lines { story: StoryRef::Body, path: at, para, l0, l1, x, y, turn: TextDirection::Horizontal, .. } if *at == path => {
let room = if *l1 >= para.lines.len() { Rooms::of(ctx, block, para).bottom } else { 0.0 };
Joint::after(para, (*l0, *l1), block, (*x, *y), room)
}
_ => None,
})
});
if let Some(j) = pb.joint.as_mut() {
(j.page, j.col) = (pb.pages.len(), pb.col);
}
}
}
/// `p` going on from the last line of the paragraph before (`j`): its first line starts at that
/// line's top, beside that paragraph's text, with no space before and its list number counted
/// but not drawn; its space after and line spacing are its own (Word, #3986).
fn place_para_joined(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, (block, body_top): (usize, f32), j: Joint) {
// The copy keeps the paragraph's revision, so the word being typed in it is found and its
// layouts are reused from one pass to the next: the cache tells them apart by `Joining`.
let mut q = p.clone();
q.props.space_before = Some(0.0);
q.props.space_before_auto = Some(false);
let outer = ctx.joined.replace(Joining::new(q.rev, 0.0));
let (gap, areas) = j.fit(ctx, &q, pb.col_w(), None);
if gap > 0.0 {
q.props.space_before = Some(gap);
ctx.joined = Some(Joining::new(q.rev, gap));
}
pb.y = j.top;
pb.prev = None;
pb.unmark_block();
pb.excl.extend(areas.iter().cloned());
place_para_alone(ctx, pb, &q, block, body_top);
ctx.joined = outer;
Joint::unfit(&areas, &mut pb.excl);
// The shared line is at least as tall as the first paragraph's, with its bottom border: what
// follows starts below it.
if (pb.pages.len(), pb.col) == (j.page, j.col) {
pb.y = pb.y.max(j.bottom() + ctx.doc.styles.resolve_para(&q.props).space_after);
}
}
/// A paragraph going on from the line of the one before (#3986) whose first line moves on to the
/// next column or page no longer shares that line: it is laid out as it is on its own there, its
/// list number drawn and its first-line indent and alignment its own.
fn unjoin(ctx: &mut Ctx, p: &Paragraph) {
if let Some(j) = ctx.joined.as_mut().filter(|j| j.rev == p.rev) {
j.shares = false;
}
}
/// A closing mark before a continuous section takes no room after content. An otherwise empty
/// section starting a new page retains its paragraph line.
fn place_para_alone(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block: usize, body_top: f32) {
pub(crate) fn place_para(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block: usize, body_top: f32) {
if !pb.web && ctx.quiet_marks.binary_search(&block).is_ok() {
let follows_section = block.checked_sub(1).and_then(|i| ctx.doc.body.get(i)).and_then(|b| b.as_para()).is_some_and(|p| p.section.is_some());
let section = pb.sect_idx;
@@ -207,7 +127,7 @@ impl Rooms {
fn of(ctx: &Ctx, block: usize, pl: &ParaLayout) -> Self {
let above = joined(ctx.doc, &ctx.doc.body, block, block.checked_sub(1), None);
let below = joined(ctx.doc, &ctx.doc.body, block, Some(block + 1), None);
let own = Edges::own(pl, 0, pl.lines.len()).sharing(pl);
let own = Edges::own(pl, 0, pl.lines.len());
Rooms { above, below, top: if above { 0.0 } else { own.top }, bottom: if below { 0.0 } else { own.bottom } }
}
}
@@ -440,7 +360,6 @@ impl<'a> Flow<'a> {
// keeps the lines and the next paragraph together at the top of a column too (#6821).
if pb.y + need > pb.bottom + 0.01 && (!pb.fresh() || Self::strict_widow_control(ctx, pb)) && need <= pb.next_room(self.body_top) {
pb.advance(self.block, self.body_top);
unjoin(ctx, self.p);
pb.y += rp.space_before.min(0.0);
return rp.space_before.min(0.0);
}
@@ -638,7 +557,6 @@ impl<'a> Flow<'a> {
fn move_on(&mut self, ctx: &mut Ctx, pb: &mut PageBuilder) {
pb.advance(self.block, self.body_top);
if self.l0 == 0 {
unjoin(ctx, self.p);
let y0 = pb.y;
self.reanchor(ctx, pb, (y0, 0.0), &[]);
self.anchor_y = y0;
@@ -928,11 +846,6 @@ fn line_numbers(ctx: &mut Ctx, pb: &mut PageBuilder, pl: &ParaLayout, (l0, l1):
{
for li in l0..l1 {
let Some(line) = pl.lines.get(li).filter(|l| !l.beside) else { continue };
// The first line of a paragraph going on from the line of the one before (#3986)
// shares that line, numbered already, unless its first word went on the next one.
if li == 0 && pl.shares_line() {
continue;
}
pb.line_no = pb.line_no.saturating_add(1);
let n = pb.line_no.saturating_add(ln.start.saturating_sub(1));
if ln.count_by > 1 && !n.is_multiple_of(ln.count_by) {
@@ -982,7 +895,7 @@ fn place_para_in_flow(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block:
}
let before = f.gap_before(ctx, pb, broke_before);
pb.y += before;
let mut rooms = Rooms::of(ctx, block, &f.pl);
let rooms = Rooms::of(ctx, block, &f.pl);
let applied_before = f.keep_together(ctx, pb, rooms, before);
// A different top only matters when there is something to wrap around.
if spot(pb) != placed_at || ((pb.y - f.guess).abs() > 0.01 && !pb.excl.is_empty()) {
@@ -991,10 +904,7 @@ fn place_para_in_flow(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block:
f.anchor_y = y0 - applied_before;
}
while f.l0 < f.n() {
// A paragraph moved on from the shared line (`unjoin`) is laid out again with borders of its own.
rooms = Rooms::of(ctx, block, &f.pl);
f.keep_again(ctx, pb, rooms);
rooms = Rooms::of(ctx, block, &f.pl);
f.place_due_late(ctx, pb);
f.relay_wrap(ctx, pb);
f.relay_pages(ctx, pb);
@@ -1188,7 +1098,6 @@ fn next_first_line(ctx: &mut Ctx, block: usize, width: f32, depth: usize, new_pa
grid: ctx.grid,
fit_objects: false,
fitted: &[],
joined: false,
};
Arc::new(para::layout_para(p, &env))
}
+4 -39
View File
@@ -279,19 +279,6 @@ fn story_items(page: &Page, story: StoryRef) -> Box<dyn Iterator<Item = &Placed>
}
}
/// The topmost uncovered table cell in `story` under `(x, y)` on `page`.
fn story_cell_at(page: &Page, story: StoryRef, x: f32, y: f32) -> Option<(&Path, usize, usize)> {
let pt = Point::new(x, y);
story_items(page, story)
.filter_map(|it| match it {
Placed::Cell { rect, table, row, cell, story: s, covered: false, .. } if *s == story && rect.contains(pt) => Some((table, *row, *cell)),
_ => None,
})
// Nested tables emit their cells before the enclosing cell, so prefer the deepest match
// and keep the last (topmost) cell on ties at the same nesting level.
.max_by_key(|(table, _, _)| table.0.len())
}
/// Whether header/footer part `id` has text near (x, y) on the page (its header or footer
/// lines). Used so an object behind the header text is only grabbed where there's no text,
/// mirroring `text_at` for the body.
@@ -332,14 +319,6 @@ pub fn page_lines(page: &Page, story: StoryRef) -> Vec<LineHit<'_>> {
}
}
}
// A paragraph going on from the last line of one whose mark is hidden shares that line
// (#3986): the first one's part of it ends where the second one's text starts.
let joins: Vec<(f32, f32, f32)> = v.iter().filter(|l| l.para.shares_line() && l.li == 0).map(|l| (l.top, l.bottom, l.left)).collect();
for (top, bottom, left) in joins {
for l in v.iter_mut().filter(|l| l.top < bottom && top < l.bottom && l.left < left && left < l.right) {
l.right = left;
}
}
v
}
@@ -464,31 +443,17 @@ impl DocLayout {
// other text on the page: below one, it goes to the text beside or after it (#2038).
let floats = if story == StoryRef::Body { float_table_areas(p) } else { Vec::new() };
let away = |path: &Path| floats.iter().any(|(t, r)| path.0.len() > t.0.len() && path.0.starts_with(&t.0) && !r.contains(Point::new(x, y)));
let cell = story_cell_at(p, story, x, y);
let in_cell = |path: &Path, table: &Path, row: usize, col: usize| {
path.0.starts_with(&table.0) && path.0.get(table.0.len()) == Some(&(row as u32)) && path.0.get(table.0.len() + 1) == Some(&(col as u32))
};
// Turned cell text takes a click up to 2pt outside it, so outside a floating table too,
// but a click inside one table cell must never be stolen by a neighbouring cell's text.
let skip_turned = |path: &Path| away(path) || cell.is_some_and(|(table, row, col)| !in_cell(path, table, row, col));
if let Some(pos) = turned_hit(p, story, x, y, &skip_turned) {
// Turned cell text takes a click up to 2pt outside it, so outside a floating table too.
if let Some(pos) = turned_hit(p, story, x, y, &away) {
return Some(pos);
}
let lines = page_lines(p, story);
let nearest = |a: &&LineHit, b: &&LineHit| score(a, x, y).total_cmp(&score(b, x, y));
let at = |l: &LineHit| Pos { story: l.story, path: l.path.clone(), off: l.para.off_at_x(l.li, x - l.x) };
if let Some((table, row, col)) = cell {
if let Some(best) = lines.iter().filter(|l| in_cell(l.path, table, row, col)).min_by(nearest) {
return Some(at(best));
}
if let Some(pos) = nearest_turned(p, story, x, y, &|path| !in_cell(path, table, row, col)) {
return Some(pos);
}
}
if lines.is_empty() {
// A page of turned text (a vertical section): the nearest turned line.
return nearest_turned(p, story, x, y, &away).or_else(|| nearest_turned(p, story, x, y, &|_: &Path| false));
}
let nearest = |a: &&LineHit, b: &&LineHit| score(a, x, y).total_cmp(&score(b, x, y));
let at = |l: &LineHit| Pos { story: l.story, path: l.path.clone(), off: l.para.off_at_x(l.li, x - l.x) };
if let Some(best) = lines.iter().filter(|l| !away(l.path)).min_by(nearest) {
return Some(at(best));
}
+1 -13
View File
@@ -1,4 +1,4 @@
use super::boxes::{BoxInput, Joint, box_rules, layout_box};
use super::boxes::{BoxInput, box_rules, layout_box};
use super::ctx::{Ctx, with_pin};
use super::floats::{EarlyFloats, WrapArea};
use super::notes::{NOTE_SEP, NOTE_SEP_W, NoteBox, NoteSeps, v_span};
@@ -35,8 +35,6 @@ pub(crate) struct PageBuilder<'a> {
/// The previous paragraph ended with a page break (its mark stayed with the break): the next
/// paragraph, first on the new page, gets no space before (Word).
pub(crate) after_break_mark: bool,
/// Where the last paragraph, whose mark is hidden, ended: the next one goes on from there.
pub(crate) joint: Option<Joint>,
/// The next section starts on a new page: this section's closing mark, when empty, needs no
/// room (Word leaves it on a full page rather than starting a page for it).
pub(crate) next_starts_page: bool,
@@ -230,16 +228,6 @@ impl PageBuilder<'_> {
self.block_marks.push(pg.items.len().saturating_sub(behind));
}
}
/// Takes back the mark of a block that has placed nothing yet: it goes on from the line of
/// the block before (#3986), and justified vertical alignment keeps the two together.
pub(crate) fn unmark_block(&mut self) {
if let Some(pg) = self.pages.last() {
let behind = self.behind.last().copied().unwrap_or(0);
if self.block_marks.last() == Some(&pg.items.len().saturating_sub(behind)) {
self.block_marks.pop();
}
}
}
/// Justified vertical alignment: share the room left below the page's text out equally
/// between the gaps of its blocks, so the last line sits on the bottom margin (above the
/// footnotes). A page with one block, or several columns, stays at the top.
-12
View File
@@ -101,20 +101,9 @@ pub struct ParaLayout {
/// Room after a cluster between Asian text and Latin text or digits ([`auto_space`]), by
/// cluster index, sorted. It is part of the cluster's advance, but takes no room at a line's end.
pub auto_space: Vec<(usize, f32)>,
/// It goes on from the last line of the paragraph before, whose mark is hidden, and shares
/// that line ([`ParaEnv::joined`]).
pub joined: bool,
/// How tall the line breaker takes a row to be when it checks it against wrap areas.
pub(crate) row_est: f32,
}
impl ParaLayout {
/// Whether its first line is the one it shares with the paragraph before, whose mark is
/// hidden (#3986), rather than a line of its own below it (its first word didn't fit there).
pub(crate) fn shares_line(&self) -> bool {
self.joined && self.lines.first().is_some_and(|l| l.top <= 0.01)
}
/// The room a horizontal rule at cluster `k` is placed in, from its left edge to the end of
/// what the line has left. A first-line indent moves that end along (Word, measured with
/// 50 % and fixed-width rules beside floats on either side and with first-line and hanging
@@ -370,7 +359,6 @@ mod label_spacing_tests {
read_line_spacing: None,
fit_objects: false,
fitted: &[],
joined: false,
};
let mut p = Paragraph::with_text(if wrap { "Alpha probe synthetic business text repeated" } else { "Alpha probe" }, Default::default());
p.props.line_spacing = Some(spacing);
+6 -22
View File
@@ -63,9 +63,6 @@ struct Breaker<'e> {
row_first: usize,
/// Spans skipped in a row because the next word didn't fit (see `Scan::skip`).
skipped: usize,
/// The paragraph goes on from the line of the one before (#3986): its first line starts right
/// after that one's text, and takes its place there whatever its own alignment.
joined: bool,
/// A left tab past the right indent that wrapped to start the next line.
wrapped_tab: Option<usize>,
}
@@ -191,9 +188,7 @@ impl<'e> Breaker<'e> {
n: pl.clusters.len(),
width,
base_right: (width - rp.indent_right).max(1.0),
// On the line it shares with the paragraph before (#3986), kept clear of that one's
// text by an exclusion, a joined paragraph's own indents don't hold its text back.
first_left: if env.joined { (rp.indent_left + rp.indent_first).min(0.0) } else { rp.indent_left + rp.indent_first },
first_left: rp.indent_left + rp.indent_first,
default_tab: settings.default_tab,
hanging_at: if rp.indent_first < 0.0 { Some(rp.indent_left) } else { None },
tab_origin: if settings.odf.is_some_and(|o| o.tabs_from_indent) { rp.indent_left } else { 0.0 },
@@ -227,20 +222,13 @@ impl<'e> Breaker<'e> {
row_rest: VecDeque::new(),
row_first: 0,
skipped: 0,
joined: env.joined,
wrapped_tab: None,
}
}
/// The first line's start: a joined paragraph's first line pushed below the shared line (its
/// first word didn't fit there) starts at the paragraph's left indent, as its other lines do.
fn first_indent(&self) -> f32 {
if self.joined && self.top > 0.0 { self.rp.indent_left } else { self.first_left }
}
/// The left edge of the row's first span: the indent, behind a drop cap on its lines.
fn row_left(&self, pl: &ParaLayout) -> f32 {
let lo = if self.first { self.first_indent() } else { self.rp.indent_left };
let lo = if self.first { self.first_left } else { self.rp.indent_left };
match pl.drop_cap {
Some((_, dl, dw)) if dw > 0.0 && self.lines.len() < dl as usize => self.first_left.max(self.rp.indent_left) + dw,
_ => lo,
@@ -283,7 +271,7 @@ impl<'e> Breaker<'e> {
/// The start of a line: its span, and the list label if it is the first.
fn begin_line(&mut self, pl: &mut ParaLayout) -> Scan {
let beside = !self.row_rest.is_empty() && self.lines.len() > self.row_first;
let row_lo = if self.first { self.first_indent() } else { self.rp.indent_left };
let row_lo = if self.first { self.first_left } else { self.rp.indent_left };
let (left, right_edge, narrowed) = self.next_span(pl);
let x = if self.first { self.place_label(pl, left) } else { left };
Scan {
@@ -575,10 +563,7 @@ impl<'e> Breaker<'e> {
let last_tab = (c0..c1).rev().find(|k| pl.clusters.get(*k).is_some_and(|c| c.kind == ClKind::Tab));
let align_from = last_tab.map(|k| k + 1).unwrap_or(c0);
let display = pl.displays.iter().find(|(ci, _)| *ci >= c0 && *ci < c1).map(|d| d.1);
// The line a paragraph shares with the one before, whose mark is hidden, starts in that
// one, and takes its place right after that one's text (Word, #3986).
let align = if self.joined && self.lines.is_empty() { Align::Left } else { rp.align };
let shift = match (display, align) {
let shift = match (display, rp.align) {
(Some(MathJc::Left), _) => 0.0,
(Some(MathJc::Right), _) => slack,
(Some(_), _) => slack / 2.0,
@@ -602,13 +587,13 @@ 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);
let justify = display.is_none() && ((rp.align == Align::Justify && stretch_end) || rp.align == Align::Distribute);
// 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, 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);
justify_line(pl, &mut sc.xs, (c0, c1, align_from), (content_end, slack), rp.align == Align::Distribute);
}
}
@@ -707,7 +692,6 @@ impl<'e> Breaker<'e> {
fn finish(mut self, pl: &mut ParaLayout) {
self.hang_drop_cap(pl);
pl.height = self.top;
pl.row_est = self.est_h;
pl.lines = std::mem::take(&mut self.lines);
let label_shift = self.label_shifts.get(pl.label_line()).copied().unwrap_or(0.0);
if let Some(lab) = pl.label.as_mut() {
-3
View File
@@ -401,7 +401,4 @@ pub struct ParaEnv<'a> {
/// Heights of the paragraph's inline text boxes that resize to fit their text, by object
/// index: they take these instead of their saved heights.
pub fitted: &'a [(usize, f32)],
/// The paragraph goes on from the line of the one before, whose mark is hidden (#3986): its
/// list number is counted and sets its indents, but isn't drawn.
pub joined: bool,
}
+3 -6
View File
@@ -533,14 +533,13 @@ fn mark_break_opportunities(clusters: &mut [Cluster], bt: &BreakText, rp: &Resol
}
}
/// The list label, shaped; none on a paragraph containing only a page break, nor on one that goes
/// on from the line of the paragraph before (#3986): Word hides it there. The list counter has
/// already advanced, so the following item keeps its number.
/// The list label, shaped; none on a paragraph containing only a page break: Word hides it there.
/// The list counter has already advanced, so the following item keeps its number.
fn list_label(cx: &Cx, b: &mut Builder, mark_style: u32) -> Option<Label> {
let (p, rp) = (cx.p, cx.rp);
let break_only =
b.clusters.iter().any(|c| c.kind == ClKind::PageBreak) && b.clusters.iter().all(|c| matches!(c.kind, ClKind::PageBreak | ClKind::Marker));
let (text, lvl) = cx.env.label.as_ref().filter(|_| !break_only && !cx.env.joined)?;
let (text, lvl) = cx.env.label.as_ref().filter(|_| !break_only)?;
let rc = cx.res.char(&p.mark.clone().overlaid(&lvl.chr));
// A bullet no installed font can draw would come from whatever icon font has its
// private-use code (Font Awesome's Twitter logo at U+F081, #1683): it shows the level's
@@ -714,8 +713,6 @@ pub fn layout_para(p: &Paragraph, env: &ParaEnv) -> ParaLayout {
left_out: Vec::new(),
enclosures,
auto_space,
joined: env.joined,
row_est: 0.0,
};
let auto = env.doc.settings.auto_hyphenation && !pl.rp.suppress_hyphens;
pl.hyph_after = hyphenation_points(&bt.text, |i| bt.to_para(i), &pl, auto, env.doc.settings.hyphenate_caps, &runs);
-2
View File
@@ -110,7 +110,6 @@ fn new_ctx<'a>(
track_totals: true,
pct_base: None,
quiet_marks: Vec::new(),
joined: None,
stacked_marks: Vec::new(),
mirror: false,
table_keys: Vec::new(),
@@ -212,7 +211,6 @@ fn new_page_builder<'p>(
orig_bottom: 0.0,
prev: None,
after_break_mark: false,
joint: None,
next_starts_page: false,
restart_at: None,
excl: Vec::new(),
-1
View File
@@ -233,7 +233,6 @@ pub fn measure_table_columns(doc: &wordcraft_doc::Document, t: &Table) -> Vec<(f
grid: crate::para::Grid::default(),
fit_objects: false,
fitted: &[],
joined: false,
};
let (mut min, mut max) = (EMPTY_TEXT, EMPTY_TEXT);
if cell.props.vmerge != VMerge::Continue && !cell.props.text_direction.is_turned() {
-852
View File
@@ -13,7 +13,6 @@ mod complex;
mod float_top;
mod grid;
mod header_legacy_float;
mod joined;
mod keep_next_section;
mod ligature;
pub(crate) mod linear;
@@ -2253,410 +2252,6 @@ fn empty_list_paragraph_with_a_hidden_mark_counts_but_shows_nothing() {
}
}
#[test]
fn a_paragraph_with_a_hidden_mark_goes_on_into_the_next_one() {
// Word (#3986): a paragraph whose mark is hidden is shown on one line with the next one. The
// next one's text goes on from where the first one's ends; its number is counted but not
// drawn ("1. AlphaOmega", then "3. Beta") and it takes no line of its own. A paragraph that
// shows nothing in between passes the joint on. In a table cell as in the body.
let doc = |paras: &[(&str, bool)], in_cell: bool| {
let text: Vec<&str> = paras.iter().map(|(t, _)| *t).collect();
let mut d = Document::from_text(&text.join("\n"));
let id = Arc::make_mut(&mut d.numbering).add_list(wordcraft_doc::ListKind::Numbered);
let last = d.body.len() - 1;
let end = paras.last().map_or(0, |(t, _)| t.len());
d.format_paragraphs(&Pos::body(0, 0), &Pos::body(last, end), &|p| {
p.numbering = Some(wordcraft_doc::props::NumRef { num: id, level: 0 });
})
.unwrap();
for (i, (_, hidden)) in paras.iter().enumerate() {
if *hidden {
d.para_mut(StoryRef::Body, &Path::top(i)).unwrap().mark.hidden = Some(true);
}
}
if in_cell {
let mut table = Table::new(1, 1, 400.0);
table.rows[0].cells[0].blocks = std::mem::take(&mut d.body);
d.body = vec![std::sync::Arc::new(Block::Table(table))];
}
d
};
// Each paragraph's number, the top of its first line, and the x its text starts and ends at.
let laid = |d: &Document, show_hidden: bool| {
let l = layout(d, &mut LayoutCache::new(), &LayoutOptions { show_hidden, ..Default::default() });
let lines: Vec<(Option<String>, f32, f32, f32)> = l
.pages
.iter()
.flat_map(|p| &p.items)
.filter_map(|it| match it {
Placed::Lines { para, l0, l1, x, y, .. } => {
let last = l1.checked_sub(1)?;
Some((para.label.as_ref().map(|label| label.text.clone()), *y, x + para.x_of(*l0, 0)?, x + para.x_of(last, para.text_len)?))
}
_ => None,
})
.collect();
lines
};
for in_cell in [false, true] {
let plain = laid(&doc(&[("Alpha", false), ("Beta", false)], in_cell), false);
let beta_y = plain[1].1;
// Text: "Omega" on Alpha's line, after Alpha's text.
let joined = laid(&doc(&[("Alpha", true), ("Omega", false), ("Beta", false)], in_cell), false);
let labels: Vec<_> = joined.iter().map(|l| l.0.as_deref()).collect();
assert_eq!(labels, vec![Some("1."), None, Some("3.")], "in_cell={in_cell}");
assert!((joined[1].1 - joined[0].1).abs() < 0.01, "in_cell={in_cell}: Omega at {} not on Alpha's line {}", joined[1].1, joined[0].1);
assert!((joined[1].2 - joined[0].3).abs() < 0.5, "in_cell={in_cell}: Omega starts at {}, Alpha ends at {}", joined[1].2, joined[0].3);
assert!((joined[2].1 - beta_y).abs() < 0.01, "in_cell={in_cell}: Beta at {} instead of {beta_y}", joined[2].1);
// An empty paragraph: no line of its own, no number.
let empty = laid(&doc(&[("Alpha", true), ("", false), ("Beta", false)], in_cell), false);
let labels: Vec<_> = empty.iter().map(|l| l.0.as_deref()).collect();
assert_eq!(labels, vec![Some("1."), None, Some("3.")], "in_cell={in_cell}");
assert!((empty[2].1 - beta_y).abs() < 0.01, "in_cell={in_cell}: Beta at {} instead of {beta_y}", empty[2].1);
// Through an empty paragraph with a hidden mark (which shows nothing).
let chain = laid(&doc(&[("Alpha", true), ("", true), ("Omega", false), ("Beta", false)], in_cell), false);
let labels: Vec<_> = chain.iter().map(|l| l.0.as_deref()).collect();
assert_eq!(labels, vec![Some("1."), None, None, Some("4.")], "in_cell={in_cell}");
assert!((chain[2].1 - chain[0].1).abs() < 0.01, "in_cell={in_cell}: Omega not on Alpha's line");
// Hidden text shown: each paragraph on its own line, with its number.
let shown = laid(&doc(&[("Alpha", true), ("Omega", false), ("Beta", false)], in_cell), true);
let labels: Vec<_> = shown.iter().map(|l| l.0.as_deref()).collect();
assert_eq!(labels, vec![Some("1."), Some("2."), Some("3.")], "in_cell={in_cell}");
assert!(shown[1].1 > shown[0].1 + 5.0, "in_cell={in_cell}: shown hidden text keeps the paragraphs apart");
}
// A click on the joined text lands in the paragraph it belongs to.
let d = doc(&[("Alpha", true), ("Omega", false), ("Beta", false)], false);
let l = lay(&d);
let omega = l.caret(&Pos::body(1, 2)).unwrap();
let hit = l.hit(omega.page, omega.x + 0.5, omega.top + omega.height / 2.0, StoryRef::Body).unwrap();
assert_eq!(hit.path, Path::top(1));
}
#[test]
fn text_going_on_from_a_larger_heading_sits_on_its_baseline() {
// A heading with a hidden mark followed by body text (a style separator in Word, #3986): the
// body text's first line goes on beside the heading, on the heading's baseline; its next lines
// start at the margin, below both.
let body = "Body text that is long enough to wrap onto a second line in this column. ".repeat(3);
let mut d = Document::from_text(&format!("Heading\n{body}"));
d.format_range(&Pos::body(0, 0), &Pos::body(0, 7), &|c| c.size = Some(18.0)).unwrap();
d.para_mut(StoryRef::Body, &Path::top(0)).unwrap().mark.hidden = Some(true);
let l = lay(&d);
let lines: Vec<(Path, f32, f32, f32)> = l.pages[0]
.items
.iter()
.filter_map(|it| match it {
Placed::Lines { path, para, l0, l1, x, y, .. } => {
let first = para.lines.get(*l0)?;
let (x, y) = (*x, *y);
Some((*l0..*l1).filter_map(move |li| {
let line = para.lines.get(li)?;
Some((path.clone(), y + line.baseline - first.top, x + para.x_of(li, line.start)?, y + line.top - first.top))
}))
}
_ => None,
})
.flatten()
.collect();
let heading = lines.iter().find(|l| l.0 == Path::top(0)).unwrap();
let body: Vec<_> = lines.iter().filter(|l| l.0 == Path::top(1)).collect();
assert!(body.len() >= 2, "{lines:?}");
assert!((body[0].1 - heading.1).abs() < 0.01, "body baseline {} vs heading {}", body[0].1, heading.1);
assert!(body[0].2 > 100.0, "the body text starts after the heading's, at {}", body[0].2);
assert!((body[1].2 - 72.0).abs() < 0.5, "the next line starts at the margin, not at {}", body[1].2);
assert!(body[1].3 > heading.1, "the next line is below the shared one");
}
#[test]
fn a_text_box_anchored_in_a_paragraph_with_a_hidden_mark_is_not_joined() {
// A text box anchored in the first paragraph lays its own story out, whose first line has
// the same path as that paragraph (#3986). The next paragraph goes on from the paragraph's
// text, not from the box's, which is drawn after it.
let mut d = Document::from_text("Alpha\nOmega");
d.para_mut(StoryRef::Body, &Path::top(0)).unwrap().mark.hidden = Some(true);
let float = wordcraft_doc::para::Float {
wrap: wordcraft_doc::para::Wrap::InFrontOfText,
h_rel: wordcraft_doc::para::Anchor::Column,
v_rel: wordcraft_doc::para::Anchor::Paragraph,
x: 200.0,
y: 100.0,
dist: 0.0,
..Default::default()
};
text_box(&mut d, 0, "Box", 100.0, 40.0, float);
let l = lay(&d);
// The top of a story's line at a block, and the x its text starts and ends at.
let line = |story: StoryRef, block: usize| {
l.pages[0].items.iter().find_map(|it| match it {
Placed::Lines { story: s, path, para, l0, l1, x, y, .. } if *s == story && *path == Path::top(block) => {
Some((*y, x + para.x_of(*l0, 0)?, x + para.x_of(l1.checked_sub(1)?, para.text_len)?))
}
_ => None,
})
};
let (alpha, omega) = (line(StoryRef::Body, 0).unwrap(), line(StoryRef::Body, 1).unwrap());
assert!((omega.0 - alpha.0).abs() < 0.01, "Omega at {} not on Alpha's line {}", omega.0, alpha.0);
assert!((omega.1 - alpha.2).abs() < 0.5, "Omega starts at {}, Alpha ends at {}", omega.1, alpha.2);
}
#[test]
fn a_joined_paragraph_moved_to_the_next_page_has_its_own_number() {
// A paragraph going on from one with a hidden mark (#3986) that moves whole to the next page
// (its lines kept together) no longer shares that line: there its number is drawn and its
// text starts at its own indent.
let omega = "Omega ".repeat(60);
let build = |filler: usize| {
let mut text: Vec<String> = (0..filler).map(|i| format!("Filler {i}")).collect();
text.push("Alpha".into());
text.push(omega.clone());
let mut d = Document::from_text(&text.join("\n"));
let id = Arc::make_mut(&mut d.numbering).add_list(wordcraft_doc::ListKind::Numbered);
d.format_paragraphs(&Pos::body(filler, 0), &Pos::body(filler + 1, omega.len()), &|p| {
p.numbering = Some(wordcraft_doc::props::NumRef { num: id, level: 0 });
})
.unwrap();
d.para_mut(StoryRef::Body, &Path::top(filler)).unwrap().mark.hidden = Some(true);
d.para_mut(StoryRef::Body, &Path::top(filler + 1)).unwrap().props.keep_lines = Some(true);
d
};
// The page of a paragraph's first line, with its number there.
let first = |l: &DocLayout, block: usize| {
l.pages.iter().enumerate().find_map(|(pi, page)| {
page.items.iter().find_map(|it| match it {
Placed::Lines { path, para, l0: 0, .. } if *path == Path::top(block) => {
Some((pi, para.label.as_ref().map(|label| label.text.clone())))
}
_ => None,
})
})
};
for filler in 20..80 {
let d = build(filler);
let l = lay(&d);
let (Some((0, alpha)), Some((1, omega_label))) = (first(&l, filler), first(&l, filler + 1)) else { continue };
assert_eq!(alpha.as_deref(), Some("1."));
assert_eq!(omega_label.as_deref(), Some("2."), "the moved paragraph draws its number");
let (a, o) = (l.caret(&Pos::body(filler, 0)).unwrap(), l.caret(&Pos::body(filler + 1, 0)).unwrap());
assert_eq!(o.page, 1);
assert!((o.x - a.x).abs() < 0.5, "the moved paragraph's text starts at its own indent: {} vs {}", o.x, a.x);
return;
}
panic!("no filler put Alpha last on the first page with the joined paragraph moved on");
}
#[test]
fn a_joined_first_word_that_does_not_fit_goes_on_the_next_line_at_the_indent() {
// Word (#3986): when the next paragraph's first word doesn't fit after the first one's text,
// it goes on the next line, still joined (no number drawn), at the indent of the list's text.
let build = |n: usize| {
let alpha = vec!["aa"; n].join(" ");
let omega = "Omegaomegaomega tail";
let mut d = Document::from_text(&format!("{alpha}\n{omega}"));
let id = Arc::make_mut(&mut d.numbering).add_list(wordcraft_doc::ListKind::Numbered);
d.format_paragraphs(&Pos::body(0, 0), &Pos::body(1, omega.len()), &|p| {
p.numbering = Some(wordcraft_doc::props::NumRef { num: id, level: 0 });
})
.unwrap();
d.para_mut(StoryRef::Body, &Path::top(0)).unwrap().mark.hidden = Some(true);
(d, alpha.len())
};
for n in 20..200 {
let (d, alpha_len) = build(n);
let l = lay(&d);
let (end, start) = (l.caret(&Pos::body(0, alpha_len)).unwrap(), l.caret(&Pos::body(1, 0)).unwrap());
if (start.top - end.top).abs() < 0.5 {
continue; // still on the shared line
}
let indent = l.caret(&Pos::body(0, 0)).unwrap().x;
assert!(start.top > end.top, "the first word goes below the shared line");
assert!((start.x - indent).abs() < 0.5, "at the list text's indent {indent}, not {}", start.x);
let label = l.pages.iter().flat_map(|p| &p.items).find_map(|it| match it {
Placed::Lines { path, para, .. } if *path == Path::top(1) => Some(para.label.as_ref().map(|label| label.text.clone())),
_ => None,
});
assert_eq!(label, Some(None), "still joined: no number drawn");
return;
}
panic!("no length of the first paragraph left its last line too full for the next one's first word");
}
#[test]
fn a_shared_line_is_one_line_for_line_numbers_and_vertical_alignment() {
// Word (#3986): the line two paragraphs share through a hidden mark is one line. Line
// numbering gives it one number ("Line one", the shared line, "After": 1, 2, 3), and justified
// vertical alignment keeps the two paragraphs together as one block.
let doc = |valign: wordcraft_doc::section::PageVAlign| {
let mut d = Document::from_text("Line one\nAlpha\nOmega\nAfter");
for b in d.body.iter_mut() {
if let Block::Para(p) = std::sync::Arc::make_mut(b) {
p.props.space_before = Some(0.0);
p.props.space_after = Some(0.0);
}
}
d.para_mut(StoryRef::Body, &Path::top(1)).unwrap().mark.hidden = Some(true);
d.last_section.valign = valign;
d
};
let mut d = doc(wordcraft_doc::section::PageVAlign::Top);
d.last_section.line_numbers = Some(Default::default());
let l = lay(&d);
let numbers: Vec<f32> = l.pages[0]
.items
.iter()
.filter_map(|it| match it {
Placed::Lines { story, y, .. } if *story == DECOR_STORY => Some(*y),
_ => None,
})
.collect();
assert_eq!(numbers.len(), 3, "one number per shown line: {numbers:?}");
assert!(numbers.windows(2).all(|w| w[1] > w[0] + 5.0), "no two numbers on one line: {numbers:?}");
let l = lay(&doc(wordcraft_doc::section::PageVAlign::Justify));
let y = |off: (usize, usize)| l.caret(&Pos::body(off.0, off.1)).unwrap().top;
assert!((y((2, 0)) - y((1, 0))).abs() < 0.01, "Omega stays on Alpha's line: {} vs {}", y((2, 0)), y((1, 0)));
let (g1, g2) = (y((1, 0)) - y((0, 0)), y((3, 0)) - y((1, 0)));
assert!(g1 > 100.0 && (g1 - g2).abs() < 0.05, "equal gaps around the shared line: {g1} {g2}");
}
#[test]
fn a_joined_line_with_a_hanging_indent_still_starts_after_the_text_before() {
// The joined paragraph's first-line indent reaches left of the margin: its text still starts
// after the text of the paragraph before, never left of it (#3986).
let mut d = Document::from_text("Alpha\na b c");
d.para_mut(StoryRef::Body, &Path::top(0)).unwrap().mark.hidden = Some(true);
let q = d.para_mut(StoryRef::Body, &Path::top(1)).unwrap();
q.props.indent_left = Some(0.0);
q.props.indent_first = Some(-36.0);
let l = lay(&d);
let (end, start) = (l.caret(&Pos::body(0, 5)).unwrap(), l.caret(&Pos::body(1, 0)).unwrap());
assert!((start.top - end.top).abs() < 0.01, "on the shared line");
assert!(start.x >= end.x - 0.01, "after Alpha: starts at {}, Alpha ends at {}", start.x, end.x);
}
#[test]
fn a_joined_paragraphs_shading_and_borders_start_below_the_shared_line() {
// Word (synthetic DOCX, 16.0.20625): the line a paragraph shares with the one before, whose
// mark is hidden, shows that one's shading and borders, not its own. Its own start on its next
// line (no top border there), and a paragraph that is all on the shared line shows neither and
// takes no room for its borders; what follows starts below the first one's bottom border.
let yellow = wordcraft_doc::props::Rgb(0xFF, 0xFF, 0);
let boxed = || Some(Borders::all(Border { space: 1.0, ..Border::single(1.5) }));
// "Alpha" (mark hidden) with `first`'s formatting, then `second` with its own, then "After".
let doc = |first: &dyn Fn(&mut ParaProps), second_text: &str, second: &dyn Fn(&mut ParaProps), in_cell: bool| {
let mut d = Document::from_text(&format!("Alpha\n{second_text}\nAfter"));
let a = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
a.mark.hidden = Some(true);
first(&mut a.props);
second(&mut d.para_mut(StoryRef::Body, &Path::top(1)).unwrap().props);
if in_cell {
let mut table = Table::new(1, 1, 400.0);
table.props.borders = Some(Borders::all(Border { style: BorderStyle::None, width: 0.0, color: None, space: 0.0 }));
table.rows[0].cells[0].blocks = std::mem::take(&mut d.body);
d.body = vec![std::sync::Arc::new(Block::Table(table))];
}
d
};
let path = |i: u32, in_cell: bool| if in_cell { Path(vec![0, 0, 0, i]) } else { Path::top(i as usize) };
// The shared line (top, bottom), "After"'s top, fills and the paragraphs' horizontal rules.
let laid = |d: &Document, in_cell: bool| {
crate::test_fonts();
let l = lay(d);
let at = |i: u32| l.caret(&Pos { story: StoryRef::Body, path: path(i, in_cell), off: 0 }).unwrap();
let (alpha, after) = (at(0), at(2));
let fills: Vec<Rect> = l.pages[0]
.items
.iter()
.filter_map(|i| if let Placed::Fill { rect, color } = i { (*color == yellow).then_some(*rect) } else { None })
.collect();
let rules: Vec<(f32, f32, f32, f32)> = l.pages[0]
.items
.iter()
.filter_map(
|i| if let Placed::Rule { x0, y0, x1, y1, border } = i { (border.width == 1.5).then_some((*x0, *y0, *x1, *y1)) } else { None },
)
.collect();
(alpha.top, alpha.top + alpha.height, after.top, fills, rules)
};
let none = |_: &mut ParaProps| {};
let long = format!("Omega {}", "zeta ".repeat(30));
for in_cell in [false, true] {
let (top, bottom, after, ..) = laid(&doc(&none, "Omega", &none, in_cell), in_cell);
// The second one shaded, all of it on the shared line: no shading over "Alpha".
let (t, _, a, fills, _) = laid(&doc(&none, "Omega", &|p| p.shading = Some(yellow), in_cell), in_cell);
assert!(fills.is_empty(), "in_cell={in_cell}: {fills:?}");
assert!((t - top).abs() < 0.01 && (a - after).abs() < 0.01, "in_cell={in_cell}");
// Shaded and running on: the shading starts on its own next line.
let (_, b, _, fills, _) = laid(&doc(&none, &long, &|p| p.shading = Some(yellow), in_cell), in_cell);
assert_eq!(fills.len(), 1, "in_cell={in_cell}: {fills:?}");
assert!(fills[0].y >= b - 0.01, "in_cell={in_cell}: shading from {} over the shared line ending at {b}", fills[0].y);
// The first one shaded: the shared line is.
let (t, b, _, fills, _) = laid(&doc(&|p| p.shading = Some(yellow), "Omega", &none, in_cell), in_cell);
assert_eq!(fills.len(), 1, "in_cell={in_cell}: {fills:?}");
assert!(fills[0].y <= t + 0.01 && fills[0].bottom() >= b - 0.01, "in_cell={in_cell}: {fills:?}");
// The second one boxed, all of it on the shared line: no borders, no room for them.
let (t, _, a, _, rules) = laid(&doc(&none, "Omega", &|p| p.borders = boxed(), in_cell), in_cell);
assert!(rules.is_empty(), "in_cell={in_cell}: {rules:?}");
assert!((t - top).abs() < 0.01 && (a - after).abs() < 0.01, "in_cell={in_cell}: {t} {a}");
// Boxed and running on: its box is around its own lines, open at the top, with its bottom
// border's room under it; the shared line stays where it is.
let (t, b, _, _, rules) = laid(&doc(&none, &long, &|p| p.borders = boxed(), in_cell), in_cell);
assert!((t - top).abs() < 0.01, "in_cell={in_cell}: shared line moved to {t}");
assert_eq!(rules.iter().filter(|r| r.1 == r.3).count(), 1, "in_cell={in_cell}: only the bottom border: {rules:?}");
assert!(rules.iter().all(|r| r.1.min(r.3) >= b - 0.01), "in_cell={in_cell}: a border over the shared line: {rules:?}");
// The first one boxed: what follows starts below its bottom border.
let (_, _, a, _, rules) = laid(&doc(&|p| p.borders = boxed(), "Omega", &none, in_cell), in_cell);
let bottom_rule = rules.iter().filter(|r| r.1 == r.3).map(|r| r.1).fold(f32::MIN, f32::max);
assert!(bottom_rule > bottom, "in_cell={in_cell}: {rules:?}");
assert!(a >= bottom_rule + 0.75 - 0.01, "in_cell={in_cell}: After at {a}, over the border at {bottom_rule}");
}
}
#[test]
fn a_joined_paragraph_keeps_its_revision_for_the_cache_and_the_word_being_typed() {
// The joined paragraph is laid out as a copy without its space before (#3986). The copy keeps
// the document's revision: the word being typed in it gets no squiggle, and laying the
// document out again reuses its layouts.
crate::test_fonts();
let mut d = Document::from_text("Alpha\nhelo wrld\nAfter");
d.para_mut(StoryRef::Body, &Path::top(0)).unwrap().mark.hidden = Some(true);
let rev = d.para(StoryRef::Body, &Path::top(1)).unwrap().rev;
let marks = |l: &DocLayout| -> Vec<String> {
l.pages[0]
.items
.iter()
.filter_map(|i| match i {
Placed::Lines { para, path, .. } if *path == Path::top(1) => {
Some(para.issues.iter().filter(|i| !i.2).map(|i| "helo wrld"[i.0..i.1].to_string()).collect::<Vec<_>>())
}
_ => None,
})
.flatten()
.collect()
};
let mut c = LayoutCache::new();
let opts = LayoutOptions { proofing: true, ..LayoutOptions::default() };
let both = layout(&d, &mut c, &opts);
assert_eq!(marks(&both), ["helo", "wrld"]);
let (a, b) = (both.caret(&Pos::body(0, 5)).unwrap(), both.caret(&Pos::body(1, 0)).unwrap());
assert!((a.top - b.top).abs() < 0.01, "joined");
let misses = c.misses;
let again = layout(&d, &mut c, &opts);
assert_eq!(marks(&again), ["helo", "wrld"]);
assert_eq!(c.misses, misses, "nothing laid out again");
let typing = layout(&d, &mut c, &LayoutOptions { typing_word: Some(TypingWord { rev, start: 5, end: 9 }), ..opts.clone() });
assert_eq!(marks(&typing), ["helo"], "the word being typed is left alone");
}
#[test]
fn a_numbered_heading_opening_with_a_page_break_takes_its_number_along() {
crate::test_fonts();
@@ -2906,239 +2501,6 @@ fn tables_lay_out_cells() {
assert!(l.cell_at(0, c.x, c.top + 2.0).is_some());
}
#[test]
fn clicking_in_a_table_cell_stays_in_that_cell_even_away_from_center() {
use wordcraft_doc::props::VAlign;
crate::test_fonts();
let mut d = Document::from_text("before\nafter");
let mut t = Table::new(2, 3, 468.0);
// Row 0, Cell 0 has one short line:
t.rows[0].cells[0].blocks = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("Short", Default::default()))];
// Row 0, Cell 1 has multiple lines, making the row tall:
t.rows[0].cells[1].blocks =
vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("Line 1\nLine 2\nLine 3\nLine 4\nLine 5\nLine 6", Default::default()))];
// Row 0, Cell 2 is empty:
t.rows[0].cells[2].blocks = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::new())];
// Row 1, Cell 0 is vertically centered:
t.rows[1].cells[0].props.valign = Some(VAlign::Center);
t.rows[1].cells[0].blocks = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("Centered", Default::default()))];
// Row 1, Cell 1 is tall:
t.rows[1].cells[1].blocks =
vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("R1 L1\nR1 L2\nR1 L3\nR1 L4\nR1 L5", Default::default()))];
// Row 1, Cell 2 has turned text:
t.rows[1].cells[2].props.text_direction = TextDirection::Down;
t.rows[1].cells[2].blocks = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("Turned", Default::default()))];
d.insert_block(StoryRef::Body, &Path::top(1), wordcraft_doc::Block::Table(t)).unwrap();
let l = lay(&d);
let cell_rect = |r: usize, c: usize| {
l.pages[0]
.items
.iter()
.find_map(|it| match it {
Placed::Cell { rect, row, cell, .. } if *row == r && *cell == c => Some(*rect),
_ => None,
})
.unwrap()
};
let r00 = cell_rect(0, 0);
let r02 = cell_rect(0, 2);
let r10 = cell_rect(1, 0);
let r12 = cell_rect(1, 2);
// 1. Click near the bottom of Row 0, Cell 0 (away from its short text, near row boundary):
let click00 = l.hit(0, r00.x + 10.0, r00.bottom() - 4.0, StoryRef::Body).unwrap();
assert_eq!(click00.path, Path(vec![1, 0, 0, 0]), "click in (0, 0) must stay in (0, 0), got {:?}", click00.path);
// 2. Click in the middle/bottom of empty Row 0, Cell 2:
let click02 = l.hit(0, r02.x + 20.0, r02.y + r02.h * 0.75, StoryRef::Body).unwrap();
assert_eq!(click02.path, Path(vec![1, 0, 2, 0]), "click in empty (0, 2) must stay in (0, 2), got {:?}", click02.path);
// 3. Click near top of vertically centered Row 1, Cell 0 (above centered text):
let click10_top = l.hit(0, r10.x + 15.0, r10.y + 4.0, StoryRef::Body).unwrap();
assert_eq!(click10_top.path, Path(vec![1, 1, 0, 0]), "click near top of centered (1, 0) must stay in (1, 0), got {:?}", click10_top.path);
// 4. Click near bottom of vertically centered Row 1, Cell 0 (below centered text):
let click10_bot = l.hit(0, r10.x + 15.0, r10.bottom() - 4.0, StoryRef::Body).unwrap();
assert_eq!(click10_bot.path, Path(vec![1, 1, 0, 0]), "click near bottom of centered (1, 0) must stay in (1, 0), got {:?}", click10_bot.path);
// 5. Click in turned text Row 1, Cell 2 (away from text edge, inside cell):
let click12 = l.hit(0, r12.x + 10.0, r12.bottom() - 6.0, StoryRef::Body).unwrap();
assert_eq!(click12.path, Path(vec![1, 1, 2, 0]), "click in turned cell (1, 2) must stay in (1, 2), got {:?}", click12.path);
}
#[test]
fn clicking_in_a_nested_table_cell_stays_in_nested_cell() {
crate::test_fonts();
let mut d = Document::new();
let mut outer = Table::new(1, 1, 468.0);
let mut inner = Table::new(1, 2, 300.0);
inner.rows[0].cells[0].blocks = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("Inner", Default::default()))];
inner.rows[0].cells[1].blocks = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("L1\nL2\nL3\nL4\nL5", Default::default()))];
outer.rows[0].cells[0].blocks = vec![
wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("Outer\n\n\n\n\n\n", Default::default())),
wordcraft_doc::Block::Table(inner).into(),
];
d.body = vec![wordcraft_doc::Block::Table(outer).into()];
let l = lay(&d);
let inner_cell = l.pages[0]
.items
.iter()
.find_map(|it| match it {
Placed::Cell { rect, table, row, cell, .. } if table.0 == vec![0, 0, 0, 1] && *row == 0 && *cell == 0 => Some(*rect),
_ => None,
})
.unwrap();
// Click near the bottom of inner cell (0, 0), closer to outer cell's bottom or away from "Inner":
let click = l.hit(0, inner_cell.x + 10.0, inner_cell.bottom() - 4.0, StoryRef::Body).unwrap();
assert_eq!(click.path, Path(vec![0, 0, 0, 1, 0, 0, 0]), "click in nested cell must stay in nested cell, got {:?}", click.path);
}
#[test]
fn clicking_in_a_turned_cell_on_an_all_turned_page_stays_in_that_cell() {
crate::test_fonts();
let mut d = Document::new();
let mut t = Table::new(1, 2, 468.0);
// TextDirection::Up places text on the left side of each cell, so a click near the right
// edge of cell 0 is much closer to cell 1's text than cell 0's own text.
t.rows[0].cells[0].props.text_direction = TextDirection::Up;
t.rows[0].cells[0].blocks = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("Left", Default::default()))];
t.rows[0].cells[1].props.text_direction = TextDirection::Up;
t.rows[0].cells[1].blocks = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("Right", Default::default()))];
d.body = vec![wordcraft_doc::Block::Table(t).into()];
let l = lay(&d);
assert!(crate::hit::page_lines(&l.pages[0], StoryRef::Body).is_empty(), "page should have only turned lines");
let left_cell = l.pages[0]
.items
.iter()
.find_map(|it| match it {
Placed::Cell { rect, row, cell, .. } if *row == 0 && *cell == 0 => Some(*rect),
_ => None,
})
.unwrap();
let click_right = l.hit(0, left_cell.right() - 4.0, left_cell.y + 10.0, StoryRef::Body).unwrap();
assert_eq!(click_right.path, Path(vec![0, 0, 0, 0]), "click on right of turned cell 0 must stay in cell 0, got {:?}", click_right.path);
}
#[test]
fn clicking_near_shared_edge_within_turned_tolerance_stays_in_clicked_cell() {
crate::test_fonts();
let mut d = Document::new();
let mut t = Table::new(1, 2, 468.0);
// Cell 0 is empty; Cell 1 has TextDirection::Up, which places turned text near Cell 1's left
// edge (the shared border with Cell 0) so its 2pt expanded hit box reaches into Cell 0.
t.rows[0].cells[0].blocks = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::new())];
t.rows[0].cells[1].props.margins = Some([0.0; 4]);
t.rows[0].cells[1].props.text_direction = TextDirection::Up;
t.rows[0].cells[1].blocks = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("Turned", Default::default()))];
d.body = vec![wordcraft_doc::Block::Table(t).into()];
let l = lay(&d);
let cell0 = l.pages[0]
.items
.iter()
.find_map(|it| match it {
Placed::Cell { rect, row, cell, .. } if *row == 0 && *cell == 0 => Some(*rect),
_ => None,
})
.unwrap();
let turned_bounds = l.pages[0]
.items
.iter()
.find_map(|it| match it {
Placed::Lines { path, .. } if path == &Path(vec![0, 0, 1, 0]) => it.turned_bounds(),
_ => None,
})
.unwrap();
// Click inside Cell 0, 0.5pt left of the shared border, and confirm it lies within the 2pt
// expanded turned_bounds of Cell 1.
let click_x = cell0.right() - 0.5;
let click_y = turned_bounds.y + turned_bounds.h * 0.5;
assert!(cell0.contains(wordcraft_geom::Point::new(click_x, click_y)));
assert!(turned_bounds.expand(2.0).contains(wordcraft_geom::Point::new(click_x, click_y)));
let hit = l.hit(0, click_x, click_y, StoryRef::Body).unwrap();
assert_eq!(hit.path, Path(vec![0, 0, 0, 0]), "click inside cell 0 within 2pt of cell 1's turned text must stay in cell 0, got {:?}", hit.path);
// Outside the table, the 2pt tolerance on turned text still applies.
let mut d_out = Document::new();
let mut t_out = Table::new(1, 1, 468.0);
t_out.rows[0].cells[0].props.margins = Some([0.0; 4]);
t_out.rows[0].cells[0].props.text_direction = TextDirection::Up;
t_out.rows[0].cells[0].blocks = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("Edge", Default::default()))];
d_out.body = vec![
wordcraft_doc::Block::Table(t_out).into(),
wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("Upright", Default::default())),
];
let l_out = lay(&d_out);
let out_cell = l_out.pages[0]
.items
.iter()
.find_map(|it| match it {
Placed::Cell { rect, .. } => Some(*rect),
_ => None,
})
.unwrap();
let out_bounds = l_out.pages[0].items.iter().find_map(|it| it.turned_bounds()).unwrap();
let out_x = out_bounds.x - 1.0;
let out_y = out_bounds.y + out_bounds.h * 0.5;
assert!(!out_cell.contains(wordcraft_geom::Point::new(out_x, out_y)));
assert!(out_bounds.expand(2.0).contains(wordcraft_geom::Point::new(out_x, out_y)));
let out_hit = l_out.hit(0, out_x, out_y, StoryRef::Body).unwrap();
assert_eq!(out_hit.path, Path(vec![0, 0, 0, 0]));
// Beyond the 2pt tolerance, the upright paragraph is hit instead (proving tolerance is required).
let far_hit = l_out.hit(0, out_bounds.x - 3.0, out_y, StoryRef::Body).unwrap();
assert_eq!(far_hit.path, Path(vec![1]));
}
#[test]
fn clicking_in_a_header_or_footer_table_cell_stays_in_that_cell() {
crate::test_fonts();
let mut d = Document::from_text("Body text");
let mut ht = Table::new(1, 2, 468.0);
ht.rows[0].cells[0].blocks = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("Short", Default::default()))];
ht.rows[0].cells[1].blocks = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("H1\nH2\nH3\nH4\nH5", Default::default()))];
let hid = d.add_part(wordcraft_doc::PartKind::Header, vec![wordcraft_doc::Block::Table(ht).into()]);
d.last_section.headers.default = Some(hid);
let mut ft = Table::new(1, 2, 468.0);
ft.rows[0].cells[0].blocks = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("FShort", Default::default()))];
ft.rows[0].cells[1].blocks = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("F1\nF2\nF3\nF4\nF5", Default::default()))];
let fid = d.add_part(wordcraft_doc::PartKind::Footer, vec![wordcraft_doc::Block::Table(ft).into()]);
d.last_section.footers.default = Some(fid);
let l = lay(&d);
let h_cell0 = l.pages[0]
.header
.iter()
.find_map(|it| match it {
Placed::Cell { rect, story, row, cell, .. } if *story == StoryRef::Part(hid) && *row == 0 && *cell == 0 => Some(*rect),
_ => None,
})
.unwrap();
let h_hit = l.hit(0, h_cell0.x + 10.0, h_cell0.bottom() - 4.0, StoryRef::Part(hid)).unwrap();
assert_eq!(h_hit.path, Path(vec![0, 0, 0, 0]), "click in header cell (0, 0) must stay in (0, 0), got {:?}", h_hit.path);
let f_cell0 = l.pages[0]
.footer
.iter()
.find_map(|it| match it {
Placed::Cell { rect, story, row, cell, .. } if *story == StoryRef::Part(fid) && *row == 0 && *cell == 0 => Some(*rect),
_ => None,
})
.unwrap();
let f_hit = l.hit(0, f_cell0.x + 10.0, f_cell0.bottom() - 4.0, StoryRef::Part(fid)).unwrap();
assert_eq!(f_hit.path, Path(vec![0, 0, 0, 0]), "click in footer cell (0, 0) must stay in (0, 0), got {:?}", f_hit.path);
}
#[test]
fn a_tables_own_space_above_and_below_moves_the_text() {
// ODT tables' `fo:margin-top`/`fo:margin-bottom`: added to the spacing around the table.
@@ -9223,220 +8585,6 @@ fn chart_text_the_font_lacks_is_drawn_in_a_fallback_face() {
assert!(xs.windows(2).all(|w| w[0] <= w[1]), "{xs:?}");
}
/// A bundled Source Sans 3 font patched so its last cmap group (U+1F916) maps `first..=last`,
/// registered in [`wordcraft_fonts::FontDb::global`] under `family`.
fn diagram_test_font(family: &str, first: u32, last: u32) -> (Vec<u8>, String) {
let mut data = std::fs::read(std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/fonts/SourceSans3-Regular.ttf")).unwrap();
let from = [0x0001_F916_u32.to_be_bytes(); 2].concat();
let to = [first.to_be_bytes(), last.to_be_bytes()].concat();
let mut patched = 0;
while let Some(at) = data.windows(from.len()).position(|w| w == from) {
data[at..at + to.len()].copy_from_slice(&to);
patched += 1;
}
assert!(patched > 0);
(data, family.to_string())
}
/// RAII guard to clean up test document fonts added to [`wordcraft_fonts::FontDb::global`].
struct CleanupDocumentFonts<'a>(&'a wordcraft_fonts::FontDb, &'static [&'static str]);
impl Drop for CleanupDocumentFonts<'_> {
fn drop(&mut self) {
self.0.remove_document_fonts(self.1);
}
}
/// SmartArt diagram CJK labels keep one consistent fallback font across nodes,
/// matching the diagram's primary serif/sans nature, including when a label contains a symbol (#5672).
#[test]
fn smart_art_diagram_cjk_labels_maintain_consistent_fallback_font() {
crate::test_fonts();
// #5672: CJK labels in a SmartArt diagram rendered in two different fallback fonts
// (first node serif Mincho, rest sans). The diagram must maintain a consistent fallback font
// matching the diagram's primary font style, even when another character needs a separate symbol
// fallback face. Both sans-serif and serif primaries are tested with synthetic fonts.
use wordcraft_doc::graphic::{Graphic, GraphicItem, GraphicKind, TextAlign};
use wordcraft_doc::props::Rgb;
let db = wordcraft_fonts::FontDb::global();
const TEST_FONTS: &[&str] = &["DiagBothMincho", "DiagBothGothic", "DiagOnlySymbol"];
let _cleanup = CleanupDocumentFonts(db, TEST_FONTS);
db.add_document_fonts(vec![
diagram_test_font("DiagBothMincho", 0x3FF21, 0x3FF22),
diagram_test_font("DiagBothGothic", 0x3FF21, 0x3FF22),
diagram_test_font("DiagOnlySymbol", 0xF0129, 0xF0129),
]);
// 1. Sans-serif diagram: prefers DiagBothGothic over DiagBothMincho.
let sans_items = ["\u{3FF21} \u{F0129}", "\u{3FF22}", "\u{F0129}"]
.iter()
.enumerate()
.map(|(i, &label)| GraphicItem::Text {
rect: [0.0, (i as f32) * 30.0, 100.0, 20.0],
text: label.into(),
size: 12.0,
color: Rgb::BLACK,
bold: false,
align: TextAlign::Center,
font: Some("Source Sans 3".into()),
angle: 0.0,
})
.collect();
let sans_graphic = Graphic { kind: GraphicKind::Diagram, items: sans_items, ..Default::default() };
let sans_obj = InlineObject::Graphic { w: 300.0, h: 200.0, alt: String::new(), float: Default::default(), graphic: Arc::new(sans_graphic) };
let mut sans_doc = Document::from_text("Diagram");
sans_doc.insert_object(&Pos::body(0, 0), sans_obj, &Default::default()).unwrap();
let sans_draws = flat(display::page_display(&sans_doc, &lay(&sans_doc).pages[0], &Default::default()));
let sans_cjk_draws: Vec<_> = sans_draws
.iter()
.filter_map(|x| if let display::Draw::Glyphs { face, text, .. } = x { Some((text.as_str(), *face)) } else { None })
.filter(|(t, _)| t.contains('\u{3FF21}') || t.contains('\u{3FF22}'))
.collect();
assert_eq!(sans_cjk_draws.len(), 2, "both CJK labels drawn in sans diagram");
for (t, face) in &sans_cjk_draws {
assert_eq!(face.family, "DiagBothGothic", "CJK label {t:?} should use sans fallback DiagBothGothic");
assert!(!face.is_serif(), "fallback face must be sans");
}
let sans_sym_draws: Vec<_> = sans_draws
.iter()
.filter_map(|x| if let display::Draw::Glyphs { face, text, .. } = x { Some((text.as_str(), *face)) } else { None })
.filter(|(t, _)| t.contains('\u{F0129}'))
.collect();
assert_eq!(sans_sym_draws.len(), 2, "symbol drawn in both mixed and standalone nodes");
for (_, face) in &sans_sym_draws {
assert_eq!(face.family, "DiagOnlySymbol");
}
// 2. Serif diagram: prefers DiagBothMincho over DiagBothGothic.
let serif_items = ["\u{3FF21} \u{F0129}", "\u{3FF22}", "\u{F0129}"]
.iter()
.enumerate()
.map(|(i, &label)| GraphicItem::Text {
rect: [0.0, (i as f32) * 30.0, 100.0, 20.0],
text: label.into(),
size: 12.0,
color: Rgb::BLACK,
bold: false,
align: TextAlign::Center,
font: Some("Source Serif 4".into()),
angle: 0.0,
})
.collect();
let serif_graphic = Graphic { kind: GraphicKind::Diagram, items: serif_items, ..Default::default() };
let serif_obj = InlineObject::Graphic { w: 300.0, h: 200.0, alt: String::new(), float: Default::default(), graphic: Arc::new(serif_graphic) };
let mut serif_doc = Document::from_text("Diagram");
serif_doc.insert_object(&Pos::body(0, 0), serif_obj, &Default::default()).unwrap();
let serif_draws = flat(display::page_display(&serif_doc, &lay(&serif_doc).pages[0], &Default::default()));
let serif_cjk_draws: Vec<_> = serif_draws
.iter()
.filter_map(|x| if let display::Draw::Glyphs { face, text, .. } = x { Some((text.as_str(), *face)) } else { None })
.filter(|(t, _)| t.contains('\u{3FF21}') || t.contains('\u{3FF22}'))
.collect();
assert_eq!(serif_cjk_draws.len(), 2, "both CJK labels drawn in serif diagram");
for (t, face) in &serif_cjk_draws {
assert_eq!(face.family, "DiagBothMincho", "CJK label {t:?} should use serif fallback DiagBothMincho");
assert!(face.is_serif(), "fallback face must be serif");
}
// 3. Real CJK check (reconciled with synthetic fixtures, #5672):
// Synthetic fixtures above provide deterministic coverage for both sans-serif and serif
// diagrams across all platforms and CI runners without depending on installed CJK fonts.
// When the host environment does have a real sans-serif CJK candidate available, also
// verify that real CJK labels in a SmartArt diagram resolve consistently to a sans-serif
// fallback face across nodes.
let labels = ["新建文档", "施加样式", "导出验证"];
let label_chars: Vec<char> = labels.iter().flat_map(|s| s.chars()).collect();
let minor = wordcraft_fonts::word::resolve(&Document::default().settings.minor_font, false, false);
if db.fallback_for_diagram(&label_chars, minor.face.id(), false).is_some_and(|f| !f.is_serif()) {
let real_items = ["新建文档 \u{F0129}", "施加样式", "导出验证", "\u{F0129}"]
.iter()
.enumerate()
.map(|(i, &label)| GraphicItem::Text {
rect: [0.0, (i as f32) * 30.0, 100.0, 20.0],
text: label.into(),
size: 12.0,
color: Rgb::BLACK,
bold: false,
align: TextAlign::Center,
font: None,
angle: 0.0,
})
.collect();
let real_graphic = Graphic { kind: GraphicKind::Diagram, items: real_items, ..Default::default() };
let real_obj = InlineObject::Graphic { w: 300.0, h: 200.0, alt: String::new(), float: Default::default(), graphic: Arc::new(real_graphic) };
let mut real_doc = Document::from_text("Diagram");
real_doc.insert_object(&Pos::body(0, 0), real_obj, &Default::default()).unwrap();
let real_draws = flat(display::page_display(&real_doc, &lay(&real_doc).pages[0], &Default::default()));
let real_cjk_draws: Vec<_> = real_draws
.iter()
.filter_map(|x| if let display::Draw::Glyphs { face, text, .. } = x { Some((text.clone(), *face)) } else { None })
.filter(|(text, _)| labels.iter().any(|l| text.trim().starts_with(l)))
.collect();
assert_eq!(real_cjk_draws.len(), 3, "all three real CJK diagram labels were drawn");
let first_family = real_cjk_draws[0].1.family.clone();
assert!(!real_cjk_draws[0].1.is_serif(), "diagram fallback font should be sans-serif, was {first_family}");
for (text, face) in &real_cjk_draws {
assert_eq!(face.family, first_family, "label {text:?} used a different font family from first node");
assert!(!face.is_serif(), "label {text:?} rendered in serif font {}", face.family);
}
} else {
eprintln!("skipped real CJK check: no sans-serif CJK font covers all diagram labels");
}
}
/// In a mixed-font diagram where the first label's primary font covers characters missing from
/// later labels, later labels use the diagram fallback face, which here is that same font.
#[test]
fn mixed_font_diagram_uses_covering_fallback_for_later_missing_characters() {
crate::test_fonts();
use wordcraft_doc::graphic::{Graphic, GraphicItem, GraphicKind, TextAlign};
use wordcraft_doc::props::Rgb;
let db = wordcraft_fonts::FontDb::global();
const TEST_FONTS: &[&str] = &["DiagPartAGothic", "DiagPartBGothic", "DiagWholeGothic"];
let _cleanup = CleanupDocumentFonts(db, TEST_FONTS);
db.add_document_fonts(vec![
diagram_test_font("DiagPartAGothic", 0x3FF11, 0x3FF11),
diagram_test_font("DiagPartBGothic", 0x3FF12, 0x3FF12),
diagram_test_font("DiagWholeGothic", 0x3FF11, 0x3FF12),
]);
let items = [
("\u{3FF11}", Some("DiagWholeGothic".to_string())),
("\u{3FF11}", Some("Source Sans 3".to_string())),
("\u{3FF12}", Some("Source Sans 3".to_string())),
]
.into_iter()
.enumerate()
.map(|(i, (label, font))| GraphicItem::Text {
rect: [0.0, (i as f32) * 30.0, 100.0, 20.0],
text: label.into(),
size: 12.0,
color: Rgb::BLACK,
bold: false,
align: TextAlign::Center,
font,
angle: 0.0,
})
.collect();
let graphic = Graphic { kind: GraphicKind::Diagram, items, ..Default::default() };
let obj = InlineObject::Graphic { w: 300.0, h: 200.0, alt: String::new(), float: Default::default(), graphic: Arc::new(graphic) };
let mut d = Document::from_text("Diagram");
d.insert_object(&Pos::body(0, 0), obj, &Default::default()).unwrap();
let draws = flat(display::page_display(&d, &lay(&d).pages[0], &Default::default()));
let cjk_faces: Vec<_> = draws
.iter()
.filter_map(|x| if let display::Draw::Glyphs { face, text, .. } = x { Some((text.as_str(), *face)) } else { None })
.filter(|(t, _)| t.contains('\u{3FF11}') || t.contains('\u{3FF12}'))
.collect();
assert_eq!(cjk_faces.len(), 3, "all three labels drawn");
for (text, face) in &cjk_faces {
assert_eq!(face.family, "DiagWholeGothic", "label {text:?} should use the shared diagram fallback face");
}
}
/// The draws with figures opened up.
fn flat(draws: Vec<display::Draw>) -> Vec<display::Draw> {
draws.into_iter().flat_map(|x| if let display::Draw::Figure { draws, .. } = x { draws } else { vec![x] }).collect()
-165
View File
@@ -1,165 +0,0 @@
//! A paragraph going on from the line of one whose mark is hidden (#3986): what changes when it
//! moves off that line or is placed apart from it.
use super::lay;
use crate::{Arc, DocLayout, Placed, StoryRef, hit};
use wordcraft_doc::para::{Anchor, Float, Wrap};
use wordcraft_doc::props::{Border, Borders, LineSpacing, NumRef, TextFrame};
use wordcraft_doc::{Block, Document, Path, Pos, Table};
/// A table around the document's paragraphs (the cell paths are `[0, 0, 0, i]`).
fn in_cell(d: &mut Document) {
let mut table = Table::new(1, 1, 400.0);
table.rows[0].cells[0].blocks = std::mem::take(&mut d.body);
d.body = vec![Arc::new(Block::Table(table))];
}
/// The top of the lines of the body block or cell paragraph at `path`.
fn top_of(l: &DocLayout, path: &Path) -> f32 {
l.pages[0]
.items
.iter()
.find_map(|it| match it {
Placed::Lines { story: StoryRef::Body, path: p, y, .. } if p == path => Some(*y),
_ => None,
})
.unwrap_or_else(|| panic!("no lines at {path:?}"))
}
#[test]
fn a_joined_paragraph_moved_to_the_next_page_gets_its_top_border() {
// Sharing the line it takes no room for a top border; moved whole to the next page it is
// laid out on its own and draws one above its first line.
let omega = "Omega ".repeat(60);
let boxed = Some(Borders::all(Border { space: 1.0, ..Border::single(1.5) }));
for filler in 20..80 {
let mut text: Vec<String> = (0..filler).map(|i| format!("Filler {i}")).collect();
text.push("Alpha".into());
text.push(omega.clone());
let mut d = Document::from_text(&text.join("\n"));
d.para_mut(StoryRef::Body, &Path::top(filler)).unwrap().mark.hidden = Some(true);
let o = d.para_mut(StoryRef::Body, &Path::top(filler + 1)).unwrap();
(o.props.keep_lines, o.props.borders) = (Some(true), boxed);
let l = lay(&d);
let o = l.caret(&Pos::body(filler + 1, 0)).unwrap();
if l.caret(&Pos::body(filler, 0)).unwrap().page != 0 || o.page != 1 {
continue;
}
let tops = l.pages[1].items.iter().filter(|i| matches!(i, Placed::Rule { y0, y1, border, .. } if y0 == y1 && border.width == 1.5));
let above = tops.filter(|i| matches!(i, Placed::Rule { y0, .. } if *y0 < o.top)).count();
assert_eq!(above, 1, "the moved paragraph draws its top border above its first line");
return;
}
panic!("no filler moved the joined paragraph to the next page");
}
#[test]
fn a_joined_first_line_below_the_shared_line_does_not_cut_the_line_above() {
// "Omega"'s first word does not fit after "Alpha", so its first line goes below; its indent
// (inside "Alpha"'s text) must not cut "Alpha"'s hit extent.
let mut d = Document::from_text(&format!("Alpha\n{} tail", "W".repeat(48)));
d.para_mut(StoryRef::Body, &Path::top(0)).unwrap().mark.hidden = Some(true);
d.para_mut(StoryRef::Body, &Path::top(1)).unwrap().props.indent_left = Some(20.0);
let l = lay(&d);
let lines = hit::page_lines(&l.pages[0], StoryRef::Body);
let alpha = lines.iter().find(|h| h.path == &Path::top(0)).unwrap();
let omega = lines.iter().find(|h| h.path == &Path::top(1) && h.li == 0).unwrap();
assert!(omega.top > alpha.top + 1.0, "setup: the first word moved below the shared line");
let text_end = l.caret(&Pos::body(0, 5)).unwrap().x;
assert!(alpha.right >= text_end - 0.5, "Alpha's line reaches {} but its text ends at {text_end}", alpha.right);
}
#[test]
fn a_joined_paragraphs_drawings_are_relative_to_the_shared_line() {
// A drawing anchored to the paragraph, at its top: the paragraph's top is the shared line's,
// not the end of the paragraph before.
let mut d = Document::from_text("Alpha\nOmega\nAfter");
d.para_mut(StoryRef::Body, &Path::top(0)).unwrap().mark.hidden = Some(true);
let float =
Float { wrap: Wrap::InFrontOfText, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, x: 200.0, y: 0.0, dist: 0.0, ..Default::default() };
super::text_box_at(&mut d, &Pos::body(1, 0), "Box", 100.0, 40.0, float);
in_cell(&mut d);
let l = lay(&d);
let alpha = top_of(&l, &Path(vec![0, 0, 0, 0]));
let boxed = l.pages[0].items.iter().find_map(|it| match it {
Placed::Lines { story: StoryRef::Part(_), y, .. } => Some(*y),
_ => None,
});
let boxed = boxed.expect("the box's text is laid out");
assert!(boxed < alpha + 12.0, "the box's text at {boxed} is below the shared line at {alpha}");
}
#[test]
fn a_text_frame_after_a_hidden_mark_is_not_joined() {
// A framed paragraph is placed apart, so it shares no line with the one before: its number is
// drawn (it is counted either way). The frame is its own, or given by the table's style.
let frame =
TextFrame { x_align: Some("right".into()), h_anchor: "text".into(), v_anchor: "text".into(), wrap: "around".into(), ..Default::default() };
for from_style in [false, true] {
let mut d = Document::from_text("Alpha\n7");
let id = Arc::make_mut(&mut d.numbering).add_list(wordcraft_doc::ListKind::Numbered);
d.format_paragraphs(&Pos::body(0, 0), &Pos::body(1, 1), &|p| p.numbering = Some(NumRef { num: id, level: 0 })).unwrap();
d.para_mut(StoryRef::Body, &Path::top(0)).unwrap().mark.hidden = Some(true);
// From the table's style, the frame is given to "Alpha" too: zero dimensions cancel it there.
let (at, own) = if from_style { (0, TextFrame { w: Some(0.0), h: Some(0.0), ..frame.clone() }) } else { (1, frame.clone()) };
d.para_mut(StoryRef::Body, &Path::top(at)).unwrap().props.frame = Some(own);
in_cell(&mut d);
if from_style {
Arc::make_mut(&mut d.styles).get_mut("TableGrid").expect("Table Grid").para.frame = Some(frame.clone());
if let Some(Block::Table(t)) = d.body.first_mut().map(Arc::make_mut) {
t.props.style = Some("TableGrid".into());
}
}
let l = lay(&d);
let label = l.pages[0].items.iter().find_map(|it| match it {
Placed::Lines { path, para, .. } if path.0 == [0, 0, 0, 1] => Some(para.label.is_some()),
_ => None,
});
assert_eq!(label, Some(true), "the framed paragraph keeps its number (frame from the table style: {from_style})");
}
}
#[test]
fn a_joined_paragraphs_later_lines_start_below_a_taller_shared_line() {
// A heading whose mark is hidden, then body text going on from it: the text's first line
// shares the heading's line; its later lines start below that line and the heading's bottom
// border, not inside it (Word), whatever the text's line spacing.
let spacings = [None, Some(LineSpacing::Exactly(12.0)), Some(LineSpacing::AtLeast(12.0)), Some(LineSpacing::Multiple(2.0))];
// A large word that fits the first line of the text laid out alone but wraps off the
// narrower shared line onto the second (`big`), so the two first lines differ in height.
let cases = [false, true].into_iter().flat_map(|c| spacings.into_iter().flat_map(move |s| [(c, s, false, None), (c, s, true, None)]));
let big = [60, 70, 80].into_iter().flat_map(|at| [(false, None, false, Some(at)), (true, None, false, Some(at))]);
for (cell, spacing, bordered, large) in cases.chain(big) {
let case = format!("cell {cell}, {spacing:?}, border {bordered}, large word at {large:?}");
let mut d = Document::from_text(&format!("Heading\n{}", "body text ".repeat(40)));
d.format_range(&Pos::body(0, 0), &Pos::body(0, 7), &|c| c.size = Some(40.0)).unwrap();
if let Some(at) = large {
d.format_range(&Pos::body(1, at), &Pos::body(1, at + 4), &|c| c.size = Some(30.0)).unwrap();
}
let heading = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
heading.mark.hidden = Some(true);
if bordered {
heading.props.borders = Some(Borders { bottom: Some(Border { space: 4.0, ..Border::single(1.5) }), ..Default::default() });
}
d.para_mut(StoryRef::Body, &Path::top(1)).unwrap().props.line_spacing = spacing;
if cell {
in_cell(&mut d);
}
let l = lay(&d);
let lines = hit::page_lines(&l.pages[0], StoryRef::Body);
let heading = lines.iter().find(|h| h.path.0.last() == Some(&0)).unwrap();
// The shared line's bottom, with the heading's bottom border under it.
let rule = l.pages[0].items.iter().filter_map(|it| match it {
Placed::Rule { y0, y1, border, .. } if y0 == y1 && border.width == 1.5 => Some(*y0),
_ => None,
});
let floor = rule.fold(heading.bottom, f32::max);
assert!(!bordered || floor > heading.bottom, "setup: the border is drawn below the shared line ({case})");
let body: Vec<_> = lines.iter().filter(|h| h.path.0.last() == Some(&1)).collect();
assert!(body.len() > 2, "setup: the body text runs to several lines ({case})");
assert!(body[0].top < heading.bottom - 1.0, "the first line at {} shares the heading's line ({case})", body[0].top);
for line in &body[1..] {
assert!(line.top >= floor - 0.01, "line {} at {} starts inside the shared line, ending {floor} ({case})", line.li, line.top);
}
}
}

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