mirror of
https://github.com/storytold/wordcraft.git
synced 2026-11-27 21:39:26 +00:00
Compare commits
192
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c1b16b5e88 | ||
|
|
5687172000 | ||
|
|
0b5d4df261 | ||
|
|
6cbd8114d7 | ||
|
|
760cb852a2 | ||
|
|
59803ced07 | ||
|
|
fddd892b2d | ||
|
|
c98954d755 | ||
|
|
5d2153c15d | ||
|
|
257b81ec8f | ||
|
|
7883de796d | ||
|
|
59269a4e0e | ||
|
|
f9aaa12da7 | ||
|
|
cc9ad91d2a | ||
|
|
f1810cb01d | ||
|
|
0151061ccd | ||
|
|
992937e5dd | ||
|
|
e51fbe2e4b | ||
|
|
3a3523f172 | ||
|
|
bfc6fbc46b | ||
|
|
bdbb15e197 | ||
|
|
b7b978b05c | ||
|
|
66f603931f | ||
|
|
e7647ca261 | ||
|
|
c3e38cef0b | ||
|
|
5de0344173 | ||
|
|
b67d4723cf | ||
|
|
c7009c675f | ||
|
|
274cf67ac2 | ||
|
|
0c6a8ea18d | ||
|
|
a0f82451e3 | ||
|
|
5e129ac951 | ||
|
|
62391d8aa3 | ||
|
|
44719ece99 | ||
|
|
6c6ac698ca | ||
|
|
68c024a624 | ||
|
|
104556e47d | ||
|
|
765abcc790 | ||
|
|
a44dc74fc0 | ||
|
|
77a530b179 | ||
|
|
4e00d00779 | ||
|
|
26b1d89ad2 | ||
|
|
a272715194 | ||
|
|
ff90488655 | ||
|
|
bc629b7a4f | ||
|
|
954750790b | ||
|
|
f587bcb95a | ||
|
|
b068e1a538 | ||
|
|
9ab9f2f874 | ||
|
|
231a09761c | ||
|
|
dc12b22371 | ||
|
|
b77c55c028 | ||
|
|
09465c9fc4 | ||
|
|
c8ecea24cf | ||
|
|
2a09d78972 | ||
|
|
b163c0568d | ||
|
|
8ed5ddd47b | ||
|
|
ea8f665f20 | ||
|
|
c30777bf2a | ||
|
|
34b79b33db | ||
|
|
f89c52c428 | ||
|
|
4da5534eb8 | ||
|
|
afe332b225 | ||
|
|
3ebf69481a | ||
|
|
ab014b8fe5 | ||
|
|
7951466b8b | ||
|
|
d26c7375ff | ||
|
|
e3b742f75a | ||
|
|
f847159a29 | ||
|
|
9409b2fd79 | ||
|
|
e2f001b946 | ||
|
|
dc5d27cded | ||
|
|
c56825487f | ||
|
|
4343683da8 | ||
|
|
1f65a8e588 | ||
|
|
bfc160809c | ||
|
|
3639389be3 | ||
|
|
37d03a1eb4 | ||
|
|
7fa77df595 | ||
|
|
c179a31619 | ||
|
|
6e92d33e07 | ||
|
|
4d7100a7f8 | ||
|
|
920d9342e7 | ||
|
|
c11504affa | ||
|
|
604ad56f0a | ||
|
|
852330e928 | ||
|
|
b5fb29b539 | ||
|
|
012d0dd875 | ||
|
|
352042d41f | ||
|
|
4f6cc31af6 | ||
|
|
58e52bc962 | ||
|
|
bf2be3cad8 | ||
|
|
805fb543fa | ||
|
|
73de5b5569 | ||
|
|
5e83839736 | ||
|
|
cf161d30a3 | ||
|
|
e4633540c0 | ||
|
|
73d3c71346 | ||
|
|
c939e644aa | ||
|
|
c406211ce9 | ||
|
|
720d6f4586 | ||
|
|
224b65101c | ||
|
|
ada0a0247d | ||
|
|
027dc1f197 | ||
|
|
57a9ff0dda | ||
|
|
4700018be7 | ||
|
|
700ce2f861 | ||
|
|
6088bf6f30 | ||
|
|
7fd0136bc8 | ||
|
|
f94728dea0 | ||
|
|
6837508ec9 | ||
|
|
262d036420 | ||
|
|
eb7d54c59d | ||
|
|
c369c3a20b | ||
|
|
0ce25a8d6d | ||
|
|
3d2d9a3d9b | ||
|
|
e34e841b8f | ||
|
|
9409bc7763 | ||
|
|
d7085aabde | ||
|
|
9cfe513477 | ||
|
|
f1decbad01 | ||
|
|
139f3a2c7e | ||
|
|
a5d5ee8a29 | ||
|
|
08fe7bbb70 | ||
|
|
9f1f2cfb4f | ||
|
|
dda2b45e3c | ||
|
|
b8627a2373 | ||
|
|
993d39c723 | ||
|
|
33d874c1f5 | ||
|
|
85370b265f | ||
|
|
edd33f9db5 | ||
|
|
f005c58134 | ||
|
|
8fb8a5b789 | ||
|
|
616b43bb74 | ||
|
|
fbade3d8c2 | ||
|
|
678f9473d8 | ||
|
|
c3d854b644 | ||
|
|
8151605909 | ||
|
|
e6bc8fd884 | ||
|
|
ec483a4fb0 | ||
|
|
8b73226375 | ||
|
|
e15a3f9861 | ||
|
|
05fe5c0598 | ||
|
|
4db39e40eb | ||
|
|
f44b2e4165 | ||
|
|
45f49e9990 | ||
|
|
8a047c333b | ||
|
|
70ecef86df | ||
|
|
60ac6f5e6d | ||
|
|
1094d3c35e | ||
|
|
cc9778ebe1 | ||
|
|
442d1c3f53 | ||
|
|
3e0b11df2f | ||
|
|
ecb3633aff | ||
|
|
22314f552d | ||
|
|
685869239f | ||
|
|
f5f29dc076 | ||
|
|
fea7a9182e | ||
|
|
cdebeace8d | ||
|
|
46954248d1 | ||
|
|
f2e6234c52 | ||
|
|
f42efe368c | ||
|
|
eb5a5a451c | ||
|
|
147780b8a8 | ||
|
|
ec8f946621 | ||
|
|
e4f17d8dcc | ||
|
|
20c06f9f77 | ||
|
|
79a36f192d | ||
|
|
578f3576e9 | ||
|
|
e28050be8b | ||
|
|
b5e0be7879 | ||
|
|
d22840c369 | ||
|
|
a7257e8fed | ||
|
|
0478b7633f | ||
|
|
3eaf2e1dcf | ||
|
|
7d1b59ffd7 | ||
|
|
f5c59929b7 | ||
|
|
5df58a74e8 | ||
|
|
cb149e62a2 | ||
|
|
ee167c2696 | ||
|
|
4a1b0aac18 | ||
|
|
016d9f3525 | ||
|
|
6b5f158769 | ||
|
|
7e5f66bdac | ||
|
|
ebd5dbdbab | ||
|
|
ada55c97d6 | ||
|
|
6e8c5e5a44 | ||
|
|
d75d53376c | ||
|
|
6eab393ee7 | ||
|
|
eb7e360652 | ||
|
|
8c73173d92 | ||
|
|
c787c3e8b2 |
+12
-1
@@ -2,4 +2,15 @@
|
||||
# (#6537) and `cargo fmt --check` still passed, so the gate could not see it. Normalise on add.
|
||||
* text=auto
|
||||
|
||||
craft-i18n.rev text eol=lf
|
||||
craft-i18n.rev text eol=lf
|
||||
|
||||
# These model sources and generated tables have byte hashes recorded in model/README.md.
|
||||
# Keep checkout bytes stable even when core.autocrlf=true.
|
||||
crates/validate/model/extract_content_model.py text eol=lf
|
||||
crates/validate/model/generate_model.py text eol=lf
|
||||
crates/validate/model/content_model_v2.json text eol=lf
|
||||
crates/validate/model/content_model_v2_transitional.json text eol=lf
|
||||
crates/validate/model/content_model_dml_v2.json text eol=lf
|
||||
crates/validate/model/content_model_dml_v2_transitional.json text eol=lf
|
||||
crates/validate/src/model.rs text eol=lf
|
||||
crates/validate/model/extract_model_lf.py text eol=lf
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
-----BEGIN PGP PUBLIC KEY BLOCK-----
|
||||
|
||||
mDMEaulK1xYJKwYBBAHaRw8BAQdAqHJeDCjY6Hx5FTn/hW+aqu6V394ubLk0Zj3C
|
||||
bftDwFm0IkFydENyYWZ0IExpbnV4IFJlbGVhc2UgU2lnbmluZyBLZXmIkwQTFgoA
|
||||
OxYhBCt2dBtBSq1s0z5jEhOgBcC518PtBQJq6UrXAhsBBQsJCAcCAiICBhUKCQgL
|
||||
AgQWAgMBAh4HAheAAAoJEBOgBcC518PtGeUA/RjvULBTLlccc+2wtJkfjSnCV+cf
|
||||
PUMEGmW7XkZWkk51AP9w2A/WLv+79nREWEpZzI8LGK5EjrNazP+sY0l7j5rFCLgz
|
||||
BGrpStcWCSsGAQQB2kcPAQEHQPl7XkQ1gWsvSPf/T9b4m/UHcjJjBpSOtpYlWR56
|
||||
er5RiO8EGBYKACAWIQQrdnQbQUqtbNM+YxIToAXAudfD7QUCaulK1wIbAgCBCRAT
|
||||
oAXAudfD7XYgBBkWCgAdFiEEVo3B9o+Prsx5fzx7AG2va7DvM04FAmrpStcACgkQ
|
||||
AG2va7DvM07taQEA4d2VFkKRIP0g9TrE86KpnuXPap+LKqe0tfIxpdf9YxIA/0Wo
|
||||
9H/iG8nH++nxC087p3HE0S+0UovxqkhXJLSr8B4JDOoA/iLRpqTdYmk6fVXMyPJo
|
||||
SkOVuwZIGS6VgBdSQP0e2P2YAP41L5OoSvwdQIG3/uNrM+ieqpYeM597/hCLFs5A
|
||||
ga/qCA==
|
||||
=3wGQ
|
||||
-----END PGP PUBLIC KEY BLOCK-----
|
||||
@@ -0,0 +1,107 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
name: Nightly build check
|
||||
|
||||
# Builds the unsigned WordCraft Nightly the way the producer does (packaging/linux/nightly.sh,
|
||||
# packaging/windows/package.ps1 -Nightly, packaging/macos/nightly.sh) and checks each archive as the
|
||||
# Launcher unpacks it. No secrets and no environment: the real Nightly is signed by the shared
|
||||
# release-ref signer (craft-common-actions), which calls packaging/macos/nightly-sign.sh and the
|
||||
# app's sign.ps1.
|
||||
on:
|
||||
# The platform runners are shared with release builds: pull requests run this only with the
|
||||
# `full-ci` label, never by changed paths. `labeled` so adding it starts a run.
|
||||
pull_request:
|
||||
types: [opened, synchronize, reopened, labeled]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
# A newer push to a labelled PR cancels its older run. Any event that will not build (no `full-ci`
|
||||
# label, or another label added) gets a group of its own, so it never cancels a real build.
|
||||
concurrency:
|
||||
group: nightly-build-${{ github.event_name == 'pull_request' && contains(github.event.pull_request.labels.*.name, 'full-ci') && (github.event.action != 'labeled' || github.event.label.name == 'full-ci') && github.ref || github.run_id }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
jobs:
|
||||
linux:
|
||||
name: Nightly tar (x86_64, unsigned)
|
||||
if: >-
|
||||
github.event_name == 'workflow_dispatch' ||
|
||||
(contains(github.event.pull_request.labels.*.name, 'full-ci') &&
|
||||
(github.event.action != 'labeled' || github.event.label.name == 'full-ci'))
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 120
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
CARGO_INCREMENTAL: 0
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Install the system libraries the GUI links
|
||||
run: sudo apt-get update && sudo apt-get install -y pkg-config libxkbcommon-dev libwayland-dev libx11-dev libxcursor-dev libxrandr-dev libxi-dev libgtk-3-dev libfontconfig1-dev libfreetype-dev
|
||||
- name: Check out craft-fonts
|
||||
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@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
|
||||
@@ -0,0 +1,72 @@
|
||||
name: Dispatch release-ref nightly
|
||||
|
||||
# Transport only, never authorization. No checkout, payload parsing or release environment.
|
||||
on:
|
||||
workflow_run:
|
||||
workflows: [WordCraft unsigned nightly]
|
||||
types: [completed]
|
||||
branches: [main]
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
dispatch:
|
||||
# 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.')
|
||||
@@ -0,0 +1,45 @@
|
||||
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.
|
||||
@@ -0,0 +1,34 @@
|
||||
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"]'
|
||||
@@ -5,9 +5,9 @@ name: Packaging lint
|
||||
on:
|
||||
push:
|
||||
branches: [main, release]
|
||||
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**"]
|
||||
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**", ".github/nightly-signing-policy.json", ".github/nightly-linux-signing-key.asc", "sonar-project.properties"]
|
||||
pull_request:
|
||||
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**"]
|
||||
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**", ".github/nightly-signing-policy.json", ".github/nightly-linux-signing-key.asc", "sonar-project.properties"]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
@@ -49,3 +49,26 @@ jobs:
|
||||
- name: Build and check non-executable installer fixtures
|
||||
shell: pwsh
|
||||
run: ./packaging/windows/test-install-policy.ps1 -OutputDirectory (Join-Path $env:RUNNER_TEMP 'craft-install-policy-tests')
|
||||
|
||||
nightly-source-contract:
|
||||
name: Nightly source contracts (no build or signing)
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Enforce nightly serialization and synthetic packaging contracts
|
||||
run: python3 packaging/nightly-tests.py
|
||||
- name: Check the Arch Nightly handoff launcher (no build)
|
||||
run: bash packaging/linux/nightly-arch-tar-test.sh
|
||||
- name: Render and run the Nightly tar launcher (no build)
|
||||
run: bash packaging/linux/nightly-package-test.sh
|
||||
- name: Check the flat Nightly tar's shared template launcher (no build)
|
||||
run: bash packaging/linux/nightly-tar-launch-test.sh
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# Exercise the native print host and all UI tests on PRs; the broad FreeBSD/ARM64 gates
|
||||
# Exercise the native print host and all UI tests on Windows and macOS on PRs; the broad FreeBSD/ARM64 gates
|
||||
# stay on their existing nightly/release schedule.
|
||||
name: Printing
|
||||
|
||||
@@ -30,31 +30,32 @@ concurrency:
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
# The print host and UI tests on Linux, Windows and macOS, through the suite's shared gate: it
|
||||
# checks out craft-i18n (craft-i18n.rev) and craft-fonts, and installs the Ubuntu packages through
|
||||
# install-apt-packages, which falls back to mirrors outside ubuntu.com (as on 11 Nov 2026).
|
||||
# The print host and UI tests on Windows and macOS, through the suite's shared gate: it checks out
|
||||
# craft-i18n (craft-i18n.rev) and craft-fonts. Linux is not repeated here: ci.yml's gate runs
|
||||
# `cargo xtask ci` there, which already covers fmt, workspace clippy, every test and the wasm build.
|
||||
native:
|
||||
name: Print
|
||||
# Tracks @main so suite-wide CI fixes reach every app without a PR in each repository.
|
||||
uses: storytold/craft-common-actions/.github/workflows/gate.yml@main
|
||||
with:
|
||||
os: '["ubuntu-24.04","windows-latest","macos-latest"]'
|
||||
os: '["windows-latest","macos-latest"]'
|
||||
timeout-minutes: 90
|
||||
# The catalogs include CJK interface languages, so the UI tests need the suite's fonts, as in
|
||||
# the gate (same commit as ci.yml and release.yml).
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
packages: >-
|
||||
pkg-config libxkbcommon-dev libwayland-dev libx11-dev libxcursor-dev libxrandr-dev
|
||||
libxi-dev libgtk-3-dev libfontconfig1-dev libfreetype-dev libvulkan1 mesa-vulkan-drivers
|
||||
# No nextest: the tests run with cargo test, as before.
|
||||
tools: ""
|
||||
# Its own cache, apart from ci.yml's gate, which builds the whole workspace.
|
||||
cache-version: v1-printing
|
||||
command: |
|
||||
cargo fmt --all -- --check
|
||||
# Test binaries without debug info: they link faster and shrink to about a third, and panics
|
||||
# keep their file:line.
|
||||
dev-strip: true
|
||||
# Clippy on its own leg beside the tests, off their critical path. fmt is platform-independent
|
||||
# and runs in ci.yml. The web app's wasm build, once: ci.yml's `cargo xtask wasm` checks the
|
||||
# library crates and ui-egui, not apps/wordcraft-web.
|
||||
lint-command: |
|
||||
cargo clippy -p wordcraft -p wordcraft-ui-egui --all-targets --locked -- -D warnings
|
||||
cargo test -p wordcraft -p wordcraft-ui-egui --locked
|
||||
# Browser compatibility, once.
|
||||
if [ "$RUNNER_OS" = Linux ]; then
|
||||
if [ "$RUNNER_OS" = macOS ]; then
|
||||
cargo check -p wordcraft-web --target wasm32-unknown-unknown --locked
|
||||
fi
|
||||
command: cargo test -p wordcraft -p wordcraft-ui-egui --locked
|
||||
|
||||
@@ -60,3 +60,4 @@ jobs:
|
||||
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
|
||||
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
|
||||
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
|
||||
ARTCRAFT_SERVICES_DISPATCH_TOKEN: ${{ secrets.ARTCRAFT_SERVICES_DISPATCH_TOKEN }}
|
||||
|
||||
@@ -8,3 +8,7 @@ plan/
|
||||
/.claude/
|
||||
/target-*/
|
||||
/craft-fonts/
|
||||
/.nightly-tools
|
||||
/.nightly-input
|
||||
/craft-i18n
|
||||
__pycache__/
|
||||
|
||||
@@ -71,8 +71,8 @@ WordCraft is a Rust word processor targeting Microsoft Word parity, for macOS, W
|
||||
- Commands: each is a `CommandSpec` in `crates/engine/src/cmd/*.rs` (id, label, ribbon place, shortcut, params doc, `enabled`, `run`). UI-only commands (`ui.*`) are in `crates/ui-egui/src/lib.rs`. Colours come from `theme::Tokens`. `crates/engine/src/catalog.rs` lists Word's features with command ids; `cargo xtask parity` writes `docs/parity-checklist.md`.
|
||||
- Checks for the crates you changed: `cargo fmt --all --check`, `cargo clippy -p <crate> --all-targets -- -D warnings`, `cargo test -p <crate>`, `cargo xtask layers`, `cargo xtask wasm`, `cargo xtask assets` when assets change. `cargo xtask ci` runs all of them for the whole workspace.
|
||||
- `unsafe`: none; the workspace forbids it. Typing behaviour is pinned by `crates/engine/src/tests/typing.rs` and described in `docs/typing-parity.md`.
|
||||
- Attribution: `ATTRIBUTION.md`, a row per asset file, checked by `cargo xtask assets`. Icons are drawn in code in `crates/ui-egui/src/icons.rs`; sample content is in `crates/engine/src/sample.rs` and `cmd/design.rs`.
|
||||
- Attribution: `ATTRIBUTION.md`, a row per asset file, checked by `cargo xtask assets`. Icons are our own SVG set in `crates/ui-egui/icons/` (draw new icons there); sample content is in `crates/engine/src/sample.rs` and `cmd/design.rs`.
|
||||
- Fonts and language data come from other repositories as optional build inputs: craft-fonts through `CRAFT_FONTS_DIR`, and craft-i18n's `language-data/` through `CRAFT_I18N_DIR` (pinned by `craft-i18n.rev`; CI checks it out). Without craft-i18n the app builds with fallback spelling and no pattern hyphenation, so proofing tests need it. Proprietary font requests use installed fonts or the open substitutes in `crates/fonts/src/word.rs`. Layout tests use the fixed fonts in `assets/fonts/` ([docs/testing.md](docs/testing.md)).
|
||||
- Run: `cargo run --release -p wordcraft -- --sample --control 7981` starts the app with a sample document and the control channel. It takes JSON lines on `127.0.0.1:7981`, each with the window's key from `~/.config/wordcraft/control-key.local-7981` (macOS: `~/Library/Application Support/WordCraft/`); methods are in `crates/ui-egui/src/control.rs`, docs in `docs/control-protocol.md`. Headless screenshots: `cargo run --release -p wordcraft-ui-egui --example ui_shot -- script.jsonl`. CLI: `wordcraft-cli convert|run|commands|parity`. MCP: `wordcraft-cli mcp` (add `--connect 127.0.0.1:7981` to drive the app), see `docs/mcp.md`.
|
||||
- Run: `cargo run --release -p wordcraft -- --sample --control 7981` starts the app with a sample document and the control channel. It takes JSON lines on `127.0.0.1:7981`: authenticate once per connection with the token from `~/.config/wordcraft/control-key.local-7981` (macOS: `~/Library/Application Support/WordCraft/`), `{"id":1,"method":"auth","params":{"token":"…"}}`, then send requests without a token; methods are in `crates/ui-egui/src/control.rs`, docs in `docs/control-protocol.md` (Token). Headless screenshots: `cargo run --release -p wordcraft-ui-egui --example ui_shot -- script.jsonl`. CLI: `wordcraft-cli convert|run|commands|parity`. MCP: `wordcraft-cli mcp --automation-read-root DIR --automation-write-root DIR` (both required; `--connect` is refused until the app confines its control channel, #3695), see `docs/mcp.md`.
|
||||
- Notes and progress: `plan/` is an optional gitignored notebook. Committed: `ROADMAP.md` (progress log), `docs/gaps.md`, `docs/roadmap.md`, `docs/target-app-parity.md`, `docs/architecture.md` and the parity checklists.
|
||||
- Contributor credits: `docs/contributors.md`.
|
||||
|
||||
+369
-1
@@ -4,7 +4,7 @@ Every non-code asset in this repository (fonts, icons, images, example documents
|
||||
|
||||
**Policy (mandatory):** WordCraft contains **no Microsoft, Adobe, Avid or Autodesk iconography, images, templates, themes, clip art, fonts or other assets**. Every asset is original work by WordCraft contributors or third-party material under an open licence (OSI open source, public domain / CC0, or a Creative Commons licence that allows redistribution). Screenshots of other vendors' software are never committed. New font files go to [storytold/craft-fonts](https://github.com/storytold/craft-fonts), not this repo. The one exception is the ArtCraft brand files in `docs/brand/`: ArtCraft trademarks, not open source, used under `docs/brand/LICENSE-brand.txt`.
|
||||
|
||||
Generated-in-code art is original and has no file to list: the UI icon set (`crates/ui-egui/src/icons.rs`), the sample documents and templates (`crates/engine/src/sample.rs`), the table and style previews, and theme colours (`crates/engine/src/cmd/design.rs`).
|
||||
The UI icons are SVG files in `crates/ui-egui/icons/`, one row each below. Generated-in-code art is original and has no file to list: the sample documents and templates (`crates/engine/src/sample.rs`), the table and style previews, and theme colours (`crates/engine/src/cmd/design.rs`).
|
||||
|
||||
| Asset | Author | Source | Licence | Notes |
|
||||
|---|---|---|---|---|
|
||||
@@ -26,6 +26,12 @@ Generated-in-code art is original and has no file to list: the UI icon set (`cra
|
||||
| `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) |
|
||||
@@ -59,6 +65,368 @@ Generated-in-code art is original and has no file to list: the UI icon set (`cra
|
||||
| `docs/brand/artcraft-mark-black.svg` | ArtCraft Team | ArtCraft brand kit (project owner) | ArtCraft trademark, `docs/brand/LICENSE-brand.txt` | Not open source; usable unmodified only |
|
||||
| `docs/brand/artcraft-mark.png` | ArtCraft Team | ArtCraft brand kit (project owner) | ArtCraft trademark, `docs/brand/LICENSE-brand.txt` | Not open source; usable unmodified only |
|
||||
| `docs/brand/artcraft-mark.svg` | ArtCraft Team | ArtCraft brand kit (project owner) | ArtCraft trademark, `docs/brand/LICENSE-brand.txt` | Not open source; usable unmodified only |
|
||||
| `crates/ui-egui/icons/accept.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/accessibility.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/addNote.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/addPen.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/addShape.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/addText.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/addins.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/addressBlock.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/align.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/alignCenter.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/alignLeft.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/alignRight.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/alignText.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/altText.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/arrangeAll.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/autofit.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/bibliography.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/blankPage.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/blockAuthors.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/bold.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/bookmark.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/borderPainter.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/borders.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/breaks.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/bringForward.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/bullets.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/canvas.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/caption.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/case.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/ccCheckBox.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/ccComboBox.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/ccDate.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/ccDropDown.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/ccGallery.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/ccPicture.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/ccPlainText.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/ccRepeat.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/ccRichText.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/cellAlign.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/cellMargins.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/changeChartType.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/charborder.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/chart.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/chartData.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/chartTitle.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/check.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/checkErrors.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/chevronDoubleRight.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/chevronDown.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/chevronLeft.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/chevronRight.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/chevronUp.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/citation.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/clear.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/close.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/closeOutline.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/colWidth.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/colors.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/columns.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/combine.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/comment.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/compare.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/copy.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/coverPage.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/crop.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/crossRef.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/cut.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/darkMode.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/dataLabels.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/dateTime.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/deleteComment.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/deleteTable.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/demote.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/designMode.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/dictate.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/discord.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/discordPill.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/distributeCols.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/distributeRows.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/docPrefs.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/documentTemplate.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/draft.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/draw.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/drawTable.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/dropCap.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/dropdown.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/editRecipients.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/editor.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/effects.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/effectsDesign.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/enclose.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/endnote.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/envelope.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/equation.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/eraser.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/export.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/file.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/find.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/finish.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/first.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/fitOnePage.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/focus.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/folder.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/fontMissing.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/fontcolor.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/fontdialog.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/fonts.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/footer.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/footnote.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/formula.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/fullScreen.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/greetingLine.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/gridlines.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/group.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/grow.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/header.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/help.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/hideInk.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/highlight.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/highlightFields.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/highlightNoColor.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/homeFolder.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/hyphenation.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/icons.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/immersive.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/indent.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/indentLeft.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/indentRight.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/index.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/info.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/inkToMath.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/inkToShape.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/insertAbove.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/insertBelow.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/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/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 |
|
||||
| `crates/ui-egui/icons/lasso.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/last.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/launcher.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/legend.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/lineNumbers.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/lineSpacing.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/link.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/macros.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/mailMerge.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/margins.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/markCitation.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/markEntry.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/markdownSource.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/markup.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/matchFields.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/merge.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/mergeField.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/minus.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/models3d.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/more.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/multilevel.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/multiplePages.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/navPane.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/newComment.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/newWindow.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/next.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/nextChange.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/nextComment.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/nextFootnote.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/numbering.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/object.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/onePage.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/onlinePicture.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/open.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/options.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/orientation.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/outdent.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/outline.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/outlineBody.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/outlineCollapse.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/outlineDemote.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/outlineDown.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/outlineExpand.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/outlinePromote.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/outlineTop.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/outlineUp.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/pageBorders.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/pageBreak.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/pageColor.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/pageNumber.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
|
||||
| `crates/ui-egui/icons/pageWidth.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
|
||||
| `crates/ui-egui/icons/painter.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
|
||||
| `crates/ui-egui/icons/paraSpacing.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
|
||||
| `crates/ui-egui/icons/pastCitation.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
|
||||
| `crates/ui-egui/icons/paste.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
|
||||
| `crates/ui-egui/icons/pen.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/pencil.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/phonetic.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/picture.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/pilcrow.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/pin.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/plus.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/position.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/prevChange.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/prevComment.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/preview.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/previous.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/print.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/printLayout.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/promote.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/properties.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/protect.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/quickParts.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/readAloud.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/readMode.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/recipients.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/recover.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/redo.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/reject.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/repeatHeader.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/replace.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/replay.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/replayForward.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/replayPause.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/replayPlay.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/replayRewind.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/researcher.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/resetGraphic.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/resolve.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/restrict.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/reviewingPane.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/rotate.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/rowHeight.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/ruler.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/rules.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/save.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/saveAs.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/screenshot.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/search.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/select.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/selectTable.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/selectionPane.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/sendBackward.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/setDefault.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/shading.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/shadingNoBar.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/shape.arrow.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/shape.curvedArrowConnector.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/shape.curvedConnector.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/shape.diamond.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/shape.elbowArrowConnector.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/shape.elbowConnector.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/shape.ellipse.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/shape.heart.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/shape.line.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/shape.rectangle.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/shape.roundedRectangle.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/shape.star.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/shape.straightArrowConnector.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/shape.straightConnector.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/shape.triangle.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/shapeEffects.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/shapes.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/share.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/showComments.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/showNotes.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/shrink.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/sideBySide.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/sideToSide.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/signature.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/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 |
|
||||
| `crates/ui-egui/icons/spaceBefore.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/spelling.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/split.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/splitCells.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/splitTable.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/strike.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/styles.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/stylesPane.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/subscript.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/superscript.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/switchWindows.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/symbol.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/syncScroll.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/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 |
|
||||
| `crates/ui-egui/icons/textDirection.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/textFill.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/textLtr.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/textOutline.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/textPane.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/textRtl.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/themes.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/thesaurus.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/thickness.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/toText.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/toc.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/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/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 |
|
||||
| `crates/ui-egui/icons/updateTable.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/user.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/vertical.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/video.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/watermark.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/webLayout.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/wordArt.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/wordCount.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/wrapText.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/zoom.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/zoom100.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/zoomIn.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/zoomOut.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 |
|
||||
| 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
+2114
-206
File diff suppressed because it is too large
Load Diff
+73
-45
@@ -3,8 +3,17 @@ resolver = "3"
|
||||
members = ["crates/*", "apps/*", "xtask"]
|
||||
default-members = ["crates/*", "apps/wordcraft", "apps/wordcraft-cli", "xtask"]
|
||||
|
||||
[workspace.metadata.cl]
|
||||
# Port build loop (craft-ui-port-kit): every member but xtask, so the baseline covers the
|
||||
# non-UI crates whose framework dependencies the next pin moves too.
|
||||
selection = ["wordcraft", "wordcraft-ui-egui", "wordcraft-web", "wordcraft-cli", "wordcraft-control-key", "wordcraft-doc", "wordcraft-docbin", "wordcraft-docx", "wordcraft-engine", "wordcraft-fonts", "wordcraft-formats", "wordcraft-geom", "wordcraft-layout", "wordcraft-mcp", "wordcraft-pdf", "wordcraft-render", "wordcraft-zotero"]
|
||||
tracked = ["egui", "eframe", "wordcraft-ui-egui"]
|
||||
unset_env = ["CARGO_INCREMENTAL", "WORDCRAFT_REQUIRE_WINRES", "CRAFT_FONTS_REQUIRED", "CRAFT_I18N_REQUIRED", "CRAFT_PROOF_EMBED"]
|
||||
run_slots = 3
|
||||
test_threads = 4
|
||||
|
||||
[workspace.package]
|
||||
version = "0.19.1"
|
||||
version = "0.18.1"
|
||||
edition = "2024"
|
||||
license = "MIT OR Apache-2.0"
|
||||
rust-version = "1.95"
|
||||
@@ -28,23 +37,33 @@ 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 = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" }
|
||||
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" }
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" }
|
||||
craft-ssip = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" }
|
||||
wordcraft-proof = { package = "craft-proof", git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-ssip = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
wordcraft-engine = { path = "crates/engine" }
|
||||
wordcraft-mcp = { path = "crates/mcp" }
|
||||
wordcraft-zotero = { path = "crates/zotero" }
|
||||
wordcraft-control-key = { path = "crates/control-key" }
|
||||
wordcraft-ui-egui = { path = "crates/ui-egui" }
|
||||
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" }
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" }
|
||||
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" }
|
||||
|
||||
# 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"] }
|
||||
@@ -69,29 +88,28 @@ wuff = "0.2.9"
|
||||
brotli-decompressor = "5"
|
||||
vello_cpu = "0.2"
|
||||
image = { version = "0.25", default-features = false }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0", default-features = false, features = ["write"] }
|
||||
# craft-update: app-specific pretend versions apply to startup and manual checks.
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", features = ["egui"] }
|
||||
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" }
|
||||
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" }
|
||||
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" }
|
||||
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0", features = ["doc"] }
|
||||
craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" }
|
||||
craft-flow = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" }
|
||||
craft-odf = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0", features = ["text"] }
|
||||
craft-markdown = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" }
|
||||
craft-html = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0", features = ["flow"] }
|
||||
craft-latex = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" }
|
||||
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0", features = ["detect"] }
|
||||
craft-sheet = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" }
|
||||
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" }
|
||||
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" }
|
||||
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" }
|
||||
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "=0.1.0" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0", default-features = false, features = ["write"] }
|
||||
|
||||
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0", features = ["doc"] }
|
||||
craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-flow = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-odf = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0", features = ["text"] }
|
||||
craft-markdown = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-html = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0", features = ["flow"] }
|
||||
craft-latex = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0", features = ["detect"] }
|
||||
craft-sheet = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
# zlib streams (compressed metafile pictures in `.doc` drawings); already in the lock as a dependency of other crates.
|
||||
miniz_oxide = "0.9"
|
||||
cfb = "0.15"
|
||||
@@ -156,20 +174,30 @@ codegen-units = 16
|
||||
debug = 0
|
||||
|
||||
# Required by craft-pdf: the backend rejects writers that failed during unwinding.
|
||||
# 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 = "93dac78c93a7f1fd66e2022edeb089233b1dc45a" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541" }
|
||||
hayro = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
|
||||
|
||||
|
||||
+13
@@ -66,3 +66,16 @@ _Avoid_: Tofu, box, notdef character
|
||||
A picture the document refers to that the output cannot include: its part is absent, its data
|
||||
cannot be decoded, its format is unsupported, or it is linked from outside the file.
|
||||
_Avoid_: Broken image, dropped image
|
||||
|
||||
## Windows
|
||||
|
||||
**Document window**:
|
||||
A top-level window showing one open document. A document can be shown in several document windows
|
||||
at once (View › New Window); each window shows exactly one.
|
||||
_Avoid_: Viewport (that is the framework's surface), root window, tab
|
||||
|
||||
**Save prompt**:
|
||||
The question "Save changes?" asked when the last document window showing a document with unsaved
|
||||
changes is about to close. It belongs to that window and appears there; while it is up, the other
|
||||
windows wait.
|
||||
_Avoid_: Close guard, save dialog, unsaved-changes dialog
|
||||
|
||||
@@ -157,7 +157,7 @@ Command line:
|
||||
|
||||
```sh
|
||||
wordcraft-cli convert report.docx report.pdf # docx, pdf, odt, rtf, html, md, tex, txt, png
|
||||
wordcraft-cli convert report.docx report.pdf --strict # exit 3, no file, if a character or picture would be left out
|
||||
wordcraft-cli convert report.docx report.pdf --strict # exit 1, no file, if a character or picture would be left out
|
||||
wordcraft-cli text report.docx # plain text
|
||||
wordcraft-cli inspect report.docx # structure as JSON
|
||||
wordcraft-cli run --template sample \
|
||||
@@ -165,16 +165,27 @@ wordcraft-cli run --template sample \
|
||||
wordcraft-cli run --script job.json # the same from a file: commands, then save to docx and pdf
|
||||
```
|
||||
|
||||
`convert --strict` (a `.pdf` or `.png` output only) and `render --strict` (a PNG of one page) refuse a silently incomplete render: they exit 3
|
||||
`wordcraft-cli` follows [RFC-0018](https://github.com/storytold/craft-contrib/blob/main/rfcs/0018-cli-conventions.md)
|
||||
(command-line conventions); `wordcraft-cli --help` and `<subcommand> --help` are the reference for every flag. Exit status:
|
||||
0 success, 1 the command failed, 2 a usage error (an unknown or repeated flag, a bad value, flags that conflict or that a
|
||||
subcommand doesn't take, all checked before any file is opened), and 128 plus the signal number when a signal ends the
|
||||
process. Errors are `error: <message>` on stderr; results are on stdout. `--version`/`-V` work on every subcommand and there
|
||||
is no `version` subcommand. `WORDCRAFT_PASSWORD` is read by `--password` (a flag wins, an empty variable counts as unset,
|
||||
and `--help` never shows its value); `WORDCRAFT_REGION` sets the paper. The Linux packages (deb, rpm and tar.gz) and the
|
||||
FreeBSD package install the man pages and the bash, zsh and fish completions.
|
||||
|
||||
`convert --strict` (a `.pdf` or `.png` output only) and `render --strict` (a PNG of one page) refuse a silently incomplete render: they exit 1
|
||||
and write nothing if the output would draw a character no font has (an empty box) or leave out a
|
||||
picture. Exit codes are 0 (written), 1 (unreadable input, usage error, or `--strict` with another
|
||||
output type, checked before the input is read) and 3 (strict refusal). On exit 3, stderr has one
|
||||
`wordcraft-cli: strict: …` line per kind, then one JSON line:
|
||||
picture. Exit codes are 0 (written) and 1 (unreadable input or a strict refusal); `--strict` with another
|
||||
output type is a usage error (2), checked before the input is read. On a strict refusal, stderr has one
|
||||
`error: strict: …` line per kind, then one JSON line. (Before RFC-0018 a strict refusal exited 3; RFC-0018 has no code 3.)
|
||||
`validate` exits 0 for PASS and 1 for FAIL, INCOMPLETE or a file it can't read: the verdict is the first line of the report
|
||||
(`verdict` with `--json`).
|
||||
|
||||
```sh
|
||||
wordcraft-cli convert in.docx out.pdf --strict
|
||||
# wordcraft-cli: strict: 1 character cannot be drawn: U+2D30 (×3)
|
||||
# wordcraft-cli: strict: 1 picture(s) left out: word/media/image2.bin (header2.xml): unsupported format
|
||||
# error: strict: 1 character cannot be drawn: U+2D30 (×3)
|
||||
# error: strict: 1 picture(s) left out: word/media/image2.bin (header2.xml): unsupported format
|
||||
# {"schema":1,"strict":"failed","missing_glyphs":[{"cp":"U+2D30","count":3}],"missing_pictures":[{"part":"word/media/image2.bin","source_part":"word/header2.xml","reason":"unsupported_format"}],"truncated":false,"total_missing_glyphs":1,"total_missing_pictures":1,"glyphs_truncated":false,"pictures_truncated":false}
|
||||
```
|
||||
|
||||
@@ -206,14 +217,15 @@ Web: `cd apps/wordcraft-web && trunk serve`, then open <http://127.0.0.1:8771/?s
|
||||
WordCraft was designed to be driven by people *and* by AI agents.
|
||||
|
||||
```sh
|
||||
claude mcp add wordcraft -- wordcraft-cli mcp # headless documents
|
||||
# confine the agent to folders: wordcraft-cli mcp --automation-read-root DIR --automation-write-root DIR
|
||||
wordcraft --control 7981 & # or drive the running app…
|
||||
claude mcp add wordcraft-app -- wordcraft-cli mcp --connect 127.0.0.1:7981
|
||||
# headless documents; the agent reads only inside the first folder and writes only inside the second
|
||||
claude mcp add wordcraft -- wordcraft-cli mcp --automation-read-root DIR --automation-write-root DIR
|
||||
```
|
||||
|
||||
Both roots are required. Bridging an agent to the running app (`mcp --connect`) is refused until
|
||||
the app confines its control channel to the same roots (#3695).
|
||||
|
||||
Tools include `list_commands`, `execute`, `batch`, `type_text`, `select_text`, `inspect_document`,
|
||||
`render_page`, `save_document`, and, with a running app, `screenshot`, `click` and `key`. Agents
|
||||
`render_page` and `save_document`. Agents
|
||||
can check their work through `inspect_document` without screenshots. See [docs/mcp.md](docs/mcp.md)
|
||||
and the [control protocol](docs/control-protocol.md). Macros record any sequence of commands and
|
||||
play it back (`tools.recordMacro`, `tools.macros`).
|
||||
|
||||
+668
-610
File diff suppressed because one or more lines are too long
@@ -6,6 +6,9 @@ license.workspace = true
|
||||
publish = false
|
||||
description = "WordCraft command line: convert, inspect, render, run commands, MCP server"
|
||||
|
||||
[lib]
|
||||
path = "src/lib.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "wordcraft-cli"
|
||||
path = "src/main.rs"
|
||||
@@ -19,11 +22,17 @@ 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 }
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
//! Writes wordcraft-cli's shell completions ([`clap_complete`]: bash, zsh, fish, elvish,
|
||||
//! PowerShell) and man pages ([`clap_mangen`]: `wordcraft-cli.1` and one per subcommand, such as
|
||||
//! `wordcraft-cli-run.1`) into a directory. The Linux and FreeBSD packages ship them
|
||||
//! (see `packaging/`):
|
||||
//!
|
||||
//! ```sh
|
||||
//! cargo run -p wordcraft-cli --example man-and-completions -- <out-dir>
|
||||
//! ```
|
||||
|
||||
use std::path::Path;
|
||||
use std::process::ExitCode;
|
||||
|
||||
use clap::ValueEnum;
|
||||
use clap_complete::Shell;
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let mut args = std::env::args_os().skip(1);
|
||||
let (Some(dir), None) = (args.next(), args.next()) else {
|
||||
eprintln!("usage: man-and-completions <out-dir>");
|
||||
return ExitCode::from(2);
|
||||
};
|
||||
let dir = Path::new(&dir);
|
||||
match generate(dir) {
|
||||
Ok(()) => ExitCode::SUCCESS,
|
||||
Err(e) => {
|
||||
eprintln!("error: {}: {e}", dir.display());
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Also run by the tests.
|
||||
pub(crate) fn generate(dir: &Path) -> std::io::Result<()> {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
let mut cmd = wordcraft_cli::command();
|
||||
for &shell in Shell::value_variants() {
|
||||
clap_complete::generate_to(shell, &mut cmd, "wordcraft-cli", dir)?;
|
||||
}
|
||||
// A fresh command: `clap_complete::generate_to` built `cmd`, adding the `help` subcommand,
|
||||
// which `clap_mangen` would otherwise give pages of its own (`wordcraft-cli-help-convert.1`).
|
||||
clap_mangen::generate_to(wordcraft_cli::command(), dir)
|
||||
}
|
||||
@@ -0,0 +1,343 @@
|
||||
//! The command line as clap derive types (RFC-0018). Values arrive typed, so the commands never validate a string; what
|
||||
//! clap cannot say alone is a [`UsageError`], printed and exited like clap's own.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use clap::{ArgMatches, Args, CommandFactory, FromArgMatches, Parser, Subcommand, ValueEnum};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// The end of every subcommand's `--help`.
|
||||
const EXIT_STATUS: &str = "Exit status:\n 0 success\n 1 the command failed (for `convert --strict` and `render --strict`, a refusal; for `validate`, a verdict other than PASS)\n 2 usage error\n\nA process ended by a signal exits 128 + the signal number (130 for Ctrl-C), as in the shell.";
|
||||
|
||||
/// The top-level `--help` ends with the environment and the exit status.
|
||||
const TOP_NOTES: &str = "A password-protected Word file is opened with --password PASS, --password-file PATH or the WORDCRAFT_PASSWORD environment variable; a password given on the command line is readable by every other process, so the other two are better. A file opened with a password is written with it again, as the app does. Exports that cannot carry a password (pdf, html, txt) stay plain.\n\nPaper: documents created here, and HTML, Markdown and text files (which give no page size), use the system region's paper (A4, or Letter in the US and other Letter regions), read from LC_ALL / LC_PAPER / LANG or the platform. Set WORDCRAFT_REGION=en-US (or another tag) for the same output on every machine.\n\nEnvironment:\n WORDCRAFT_PASSWORD the password of a protected Word file, when neither --password nor --password-file is given\n WORDCRAFT_REGION the paper and region to use instead of the system's (a tag such as en-US)\n\nExit status:\n 0 success\n 1 the command failed (for `convert --strict` and `render --strict`, a refusal; for `validate`, a verdict other than PASS)\n 2 usage error\n\nA process ended by a signal exits 128 + the signal number (130 for Ctrl-C), as in the shell.";
|
||||
|
||||
/// WordCraft from the command line: convert, inspect, render, run commands, validate, serve MCP
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(name = "wordcraft-cli", version, propagate_version = true, arg_required_else_help = true, after_help = TOP_NOTES)]
|
||||
pub(crate) struct Cli {
|
||||
#[command(subcommand)]
|
||||
pub(crate) command: Command,
|
||||
}
|
||||
|
||||
#[derive(Subcommand, Debug)]
|
||||
pub(crate) enum Command {
|
||||
/// Convert between formats (docx, doc [read], pdf, odt, rtf, html, md, tex, txt, json, png, xml)
|
||||
///
|
||||
/// `--update-fields` refreshes unlocked fields before saving (if protection blocks updates, they are skipped with a
|
||||
/// warning). An .xml file is a Word XML Document (Flat OPC), or with `--format wordml2003` a Word 2003 XML Document.
|
||||
/// `--markup` (Print Markup) puts comments beside each page and tracked changes in pdf/png, and a comment list in
|
||||
/// html/md/txt. `--strict` (pdf or png output only) writes nothing and exits 1 if a character can't be drawn or a
|
||||
/// picture is missing or undecodable; the report is on stderr, with one JSON line.
|
||||
#[command(after_help = EXIT_STATUS)]
|
||||
Convert(ConvertArgs),
|
||||
/// Pages, words, paragraphs and properties (JSON)
|
||||
#[command(after_help = EXIT_STATUS)]
|
||||
Info(FileArgs),
|
||||
/// The plain text
|
||||
#[command(after_help = EXIT_STATUS)]
|
||||
Text(FileArgs),
|
||||
/// The document structure (JSON)
|
||||
#[command(after_help = EXIT_STATUS)]
|
||||
Inspect(FileArgs),
|
||||
/// Render one page to a PNG
|
||||
///
|
||||
/// `--strict` writes nothing and exits 1 if a character on the page can't be drawn or a picture is missing or
|
||||
/// undecodable (the report is on stderr, as for `convert --strict`).
|
||||
#[command(after_help = EXIT_STATUS)]
|
||||
Render(RenderArgs),
|
||||
/// Run commands headlessly, then save
|
||||
///
|
||||
/// `--script` runs a JSON file (`-` is stdin) first: {"file"?, "template"?, "commands": [{"command": id, "params"?:
|
||||
/// {…}} | id, …], "save"?: [OUT, …]}; save formats follow the extension (docx and pdf in one run); relative paths
|
||||
/// resolve against the script's folder. `file.new` and `file.open` open another document and make it active; later
|
||||
/// commands and the saves work on the active one; `view.switchWindows` lists the open documents and with {"id": N}
|
||||
/// makes one active. PNG saves use `--page` (1-based, default 1) and `--scale` (default 2).
|
||||
#[command(after_help = EXIT_STATUS)]
|
||||
Run(RunArgs),
|
||||
/// List every command
|
||||
#[command(after_help = EXIT_STATUS)]
|
||||
Commands(JsonArgs),
|
||||
/// Feature-catalog parity
|
||||
#[command(after_help = EXIT_STATUS)]
|
||||
Parity(ParityArgs),
|
||||
/// Structural integrity check
|
||||
///
|
||||
/// Exit 0 for PASS; 1 for FAIL, INCOMPLETE or a file that can't be read (the verdict is the first line of the report,
|
||||
/// and `verdict` in `--json`).
|
||||
#[command(after_help = EXIT_STATUS)]
|
||||
Validate(ValidateArgs),
|
||||
/// MCP server on stdio, with a headless session
|
||||
///
|
||||
/// Both roots are required: the agent's commands read files (open, insert text or picture, mail-merge data,
|
||||
/// templates…) only inside the read root and write them (save, export, merge output…) only inside the write root,
|
||||
/// links followed; the same folder may be both. `--connect` (bridge to the running app) is refused until the app
|
||||
/// confines its control channel (#3695, #5819).
|
||||
#[command(after_help = EXIT_STATUS)]
|
||||
Mcp(McpArgs),
|
||||
/// Run a Zotero command on a document (Zotero must be running)
|
||||
///
|
||||
/// The commands are addEditCitation, addEditBibliography, addNote, refresh, removeCodes and setDocPrefs; `--cmd`
|
||||
/// runs first (for example `--cmd caret.docEnd`).
|
||||
#[command(after_help = EXIT_STATUS)]
|
||||
Zotero(ZoteroArgs),
|
||||
}
|
||||
|
||||
/// How a password-protected Word file is opened.
|
||||
#[derive(Args, Debug, Default)]
|
||||
pub(crate) struct Password {
|
||||
/// The password (readable by every other process on the machine; prefer --password-file)
|
||||
#[arg(long, value_name = "PASS", env = "WORDCRAFT_PASSWORD", hide_env_values = true)]
|
||||
pub(crate) password: Option<String>,
|
||||
/// Read the password from this file (a trailing newline is dropped)
|
||||
#[arg(long = "password-file", value_name = "PATH")]
|
||||
pub(crate) password_file: Option<PathBuf>,
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub(crate) struct FileArgs {
|
||||
/// The document
|
||||
pub(crate) file: PathBuf,
|
||||
#[command(flatten)]
|
||||
pub(crate) open: Password,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, ValueEnum)]
|
||||
pub(crate) enum XmlFormat {
|
||||
/// A Word 2003 XML Document
|
||||
Wordml2003,
|
||||
/// A Word XML Document (Flat OPC), the default
|
||||
Flatopc,
|
||||
}
|
||||
|
||||
impl XmlFormat {
|
||||
pub(crate) fn name(self) -> &'static str {
|
||||
match self {
|
||||
XmlFormat::Wordml2003 => "wordml2003",
|
||||
XmlFormat::Flatopc => "flatopc",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub(crate) struct ConvertArgs {
|
||||
/// The document to read
|
||||
pub(crate) input: PathBuf,
|
||||
/// The file to write; its extension names the format
|
||||
pub(crate) output: PathBuf,
|
||||
/// Print Markup: comments beside each page and tracked changes
|
||||
#[arg(long)]
|
||||
pub(crate) markup: bool,
|
||||
/// Refresh unlocked fields before saving
|
||||
#[arg(long = "update-fields")]
|
||||
pub(crate) update_fields: bool,
|
||||
/// For pdf or png output: write nothing and fail if a character can't be drawn or a picture is missing
|
||||
#[arg(long)]
|
||||
pub(crate) strict: bool,
|
||||
/// The kind of .xml file to write
|
||||
#[arg(long, value_enum, value_name = "KIND")]
|
||||
pub(crate) format: Option<XmlFormat>,
|
||||
#[command(flatten)]
|
||||
pub(crate) open: Password,
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub(crate) struct RenderArgs {
|
||||
/// The document
|
||||
pub(crate) input: PathBuf,
|
||||
/// The PNG to write
|
||||
pub(crate) output: PathBuf,
|
||||
/// The page, from 1
|
||||
#[arg(long, value_name = "N", value_parser = page, default_value = "1")]
|
||||
pub(crate) page: u64,
|
||||
/// Device pixels per point
|
||||
#[arg(long, value_name = "S", allow_negative_numbers = true, value_parser = scale, default_value = "2")]
|
||||
pub(crate) scale: f64,
|
||||
/// Write nothing and fail if a character can't be drawn or a picture is missing
|
||||
#[arg(long)]
|
||||
pub(crate) strict: bool,
|
||||
#[command(flatten)]
|
||||
pub(crate) open: Password,
|
||||
}
|
||||
|
||||
/// One `--cmd ID[=JSON]`.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct Cmd {
|
||||
pub(crate) id: String,
|
||||
pub(crate) params: Value,
|
||||
}
|
||||
|
||||
fn cmd(text: &str) -> Result<Cmd, UsageError> {
|
||||
match text.split_once('=') {
|
||||
Some((id, p)) => {
|
||||
let params = serde_json::from_str(p).map_err(|e| UsageError::CmdJson { id: id.to_owned(), why: e.to_string() })?;
|
||||
Ok(Cmd { id: id.to_owned(), params })
|
||||
}
|
||||
None => Ok(Cmd { id: text.to_owned(), params: json!({}) }),
|
||||
}
|
||||
}
|
||||
|
||||
fn page(text: &str) -> Result<u64, UsageError> {
|
||||
match text.parse::<u64>() {
|
||||
Ok(0) => Err(UsageError::Page("invalid --page `0`: page numbers start at 1".to_owned())),
|
||||
Ok(n) => Ok(n),
|
||||
Err(_) => Err(UsageError::Page(format!("invalid --page `{text}`: not a valid integer"))),
|
||||
}
|
||||
}
|
||||
|
||||
fn scale(text: &str) -> Result<f64, UsageError> {
|
||||
let n = text.parse::<f64>().map_err(|_| UsageError::Scale(format!("invalid --scale `{text}`: not a number")))?;
|
||||
if n.is_finite() && n > 0.0 { Ok(n) } else { Err(UsageError::Scale(format!("invalid --scale `{text}`: scale must be a finite positive number"))) }
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub(crate) struct RunArgs {
|
||||
/// Open this document first
|
||||
#[arg(long, value_name = "F", conflicts_with = "template")]
|
||||
pub(crate) file: Option<PathBuf>,
|
||||
/// Start from this template
|
||||
#[arg(long, value_name = "T")]
|
||||
pub(crate) template: Option<String>,
|
||||
/// A script to run first (`-` is stdin)
|
||||
#[arg(long, value_name = "FILE")]
|
||||
pub(crate) script: Option<PathBuf>,
|
||||
/// Run one command, `ID` or `ID={json}`; repeatable
|
||||
#[arg(long = "cmd", value_name = "ID={JSON}", value_parser = cmd)]
|
||||
pub(crate) cmds: Vec<Cmd>,
|
||||
/// Save the result here (the extension names the format)
|
||||
#[arg(long, value_name = "OUT")]
|
||||
pub(crate) save: Option<PathBuf>,
|
||||
/// The page of a PNG save, from 1 (default 1)
|
||||
#[arg(long, value_name = "N", value_parser = page)]
|
||||
pub(crate) page: Option<u64>,
|
||||
/// The scale of a PNG save (default 2)
|
||||
#[arg(long, value_name = "S", allow_negative_numbers = true, value_parser = scale)]
|
||||
pub(crate) scale: Option<f64>,
|
||||
/// Print each command's result
|
||||
#[arg(long)]
|
||||
pub(crate) print: bool,
|
||||
/// Who tracked changes and comments are by
|
||||
#[arg(long, value_name = "NAME")]
|
||||
pub(crate) author: Option<String>,
|
||||
#[command(flatten)]
|
||||
pub(crate) open: Password,
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub(crate) struct JsonArgs {
|
||||
/// JSON alone on stdout
|
||||
#[arg(long)]
|
||||
pub(crate) json: bool,
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub(crate) struct ParityArgs {
|
||||
/// Markdown instead of JSON
|
||||
#[arg(long)]
|
||||
pub(crate) markdown: bool,
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub(crate) struct ValidateArgs {
|
||||
/// The document
|
||||
pub(crate) file: PathBuf,
|
||||
/// JSON alone on stdout
|
||||
#[arg(long)]
|
||||
pub(crate) json: bool,
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub(crate) struct McpArgs {
|
||||
/// The folder the agent may read in (links followed); the same folder may be the write root
|
||||
#[arg(long = "automation-read-root", value_name = "DIR", required_unless_present = "connect", value_parser = folder)]
|
||||
pub(crate) read_root: Option<PathBuf>,
|
||||
/// The folder the agent may write in (links followed)
|
||||
#[arg(long = "automation-write-root", value_name = "DIR", required_unless_present = "connect", value_parser = folder)]
|
||||
pub(crate) write_root: Option<PathBuf>,
|
||||
/// Who tracked changes and comments are by
|
||||
#[arg(long, value_name = "NAME")]
|
||||
pub(crate) author: Option<String>,
|
||||
/// Refused for now: the desktop app does not confine its control channel to automation roots yet
|
||||
#[arg(long, value_name = "HOST:PORT")]
|
||||
pub(crate) connect: Option<String>,
|
||||
}
|
||||
|
||||
fn folder(text: &str) -> Result<PathBuf, UsageError> {
|
||||
if text.is_empty() { Err(UsageError::EmptyFolder) } else { Ok(PathBuf::from(text)) }
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub(crate) struct ZoteroArgs {
|
||||
/// The Zotero command (addEditCitation, addEditBibliography, addNote, refresh, removeCodes or setDocPrefs)
|
||||
#[arg(value_parser = zotero_command)]
|
||||
pub(crate) command: String,
|
||||
/// The document
|
||||
pub(crate) file: PathBuf,
|
||||
/// Run one command first, `ID` or `ID={json}`; repeatable
|
||||
#[arg(long = "cmd", value_name = "ID={JSON}", value_parser = cmd)]
|
||||
pub(crate) cmds: Vec<Cmd>,
|
||||
/// Save the document here afterwards
|
||||
#[arg(long, value_name = "OUT")]
|
||||
pub(crate) save: Option<PathBuf>,
|
||||
/// Show the calls to and from Zotero on stderr
|
||||
#[arg(long)]
|
||||
pub(crate) trace: bool,
|
||||
/// Zotero's port
|
||||
#[arg(long, value_name = "P")]
|
||||
pub(crate) port: Option<u16>,
|
||||
}
|
||||
|
||||
fn zotero_command(text: &str) -> Result<String, UsageError> {
|
||||
if wordcraft_zotero::Command::from_name(text).is_some() { Ok(text.to_owned()) } else { Err(UsageError::Zotero(text.to_owned())) }
|
||||
}
|
||||
|
||||
/// A mistake in the command line that clap can't see by itself.
|
||||
#[derive(Debug, PartialEq, thiserror::Error)]
|
||||
pub(crate) enum UsageError {
|
||||
#[error("{0}")]
|
||||
Page(String),
|
||||
#[error("{0}")]
|
||||
Scale(String),
|
||||
#[error("--cmd {id}: bad JSON params: {why}")]
|
||||
CmdJson { id: String, why: String },
|
||||
#[error("a folder is needed, not an empty name")]
|
||||
EmptyFolder,
|
||||
#[error("unknown Zotero command `{0}` (addEditCitation, addEditBibliography, addNote, refresh, removeCodes or setDocPrefs)")]
|
||||
Zotero(String),
|
||||
}
|
||||
|
||||
/// The clap definition of the whole command line (completions and man pages are generated from it).
|
||||
pub fn command() -> clap::Command {
|
||||
Cli::command()
|
||||
}
|
||||
|
||||
/// Parse the arguments (without the program name). Help and the version come back as the `Err` clap uses for them.
|
||||
pub(crate) fn parse(args: &[OsString]) -> Result<Cli, clap::Error> {
|
||||
let matches = Cli::command().try_get_matches_from(std::iter::once(OsString::from("wordcraft-cli")).chain(args.iter().cloned()))?;
|
||||
let mut cli = Cli::from_arg_matches(&matches)?;
|
||||
if let Some((name, sub)) = matches.subcommand() {
|
||||
password_precedence(&mut cli.command, sub, name);
|
||||
}
|
||||
Ok(cli)
|
||||
}
|
||||
|
||||
/// `--password`, `--password-file`, then `WORDCRAFT_PASSWORD`: a password file named on the command line beats the
|
||||
/// variable, which clap would otherwise read into `--password`.
|
||||
fn password_precedence(command: &mut Command, sub: &ArgMatches, _name: &str) {
|
||||
let open = match command {
|
||||
Command::Convert(a) => &mut a.open,
|
||||
Command::Info(a) | Command::Text(a) | Command::Inspect(a) => &mut a.open,
|
||||
Command::Render(a) => &mut a.open,
|
||||
Command::Run(a) => &mut a.open,
|
||||
_ => return,
|
||||
};
|
||||
let from_env = sub.value_source("password") == Some(clap::parser::ValueSource::EnvVariable);
|
||||
if from_env && open.password_file.is_some() {
|
||||
open.password = None;
|
||||
}
|
||||
// A blank variable counts as unset.
|
||||
if from_env && open.password.as_deref() == Some("") {
|
||||
open.password = None;
|
||||
}
|
||||
}
|
||||
@@ -1,90 +0,0 @@
|
||||
//! Parse `--automation-read-root` / `--automation-write-root` before the server starts. A malformed
|
||||
//! flag must not silently remove a root and leave the server unconfined.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub struct AutomationArgs {
|
||||
pub read_root: Option<PathBuf>,
|
||||
pub write_root: Option<PathBuf>,
|
||||
read_given: bool,
|
||||
write_given: bool,
|
||||
}
|
||||
|
||||
impl AutomationArgs {
|
||||
pub fn new(read_root: Option<PathBuf>, write_root: Option<PathBuf>) -> Self {
|
||||
Self { read_root, write_root, read_given: false, write_given: false }
|
||||
}
|
||||
|
||||
/// Returns whether this argument is a root flag. A second occurrence of a flag is an error,
|
||||
/// including when the two spellings (`--flag DIR`, `--flag=DIR`) are mixed.
|
||||
pub fn consume(&mut self, arg: &str, args: &mut impl Iterator<Item = String>) -> Result<bool, String> {
|
||||
let (flag, inline) = arg.split_once('=').map_or((arg, None), |(flag, value)| (flag, Some(value)));
|
||||
let (root, given) = match flag {
|
||||
"--automation-read-root" => (&mut self.read_root, &mut self.read_given),
|
||||
"--automation-write-root" => (&mut self.write_root, &mut self.write_given),
|
||||
_ => return Ok(false),
|
||||
};
|
||||
if *given {
|
||||
return Err(format!("{flag} given twice"));
|
||||
}
|
||||
let value = match inline {
|
||||
Some(value) => value.to_owned(),
|
||||
None => {
|
||||
let value = args.next().ok_or_else(|| format!("{flag} needs a folder"))?;
|
||||
if value.starts_with('-') {
|
||||
return Err(format!("{flag} needs a folder; use {flag}=<dir> for a folder starting with '-'"));
|
||||
}
|
||||
value
|
||||
}
|
||||
};
|
||||
if value.is_empty() {
|
||||
return Err(format!("{flag} needs a non-empty folder"));
|
||||
}
|
||||
*root = Some(value.into());
|
||||
*given = true;
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn roots_are_taken_once_and_other_arguments_are_left() {
|
||||
let mut roots = AutomationArgs::new(None, None);
|
||||
let mut args = ["a folder".to_owned(), "report.docx".to_owned()].into_iter();
|
||||
assert!(roots.consume("--automation-read-root", &mut args).unwrap());
|
||||
assert!(roots.consume("--automation-write-root=out", &mut args).unwrap());
|
||||
assert!(!roots.consume("--author", &mut args).unwrap());
|
||||
assert_eq!(roots.read_root, Some("a folder".into()));
|
||||
assert_eq!(roots.write_root, Some("out".into()));
|
||||
assert_eq!(args.next().as_deref(), Some("report.docx"));
|
||||
assert!(roots.consume("--automation-read-root=other", &mut args).is_err());
|
||||
assert_eq!(roots.read_root, Some("a folder".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_operands_leave_roots_unchanged() {
|
||||
for flag in ["--automation-read-root", "--automation-write-root"] {
|
||||
for operand in [None, Some(""), Some("--version"), Some("--connect"), Some("-folder")] {
|
||||
let mut roots = AutomationArgs::new(Some("read".into()), Some("write".into()));
|
||||
let mut args = operand.map(str::to_owned).into_iter();
|
||||
assert!(roots.consume(flag, &mut args).is_err(), "{flag} {operand:?}");
|
||||
assert_eq!(roots.read_root, Some("read".into()));
|
||||
assert_eq!(roots.write_root, Some("write".into()));
|
||||
}
|
||||
let mut roots = AutomationArgs::new(None, None);
|
||||
assert!(roots.consume(&format!("{flag}="), &mut std::iter::empty()).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_dash_folder_and_relative_dash_folder_are_valid() {
|
||||
let mut roots = AutomationArgs::new(None, None);
|
||||
assert!(roots.consume("--automation-read-root=-folder", &mut std::iter::empty()).unwrap());
|
||||
assert!(roots.consume("--automation-write-root", &mut ["./-folder".to_owned()].into_iter()).unwrap());
|
||||
assert_eq!(roots.read_root, Some("-folder".into()));
|
||||
assert_eq!(roots.write_root, Some("./-folder".into()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,609 @@
|
||||
//! The subcommands: each takes its parsed arguments and the output streams, and returns the exit status.
|
||||
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use wordcraft_engine::{CmdError, Session};
|
||||
|
||||
use crate::args::{self, Command, ConvertArgs, FileArgs, JsonArgs, McpArgs, ParityArgs, Password, RenderArgs, RunArgs, ValidateArgs, ZoteroArgs};
|
||||
use crate::error::CliError;
|
||||
use crate::script;
|
||||
use crate::{Io, errln};
|
||||
|
||||
type Result<T> = std::result::Result<T, CliError>;
|
||||
|
||||
fn engine_error(e: impl std::fmt::Display) -> CliError {
|
||||
CliError::Failed(escape_text(&e.to_string(), false))
|
||||
}
|
||||
|
||||
/// Open a document for a subcommand. A password-protected Word file needs its password
|
||||
/// ([`password_from`]). As in the app, a document opened with one is saved with it again, so
|
||||
/// `convert` does not quietly write a copy the password no longer protects.
|
||||
fn open(path: &Path, password: Option<&str>) -> Result<Session> {
|
||||
// A file that gives no page size (HTML, Markdown, plain text) opens on the system region's
|
||||
// paper, as in the app: A4 in Italy, Letter in the US (#1381).
|
||||
let region = system_region();
|
||||
let (doc, encrypted) = wordcraft_engine::io::open_path_in(path, password, ®ion).map_err(engine_error)?;
|
||||
let mut s = session(doc);
|
||||
s.path = Some(path.into());
|
||||
if encrypted {
|
||||
s.password = password.map(wordcraft_engine::io::Password::new);
|
||||
}
|
||||
Ok(s)
|
||||
}
|
||||
|
||||
/// The password for a protected Word file: `--password`, `--password-file` or `WORDCRAFT_PASSWORD` (clap reads the
|
||||
/// variable into `--password`; a blank one counts as unset). The file form exists because a password on a command line
|
||||
/// is readable by every other process on the machine; a trailing newline is dropped so a file written by `echo` works.
|
||||
/// Never logged, and never named in an error.
|
||||
pub(crate) fn password_from(open: &Password) -> Result<Option<String>> {
|
||||
if let Some(password) = &open.password {
|
||||
return Ok(Some(password.clone()));
|
||||
}
|
||||
if let Some(path) = &open.password_file {
|
||||
let raw =
|
||||
std::fs::read_to_string(path).map_err(|e| CliError::Failed(escape_text(&format!("--password-file {}: {e}", path.display()), false)))?;
|
||||
return Ok(Some(raw.trim_end_matches(['\r', '\n']).to_string()));
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// A path the engine takes as text: output paths must be valid Unicode (only the opened file may not be, #1440).
|
||||
fn unicode(path: &Path) -> Result<&str> {
|
||||
path.to_str().ok_or_else(|| CliError::Failed(format!("{}: the file name is not valid Unicode", path.display().to_string().escape_debug())))
|
||||
}
|
||||
|
||||
/// A headless session in the system region: every way the CLI starts one gives `file.new` the
|
||||
/// same paper (#1381).
|
||||
fn session(doc: wordcraft_doc::Document) -> Session {
|
||||
let mut s = Session::new(doc);
|
||||
s.system_region = system_region();
|
||||
s
|
||||
}
|
||||
|
||||
/// The system region, read as the app reads it (locale variables, else the platform's locale).
|
||||
fn system_region() -> wordcraft_engine::Region {
|
||||
wordcraft_engine::Region::from_locale_vars(|name| std::env::var(name).ok(), sys_locale::get_locale)
|
||||
}
|
||||
|
||||
/// The body text for `text`: the plain-text export, so list items keep their bullet or number label.
|
||||
fn listed_text(doc: &wordcraft_doc::Document) -> std::result::Result<String, String> {
|
||||
let bytes = wordcraft_engine::io::save_bytes("out.txt", doc)?;
|
||||
Ok(String::from_utf8_lossy(&bytes).replace("\r\n", "\n"))
|
||||
}
|
||||
|
||||
/// `--author NAME`: the author recorded on tracked changes and comments (`file.setAuthor`).
|
||||
/// The command also checks whether the open document is protected: this name determines which
|
||||
/// named editing exceptions the session can use, so the flag must not bypass that check.
|
||||
fn set_author(s: &mut Session, name: &str) -> std::result::Result<(), String> {
|
||||
s.run("file.setAuthor", &json!({"name": name})).map(|_| ()).map_err(|e| escape_text(&format!("--author: {e}"), false))
|
||||
}
|
||||
|
||||
/// `mcp`'s headless backend: a session confined to `roots`, its author `author` when given. The caller confines the
|
||||
/// process to the same roots first (`confine_process`), which a test must not do.
|
||||
fn headless_mcp(
|
||||
roots: std::sync::Arc<wordcraft_engine::file_access::AutomationRoots>,
|
||||
author: Option<&str>,
|
||||
) -> std::result::Result<wordcraft_mcp::Headless, String> {
|
||||
let mut headless = wordcraft_mcp::Headless::default().with_automation_roots(Some(roots));
|
||||
if let Some(name) = author {
|
||||
set_author(&mut headless.session, name)?;
|
||||
}
|
||||
Ok(headless)
|
||||
}
|
||||
|
||||
/// A failed `--strict` export: a strict refusal becomes [`CliError::Strict`] carrying what stderr
|
||||
/// shows (each line of the report as `error: …`, then its JSON on one line, from
|
||||
/// `file.strictReport` for `page` of a page image, else the PDF); any other error is an ordinary
|
||||
/// failure.
|
||||
fn refusal(s: &mut Session, e: wordcraft_engine::CmdError, markup: bool, page: Option<u64>) -> CliError {
|
||||
if !matches!(&e, wordcraft_engine::CmdError::Failed(m) if m.starts_with("strict: ")) {
|
||||
return engine_error(e);
|
||||
}
|
||||
let mut params = json!({"markup": markup});
|
||||
if let Some(page) = page {
|
||||
params["page"] = json!(page);
|
||||
}
|
||||
CliError::Strict(match s.run("file.strictReport", ¶ms).map_err(|e| e.to_string()) {
|
||||
Ok(json) => {
|
||||
let mut text = String::new();
|
||||
for line in report_lines(&json) {
|
||||
text += &format!("error: {}\n", escape_peer(&line));
|
||||
}
|
||||
text + &json_line_safe(&json.to_string())
|
||||
}
|
||||
Err(e) => format!("error: strict: refused, and the report could not be made: {}", escape_text(&e, false)),
|
||||
})
|
||||
}
|
||||
|
||||
/// The report's human lines, from its JSON (the engine's `StrictReport::lines`).
|
||||
fn report_lines(json: &Value) -> Vec<String> {
|
||||
wordcraft_engine::strict::lines_from_json(json)
|
||||
}
|
||||
|
||||
/// Explicitly update unlocked fields in a session before saving the document.
|
||||
///
|
||||
/// If field updates are disabled by document protection (`CmdError::Disabled`), logs a warning to
|
||||
/// stderr and continues conversion rather than aborting. Other command failures are converted to
|
||||
/// [`CliError`] via [`engine_error`].
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `s` - The active document [`Session`] whose unlocked fields should be refreshed.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns `Err(CliError)` if the command fails with an error other than `CmdError::Disabled`.
|
||||
fn update_fields(s: &mut Session, io: &mut Io) -> Result<()> {
|
||||
if let Err(e) = s.run("references.updateFields", &json!({})) {
|
||||
if matches!(e, CmdError::Disabled(_)) {
|
||||
errln!(io, "warning: {e}");
|
||||
} else {
|
||||
return Err(engine_error(e));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// At most 400 characters of `s`, for traces.
|
||||
fn clip(s: &str) -> String {
|
||||
match s.char_indices().nth(400) {
|
||||
Some((i, _)) => format!("{}…", s.get(..i).unwrap_or(s)),
|
||||
None => s.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Text from another program (Zotero, or whatever answered on its port) for one diagnostic
|
||||
/// line: backslashes, control characters (newline, escape, C1…), line separators and bidi
|
||||
/// overrides are shown as escapes (`\\`, `\n`, `\u{1b}`), so it can't end its line, drive the
|
||||
/// terminal or pass for other output.
|
||||
fn escape_peer(s: &str) -> String {
|
||||
escape_text(s, true)
|
||||
}
|
||||
|
||||
/// Whether `c` must not reach a terminal as itself: a control character, a line or paragraph
|
||||
/// separator, a bidi control, or one that shows nothing (soft hyphen, zero-width characters, word
|
||||
/// joiners, the byte order mark, tag characters), which can hide or reorder what a line says.
|
||||
fn is_unsafe_char(c: char) -> bool {
|
||||
c.is_control()
|
||||
|| matches!(
|
||||
c,
|
||||
'\u{00ad}'
|
||||
| '\u{061c}'
|
||||
| '\u{200b}'..='\u{200f}'
|
||||
| '\u{2028}'..='\u{202e}'
|
||||
| '\u{2060}'..='\u{2064}'
|
||||
| '\u{2066}'..='\u{2069}'
|
||||
| '\u{feff}'
|
||||
| '\u{e0000}'..='\u{e007f}'
|
||||
)
|
||||
}
|
||||
|
||||
/// [`escape_peer`], with backslashes escaped only when `backslash` (error messages quote Windows
|
||||
/// paths, and a backslash can't forge or hide anything).
|
||||
fn escape_text(s: &str, backslash: bool) -> String {
|
||||
let mut out = String::with_capacity(s.len());
|
||||
for c in s.chars() {
|
||||
match c {
|
||||
'\\' if backslash => out.push_str("\\\\"),
|
||||
'\n' => out.push_str("\\n"),
|
||||
'\r' => out.push_str("\\r"),
|
||||
'\t' => out.push_str("\\t"),
|
||||
c if is_unsafe_char(c) => out.extend(c.escape_unicode()),
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A JSON line safe to print: serde escapes control characters below U+0020 but not the other
|
||||
/// characters [`is_unsafe_char`] names, which a crafted file could put in a report. They become
|
||||
/// `\uXXXX` escapes (a surrogate pair above U+FFFF), so the line parses to the same value and
|
||||
/// can't drive or spoof a terminal.
|
||||
fn json_line_safe(json: &str) -> String {
|
||||
let mut out = String::with_capacity(json.len());
|
||||
for c in json.chars() {
|
||||
if is_unsafe_char(c) {
|
||||
for unit in c.encode_utf16(&mut [0u16; 2]) {
|
||||
out.push_str(&format!("\\u{unit:04x}"));
|
||||
}
|
||||
} else {
|
||||
out.push(c);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn parity_markdown(p: &Value) -> String {
|
||||
let mut s = String::from(
|
||||
"# WordCraft feature parity\n\nGenerated by `cargo xtask parity` (`wordcraft-cli parity --markdown`): the word-processor feature catalog (`crates/engine/src/catalog.rs`) compared with the live command registry.\n\n",
|
||||
);
|
||||
s += &format!(
|
||||
"**{} of {} catalog features have commands ({}%).**\n\n| Tab | Live | Total |\n|---|---|---|\n",
|
||||
p["live"], p["total"], p["percent"]
|
||||
);
|
||||
for t in p["tabs"].as_array().cloned().unwrap_or_default() {
|
||||
s += &format!("| {} | {} | {} |\n", t["tab"].as_str().unwrap_or(""), t["live"], t["total"]);
|
||||
}
|
||||
s += "\n## Missing\n\n";
|
||||
for t in p["tabs"].as_array().cloned().unwrap_or_default() {
|
||||
let m = t["missing"].as_array().cloned().unwrap_or_default();
|
||||
if m.is_empty() {
|
||||
continue;
|
||||
}
|
||||
s += &format!("### {}\n\n", t["tab"].as_str().unwrap_or(""));
|
||||
for x in m {
|
||||
s += &format!("- {}\n", x.as_str().unwrap_or(""));
|
||||
}
|
||||
s += "\n";
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// Write a `validate` report for people: the verdict, then one line per finding
|
||||
/// (`SEVERITY RULE [part] message`), then the coverage notes.
|
||||
fn write_validate_report(o: &mut dyn Write, report: &wordcraft_validate::Report) -> std::io::Result<()> {
|
||||
o.write_all(render_validate_report(report).as_bytes())
|
||||
}
|
||||
|
||||
/// Render a `validate` report for people. Document-controlled text — a ZIP entry name flowing into
|
||||
/// a finding part or coverage note — is escaped so a name cannot end its line or drive the
|
||||
/// terminal; printable text, including Unicode, is left as written.
|
||||
///
|
||||
/// The `--json` form is not escaped by hand; it is the validator's own `serde_json` serialization.
|
||||
/// `serde_json` escapes `U+0000`–`U+001F`, `"` and `\`; C1 controls such as `U+009B` and the bidi
|
||||
/// embeddings/overrides (`U+202A`–`U+202E`, `U+2066`–`U+2069`) are emitted raw. So a control or bidi
|
||||
/// run carried by a ZIP entry name survives into the JSON text; JSON is only safe because a
|
||||
/// *parser* takes the string value as data. If that text is printed directly to a terminal, the raw
|
||||
/// C1/bidi run reaches the terminal exactly as it would from any other text, so the JSON form is
|
||||
/// not a terminal-safe rendering. Only the human report below escapes those characters, and it does
|
||||
/// so to defend the terminal; keeping the JSON byte-for-byte the validator's own serialization is
|
||||
/// why its escaping is left to `serde_json`.
|
||||
fn render_validate_report(report: &wordcraft_validate::Report) -> String {
|
||||
let mut out = format!("{}\n", verdict_label(report.verdict));
|
||||
for f in &report.findings {
|
||||
let severity = severity_label(f.severity);
|
||||
match &f.part {
|
||||
Some(part) => out.push_str(&format!("{severity} {} [{}] {}\n", f.rule, escape_report_text(part), escape_report_text(&f.message))),
|
||||
None => out.push_str(&format!("{severity} {} {}\n", f.rule, escape_report_text(&f.message))),
|
||||
}
|
||||
}
|
||||
for note in &report.coverage_notes {
|
||||
out.push_str(&format!("note: {}\n", escape_report_text(note)));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Escape the control and invisible-formatting characters that could spoof a report line, in the
|
||||
/// same escape *form* `escape_debug` uses (`\u{1b}`, `\n`); printable characters (including Unicode)
|
||||
/// are left untouched. The *selection* is a hand-picked set ([`is_invisible_format`] plus
|
||||
/// `char::is_control`), not `escape_debug`'s full non-printable set: it omits, for example, the
|
||||
/// U+E0000 tag block, U+FFF9–U+FFFB and the Hangul fillers. None of those can end a line or drive a
|
||||
/// terminal, which is the threat this guards against. Backslash is not escaped, so a name that
|
||||
/// literally contains the text `\u{1b}` prints exactly like an escaped ESC and the output is not
|
||||
/// injective.
|
||||
fn escape_report_text(s: &str) -> String {
|
||||
let mut out = String::with_capacity(s.len());
|
||||
for c in s.chars() {
|
||||
if c.is_control() || is_invisible_format(c) {
|
||||
out.extend(c.escape_debug());
|
||||
} else {
|
||||
out.push(c);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Invisible Unicode formatting characters and line/paragraph separators: no glyph, but they can
|
||||
/// alter how a terminal renders the rest of the line (`char::is_control` covers C0/C1 controls).
|
||||
fn is_invisible_format(c: char) -> bool {
|
||||
matches!(
|
||||
c,
|
||||
'\u{00ad}' | '\u{061c}' | '\u{180e}' | '\u{200b}'..='\u{200f}' | '\u{2028}'..='\u{202e}' | '\u{2060}'..='\u{206f}' | '\u{feff}'
|
||||
)
|
||||
}
|
||||
|
||||
/// Map a validation verdict enum to its human-readable uppercase display label.
|
||||
fn verdict_label(v: wordcraft_validate::Verdict) -> &'static str {
|
||||
match v {
|
||||
wordcraft_validate::Verdict::Pass => "PASS",
|
||||
wordcraft_validate::Verdict::Fail => "FAIL",
|
||||
wordcraft_validate::Verdict::Incomplete => "INCOMPLETE",
|
||||
}
|
||||
}
|
||||
|
||||
/// Map a validation severity enum to its human-readable uppercase display label.
|
||||
fn severity_label(s: wordcraft_validate::Severity) -> &'static str {
|
||||
match s {
|
||||
wordcraft_validate::Severity::Corrupt => "CORRUPT",
|
||||
wordcraft_validate::Severity::Error => "ERROR",
|
||||
wordcraft_validate::Severity::Warning => "WARNING",
|
||||
}
|
||||
}
|
||||
|
||||
/// Why `mcp --connect` is refused: the running app would not confine the agent's file access.
|
||||
// lean: refused outright; allow it once the app confines its control channel and reports both roots.
|
||||
const MCP_CONNECT_REFUSED: &str = "mcp: --connect is refused for now: the desktop app does not confine its control \
|
||||
channel to automation roots yet (storytold/wordcraft#3695, #5819). Use the headless server: wordcraft-cli mcp \
|
||||
--automation-read-root DIR --automation-write-root DIR";
|
||||
|
||||
/// Run one parsed subcommand; the result is the exit status.
|
||||
pub(crate) fn dispatch(command: Command, io: &mut Io) -> Result<u8> {
|
||||
match command {
|
||||
Command::Convert(a) => convert(a, io).map(|()| 0),
|
||||
Command::Info(a) => info(a, io).map(|()| 0),
|
||||
Command::Text(a) => text(a, io).map(|()| 0),
|
||||
Command::Inspect(a) => inspect(a, io).map(|()| 0),
|
||||
Command::Render(a) => render(a, io).map(|()| 0),
|
||||
Command::Run(a) => run_script(a, io).map(|()| 0),
|
||||
Command::Commands(a) => commands(a, io).map(|()| 0),
|
||||
Command::Parity(a) => parity(a, io).map(|()| 0),
|
||||
Command::Validate(a) => validate(a, io),
|
||||
Command::Mcp(a) => mcp(a, io).map(|()| 0),
|
||||
Command::Zotero(a) => zotero(a, io).map(|()| 0),
|
||||
}
|
||||
}
|
||||
|
||||
/// Write to stdout and flush. A closed stdout comes back as [`CliError::StdoutClosed`] instead of a panic.
|
||||
fn write_stdout(io: &mut Io, write: impl FnOnce(&mut dyn Write) -> std::io::Result<()>) -> Result<()> {
|
||||
write(&mut *io.out)?;
|
||||
io.out.flush()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn convert(a: ConvertArgs, io: &mut Io) -> Result<()> {
|
||||
let o = unicode(&a.output)?.to_owned();
|
||||
// Before the input is opened: a wrong output type is a usage error, not a file error.
|
||||
let to_png = o.to_ascii_lowercase().ends_with(".png");
|
||||
if a.strict && !(to_png || o.to_ascii_lowercase().ends_with(".pdf")) {
|
||||
return Err(CliError::Usage("convert: --strict needs a .pdf or .png output".into()));
|
||||
}
|
||||
let password = password_from(&a.open)?;
|
||||
let mut s = open(&a.input, password.as_deref())?;
|
||||
if a.update_fields {
|
||||
update_fields(&mut s, io)?;
|
||||
}
|
||||
let r = if to_png {
|
||||
s.run("file.exportPng", &json!({"path": o, "page": 1, "markup": a.markup, "strict": a.strict}))
|
||||
} else {
|
||||
let mut params = json!({"path": o, "markup": a.markup, "strict": a.strict});
|
||||
if let Some(f) = a.format {
|
||||
params["format"] = json!(f.name());
|
||||
}
|
||||
s.run("file.save", ¶ms)
|
||||
};
|
||||
if let Err(e) = r {
|
||||
return Err(if a.strict { refusal(&mut s, e, a.markup, to_png.then_some(1)) } else { engine_error(e) });
|
||||
}
|
||||
errln!(io, "wrote {o}");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn open_file(a: &FileArgs) -> Result<Session> {
|
||||
let password = password_from(&a.open)?;
|
||||
open(&a.file, password.as_deref())
|
||||
}
|
||||
|
||||
fn info(a: FileArgs, io: &mut Io) -> Result<()> {
|
||||
let mut s = open_file(&a)?;
|
||||
let info = serde_json::to_string_pretty(&s.run("file.info", &json!({})).map_err(engine_error)?).unwrap_or_default();
|
||||
write_stdout(io, |o| writeln!(o, "{info}"))
|
||||
}
|
||||
|
||||
fn text(a: FileArgs, io: &mut Io) -> Result<()> {
|
||||
let s = open_file(&a)?;
|
||||
let text = listed_text(&s.doc)?;
|
||||
write_stdout(io, |o| writeln!(o, "{text}"))
|
||||
}
|
||||
|
||||
fn inspect(a: FileArgs, io: &mut Io) -> Result<()> {
|
||||
let mut s = open_file(&a)?;
|
||||
let tree = serde_json::to_string_pretty(&s.run("document.inspect", &json!({})).map_err(engine_error)?).unwrap_or_default();
|
||||
write_stdout(io, |o| writeln!(o, "{tree}"))
|
||||
}
|
||||
|
||||
fn render(a: RenderArgs, io: &mut Io) -> Result<()> {
|
||||
let o = unicode(&a.output)?.to_owned();
|
||||
let password = password_from(&a.open)?;
|
||||
let mut s = open(&a.input, password.as_deref())?;
|
||||
let mut params = json!({"path": o, "page": a.page, "scale": a.scale, "strict": a.strict});
|
||||
if a.strict {
|
||||
// The check and its report must see the page as it is written.
|
||||
params["markup"] = json!(false);
|
||||
}
|
||||
let r = match s.run("file.exportPng", ¶ms) {
|
||||
Ok(r) => r,
|
||||
Err(e) if a.strict => return Err(refusal(&mut s, e, false, Some(a.page))),
|
||||
Err(e) => return Err(engine_error(e)),
|
||||
};
|
||||
write_stdout(io, |o| writeln!(o, "{r}"))
|
||||
}
|
||||
|
||||
fn load_run_script(path: Option<&Path>) -> Result<Option<script::Script>> {
|
||||
path.map(|p| script::load(p).map_err(engine_error)).transpose()
|
||||
}
|
||||
|
||||
fn run_script(a: RunArgs, io: &mut Io) -> Result<()> {
|
||||
let password = password_from(&a.open)?;
|
||||
let script = load_run_script(a.script.as_deref())?;
|
||||
// A source named on the command line wins over both of the script's.
|
||||
let (mut from_file, mut from_template) = (a.file.clone(), a.template.clone());
|
||||
if from_file.is_none() && from_template.is_none() {
|
||||
from_file = script.as_ref().and_then(|loaded| loaded.file.as_deref().map(std::path::PathBuf::from));
|
||||
from_template = script.as_ref().and_then(|loaded| loaded.template.clone());
|
||||
}
|
||||
let mut s = match (from_file, from_template) {
|
||||
(Some(f), _) => open(&f, password.as_deref())?,
|
||||
// Both go through `file.new`, which puts a blank document on the region's paper (#3152).
|
||||
// `file.new` opens beside the session's first document, which is then closed: the
|
||||
// run starts with one open document.
|
||||
(None, t) => {
|
||||
let mut s = session(wordcraft_doc::Document::new());
|
||||
let first = s.document_id();
|
||||
let params = t.map_or_else(|| json!({}), |t| json!({"template": t}));
|
||||
s.run("file.new", ¶ms).map_err(engine_error)?;
|
||||
s.close_document(first).map_err(engine_error)?;
|
||||
s
|
||||
}
|
||||
};
|
||||
if let Some(name) = &a.author {
|
||||
set_author(&mut s, name).map_err(CliError::Failed)?;
|
||||
}
|
||||
for (n, (id, params)) in script.iter().flat_map(|c| c.commands.iter()).enumerate() {
|
||||
let r = s.run(id, params).map_err(|e| engine_error(format!("command {} ({id}): {e}", n + 1)))?;
|
||||
if a.print {
|
||||
write_stdout(io, |o| writeln!(o, "{id}: {r}"))?;
|
||||
}
|
||||
}
|
||||
for args::Cmd { id, params } in &a.cmds {
|
||||
let r = s.run(id, params).map_err(|e| engine_error(format!("{id}: {e}")))?;
|
||||
if a.print {
|
||||
write_stdout(io, |o| writeln!(o, "{id}: {r}"))?;
|
||||
}
|
||||
}
|
||||
let mut outputs: Vec<String> = script.iter().flat_map(|c| c.save.iter().cloned()).collect();
|
||||
if let Some(save) = &a.save {
|
||||
outputs.push(unicode(save)?.to_owned());
|
||||
}
|
||||
// Check every output can be made before writing any, so a bad one leaves no half-done job.
|
||||
for out in &outputs {
|
||||
let parent = Path::new(out).parent().filter(|p| !p.as_os_str().is_empty());
|
||||
if let Some(p) = parent.filter(|p| !p.is_dir()) {
|
||||
return Err(format!("{out}: folder {} does not exist", p.display()).into());
|
||||
}
|
||||
if Path::new(out).is_dir() {
|
||||
return Err(format!("{out}: is a folder, not a file").into());
|
||||
}
|
||||
if !out.to_ascii_lowercase().ends_with(".png") {
|
||||
wordcraft_engine::io::save_bytes(out, &s.doc).map_err(engine_error)?;
|
||||
}
|
||||
}
|
||||
for out in outputs {
|
||||
let r = if out.to_ascii_lowercase().ends_with(".png") {
|
||||
let mut v = json!({"path": out});
|
||||
if let Some(n) = a.page {
|
||||
v["page"] = json!(n);
|
||||
}
|
||||
if let Some(k) = a.scale {
|
||||
v["scale"] = json!(k);
|
||||
}
|
||||
s.run("file.exportPng", &v)
|
||||
} else {
|
||||
s.run("file.save", &json!({"path": out}))
|
||||
};
|
||||
r.map_err(engine_error)?;
|
||||
errln!(io, "wrote {out}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn commands(a: JsonArgs, io: &mut Io) -> Result<()> {
|
||||
let s = session(wordcraft_doc::Document::new());
|
||||
if a.json {
|
||||
let list = serde_json::to_string_pretty(&s.registry.describe()).unwrap_or_default();
|
||||
write_stdout(io, |o| writeln!(o, "{list}"))
|
||||
} else {
|
||||
write_stdout(io, |o| {
|
||||
for c in s.registry.all() {
|
||||
writeln!(o, "{:<32} {:<36} {:<24} {}", c.id, c.label, c.shortcut, c.location)?;
|
||||
}
|
||||
writeln!(o, "{:<32} Structural integrity check", "validate")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn parity(a: ParityArgs, io: &mut Io) -> Result<()> {
|
||||
let s = session(wordcraft_doc::Document::new());
|
||||
let p = wordcraft_engine::catalog::parity(&s.registry);
|
||||
if a.markdown {
|
||||
write_stdout(io, |o| write!(o, "{}", parity_markdown(&p)))
|
||||
} else {
|
||||
write_stdout(io, |o| writeln!(o, "{}", serde_json::to_string_pretty(&p).unwrap_or_default()))
|
||||
}
|
||||
}
|
||||
|
||||
fn mcp(a: McpArgs, io: &mut Io) -> Result<()> {
|
||||
if a.connect.is_some() {
|
||||
return Err(MCP_CONNECT_REFUSED.into());
|
||||
}
|
||||
// Shared rule 18 (#7124): an agent entry point never runs unconfined. clap requires both roots.
|
||||
let roots = wordcraft_engine::file_access::AutomationRoots::new(a.read_root.as_deref(), a.write_root.as_deref())
|
||||
.map_err(|e| CliError::Failed(format!("mcp: {e}")))?;
|
||||
let Some(roots) = roots.filter(|r| r.read_root().is_some() && r.write_root().is_some()) else {
|
||||
return Err(CliError::Usage("mcp: give both --automation-read-root DIR and --automation-write-root DIR".into()));
|
||||
};
|
||||
// Every thread of this process, not only the server's: nothing reaches past the roots.
|
||||
wordcraft_engine::file_access::confine_process(roots.clone());
|
||||
let show = |root: Option<&Path>| root.map_or_else(|| "none".to_string(), |r| r.display().to_string());
|
||||
errln!(io, "files confined: read root {}, write root {}", show(roots.read_root()), show(roots.write_root()));
|
||||
let backend: Box<dyn wordcraft_mcp::Backend> = Box::new(headless_mcp(roots, a.author.as_deref()).map_err(CliError::Failed)?);
|
||||
let mut server = wordcraft_mcp::Server::new(backend);
|
||||
let stdin = std::io::stdin();
|
||||
// A client that closes our stdout has hung up: `serve` returns BrokenPipe and we end cleanly.
|
||||
Ok(server.serve(stdin.lock(), &mut *io.out)?)
|
||||
}
|
||||
|
||||
fn zotero(a: ZoteroArgs, io: &mut Io) -> Result<()> {
|
||||
let command =
|
||||
wordcraft_zotero::Command::from_name(&a.command).ok_or_else(|| CliError::Usage(format!("unknown Zotero command `{}`", a.command)))?;
|
||||
let mut s = open(&a.file, None)?;
|
||||
for args::Cmd { id, params } in &a.cmds {
|
||||
s.run(id, params).map_err(|e| engine_error(format!("{id}: {e}")))?;
|
||||
}
|
||||
let mut opts = wordcraft_zotero::client::Options::default();
|
||||
if let Some(p) = a.port {
|
||||
opts.addr.set_port(p);
|
||||
}
|
||||
let mut bridge = wordcraft_zotero::Bridge::new();
|
||||
let mut host = wordcraft_zotero::Headless::default();
|
||||
let mut trace = Vec::new();
|
||||
let out = wordcraft_zotero::client::run_command(&opts, command, &mut |call| {
|
||||
let r = bridge.handle(&mut s, &mut host, call);
|
||||
if a.trace {
|
||||
trace.push(format!("← {} {}", escape_peer(&call.method), escape_peer(&clip(&Value::Array(call.args.clone()).to_string()))));
|
||||
trace.push(format!("→ {}", escape_peer(&clip(&String::from_utf8_lossy(&wordcraft_zotero::wire::encode_reply(&r))))));
|
||||
}
|
||||
r
|
||||
})
|
||||
.map_err(engine_error)?;
|
||||
for line in &trace {
|
||||
errln!(io, "{line}");
|
||||
}
|
||||
for alert in &host.alerts {
|
||||
errln!(io, "Zotero: {}", escape_peer(alert));
|
||||
}
|
||||
errln!(io, "{} calls, {}", out.calls, if out.completed { "completed" } else { "ended without completing (cancelled?)" });
|
||||
if let Some(o) = &a.save {
|
||||
let o = unicode(o)?;
|
||||
s.run("file.save", &json!({"path": o})).map_err(engine_error)?;
|
||||
errln!(io, "wrote {o}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `validate`: 0 for PASS, 1 for any other verdict or a file that can't be read (RFC-0018 rule 1.2 has no other code;
|
||||
/// the verdict is in the report).
|
||||
fn validate(a: ValidateArgs, io: &mut Io) -> Result<u8> {
|
||||
let report =
|
||||
wordcraft_validate::validate_path(&a.file).map_err(|e| CliError::Failed(escape_text(&format!("{}: {e}", a.file.display()), false)))?;
|
||||
let written = if a.json {
|
||||
let json = serde_json::to_string_pretty(&report).unwrap_or_default();
|
||||
write_stdout(io, |o| writeln!(o, "{json}"))
|
||||
} else {
|
||||
write_stdout(io, |o| write_validate_report(o, &report))
|
||||
};
|
||||
match written {
|
||||
// A reader closing early must not turn a FAIL or INCOMPLETE verdict into PASS.
|
||||
Ok(()) | Err(CliError::StdoutClosed) => {}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
Ok(match report.verdict {
|
||||
wordcraft_validate::Verdict::Pass => 0,
|
||||
wordcraft_validate::Verdict::Fail | wordcraft_validate::Verdict::Incomplete => 1,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,37 @@
|
||||
//! What stops a command, and how each case exits.
|
||||
|
||||
/// Why a CLI run stopped early.
|
||||
#[derive(Debug, PartialEq, thiserror::Error)]
|
||||
pub enum CliError {
|
||||
/// The command failed (exit 1); the text is already safe to print.
|
||||
#[error("{0}")]
|
||||
Failed(String),
|
||||
/// A mistake in the command line found after parsing (exit 2).
|
||||
#[error("{0}")]
|
||||
Usage(String),
|
||||
/// A strict export refused (exit 1): the report's lines, then its JSON line, ready for stderr.
|
||||
#[error("{0}")]
|
||||
Strict(String),
|
||||
/// Whoever read stdout closed it (`wordcraft-cli commands --json | head`): nobody is left to write to, so a quiet
|
||||
/// exit 0 (`validate` keeps its verdict's status).
|
||||
#[error("stdout closed")]
|
||||
StdoutClosed,
|
||||
}
|
||||
|
||||
impl From<String> for CliError {
|
||||
fn from(e: String) -> Self {
|
||||
CliError::Failed(e)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&str> for CliError {
|
||||
fn from(e: &str) -> Self {
|
||||
CliError::Failed(e.into())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<std::io::Error> for CliError {
|
||||
fn from(e: std::io::Error) -> Self {
|
||||
if e.kind() == std::io::ErrorKind::BrokenPipe { CliError::StdoutClosed } else { CliError::Failed(e.to_string()) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
//! Headless WordCraft (`wordcraft-cli`). [`run`] is the whole program, so it can be tested in-process as well as
|
||||
//! through the binary; `wordcraft-cli --help` lists the subcommands. The conventions are RFC-0018's: exit 0, 1 (a
|
||||
//! command failed) or 2 (a usage error), results on stdout, `error: <message>` on stderr.
|
||||
|
||||
mod args;
|
||||
mod commands;
|
||||
mod error;
|
||||
mod script;
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::io::Write;
|
||||
|
||||
use error::CliError;
|
||||
|
||||
pub use args::command;
|
||||
|
||||
/// Where a command writes: results to `out`, diagnostics and progress to `err`.
|
||||
pub(crate) struct Io<'a> {
|
||||
pub(crate) out: &'a mut dyn Write,
|
||||
pub(crate) err: &'a mut dyn Write,
|
||||
}
|
||||
|
||||
/// Writes a line of progress or a warning; a closed stderr is not worth an error.
|
||||
macro_rules! errln {
|
||||
($io:expr, $($arg:tt)*) => {
|
||||
drop(writeln!($io.err, $($arg)*))
|
||||
};
|
||||
}
|
||||
|
||||
pub(crate) use errln;
|
||||
|
||||
/// The Launcher's Nightly bootstrap belongs to the desktop app: a CLI must not accept it, in the
|
||||
/// separate-token or `=` form, so a mis-routed launch fails loudly instead of editing stable data.
|
||||
fn launcher_profile_flag(args: &[OsString]) -> bool {
|
||||
args.iter().any(|arg| {
|
||||
let arg = arg.to_string_lossy();
|
||||
arg == "--launch-profile" || arg == "--profile-root" || arg.starts_with("--launch-profile=") || arg.starts_with("--profile-root=")
|
||||
})
|
||||
}
|
||||
|
||||
/// Run the CLI on its arguments (without the program name), writing results to `out` and diagnostics to `err`.
|
||||
/// Returns the process exit code: 0 on success, 1 when a command failed, 2 for a usage error. Help and the version go
|
||||
/// to `out`, exit 0.
|
||||
pub fn run<I, T>(args: I, out: &mut dyn Write, err: &mut dyn Write) -> i32
|
||||
where
|
||||
I: IntoIterator<Item = T>,
|
||||
T: Into<OsString>,
|
||||
{
|
||||
let args: Vec<OsString> = args.into_iter().map(Into::into).collect();
|
||||
if launcher_profile_flag(&args) {
|
||||
let _ = writeln!(err, "error: --launch-profile and --profile-root are the desktop app's Nightly bootstrap, not a CLI option");
|
||||
return 2;
|
||||
}
|
||||
// Help and the version (`help`, `-h`, `<subcommand> --help`, `-V`) come back as errors too.
|
||||
let cli = match args::parse(&args) {
|
||||
Ok(cli) => cli,
|
||||
Err(e) => {
|
||||
let to: &mut dyn Write = if e.use_stderr() { err } else { out };
|
||||
let _ = write!(to, "{}", e.render());
|
||||
return e.exit_code();
|
||||
}
|
||||
};
|
||||
let mut io = Io { out, err };
|
||||
// Language packs installed in the suite's font store are used; `proof.installPack` installs
|
||||
// only while the person has turned downloading on in the app.
|
||||
wordcraft_engine::packs::use_font_store(false);
|
||||
if let Some(source) = wordcraft_engine::packs::index_override() {
|
||||
errln!(io, "Language packs come from a test source: {source}");
|
||||
}
|
||||
match commands::dispatch(cli.command, &mut io) {
|
||||
Ok(code) => i32::from(code),
|
||||
// A reader that stopped early (a closed pipe) ends the program quietly, as ripgrep does.
|
||||
Err(CliError::StdoutClosed) => 0,
|
||||
Err(CliError::Usage(e)) => {
|
||||
errln!(io, "error: {e}");
|
||||
2
|
||||
}
|
||||
// The report's lines already start with `error:`.
|
||||
Err(CliError::Strict(report)) => {
|
||||
errln!(io, "{report}");
|
||||
1
|
||||
}
|
||||
Err(e) => {
|
||||
errln!(io, "error: {e}");
|
||||
1
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,942 +1,9 @@
|
||||
//! `wordcraft-cli`: WordCraft from the command line.
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
//! The `wordcraft-cli` program: [`wordcraft_cli::run`] with the process's streams.
|
||||
|
||||
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;
|
||||
|
||||
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 [--connect HOST:PORT | --author NAME] [--automation-read-root DIR] [--automation-write-root DIR]
|
||||
MCP server on stdio (headless, or bridged to the app).
|
||||
--automation-read-root / --automation-write-root confine
|
||||
the files the agent's commands read (open, insert text
|
||||
or picture, mail-merge data, templates…) and write (save,
|
||||
export, merge output…) to DIR, links followed; a root left
|
||||
out grants none of its access. They apply to the headless
|
||||
server and are an error with --connect.
|
||||
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, ®ion).map_err(engine_error)?;
|
||||
let mut s = session(doc);
|
||||
s.path = Some(path.into());
|
||||
if encrypted {
|
||||
s.password = password.map(wordcraft_engine::io::Password::new);
|
||||
}
|
||||
Ok(s)
|
||||
}
|
||||
|
||||
/// The 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))
|
||||
}
|
||||
|
||||
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 }];
|
||||
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()))
|
||||
}
|
||||
|
||||
/// Whether `addr` (`HOST:PORT`, as `--connect` gives it) is at least shaped like an address: a
|
||||
/// host of some kind and a numeric port. Malformed addresses fail at startup — a lazy remote
|
||||
/// would otherwise retry one on every call and never say why nothing connects.
|
||||
fn valid_connect_addr(addr: &str) -> bool {
|
||||
let Some((host, port)) = addr.rsplit_once(':') else { return false };
|
||||
!host.is_empty() && port.parse::<u16>().is_ok()
|
||||
}
|
||||
|
||||
/// 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", ¶ms).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", ¶ms)
|
||||
};
|
||||
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", ¶ms) {
|
||||
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", ¶ms).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, ¶ms).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)?;
|
||||
validate_options("mcp", &rest, MCP_OPTIONS)?;
|
||||
let author = arg_value(&rest, "--author");
|
||||
let connect = arg_value(&rest, "--connect");
|
||||
if roots.is_some() && connect.is_some() {
|
||||
return Err(
|
||||
"mcp: --automation-read-root and --automation-write-root confine the headless server; a running app is not confined by them"
|
||||
.into(),
|
||||
);
|
||||
}
|
||||
let backend: Box<dyn wordcraft_mcp::Backend> = match connect {
|
||||
// The app's user name is the person's own setting; don't rewrite it from a flag.
|
||||
Some(_) if author.is_some() => {
|
||||
return Err("mcp: --author applies to the headless server; with --connect, run file.setAuthor".into());
|
||||
}
|
||||
Some(addr) => {
|
||||
// A malformed address must fail at startup, not on every tool call the lazy
|
||||
// remote would retry it with.
|
||||
if !valid_connect_addr(&addr) {
|
||||
return Err(format!("mcp: --connect needs HOST:PORT with a numeric port, got `{addr}`").into());
|
||||
}
|
||||
match wordcraft_mcp::Remote::connect(&addr) {
|
||||
Ok(remote) => {
|
||||
eprintln!("wordcraft-cli mcp: connected to WordCraft at {addr}");
|
||||
if let Some(w) = remote.key_warning() {
|
||||
eprintln!("wordcraft-cli: {w}");
|
||||
}
|
||||
Box::new(remote)
|
||||
}
|
||||
// The app may start after the client does: serve anyway and connect on the
|
||||
// first call, or the client marks the server failed for its whole session
|
||||
// (#4078).
|
||||
Err(e) => {
|
||||
eprintln!("wordcraft-cli mcp: WordCraft is not reachable at {addr} yet ({e}); will retry on each call");
|
||||
Box::new(wordcraft_mcp::Remote::lazy(&addr))
|
||||
}
|
||||
}
|
||||
}
|
||||
None => {
|
||||
let mut headless = wordcraft_mcp::Headless::default();
|
||||
if let Some(roots) = roots {
|
||||
// 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()));
|
||||
headless = headless.with_automation_roots(Some(roots));
|
||||
}
|
||||
if let Some(name) = author {
|
||||
set_author(&mut headless.session, &name)?;
|
||||
}
|
||||
Box::new(headless)
|
||||
}
|
||||
};
|
||||
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, ¶ms).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)
|
||||
}
|
||||
}
|
||||
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))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
+401
-328
@@ -1,10 +1,303 @@
|
||||
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 é";
|
||||
@@ -14,132 +307,12 @@ fn peer_text_stays_on_one_visible_line() {
|
||||
assert_eq!(escape_peer("Citation (Doe, 2020) — “ok”"), "Citation (Doe, 2020) — “ok”");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validators_accept_only_the_documented_options() {
|
||||
assert!(validate_options("info", &args(&["file.docx"]), PASSWORD_OPTIONS).is_ok());
|
||||
assert!(validate_options("render", &args(&["in.docx", "out.png", "--page", "2", "--scale", "1.5"]), RENDER_OPTIONS).is_ok());
|
||||
assert!(validate_options("run", &args(&["--cmd", "text.insert={}", "--cmd", "edit.undo", "--print"]), RUN_OPTIONS).is_ok());
|
||||
assert!(validate_options("commands", &args(&["--json"]), COMMANDS_OPTIONS).is_ok());
|
||||
assert!(validate_options("parity", &args(&["--markdown"]), PARITY_OPTIONS).is_ok());
|
||||
assert!(validate_options("mcp", &args(&["--connect", "127.0.0.1:9000"]), MCP_OPTIONS).is_ok());
|
||||
assert!(validate_options("render", &args(&["in.docx", "out.png", "--page"]), RENDER_OPTIONS).is_ok());
|
||||
assert!(
|
||||
validate_options(
|
||||
"zotero",
|
||||
&args(&["refresh", "in.docx", "--cmd", "caret.docEnd", "--save", "out.docx", "--trace", "--port", "23119"]),
|
||||
ZOTERO_OPTIONS
|
||||
)
|
||||
.is_ok()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_option_value_is_never_read_as_a_path() {
|
||||
// `--password`'s value sits between the paths and would be taken for one without
|
||||
// `positionals`, so `render` would write its picture over a file called after the password.
|
||||
assert_eq!(positionals(&args(&["in.docx", "--password", "secret", "out.png"]), RENDER_OPTIONS), vec!["in.docx", "out.png"]);
|
||||
assert_eq!(positionals(&args(&["in.docx", "out.png", "--page", "2"]), RENDER_OPTIONS), vec!["in.docx", "out.png"]);
|
||||
// A bare flag takes no value, so the next argument stays a path.
|
||||
assert_eq!(positionals(&args(&["--print", "in.docx"]), RUN_OPTIONS), vec!["in.docx"]);
|
||||
// `convert` is the one with a value-taking flag between the two paths.
|
||||
assert_eq!(positionals(&args(&["in.docx", "--format", "flatopc", "out.docx"]), CONVERT_OPTIONS), vec!["in.docx", "out.docx"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_password_comes_from_an_option_a_file_or_the_environment() {
|
||||
assert_eq!(password_from(&args(&["f.docx"])), Ok(None));
|
||||
assert_eq!(password_from(&args(&["f.docx", "--password", "s3cret"])), Ok(Some("s3cret".into())));
|
||||
// `--password` wins over the other two sources.
|
||||
assert_eq!(password_from(&args(&["--password", "a", "--password-file", "/nonexistent"])), Ok(Some("a".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_password_file_loses_only_its_trailing_newline() {
|
||||
let path = std::env::temp_dir().join("wordcraft-cli-password-test.txt");
|
||||
std::fs::write(&path, "s3cret\r\n").unwrap();
|
||||
let got = password_from(&args(&["f.docx", "--password-file", &path.to_string_lossy()]));
|
||||
std::fs::remove_file(&path).ok();
|
||||
assert_eq!(got, Ok(Some("s3cret".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_password_file_is_named_without_the_password() {
|
||||
let err = password_from(&args(&["f.docx", "--password-file", "/nonexistent/secret.txt"])).unwrap_err();
|
||||
assert!(err.contains("--password-file"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_options_are_rejected_before_file_access() {
|
||||
assert_eq!(run(&args(&["info", "missing.docx", "--passwrod", "x"])), Err("info: unknown option --passwrod".into()));
|
||||
assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--sclae", "2"])), Err("render: unknown option --sclae".into()));
|
||||
assert_eq!(run(&args(&["zotero", "refresh", "missing.docx", "--prot", "1"])), Err("zotero: unknown option --prot".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convert_rejects_malformed_format_options_before_file_access() {
|
||||
for (options, error) in [
|
||||
(vec!["--format"], "convert: --format requires a value"),
|
||||
(vec!["--format", "--markup"], "convert: --format requires a value"),
|
||||
(vec!["--format", "flatopc", "--format", "wordml2003"], "convert: duplicate --format option"),
|
||||
] {
|
||||
let mut argv = args(&["convert", "missing.docx", "out.xml"]);
|
||||
argv.extend(args(&options));
|
||||
assert_eq!(run(&argv), Err(error.into()), "{options:?}");
|
||||
}
|
||||
// A valid single value reaches file access, rather than a format-option error.
|
||||
let error = run(&args(&["convert", "missing.docx", "out.xml", "--format", "flatopc"])).unwrap_err().to_string();
|
||||
assert!(error.starts_with("missing.docx:"), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn help_or_h_after_a_subcommand_asks_for_the_usage() {
|
||||
for cmd in SUBCOMMANDS {
|
||||
assert!(wants_help(cmd, &args(&["in.docx", "--help"])), "{cmd}");
|
||||
assert!(wants_help(cmd, &args(&["-h"])), "{cmd}");
|
||||
assert!(!wants_help(cmd, &args(&["in.docx", "--hepl"])), "{cmd}");
|
||||
}
|
||||
assert!(!wants_help("frobnicate", &args(&["--help"])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn usage_lists_exactly_the_subcommands() {
|
||||
let listed: Vec<&str> = USAGE
|
||||
.lines()
|
||||
.filter_map(|line| line.strip_prefix(" wordcraft-cli ")?.split_whitespace().next())
|
||||
.filter(|word| !word.starts_with(['-', '[']))
|
||||
.collect();
|
||||
assert_eq!(listed, SUBCOMMANDS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_keeps_bullet_and_number_labels() {
|
||||
let doc = wordcraft_engine::io::open_bytes("lists.md", b"- alpha\n- beta\n\n1. first\n2. second\n").unwrap();
|
||||
assert_eq!(listed_text(&doc).unwrap(), "\u{2022}\talpha\n\u{2022}\tbeta\n1.\tfirst\n2.\tsecond");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn author_flag_names_the_headless_session() {
|
||||
assert!(validate_options("run", &args(&["--author", "Claude (copyedit)", "--cmd", "edit.undo"]), RUN_OPTIONS).is_ok());
|
||||
assert!(validate_options("mcp", &args(&["--author", "Claude"]), MCP_OPTIONS).is_ok());
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
assert!(set_author(&mut s, " Claude (copyedit) ").is_ok());
|
||||
assert_eq!(s.author, "Claude (copyedit)");
|
||||
assert!(set_author(&mut s, " ").is_err_and(|e| e.starts_with("--author:")));
|
||||
assert!(run(&args(&["run", "--author", "Claude", "--cmd", "review.trackChanges={\"value\":true}"])).is_ok());
|
||||
// The app's user name is the person's own; a bridge flag must not rewrite it.
|
||||
assert!(run(&args(&["mcp", "--connect", "127.0.0.1:9", "--author", "Claude"])).is_err_and(|e| e.to_string().contains("--author")));
|
||||
// A malformed address fails at startup, not on every retried call.
|
||||
assert!(run(&args(&["mcp", "--connect", "127.0.0.1:notaport"])).is_err_and(|e| e.to_string().contains("numeric port")));
|
||||
assert!(run(&args(&["mcp", "--connect", "notaport"])).is_err_and(|e| e.to_string().contains("numeric port")));
|
||||
// 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};
|
||||
@@ -158,194 +331,41 @@ 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());
|
||||
/// An exclusively created scratch folder, removed on drop even when an assertion fails.
|
||||
struct Scratch(PathBuf);
|
||||
|
||||
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"));
|
||||
impl Scratch {
|
||||
fn new(tag: &str) -> Self {
|
||||
static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
|
||||
loop {
|
||||
let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
let dir = std::env::temp_dir().join(format!("wc-cli-{tag}-{}-{n}", std::process::id()));
|
||||
// `create_dir` fails when the path exists, so a leftover or a planted folder is never reused. Any
|
||||
// other failure (no temp folder, no permission) fails every name: report it instead of looping.
|
||||
match std::fs::create_dir(&dir) {
|
||||
Ok(()) => return Self(dir),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
|
||||
Err(e) => panic!("scratch folder {}: {e}", dir.display()),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn automation_roots_are_an_error_with_connect() {
|
||||
let dir = std::env::temp_dir().to_string_lossy().into_owned();
|
||||
let e = run(&args(&["mcp", "--connect", "127.0.0.1:9", "--automation-read-root", &dir])).unwrap_err().to_string();
|
||||
assert!(e.contains("--automation-read-root") && e.contains("headless"), "{e}");
|
||||
impl Drop for Scratch {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// `mcp`'s headless session takes `--author` as the session's author, and refuses a blank one as `run` does.
|
||||
#[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())
|
||||
);
|
||||
fn mcp_headless_session_takes_the_author_flag() {
|
||||
let scratch = Scratch::new("mcp-author");
|
||||
let roots = wordcraft_engine::file_access::AutomationRoots::new(Some(&scratch.0), Some(&scratch.0)).unwrap().unwrap();
|
||||
assert_eq!(headless_mcp(roots.clone(), Some("Claude (copyedit)")).unwrap().session.author, "Claude (copyedit)");
|
||||
assert!(headless_mcp(roots.clone(), Some(" ")).is_err_and(|e| e.starts_with("--author:")));
|
||||
let unnamed = headless_mcp(roots, None).unwrap();
|
||||
assert_eq!(unnamed.session.author, wordcraft_mcp::Headless::default().session.author, "no flag keeps the default author");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -497,33 +517,6 @@ fn command_line_template_wins_over_the_scripts_file() {
|
||||
assert!(std::fs::read_to_string(&b).unwrap().contains("FROM FILE"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmd_value_missing_is_reported() {
|
||||
let missing = std::env::temp_dir().join(format!(
|
||||
"wc-cli-missing-cmd-{}-{}.docx",
|
||||
std::process::id(),
|
||||
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_nanos()
|
||||
));
|
||||
assert!(!missing.exists());
|
||||
let missing = missing.to_string_lossy();
|
||||
for argv in [
|
||||
vec!["run", "--cmd"],
|
||||
vec!["run", "--cmd", "--save", "out.docx"],
|
||||
vec!["run", "--cmd", "caret.docEnd", "--cmd", "--print"],
|
||||
vec!["run", "--cmd", "--bogus"],
|
||||
vec!["run", "--cmd", "--file", &missing],
|
||||
] {
|
||||
assert_eq!(run(&args(&argv)), Err("--cmd needs a value".into()), "{argv:?}");
|
||||
}
|
||||
assert!(run(&args(&["run", "--cmd", "caret.docEnd", "--cmd", "caret.docStart"])).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_value_missing_is_reported() {
|
||||
let e = run(&args(&["run", "--script", "--cmd", "caret.docEnd"])).unwrap_err().to_string();
|
||||
assert!(e.contains("--script requires a value"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_reads_from_a_stream_and_caps_its_size() {
|
||||
let s = script::load_from(&br#"{"commands":["caret.docEnd"],"save":["o.docx"]}"#[..], "-", None).unwrap();
|
||||
@@ -586,6 +579,86 @@ 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";
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! A reader that closes stdout early (`wordcraft-cli commands --json | head`) must end the CLI
|
||||
//! quietly with exit 0, never with a panic (#508).
|
||||
//! Readers closing stdout early must not panic (#508). Listing and MCP stop quietly;
|
||||
//! validation retains its verdict exit status.
|
||||
|
||||
use std::io::{Read, Write};
|
||||
use std::process::{Command, Stdio};
|
||||
@@ -24,7 +24,19 @@ fn commands_json_into_a_closed_pipe_exits_quietly() {
|
||||
|
||||
#[test]
|
||||
fn mcp_server_ends_cleanly_when_its_client_closes_stdout() {
|
||||
let mut child = cli().arg("mcp").stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
|
||||
// The server starts only with both roots (#7124); the temporary folder serves as both.
|
||||
let root = std::env::temp_dir();
|
||||
let mut child = cli()
|
||||
.arg("mcp")
|
||||
.arg("--automation-read-root")
|
||||
.arg(&root)
|
||||
.arg("--automation-write-root")
|
||||
.arg(&root)
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
drop(child.stdout.take());
|
||||
let mut stdin = child.stdin.take().unwrap();
|
||||
// The reply to this request has nowhere to go.
|
||||
@@ -35,3 +47,65 @@ fn mcp_server_ends_cleanly_when_its_client_closes_stdout() {
|
||||
assert!(out.status.success(), "status {:?}, stderr: {stderr}", out.status);
|
||||
assert!(!stderr.contains("panicked"), "stderr: {stderr}");
|
||||
}
|
||||
|
||||
/// A closed reader preserves validation's verdict for both report formats, including INCOMPLETE.
|
||||
#[test]
|
||||
fn validate_closed_stdout_preserves_verdict() {
|
||||
let corpus = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../crates/validate/corpus/calibration");
|
||||
let sparse = std::env::temp_dir().join(format!("wordcraft-validate-closed-stdout-{}.docx", std::process::id()));
|
||||
// The validator checks metadata before reading inputs over its 512 MiB limit.
|
||||
std::fs::File::create(&sparse).unwrap().set_len((512 << 20) + 1).unwrap();
|
||||
let pass = sparse.with_file_name(format!("wordcraft-validate-closed-stdout-pass-{}.docx", std::process::id()));
|
||||
let bytes = wordcraft_engine::io::save_bytes("pass.docx", &wordcraft_doc::Document::from_text("Control")).unwrap();
|
||||
std::fs::write(&pass, bytes).unwrap();
|
||||
let mut results = Vec::new();
|
||||
for (fixture, expected) in [(pass.clone(), 0), (corpus.join("14-comment-dup.docx"), 1), (sparse.clone(), 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:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
use std::process::{Command, Output};
|
||||
|
||||
const SUBCOMMANDS: [&str; 10] = ["convert", "info", "text", "inspect", "render", "run", "commands", "parity", "mcp", "zotero"];
|
||||
const SUBCOMMANDS: [&str; 11] = ["convert", "info", "text", "inspect", "render", "run", "commands", "parity", "validate", "mcp", "zotero"];
|
||||
|
||||
fn cli(args: &[&str]) -> Output {
|
||||
// `output()` gives the child no stdin, so `mcp` can't wait for a client.
|
||||
@@ -14,7 +14,7 @@ fn assert_prints_usage(args: &[&str]) {
|
||||
let out = cli(args);
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(out.status.success(), "{args:?}: status {:?}, stderr: {stderr}", out.status);
|
||||
assert!(String::from_utf8_lossy(&out.stdout).starts_with("wordcraft-cli — "), "{args:?}: stdout: {}", String::from_utf8_lossy(&out.stdout));
|
||||
assert!(String::from_utf8_lossy(&out.stdout).contains("wordcraft-cli"), "{args:?}: stdout: {}", String::from_utf8_lossy(&out.stdout));
|
||||
assert!(stderr.is_empty(), "{args:?}: stderr: {stderr}");
|
||||
}
|
||||
|
||||
@@ -39,9 +39,9 @@ fn help_comes_before_opening_files_and_folders() {
|
||||
#[test]
|
||||
fn misspelled_options_and_unknown_commands_still_fail() {
|
||||
let out = cli(&["info", "--hepl"]);
|
||||
assert!(!out.status.success());
|
||||
assert!(String::from_utf8_lossy(&out.stderr).contains("info: unknown option --hepl"));
|
||||
assert_eq!(out.status.code(), Some(2));
|
||||
assert!(String::from_utf8_lossy(&out.stderr).contains("--hepl"));
|
||||
let out = cli(&["frobnicate", "--help"]);
|
||||
assert!(!out.status.success());
|
||||
assert!(String::from_utf8_lossy(&out.stderr).contains("unknown command `frobnicate`"));
|
||||
assert_eq!(out.status.code(), Some(2));
|
||||
assert!(String::from_utf8_lossy(&out.stderr).contains("frobnicate"));
|
||||
}
|
||||
|
||||
@@ -3,6 +3,8 @@ 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;
|
||||
mod picture_then_typing;
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
//! The clap definition is consistent, and every shell's completions and every man page
|
||||
//! (`examples/man-and-completions.rs`) can be generated from it.
|
||||
|
||||
use clap::ValueEnum;
|
||||
use clap_complete::Shell;
|
||||
|
||||
// The example itself, so the test writes the files exactly as the packages get them.
|
||||
#[allow(dead_code)]
|
||||
#[path = "../../examples/man-and-completions.rs"]
|
||||
mod example;
|
||||
|
||||
#[test]
|
||||
fn command_is_consistent() {
|
||||
wordcraft_cli::command().debug_assert();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completions_generate_for_every_shell() {
|
||||
for &shell in Shell::value_variants() {
|
||||
let mut out = Vec::new();
|
||||
clap_complete::generate(shell, &mut wordcraft_cli::command(), "wordcraft-cli", &mut out);
|
||||
assert!(!out.is_empty(), "{shell}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn man_pages_render_for_the_command_and_every_subcommand() {
|
||||
let cmd = wordcraft_cli::command();
|
||||
for page in std::iter::once(&cmd).chain(cmd.get_subcommands()) {
|
||||
let mut out = Vec::new();
|
||||
clap_mangen::Man::new(page.clone()).render(&mut out).unwrap();
|
||||
assert!(!out.is_empty(), "{}", page.get_name());
|
||||
}
|
||||
}
|
||||
|
||||
/// The example writes the five completion files under the names `packaging/linux/package.sh` and
|
||||
/// `packaging/freebsd/package.sh` install, `wordcraft-cli.1` and a page per subcommand, and no
|
||||
/// pages for the `help` subcommand.
|
||||
#[test]
|
||||
fn the_example_writes_the_files_the_packages_install() {
|
||||
let dir = std::env::temp_dir().join(format!("wc-cli-{}-man-and-completions", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
example::generate(&dir).unwrap();
|
||||
|
||||
let mut written: Vec<String> = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().file_name().into_string().unwrap()).collect();
|
||||
written.sort();
|
||||
let completions = ["wordcraft-cli.bash", "_wordcraft-cli", "wordcraft-cli.fish", "wordcraft-cli.elv", "_wordcraft-cli.ps1"];
|
||||
let subcommands = ["commands", "convert", "info", "inspect", "mcp", "parity", "render", "run", "text", "validate", "zotero"];
|
||||
let mut expected: Vec<String> = completions.map(String::from).into();
|
||||
expected.push("wordcraft-cli.1".into());
|
||||
expected.extend(subcommands.iter().map(|s| format!("wordcraft-cli-{s}.1")));
|
||||
expected.sort();
|
||||
assert_eq!(written, expected);
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
//! Shared rule 18 (#7124): `wordcraft-cli mcp` refuses to start without both
|
||||
//! `--automation-read-root` and `--automation-write-root`, refuses `--connect` while the desktop
|
||||
//! app doesn't confine its control channel (#3695, #5819), and with both roots refuses files
|
||||
//! outside them, through the real binary.
|
||||
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Output, Stdio};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// An exclusively created folder holding `in` (the read root, with `a.txt`), `out` (the write
|
||||
/// root) and `outside` (with `secret.txt`). Removed on drop, even when an assertion fails.
|
||||
struct Folders(PathBuf);
|
||||
|
||||
impl Folders {
|
||||
fn new(tag: &str) -> Self {
|
||||
static NEXT: AtomicUsize = AtomicUsize::new(0);
|
||||
let base = loop {
|
||||
let n = NEXT.fetch_add(1, Ordering::Relaxed);
|
||||
let dir = std::env::temp_dir().join(format!("wc-cli-mcp-roots-{tag}-{}-{n}", std::process::id()));
|
||||
// `create_dir` fails when the path exists, so a leftover or a planted folder is never reused. Any
|
||||
// other failure (no temp folder, no permission) fails every name: report it instead of looping.
|
||||
match std::fs::create_dir(&dir) {
|
||||
Ok(()) => break dir,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
|
||||
Err(e) => panic!("scratch folder {}: {e}", dir.display()),
|
||||
}
|
||||
};
|
||||
let folders = Self(base);
|
||||
for d in ["in", "out", "outside"] {
|
||||
std::fs::create_dir_all(folders.0.join(d)).unwrap();
|
||||
}
|
||||
std::fs::write(folders.0.join("in/a.txt"), "Inside text").unwrap();
|
||||
std::fs::write(folders.0.join("outside/secret.txt"), "TOP SECRET").unwrap();
|
||||
folders
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Folders {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn s(p: &Path) -> String {
|
||||
p.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
/// Run `wordcraft-cli mcp <args>`, send `lines` on stdin, then hang up.
|
||||
fn mcp(args: &[String], lines: &[Value]) -> Output {
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli"))
|
||||
.arg("mcp")
|
||||
.args(args)
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let mut stdin = child.stdin.take().unwrap();
|
||||
for line in lines {
|
||||
// A server that refused to start has closed its end: that is the expected outcome.
|
||||
let _ = writeln!(stdin, "{line}");
|
||||
}
|
||||
drop(stdin);
|
||||
child.wait_with_output().unwrap()
|
||||
}
|
||||
|
||||
const PING: &str = r#"{"jsonrpc":"2.0","id":1,"method":"ping"}"#;
|
||||
|
||||
fn refused_at_start(args: &[String], why: &[&str]) {
|
||||
let out = mcp(args, &[serde_json::from_str(PING).unwrap()]);
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(!out.status.success(), "{args:?} started: stderr {stderr}");
|
||||
assert!(out.stdout.is_empty(), "{args:?} served: {}", String::from_utf8_lossy(&out.stdout));
|
||||
for w in why {
|
||||
assert!(stderr.contains(w), "{args:?}: `{w}` missing from {stderr}");
|
||||
}
|
||||
assert!(!stderr.contains("panicked"), "{stderr}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mcp_refuses_to_start_without_both_roots() {
|
||||
let folders = Folders::new("start");
|
||||
let base = folders.0.clone();
|
||||
let (read, write) = (s(&base.join("in")), s(&base.join("out")));
|
||||
let both = ["--automation-read-root", "--automation-write-root"];
|
||||
refused_at_start(&[], &both);
|
||||
refused_at_start(&["--author".into(), "Claude".into()], &both);
|
||||
refused_at_start(&["--automation-read-root".into(), read.clone()], &both);
|
||||
refused_at_start(&[format!("--automation-write-root={write}")], &both);
|
||||
// Both: it serves.
|
||||
let out = mcp(&["--automation-read-root".into(), read, "--automation-write-root".into(), write], &[serde_json::from_str(PING).unwrap()]);
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(out.status.success(), "stderr: {stderr}");
|
||||
let reply: Value = serde_json::from_slice(out.stdout.split(|b| *b == b'\n').next().unwrap()).unwrap();
|
||||
assert_eq!(reply["id"], 1, "{reply}");
|
||||
assert!(reply.get("error").is_none(), "{reply}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mcp_connect_is_refused_until_the_app_confines_its_control_channel() {
|
||||
let folders = Folders::new("connect");
|
||||
let base = folders.0.clone();
|
||||
let (read, write) = (s(&base.join("in")), s(&base.join("out")));
|
||||
let why = ["--connect", "#3695", "#5819"];
|
||||
refused_at_start(&["--connect".into(), "127.0.0.1:9".into()], &why);
|
||||
refused_at_start(
|
||||
&["--connect".into(), "127.0.0.1:9".into(), "--automation-read-root".into(), read, "--automation-write-root".into(), write],
|
||||
&why,
|
||||
);
|
||||
}
|
||||
|
||||
/// `tools/call` request `id` for `name` with `arguments`.
|
||||
fn tool(id: u64, name: &str, arguments: Value) -> Value {
|
||||
json!({"jsonrpc": "2.0", "id": id, "method": "tools/call", "params": {"name": name, "arguments": arguments}})
|
||||
}
|
||||
|
||||
fn execute(id: u64, command: &str, params: Value) -> Value {
|
||||
tool(id, "execute", json!({"command": command, "params": params}))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mcp_with_both_roots_refuses_files_outside_them() {
|
||||
let folders = Folders::new("files");
|
||||
let base = folders.0.clone();
|
||||
let sep = std::path::MAIN_SEPARATOR;
|
||||
let (inside, outside) = (base.join("in"), base.join("outside"));
|
||||
let secret = s(&outside.join("secret.txt"));
|
||||
let up = |root: &str, rest: &str| format!("{}{sep}..{sep}{rest}", s(&base.join(root)));
|
||||
#[cfg(unix)]
|
||||
let linked = std::os::unix::fs::symlink(&outside, base.join("out/away")).is_ok()
|
||||
&& std::os::unix::fs::symlink(outside.join("secret.txt"), inside.join("leak.txt")).is_ok();
|
||||
#[cfg(not(unix))]
|
||||
let linked = false;
|
||||
|
||||
// (id, request, refused with). Reads first, then writes, then the allowed ones.
|
||||
let mut cases = vec![
|
||||
(2, tool(2, "open_document", json!({"path": secret})), Some("outside the read root")),
|
||||
(3, execute(3, "file.open", json!({"path": secret})), Some("outside the read root")),
|
||||
(4, execute(4, "file.open", json!({"path": up("in", "outside/secret.txt")})), Some("outside the read root")),
|
||||
(5, execute(5, "insert.picture", json!({"path": s(&outside.join("pic.png"))})), Some("outside the read root")),
|
||||
(6, execute(6, "insert.textFromFile", json!({"path": secret})), Some("outside the read root")),
|
||||
(7, tool(7, "save_document", json!({"path": s(&outside.join("a.docx"))})), Some("outside the write root")),
|
||||
(8, execute(8, "file.saveAs", json!({"path": s(&outside.join("b.docx"))})), Some("outside the write root")),
|
||||
(9, execute(9, "file.exportPdf", json!({"path": s(&outside.join("c.pdf"))})), Some("outside the write root")),
|
||||
(10, execute(10, "file.exportPng", json!({"path": s(&outside.join("d.png"))})), Some("outside the write root")),
|
||||
(11, execute(11, "file.saveAs", json!({"path": up("out", "outside/e.docx")})), Some("outside the write root")),
|
||||
// The write root isn't readable, nor the read root writable.
|
||||
(12, execute(12, "file.saveAs", json!({"path": s(&inside.join("f.docx"))})), Some("outside the write root")),
|
||||
(13, tool(13, "open_document", json!({"path": s(&inside.join("a.txt"))})), None),
|
||||
(14, execute(14, "file.saveAs", json!({"path": s(&base.join("out/g.docx"))})), None),
|
||||
];
|
||||
if linked {
|
||||
cases.push((15, tool(15, "open_document", json!({"path": s(&inside.join("leak.txt"))})), Some("outside the read root")));
|
||||
cases.push((16, execute(16, "file.saveAs", json!({"path": s(&base.join("out/away/h.docx"))})), Some("outside the write root")));
|
||||
}
|
||||
let requests: Vec<Value> = cases.iter().map(|(_, r, _)| r.clone()).collect();
|
||||
let out = mcp(&["--automation-read-root".into(), s(&inside), "--automation-write-root".into(), s(&base.join("out"))], &requests);
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(out.status.success(), "stderr: {stderr}");
|
||||
let replies: Vec<Value> =
|
||||
String::from_utf8_lossy(&out.stdout).lines().filter(|l| !l.trim().is_empty()).map(|l| serde_json::from_str(l).unwrap()).collect();
|
||||
for (id, request, why) in &cases {
|
||||
let reply = replies.iter().find(|r| r["id"] == *id).unwrap_or_else(|| panic!("no reply to {request}"));
|
||||
let result = &reply["result"];
|
||||
let text: String = result["content"].as_array().into_iter().flatten().filter_map(|c| c["text"].as_str()).collect();
|
||||
match why {
|
||||
Some(why) => assert!(result["isError"] == true && text.contains(why), "{request} should be refused ({why}): {reply}"),
|
||||
None => assert!(result["isError"] != true, "{request}: {reply}"),
|
||||
}
|
||||
}
|
||||
let mut written: Vec<String> = std::fs::read_dir(&outside).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect();
|
||||
written.sort();
|
||||
assert_eq!(written, ["secret.txt"], "nothing was written outside the roots");
|
||||
assert!(!inside.join("f.docx").exists());
|
||||
assert!(base.join("out/g.docx").is_file());
|
||||
}
|
||||
@@ -67,17 +67,19 @@ fn any_other_such_argument_is_an_error_naming_it() {
|
||||
let (dir, file) = folder("error");
|
||||
let out_name = dir.join(OsString::from_vec(b"caf\xe9.md".to_vec())).into_os_string();
|
||||
let cmd = OsString::from_vec(b"text.insert={\"text\":\"\xe9\"}".to_vec());
|
||||
for (args, n) in [
|
||||
(vec!["convert".into(), file.clone(), out_name.clone()], 3),
|
||||
(vec!["run".into(), "--file".into(), file.clone(), "--cmd".into(), cmd], 5),
|
||||
(vec![OsString::from_vec(b"t\xe9xt".to_vec()), file.clone()], 1),
|
||||
// An output the engine takes as text: a failure (1), naming it; the other arguments are usage errors (2).
|
||||
for (args, code, shown) in [
|
||||
(vec!["convert".into(), file.clone(), out_name.clone()], 1, out_name.clone()),
|
||||
(vec!["run".into(), "--file".into(), file.clone(), "--cmd".into(), cmd.clone()], 2, cmd),
|
||||
(vec![OsString::from_vec(b"t\xe9xt".to_vec()), file.clone()], 2, OsString::from_vec(b"t\xe9xt".to_vec())),
|
||||
] {
|
||||
let out = cli(&args);
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
let shown = args[n - 1].to_string_lossy();
|
||||
let shown = shown.to_string_lossy();
|
||||
assert!(shown.contains('\u{FFFD}'));
|
||||
assert_eq!(out.status.code(), Some(1), "{args:?}: stderr: {stderr}");
|
||||
assert_eq!(stderr, format!("wordcraft-cli: argument {n} is not valid Unicode: {shown}\n"), "{args:?}");
|
||||
assert_eq!(out.status.code(), Some(code), "{args:?}: stderr: {stderr}");
|
||||
assert!(stderr.starts_with("error: "), "{args:?}: {stderr}");
|
||||
assert!(stderr.contains("not valid Unicode") || stderr.contains("invalid UTF-8") || stderr.contains(&*shown), "{args:?}: {stderr}");
|
||||
}
|
||||
assert!(!std::path::Path::new(&out_name).exists());
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! `convert --strict` (#6005): exit 3 and a report when a PDF or PNG would silently lack a
|
||||
//! `convert --strict` (#6005): exit 1 and a report when a PDF or PNG would silently lack a
|
||||
//! character or a picture, nothing written; exit 0 otherwise.
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Output};
|
||||
@@ -145,9 +145,9 @@ fn an_uncovered_code_point_fails_strict_with_a_report_and_no_file() {
|
||||
for out in ["out.pdf", "out.png"] {
|
||||
let out = d.join(out);
|
||||
let r = convert(&input, &out, true);
|
||||
assert_eq!(r.status.code(), Some(3), "{}", stderr(&r));
|
||||
assert_eq!(r.status.code(), Some(1), "{}", stderr(&r));
|
||||
let text = stderr(&r);
|
||||
assert!(text.contains(&format!("wordcraft-cli: strict: 1 character cannot be drawn: {cp} (×3)")), "{text}");
|
||||
assert!(text.contains(&format!("error: strict: 1 character cannot be drawn: {cp} (×3)")), "{text}");
|
||||
let json = report_json(&r);
|
||||
assert_eq!(json["schema"], 1);
|
||||
assert_eq!(json["strict"], "failed");
|
||||
@@ -186,7 +186,7 @@ fn a_corrupt_header_picture_fails_strict_naming_the_part_and_the_header() {
|
||||
for out in ["out.pdf", "out.png"] {
|
||||
let out = d.join(out);
|
||||
let r = convert(&input, &out, true);
|
||||
assert_eq!(r.status.code(), Some(3), "{}", stderr(&r));
|
||||
assert_eq!(r.status.code(), Some(1), "{}", stderr(&r));
|
||||
let text = stderr(&r);
|
||||
assert!(text.contains("word/media/image2.bin (header2.xml): unsupported format"), "{text}");
|
||||
let json = report_json(&r);
|
||||
@@ -218,7 +218,7 @@ fn an_external_picture_target_is_never_fetched_and_is_reported_under_strict() {
|
||||
assert_eq!(lenient.status.code(), Some(0), "{}", stderr(&lenient));
|
||||
let out = d.join("strict.pdf");
|
||||
let strict = convert(&input, &out, true);
|
||||
assert_eq!(strict.status.code(), Some(3), "{}", stderr(&strict));
|
||||
assert_eq!(strict.status.code(), Some(1), "{}", stderr(&strict));
|
||||
let json = report_json(&strict);
|
||||
assert_eq!(json["missing_pictures"][0]["reason"], "external_target");
|
||||
assert!(stderr(&strict).contains("external target"));
|
||||
@@ -246,19 +246,19 @@ fn bad_input_exits_1_with_the_usual_message_with_and_without_strict() {
|
||||
assert_eq!(plain.status.code(), Some(1), "{}", stderr(&plain));
|
||||
assert_eq!(strict.status.code(), Some(1), "{}", stderr(&strict));
|
||||
assert_eq!(stderr(&plain), stderr(&strict));
|
||||
assert!(stderr(&plain).starts_with("wordcraft-cli: "), "{}", stderr(&plain));
|
||||
assert!(stderr(&plain).starts_with("error: "), "{}", stderr(&plain));
|
||||
assert!(!d.join("a.pdf").exists() && !d.join("b.pdf").exists());
|
||||
}
|
||||
std::fs::remove_dir_all(d).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_with_another_output_type_exits_1_before_the_input_is_read() {
|
||||
fn strict_with_another_output_type_exits_2_before_the_input_is_read() {
|
||||
let d = dir("wrong-output");
|
||||
let missing = d.join("does-not-exist.docx");
|
||||
for out in ["out.docx", "out.txt", "out.odt"] {
|
||||
let r = convert(&missing, &d.join(out), true);
|
||||
assert_eq!(r.status.code(), Some(1));
|
||||
assert_eq!(r.status.code(), Some(2));
|
||||
let text = stderr(&r);
|
||||
assert!(text.contains("--strict needs a .pdf or .png output"), "{text}");
|
||||
assert!(!d.join(out).exists());
|
||||
@@ -291,11 +291,11 @@ fn render_strict_refuses_an_uncovered_character_on_the_page_with_no_stdout_or_fi
|
||||
let input = two_page_input(&d, &format!("a{c}b"));
|
||||
let out = d.join("p1.png");
|
||||
let r = render(&input, &out, &["--strict"]);
|
||||
assert_eq!(r.status.code(), Some(3), "{}", stderr(&r));
|
||||
assert_eq!(r.status.code(), Some(1), "{}", stderr(&r));
|
||||
assert!(r.stdout.is_empty(), "{}", String::from_utf8_lossy(&r.stdout));
|
||||
assert!(!out.exists());
|
||||
let text = stderr(&r);
|
||||
assert!(text.contains(&format!("wordcraft-cli: strict: 1 character cannot be drawn: {cp} (×1)")), "{text}");
|
||||
assert!(text.contains(&format!("error: strict: 1 character cannot be drawn: {cp} (×1)")), "{text}");
|
||||
assert_eq!(report_json(&r)["missing_glyphs"][0]["cp"], cp.as_str());
|
||||
eprintln!("{text}");
|
||||
|
||||
@@ -323,7 +323,7 @@ fn render_strict_refuses_a_corrupt_header_picture_and_bad_input_still_exits_1()
|
||||
std::fs::write(&input, docx_with_header_picture(b"corrupt bytes, not a picture")).unwrap();
|
||||
let out = d.join("out.png");
|
||||
let r = render(&input, &out, &["--strict"]);
|
||||
assert_eq!(r.status.code(), Some(3), "{}", stderr(&r));
|
||||
assert_eq!(r.status.code(), Some(1), "{}", stderr(&r));
|
||||
assert!(r.stdout.is_empty());
|
||||
assert!(stderr(&r).contains("word/media/image2.bin (header2.xml)"), "{}", stderr(&r));
|
||||
assert!(!out.exists());
|
||||
@@ -341,16 +341,16 @@ fn a_picture_target_with_a_newline_and_a_bidi_override_cannot_forge_a_report_lin
|
||||
let d = dir("escape");
|
||||
let input = d.join("in.docx");
|
||||
// XML character references put a newline and U+202E in the target.
|
||||
std::fs::write(&input, docx_with_external_picture("http://example.invalid/a wordcraft-cli: strict: forged‮gnp.png")).unwrap();
|
||||
std::fs::write(&input, docx_with_external_picture("http://example.invalid/a error: strict: forged‮gnp.png")).unwrap();
|
||||
let out = d.join("out.pdf");
|
||||
let r = convert(&input, &out, true);
|
||||
assert_eq!(r.status.code(), Some(3), "{}", stderr(&r));
|
||||
assert_eq!(r.status.code(), Some(1), "{}", stderr(&r));
|
||||
let text = stderr(&r);
|
||||
let lines: Vec<&str> = text.lines().collect();
|
||||
// One human line for the picture, then the JSON line.
|
||||
assert_eq!(lines.len(), 2, "{text}");
|
||||
assert!(lines[0].starts_with("wordcraft-cli: strict: 1 picture(s) left out: "), "{text}");
|
||||
assert!(lines[0].contains("\\nwordcraft-cli: strict: forged\\u{202e}gnp.png"), "{text}");
|
||||
assert!(lines[0].starts_with("error: strict: 1 picture(s) left out: "), "{text}");
|
||||
assert!(lines[0].contains("\\nerror: strict: forged\\u{202e}gnp.png"), "{text}");
|
||||
assert!(!text.contains('\u{202e}'), "the raw bidi override reached the terminal");
|
||||
// The JSON keeps the raw value, escaped by the JSON encoder.
|
||||
let json = report_json(&r);
|
||||
@@ -363,14 +363,14 @@ fn a_picture_target_with_a_newline_and_a_bidi_override_cannot_forge_a_report_lin
|
||||
fn run_with_strict_cannot_forge_an_error_line_either() {
|
||||
let d = dir("run-escape");
|
||||
let input = d.join("in.docx");
|
||||
std::fs::write(&input, docx_with_external_picture("http://example.invalid/a wordcraft-cli: strict: forged[2J‮gnp.png")).unwrap();
|
||||
std::fs::write(&input, docx_with_external_picture("http://example.invalid/a error: strict: forged[2J‮gnp.png")).unwrap();
|
||||
let out = d.join("out.pdf");
|
||||
let cmd = format!("file.exportPdf={}", serde_json::json!({"path": out, "strict": true}));
|
||||
let r = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli")).arg("run").arg("--file").arg(&input).arg("--cmd").arg(cmd).output().unwrap();
|
||||
assert_eq!(r.status.code(), Some(1));
|
||||
let text = stderr(&r);
|
||||
assert_eq!(text.lines().count(), 1, "{text}");
|
||||
assert!(text.contains("\\nwordcraft-cli: strict: forged") && text.contains("\\u{202e}"), "{text}");
|
||||
assert!(text.contains("\\nerror: strict: forged") && text.contains("\\u{202e}"), "{text}");
|
||||
assert!(!text.contains('\u{1b}') && !text.contains('\u{202e}'), "{text:?}");
|
||||
assert!(!out.exists());
|
||||
std::fs::remove_dir_all(d).unwrap();
|
||||
@@ -378,19 +378,20 @@ fn run_with_strict_cannot_forge_an_error_line_either() {
|
||||
|
||||
#[test]
|
||||
fn usage_errors_keep_their_line_breaks() {
|
||||
// Errors go to stderr with the usage after a blank line (`missing argument`, `unknown command`).
|
||||
// Errors go to stderr (clap's message, then its usage), exit 2.
|
||||
for args in [&["frobnicate"][..], &["convert"][..]] {
|
||||
let r = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli")).args(args).output().unwrap();
|
||||
let text = stderr(&r);
|
||||
assert_eq!(r.status.code(), Some(1), "{args:?}: {text}");
|
||||
assert!(text.lines().count() > 3, "{args:?}: {text}");
|
||||
assert!(text.lines().any(|l| l == "USAGE:"), "{args:?}: {text}");
|
||||
assert_eq!(r.status.code(), Some(2), "{args:?}: {text}");
|
||||
assert!(text.lines().count() > 2, "{args:?}: {text}");
|
||||
assert!(text.lines().any(|l| l.starts_with("Usage:")), "{args:?}: {text}");
|
||||
assert!(!text.contains("\\n"), "{args:?}: {text}");
|
||||
}
|
||||
// No arguments at all prints the usage as help, on stdout.
|
||||
// No arguments at all prints the help (on stderr, as clap does for a missing subcommand), exit 2.
|
||||
let r = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli")).output().unwrap();
|
||||
assert_eq!(r.status.code(), Some(2));
|
||||
let all = format!("{}{}", String::from_utf8_lossy(&r.stdout), stderr(&r));
|
||||
assert!(all.lines().count() > 3 && all.lines().any(|l| l == "USAGE:"), "{all}");
|
||||
assert!(all.lines().count() > 3 && all.lines().any(|l| l.starts_with("Usage:")), "{all}");
|
||||
}
|
||||
|
||||
/// A minimal EMF (88-byte header, 100 mm square frame) with one EMR_EXTTEXTOUTW record showing
|
||||
@@ -444,7 +445,7 @@ fn a_character_in_a_metafile_pictures_text_fails_strict_like_the_pages_own() {
|
||||
for out in ["out.pdf", "out.png"] {
|
||||
let out = d.join(out);
|
||||
let r = convert(&input, &out, true);
|
||||
assert_eq!(r.status.code(), Some(3), "{}", stderr(&r));
|
||||
assert_eq!(r.status.code(), Some(1), "{}", stderr(&r));
|
||||
assert_eq!(report_json(&r)["missing_glyphs"][0]["cp"], cp.as_str(), "{}", stderr(&r));
|
||||
assert!(!out.exists(), "{} was written", out.display());
|
||||
// Without --strict it converts, the character a hollow box.
|
||||
@@ -454,7 +455,7 @@ fn a_character_in_a_metafile_pictures_text_fails_strict_like_the_pages_own() {
|
||||
}
|
||||
let out = d.join("p1.png");
|
||||
let r = render(&input, &out, &["--strict"]);
|
||||
assert_eq!(r.status.code(), Some(3), "{}", stderr(&r));
|
||||
assert_eq!(r.status.code(), Some(1), "{}", stderr(&r));
|
||||
assert!(r.stdout.is_empty() && !out.exists());
|
||||
assert_eq!(report_json(&r)["missing_glyphs"][0]["cp"], cp.as_str());
|
||||
// Text the faces cover passes.
|
||||
@@ -479,7 +480,7 @@ fn a_metafile_page_background_fails_strict_for_png_but_not_for_pdf() {
|
||||
std::fs::write(&input, serde_json::to_vec(&doc).unwrap()).unwrap();
|
||||
let png = d.join("out.png");
|
||||
let r = convert(&input, &png, true);
|
||||
assert_eq!(r.status.code(), Some(3), "{}", stderr(&r));
|
||||
assert_eq!(r.status.code(), Some(1), "{}", stderr(&r));
|
||||
let json = report_json(&r);
|
||||
assert_eq!(json["missing_pictures"][0]["part"], "bg.emf", "{}", stderr(&r));
|
||||
assert_eq!(json["missing_pictures"][0]["source_part"], "background");
|
||||
|
||||
@@ -16,10 +16,9 @@ path = "src/main.rs"
|
||||
[dependencies]
|
||||
wordcraft-engine = { workspace = true }
|
||||
wordcraft-ui-egui = { workspace = true }
|
||||
# The host messages (storytold/craft-libs): one contract and one bridge for the web builds.
|
||||
# The page command API (storytold/craft-libs#413): window.wordcraft over the control channel.
|
||||
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "0.1.0" }
|
||||
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a", version = "0.1.0" }
|
||||
# The Craft libraries through the facade (storytold/craft-libs): the host messages and bridge, the page command API,
|
||||
# browser files, clipboard and appearance, print, settings and the UI shell.
|
||||
craft = { workspace = true, features = ["web-api", "web-host", "platform-browser", "platform-appearance", "platform-clipboard", "automation", "print", "settings", "ui", "window"] }
|
||||
egui = { workspace = true }
|
||||
log = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
@@ -29,8 +28,12 @@ wordcraft-fonts = { workspace = true }
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
||||
# `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback.
|
||||
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] }
|
||||
rfd = { workspace = true }
|
||||
web-time = "1.1"
|
||||
wasm-bindgen = "0.2"
|
||||
wasm-bindgen-futures = "0.4"
|
||||
js-sys = "0.3"
|
||||
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "HtmlIFrameElement", "Blob", "BlobPropertyBag", "Url", "Location", "CssStyleDeclaration", "Event", "EventTarget", "BeforeUnloadEvent", "ClipboardEvent", "DataTransfer", "FileList", "File", "DomStringList", "IdbFactory", "IdbOpenDbRequest", "IdbRequest", "IdbDatabase", "IdbObjectStore", "IdbTransaction", "IdbTransactionMode", "MediaQueryList", "Storage", "MessageEvent", "UrlSearchParams", "CustomEvent", "CustomEventInit"] }
|
||||
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "Blob", "Location", "CssStyleDeclaration", "Event", "EventTarget", "BeforeUnloadEvent", "ClipboardEvent", "DataTransfer", "FileList", "File", "DomStringList", "IdbFactory", "IdbOpenDbRequest", "IdbRequest", "IdbDatabase", "IdbObjectStore", "IdbTransaction", "IdbTransactionMode", "MessageEvent", "UrlSearchParams", "CustomEvent", "CustomEventInit"] }
|
||||
|
||||
[dev-dependencies]
|
||||
# The in-memory settings files the host-author trial runs over.
|
||||
craft = { workspace = true, features = ["settings-testing"] }
|
||||
|
||||
@@ -4,17 +4,17 @@
|
||||
//! The crate owns the JavaScript side (`request`, `execute`, `commands`, `docInspect`, `uiInspect`,
|
||||
//! `screenshot`, as promises with a timeout). This module is WordCraft's part: a [`Request`] that
|
||||
//! queues a [`ControlRequest`] for the app, which answers it on its next frame, and waits for the
|
||||
//! reply. WordCraft's control request has no abandon state, so a call the page gave up on still runs
|
||||
//! when the app reaches it, as it does for a desktop client that timed out.
|
||||
//! reply. A call the page gave up on still runs when the app reaches it, as it does for a desktop
|
||||
//! client that timed out.
|
||||
|
||||
use std::rc::Rc;
|
||||
use std::sync::mpsc::{Receiver, TryRecvError, channel};
|
||||
|
||||
use craft_web_api::methods::Methods;
|
||||
use craft_web_api::page::{PageApi, Request};
|
||||
use craft::automation::control::ControlRequest;
|
||||
use craft::web_api::methods::Methods;
|
||||
use craft::web_api::page::{PageApi, Request};
|
||||
use serde_json::{Value, json};
|
||||
use wasm_bindgen_futures::JsFuture;
|
||||
use wordcraft_ui_egui::ControlRequest;
|
||||
|
||||
/// The app id in `window.<app>`.
|
||||
const APP: &str = "wordcraft";
|
||||
@@ -23,7 +23,7 @@ const APP: &str = "wordcraft";
|
||||
const POLL_MS: i32 = 16;
|
||||
|
||||
/// Put `window.wordcraft` on the page and return the queue the app drains each frame (hand it to
|
||||
/// `WordApp::with_control`). An existing `window.wordcraft` keeps the functions it already has.
|
||||
/// `ControlChannel::new`). An existing `window.wordcraft` keeps the functions it already has.
|
||||
pub fn install(ctx: egui::Context) -> Receiver<ControlRequest> {
|
||||
let (queue, requests) = channel::<ControlRequest>();
|
||||
let request: Request = Rc::new(move |method, params| {
|
||||
|
||||
+112
-23
@@ -30,10 +30,18 @@
|
||||
//! to the host rather than downloaded, the host guards leaving the page, and `?author=` names the
|
||||
//! user for comments and tracked changes.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
|
||||
use craft_web_host::web::{FileData, Host, Message};
|
||||
use wordcraft_ui_egui::{Inbox, Services, WordApp};
|
||||
use craft::host::{FileError, Files, PendingPick, PickId, PickRequest, Picked, WriteIntent};
|
||||
use craft::platform::browser_files::BrowserFiles;
|
||||
use craft::platform::open::{DroppedFile, IntakeSender};
|
||||
use craft::web_host::web::{FileData, Host, Message};
|
||||
use wordcraft_ui_egui::{Services, WordApp};
|
||||
|
||||
/// The app id in the host messages (`wordcraft:ready`).
|
||||
const APP: &str = "wordcraft";
|
||||
@@ -47,6 +55,12 @@ const MAX_OPEN_BYTES: u64 = 512 << 20;
|
||||
/// The longest user name taken from `?author=`.
|
||||
const MAX_AUTHOR_CHARS: usize = 200;
|
||||
|
||||
thread_local! {
|
||||
/// The page's bridge, for [`HostedFiles`]: `Files` is `Send + Sync` but the page host is not. The browser
|
||||
/// runs everything on one thread, so a save, called in the pass of the user's gesture, reaches it here.
|
||||
static BRIDGE: RefCell<Option<Bridge>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Bridge {
|
||||
host: Rc<Host>,
|
||||
@@ -60,17 +74,11 @@ impl Bridge {
|
||||
Some(Self { host: Rc::new(Host::connect(APP, canvas)?) })
|
||||
}
|
||||
|
||||
/// Hand saved and exported files to the host instead of downloading them, report unsaved
|
||||
/// changes to it, and hear the files it sends.
|
||||
pub fn connect(&self, services: &mut Services, inbox: Inbox, ctx: egui::Context) {
|
||||
self.listen(inbox, ctx);
|
||||
let bridge = self.clone();
|
||||
services.host_save = Some(Box::new(move |name: &str, bytes: &[u8], save_as: bool| bridge.post_save(name, bytes, save_as)));
|
||||
// Anything else that would download goes to the host too.
|
||||
let bridge = self.clone();
|
||||
services.download = Some(Box::new(move |name: &str, bytes: &[u8]| bridge.post_save(name, bytes, false)));
|
||||
// The browser's save picker is never used, so no save finishes later.
|
||||
services.async_saves = None;
|
||||
/// Report unsaved changes to the host page, hear the files it sends, and let [`HostedFiles`]
|
||||
/// hand it the saves.
|
||||
pub fn connect(&self, services: &mut Services, intake: IntakeSender) {
|
||||
self.listen(intake);
|
||||
BRIDGE.with(|b| *b.borrow_mut() = Some(self.clone()));
|
||||
// The crate does not repeat a state it already reported.
|
||||
let host = self.host.clone();
|
||||
services.on_dirty = Some(Box::new(move |dirty: bool| host.post_dirty(dirty)));
|
||||
@@ -94,25 +102,25 @@ impl Bridge {
|
||||
}
|
||||
|
||||
fn post_save(&self, path: &str, bytes: &[u8], save_as: bool) -> Result<(), String> {
|
||||
let name = std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| path.to_string());
|
||||
let name = Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| path.to_string());
|
||||
self.host.post_save(&name, bytes, None, save_as)
|
||||
}
|
||||
|
||||
/// Hear `wordcraft:open` and queue the file like a dropped one.
|
||||
fn listen(&self, inbox: Inbox, ctx: egui::Context) {
|
||||
fn listen(&self, intake: IntakeSender) {
|
||||
self.host.listen(move |message| {
|
||||
if let Message::Open { name, data } = message {
|
||||
deliver_open(&inbox, &ctx, &name, &data);
|
||||
deliver_open(&intake, &name, &data);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// The file an open message carries, pushed onto the inbox for the next frame, like a dropped
|
||||
/// file. A host's file is untrusted input: an oversized one is refused before it is copied into
|
||||
/// the app's memory (the data's own length, not the host's claim). The crate has cleaned the name
|
||||
/// (and cut it to 255 characters); a blank one comes as `document` and becomes `Document.docx`.
|
||||
fn deliver_open(inbox: &Inbox, ctx: &egui::Context, name: &str, data: &FileData) {
|
||||
/// The file an open message carries, queued for the next frame like a dropped file. A host's file
|
||||
/// is untrusted input: an oversized one is refused before it is copied into the app's memory (the
|
||||
/// data's own length, not the host's claim). The crate has cleaned the name (and cut it to 255
|
||||
/// characters); a blank one comes as `document` and becomes `Document.docx`.
|
||||
fn deliver_open(intake: &IntakeSender, name: &str, data: &FileData) {
|
||||
let name = if name == "document" { DEFAULT_NAME } else { name }.to_string();
|
||||
let FileData::Bytes(array) = data else {
|
||||
log::warn!("host file {name} came as a File; WordCraft reads bytes only; not opened");
|
||||
@@ -122,6 +130,87 @@ fn deliver_open(inbox: &Inbox, ctx: &egui::Context, name: &str, data: &FileData)
|
||||
log::warn!("host file is {} bytes, over the {} MiB host open limit; not opened", data.size(), MAX_OPEN_BYTES >> 20);
|
||||
return;
|
||||
}
|
||||
inbox.lock().unwrap_or_else(|e| e.into_inner()).push((name, array.to_vec()));
|
||||
ctx.request_repaint();
|
||||
let file = DroppedFile { path: None, name, bytes: Some(Arc::from(array.to_vec())) };
|
||||
intake.dropped(vec![file]);
|
||||
}
|
||||
|
||||
/// The files of a hosted page: reads go to the browser's files, but a save goes to the host page,
|
||||
/// which stores it, so it answers at once.
|
||||
pub struct HostedFiles {
|
||||
inner: Arc<BrowserFiles>,
|
||||
/// Save answers by the id the inner files issued for them.
|
||||
answers: Mutex<HashMap<u64, Picked>>,
|
||||
}
|
||||
|
||||
impl HostedFiles {
|
||||
/// Hosted files over the browser's.
|
||||
pub fn new(inner: Arc<BrowserFiles>) -> Self {
|
||||
Self { inner, answers: Mutex::new(HashMap::new()) }
|
||||
}
|
||||
}
|
||||
|
||||
impl Files for HostedFiles {
|
||||
fn pick(&self, request: PickRequest) -> PickId {
|
||||
self.inner.pick(request)
|
||||
}
|
||||
|
||||
fn take_answer(&self, id: PickId) -> Option<Picked> {
|
||||
if let Some(answer) = self.answers.lock().unwrap_or_else(|e| e.into_inner()).remove(&id.0) {
|
||||
return Some(answer);
|
||||
}
|
||||
self.inner.take_answer(id)
|
||||
}
|
||||
|
||||
fn forget(&self, id: PickId) {
|
||||
if self.answers.lock().unwrap_or_else(|e| e.into_inner()).remove(&id.0).is_none() {
|
||||
self.inner.forget(id);
|
||||
}
|
||||
}
|
||||
|
||||
fn pending_pick(&self) -> Option<PendingPick> {
|
||||
self.inner.pending_pick()
|
||||
}
|
||||
|
||||
fn read(&self, path: &Path) -> Result<Vec<u8>, FileError> {
|
||||
self.inner.read(path)
|
||||
}
|
||||
|
||||
fn write(&self, path: &Path, bytes: &[u8], intent: WriteIntent) -> Result<bool, FileError> {
|
||||
self.inner.write(path, bytes, intent)
|
||||
}
|
||||
|
||||
fn last_folder(&self, purpose: &str) -> Option<PathBuf> {
|
||||
self.inner.last_folder(purpose)
|
||||
}
|
||||
|
||||
fn save(&self, request: PickRequest, bytes: Vec<u8>) -> PickId {
|
||||
let name = request.file_name.clone().unwrap_or_else(|| DEFAULT_NAME.to_string());
|
||||
let sent = BRIDGE.with(|b| match b.borrow().as_ref() {
|
||||
Some(bridge) => bridge.post_save(&name, &bytes, request.save_as),
|
||||
None => Err("no host page".to_string()),
|
||||
});
|
||||
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 },
|
||||
// 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),
|
||||
};
|
||||
// The inner files own the id space: a Folder pick is answered `Unavailable` at once, so it
|
||||
// opens no picker and only yields an id, which is released and reused for this answer.
|
||||
let id = self.inner.pick(PickRequest::folder("hosted-save"));
|
||||
self.inner.forget(id);
|
||||
self.answers.lock().unwrap_or_else(|e| e.into_inner()).insert(id.0, answer);
|
||||
id
|
||||
}
|
||||
|
||||
/// The host page opens documents, so no picker is offered.
|
||||
fn can_pick(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn browser_saves(&self) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,8 +5,9 @@
|
||||
//! directory (output in `dist/web`).
|
||||
//!
|
||||
//! Differences from the desktop app: no TCP control channel; Open and Insert › Pictures use the
|
||||
//! browser file picker (bytes arrive through `Services::inbox`); Save and Export download.
|
||||
//! Preferences (theme, interface size, editing options…) are kept in `localStorage` (`prefs`).
|
||||
//! browser file picker (bytes arrive through the host's `Files`); Save and Export download.
|
||||
//! Preferences (theme, interface size, editing options…) are kept by the settings store in
|
||||
//! `localStorage` (`prefs`).
|
||||
//! URL flags: `?webgl` forces WebGL2; `?sample` opens the sample document.
|
||||
//! `?host=parent` (inside an `<iframe>`) talks to a same-origin parent page instead: it sends the
|
||||
//! document to open and stores what WordCraft saves (`host`). A page can also host WordCraft in
|
||||
@@ -17,8 +18,6 @@
|
||||
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
mod prefs;
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
mod save_fallback;
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod api;
|
||||
|
||||
+69
-104
@@ -1,129 +1,94 @@
|
||||
//! Preferences between visits (#2132): the same [`UiState`] the desktop app keeps in `ui.json`
|
||||
//! (theme, interface size, recent symbols, editing options…), kept in the browser's
|
||||
//! `localStorage` under [`KEY`]. Restored at startup; written back whenever it changes, so a
|
||||
//! reload or a closed tab keeps the last setting (browsers don't reliably run exit code).
|
||||
//! Preferences between visits (#2132): the same [`Prefs`] the desktop app keeps in its settings
|
||||
//! file (theme, interface size, recent symbols, editing options…), kept by the settings store in the
|
||||
//! browser's `localStorage`. A value stored by an earlier build under `wordcraft.ui` is imported once.
|
||||
|
||||
use wordcraft_ui_egui::{UiState, WordApp};
|
||||
use craft::settings::SharedSettings;
|
||||
use wordcraft_ui_egui::prefs::Prefs;
|
||||
|
||||
/// The `localStorage` key.
|
||||
#[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
|
||||
pub const KEY: &str = "wordcraft.ui";
|
||||
/// Largest stored value read back (`localStorage` holds about 5 MB per site).
|
||||
const MAX_STORED: usize = 4 << 20;
|
||||
/// Opens the settings store over the browser's `localStorage`. Changes are written at once on the
|
||||
/// next tick: a reload or closed tab never runs exit code.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub fn open() -> (SharedSettings<Prefs>, craft::settings::LoadReport) {
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
/// Apply preferences stored on an earlier visit. Missing, oversized or unreadable values leave
|
||||
/// the defaults.
|
||||
pub fn restore(app: &mut WordApp, stored: Option<&str>) {
|
||||
if let Some(s) = stored.filter(|s| s.len() <= MAX_STORED)
|
||||
&& let Some(ui) = UiState::from_json(s.as_bytes())
|
||||
{
|
||||
app.apply_prefs(ui);
|
||||
}
|
||||
use craft::settings::{LegacyFile, LocalStorageFiles, Location, OpenOptions, SettingsStore};
|
||||
use wordcraft_ui_egui::prefs::legacy_ui_json;
|
||||
|
||||
/// Largest stored value read back (`localStorage` holds about 5 MB per site).
|
||||
const MAX_STORED: usize = 4 << 20;
|
||||
let options = OpenOptions::new(Location::Dir("wordcraft".into()))
|
||||
.files(Arc::new(LocalStorageFiles::new(MAX_STORED)))
|
||||
.debounce(Duration::ZERO)
|
||||
.legacy(vec![LegacyFile { path: "wordcraft.ui".into(), parse: legacy_ui_json }]);
|
||||
let (store, report) = SettingsStore::open_with(options);
|
||||
(SharedSettings::new(store), report)
|
||||
}
|
||||
|
||||
/// Tracks what was last written, so the store is written only when a preference changed.
|
||||
#[derive(Default)]
|
||||
pub struct PrefsSync {
|
||||
last: Option<String>,
|
||||
/// A host page's name for the user (`?author=`) and the user's own, which is stored in its
|
||||
/// place while the user keeps the host's.
|
||||
host_author: Option<(String, String)>,
|
||||
/// A host page's name for the user (`?author=`) and the user's own. The session signs with the
|
||||
/// host's name, but the store keeps the user's own, which a visit outside the host would restore.
|
||||
pub struct HostAuthor {
|
||||
host: String,
|
||||
own: String,
|
||||
}
|
||||
|
||||
impl PrefsSync {
|
||||
/// Starts from what is already stored, so restoring doesn't write it straight back.
|
||||
pub fn new(stored: Option<String>) -> Self {
|
||||
Self { last: stored, host_author: None }
|
||||
}
|
||||
|
||||
/// The session signs with `host`, a host page's name for the user, but `own` stays the
|
||||
/// stored name. A name the user then chooses in File › Options is stored as usual.
|
||||
impl HostAuthor {
|
||||
/// The rule for a session that signs with `host` while `own` stays stored; `None` when they are
|
||||
/// the same name.
|
||||
#[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
|
||||
pub fn keep_own_author(&mut self, host: &str, own: &str) {
|
||||
if host != own {
|
||||
self.host_author = Some((host.to_string(), own.to_string()));
|
||||
}
|
||||
pub fn new(host: &str, own: &str) -> Option<Self> {
|
||||
(host != own).then(|| Self { host: host.to_string(), own: own.to_string() })
|
||||
}
|
||||
|
||||
/// The JSON to store when the app's preferences differ from what was last written.
|
||||
pub fn changed(&mut self, app: &WordApp) -> Option<String> {
|
||||
let mut prefs = app.prefs();
|
||||
if let Some((host, own)) = &self.host_author
|
||||
&& prefs.author.as_deref() == Some(host.as_str())
|
||||
{
|
||||
prefs.author = Some(own.clone());
|
||||
/// The name to keep in the store in place of `stored`: the user's own when `stored` is the
|
||||
/// host's, `None` when `stored` stays as it is. A name the user chose in File › Options differs
|
||||
/// from the host's and is stored as usual.
|
||||
pub fn stored_author(&self, stored: Option<&str>) -> Option<&str> {
|
||||
(stored == Some(self.host.as_str())).then_some(self.own.as_str())
|
||||
}
|
||||
|
||||
/// Puts the user's own name back into the store where the app wrote the host's.
|
||||
#[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
|
||||
pub fn keep_own_author(&self, settings: &SharedSettings<Prefs>) {
|
||||
let mut store = settings.lock();
|
||||
if let Some(own) = self.stored_author(store.get().author.as_deref()).map(str::to_string) {
|
||||
store.update(|prefs| prefs.author = Some(own));
|
||||
}
|
||||
let json = match serde_json::to_string(&prefs) {
|
||||
Ok(j) => j,
|
||||
Err(e) => {
|
||||
log::warn!("preferences: cannot serialize: {e}");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
if self.last.as_deref() == Some(json.as_str()) {
|
||||
return None;
|
||||
}
|
||||
self.last = Some(json.clone());
|
||||
Some(json)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
use wordcraft_ui_egui::Services;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
fn app() -> WordApp {
|
||||
WordApp::new(wordcraft_engine::Session::new(wordcraft_engine::sample::sample_document()), Services::default())
|
||||
use craft::settings::testing::MemoryFiles;
|
||||
use craft::settings::{Location, OpenOptions, SettingsStore};
|
||||
|
||||
use super::*;
|
||||
|
||||
fn store() -> SharedSettings<Prefs> {
|
||||
let options: OpenOptions<Prefs> =
|
||||
OpenOptions::new(Location::Dir("wordcraft".into())).files(Arc::new(MemoryFiles::new())).debounce(Duration::ZERO);
|
||||
let (store, _report) = SettingsStore::<Prefs>::open_with(options);
|
||||
SharedSettings::new(store)
|
||||
}
|
||||
|
||||
/// A host page's name for the user signs the visit but isn't stored; a name the user then
|
||||
/// chooses is.
|
||||
#[test]
|
||||
fn host_author_is_not_stored() {
|
||||
let mut a = app();
|
||||
a.session.author = "Grace Hopper".into();
|
||||
let mut sync = PrefsSync::new(None);
|
||||
let stored = sync.changed(&a).unwrap();
|
||||
a.session.author = "rob".into();
|
||||
sync.keep_own_author("rob", "Grace Hopper");
|
||||
a.run("ui.theme", json!({"value": "dark"})).unwrap();
|
||||
let json = sync.changed(&a).expect("the theme changed");
|
||||
assert_ne!(json, stored);
|
||||
let mut next = app();
|
||||
restore(&mut next, Some(&json));
|
||||
assert_eq!(next.session.author, "Grace Hopper");
|
||||
a.session.author = "Rob Hones".into();
|
||||
let json = sync.changed(&a).expect("the user chose a name");
|
||||
let mut next = app();
|
||||
restore(&mut next, Some(&json));
|
||||
assert_eq!(next.session.author, "Rob Hones");
|
||||
}
|
||||
|
||||
/// #2132: dark mode chosen on one visit is there after a reload.
|
||||
#[test]
|
||||
fn dark_mode_survives_reload() {
|
||||
let mut first = app();
|
||||
let mut sync = PrefsSync::new(None);
|
||||
let initial = sync.changed(&first);
|
||||
assert!(initial.is_some(), "first frame stores the preferences");
|
||||
assert_eq!(sync.changed(&first), None, "unchanged preferences are not rewritten");
|
||||
first.run("ui.theme", json!({"value": "dark"})).unwrap();
|
||||
let stored = sync.changed(&first).expect("the theme change is stored");
|
||||
|
||||
let mut reloaded = app();
|
||||
restore(&mut reloaded, Some(&stored));
|
||||
assert_eq!(reloaded.ui.theme, wordcraft_ui_egui::theme::Appearance::Dark);
|
||||
assert_eq!(PrefsSync::new(Some(stored)).changed(&reloaded), None, "restoring doesn't write back");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn junk_storage_keeps_defaults() {
|
||||
for junk in [None, Some(""), Some("not json"), Some("[1,2]"), Some("{\"theme\":42}")] {
|
||||
let mut a = app();
|
||||
restore(&mut a, junk);
|
||||
assert_eq!(a.ui.theme, wordcraft_ui_egui::theme::Appearance::System, "junk keeps the default appearance");
|
||||
}
|
||||
let settings = store();
|
||||
settings.lock().update(|p| p.author = Some("Grace Hopper".into()));
|
||||
let rule = HostAuthor::new("rob", "Grace Hopper").unwrap();
|
||||
// The app writes the session's author, the host's name, into the store.
|
||||
settings.lock().update(|p| p.author = Some("rob".into()));
|
||||
rule.keep_own_author(&settings);
|
||||
assert_eq!(settings.lock().get().author.as_deref(), Some("Grace Hopper"));
|
||||
// The user chooses a name of their own.
|
||||
settings.lock().update(|p| p.author = Some("Rob Hones".into()));
|
||||
rule.keep_own_author(&settings);
|
||||
assert_eq!(settings.lock().get().author.as_deref(), Some("Rob Hones"));
|
||||
assert!(HostAuthor::new("same", "same").is_none());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,46 +0,0 @@
|
||||
//! Save-picker rejection policy, shared with native tests of the browser fallback.
|
||||
|
||||
use wordcraft_ui_egui::async_saves::SaveOutcome;
|
||||
|
||||
/// A cancelled picker ends the save. Other picker failures try the browser download path.
|
||||
/// Write/close errors do not pass through this function: they retain their own failure.
|
||||
pub(crate) fn picker_rejected(name: &str, download: impl FnOnce() -> Result<(), String>) -> SaveOutcome {
|
||||
if name == "AbortError" {
|
||||
SaveOutcome::Cancelled
|
||||
} else {
|
||||
match download() {
|
||||
Ok(()) => SaveOutcome::Saved,
|
||||
Err(error) => SaveOutcome::Failed(error),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn unavailable_picker_downloads_once() {
|
||||
for name in ["SecurityError", "NotSupportedError", "TypeError", ""] {
|
||||
let mut calls = 0;
|
||||
let outcome = picker_rejected(name, || {
|
||||
calls += 1;
|
||||
Ok(())
|
||||
});
|
||||
assert_eq!(outcome, SaveOutcome::Saved);
|
||||
assert_eq!(calls, 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancelled_picker_never_downloads() {
|
||||
let outcome = picker_rejected("AbortError", || panic!("cancel must not download"));
|
||||
assert_eq!(outcome, SaveOutcome::Cancelled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_fallback_remains_a_failed_save() {
|
||||
let outcome = picker_rejected("SecurityError", || Err("download unavailable".into()));
|
||||
assert_eq!(outcome, SaveOutcome::Failed("download unavailable".into()));
|
||||
}
|
||||
}
|
||||
+132
-380
@@ -1,18 +1,26 @@
|
||||
//! The browser shell: web `Services`, drag-and-drop, the unsaved-changes guard and the eframe
|
||||
//! web runner.
|
||||
//! The browser shell: the framework host (files, intake, clipboard, print, settings), the
|
||||
//! unsaved-changes guard and the eframe web runner.
|
||||
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft::automation::control::ControlChannel;
|
||||
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::print::spool::Spool;
|
||||
use craft::settings::SharedSettings;
|
||||
use craft::ui::InstallSpec;
|
||||
use craft::ui::shell::embed;
|
||||
use craft::window::system::NoWindows;
|
||||
use wasm_bindgen::JsCast as _;
|
||||
use wordcraft_engine::Session;
|
||||
use wordcraft_ui_egui::async_saves::{AsyncSaves, SaveOutcome};
|
||||
use wordcraft_ui_egui::{Inbox, Services, WordApp};
|
||||
use wordcraft_ui_egui::prefs::Prefs;
|
||||
use wordcraft_ui_egui::{Services, WordApp};
|
||||
|
||||
const DOC_EXTS: &[&str] =
|
||||
&["docx", "docm", "dotx", "dotm", "doc", "dot", "odt", "ott", "fodt", "rtf", "txt", "md", "html", "htm", "mht", "mhtml", "tex", "json", "xml"];
|
||||
const IMAGE_EXTS: &[&str] = &["png", "jpg", "jpeg", "gif", "webp", "bmp", "wmf", "emf"];
|
||||
const RECIPIENT_EXTS: &[&str] = wordcraft_engine::cmd::mailings::RECIPIENT_EXTENSIONS;
|
||||
mod font_store;
|
||||
const CANVAS_ID: &str = "wordcraft_canvas";
|
||||
const LOADING_ID: &str = "wordcraft_loading";
|
||||
@@ -36,12 +44,6 @@ pub fn start() {
|
||||
let bridge = crate::host::Bridge::detect(&canvas);
|
||||
let app_bridge = bridge.clone();
|
||||
let dirty = Rc::new(Cell::new(false));
|
||||
let saves = AsyncSaves::default();
|
||||
if bridge.is_none()
|
||||
&& let Err(e) = guard_unload(dirty.clone(), saves.clone())
|
||||
{
|
||||
log::error!("no unsaved-changes guard: {e}");
|
||||
}
|
||||
let mut options = eframe::WebOptions::default();
|
||||
if query().contains("webgl")
|
||||
&& let eframe::egui_wgpu::WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup
|
||||
@@ -56,56 +58,97 @@ pub fn start() {
|
||||
if let Some(rs) = &cc.wgpu_render_state {
|
||||
log::info!("wordcraft-web: wgpu backend {:?}", rs.adapter.get_info().backend);
|
||||
}
|
||||
let ctx = cc.egui_ctx.clone();
|
||||
// Fonts the user added on an earlier visit (#582); the app notices them arrive.
|
||||
font_store::load_all(cc.egui_ctx.clone());
|
||||
let inbox: Inbox = Inbox::default();
|
||||
let pasted: Inbox = Inbox::default();
|
||||
if let Err(e) = listen_for_pasted_pictures(pasted.clone(), cc.egui_ctx.clone()) {
|
||||
font_store::load_all(ctx.clone());
|
||||
|
||||
// The clipboard: the browser's paste event feeds it; a late paste (a picture read
|
||||
// asynchronously) arrives through `late_offers`. The pass clock counts frames, so a late
|
||||
// offer is readable in every pass of its frame.
|
||||
let frame_ctx = ctx.clone();
|
||||
let copy_ctx = ctx.clone();
|
||||
let event_clipboard = EventClipboard::new(move || frame_ctx.cumulative_frame_nr(), move |flavors| copy_out(©_ctx, flavors))
|
||||
.with_wake(waker(&ctx));
|
||||
let late_offers = event_clipboard.late_offers();
|
||||
if let Err(e) = listen_for_pasted_pictures(late_offers) {
|
||||
log::error!("pasting pictures is unavailable: {e}");
|
||||
}
|
||||
|
||||
// The browser's locale picks the new document's paper, the units and the
|
||||
// decimal separator (#838).
|
||||
let region = wordcraft_ui_egui::i18n::system_region();
|
||||
|
||||
// The stored interface language picks the fonts' script coverage, so the settings open first.
|
||||
let (settings, report) = crate::prefs::open();
|
||||
if report.has_problems() {
|
||||
log::warn!("preferences: {report:?}");
|
||||
}
|
||||
let lang = wordcraft_ui_egui::i18n::Lang::from_pref(&settings.lock().get().language);
|
||||
let spec = InstallSpec::new(craft::host::target::ShellInfo::current(), Arc::new(NoWindows))
|
||||
.app_id("wordcraft")
|
||||
.system(SystemReader::start(waker(&ctx)))
|
||||
.clipboard(Clipboard::new(event_clipboard));
|
||||
if let Err(e) = embed::install(&ctx, spec, &wordcraft_ui_egui::ui_fonts(lang)) {
|
||||
log::error!("wordcraft-web: the UI runtime did not install: {e:?}");
|
||||
}
|
||||
|
||||
// Files: the browser's pickers and downloads; a host page stores what is saved instead.
|
||||
let browser = Arc::new(BrowserFiles::new(waker(&ctx)));
|
||||
if app_bridge.is_none()
|
||||
&& let Err(e) = guard_unload(dirty.clone(), browser.clone())
|
||||
{
|
||||
log::error!("no unsaved-changes guard: {e}");
|
||||
}
|
||||
let files: Arc<dyn Files> =
|
||||
if app_bridge.is_some() { Arc::new(crate::host::HostedFiles::new(browser.clone())) } else { browser.clone() };
|
||||
|
||||
let host = Arc::new(
|
||||
Host::builder(wordcraft_ui_egui::APP)
|
||||
.i18n(wordcraft_ui_egui::i18n::catalogs())
|
||||
.files(files)
|
||||
.settings(Arc::new(settings.clone()))
|
||||
.lang(lang.craft_lang())
|
||||
.build(),
|
||||
);
|
||||
|
||||
let (intake, sender) = FileIntake::new(Wake::new(waker(&ctx)));
|
||||
|
||||
// In host mode the parent sends the document to edit; no sample meanwhile.
|
||||
let sample = app_bridge.is_none() && query().contains("sample");
|
||||
let doc = if sample { wordcraft_engine::sample::sample_document() } else { wordcraft_engine::blank_document(®ion) };
|
||||
let mut session = Session::new(doc);
|
||||
session.system_region = region;
|
||||
let messages = Rc::new(RefCell::new(Vec::new()));
|
||||
let mut services = services(inbox.clone(), cc.egui_ctx.clone(), dirty, saves.clone(), messages.clone());
|
||||
let mut services = services(&host, ctx.clone(), dirty, messages.clone(), intake);
|
||||
if let Some(bridge) = &app_bridge {
|
||||
bridge.connect(&mut services, inbox.clone(), cc.egui_ctx.clone());
|
||||
bridge.connect(&mut services, sender.clone());
|
||||
}
|
||||
let control = crate::api::install(cc.egui_ctx.clone());
|
||||
let mut app = WordApp::new(session, services).with_control(control);
|
||||
// Pasted pictures wait apart from dropped files: the app inserts one only when the page is the edit target (#1349).
|
||||
app.services.pasted = Some(pasted);
|
||||
let requests = crate::api::install(ctx.clone());
|
||||
let mut app =
|
||||
WordApp::new(session, services).with_host(host).with_settings(settings.clone()).with_control(ControlChannel::new(requests));
|
||||
app.autosave = false;
|
||||
app.tell_about_font_downloads();
|
||||
// Preferences from an earlier visit (#2132), as the desktop app reads `ui.json`.
|
||||
let stored = stored_prefs();
|
||||
crate::prefs::restore(&mut app, stored.as_deref());
|
||||
// A region chosen in File › Options replaces the browser's for the first blank
|
||||
// document too (#838).
|
||||
if !sample && app.session.prefs.region.is_some() {
|
||||
let doc = app.session.blank_document();
|
||||
app.session.set_document(doc);
|
||||
}
|
||||
let mut prefs = crate::prefs::PrefsSync::new(stored);
|
||||
// No document to show: start on File › Home, as the desktop app does (#766).
|
||||
if !sample {
|
||||
app.start_screen();
|
||||
}
|
||||
// The host's name for the user signs this visit's work, but isn't stored as the
|
||||
// browser's own preference, which a visit outside the host would restore.
|
||||
let mut author = None;
|
||||
if app_bridge.is_some()
|
||||
&& let Some(author) = query_param("author")
|
||||
&& let Some(name) = query_param("author")
|
||||
{
|
||||
let own = app.session.author.clone();
|
||||
crate::host::Bridge::set_author(&mut app, &author);
|
||||
prefs.keep_own_author(&app.session.author, &own);
|
||||
crate::host::Bridge::set_author(&mut app, &name);
|
||||
author = crate::prefs::HostAuthor::new(&app.session.author, &own);
|
||||
}
|
||||
Ok(Box::new(WebShell { app, inbox, messages, prefs }))
|
||||
Ok(Box::new(WebShell { app, sender, messages, settings, author }))
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
@@ -133,75 +176,69 @@ fn query_param(key: &str) -> Option<String> {
|
||||
web_sys::UrlSearchParams::new_with_str(&query()).ok()?.get(key)
|
||||
}
|
||||
|
||||
/// A wake that asks `ctx` for a frame; callable from any task.
|
||||
fn waker(ctx: &egui::Context) -> impl Fn() + Send + Sync + Clone + 'static {
|
||||
let ctx = ctx.clone();
|
||||
move || ctx.request_repaint()
|
||||
}
|
||||
|
||||
/// The clipboard's copy path: eframe's own text copy is the browser's only write.
|
||||
fn copy_out(ctx: &egui::Context, flavors: &[Flavor]) -> Result<usize, ClipboardError> {
|
||||
let (index, text) = flavors.iter().enumerate().find(|(_, f)| f.mime == TEXT).ok_or(ClipboardError::NoFormat)?;
|
||||
ctx.copy_text(String::from_utf8_lossy(&text.data).into_owned());
|
||||
Ok(index)
|
||||
}
|
||||
|
||||
/// Wraps the app to read dropped files asynchronously (browsers can't read them synchronously)
|
||||
/// and feed them through the inbox.
|
||||
/// and feed them through the intake.
|
||||
struct WebShell {
|
||||
app: WordApp,
|
||||
inbox: Inbox,
|
||||
sender: IntakeSender,
|
||||
messages: Rc<RefCell<Vec<String>>>,
|
||||
prefs: crate::prefs::PrefsSync,
|
||||
}
|
||||
|
||||
fn local_storage() -> Option<web_sys::Storage> {
|
||||
web_sys::window()?.local_storage().ok()?
|
||||
}
|
||||
|
||||
/// The preferences stored on an earlier visit, if the browser allows storage.
|
||||
fn stored_prefs() -> Option<String> {
|
||||
local_storage()?.get_item(crate::prefs::KEY).ok()?
|
||||
settings: SharedSettings<Prefs>,
|
||||
/// Set when a host page named the user: its name is not kept in the stored preferences.
|
||||
author: Option<crate::prefs::HostAuthor>,
|
||||
}
|
||||
|
||||
impl eframe::App for WebShell {
|
||||
/// Runs one browser frame: forwards queued host messages to the status bar, advances the app,
|
||||
/// then writes changed preferences to browser storage immediately, because a reload or closed
|
||||
/// tab never runs the exit path.
|
||||
/// then ticks the settings store, which writes changed preferences to browser storage at once
|
||||
/// (a reload or closed tab never runs an exit path). The browser has no window-close path.
|
||||
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
|
||||
let msgs = std::mem::take(&mut *self.messages.borrow_mut());
|
||||
for msg in msgs {
|
||||
self.app.status(msg);
|
||||
}
|
||||
self.app.logic(ctx);
|
||||
// Store changed preferences straight away: a reload or closed tab runs no exit code (#2132).
|
||||
if let Some(json) = self.prefs.changed(&self.app) {
|
||||
match local_storage() {
|
||||
Some(store) => {
|
||||
if let Err(e) = store.set_item(crate::prefs::KEY, &json) {
|
||||
log::warn!("preferences: cannot save: {e:?}");
|
||||
}
|
||||
}
|
||||
None => log::warn!("preferences: browser storage is unavailable"),
|
||||
}
|
||||
if let Some(author) = &self.author {
|
||||
author.keep_own_author(&self.settings);
|
||||
}
|
||||
self.settings.lock().tick(web_time::Instant::now());
|
||||
}
|
||||
|
||||
/// Forwards this frame's raw browser input to the app before widgets run.
|
||||
/// Takes the browser's dropped files once per frame, before any pass, and spawns asynchronous
|
||||
/// byte reads into the intake (browsers can't read them synchronously); then hands the runtime's
|
||||
/// output to the app and gives the coming passes the app's input.
|
||||
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
|
||||
self.app.raw_input_hook(ctx, raw);
|
||||
for f in std::mem::take(&mut raw.dropped_files) {
|
||||
let sender = self.sender.clone();
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
let name = f.path().file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "dropped".into());
|
||||
match f.bytes_async().await {
|
||||
Ok(bytes) => {
|
||||
let file = DroppedFile { path: None, name, bytes: Some(Arc::from(bytes)) };
|
||||
sender.dropped(vec![file]);
|
||||
}
|
||||
Err(e) => log::error!("couldn't read dropped file {name}: {e}"),
|
||||
}
|
||||
});
|
||||
}
|
||||
embed::before_input(ctx, |out| self.app.frame_input(out));
|
||||
}
|
||||
|
||||
/// Draws the app. On the first pass of a visible frame it takes the browser's dropped files and
|
||||
/// spawns asynchronous byte reads into the inbox; later passes only draw.
|
||||
/// Draws the app.
|
||||
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
|
||||
// Browser drops are input: take them only in the first real UI pass, never in a hidden
|
||||
// `run_logic` tick that still sees the previous shown frame's RawInput.
|
||||
if ui.ctx().current_pass_index() == 0 {
|
||||
let ctx = ui.ctx().clone();
|
||||
let dropped = ctx.input_mut(|i| std::mem::take(&mut i.raw.dropped_files));
|
||||
for f in dropped {
|
||||
let inbox = self.inbox.clone();
|
||||
let ctx = ctx.clone();
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
let name = f.path().file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "dropped".into());
|
||||
match f.bytes_async().await {
|
||||
Ok(bytes) => {
|
||||
inbox.lock().unwrap_or_else(|e| e.into_inner()).push((name, bytes));
|
||||
ctx.request_repaint();
|
||||
}
|
||||
Err(e) => log::error!("couldn't read dropped file {name}: {e}"),
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
// No `embed::before_ui`: it fits and routes a native window, and the page's canvas is neither.
|
||||
self.app.ui(ui);
|
||||
}
|
||||
}
|
||||
@@ -212,10 +249,12 @@ const MAX_PASTED_BYTES: f64 = (200u32 << 20) as f64;
|
||||
const MAX_PASTED_PICTURES: u32 = 20;
|
||||
|
||||
/// Pasting a picture (#45): eframe's paste handler only reads text, so a clipboard holding just
|
||||
/// pictures (a screenshot, a browser's Copy Image) is read here and the pictures arrive through
|
||||
/// the app's `pasted` queue, which inserts them only when the page is the edit target (#1349). A clipboard with text is left to eframe.
|
||||
fn listen_for_pasted_pictures(inbox: Inbox, ctx: egui::Context) -> Result<(), String> {
|
||||
/// pictures (a screenshot, a browser's Copy Image) is read here and offered to the clipboard as a
|
||||
/// late paste; the app inserts it only when the page is the edit target (#1349). A clipboard with
|
||||
/// text is left to eframe.
|
||||
fn listen_for_pasted_pictures(late: LateOffers) -> Result<(), String> {
|
||||
let document = web_sys::window().and_then(|w| w.document()).ok_or("no document")?;
|
||||
let late = Rc::new(late);
|
||||
let on_paste = wasm_bindgen::closure::Closure::<dyn FnMut(web_sys::ClipboardEvent)>::new(move |e: web_sys::ClipboardEvent| {
|
||||
// The target is always eframe's hidden text input while the page has focus; the app decides (#1349).
|
||||
let Some(data) = e.clipboard_data() else { return };
|
||||
@@ -232,15 +271,13 @@ fn listen_for_pasted_pictures(inbox: Inbox, ctx: egui::Context) -> Result<(), St
|
||||
log::warn!("pasted picture is larger than 200 MB; not inserted");
|
||||
continue;
|
||||
}
|
||||
let inbox = inbox.clone();
|
||||
let ctx = ctx.clone();
|
||||
let late = late.clone();
|
||||
let mime = file.type_();
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
match wasm_bindgen_futures::JsFuture::from(file.array_buffer()).await {
|
||||
Ok(buf) => {
|
||||
let bytes = js_sys::Uint8Array::new(&buf).to_vec();
|
||||
// The engine reads the format from the bytes; the name is ignored.
|
||||
inbox.lock().unwrap_or_else(|e| e.into_inner()).push(("pasted.png".into(), bytes));
|
||||
ctx.request_repaint();
|
||||
late.offer(vec![Flavor::new(mime, bytes)]);
|
||||
}
|
||||
Err(e) => log::error!("couldn't read the pasted picture: {e:?}"),
|
||||
}
|
||||
@@ -254,51 +291,13 @@ fn listen_for_pasted_pictures(inbox: Inbox, ctx: egui::Context) -> Result<(), St
|
||||
}
|
||||
|
||||
/// `dirty` is the flag the `beforeunload` guard reads ([`guard_unload`]).
|
||||
fn services(inbox: Inbox, ctx: egui::Context, dirty: Rc<Cell<bool>>, saves: AsyncSaves, messages: Rc<RefCell<Vec<String>>>) -> Services {
|
||||
let open_inbox = inbox.clone();
|
||||
let save_ctx = ctx.clone();
|
||||
let font_ctx = ctx.clone();
|
||||
let font_messages = messages.clone();
|
||||
fn services(host: &Host, ctx: egui::Context, dirty: Rc<Cell<bool>>, messages: Rc<RefCell<Vec<String>>>, intake: FileIntake) -> Services {
|
||||
let font_ctx = ctx;
|
||||
let font_messages = messages;
|
||||
Services {
|
||||
open_async: Some(Box::new(move |purpose: &str| {
|
||||
let inbox = open_inbox.clone();
|
||||
let ctx = ctx.clone();
|
||||
let dialog = if purpose == "picture" {
|
||||
rfd::AsyncFileDialog::new().add_filter("Pictures", IMAGE_EXTS)
|
||||
} else if purpose == "font" {
|
||||
rfd::AsyncFileDialog::new().add_filter("Fonts", wordcraft_fonts::FONT_FILE_EXTS)
|
||||
} else if purpose == "recipients" {
|
||||
rfd::AsyncFileDialog::new().add_filter("Recipient lists", RECIPIENT_EXTS)
|
||||
} else {
|
||||
rfd::AsyncFileDialog::new().add_filter("Documents", DOC_EXTS)
|
||||
};
|
||||
let many = purpose == "font";
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
// Add Font takes every selected file (#1789); the others one.
|
||||
let files = if many { dialog.pick_files().await.unwrap_or_default() } else { dialog.pick_file().await.into_iter().collect() };
|
||||
for file in files.into_iter().take(MAX_PICKED_FILES) {
|
||||
let mut bytes = file.read().await;
|
||||
let mut pending = inbox.lock().unwrap_or_else(|e| e.into_inner());
|
||||
// Fonts waiting for the app to drain them stay under a byte cap. A file
|
||||
// over it is queued empty, so Add Font reports that file on its own.
|
||||
let held: usize = pending.iter().map(|(_, b)| b.len()).fold(0, usize::saturating_add);
|
||||
if many && held.saturating_add(bytes.len()) > MAX_PENDING_PICKED_BYTES {
|
||||
bytes = Vec::new();
|
||||
}
|
||||
pending.push((file.file_name(), bytes));
|
||||
drop(pending);
|
||||
ctx.request_repaint();
|
||||
}
|
||||
});
|
||||
})),
|
||||
// Exports ask for a name; the browser decides where the download goes.
|
||||
pick_save: Some(Box::new(|name: &str| Some(name.to_string()))),
|
||||
async_saves: Some(saves.clone()),
|
||||
download: Some(Box::new(move |path: &str, bytes: &[u8]| download(&saves, &save_ctx, path, bytes))),
|
||||
print: Some(Box::new(print_pdf)),
|
||||
inbox: Some(inbox),
|
||||
print: Some(Spool::new(host.jobs_shared().clone())),
|
||||
intake: Some(intake),
|
||||
on_dirty: Some(Box::new(move |d| dirty.set(d))),
|
||||
animations_enabled: Some(animations_enabled()),
|
||||
store_font: Some(Box::new(font_store::store)),
|
||||
forget_font: Some(Box::new(font_store::forget)),
|
||||
load_system_fonts: Some(Box::new(move || {
|
||||
@@ -308,10 +307,6 @@ fn services(inbox: Inbox, ctx: egui::Context, dirty: Rc<Cell<bool>>, saves: Asyn
|
||||
}
|
||||
}
|
||||
|
||||
/// Most files one multi-select pick (Add Font) reads.
|
||||
const MAX_PICKED_FILES: usize = 2000;
|
||||
/// Most bytes of picked fonts held in the inbox before the app drains them.
|
||||
const MAX_PENDING_PICKED_BYTES: usize = 256 << 20;
|
||||
/// Most local fonts one Load System Installed Fonts installs (a designer's machine has thousands).
|
||||
const MAX_SYSTEM_FONTS: usize = 500;
|
||||
/// Most font bytes one Load System Installed Fonts reads into memory (wasm memory is small).
|
||||
@@ -411,21 +406,13 @@ fn load_system_fonts(ctx: egui::Context, messages: Rc<RefCell<Vec<String>>>) {
|
||||
});
|
||||
}
|
||||
|
||||
/// Whether the system has animation effects on, as the browser passes it on: off while the
|
||||
/// `prefers-reduced-motion: reduce` media query matches. `None` when the browser can't say. The
|
||||
/// query is made once and asked every frame; it follows the system's setting by itself.
|
||||
fn animations_enabled() -> Box<dyn Fn() -> Option<bool>> {
|
||||
let reduce = web_sys::window().and_then(|w| w.match_media("(prefers-reduced-motion: reduce)").ok().flatten());
|
||||
Box::new(move || reduce.as_ref().map(|query| !query.matches()))
|
||||
}
|
||||
|
||||
/// Closing, reloading or leaving the tab with unsaved changes asks first. Browsers show their own
|
||||
/// confirmation (a page can only ask for it), so there is no Save button: Cancel, then File › Save.
|
||||
fn guard_unload(dirty: Rc<Cell<bool>>, saves: AsyncSaves) -> Result<(), String> {
|
||||
fn guard_unload(dirty: Rc<Cell<bool>>, files: Arc<BrowserFiles>) -> Result<(), String> {
|
||||
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() || saves.pending() > 0 {
|
||||
if dirty.get() || files.pending_pick().is_some() {
|
||||
e.prevent_default();
|
||||
// Older browsers ask only when `returnValue` is set.
|
||||
e.set_return_value("unsaved changes");
|
||||
@@ -436,238 +423,3 @@ fn guard_unload(dirty: Rc<Cell<bool>>, saves: AsyncSaves) -> Result<(), String>
|
||||
on_unload.forget();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Trigger a browser save dialog or download of `bytes` named after the last component of `path`.
|
||||
fn download(saves: &AsyncSaves, ctx: &egui::Context, path: &str, bytes: &[u8]) -> Result<(), String> {
|
||||
let name = std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "document".into());
|
||||
let window = web_sys::window().ok_or("no window")?;
|
||||
|
||||
// On browsers supporting the File System Access API (Chromium: Chrome, Edge, etc.),
|
||||
// `showSaveFilePicker` lets the user choose the save location and filename natively.
|
||||
if let Ok(picker_val) = js_sys::Reflect::get(&window, &wasm_bindgen::JsValue::from_str("showSaveFilePicker"))
|
||||
&& let Ok(picker_fn) = picker_val.dyn_into::<js_sys::Function>()
|
||||
{
|
||||
match trigger_save_file_picker(saves, ctx, &window, &picker_fn, &name, bytes) {
|
||||
Ok(()) => return Ok(()),
|
||||
Err(e) => {
|
||||
log::warn!("showSaveFilePicker failed: {e}; falling back to anchor download");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback for browsers without showSaveFilePicker (e.g. Firefox, Safari):
|
||||
trigger_anchor_download(&window, &name, bytes)
|
||||
}
|
||||
|
||||
fn trigger_save_file_picker(
|
||||
saves: &AsyncSaves,
|
||||
ctx: &egui::Context,
|
||||
window: &web_sys::Window,
|
||||
picker_fn: &js_sys::Function,
|
||||
name: &str,
|
||||
bytes: &[u8],
|
||||
) -> Result<(), String> {
|
||||
let js = |e: wasm_bindgen::JsValue| format!("{e:?}");
|
||||
let ext = std::path::Path::new(name).extension().and_then(std::ffi::OsStr::to_str).unwrap_or("docx").to_ascii_lowercase();
|
||||
let dot_ext = format!(".{ext}");
|
||||
let mime = mime_for(name);
|
||||
|
||||
let accept_obj = js_sys::Object::new();
|
||||
let exts_arr = js_sys::Array::new();
|
||||
exts_arr.push(&wasm_bindgen::JsValue::from_str(&dot_ext));
|
||||
let _ = js_sys::Reflect::set(&accept_obj, &wasm_bindgen::JsValue::from_str(mime), &exts_arr);
|
||||
|
||||
// Our own neutral description: the format's name, as its extension says it.
|
||||
let type_desc = match ext.as_str() {
|
||||
"htm" => "HTML".to_string(),
|
||||
"txt" => "Text".to_string(),
|
||||
e if !e.is_empty() && e.len() <= 8 && e.chars().all(|c| c.is_ascii_alphanumeric()) => e.to_ascii_uppercase(),
|
||||
_ => "Document".to_string(),
|
||||
};
|
||||
|
||||
let type_obj = js_sys::Object::new();
|
||||
let _ = js_sys::Reflect::set(&type_obj, &wasm_bindgen::JsValue::from_str("description"), &wasm_bindgen::JsValue::from_str(&type_desc));
|
||||
let _ = js_sys::Reflect::set(&type_obj, &wasm_bindgen::JsValue::from_str("accept"), &accept_obj);
|
||||
|
||||
let types_arr = js_sys::Array::new();
|
||||
types_arr.push(&type_obj);
|
||||
|
||||
let picker_opts = js_sys::Object::new();
|
||||
let _ = js_sys::Reflect::set(&picker_opts, &wasm_bindgen::JsValue::from_str("suggestedName"), &wasm_bindgen::JsValue::from_str(name));
|
||||
let _ = js_sys::Reflect::set(&picker_opts, &wasm_bindgen::JsValue::from_str("types"), &types_arr);
|
||||
|
||||
// Call showSaveFilePicker synchronously while transient user activation is active:
|
||||
let prom_val = picker_fn.call1(window, &picker_opts).map_err(js)?;
|
||||
let prom: js_sys::Promise = prom_val.dyn_into().map_err(|_| "not a promise".to_string())?;
|
||||
|
||||
let bytes_vec = bytes.to_vec();
|
||||
let window = window.clone();
|
||||
let saves = saves.clone();
|
||||
let ctx = ctx.clone();
|
||||
let name = name.to_string();
|
||||
// The app holds back a Save Changes prompt's New/Open until this ticket ends (#1315).
|
||||
let ticket = saves.start();
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
// The document counts as saved only once the file is written and closed.
|
||||
let outcome = match wasm_bindgen_futures::JsFuture::from(prom).await {
|
||||
Ok(handle_val) => match write_file_handle(&handle_val, &bytes_vec).await {
|
||||
Ok(()) => {
|
||||
log::info!("saved {name} through the save picker");
|
||||
SaveOutcome::Saved
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("couldn't write {name}: {e}");
|
||||
SaveOutcome::Failed(e)
|
||||
}
|
||||
},
|
||||
Err(e) => {
|
||||
let err_name =
|
||||
js_sys::Reflect::get(&e, &wasm_bindgen::JsValue::from_str("name")).ok().and_then(|v| v.as_string()).unwrap_or_default();
|
||||
// A browser can expose the picker but reject its promise (for example in
|
||||
// a cross-origin iframe). Use the same download path as an absent API;
|
||||
// cancelling a picker must never start an unwanted download (#1246).
|
||||
crate::save_fallback::picker_rejected(&err_name, || trigger_anchor_download(&window, &name, &bytes_vec))
|
||||
}
|
||||
};
|
||||
saves.finish(ticket, outcome);
|
||||
ctx.request_repaint();
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn write_file_handle(handle: &wasm_bindgen::JsValue, bytes: &[u8]) -> Result<(), String> {
|
||||
let js = |e: wasm_bindgen::JsValue| format!("{e:?}");
|
||||
let create_fn: js_sys::Function = js_sys::Reflect::get(handle, &wasm_bindgen::JsValue::from_str("createWritable"))
|
||||
.map_err(js)?
|
||||
.dyn_into()
|
||||
.map_err(|_| "createWritable is not a function".to_string())?;
|
||||
let stream_prom: js_sys::Promise = create_fn.call0(handle).map_err(js)?.dyn_into().map_err(|_| "not a promise".to_string())?;
|
||||
let stream = wasm_bindgen_futures::JsFuture::from(stream_prom).await.map_err(js)?;
|
||||
|
||||
let write_fn: js_sys::Function = js_sys::Reflect::get(&stream, &wasm_bindgen::JsValue::from_str("write"))
|
||||
.map_err(js)?
|
||||
.dyn_into()
|
||||
.map_err(|_| "write is not a function".to_string())?;
|
||||
let uint8 = js_sys::Uint8Array::from(bytes);
|
||||
let write_prom: js_sys::Promise = write_fn.call1(&stream, &uint8).map_err(js)?.dyn_into().map_err(|_| "not a promise".to_string())?;
|
||||
wasm_bindgen_futures::JsFuture::from(write_prom).await.map_err(js)?;
|
||||
|
||||
let close_fn: js_sys::Function = js_sys::Reflect::get(&stream, &wasm_bindgen::JsValue::from_str("close"))
|
||||
.map_err(js)?
|
||||
.dyn_into()
|
||||
.map_err(|_| "close is not a function".to_string())?;
|
||||
let close_prom: js_sys::Promise = close_fn.call0(&stream).map_err(js)?.dyn_into().map_err(|_| "not a promise".to_string())?;
|
||||
wasm_bindgen_futures::JsFuture::from(close_prom).await.map_err(js)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn trigger_anchor_download(window: &web_sys::Window, name: &str, bytes: &[u8]) -> Result<(), String> {
|
||||
let js = |e: wasm_bindgen::JsValue| format!("{e:?}");
|
||||
let document = window.document().ok_or("no document")?;
|
||||
let parts = js_sys::Array::of1(&js_sys::Uint8Array::from(bytes));
|
||||
let opts = web_sys::BlobPropertyBag::new();
|
||||
opts.set_type(mime_for(name));
|
||||
let blob = web_sys::Blob::new_with_u8_array_sequence_and_options(&parts, &opts).map_err(js)?;
|
||||
let url = web_sys::Url::create_object_url_with_blob(&blob).map_err(js)?;
|
||||
let a: web_sys::HtmlAnchorElement = document.create_element("a").map_err(js)?.dyn_into().map_err(|_| "not an anchor".to_string())?;
|
||||
a.set_href(&url);
|
||||
a.set_download(name);
|
||||
a.style().set_property("display", "none").map_err(js)?;
|
||||
let body = document.body().ok_or("no body")?;
|
||||
body.append_child(&a).map_err(js)?;
|
||||
a.click();
|
||||
a.remove();
|
||||
// Revoke after the click has been dispatched; the download keeps its own reference.
|
||||
let revoke = wasm_bindgen::closure::Closure::once_into_js(move || {
|
||||
web_sys::Url::revoke_object_url(&url).ok();
|
||||
});
|
||||
window.set_timeout_with_callback_and_timeout_and_arguments_0(revoke.unchecked_ref(), 10_000).map_err(js)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The hidden iframe the last print loaded its PDF into.
|
||||
const PRINT_FRAME_ID: &str = "wordcraft-print-frame";
|
||||
|
||||
/// Opens `bytes` (a PDF) as an object URL in a hidden iframe and calls the
|
||||
/// iframe's own `print()` once it has finished loading — this is the
|
||||
/// standard way to drive the browser's native print dialog on a PDF without
|
||||
/// a download or a popup window the browser might block. The previous
|
||||
/// print's iframe and object URL are removed first, so only one copy of the
|
||||
/// document's PDF stays in the page (the last one may still be printing).
|
||||
fn print_pdf(bytes: &[u8]) -> Result<(), String> {
|
||||
let js = |e: wasm_bindgen::JsValue| format!("{e:?}");
|
||||
let window = web_sys::window().ok_or("no window")?;
|
||||
let document = window.document().ok_or("no document")?;
|
||||
|
||||
if let Some(old) = document.get_element_by_id(PRINT_FRAME_ID) {
|
||||
if let Ok(frame) = old.clone().dyn_into::<web_sys::HtmlIFrameElement>() {
|
||||
let src = frame.src();
|
||||
if src.starts_with("blob:") {
|
||||
web_sys::Url::revoke_object_url(&src).ok();
|
||||
}
|
||||
}
|
||||
old.remove();
|
||||
}
|
||||
|
||||
let parts = js_sys::Array::of1(&js_sys::Uint8Array::from(bytes));
|
||||
let opts = web_sys::BlobPropertyBag::new();
|
||||
opts.set_type("application/pdf");
|
||||
let blob = web_sys::Blob::new_with_u8_array_sequence_and_options(&parts, &opts).map_err(js)?;
|
||||
let url = web_sys::Url::create_object_url_with_blob(&blob).map_err(js)?;
|
||||
|
||||
let iframe: web_sys::HtmlIFrameElement =
|
||||
match document.create_element("iframe").map_err(js).and_then(|e| e.dyn_into().map_err(|_| "not an iframe".to_string())) {
|
||||
Ok(f) => f,
|
||||
Err(e) => {
|
||||
web_sys::Url::revoke_object_url(&url).ok();
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
iframe.set_id(PRINT_FRAME_ID);
|
||||
let attached = iframe
|
||||
.style()
|
||||
.set_property("display", "none")
|
||||
.map_err(js)
|
||||
.and_then(|()| document.body().ok_or_else(|| "no body".to_string()))
|
||||
.and_then(|body| body.append_child(&iframe).map_err(js));
|
||||
if let Err(e) = attached {
|
||||
iframe.remove();
|
||||
web_sys::Url::revoke_object_url(&url).ok();
|
||||
return Err(e);
|
||||
}
|
||||
|
||||
// `onload` fires once the PDF has actually rendered inside the iframe;
|
||||
// printing before that would show a blank page. Set the handler BEFORE
|
||||
// `src` so a fast/cached load can't fire before we're listening.
|
||||
let iframe_for_load = iframe.clone();
|
||||
let on_load = wasm_bindgen::closure::Closure::once_into_js(move || {
|
||||
if let Some(w) = iframe_for_load.content_window() {
|
||||
// Ignore errors: some browsers (notably Firefox with a built-in
|
||||
// PDF viewer) print fine but report a benign cross-origin-style
|
||||
// error back on this call.
|
||||
let _ = w.print();
|
||||
}
|
||||
});
|
||||
iframe.set_onload(Some(on_load.unchecked_ref()));
|
||||
iframe.set_src(&url);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn mime_for(name: &str) -> &'static str {
|
||||
match name.rsplit('.').next().map(str::to_ascii_lowercase).as_deref() {
|
||||
Some("png") => "image/png",
|
||||
Some("jpg" | "jpeg") => "image/jpeg",
|
||||
Some("pdf") => "application/pdf",
|
||||
Some("docx") => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||
Some("odt") => "application/vnd.oasis.opendocument.text",
|
||||
Some("ott") => "application/vnd.oasis.opendocument.text-template",
|
||||
Some("fodt") => "application/vnd.oasis.opendocument.text-flat-xml",
|
||||
Some("rtf") => "application/rtf",
|
||||
Some("html") => "text/html",
|
||||
Some("md" | "txt") => "text/plain",
|
||||
Some("tex") => "application/x-tex",
|
||||
Some("json") => "application/json",
|
||||
Some("xml") => "application/xml",
|
||||
_ => "application/octet-stream",
|
||||
}
|
||||
}
|
||||
|
||||
+34
-59
@@ -17,15 +17,38 @@ wordcraft-proof = { workspace = true }
|
||||
# Fonts the user added (#582) load from the settings folder at start-up.
|
||||
wordcraft-fonts = { workspace = true }
|
||||
wordcraft-ui-egui = { workspace = true }
|
||||
# The clipboard's PNG decoder.
|
||||
wordcraft-geom = { workspace = true, features = ["image"] }
|
||||
# The control key file's location (shared with the MCP bridge).
|
||||
wordcraft-control-key = { workspace = true }
|
||||
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "clipboard", "wayland", "x11", "links"] }
|
||||
egui = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
tempfile = "3"
|
||||
log = { workspace = true }
|
||||
chrono = { 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.
|
||||
craft = { workspace = true, features = [
|
||||
"ui",
|
||||
"ui-app",
|
||||
"dialogs",
|
||||
"automation",
|
||||
"gpu-startup",
|
||||
"print",
|
||||
"settings",
|
||||
"window",
|
||||
"platform-appearance",
|
||||
"platform-clipboard-system",
|
||||
] }
|
||||
|
||||
[dev-dependencies]
|
||||
# Temporary settings folders for the `prefs` tests.
|
||||
tempfile = "3"
|
||||
# The frame driver of the `smoke` test.
|
||||
craft = { workspace = true, features = ["ui-testing"] }
|
||||
|
||||
[build-dependencies]
|
||||
# Icon + VERSIONINFO for wordcraft.exe; build.rs only uses it when the target is Windows.
|
||||
@@ -33,69 +56,21 @@ winresource = "0.1"
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
# Finder double-click, Open With, Dock drops and `open -a WordCraft letter.docx` arrive as a
|
||||
# kAEOpenDocuments Apple event, which winit 0.30 doesn't handle (#27). This audited crate (also used
|
||||
# by PdfCraft and PhotoCraft) registers the handler (Objective-C interop needs unsafe, which our
|
||||
# workspace forbids) behind a safe API. Pinned exactly: review the diff before bumping.
|
||||
fmv-macos-events = "=0.1.0"
|
||||
# The system's Reduce motion setting (System Settings › Accessibility › Display), read through
|
||||
# NSWorkspace: a safe call in these bindings. Already in the build through eframe, rfd and arboard,
|
||||
# at this version; this adds the `NSAccessibility` bindings and, to fit the title bar around the
|
||||
# traffic lights, the window, button and view ones; and `NSPasteboard` for the clipboard's RTF.
|
||||
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSWorkspace", "NSAccessibility", "NSApplication", "NSWindow", "NSButton", "NSControl", "NSView", "NSResponder", "NSPasteboard"] }
|
||||
objc2 = "0.6"
|
||||
# A copied equation's MathML goes on the pasteboard as `public.mathml.presentation` beside
|
||||
# arboard's HTML and text (#1297), through NSPasteboard's safe `setString:forType:`. Already in
|
||||
# the build through arboard, at this version; this adds only the NSString bindings, and NSData
|
||||
# for the clipboard's RTF (`public.rtf`).
|
||||
objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSString", "NSData"] }
|
||||
# Closing the window must quit through NSApplication rather than by dropping the NSWindow
|
||||
# inside the AppKit run loop (see `schedule_macos_terminate`).
|
||||
dispatch2 = "0.3"
|
||||
# kAEOpenDocuments Apple event, which winit doesn't handle (#27).
|
||||
craft = { workspace = true, features = ["platform-apple-events"] }
|
||||
|
||||
[target.'cfg(all(unix, not(target_os = "macos")))'.dependencies]
|
||||
winit = { version = "0.30", default-features = false, features = ["x11"] }
|
||||
# The desktop's animation setting on Linux and the BSDs, read from the XDG settings portal over
|
||||
# D-Bus. Already in the build through AccessKit, at this version; this adds only its blocking API.
|
||||
zbus = { version = "5", default-features = false, features = ["async-io", "blocking-api"] }
|
||||
# Wayland's clipboard through the data-control protocol (#687, #833): the RTF and other picture
|
||||
# types that arboard doesn't read, and the formats offered. Already in the build through arboard's
|
||||
# `wayland-data-control` feature, at this version.
|
||||
wl-clipboard-rs = "0.9"
|
||||
# Another program's RTF on X11 (`text/rtf`), which arboard doesn't read. Already in the build
|
||||
# through arboard, at this version.
|
||||
x11rb = "0.13"
|
||||
# Check that the libraries winit's X11 backend opens are installed before choosing XWayland (see
|
||||
# `x11_libraries` in main.rs). Both are already in the build through winit's `x11` feature, at
|
||||
# these versions and with this feature.
|
||||
x11-dl = "2.21"
|
||||
xkbcommon-dl = { version = "0.4.2", features = ["x11"] }
|
||||
|
||||
[target.'cfg(target_os = "windows")'.dependencies]
|
||||
# The upstream default-apps button opens Windows Settings; printing uses craft-print instead.
|
||||
open = "5"
|
||||
# The system's Animation effects setting (Settings › Accessibility › Visual effects), read through
|
||||
# the Windows Runtime's UISettings: a safe API, where the Win32 call needs unsafe, which our
|
||||
# workspace forbids. Already in the build through wgpu and AccessKit, at this version; this adds
|
||||
# only the `UI_ViewManagement` bindings, and `System_UserProfile` for the home region new
|
||||
# documents take their paper and units from (#838).
|
||||
windows = { version = "0.62", features = ["UI_ViewManagement", "System_UserProfile"] }
|
||||
# The clipboard's "Rich Text Format" and the names of its formats (#687, #833), which arboard
|
||||
# doesn't read. Already in the build through arboard, at this version.
|
||||
clipboard-win = { version = "5.4", features = ["std"] }
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
# At the same craft-libs commit as the workspace's crates: `printer_queues`, the printer list that
|
||||
# asks no driver (#5710, storytold/craft-libs#618), and `submit_cancellable` (storytold/craft-libs#622).
|
||||
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "93dac78c93a7f1fd66e2022edeb089233b1dc45a" }
|
||||
rfd = { workspace = true }
|
||||
# Waits for an `rfd::AsyncFileDialog` on a background thread (the dialogs don't block the UI, #94);
|
||||
# rfd itself already depends on it.
|
||||
pollster = "1"
|
||||
# Pictures and copied files on the system clipboard (#45); egui's paste only carries text. Already
|
||||
# in the build through egui-winit, with the same features.
|
||||
arboard = { workspace = true, features = ["image-data"] }
|
||||
# The control server's random key.
|
||||
getrandom = "0.3"
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
craft-update = { workspace = true }
|
||||
# The update helper: a copy of this program started with `--finish-update`
|
||||
# (`craft::update::self_update::finish`).
|
||||
craft = { workspace = true, features = ["update"] }
|
||||
# The nightly Windows identity: an explicit AppUserModelID, so Nightly gets its own taskbar
|
||||
# button instead of sharing the stable app's (#16335's rule for the suite).
|
||||
winsafe = { version = "=0.0.29", default-features = false, features = ["user", "shell"] }
|
||||
|
||||
+43
-5
@@ -1,25 +1,63 @@
|
||||
//! Windows only: embed the app icon and version info (VERSIONINFO) into `wordcraft.exe`, so it
|
||||
//! shows in Explorer, the taskbar, the Start menu and Alt-Tab.
|
||||
//!
|
||||
//! On every other target this does nothing. A missing resource compiler is a warning, so a
|
||||
//! cross-compile from macOS or Linux still links, unless `WORDCRAFT_REQUIRE_WINRES=1` turns it
|
||||
//! The build channel (`WORDCRAFT_BUILD_CHANNEL`) is decided here, before any code is compiled: a
|
||||
//! nightly-v1 build gets its own cfg, its own icon and its exact feed version in VERSIONINFO.
|
||||
//! On every other target this does nothing but that. A missing resource compiler is a warning, so
|
||||
//! a cross-compile from macOS or Linux still links, unless `WORDCRAFT_REQUIRE_WINRES=1` turns it
|
||||
//! into an error (for release builds).
|
||||
|
||||
#[path = "src/build_channel.rs"]
|
||||
mod build_channel;
|
||||
|
||||
fn main() {
|
||||
println!("cargo:rerun-if-changed=build.rs");
|
||||
println!("cargo:rerun-if-env-changed=WORDCRAFT_BUILD_CHANNEL");
|
||||
println!("cargo:rustc-check-cfg=cfg(wordcraft_nightly_v1)");
|
||||
let nightly = match std::env::var("WORDCRAFT_BUILD_CHANNEL").as_deref() {
|
||||
Ok("nightly-v1") => {
|
||||
println!("cargo:rustc-cfg=wordcraft_nightly_v1");
|
||||
true
|
||||
}
|
||||
// An empty value (an unset CI input) means the default stable build.
|
||||
Ok("stable" | "") | Err(std::env::VarError::NotPresent) => false,
|
||||
_ => {
|
||||
eprintln!("unsupported WORDCRAFT_BUILD_CHANNEL (expected stable or nightly-v1)");
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
println!("cargo:rerun-if-changed=../../assets/app-icon/wordcraft.ico");
|
||||
println!("cargo:rerun-if-changed=../../assets/app-icon/wordcraft-nightly.ico");
|
||||
println!("cargo:rerun-if-env-changed=WORDCRAFT_REQUIRE_WINRES");
|
||||
println!("cargo:rerun-if-env-changed=WORDCRAFT_VERSION");
|
||||
let built_version = if nightly {
|
||||
match std::env::var("WORDCRAFT_VERSION") {
|
||||
Ok(version) if build_channel::is_nightly_version(&version) => version,
|
||||
_ => {
|
||||
eprintln!("nightly-v1 requires an explicit WORDCRAFT_VERSION feed identity");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
std::env::var("CARGO_PKG_VERSION").unwrap_or_default()
|
||||
};
|
||||
println!("cargo:rustc-env=WORDCRAFT_BUILT_VERSION={built_version}");
|
||||
|
||||
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") {
|
||||
return;
|
||||
}
|
||||
let mut res = winresource::WindowsResource::new();
|
||||
res.set_icon("../../assets/app-icon/wordcraft.ico")
|
||||
.set("ProductName", "WordCraft")
|
||||
.set("FileDescription", "WordCraft word processor")
|
||||
res.set_icon(build_channel::windows_icon_path(nightly))
|
||||
.set("ProductName", if nightly { "WordCraft Nightly" } else { "WordCraft" })
|
||||
.set("FileDescription", if nightly { "WordCraft Nightly word processor" } else { "WordCraft word processor" })
|
||||
.set("CompanyName", "Learning Machines LLC")
|
||||
.set("LegalCopyright", "Copyright (c) the WordCraft authors. MIT OR Apache-2.0.")
|
||||
.set("OriginalFilename", "wordcraft.exe")
|
||||
.set("InternalName", "wordcraft");
|
||||
if nightly {
|
||||
// The Launcher verifies the PE ProductVersion against the exact feed identity, not FileVersion.
|
||||
res.set("ProductVersion", &built_version);
|
||||
}
|
||||
if let Err(e) = res.compile() {
|
||||
if std::env::var_os("WORDCRAFT_REQUIRE_WINRES").is_some() {
|
||||
eprintln!("embedding Windows resources failed: {e}");
|
||||
|
||||
@@ -1,99 +0,0 @@
|
||||
//! The system's animation setting, which File › Options › Accessibility › Animation effects
|
||||
//! follows when set to "Use system setting" (`Services::animations_enabled`).
|
||||
//!
|
||||
//! - Windows: Settings › Accessibility › Visual effects › Animation effects, read through the
|
||||
//! Windows Runtime's `UISettings`.
|
||||
//! - macOS: System Settings › Accessibility › Display › Reduce motion, read through `NSWorkspace`.
|
||||
//! - Linux and the BSDs: the desktop's setting, read through the settings portal ([`desktop`]).
|
||||
//!
|
||||
//! All three are safe APIs of crates already in the build (our workspace forbids unsafe). The UI
|
||||
//! asks every frame, so the answer always comes from memory: Windows and macOS are asked again at
|
||||
//! most once a second, and the Linux/BSD side keeps its answer up to date on a thread of its own.
|
||||
|
||||
#[cfg(any(all(unix, not(target_os = "macos")), test))]
|
||||
mod desktop;
|
||||
|
||||
/// The answer to "does the system have animation effects on?" for the UI: `None` when the system
|
||||
/// doesn't say. `ctx` is asked to redraw when an answer that arrives later changes it.
|
||||
pub fn hook(ctx: &egui::Context) -> Box<dyn Fn() -> Option<bool>> {
|
||||
#[cfg(any(target_os = "windows", target_os = "macos"))]
|
||||
{
|
||||
let _ = ctx;
|
||||
Box::new(remembered(system_enabled, REFRESH))
|
||||
}
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
{
|
||||
Box::new(desktop::watch(ctx.clone()))
|
||||
}
|
||||
#[cfg(not(any(target_os = "windows", unix)))]
|
||||
{
|
||||
let _ = ctx;
|
||||
Box::new(|| None)
|
||||
}
|
||||
}
|
||||
|
||||
/// How long an answer from Windows or macOS is kept before the system is asked again.
|
||||
#[cfg(any(target_os = "windows", target_os = "macos"))]
|
||||
const REFRESH: std::time::Duration = std::time::Duration::from_secs(1);
|
||||
|
||||
/// `read`, asked at most once per `every` and answered from memory in between.
|
||||
#[cfg(any(target_os = "windows", target_os = "macos", test))]
|
||||
fn remembered(read: impl Fn() -> Option<bool>, every: std::time::Duration) -> impl Fn() -> Option<bool> {
|
||||
let last = std::cell::Cell::new(None::<(std::time::Instant, Option<bool>)>);
|
||||
move || {
|
||||
if let Some((at, answer)) = last.get()
|
||||
&& at.elapsed() < every
|
||||
{
|
||||
return answer;
|
||||
}
|
||||
let answer = read();
|
||||
last.set(Some((std::time::Instant::now(), answer)));
|
||||
answer
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether Windows has animation effects on; `None` when it can't be asked.
|
||||
#[cfg(target_os = "windows")]
|
||||
fn system_enabled() -> Option<bool> {
|
||||
windows::UI::ViewManagement::UISettings::new()
|
||||
.and_then(|settings| settings.AnimationsEnabled())
|
||||
.map_err(|e| log::debug!("system animation setting: {e}"))
|
||||
.ok()
|
||||
}
|
||||
|
||||
/// Whether macOS plays animations: Reduce motion is off.
|
||||
#[cfg(target_os = "macos")]
|
||||
fn system_enabled() -> Option<bool> {
|
||||
Some(!objc2_app_kit::NSWorkspace::sharedWorkspace().accessibilityDisplayShouldReduceMotion())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::cell::Cell;
|
||||
use std::time::Duration;
|
||||
|
||||
use super::remembered;
|
||||
|
||||
/// The UI asks every frame; the system is asked once per interval and the answer kept between.
|
||||
#[test]
|
||||
fn the_system_is_asked_once_per_interval() {
|
||||
let asked = Cell::new(0);
|
||||
let system = Cell::new(Some(false));
|
||||
let read = || {
|
||||
asked.set(asked.get() + 1);
|
||||
system.get()
|
||||
};
|
||||
let kept = remembered(read, Duration::from_secs(3600));
|
||||
assert_eq!((kept(), kept(), kept()), (Some(false), Some(false), Some(false)));
|
||||
system.set(Some(true));
|
||||
assert_eq!(kept(), Some(false), "within the interval the remembered answer stands");
|
||||
assert_eq!(asked.get(), 1);
|
||||
|
||||
// Once the interval has passed (here: at once) the system is asked again.
|
||||
let fresh = remembered(read, Duration::ZERO);
|
||||
assert_eq!(fresh(), Some(true));
|
||||
system.set(None);
|
||||
assert_eq!(fresh(), None);
|
||||
assert_eq!(asked.get(), 3);
|
||||
}
|
||||
}
|
||||
@@ -1,305 +0,0 @@
|
||||
//! The desktop's animation setting on Linux and the BSDs.
|
||||
//!
|
||||
//! Asked of the XDG settings portal over D-Bus (`org.freedesktop.portal.Settings`), which GNOME,
|
||||
//! KDE Plasma and the other desktops with a portal answer, inside Flatpak too. Three settings say
|
||||
//! whether animations play ([`KEYS`]); any one of them saying no turns them off. Where no portal
|
||||
//! answers, or it knows none of the three (a bare window manager), the user's own KDE and GTK
|
||||
//! settings files are read instead, once.
|
||||
//!
|
||||
//! A thread asks at start-up and then follows the portal's change signal, so the UI's question is
|
||||
//! always answered from memory and a change in the desktop's settings shows without a restart.
|
||||
|
||||
/// What a setting holds, whichever way it was stored.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Reading {
|
||||
Bool(bool),
|
||||
Number(f64),
|
||||
Text(String),
|
||||
}
|
||||
|
||||
/// A setting as the portal names it: (namespace, key).
|
||||
type Key = (&'static str, &'static str);
|
||||
|
||||
/// The cross-desktop preference: 1 asks for reduced motion; 0, and values not defined yet, are
|
||||
/// no preference.
|
||||
const REDUCED_MOTION: Key = ("org.freedesktop.appearance", "reduced-motion");
|
||||
/// GNOME's switch, the one GTK follows.
|
||||
const GNOME_ANIMATIONS: Key = ("org.gnome.desktop.interface", "enable-animations");
|
||||
/// KDE Plasma's animation speed, a factor on every animation's length: 0 makes them instant.
|
||||
const KDE_ANIMATION_SPEED: Key = ("org.kde.kdeglobals.KDE", "AnimationDurationFactor");
|
||||
|
||||
/// The settings that say whether animations play.
|
||||
pub const KEYS: [Key; 3] = [REDUCED_MOTION, GNOME_ANIMATIONS, KDE_ANIMATION_SPEED];
|
||||
|
||||
/// Whether animations play according to one of [`KEYS`]; `None` for any other setting, or a
|
||||
/// value that isn't one it holds.
|
||||
pub fn says(namespace: &str, key: &str, value: &Reading) -> Option<bool> {
|
||||
match (namespace, key) {
|
||||
k if k == REDUCED_MOTION => number(value).map(|n| n != 1.0),
|
||||
k if k == GNOME_ANIMATIONS => truth(value),
|
||||
k if k == KDE_ANIMATION_SPEED => number(value).map(|n| n > 0.0),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn number(value: &Reading) -> Option<f64> {
|
||||
let n = match value {
|
||||
Reading::Number(n) => *n,
|
||||
Reading::Text(t) => t.trim().parse().ok()?,
|
||||
Reading::Bool(_) => return None,
|
||||
};
|
||||
n.is_finite().then_some(n)
|
||||
}
|
||||
|
||||
fn truth(value: &Reading) -> Option<bool> {
|
||||
match value {
|
||||
Reading::Bool(b) => Some(*b),
|
||||
Reading::Number(n) => n.is_finite().then_some(*n != 0.0),
|
||||
Reading::Text(t) => match t.trim().to_ascii_lowercase().as_str() {
|
||||
"true" | "1" => Some(true),
|
||||
"false" | "0" => Some(false),
|
||||
_ => None,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Several settings' answers as one: off as soon as one says off, on when at least one says on,
|
||||
/// `None` when none says anything.
|
||||
pub fn combine(answers: impl IntoIterator<Item = Option<bool>>) -> Option<bool> {
|
||||
let mut any = None;
|
||||
for on in answers.into_iter().flatten() {
|
||||
if !on {
|
||||
return Some(false);
|
||||
}
|
||||
any = Some(true);
|
||||
}
|
||||
any
|
||||
}
|
||||
|
||||
/// The value of `key` in `[section]` of a settings file in INI form (KDE's `kdeglobals`, GTK's
|
||||
/// `settings.ini`). The last one wins, as the toolkits read it.
|
||||
pub fn ini_value<'a>(text: &'a str, section: &str, key: &str) -> Option<&'a str> {
|
||||
let mut inside = false;
|
||||
let mut found = None;
|
||||
for line in text.lines().map(str::trim) {
|
||||
if let Some(name) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) {
|
||||
inside = name.trim() == section;
|
||||
} else if inside
|
||||
&& !line.starts_with(['#', ';'])
|
||||
&& let Some((k, v)) = line.split_once('=')
|
||||
&& k.trim() == key
|
||||
{
|
||||
found = Some(v.trim());
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// What the user's own settings files say, given their text (`None` for a file that isn't
|
||||
/// there): KDE Plasma's `kdeglobals` and GTK's `settings.ini`s.
|
||||
pub fn files_say(kdeglobals: Option<&str>, gtk_settings: [Option<&str>; 2]) -> Option<bool> {
|
||||
let (namespace, key) = KDE_ANIMATION_SPEED;
|
||||
let kde = kdeglobals.and_then(|text| ini_value(text, "KDE", key)).and_then(|v| says(namespace, key, &Reading::Text(v.to_string())));
|
||||
let gtk = gtk_settings
|
||||
.into_iter()
|
||||
.map(|text| text.and_then(|t| ini_value(t, "Settings", "gtk-enable-animations")).and_then(|v| truth(&Reading::Text(v.to_string()))));
|
||||
combine(std::iter::once(kde).chain(gtk))
|
||||
}
|
||||
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
pub use watching::watch;
|
||||
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
mod watching {
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU8, Ordering};
|
||||
|
||||
use zbus::blocking::{Connection, Proxy};
|
||||
use zbus::zvariant::{OwnedValue, Value};
|
||||
|
||||
use super::{KEYS, Reading, combine, files_say, says};
|
||||
|
||||
// The latest answer, as one byte the UI thread reads without waiting.
|
||||
const UNKNOWN: u8 = 0;
|
||||
const ON: u8 = 1;
|
||||
const OFF: u8 = 2;
|
||||
|
||||
/// Start following the desktop's animation setting. The returned function gives the latest
|
||||
/// answer from memory (`None` until the first one arrives, and when the desktop says nothing);
|
||||
/// `ctx` is asked to redraw when the answer changes.
|
||||
pub fn watch(ctx: egui::Context) -> impl Fn() -> Option<bool> {
|
||||
let latest = Arc::new(AtomicU8::new(UNKNOWN));
|
||||
let shared = latest.clone();
|
||||
let spawned = std::thread::Builder::new().name("animation-setting".into()).spawn(move || {
|
||||
let publish = |answer: Option<bool>| {
|
||||
let code = match answer {
|
||||
Some(true) => ON,
|
||||
Some(false) => OFF,
|
||||
None => UNKNOWN,
|
||||
};
|
||||
if shared.swap(code, Ordering::Relaxed) != code {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
};
|
||||
if let Err(e) = follow_portal(&publish) {
|
||||
log::debug!("desktop animation setting: no settings portal ({e}); reading the settings files");
|
||||
publish(read_files());
|
||||
}
|
||||
});
|
||||
if let Err(e) = spawned {
|
||||
log::warn!("desktop animation setting: {e}");
|
||||
}
|
||||
move || match latest.load(Ordering::Relaxed) {
|
||||
ON => Some(true),
|
||||
OFF => Some(false),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Publish what the settings portal says, now and after every change it announces, until the
|
||||
/// connection ends; an error when there is no session bus to ask on. While the portal knows
|
||||
/// none of the settings, the files' answer stands.
|
||||
fn follow_portal(publish: &dyn Fn(Option<bool>)) -> zbus::Result<()> {
|
||||
let connection = Connection::session()?;
|
||||
let portal = Proxy::new(&connection, "org.freedesktop.portal.Desktop", "/org/freedesktop/portal/desktop", "org.freedesktop.portal.Settings")?;
|
||||
// Listen before the first read, so a change between the two isn't missed.
|
||||
let changes = portal.receive_signal("SettingChanged")?;
|
||||
// The files are read once, the first time the portal has nothing to say.
|
||||
let mut files = None;
|
||||
let mut ask = || ask_portal(&portal).or_else(|| *files.get_or_insert_with(read_files));
|
||||
publish(ask());
|
||||
// A setting can turn up later (KDE's has no value while the speed is at its default), so
|
||||
// the changes are followed whatever the portal knew at first. Every setting is asked
|
||||
// again, not just the one announced: KDE announces a new animation speed only as the
|
||||
// cross-desktop preference, and its own setting must not be left at the old value.
|
||||
for change in changes {
|
||||
let ours = change
|
||||
.body()
|
||||
.deserialize::<(String, String, OwnedValue)>()
|
||||
.is_ok_and(|(namespace, key, _)| KEYS.contains(&(namespace.as_str(), key.as_str())));
|
||||
if ours {
|
||||
publish(ask());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// What the portal's settings come to; `None` when it has none of them.
|
||||
fn ask_portal(portal: &Proxy<'_>) -> Option<bool> {
|
||||
combine(KEYS.map(|(namespace, key)| read_setting(portal, namespace, key).and_then(|value| says(namespace, key, &value))))
|
||||
}
|
||||
|
||||
/// One setting from the portal; `None` when it doesn't have it.
|
||||
fn read_setting(portal: &Proxy<'_>, namespace: &str, key: &str) -> Option<Reading> {
|
||||
// `ReadOne` is the current call; portals from before it only have `Read`.
|
||||
let value: OwnedValue = portal.call("ReadOne", &(namespace, key)).or_else(|_| portal.call("Read", &(namespace, key))).ok()?;
|
||||
reading(&value, 0)
|
||||
}
|
||||
|
||||
fn reading(value: &Value<'_>, depth: u8) -> Option<Reading> {
|
||||
Some(match value {
|
||||
Value::Bool(b) => Reading::Bool(*b),
|
||||
Value::U8(n) => Reading::Number(f64::from(*n)),
|
||||
Value::I16(n) => Reading::Number(f64::from(*n)),
|
||||
Value::U16(n) => Reading::Number(f64::from(*n)),
|
||||
Value::I32(n) => Reading::Number(f64::from(*n)),
|
||||
Value::U32(n) => Reading::Number(f64::from(*n)),
|
||||
Value::I64(n) => Reading::Number(*n as f64),
|
||||
Value::U64(n) => Reading::Number(*n as f64),
|
||||
Value::F64(n) => Reading::Number(*n),
|
||||
Value::Str(s) => Reading::Text(s.as_str().to_string()),
|
||||
// `Read` wraps its answer in a second variant.
|
||||
Value::Value(inner) if depth < 4 => return reading(inner, depth + 1),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// What the user's settings files say (see [`files_say`]).
|
||||
fn read_files() -> Option<bool> {
|
||||
let config = std::env::var_os("XDG_CONFIG_HOME")
|
||||
.filter(|dir| !dir.is_empty())
|
||||
.map(PathBuf::from)
|
||||
.or_else(|| std::env::var_os("HOME").map(|home| PathBuf::from(home).join(".config")))?;
|
||||
let text = |file: &str| read_capped(&config.join(file));
|
||||
let (kdeglobals, gtk4, gtk3) = (text("kdeglobals"), text("gtk-4.0/settings.ini"), text("gtk-3.0/settings.ini"));
|
||||
files_say(kdeglobals.as_deref(), [gtk4.as_deref(), gtk3.as_deref()])
|
||||
}
|
||||
|
||||
/// A settings file's text: at most 256 KiB of it (they are a few kilobytes).
|
||||
fn read_capped(path: &Path) -> Option<String> {
|
||||
use std::io::Read as _;
|
||||
let mut text = String::new();
|
||||
std::fs::File::open(path).ok()?.take(256 * 1024).read_to_string(&mut text).ok()?;
|
||||
Some(text)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn text(s: &str) -> Reading {
|
||||
Reading::Text(s.to_string())
|
||||
}
|
||||
|
||||
/// Each desktop's setting, as the portal hands it over, comes to animations on or off.
|
||||
#[test]
|
||||
fn each_desktop_setting_says_on_or_off() {
|
||||
let ((appearance, reduced), (gnome, enable), (kde, factor)) = (REDUCED_MOTION, GNOME_ANIMATIONS, KDE_ANIMATION_SPEED);
|
||||
assert_eq!(KEYS, [REDUCED_MOTION, GNOME_ANIMATIONS, KDE_ANIMATION_SPEED]);
|
||||
// The cross-desktop preference: only 1 asks for reduced motion.
|
||||
assert_eq!(says(appearance, reduced, &Reading::Number(1.0)), Some(false));
|
||||
assert_eq!(says(appearance, reduced, &Reading::Number(0.0)), Some(true));
|
||||
assert_eq!(says(appearance, reduced, &Reading::Number(7.0)), Some(true), "a value not defined yet is no preference");
|
||||
assert_eq!(says(appearance, reduced, &Reading::Bool(true)), None);
|
||||
// GNOME's switch.
|
||||
assert_eq!(says(gnome, enable, &Reading::Bool(false)), Some(false));
|
||||
assert_eq!(says(gnome, enable, &Reading::Bool(true)), Some(true));
|
||||
assert_eq!(says(gnome, enable, &text("nonsense")), None);
|
||||
// KDE Plasma's animation speed arrives as text: 0 is instant.
|
||||
assert_eq!(says(kde, factor, &text("0")), Some(false));
|
||||
assert_eq!(says(kde, factor, &text(" 0.5 ")), Some(true));
|
||||
assert_eq!(says(kde, factor, &Reading::Number(1.0)), Some(true));
|
||||
for junk in [text(""), text("fast"), Reading::Number(f64::NAN), text("inf")] {
|
||||
assert_eq!(says(kde, factor, &junk), None, "{junk:?}");
|
||||
}
|
||||
// Any other setting says nothing.
|
||||
assert_eq!(says(gnome, "color-scheme", &Reading::Bool(false)), None);
|
||||
assert_eq!(says("org.example", enable, &Reading::Bool(false)), None);
|
||||
}
|
||||
|
||||
/// One setting saying off is enough; none saying anything is no answer.
|
||||
#[test]
|
||||
fn any_setting_saying_off_turns_animations_off() {
|
||||
assert_eq!(combine([]), None);
|
||||
assert_eq!(combine([None, None]), None);
|
||||
assert_eq!(combine([None, Some(true)]), Some(true));
|
||||
assert_eq!(combine([Some(true), None, Some(false)]), Some(false));
|
||||
assert_eq!(combine([Some(false), Some(true)]), Some(false));
|
||||
}
|
||||
|
||||
/// Without a portal the user's own settings files answer: KDE's animation speed and GTK's
|
||||
/// `gtk-enable-animations`.
|
||||
#[test]
|
||||
fn settings_files_answer_without_a_portal() {
|
||||
let kde_instant = "[General]\nColorScheme=Breeze\n\n[KDE]\nAnimationDurationFactor=0\nSingleClick=false\n";
|
||||
let kde_slow = "[KDE]\nAnimationDurationFactor = 2\n";
|
||||
let gtk_off = "[Settings]\ngtk-theme-name=Adwaita\ngtk-enable-animations=0\n";
|
||||
let gtk_on = "# written by hand\n[Settings]\ngtk-enable-animations=true\n";
|
||||
assert_eq!(files_say(None, [None, None]), None);
|
||||
assert_eq!(files_say(Some("[KDE]\nSingleClick=false\n"), [Some("[Settings]\n"), None]), None, "files that don't mention it");
|
||||
assert_eq!(files_say(Some(kde_instant), [None, None]), Some(false));
|
||||
assert_eq!(files_say(Some(kde_slow), [None, None]), Some(true));
|
||||
assert_eq!(files_say(None, [Some(gtk_off), None]), Some(false));
|
||||
assert_eq!(files_say(None, [None, Some(gtk_on)]), Some(true));
|
||||
assert_eq!(files_say(Some(kde_slow), [Some(gtk_on), Some(gtk_off)]), Some(false), "one file saying off is enough");
|
||||
|
||||
// The key counts only in its own section, comments don't, and the last value wins.
|
||||
assert_eq!(ini_value("[Other]\nAnimationDurationFactor=0\n[KDE]\nSingleClick=true\n", "KDE", "AnimationDurationFactor"), None);
|
||||
assert_eq!(ini_value("[KDE]\n#AnimationDurationFactor=0\n;AnimationDurationFactor=0\n", "KDE", "AnimationDurationFactor"), None);
|
||||
assert_eq!(ini_value("[KDE]\r\nAnimationDurationFactor=0\r\nAnimationDurationFactor=1\r\n", "KDE", "AnimationDurationFactor"), Some("1"));
|
||||
assert_eq!(ini_value("AnimationDurationFactor=0\n", "KDE", "AnimationDurationFactor"), None, "outside any section");
|
||||
assert_eq!(ini_value("", "KDE", "AnimationDurationFactor"), None);
|
||||
}
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
//! macOS open-documents and quit Apple events (#27).
|
||||
//!
|
||||
//! Finder double-clicks, Open With, drops on the Dock icon and `open -a WordCraft letter.docx` don't
|
||||
//! pass paths on the command line: LaunchServices sends the running (or just-launched) app a
|
||||
//! `kAEOpenDocuments` ('odoc') Apple event. winit 0.30 doesn't handle it and owns the
|
||||
//! `NSApplicationDelegate`, so AppKit answered "WordCraft cannot open files in the Word Document
|
||||
//! format". Handling it ourselves needs Objective-C class declarations, i.e. `unsafe`, which this
|
||||
//! workspace forbids. The `fmv-macos-events` crate (also used by PdfCraft and PhotoCraft)
|
||||
//! wraps exactly that, an `NSAppleEventManager` handler registered before Finder's launch event
|
||||
//! that leaves winit's delegate alone, behind a safe main-thread API.
|
||||
|
||||
use fmv_macos_events::{Event, Inbox, Registration};
|
||||
use wordcraft_ui_egui::WordApp;
|
||||
|
||||
/// Keeps the Apple-event handlers registered; hold it until the event loop returns.
|
||||
pub struct AppleEvents {
|
||||
_registration: Registration,
|
||||
inbox: Inbox,
|
||||
}
|
||||
|
||||
impl AppleEvents {
|
||||
/// Register the handlers. Call on the main thread before the event loop starts, so the event
|
||||
/// that launched the app (a Finder double-click) is caught too.
|
||||
pub fn install() -> Self {
|
||||
let (registration, inbox) = Registration::install();
|
||||
Self { _registration: registration, inbox }
|
||||
}
|
||||
|
||||
/// The queue the app drains every frame ([`poll`]); events arriving later wake `ctx`.
|
||||
pub fn connect(&self, ctx: &egui::Context) -> Inbox {
|
||||
let ctx = ctx.clone();
|
||||
self.inbox.set_wake(move || ctx.request_repaint());
|
||||
self.inbox.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// Open the documents and act on the quit requests that arrived since the last frame. A document
|
||||
/// opens like File › Open: beside the open ones, in place of an untouched blank one, or, when it
|
||||
/// is already open, by showing it; a Word template starts a new document based on it, as Word's
|
||||
/// default verb for one does (#3433). Quitting closes the window, which asks about every document
|
||||
/// with unsaved changes.
|
||||
pub fn poll(inbox: &Inbox, app: &mut WordApp, ctx: &egui::Context) {
|
||||
for e in inbox.drain() {
|
||||
match e {
|
||||
Event::Open(paths) => {
|
||||
for p in paths.iter().filter_map(|p| p.to_str()) {
|
||||
match app.open_from_platform(p, None) {
|
||||
// Leave Backstage, as opening from the Open dialog does.
|
||||
Ok(_) => app.ui.backstage = false,
|
||||
Err(e) => {
|
||||
app.report_open_failure(p, &e);
|
||||
// Backstage hides the status bar, so leave it to show the error.
|
||||
app.ui.backstage = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Quitting asks about every document with unsaved changes, each in its window; the
|
||||
// app closes once that's done (`quit_requested`).
|
||||
Event::Quit => {
|
||||
app.quit();
|
||||
ctx.request_repaint();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
//! The build-time nightly identity shared by the build script and its pure regression tests.
|
||||
pub fn is_nightly_version(version: &str) -> bool {
|
||||
let Some((base, suffix)) = version.split_once("-nightly.") else { return false };
|
||||
let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
|
||||
let base: Vec<_> = base.split('.').collect();
|
||||
let parts: Vec<_> = suffix.split('.').collect();
|
||||
base.len() == 3
|
||||
&& base.iter().all(|s| digits(s))
|
||||
&& parts.len() == 4
|
||||
&& parts[0].len() == 8
|
||||
&& digits(parts[0])
|
||||
&& digits(parts[1])
|
||||
&& digits(parts[2])
|
||||
&& parts[3].strip_prefix('g').is_some_and(|sha| sha.len() == 12 && sha.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)))
|
||||
}
|
||||
pub fn windows_icon_path(nightly: bool) -> &'static str {
|
||||
if nightly { "../../assets/app-icon/wordcraft-nightly.ico" } else { "../../assets/app-icon/wordcraft.ico" }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn windows_resource_uses_the_flavor_specific_icon_without_changing_stable() {
|
||||
assert_eq!(windows_icon_path(false), "../../assets/app-icon/wordcraft.ico");
|
||||
assert_eq!(windows_icon_path(true), "../../assets/app-icon/wordcraft-nightly.ico");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_feed_identity_is_required_for_a_nightly_build() {
|
||||
assert!(is_nightly_version("0.18.1-nightly.20261124.17.1.gabcdef012345"));
|
||||
for invalid in [
|
||||
"",
|
||||
"0.18.1",
|
||||
"0.18.1-nightly",
|
||||
"0.18.1-nightly.20261124",
|
||||
"0.18.1-nightly.20261124.17.1.gABCDEF012345",
|
||||
"0.18.1-nightly.20261124.17.1.gabcdef012345\n",
|
||||
] {
|
||||
assert!(!is_nightly_version(invalid), "{invalid:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn version_cannot_inject_a_path_or_an_extra_build_directive() {
|
||||
for invalid in [
|
||||
"../0.18.1-nightly.20261124.1.1.gabcdef012345",
|
||||
"0.18.1-nightly.20261124.1.1.gabcdef012345/other",
|
||||
"0.18.1-nightly.20261124.1.1.gabcdef012345\ncargo:rustc-cfg=other",
|
||||
] {
|
||||
assert!(!is_nightly_version(invalid));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
//! 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(&[]));
|
||||
}
|
||||
}
|
||||
@@ -1,852 +0,0 @@
|
||||
//! The system clipboard beyond egui's text (#45, #584, #687, #833): text for the ribbon's Paste,
|
||||
//! another program's formatted copy (HTML, and RTF where the platform offers it), pictures and
|
||||
//! copied files, and the names of the formats there for a paste that finds nothing it can use.
|
||||
//!
|
||||
//! On Linux, arboard talks to Wayland compositors through the data-control protocol (KDE Plasma,
|
||||
//! wlroots compositors); without it, a native Wayland window only sees what the compositor copies
|
||||
//! over to Xwayland, which KWin does only while an X11 window has focus — so pictures copied in a
|
||||
//! browser or Spectacle never arrived (#833). Compositors without the protocol fall back to X11.
|
||||
//!
|
||||
//! Everything read here comes from other programs: sizes are capped as it is read.
|
||||
//!
|
||||
//! Written here: a copy puts HTML beside its text, so other programs keep its formatting (#1523),
|
||||
//! with equations as MathML (#816). arboard sets HTML with a text alternative on every desktop
|
||||
//! platform. A copy of one equation alone also goes in the platform's MathML formats (#1297),
|
||||
//! added beside arboard's: on Windows "MathML" and "MathML Presentation" (UTF-16LE), on macOS
|
||||
//! `public.mathml.presentation` and `public.mathml` — the names W3C MathML 3 §6.2.4 registers
|
||||
//! for transferring MathML, and the ones Microsoft documents its Office apps reading first when
|
||||
//! they paste math (learn.microsoft.com/office/math/mathml, "Clipboard support"). Pasting into
|
||||
//! Word and LibreOffice is not yet verified. Linux and the BSDs have no Word, and arboard can't
|
||||
//! add MIME types of other names, so there the HTML carries the MathML alone.
|
||||
//!
|
||||
//! RTF goes beside them where we can add it: Windows ("Rich Text Format") and macOS
|
||||
//! (`public.rtf`) after arboard's HTML, Wayland (`text/rtf`) in one offer with the text and HTML.
|
||||
//! On X11 arboard owns the selection and serves only its own targets, so a copy there carries text
|
||||
//! and HTML only; reading another program's RTF works on all four.
|
||||
|
||||
use wordcraft_engine::cmd::paste::MAX_PASTE_BYTES;
|
||||
use wordcraft_ui_egui::paste_picture::ClipboardPicture;
|
||||
|
||||
fn open() -> Option<arboard::Clipboard> {
|
||||
arboard::Clipboard::new().map_err(|e| log::warn!("clipboard: {e}")).ok()
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// The clipboard copies are set through, kept open: on X11 the contents are served from it.
|
||||
static WRITER: std::cell::RefCell<Option<arboard::Clipboard>> = const { std::cell::RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// Put a copy on the clipboard: `text`, with `html` and `rtf` beside it where the platform takes
|
||||
/// them (an empty one isn't offered), and `mathml` (a copy of one equation alone; empty for any
|
||||
/// other copy) in the platform's MathML formats. `false` when the text and HTML couldn't be set
|
||||
/// (the caller copies the text alone), including a Wayland session without the data-control
|
||||
/// protocol, where arboard would fall back to X11 and native Wayland programs might not see it.
|
||||
/// RTF or MathML that can't be added is logged: the HTML still carries the copy.
|
||||
pub fn set_rich(text: &str, html: &str, rtf: &str, mathml: &str) -> bool {
|
||||
// Wayland: one offer with the text, HTML and RTF (no MathML formats there; see above).
|
||||
if platform::set_rich(text, html, rtf) {
|
||||
return true;
|
||||
}
|
||||
if !platform::can_set() {
|
||||
return false;
|
||||
}
|
||||
let set = set_html_text(html, text);
|
||||
if set && !rtf.is_empty() {
|
||||
platform::add_rtf(rtf);
|
||||
}
|
||||
if set && !mathml.is_empty() && mathml.len() <= MAX_PASTE_BYTES {
|
||||
platform::add_mathml(mathml);
|
||||
}
|
||||
set
|
||||
}
|
||||
|
||||
/// Write HTML and plain text to the system clipboard via the cached writer slot, recording ownership.
|
||||
fn set_html_text(html: &str, text: &str) -> bool {
|
||||
WRITER.with(|w| {
|
||||
let Ok(mut slot) = w.try_borrow_mut() else { return false };
|
||||
if slot.is_none() {
|
||||
*slot = open();
|
||||
}
|
||||
let set = slot.as_mut().map(|c| if html.is_empty() { c.set_text(text) } else { c.set().html(html, Some(text)) });
|
||||
match set {
|
||||
Some(Ok(())) => {
|
||||
platform::record_own();
|
||||
true
|
||||
}
|
||||
Some(Err(e)) => {
|
||||
log::warn!("clipboard: {e}");
|
||||
*slot = None;
|
||||
false
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Put a copied picture on the clipboard: its pixels, with HTML and text beside it where the
|
||||
/// platform takes them. `false` when it couldn't be set.
|
||||
pub fn set_image(image: &wordcraft_ui_egui::system_clipboard::CopyImage, html: &str, text: &str) -> bool {
|
||||
if platform::set_image(image, html, text) {
|
||||
return true;
|
||||
}
|
||||
if !platform::can_set() {
|
||||
return false;
|
||||
}
|
||||
let set = set_image_arboard(image);
|
||||
if set {
|
||||
platform::after_set_image(image, html, text);
|
||||
}
|
||||
set
|
||||
}
|
||||
|
||||
/// Write image pixels to the clipboard through arboard.
|
||||
fn set_image_arboard(image: &wordcraft_ui_egui::system_clipboard::CopyImage) -> bool {
|
||||
WRITER.with(|w| {
|
||||
let Ok(mut slot) = w.try_borrow_mut() else { return false };
|
||||
if slot.is_none() {
|
||||
*slot = open();
|
||||
}
|
||||
let img = arboard::ImageData { width: image.width, height: image.height, bytes: std::borrow::Cow::Borrowed(&image.rgba) };
|
||||
let set = slot.as_mut().map(|c| c.set().image(img));
|
||||
match set {
|
||||
Some(Ok(())) => {
|
||||
platform::record_own();
|
||||
true
|
||||
}
|
||||
Some(Err(e)) => {
|
||||
log::warn!("clipboard image: {e}");
|
||||
*slot = None;
|
||||
false
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the system clipboard still holds WordCraft's last copy.
|
||||
pub fn is_own() -> bool {
|
||||
platform::is_own()
|
||||
}
|
||||
|
||||
/// Wrap HTML in the Windows CF_HTML header format required by clipboard readers.
|
||||
///
|
||||
/// Offsets are byte offsets from the start of the payload; `EndHTML` excludes the trailing NUL.
|
||||
#[cfg(any(target_os = "windows", test))]
|
||||
fn wrap_cf_html(ctn: &str) -> Vec<u8> {
|
||||
let h_version = "Version:0.9";
|
||||
let h_start_html = "\r\nStartHTML:";
|
||||
let h_end_html = "\r\nEndHTML:";
|
||||
let h_start_frag = "\r\nStartFragment:";
|
||||
let h_end_frag = "\r\nEndFragment:";
|
||||
let c_start_frag = "\r\n<html>\r\n<body>\r\n<!--StartFragment-->\r\n";
|
||||
let c_end_frag = "\r\n<!--EndFragment-->\r\n</body>\r\n</html>\0";
|
||||
let h_len = h_version.len() + h_start_html.len() + 10 + h_end_html.len() + 10 + h_start_frag.len() + 10 + h_end_frag.len() + 10;
|
||||
let n_start_html = h_len + 2;
|
||||
let n_start_frag = h_len + c_start_frag.len();
|
||||
let n_end_frag = n_start_frag + ctn.len();
|
||||
let n_end_html = n_end_frag + c_end_frag.len() - 1;
|
||||
let header = format!(
|
||||
"{h_version}{h_start_html}{n_start_html:010}{h_end_html}{n_end_html:010}{h_start_frag}{n_start_frag:010}{h_end_frag}{n_end_frag:010}{c_start_frag}{ctn}{c_end_frag}"
|
||||
);
|
||||
header.into_bytes()
|
||||
}
|
||||
|
||||
/// The clipboard's text.
|
||||
pub fn text() -> Option<String> {
|
||||
open()?.get_text().ok()
|
||||
}
|
||||
|
||||
/// The clipboard's HTML (Windows: the fragment of its "HTML Format"), if not too large.
|
||||
pub fn html() -> Option<String> {
|
||||
open()?.get().html().ok().filter(|h| h.len() <= MAX_PASTE_BYTES)
|
||||
}
|
||||
|
||||
/// The clipboard's RTF: Windows ("Rich Text Format"), macOS (`public.rtf`), Wayland and X11
|
||||
/// (`text/rtf`); not offered by arboard, so read here.
|
||||
pub fn rtf() -> Option<String> {
|
||||
let bytes = platform::rtf()?;
|
||||
if bytes.len() > MAX_PASTE_BYTES {
|
||||
return None;
|
||||
}
|
||||
// RTF is 7-bit by the spec; stray 8-bit bytes become replacement characters.
|
||||
let s = String::from_utf8_lossy(&bytes).trim_end_matches('\0').to_string();
|
||||
s.trim_start().starts_with("{\\rtf").then_some(s)
|
||||
}
|
||||
|
||||
/// The names of the formats on the clipboard, where the platform lists them (Wayland, Windows).
|
||||
pub fn formats() -> Vec<String> {
|
||||
platform::formats()
|
||||
}
|
||||
|
||||
/// The picture on the clipboard: copied files, else image pixels, else (Wayland) an encoded
|
||||
/// picture in a format arboard doesn't decode. A picture that is there but can't be read says
|
||||
/// why (#833). The UI checks the sizes before inserting anything; on Windows and Wayland they are
|
||||
/// checked from the header before anything is decoded (#3623).
|
||||
pub fn picture() -> Option<ClipboardPicture> {
|
||||
let mut clipboard = match arboard::Clipboard::new() {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
log::warn!("clipboard: {e}");
|
||||
return Some(ClipboardPicture::Unreadable(format!("the system clipboard couldn't be opened ({e})")));
|
||||
}
|
||||
};
|
||||
if let Ok(files) = clipboard.get().file_list()
|
||||
&& !files.is_empty()
|
||||
{
|
||||
return Some(ClipboardPicture::Files(files));
|
||||
}
|
||||
decoded_picture(&mut clipboard)
|
||||
}
|
||||
|
||||
/// The clipboard's picture on Windows, read past arboard, which decodes the PNG and DIB formats
|
||||
/// with no size limits (#3623).
|
||||
#[cfg(target_os = "windows")]
|
||||
fn decoded_picture(_: &mut arboard::Clipboard) -> Option<ClipboardPicture> {
|
||||
platform::picture()
|
||||
}
|
||||
|
||||
/// The picture arboard decodes from the clipboard, else an encoded one read past it.
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
fn decoded_picture(clipboard: &mut arboard::Clipboard) -> Option<ClipboardPicture> {
|
||||
#[cfg(all(unix, not(any(target_os = "macos", target_os = "android", target_os = "emscripten"))))]
|
||||
if let Some(picture) = platform::picture() {
|
||||
return Some(picture);
|
||||
}
|
||||
match clipboard.get_image() {
|
||||
Ok(image) => Some(ClipboardPicture::Pixels { width: image.width, height: image.height, rgba: image.bytes.into_owned() }),
|
||||
Err(arboard::Error::ContentNotAvailable) => platform::encoded_picture().map(ClipboardPicture::Encoded),
|
||||
Err(arboard::Error::ConversionFailure) => Some(
|
||||
platform::encoded_picture()
|
||||
.map(ClipboardPicture::Encoded)
|
||||
.unwrap_or_else(|| ClipboardPicture::Unreadable("WordCraft can't decode its format".into())),
|
||||
),
|
||||
Err(e) => {
|
||||
log::warn!("clipboard picture: {e}");
|
||||
platform::encoded_picture().map(ClipboardPicture::Encoded).or(Some(ClipboardPicture::Unreadable(e.to_string())))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Picture types read straight from Wayland when arboard (PNG only) finds none, best first.
|
||||
#[cfg(all(unix, not(any(target_os = "macos", target_os = "android", target_os = "emscripten"))))]
|
||||
const PICTURE_MIMES: [&str; 6] = ["image/png", "image/jpeg", "image/gif", "image/webp", "image/bmp", "image/x-bmp"];
|
||||
|
||||
#[cfg(all(unix, not(any(target_os = "macos", target_os = "android", target_os = "emscripten"))))]
|
||||
mod platform {
|
||||
use std::io::Read;
|
||||
|
||||
use wl_clipboard_rs::paste::{ClipboardType, MimeType, Seat, get_contents, get_mime_types_ordered};
|
||||
use wordcraft_ui_egui::paste_picture::ClipboardPicture;
|
||||
|
||||
fn wayland() -> bool {
|
||||
std::env::var_os("WAYLAND_DISPLAY").is_some()
|
||||
}
|
||||
|
||||
/// One MIME type's bytes, at most `cap`; `None` when absent or larger.
|
||||
fn read(mime: &str, cap: u64) -> Option<Vec<u8>> {
|
||||
let (pipe, _) = get_contents(ClipboardType::Regular, Seat::Unspecified, MimeType::Specific(mime)).ok()?;
|
||||
let mut out = Vec::new();
|
||||
pipe.take(cap.saturating_add(1)).read_to_end(&mut out).ok()?;
|
||||
(out.len() as u64 <= cap).then_some(out)
|
||||
}
|
||||
|
||||
pub fn formats() -> Vec<String> {
|
||||
if !wayland() {
|
||||
return Vec::new();
|
||||
}
|
||||
get_mime_types_ordered(ClipboardType::Regular, Seat::Unspecified).unwrap_or_default()
|
||||
}
|
||||
|
||||
const OWNER_MIME: &str = "application/x-wordcraft-owner";
|
||||
|
||||
/// Process-unique ownership token placed into Wayland clipboard offers.
|
||||
fn owner_token() -> [u8; 16] {
|
||||
static TOKEN: std::sync::OnceLock<[u8; 16]> = std::sync::OnceLock::new();
|
||||
*TOKEN.get_or_init(|| {
|
||||
let mut b = [0u8; 16];
|
||||
let _ = getrandom::fill(&mut b);
|
||||
b
|
||||
})
|
||||
}
|
||||
|
||||
static X11_OWNER: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
|
||||
|
||||
/// Record clipboard ownership for X11 selection tracking.
|
||||
pub fn record_own() {
|
||||
if !wayland() {
|
||||
let win = x11::owner_window().unwrap_or(0);
|
||||
X11_OWNER.store(win, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether WordCraft still owns the Wayland offer or X11 selection.
|
||||
pub fn is_own() -> bool {
|
||||
if wayland() {
|
||||
if formats().iter().any(|m| m == OWNER_MIME) { read(OWNER_MIME, 16).is_some_and(|b| b == owner_token()) } else { false }
|
||||
} else {
|
||||
let current = x11::owner_window().unwrap_or(0);
|
||||
let recorded = X11_OWNER.load(std::sync::atomic::Ordering::Relaxed);
|
||||
recorded != 0 && current == recorded
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether arboard sets the clipboard natively: X11, or Wayland with data-control.
|
||||
pub fn can_set() -> bool {
|
||||
!wayland()
|
||||
|| !matches!(
|
||||
get_mime_types_ordered(ClipboardType::Regular, Seat::Unspecified),
|
||||
Err(wl_clipboard_rs::paste::Error::MissingProtocol { .. } | wl_clipboard_rs::paste::Error::WaylandConnection(_))
|
||||
)
|
||||
}
|
||||
|
||||
/// Put the copy on a Wayland clipboard in one offer: the text (with the usual plain-text
|
||||
/// aliases), HTML and RTF, served from a background thread until something else is copied.
|
||||
/// `false` outside Wayland (X11 goes through arboard) or without the data-control protocol.
|
||||
pub fn set_rich(text: &str, html: &str, rtf: &str) -> bool {
|
||||
use wl_clipboard_rs::copy::{MimeSource, MimeType, Options, Source};
|
||||
|
||||
if !wayland() {
|
||||
return false;
|
||||
}
|
||||
let offer = |mime: &str, data: &str| MimeSource { source: Source::Bytes(data.as_bytes().into()), mime_type: MimeType::Specific(mime.into()) };
|
||||
// The text first: the plain-text aliases serve the first text type offered.
|
||||
let mut sources = vec![offer("text/plain;charset=utf-8", text)];
|
||||
for (mime, data) in [("text/html", html), ("text/rtf", rtf)] {
|
||||
if !data.is_empty() {
|
||||
sources.push(offer(mime, data));
|
||||
}
|
||||
}
|
||||
sources.push(MimeSource { source: Source::Bytes(owner_token().to_vec().into()), mime_type: MimeType::Specific(OWNER_MIME.into()) });
|
||||
match Options::new().copy_multi(sources) {
|
||||
Ok(()) => true,
|
||||
Err(e) => {
|
||||
log::warn!("clipboard: {e}");
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Put a copied picture on the Wayland clipboard alongside HTML, text, and ownership token.
|
||||
pub fn set_image(image: &wordcraft_ui_egui::system_clipboard::CopyImage, html: &str, text: &str) -> bool {
|
||||
use wl_clipboard_rs::copy::{MimeSource, MimeType, Options, Source};
|
||||
|
||||
if !wayland() {
|
||||
return false;
|
||||
}
|
||||
let Ok(png) = wordcraft_ui_egui::paste_picture::png_from_rgba(image.width, image.height, image.rgba.clone()) else {
|
||||
return false;
|
||||
};
|
||||
let offer = |mime: &str, data: &str| MimeSource { source: Source::Bytes(data.as_bytes().into()), mime_type: MimeType::Specific(mime.into()) };
|
||||
let mut sources = vec![MimeSource { source: Source::Bytes(png.into()), mime_type: MimeType::Specific("image/png".into()) }];
|
||||
if !text.is_empty() {
|
||||
sources.push(offer("text/plain;charset=utf-8", text));
|
||||
}
|
||||
if !html.is_empty() {
|
||||
sources.push(offer("text/html", html));
|
||||
}
|
||||
sources.push(MimeSource { source: Source::Bytes(owner_token().to_vec().into()), mime_type: MimeType::Specific(OWNER_MIME.into()) });
|
||||
match Options::new().copy_multi(sources) {
|
||||
Ok(()) => true,
|
||||
Err(e) => {
|
||||
log::warn!("clipboard image: {e}");
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Additional formats to register after setting image via arboard on Unix.
|
||||
pub fn after_set_image(_image: &wordcraft_ui_egui::system_clipboard::CopyImage, _html: &str, _text: &str) {}
|
||||
|
||||
/// Wayland copies carry their RTF already; X11 ones can't (see the module docs).
|
||||
pub fn add_rtf(_rtf: &str) {}
|
||||
|
||||
/// RTF types a clipboard may offer, best first.
|
||||
const RTF_MIMES: [&str; 3] = ["text/rtf", "application/rtf", "text/richtext"];
|
||||
|
||||
/// The RTF type to ask for among those `offered`.
|
||||
fn rtf_target(offered: &[String]) -> Option<&'static str> {
|
||||
RTF_MIMES.into_iter().find(|m| offered.iter().any(|o| o == m))
|
||||
}
|
||||
|
||||
/// arboard serves its own MIME types only; Word, which reads the MathML formats, isn't here.
|
||||
pub fn add_mathml(_mathml: &str) {}
|
||||
|
||||
pub fn rtf() -> Option<Vec<u8>> {
|
||||
if !wayland() {
|
||||
return std::env::var_os("DISPLAY").is_some().then(|| x11::rtf(super::MAX_PASTE_BYTES)).flatten();
|
||||
}
|
||||
let mime = rtf_target(&formats())?;
|
||||
read(mime, super::MAX_PASTE_BYTES as u64)
|
||||
}
|
||||
|
||||
pub fn encoded_picture() -> Option<Vec<u8>> {
|
||||
if !wayland() {
|
||||
return None;
|
||||
}
|
||||
let offered = formats();
|
||||
let mime = super::PICTURE_MIMES.into_iter().find(|m| offered.iter().any(|o| o == m))?;
|
||||
read(mime, wordcraft_ui_egui::paste_picture::MAX_FILE_BYTES)
|
||||
}
|
||||
|
||||
/// Whether a property read of `len` bytes, with `bytes_after` left unread, is the whole value
|
||||
/// and at most `cap` bytes.
|
||||
fn complete(len: usize, bytes_after: u32, cap: usize) -> bool {
|
||||
bytes_after == 0 && len <= cap
|
||||
}
|
||||
|
||||
/// Reading another program's RTF on X11, which arboard doesn't offer: ask the CLIPBOARD
|
||||
/// selection's owner for its targets, then for its RTF, into a property of a hidden window.
|
||||
mod x11 {
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use x11rb::connection::Connection;
|
||||
use x11rb::protocol::Event;
|
||||
use x11rb::protocol::xproto::{Atom, AtomEnum, ConnectionExt as _, CreateWindowAux, GetPropertyReply, Window, WindowClass};
|
||||
use x11rb::rust_connection::RustConnection;
|
||||
|
||||
/// How long a paste waits for the selection's owner, in all.
|
||||
const TIMEOUT: Duration = Duration::from_secs(1);
|
||||
/// Most targets looked at.
|
||||
const MAX_TARGETS: usize = 128;
|
||||
|
||||
struct Reader {
|
||||
conn: RustConnection,
|
||||
win: Window,
|
||||
clipboard: Atom,
|
||||
prop: Atom,
|
||||
deadline: Instant,
|
||||
}
|
||||
|
||||
fn atom(conn: &RustConnection, name: &str) -> Option<Atom> {
|
||||
conn.intern_atom(false, name.as_bytes()).ok()?.reply().ok().map(|r| r.atom)
|
||||
}
|
||||
|
||||
impl Reader {
|
||||
fn new() -> Option<Self> {
|
||||
let (conn, screen) = x11rb::connect(None).ok()?;
|
||||
let root = conn.setup().roots.get(screen)?.root;
|
||||
let win = conn.generate_id().ok()?;
|
||||
conn.create_window(0, win, root, 0, 0, 1, 1, 0, WindowClass::INPUT_ONLY, x11rb::COPY_FROM_PARENT, &CreateWindowAux::new()).ok()?;
|
||||
let clipboard = atom(&conn, "CLIPBOARD")?;
|
||||
let prop = atom(&conn, "WORDCRAFT_PASTE")?;
|
||||
Some(Self { conn, win, clipboard, prop, deadline: Instant::now() + TIMEOUT })
|
||||
}
|
||||
|
||||
/// The selection converted to `target`, at most `cap` bytes; `None` when the owner
|
||||
/// refuses or doesn't answer in time. A longer value is `None` when `whole`, else
|
||||
/// its first `cap` bytes.
|
||||
fn convert(&self, target: Atom, cap: usize, whole: bool) -> Option<GetPropertyReply> {
|
||||
self.conn.convert_selection(self.win, self.clipboard, target, self.prop, x11rb::CURRENT_TIME).ok()?;
|
||||
self.conn.flush().ok()?;
|
||||
loop {
|
||||
// Checked every time round, so a stream of other events can't keep us here.
|
||||
if Instant::now() >= self.deadline {
|
||||
return None;
|
||||
}
|
||||
match self.conn.poll_for_event().ok()? {
|
||||
Some(Event::SelectionNotify(e)) if e.requestor == self.win => {
|
||||
if e.property == x11rb::NONE {
|
||||
return None;
|
||||
}
|
||||
break;
|
||||
}
|
||||
Some(_) => {}
|
||||
None => std::thread::sleep(Duration::from_millis(5)),
|
||||
}
|
||||
}
|
||||
// In 32-bit units; for a whole value one more than the cap, so a larger one shows
|
||||
// as `bytes_after`.
|
||||
let units = u32::try_from(cap / 4 + usize::from(whole)).unwrap_or(u32::MAX);
|
||||
let r = self.conn.get_property(true, self.win, self.prop, AtomEnum::ANY, 0, units).ok()?.reply().ok()?;
|
||||
(!whole || super::complete(r.value.len(), r.bytes_after, cap)).then_some(r)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Reader {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.conn.destroy_window(self.win);
|
||||
let _ = self.conn.flush();
|
||||
}
|
||||
}
|
||||
|
||||
/// The CLIPBOARD selection's RTF, at most `cap` bytes. Copies too large to send at once
|
||||
/// arrive in pieces (INCR), which aren't read: `None` then.
|
||||
pub fn rtf(cap: usize) -> Option<Vec<u8>> {
|
||||
let r = Reader::new()?;
|
||||
// The first targets only: a longer list is cut short, not refused.
|
||||
let targets = r.convert(atom(&r.conn, "TARGETS")?, MAX_TARGETS.saturating_mul(4), false)?;
|
||||
let cookies: Vec<_> = targets.value32()?.take(MAX_TARGETS).filter_map(|a| r.conn.get_atom_name(a).ok()).collect();
|
||||
let names: Vec<String> =
|
||||
cookies.into_iter().filter_map(|c| c.reply().ok()).map(|n| String::from_utf8_lossy(&n.name).into_owned()).collect();
|
||||
let target = atom(&r.conn, super::rtf_target(&names)?)?;
|
||||
let incr = atom(&r.conn, "INCR")?;
|
||||
let reply = r.convert(target, cap, true)?;
|
||||
(reply.type_ != incr).then_some(reply.value)
|
||||
}
|
||||
|
||||
/// Query X11 for the current window id owning the CLIPBOARD selection.
|
||||
pub fn owner_window() -> Option<Window> {
|
||||
let (conn, _) = x11rb::connect(None).ok()?;
|
||||
let clipboard = atom(&conn, "CLIPBOARD")?;
|
||||
let reply = conn.get_selection_owner(clipboard).ok()?.reply().ok()?;
|
||||
(reply.owner != x11rb::NONE).then_some(reply.owner)
|
||||
}
|
||||
}
|
||||
|
||||
/// The Wayland clipboard's picture, read encoded under the paste's byte cap and refused from
|
||||
/// its header when a paste can't take its size, before anything decodes it. arboard decodes
|
||||
/// and converts the PNG to RGBA with no size limits. `None` when Wayland offers no picture
|
||||
/// (or isn't reachable): arboard is asked then, which also covers X11.
|
||||
pub fn picture() -> Option<ClipboardPicture> {
|
||||
if !wayland() {
|
||||
return None;
|
||||
}
|
||||
let offered = formats();
|
||||
let mime = super::PICTURE_MIMES.into_iter().find(|m| offered.iter().any(|o| o == m))?;
|
||||
Some(match read(mime, wordcraft_ui_egui::paste_picture::MAX_FILE_BYTES) {
|
||||
Some(bytes) => wordcraft_ui_egui::paste_picture::encoded_picture(bytes),
|
||||
None => ClipboardPicture::Unreadable("the clipboard picture is larger than 200 MB, or couldn't be read".into()),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn rtf_target_prefers_text_rtf() {
|
||||
let names = |n: &[&str]| n.iter().map(|s| s.to_string()).collect::<Vec<_>>();
|
||||
assert_eq!(rtf_target(&names(&["TARGETS", "text/richtext", "application/rtf", "text/rtf"])), Some("text/rtf"));
|
||||
assert_eq!(rtf_target(&names(&["text/richtext", "UTF8_STRING"])), Some("text/richtext"));
|
||||
assert_eq!(rtf_target(&names(&["text/html", "text/rtf;charset=x"])), None);
|
||||
assert_eq!(rtf_target(&[]), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn property_reads_must_be_whole_and_capped() {
|
||||
assert!(complete(10, 0, 10));
|
||||
assert!(!complete(11, 0, 10), "over the cap");
|
||||
assert!(!complete(8, 4, 10), "more left to read");
|
||||
assert!(complete(0, 0, 0));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
mod platform {
|
||||
use clipboard_win::{Clipboard, EnumFormats, raw};
|
||||
use wordcraft_ui_egui::paste_picture::{self, ClipboardPicture};
|
||||
|
||||
pub fn formats() -> Vec<String> {
|
||||
let Ok(_open) = Clipboard::new_attempts(10) else { return Vec::new() };
|
||||
// Standard formats are named too (CF_BITMAP, CF_UNICODETEXT…).
|
||||
EnumFormats::new().take(64).filter_map(raw::format_name_big).collect()
|
||||
}
|
||||
|
||||
pub fn rtf() -> Option<Vec<u8>> {
|
||||
let format = raw::register_format("Rich Text Format")?;
|
||||
let _open = Clipboard::new_attempts(10).ok()?;
|
||||
if raw::size(format.get()).is_none_or(|n| n.get() > super::MAX_PASTE_BYTES) {
|
||||
return None;
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
raw::get_vec(format.get(), &mut out).ok()?;
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// The clipboard's picture, read without arboard: its "PNG" format as it is, else a DIB as
|
||||
/// pixels, each refused from its header when a paste can't take its size (#3623). None when
|
||||
/// it holds neither.
|
||||
pub fn picture() -> Option<ClipboardPicture> {
|
||||
use clipboard_win::formats::{CF_DIB, CF_DIBV5};
|
||||
let Ok(_open) = Clipboard::new_attempts(10) else {
|
||||
return Some(ClipboardPicture::Unreadable("the system clipboard couldn't be opened".into()));
|
||||
};
|
||||
if let Some(png) = raw::register_format("PNG").map(|f| f.get()).filter(|&f| raw::is_format_avail(f)) {
|
||||
return Some(read(png).map_or_else(ClipboardPicture::Unreadable, paste_picture::encoded_picture));
|
||||
}
|
||||
let dib = [CF_DIBV5, CF_DIB].into_iter().find(|&f| raw::is_format_avail(f))?;
|
||||
Some(read(dib).map_or_else(ClipboardPicture::Unreadable, paste_picture::dib_picture))
|
||||
}
|
||||
|
||||
/// A clipboard format's bytes, refused past the largest picture a paste takes.
|
||||
fn read(format: u32) -> Result<Vec<u8>, String> {
|
||||
match raw::size(format) {
|
||||
Some(n) if n.get() as u64 <= paste_picture::MAX_FILE_BYTES => {}
|
||||
Some(_) => return Err("the clipboard picture is larger than 200 MB".into()),
|
||||
None => return Err("the clipboard picture is empty".into()),
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
raw::get_vec(format, &mut out).map_err(|e| e.to_string())?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
const OWNER_FORMAT: &str = "WordCraft Copy Owner";
|
||||
|
||||
/// Process-unique ownership token placed into Windows clipboard marker.
|
||||
fn owner_token() -> [u8; 16] {
|
||||
static TOKEN: std::sync::OnceLock<[u8; 16]> = std::sync::OnceLock::new();
|
||||
*TOKEN.get_or_init(|| {
|
||||
let mut b = [0u8; 16];
|
||||
let _ = getrandom::fill(&mut b);
|
||||
b
|
||||
})
|
||||
}
|
||||
|
||||
/// Record clipboard ownership for Windows clipboard.
|
||||
pub fn record_own() {
|
||||
let Some(format) = raw::register_format(OWNER_FORMAT) else { return };
|
||||
let Ok(_open) = Clipboard::new_attempts(10) else { return };
|
||||
let _ = raw::set_without_clear(format.get(), &owner_token());
|
||||
}
|
||||
|
||||
/// Whether WordCraft still owns the Windows clipboard contents.
|
||||
pub fn is_own() -> bool {
|
||||
let Some(format) = raw::register_format(OWNER_FORMAT) else { return false };
|
||||
let Ok(_open) = Clipboard::new_attempts(10) else { return false };
|
||||
if !raw::is_format_avail(format.get()) {
|
||||
return false;
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
if raw::get_vec(format.get(), &mut out).is_err() {
|
||||
return false;
|
||||
}
|
||||
out == owner_token()
|
||||
}
|
||||
|
||||
/// Windows supports clipboard setting via arboard and clipboard_win.
|
||||
pub fn can_set() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// arboard sets the text and HTML.
|
||||
pub fn set_rich(_text: &str, _html: &str, _rtf: &str) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// Windows sets the primary image through arboard and supplements via [`after_set_image`].
|
||||
pub fn set_image(_image: &wordcraft_ui_egui::system_clipboard::CopyImage, _html: &str, _text: &str) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// Add PNG and CF_HTML formats alongside arboard's image, then mark ownership.
|
||||
pub fn after_set_image(image: &wordcraft_ui_egui::system_clipboard::CopyImage, html: &str, _text: &str) {
|
||||
if let Ok(png) = wordcraft_ui_egui::paste_picture::png_from_rgba(image.width, image.height, image.rgba.clone())
|
||||
&& let Some(format) = raw::register_format("PNG")
|
||||
&& let Ok(_open) = Clipboard::new_attempts(10)
|
||||
{
|
||||
let _ = raw::set_without_clear(format.get(), &png);
|
||||
}
|
||||
if !html.is_empty()
|
||||
&& let Some(format) = raw::register_format("HTML Format")
|
||||
&& let Ok(_open) = Clipboard::new_attempts(10)
|
||||
{
|
||||
let cf = super::wrap_cf_html(html);
|
||||
let _ = raw::set_without_clear(format.get(), &cf);
|
||||
}
|
||||
record_own();
|
||||
}
|
||||
|
||||
/// Add "Rich Text Format" to what arboard just set, NUL-terminated as is usual.
|
||||
pub fn add_rtf(rtf: &str) {
|
||||
let Some(format) = raw::register_format("Rich Text Format") else { return };
|
||||
let Ok(_open) = Clipboard::new_attempts(10) else { return };
|
||||
let mut bytes = Vec::with_capacity(rtf.len().saturating_add(1));
|
||||
bytes.extend_from_slice(rtf.as_bytes());
|
||||
bytes.push(0);
|
||||
if let Err(e) = raw::set_without_clear(format.get(), &bytes) {
|
||||
log::warn!("clipboard RTF: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Add the MathML to what arboard just set, as "MathML" and "MathML Presentation": UTF-16LE
|
||||
/// text (with its terminating NUL, as Windows text formats have).
|
||||
pub fn add_mathml(mathml: &str) {
|
||||
let Ok(_open) = Clipboard::new_attempts(10) else {
|
||||
log::warn!("clipboard: couldn't open it to add MathML");
|
||||
return;
|
||||
};
|
||||
let bytes: Vec<u8> = mathml.encode_utf16().chain(std::iter::once(0)).flat_map(u16::to_le_bytes).collect();
|
||||
for name in super::MATHML_FORMATS {
|
||||
let Some(format) = raw::register_format(name) else { continue };
|
||||
if let Err(e) = raw::set_without_clear(format.get(), &bytes) {
|
||||
log::warn!("clipboard: {name}: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The clipboard format names for MathML that Windows programs read (W3C MathML 3 §6.2.4; Office
|
||||
/// reads and writes both).
|
||||
#[cfg(target_os = "windows")]
|
||||
const MATHML_FORMATS: [&str; 2] = ["MathML", "MathML Presentation"];
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
mod platform {
|
||||
use objc2_app_kit::NSPasteboard;
|
||||
use objc2_foundation::{NSData, NSString};
|
||||
|
||||
/// RTF's pasteboard type (`NSPasteboardTypeRTF`, whose extern static needs unsafe to read).
|
||||
const RTF: &str = "public.rtf";
|
||||
|
||||
/// Formats offered on macOS pasteboard.
|
||||
pub fn formats() -> Vec<String> {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
/// Read RTF data from macOS pasteboard.
|
||||
pub fn rtf() -> Option<Vec<u8>> {
|
||||
let data = NSPasteboard::generalPasteboard().dataForType(&NSString::from_str(RTF))?;
|
||||
(data.len() <= super::MAX_PASTE_BYTES).then(|| data.to_vec())
|
||||
}
|
||||
|
||||
/// Read encoded picture data from macOS pasteboard.
|
||||
pub fn encoded_picture() -> Option<Vec<u8>> {
|
||||
None
|
||||
}
|
||||
|
||||
static LAST_CHANGE_COUNT: std::sync::atomic::AtomicIsize = std::sync::atomic::AtomicIsize::new(-1);
|
||||
|
||||
/// Record pasteboard changeCount on macOS to verify ownership.
|
||||
pub fn record_own() {
|
||||
let count = NSPasteboard::generalPasteboard().changeCount();
|
||||
LAST_CHANGE_COUNT.store(count, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Whether WordCraft still owns the macOS pasteboard.
|
||||
pub fn is_own() -> bool {
|
||||
let count = NSPasteboard::generalPasteboard().changeCount();
|
||||
let recorded = LAST_CHANGE_COUNT.load(std::sync::atomic::Ordering::Relaxed);
|
||||
recorded >= 0 && count == recorded
|
||||
}
|
||||
|
||||
/// Whether macOS supports setting the pasteboard.
|
||||
pub fn can_set() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// arboard sets the text and HTML.
|
||||
pub fn set_rich(_text: &str, _html: &str, _rtf: &str) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// macOS sets the primary image through arboard and supplements via [`after_set_image`].
|
||||
pub fn set_image(_image: &wordcraft_ui_egui::system_clipboard::CopyImage, _html: &str, _text: &str) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// Set supplemental PNG and HTML representations on macOS pasteboard.
|
||||
pub fn after_set_image(image: &wordcraft_ui_egui::system_clipboard::CopyImage, html: &str, _text: &str) {
|
||||
let board = NSPasteboard::generalPasteboard();
|
||||
if let Ok(png) = wordcraft_ui_egui::paste_picture::png_from_rgba(image.width, image.height, image.rgba.clone()) {
|
||||
let _ = board.setData_forType(Some(&NSData::with_bytes(&png)), &NSString::from_str("public.png"));
|
||||
}
|
||||
if !html.is_empty() {
|
||||
let _ = board.setString_forType(&NSString::from_str(html), &NSString::from_str("public.html"));
|
||||
}
|
||||
record_own();
|
||||
}
|
||||
|
||||
/// Add RTF to the pasteboard item arboard just wrote (it cleared the pasteboard first).
|
||||
pub fn add_rtf(rtf: &str) {
|
||||
if !NSPasteboard::generalPasteboard().setData_forType(Some(&NSData::with_bytes(rtf.as_bytes())), &NSString::from_str(RTF)) {
|
||||
log::warn!("clipboard: the RTF couldn't be added");
|
||||
}
|
||||
}
|
||||
|
||||
/// Add the MathML to the pasteboard item arboard just wrote, as the MathML types (W3C MathML 3
|
||||
/// §6.2.4): presentation markup, and the generic type for readers that only know that one.
|
||||
pub fn add_mathml(mathml: &str) {
|
||||
let board = NSPasteboard::generalPasteboard();
|
||||
let text = NSString::from_str(mathml);
|
||||
for name in ["public.mathml.presentation", "public.mathml"] {
|
||||
if !board.setString_forType(&text, &NSString::from_str(name)) {
|
||||
log::warn!("clipboard: couldn't add {name}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(any(
|
||||
target_os = "windows",
|
||||
target_os = "macos",
|
||||
all(unix, not(any(target_os = "macos", target_os = "android", target_os = "emscripten")))
|
||||
)))]
|
||||
mod platform {
|
||||
/// Formats on the clipboard.
|
||||
pub fn formats() -> Vec<String> {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
/// The RTF bytes on the clipboard.
|
||||
pub fn rtf() -> Option<Vec<u8>> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Encoded picture bytes on the clipboard.
|
||||
pub fn encoded_picture() -> Option<Vec<u8>> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Whether the fallback platform can set the clipboard.
|
||||
pub fn can_set() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// Record clipboard ownership on the fallback platform.
|
||||
pub fn record_own() {}
|
||||
|
||||
/// Whether WordCraft owns the clipboard on the fallback platform.
|
||||
pub fn is_own() -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// Set rich text on the fallback platform.
|
||||
pub fn set_rich(_text: &str, _html: &str, _rtf: &str) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// Set image on the fallback platform.
|
||||
pub fn set_image(_image: &wordcraft_ui_egui::system_clipboard::CopyImage, _html: &str, _text: &str) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// Post-image set hook on the fallback platform.
|
||||
pub fn after_set_image(_image: &wordcraft_ui_egui::system_clipboard::CopyImage, _html: &str, _text: &str) {}
|
||||
|
||||
/// Add RTF to the clipboard on the fallback platform.
|
||||
pub fn add_rtf(_rtf: &str) {}
|
||||
|
||||
/// Add MathML to the clipboard on the fallback platform.
|
||||
pub fn add_mathml(_mathml: &str) {}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod cf_html_tests {
|
||||
use super::wrap_cf_html;
|
||||
|
||||
fn field(data: &[u8], name: &str) -> usize {
|
||||
let at = data.windows(name.len()).position(|w| w == name.as_bytes()).expect("field") + name.len();
|
||||
std::str::from_utf8(&data[at..at + 10]).expect("offset digits").parse().expect("offset")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cf_html_offsets_delimit_the_fragment_bytes() {
|
||||
let fragment = "<p>Olá, 世界 — café</p>";
|
||||
let data = wrap_cf_html(fragment);
|
||||
|
||||
let start_html = field(&data, "StartHTML:");
|
||||
let end_html = field(&data, "EndHTML:");
|
||||
let start_fragment = field(&data, "StartFragment:");
|
||||
let end_fragment = field(&data, "EndFragment:");
|
||||
|
||||
assert!(start_html < start_fragment, "HTML starts before its fragment");
|
||||
assert!(start_fragment < end_fragment, "fragment has a positive length");
|
||||
assert!(end_fragment < end_html, "fragment ends inside the document");
|
||||
assert_eq!(&data[start_html..start_html + "<html>".len()], b"<html>");
|
||||
assert_eq!(&data[start_fragment..end_fragment], fragment.as_bytes());
|
||||
assert_eq!(end_fragment - start_fragment, fragment.len(), "offsets count UTF-8 bytes");
|
||||
assert_eq!(&data[end_html..], b"\0", "EndHTML excludes the trailing NUL");
|
||||
assert_eq!(end_html, data.len() - 1);
|
||||
}
|
||||
}
|
||||
@@ -1,84 +1,50 @@
|
||||
//! Loopback JSON-lines control server: one request per line, one reply per line.
|
||||
//! This is the transport the MCP server (`wordcraft-cli mcp --connect`) wraps.
|
||||
//! The control server: craft-automation's loopback JSON-lines transport, started on the port the
|
||||
//! user asked for.
|
||||
//!
|
||||
//! Every request needs the window's key (`docs/control-protocol.md`, Keys): once the port is
|
||||
//! bound, the app writes a random key to `<settings>/control-key.<instance>` (mode 0600) and
|
||||
//! removes the file when the window closes.
|
||||
//! A connection authenticates once with the token (`docs/control-protocol.md`, Token). When no
|
||||
//! token or token file is supplied, the app generates a token and writes it to
|
||||
//! `<settings>/control-key.<instance>` (mode 0600) after the port is bound, and removes the file
|
||||
//! when the window closes.
|
||||
|
||||
use std::io::{BufRead, BufReader, Read, Write};
|
||||
use std::net::{TcpListener, TcpStream};
|
||||
use std::net::TcpListener;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::mpsc::{Receiver, Sender, channel};
|
||||
use std::time::{Duration, Instant};
|
||||
use std::sync::mpsc::Receiver;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use wordcraft_ui_egui::ControlRequest;
|
||||
use craft::automation::args::ControlOptions;
|
||||
use craft::automation::control::ControlRequest;
|
||||
use craft::automation::server::{Listening, serve};
|
||||
use craft::ui::runtime::windows::WindowHost;
|
||||
|
||||
/// Longer request lines are refused (and the connection closed).
|
||||
const MAX_LINE: usize = 1 << 20;
|
||||
/// A running control server. [`Control::shut_down`] it when the window closes.
|
||||
pub struct Control {
|
||||
/// Dropping it stops accepting connections and frees the port.
|
||||
listening: Listening,
|
||||
/// The default token file this run wrote; a token file the user supplied is never removed.
|
||||
created: Option<PathBuf>,
|
||||
}
|
||||
|
||||
/// A connection that sends no authorised request in this time is closed.
|
||||
const FIRST_REQUEST: Duration = Duration::from_secs(30);
|
||||
|
||||
/// How long a caller waits for the UI to answer a request. A request still queued after this
|
||||
/// is cancelled and never runs.
|
||||
const REPLY_WAIT: Duration = Duration::from_secs(60);
|
||||
|
||||
/// Connections that have not yet sent an authorised request are limited to this many; more are
|
||||
/// closed at once. Each one holds a thread until its first request or [`FIRST_REQUEST`].
|
||||
const MAX_UNAUTHENTICATED: usize = 64;
|
||||
|
||||
/// Counts one unauthenticated connection until it authenticates or ends.
|
||||
struct Admission(Option<Arc<AtomicUsize>>);
|
||||
|
||||
impl Admission {
|
||||
fn enter(count: &Arc<AtomicUsize>, max: usize) -> Option<Self> {
|
||||
if count.fetch_add(1, Ordering::SeqCst) >= max {
|
||||
count.fetch_sub(1, Ordering::SeqCst);
|
||||
return None;
|
||||
}
|
||||
Some(Self(Some(count.clone())))
|
||||
}
|
||||
fn release(&mut self) {
|
||||
if let Some(c) = self.0.take() {
|
||||
c.fetch_sub(1, Ordering::SeqCst);
|
||||
}
|
||||
impl Control {
|
||||
/// Stop accepting connections and remove the token file this run wrote, if any.
|
||||
pub fn shut_down(self) {
|
||||
let Self { listening, created } = self;
|
||||
drop(listening);
|
||||
remove(created.as_deref());
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Admission {
|
||||
fn drop(&mut self) {
|
||||
self.release();
|
||||
fn remove(path: Option<&Path>) {
|
||||
if let Some(path) = path {
|
||||
let _ = std::fs::remove_file(path);
|
||||
}
|
||||
}
|
||||
|
||||
/// The key file of a running control server; [`KeyFile::remove`] it when the window closes.
|
||||
pub struct KeyFile(PathBuf);
|
||||
|
||||
impl KeyFile {
|
||||
pub fn path(&self) -> &Path {
|
||||
&self.0
|
||||
}
|
||||
pub fn remove(&self) {
|
||||
let _ = std::fs::remove_file(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Bind `127.0.0.1:port`, write the key file into `settings` and serve. `None` when the port
|
||||
/// cannot be bound or there is no random key (the control channel is off); the key file is
|
||||
/// `None` when it could not be written (requests are then refused).
|
||||
pub fn start(port: u16, ctx: egui::Context, settings: Option<&Path>) -> Option<(Receiver<ControlRequest>, Option<KeyFile>)> {
|
||||
start_with(port, ctx, settings, |listener, ctx, key| serve_on(listener, ctx, key, FIRST_REQUEST))
|
||||
}
|
||||
|
||||
fn start_with(
|
||||
port: u16,
|
||||
ctx: egui::Context,
|
||||
settings: Option<&Path>,
|
||||
serve: impl FnOnce(TcpListener, egui::Context, String) -> std::io::Result<Receiver<ControlRequest>>,
|
||||
) -> Option<(Receiver<ControlRequest>, Option<KeyFile>)> {
|
||||
/// Bind `127.0.0.1:port`, settle the token and serve. `None` when the port cannot be bound or
|
||||
/// the token cannot be set up (the control channel is off); a taken port leaves no token file.
|
||||
///
|
||||
/// With no token and no token file in `options`, the token is kept in the default file for
|
||||
/// `port` in `settings`; a file left by a run that did not exit cleanly is replaced. Without a
|
||||
/// settings folder a fresh token is generated and reported by the log.
|
||||
pub fn start(options: &ControlOptions, port: u16, host: WindowHost, settings: Option<&Path>) -> Option<(Receiver<ControlRequest>, Control)> {
|
||||
let listener = match TcpListener::bind(("127.0.0.1", port)) {
|
||||
Ok(l) => l,
|
||||
Err(e) => {
|
||||
@@ -86,255 +52,28 @@ fn start_with(
|
||||
return None;
|
||||
}
|
||||
};
|
||||
let key = match random_key() {
|
||||
Ok(k) => k,
|
||||
let created = settings.filter(|_| options.token.is_none() && options.token_file.is_none()).map(|dir| wordcraft_control_key::key_path(dir, port));
|
||||
// The port was free, so no other run owns a file left here.
|
||||
remove(created.as_deref());
|
||||
let effective = ControlOptions { token_file: created.clone().or_else(|| options.token_file.clone()), ..options.clone() };
|
||||
let token = match effective.server_token() {
|
||||
Ok(t) => t,
|
||||
Err(e) => {
|
||||
log::error!("control server off: no random key ({e})");
|
||||
remove(created.as_deref());
|
||||
log::error!("control server off: {e}");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
let key_file = match settings {
|
||||
Some(dir) => {
|
||||
let p = wordcraft_control_key::key_path(dir, port);
|
||||
match write_key_file(&p, &key) {
|
||||
Ok(()) => Some(KeyFile(p)),
|
||||
Err(e) => {
|
||||
log::error!("control key file not written ({e}): requests will be refused");
|
||||
None
|
||||
}
|
||||
}
|
||||
let notice = effective.token_notice(&token);
|
||||
match serve(listener, token, host) {
|
||||
Ok((rx, listening)) => {
|
||||
log::info!("control server listening on {}, {notice}", listening.addr);
|
||||
Some((rx, Control { listening, created }))
|
||||
}
|
||||
None => {
|
||||
log::error!("no settings folder for the control key file: requests will be refused");
|
||||
None
|
||||
}
|
||||
};
|
||||
let rx = match serve(listener, ctx, key) {
|
||||
Ok(rx) => rx,
|
||||
Err(e) => {
|
||||
if let Some(f) = &key_file {
|
||||
f.remove();
|
||||
}
|
||||
remove(created.as_deref());
|
||||
log::error!("control server off: cannot start the accept thread ({e})");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
match &key_file {
|
||||
Some(f) => log::info!("control server listening on 127.0.0.1:{port}, key in {}", f.path().display()),
|
||||
None => log::info!("control server listening on 127.0.0.1:{port}"),
|
||||
}
|
||||
Some((rx, key_file))
|
||||
}
|
||||
|
||||
/// A new key: 32 random bytes from the operating system, as hex.
|
||||
fn random_key() -> Result<String, String> {
|
||||
let mut b = [0u8; 32];
|
||||
getrandom::fill(&mut b).map_err(|e| e.to_string())?;
|
||||
Ok(b.iter().map(|x| format!("{x:02x}")).collect())
|
||||
}
|
||||
|
||||
/// Write the key file: a stale one (from a run that did not exit cleanly) is replaced; on Unix
|
||||
/// the new file is created with mode 0600.
|
||||
fn write_key_file(p: &Path, key: &str) -> Result<(), String> {
|
||||
if let Some(d) = p.parent() {
|
||||
std::fs::create_dir_all(d).map_err(|e| format!("cannot create {}: {e}", d.display()))?;
|
||||
}
|
||||
let _ = std::fs::remove_file(p);
|
||||
let mut open = std::fs::OpenOptions::new();
|
||||
open.write(true).create_new(true);
|
||||
#[cfg(unix)]
|
||||
std::os::unix::fs::OpenOptionsExt::mode(&mut open, 0o600);
|
||||
let mut f = open.open(p).map_err(|e| format!("cannot create {}: {e}", p.display()))?;
|
||||
f.write_all(key.as_bytes()).map_err(|e| format!("cannot write {}: {e}", p.display()))
|
||||
}
|
||||
|
||||
/// Compare a key with the window's in time that does not depend on where they differ. An
|
||||
/// empty key never matches.
|
||||
fn keys_match(given: &str, key: &str) -> bool {
|
||||
let (a, b) = (given.as_bytes(), key.as_bytes());
|
||||
!b.is_empty() && a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
|
||||
}
|
||||
|
||||
fn serve_on(listener: TcpListener, ctx: egui::Context, key: String, first: Duration) -> std::io::Result<Receiver<ControlRequest>> {
|
||||
serve_with(listener, ctx, key, Limits { first, wait: REPLY_WAIT, max_unauthenticated: MAX_UNAUTHENTICATED })
|
||||
}
|
||||
|
||||
/// The time and count budgets of a server (small ones in tests).
|
||||
#[derive(Clone, Copy)]
|
||||
struct Limits {
|
||||
first: Duration,
|
||||
wait: Duration,
|
||||
max_unauthenticated: usize,
|
||||
}
|
||||
|
||||
fn serve_with(listener: TcpListener, ctx: egui::Context, key: String, limits: Limits) -> std::io::Result<Receiver<ControlRequest>> {
|
||||
serve_with_spawner(listener, ctx, key, limits, |accept| std::thread::Builder::new().name("control-accept".into()).spawn(accept).map(|_| ()))
|
||||
}
|
||||
|
||||
fn serve_with_spawner(
|
||||
listener: TcpListener,
|
||||
ctx: egui::Context,
|
||||
key: String,
|
||||
limits: Limits,
|
||||
spawn: impl FnOnce(Box<dyn FnOnce() + Send>) -> std::io::Result<()>,
|
||||
) -> std::io::Result<Receiver<ControlRequest>> {
|
||||
let (tx, rx) = channel::<ControlRequest>();
|
||||
let key: Arc<str> = key.into();
|
||||
let unauthenticated = Arc::new(AtomicUsize::new(0));
|
||||
let accept = move || {
|
||||
for stream in listener.incoming().flatten() {
|
||||
let Some(admission) = Admission::enter(&unauthenticated, limits.max_unauthenticated) else {
|
||||
log::warn!("control server: too many unauthenticated connections, one closed");
|
||||
continue;
|
||||
};
|
||||
let (tx, ctx, key) = (tx.clone(), ctx.clone(), key.clone());
|
||||
// A thread that cannot start closes this connection only (the guard releases its slot).
|
||||
if let Err(e) = std::thread::Builder::new().name("control-conn".into()).spawn(move || serve(stream, tx, ctx, &key, limits, admission)) {
|
||||
log::warn!("control server: no thread for a connection: {e}");
|
||||
}
|
||||
}
|
||||
};
|
||||
spawn(Box::new(accept))?;
|
||||
Ok(rx)
|
||||
}
|
||||
|
||||
/// The read side of a connection with an optional overall deadline: each read waits only for
|
||||
/// the time left, so blank lines, bad JSON or a slow drip of bytes cannot extend it.
|
||||
struct Timed {
|
||||
s: TcpStream,
|
||||
deadline: Option<Instant>,
|
||||
}
|
||||
|
||||
impl Read for Timed {
|
||||
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
|
||||
if let Some(d) = self.deadline {
|
||||
let left = d.checked_duration_since(Instant::now()).filter(|l| !l.is_zero()).ok_or(std::io::ErrorKind::TimedOut)?;
|
||||
self.s.set_read_timeout(Some(left))?;
|
||||
}
|
||||
self.s.read(buf)
|
||||
}
|
||||
}
|
||||
|
||||
impl Timed {
|
||||
fn set_deadline(&mut self, d: Option<Instant>) {
|
||||
self.deadline = d;
|
||||
if d.is_none() {
|
||||
let _ = self.s.set_read_timeout(None);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The next line (trimmed), `None` at the end of the stream or after a read error.
|
||||
fn read_line(r: &mut BufReader<Timed>) -> Option<Result<String, &'static str>> {
|
||||
let mut buf = Vec::new();
|
||||
let n = r.by_ref().take(MAX_LINE as u64 + 1).read_until(b'\n', &mut buf).ok()?;
|
||||
if n == 0 {
|
||||
return None;
|
||||
}
|
||||
if buf.len() > MAX_LINE {
|
||||
return Some(Err("line too long"));
|
||||
}
|
||||
Some(String::from_utf8(buf).map(|s| s.trim().to_string()).map_err(|_| "not UTF-8"))
|
||||
}
|
||||
|
||||
/// Read and drop the rest of an oversize line, so closing the socket does not reset the
|
||||
/// connection before the client has read the error. At most 64 MiB, within 2 s.
|
||||
fn discard_rest_of_line(r: &mut BufReader<Timed>) {
|
||||
r.get_mut().set_deadline(Some(Instant::now() + Duration::from_secs(2)));
|
||||
let mut left: usize = 64 << 20;
|
||||
while left > 0 {
|
||||
let (used, done) = match r.fill_buf() {
|
||||
Ok([]) | Err(_) => return,
|
||||
Ok(b) => match b.iter().position(|&c| c == b'\n') {
|
||||
Some(i) => (i + 1, true),
|
||||
None => (b.len(), false),
|
||||
},
|
||||
};
|
||||
r.consume(used);
|
||||
if done {
|
||||
return;
|
||||
}
|
||||
left = left.saturating_sub(used);
|
||||
}
|
||||
}
|
||||
|
||||
fn serve(stream: TcpStream, tx: Sender<ControlRequest>, ctx: egui::Context, key: &str, limits: Limits, mut admission: Admission) {
|
||||
let Ok(read) = stream.try_clone() else { return };
|
||||
let mut out = stream;
|
||||
// One overall deadline from accept to the first authorised request; after it, none.
|
||||
let mut reader = BufReader::new(Timed { s: read, deadline: Some(Instant::now() + limits.first) });
|
||||
let mut authorised = false;
|
||||
// The key an `auth` request gave this connection.
|
||||
let mut conn_key: Option<String> = None;
|
||||
while let Some(line) = read_line(&mut reader) {
|
||||
let line = match line {
|
||||
Ok(l) => l,
|
||||
Err(e) => {
|
||||
let _ = writeln!(out, "{}", json!({"ok": false, "error": e}));
|
||||
if e == "line too long" {
|
||||
discard_rest_of_line(&mut reader);
|
||||
}
|
||||
break;
|
||||
}
|
||||
};
|
||||
if line.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let msg = match serde_json::from_str::<Value>(&line) {
|
||||
Ok(m) => m,
|
||||
// Close on a line that isn't JSON: an HTTP request (say, a web page's `fetch` to this
|
||||
// port) starts with a request line that never parses, so it can't carry a command in
|
||||
// its body, even before the key is checked.
|
||||
Err(e) => {
|
||||
let _ = writeln!(out, "{}", json!({"ok": false, "error": format!("bad JSON: {e}; closing the connection")}));
|
||||
break;
|
||||
}
|
||||
};
|
||||
let id = msg.get("id").cloned().unwrap_or(Value::Null);
|
||||
let method = msg.get("method").and_then(Value::as_str).unwrap_or("").to_string();
|
||||
let params = msg.get("params").cloned().unwrap_or(json!({}));
|
||||
// The top-level `key`; `auth` may carry it in its params. For other methods `params.key`
|
||||
// is an ordinary parameter (`ui.key {"key": "Enter"}`).
|
||||
let given =
|
||||
msg.get("key").and_then(Value::as_str).or_else(|| if method == "auth" { params.get("key").and_then(Value::as_str) } else { None });
|
||||
let mut reply = |mut v: Value| -> bool {
|
||||
if let Some(o) = v.as_object_mut() {
|
||||
o.insert("id".into(), id.clone());
|
||||
}
|
||||
writeln!(out, "{v}").is_ok()
|
||||
};
|
||||
// Checked on every request.
|
||||
let k = given.or(conn_key.as_deref()).unwrap_or("");
|
||||
if !keys_match(k, key) {
|
||||
let _ = reply(json!({"ok": false, "error": "unauthorized"}));
|
||||
break;
|
||||
}
|
||||
if !authorised {
|
||||
authorised = true;
|
||||
admission.release();
|
||||
reader.get_mut().set_deadline(None);
|
||||
}
|
||||
if method == "auth" {
|
||||
conn_key = Some(k.to_string());
|
||||
if !reply(json!({"ok": true, "result": {}})) {
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let (req, rrx, waiter) = ControlRequest::with_waiter(method, params);
|
||||
if tx.send(req).is_err() {
|
||||
break;
|
||||
}
|
||||
ctx.request_repaint();
|
||||
let r = rrx.recv_timeout(limits.wait).unwrap_or_else(|_| {
|
||||
if waiter.cancel() {
|
||||
json!({"ok": false, "error": "timeout before execution: the request was not run and never will be"})
|
||||
} else {
|
||||
json!({"ok": false, "error": "timeout: outcome unknown, the request had started when the wait ended; inspect the document to check"})
|
||||
}
|
||||
});
|
||||
if !reply(r) {
|
||||
break;
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -342,402 +81,209 @@ fn serve(stream: TcpStream, tx: Sender<ControlRequest>, ctx: egui::Context, key:
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::net::TcpStream;
|
||||
use craft::automation::client::ControlClient;
|
||||
|
||||
const KEY: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
|
||||
|
||||
fn boot_with(first: Duration) -> (u16, Receiver<ControlRequest>) {
|
||||
let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
(port, serve_on(listener, egui::Context::default(), KEY.to_string(), first).unwrap())
|
||||
fn host() -> WindowHost {
|
||||
WindowHost::of(&egui::Context::default())
|
||||
}
|
||||
|
||||
fn boot() -> (u16, Receiver<ControlRequest>) {
|
||||
boot_with(FIRST_REQUEST)
|
||||
#[test]
|
||||
fn the_token_file_is_written_after_the_bind_and_removed_on_exit() {
|
||||
let dir = std::env::temp_dir().join(format!("wordcraft-control-life-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let options = ControlOptions::default();
|
||||
|
||||
// The port is taken: no token file.
|
||||
let taken = TcpListener::bind(("127.0.0.1", 0)).unwrap();
|
||||
let port = taken.local_addr().unwrap().port();
|
||||
assert!(start(&options, port, host(), Some(&dir)).is_none());
|
||||
assert!(!dir.exists() || std::fs::read_dir(&dir).unwrap().next().is_none(), "no token file after a failed bind");
|
||||
drop(taken);
|
||||
|
||||
// Bound: the default file holds the token that opens the port.
|
||||
let (_rx, control) = start(&options, 0, host(), Some(&dir)).unwrap();
|
||||
let path = control.created.clone().unwrap();
|
||||
assert_eq!(path, wordcraft_control_key::key_path(&dir, 0));
|
||||
let token = std::fs::read_to_string(&path).unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
|
||||
}
|
||||
assert!(ControlClient::connect(control.listening.addr, token.trim()).is_ok());
|
||||
control.shut_down();
|
||||
assert!(!path.exists());
|
||||
|
||||
// A token file the user supplied stays.
|
||||
let supplied = dir.join("supplied-token");
|
||||
let options = ControlOptions { token_file: Some(supplied.clone()), ..ControlOptions::default() };
|
||||
let (_rx, control) = start(&options, 0, host(), Some(&dir)).unwrap();
|
||||
assert!(control.created.is_none());
|
||||
control.shut_down();
|
||||
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(Duration::from_secs(5)).unwrap();
|
||||
let _ = req.reply.send(json!({"ok": true, "result": {}}));
|
||||
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(BufReader<TcpStream>, TcpStream);
|
||||
struct Conn(std::io::BufReader<std::net::TcpStream>, std::net::TcpStream);
|
||||
|
||||
impl Conn {
|
||||
fn open(port: u16) -> Self {
|
||||
Self::open_within(port, Duration::from_secs(5))
|
||||
}
|
||||
fn open_within(port: u16, read_timeout: Duration) -> Self {
|
||||
let s = TcpStream::connect(("127.0.0.1", port)).unwrap();
|
||||
s.set_read_timeout(Some(read_timeout)).unwrap();
|
||||
Self(BufReader::new(s.try_clone().unwrap()), s)
|
||||
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) -> Value {
|
||||
fn recv(&mut self) -> serde_json::Value {
|
||||
use std::io::BufRead;
|
||||
let mut r = String::new();
|
||||
let _ = self.0.read_line(&mut r);
|
||||
serde_json::from_str(&r).unwrap_or_default()
|
||||
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) -> Value {
|
||||
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();
|
||||
closed_by_peer(self.0.read_line(&mut r))
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a read means the peer closed the connection. End of stream does; so does a reset,
|
||||
/// which is how Windows can deliver a close when the writer had nothing to read back (the
|
||||
/// Windows Print job failed here). Any other error, such as `InvalidData` for bytes that are
|
||||
/// not UTF-8, leaves the connection open.
|
||||
fn closed_by_peer(read: std::io::Result<usize>) -> bool {
|
||||
match read {
|
||||
Ok(n) => n == 0,
|
||||
Err(e) => matches!(
|
||||
e.kind(),
|
||||
std::io::ErrorKind::ConnectionReset
|
||||
| std::io::ErrorKind::ConnectionAborted
|
||||
| std::io::ErrorKind::NotConnected
|
||||
| std::io::ErrorKind::BrokenPipe
|
||||
),
|
||||
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_request_without_the_key_is_refused_and_closed() {
|
||||
let (port, rx) = boot();
|
||||
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 r = c.call(r#"{"id":1,"method":"document.inspect"}"#);
|
||||
assert_eq!((r["ok"].clone(), r["error"].clone(), r["id"].clone()), (json!(false), json!("unauthorized"), json!(1)));
|
||||
assert!(c.closed());
|
||||
assert!(rx.try_recv().is_err(), "nothing reached the UI");
|
||||
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 a_wrong_key_is_refused_and_closed() {
|
||||
let (port, rx) = boot();
|
||||
for key in ["nope", &KEY[..63], &format!("{KEY}0"), &KEY.to_uppercase()] {
|
||||
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(&format!(r#"{{"id":1,"key":"{key}","method":"document.inspect"}}"#))["error"], "unauthorized", "{key}");
|
||||
assert_eq!(c.call(&line), serde_json::json!({"id": id, "ok": false, "error": "authentication required"}));
|
||||
assert!(c.closed());
|
||||
}
|
||||
assert!(rx.try_recv().is_err());
|
||||
}
|
||||
assert!(rx.try_recv().is_err(), "refused requests must not reach the UI");
|
||||
|
||||
#[test]
|
||||
fn the_key_on_each_request() {
|
||||
let (port, rx) = boot();
|
||||
// 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);
|
||||
c.send(&format!(r#"{{"id":7,"key":"{KEY}","method":"document.inspect","params":{{"text":true}}}}"#));
|
||||
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), ("document.inspect", &json!({"text": true})));
|
||||
assert_eq!((req.method.as_str(), &req.params), ("ui.key", &serde_json::json!({"key": "Enter"})));
|
||||
let r = c.recv();
|
||||
assert_eq!((r["ok"].clone(), r["id"].clone()), (json!(true), json!(7)));
|
||||
// Every request needs it: one without the key is refused, also after good ones.
|
||||
assert_eq!(c.call(r#"{"id":8,"method":"document.inspect"}"#)["error"], "unauthorized");
|
||||
assert!(c.closed());
|
||||
}
|
||||
assert_eq!((&r["ok"], &r["id"]), (&serde_json::json!(true), &serde_json::json!(2)));
|
||||
|
||||
#[test]
|
||||
fn auth_once_per_connection() {
|
||||
let (port, rx) = boot();
|
||||
let mut c = Conn::open(port);
|
||||
assert_eq!(c.call(&format!(r#"{{"id":1,"method":"auth","key":"{KEY}"}}"#))["ok"], true);
|
||||
for id in 2..4 {
|
||||
c.send(&format!(r#"{{"id":{id},"method":"document.inspect"}}"#));
|
||||
answer(&rx);
|
||||
assert_eq!(c.recv()["ok"], true);
|
||||
}
|
||||
// `params.key` works for `auth` too.
|
||||
let mut c = Conn::open(port);
|
||||
assert_eq!(c.call(&format!(r#"{{"id":1,"method":"auth","params":{{"key":"{KEY}"}}}}"#))["ok"], true);
|
||||
// A wrong key on an authenticated connection is still refused, and closes it.
|
||||
assert_eq!(c.call(r#"{"id":2,"key":"nope","method":"document.inspect"}"#)["error"], "unauthorized");
|
||||
assert!(c.closed());
|
||||
// A failed auth closes the connection.
|
||||
let mut c = Conn::open(port);
|
||||
assert_eq!(c.call(r#"{"id":1,"method":"auth","key":"nope"}"#)["error"], "unauthorized");
|
||||
assert!(c.closed());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn params_key_is_only_a_secret_for_auth() {
|
||||
let (port, rx) = boot();
|
||||
// `params.key` does not authenticate other methods.
|
||||
let mut c = Conn::open(port);
|
||||
assert_eq!(c.call(&format!(r#"{{"id":1,"method":"document.inspect","params":{{"key":"{KEY}"}}}}"#))["error"], "unauthorized");
|
||||
// It is an ordinary parameter for them (`ui.key` presses a key).
|
||||
let mut c = Conn::open(port);
|
||||
c.send(&format!(r#"{{"id":1,"key":"{KEY}","method":"ui.key","params":{{"key":"Enter"}}}}"#));
|
||||
c.send(r#"{"id":3,"method":"document.inspect","params":{"token":"ordinary"}}"#);
|
||||
let req = answer(&rx);
|
||||
assert_eq!((req.method.as_str(), &req.params), ("ui.key", &json!({"key": "Enter"})));
|
||||
assert_eq!(c.recv()["ok"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_over_1_mib_is_refused_and_closed() {
|
||||
let (port, rx) = boot();
|
||||
let mut c = Conn::open(port);
|
||||
let big = format!(r#"{{"id":1,"key":"{KEY}","method":"document.inspect","pad":"{}"}}"#, "x".repeat(MAX_LINE));
|
||||
assert_eq!(c.call(&big)["error"], "line too long");
|
||||
assert!(c.closed());
|
||||
assert!(rx.try_recv().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_closure_errors_mean_the_peer_closed() {
|
||||
use std::io::{Error, ErrorKind};
|
||||
assert!(closed_by_peer(Ok(0)), "end of stream");
|
||||
for kind in [ErrorKind::ConnectionReset, ErrorKind::ConnectionAborted, ErrorKind::NotConnected, ErrorKind::BrokenPipe] {
|
||||
assert!(closed_by_peer(Err(Error::new(kind, "closed"))), "{kind:?}");
|
||||
}
|
||||
assert!(!closed_by_peer(Ok(1)), "a reply arrived");
|
||||
// Not UTF-8, a timeout or a would-block leave the socket open.
|
||||
for kind in [ErrorKind::InvalidData, ErrorKind::TimedOut, ErrorKind::WouldBlock] {
|
||||
assert!(!closed_by_peer(Err(Error::new(kind, "still open"))), "{kind:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_silent_connection_is_closed() {
|
||||
let (port, rx) = boot_with(Duration::from_millis(300));
|
||||
// A loaded Windows CI runner can take seconds to schedule the connection thread. The
|
||||
// production deadline is 30 s, so 10 s still proves the server's own budget fired.
|
||||
let mut quiet = Conn::open_within(port, Duration::from_secs(20));
|
||||
let t0 = Instant::now();
|
||||
assert!(quiet.closed());
|
||||
assert!(t0.elapsed() < Duration::from_secs(10), "{:?}", t0.elapsed());
|
||||
// After an authorised request the connection may stay idle.
|
||||
let mut busy = Conn::open(port);
|
||||
assert_eq!(busy.call(&format!(r#"{{"id":1,"method":"auth","key":"{KEY}"}}"#))["ok"], true);
|
||||
std::thread::sleep(Duration::from_millis(600));
|
||||
busy.send(r#"{"id":2,"method":"document.inspect"}"#);
|
||||
answer(&rx);
|
||||
assert_eq!(busy.recv()["ok"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_first_request_limit_is_one_overall_deadline() {
|
||||
// Blank lines and bad JSON do not keep a connection without the key open.
|
||||
let (port, _rx) = boot_with(Duration::from_millis(300));
|
||||
let s = TcpStream::connect(("127.0.0.1", port)).unwrap();
|
||||
let mut w = s.try_clone().unwrap();
|
||||
let feeder = std::thread::spawn(move || {
|
||||
for i in 0..40 {
|
||||
if w.write_all(if i % 2 == 0 { b"\n" } else { b"not json\n" }).is_err() {
|
||||
return;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
});
|
||||
let t0 = Instant::now();
|
||||
let mut r = BufReader::new(s);
|
||||
r.get_ref().set_read_timeout(Some(Duration::from_secs(5))).unwrap();
|
||||
let mut line = String::new();
|
||||
loop {
|
||||
line.clear();
|
||||
if matches!(r.read_line(&mut line), Ok(0) | Err(_)) {
|
||||
break;
|
||||
}
|
||||
assert!(line.contains("bad JSON"), "{line}");
|
||||
}
|
||||
let _ = feeder.join();
|
||||
assert!(t0.elapsed() < Duration::from_millis(1500), "{:?}", t0.elapsed());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_json_closes_the_connection() {
|
||||
let (port, rx) = boot();
|
||||
let mut c = Conn::open(port);
|
||||
assert_eq!(c.call("not json")["ok"], false);
|
||||
assert!(c.closed());
|
||||
assert!(rx.try_recv().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn http_request_cannot_smuggle_a_command() {
|
||||
// What a web page's `fetch("http://127.0.0.1:<port>/", {method: "POST", body})` sends,
|
||||
// even with the key in the body.
|
||||
let (port, rx) = boot();
|
||||
let body = format!("\n{{\"key\":\"{KEY}\",\"method\":\"file.saveAs\",\"params\":{{\"path\":\"/tmp/x.docx\"}}}}\n");
|
||||
let req = format!("POST / HTTP/1.1\r\nHost: 127.0.0.1:7981\r\nContent-Type: text/plain\r\nContent-Length: {}\r\n\r\n{body}", body.len());
|
||||
let mut c = Conn::open(port);
|
||||
c.1.write_all(req.as_bytes()).unwrap();
|
||||
let _ = c.recv();
|
||||
assert!(c.closed());
|
||||
assert!(rx.recv_timeout(Duration::from_millis(300)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keys_compare_whole() {
|
||||
assert!(keys_match(KEY, KEY));
|
||||
assert!(!keys_match(KEY, &KEY[..63]));
|
||||
assert!(!keys_match(&KEY[..63], KEY));
|
||||
assert!(!keys_match(KEY, &KEY.replace('f', "e")));
|
||||
assert!(!keys_match("", ""), "an empty key never matches");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn random_keys_are_256_bits() {
|
||||
let (a, b) = (random_key().unwrap(), random_key().unwrap());
|
||||
assert_eq!(a.len(), 64);
|
||||
assert!(a.bytes().all(|c| c.is_ascii_hexdigit()));
|
||||
assert_ne!(a, b);
|
||||
}
|
||||
|
||||
fn temp_dir(name: &str) -> std::path::PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("wordcraft-control-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
dir
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_key_file_is_written_after_the_bind_and_removed_on_exit() {
|
||||
let dir = temp_dir("life");
|
||||
// The port is taken: no key file.
|
||||
let taken = TcpListener::bind(("127.0.0.1", 0)).unwrap();
|
||||
let port = taken.local_addr().unwrap().port();
|
||||
assert!(start(port, egui::Context::default(), Some(&dir)).is_none());
|
||||
assert!(!dir.exists() || std::fs::read_dir(&dir).unwrap().next().is_none(), "no key file after a failed bind");
|
||||
drop(taken);
|
||||
// Bound: the key file holds the key that opens the port.
|
||||
let mut free_port = port.wrapping_add(1).max(1024);
|
||||
let mut started = None;
|
||||
for _ in 0..100 {
|
||||
if let Some(res) = start(free_port, egui::Context::default(), Some(&dir)) {
|
||||
started = Some((res, free_port));
|
||||
break;
|
||||
}
|
||||
free_port = free_port.wrapping_add(1).max(1024);
|
||||
}
|
||||
let ((rx, key_file), port) = started.unwrap();
|
||||
let key_file = key_file.unwrap();
|
||||
assert_eq!(key_file.path(), wordcraft_control_key::key_path(&dir, port));
|
||||
let key = std::fs::read_to_string(key_file.path()).unwrap();
|
||||
assert_eq!(key.len(), 64);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
assert_eq!(std::fs::metadata(key_file.path()).unwrap().permissions().mode() & 0o777, 0o600);
|
||||
}
|
||||
let mut c = Conn::open(port);
|
||||
c.send(&format!(r#"{{"id":1,"key":"{key}","method":"document.inspect"}}"#));
|
||||
answer(&rx);
|
||||
assert_eq!(c.recv()["ok"], true);
|
||||
key_file.remove();
|
||||
assert!(!key_file.path().exists());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_accept_thread_spawn_failure_aborts_start_and_removes_the_key() {
|
||||
let dir = temp_dir("spawn-failure");
|
||||
let path = wordcraft_control_key::key_path(&dir, 0);
|
||||
let mut bound = None;
|
||||
let result = start_with(0, egui::Context::default(), Some(&dir), |listener, ctx, key| {
|
||||
bound = Some(listener.local_addr().unwrap());
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), key, "startup wrote the key before spawning");
|
||||
serve_with_spawner(listener, ctx, key, small(150, 8), |accept| {
|
||||
drop(accept);
|
||||
Err(std::io::Error::other("injected accept thread spawn failure"))
|
||||
})
|
||||
});
|
||||
assert!(result.is_none(), "a server without its accept thread must not report success");
|
||||
assert!(!path.exists(), "failed startup must remove its published key");
|
||||
let _listener = TcpListener::bind(bound.unwrap()).unwrap();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_complete_json_request_at_eof_can_reach_the_ui() {
|
||||
// This is why a bridge write failure before the newline is outcome-unknown.
|
||||
let (port, rx) = boot();
|
||||
let mut c = Conn::open(port);
|
||||
let body = json!({"id": 1, "key": KEY, "method": "engine.execute", "params": {"command": "text.insert", "params": {"text": "once"}}});
|
||||
c.1.write_all(body.to_string().as_bytes()).unwrap();
|
||||
c.1.shutdown(std::net::Shutdown::Write).unwrap();
|
||||
let req = answer(&rx);
|
||||
assert_eq!(req.params["params"]["text"], "once");
|
||||
assert_eq!(c.recv()["ok"], true);
|
||||
assert!(c.closed());
|
||||
assert!(rx.try_recv().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stale_key_file_is_replaced() {
|
||||
let dir = temp_dir("stale");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let p = dir.join("control-key.test");
|
||||
std::fs::write(&p, "old").unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o644)).unwrap();
|
||||
}
|
||||
write_key_file(&p, KEY).unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&p).unwrap(), KEY);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
assert_eq!(std::fs::metadata(&p).unwrap().permissions().mode() & 0o777, 0o600);
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
fn boot_limits(limits: Limits) -> (u16, Receiver<ControlRequest>) {
|
||||
let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
(port, serve_with(listener, egui::Context::default(), KEY.to_string(), limits).unwrap())
|
||||
}
|
||||
|
||||
fn small(wait_ms: u64, max_unauthenticated: usize) -> Limits {
|
||||
Limits { first: FIRST_REQUEST, wait: Duration::from_millis(wait_ms), max_unauthenticated }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_request_that_timed_out_in_the_queue_never_runs() {
|
||||
let (port, rx) = boot_limits(small(150, 8));
|
||||
let mut c = Conn::open(port);
|
||||
let r = c.call(&format!(r#"{{"id":1,"key":"{KEY}","method":"engine.execute","params":{{"command":"text.insert"}}}}"#));
|
||||
assert_eq!(r["ok"], false);
|
||||
assert!(r["error"].as_str().unwrap_or("").starts_with("timeout before execution"), "{r}");
|
||||
// The UI gets to it late: it must not run it.
|
||||
let req = rx.recv_timeout(Duration::from_secs(5)).unwrap();
|
||||
assert!(!req.start(), "a cancelled request was started");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_request_that_started_before_the_timeout_reports_an_unknown_outcome() {
|
||||
let (port, rx) = boot_limits(small(150, 8));
|
||||
let mut c = Conn::open(port);
|
||||
c.send(&format!(r#"{{"id":1,"key":"{KEY}","method":"engine.execute","params":{{"command":"text.insert"}}}}"#));
|
||||
let req = rx.recv_timeout(Duration::from_secs(5)).unwrap();
|
||||
assert!(req.start());
|
||||
assert_eq!((req.method.as_str(), &req.params), ("document.inspect", &serde_json::json!({"token": "ordinary"})));
|
||||
let r = c.recv();
|
||||
assert!(r["error"].as_str().unwrap_or("").contains("outcome unknown"), "{r}");
|
||||
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 unauthenticated_connections_are_limited() {
|
||||
let (port, rx) = boot_limits(small(5_000, 2));
|
||||
let mut idle = [Conn::open(port), Conn::open(port)];
|
||||
// Give the server time to count both.
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
assert!(Conn::open(port).closed(), "the third idle connection was admitted");
|
||||
// One authenticates: its slot is free again.
|
||||
assert_eq!(idle[0].call(&format!(r#"{{"id":1,"method":"auth","key":"{KEY}"}}"#))["ok"], true);
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
let mut again = Conn::open(port);
|
||||
assert_eq!(again.call(&format!(r#"{{"id":1,"method":"auth","key":"{KEY}"}}"#))["ok"], true);
|
||||
assert!(rx.try_recv().is_err());
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,10 +2,10 @@
|
||||
//!
|
||||
//! The installers register WordCraft for Word, RTF and ODT files without taking over the
|
||||
//! defaults (`packaging/windows/wordcraft.wxs`, the `.desktop` file's `MimeType=`, `Info.plist`).
|
||||
//! This is the button that makes it the default when the user asks:
|
||||
//! This is the button that makes it the default when the user asks; the work is
|
||||
//! `craft::platform::default_app::make_default`, which this file gives WordCraft's identity:
|
||||
//! - **Windows** doesn't let apps set defaults: it opens Settings › Default apps on WordCraft's
|
||||
//! page (`ms-settings:defaultapps?registeredAppMachine=WordCraft`; Windows 10 ignores the query
|
||||
//! and shows the Default apps list), where the user picks WordCraft per type.
|
||||
//! registered page, where the user picks WordCraft per type.
|
||||
//! - **Linux and BSD**: `xdg-mime default ai.storyteller.wordcraft.desktop <types>` for
|
||||
//! [`WORD_MIME_TYPES`], which writes the user's `mimeapps.list`. Only when the desktop entry is
|
||||
//! installed (deb, rpm, Flatpak; a bare AppImage has none), and not from inside the Flatpak
|
||||
@@ -14,24 +14,11 @@
|
||||
//!
|
||||
//! [`WORD_MIME_TYPES`]: self::WORD_MIME_TYPES
|
||||
|
||||
use wordcraft_ui_egui::DefaultApp;
|
||||
|
||||
/// The `Services::make_default_app` hook.
|
||||
pub type Hook = Box<dyn Fn() -> Result<DefaultApp, String>>;
|
||||
|
||||
/// The hook for this platform; `None` where there is no button (macOS).
|
||||
pub fn hook() -> Option<Hook> {
|
||||
#[cfg(target_os = "windows")]
|
||||
let hook: Option<Hook> = Some(Box::new(windows::open_default_apps));
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
let hook: Option<Hook> = Some(Box::new(xdg::make_default));
|
||||
#[cfg(not(any(target_os = "windows", all(unix, not(target_os = "macos")))))]
|
||||
let hook: Option<Hook> = None;
|
||||
hook
|
||||
}
|
||||
#[cfg(any(unix, windows, test))]
|
||||
use craft::platform::default_app::AppIdentity;
|
||||
|
||||
/// The desktop entry the Linux packages install, and the Flatpak's app id.
|
||||
#[cfg(any(all(unix, not(target_os = "macos")), test))]
|
||||
#[cfg(any(unix, windows, test))]
|
||||
const DESKTOP_ID: &str = "ai.storyteller.wordcraft.desktop";
|
||||
|
||||
/// The types the button makes WordCraft the default for on Linux and BSD: Word documents and
|
||||
@@ -39,7 +26,7 @@ const DESKTOP_ID: &str = "ai.storyteller.wordcraft.desktop";
|
||||
/// lists under WordCraft's Capabilities; Markdown is only offered under Open With, and plain
|
||||
/// text only on Windows and macOS (the `.desktop` file leaves it out, #4137).
|
||||
/// Every one is in the `.desktop` file's `MimeType=` (a test checks).
|
||||
#[cfg(any(all(unix, not(target_os = "macos")), test))]
|
||||
#[cfg(any(unix, windows, test))]
|
||||
const WORD_MIME_TYPES: &[&str] = &[
|
||||
"application/vnd.openxmlformats-officedocument.wordprocessingml.document", // .docx
|
||||
"application/vnd.ms-word.document.macroEnabled.12", // .docm
|
||||
@@ -52,105 +39,36 @@ const WORD_MIME_TYPES: &[&str] = &[
|
||||
"application/vnd.oasis.opendocument.text", // .odt
|
||||
];
|
||||
|
||||
/// The arguments for `xdg-mime` that make `desktop_id` the default for [`WORD_MIME_TYPES`]: one
|
||||
/// call sets them all.
|
||||
#[cfg(any(all(unix, not(target_os = "macos")), test))]
|
||||
fn xdg_mime_args(desktop_id: &str) -> Vec<String> {
|
||||
["default", desktop_id].into_iter().chain(WORD_MIME_TYPES.iter().copied()).map(str::to_string).collect()
|
||||
}
|
||||
|
||||
/// The `applications` folders the desktop looks for entries in, from `XDG_DATA_HOME` (default
|
||||
/// `~/.local/share`) and `XDG_DATA_DIRS` (default `/usr/local/share:/usr/share`). Relative paths
|
||||
/// are ignored, as the XDG Base Directory spec says.
|
||||
#[cfg(all(unix, any(not(target_os = "macos"), test)))]
|
||||
fn application_dirs(data_home: Option<&str>, data_dirs: Option<&str>, home: Option<&str>) -> Vec<std::path::PathBuf> {
|
||||
use std::path::{Path, PathBuf};
|
||||
let absolute = |s: &&str| Path::new(s).is_absolute();
|
||||
let home_dir = data_home
|
||||
.filter(|s| !s.is_empty())
|
||||
.filter(absolute)
|
||||
.map(PathBuf::from)
|
||||
.or_else(|| home.filter(|s| !s.is_empty()).filter(absolute).map(|h| Path::new(h).join(".local/share")));
|
||||
let system = data_dirs.filter(|s| !s.is_empty()).unwrap_or("/usr/local/share:/usr/share");
|
||||
home_dir
|
||||
.into_iter()
|
||||
.chain(system.split(':').filter(|s| !s.is_empty()).filter(absolute).map(PathBuf::from))
|
||||
.map(|d| d.join("applications"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
mod windows {
|
||||
use wordcraft_ui_egui::DefaultApp;
|
||||
|
||||
/// Settings › Default apps, on the page of the app registered as `WordCraft` under
|
||||
/// `HKLM\Software\RegisteredApplications` (the MSI writes it).
|
||||
const SETTINGS_URI: &str = "ms-settings:defaultapps?registeredAppMachine=WordCraft";
|
||||
|
||||
pub(super) fn open_default_apps() -> Result<DefaultApp, String> {
|
||||
open::that_detached(SETTINGS_URI).map_err(|e| format!("couldn't open Settings: {e}"))?;
|
||||
Ok(DefaultApp::SettingsOpened)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
mod xdg {
|
||||
use std::process::Command;
|
||||
|
||||
use wordcraft_ui_egui::DefaultApp;
|
||||
|
||||
use super::{DESKTOP_ID, application_dirs, xdg_mime_args};
|
||||
|
||||
/// The longest error text from `xdg-mime` shown in the status bar.
|
||||
const MAX_ERROR: usize = 200;
|
||||
|
||||
pub(super) fn make_default() -> Result<DefaultApp, String> {
|
||||
if std::env::var_os("FLATPAK_ID").is_some() || std::path::Path::new("/.flatpak-info").exists() {
|
||||
return Err(
|
||||
"the Flatpak sandbox can't change default apps; choose WordCraft under Open With in your file manager or system settings".into()
|
||||
);
|
||||
}
|
||||
let var = |k: &str| std::env::var(k).ok();
|
||||
let dirs = application_dirs(var("XDG_DATA_HOME").as_deref(), var("XDG_DATA_DIRS").as_deref(), var("HOME").as_deref());
|
||||
if !dirs.iter().any(|d| d.join(DESKTOP_ID).is_file()) {
|
||||
return Err(format!("{DESKTOP_ID} isn't installed (an AppImage needs desktop integration first)"));
|
||||
}
|
||||
let out = Command::new("xdg-mime").args(xdg_mime_args(DESKTOP_ID)).output().map_err(|e| match e.kind() {
|
||||
std::io::ErrorKind::NotFound => "xdg-mime isn't installed (it comes with xdg-utils)".to_string(),
|
||||
_ => format!("couldn't run xdg-mime: {e}"),
|
||||
})?;
|
||||
if out.status.success() {
|
||||
return Ok(DefaultApp::MadeDefault);
|
||||
}
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
let first = stderr.lines().map(str::trim).find(|l| !l.is_empty()).unwrap_or("");
|
||||
let message: String = first.chars().take(MAX_ERROR).collect();
|
||||
Err(if message.is_empty() { format!("xdg-mime failed ({})", out.status) } else { format!("xdg-mime failed: {message}") })
|
||||
/// Who WordCraft is to the system: the name the MSI registers under `RegisteredApplications`, the
|
||||
/// desktop entry, and the types the button claims.
|
||||
#[cfg(any(unix, windows, test))]
|
||||
pub fn identity() -> AppIdentity {
|
||||
AppIdentity {
|
||||
registered_name: "WordCraft".to_string(),
|
||||
desktop_id: DESKTOP_ID.to_string(),
|
||||
mime_types: WORD_MIME_TYPES.iter().map(|t| (*t).to_string()).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[cfg(unix)]
|
||||
use std::path::PathBuf;
|
||||
|
||||
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 args = xdg_mime_args(DESKTOP_ID);
|
||||
assert_eq!(args.first().map(String::as_str), Some("default"));
|
||||
assert_eq!(args.get(1).map(String::as_str), Some("ai.storyteller.wordcraft.desktop"));
|
||||
assert_eq!(&args[2..], WORD_MIME_TYPES);
|
||||
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!(args.iter().any(|a| a == t), "{t}");
|
||||
assert!(id.mime_types.iter().any(|a| a == t), "{t}");
|
||||
}
|
||||
assert!(!args.iter().any(|a| a == "text/plain" || a == "text/markdown"), "plain text and Markdown are never claimed");
|
||||
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.
|
||||
@@ -174,21 +92,4 @@ mod tests {
|
||||
assert!(!declared.is_empty(), "MimeType= line not found");
|
||||
assert!(!declared.contains(&"text/plain"), "text/plain must not be declared");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn application_dirs_follow_the_xdg_spec() {
|
||||
let p = |s: &str| PathBuf::from(s);
|
||||
assert_eq!(
|
||||
application_dirs(None, None, Some("/home/a")),
|
||||
[p("/home/a/.local/share/applications"), p("/usr/local/share/applications"), p("/usr/share/applications")]
|
||||
);
|
||||
assert_eq!(
|
||||
application_dirs(Some("/data"), Some("/opt/share::relative:/usr/share"), Some("/home/a")),
|
||||
[p("/data/applications"), p("/opt/share/applications"), p("/usr/share/applications")]
|
||||
);
|
||||
// Empty or relative values fall back to the defaults; no home at all is fine.
|
||||
assert_eq!(application_dirs(Some(""), Some(""), None), [p("/usr/local/share/applications"), p("/usr/share/applications")]);
|
||||
assert_eq!(application_dirs(Some("rel"), None, Some("also-rel")), [p("/usr/local/share/applications"), p("/usr/share/applications")]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,473 +0,0 @@
|
||||
//! Native file dialogs (Open, Save As, Export, pictures) that don't freeze the window (#94).
|
||||
//!
|
||||
//! The blocking `rfd::FileDialog` ran on the UI thread: on Linux the xdg-desktop-portal call
|
||||
//! blocked the event loop until the dialog closed, and with no parent window the dialog could open
|
||||
//! behind WordCraft, which then sat there frozen. Now the app's request ([`Services::file_dialog`])
|
||||
//! is queued; the frame (which has the window) builds an `rfd::AsyncFileDialog` parented to the
|
||||
//! window, and a background thread waits for the answer, hands it to the app and wakes the UI.
|
||||
//!
|
||||
//! On Linux and the BSDs rfd asks the xdg-desktop-portal FileChooser and, failing that, runs
|
||||
//! `zenity`; with neither (a minimal Wayland compositor such as labwc with only
|
||||
//! xdg-desktop-portal-wlr, #576) it answers "cancelled" and nothing ever shows. So the waiting
|
||||
//! thread first checks that one of them is there and otherwise answers with an error, and the app
|
||||
//! shows its built-in file browser. `WORDCRAFT_FILE_DIALOG=builtin` always uses the built-in one.
|
||||
//!
|
||||
//! On Linux and the BSDs, rfd reports a portal that failed to show its dialog as a cancel (#2999).
|
||||
//! There a cancel quicker than anyone could dismiss a dialog is taken as that failure: the dialog
|
||||
//! is asked for once more without a parent window, and if that also comes back at once the
|
||||
//! built-in browser shows. Windows and macOS always show their dialog, so a quick cancel there is
|
||||
//! the person's and is answered as one.
|
||||
//!
|
||||
//! [`Services::file_dialog`]: wordcraft_ui_egui::Services::file_dialog
|
||||
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
use std::sync::mpsc::{Receiver, Sender, channel};
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use wordcraft_ui_egui::{FileDialogAnswer, FileDialogRequest};
|
||||
|
||||
/// A dialog the app asked for, with the channel its answer goes back through.
|
||||
type Request = (FileDialogRequest, Sender<FileDialogAnswer>);
|
||||
|
||||
/// The `Services::file_dialog` hook.
|
||||
pub type Hook = Box<dyn Fn(FileDialogRequest) -> Receiver<FileDialogAnswer>>;
|
||||
|
||||
/// Cancels the portal Save dialog the launcher is waiting on, if any.
|
||||
///
|
||||
/// The portal's dialog lives outside the app's window, so a portal that stops answering cannot be
|
||||
/// dismissed from WordCraft. Giving the dialog up (File › Open › Browse in WordCraft…) cancels the
|
||||
/// request: the waiting thread closes it and reports a cancellation, and the built-in browser
|
||||
/// opens instead. A no-op where Save As doesn't ask the portal (macOS and Windows).
|
||||
#[derive(Clone, Default)]
|
||||
pub struct CancelHandle {
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
armed: Arc<Mutex<Option<Armed>>>,
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
next_id: Arc<std::sync::atomic::AtomicU64>,
|
||||
}
|
||||
|
||||
/// The token a request installed in [`CancelHandle`], with the identity that owns it.
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
struct Armed {
|
||||
id: u64,
|
||||
token: crate::portal_save::CancelToken,
|
||||
}
|
||||
|
||||
impl CancelHandle {
|
||||
/// Cancels the pending portal request, if there is one.
|
||||
pub fn cancel(&self) {
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
{
|
||||
let mut slot = self.armed.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some(armed) = slot.take() {
|
||||
armed.token.cancel();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Arms the handle for the portal request about to wait, returning its token and identity.
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
fn arm(&self) -> Armed {
|
||||
let id = self.next_id.fetch_add(1, std::sync::atomic::Ordering::Relaxed).wrapping_add(1);
|
||||
let token = crate::portal_save::CancelToken::new();
|
||||
*self.armed.lock().unwrap_or_else(|e| e.into_inner()) = Some(Armed { id, token: token.clone() });
|
||||
Armed { id, token }
|
||||
}
|
||||
|
||||
/// Disarms the handle once the request with `id` has answered, leaving a newer request's
|
||||
/// token alone: an abandoned request finishing late must not make the next one uncancellable.
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
fn disarm(&self, id: u64) {
|
||||
let mut slot = self.armed.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if slot.as_ref().is_some_and(|armed| armed.id == id) {
|
||||
*slot = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A picker's answer, waited for off the UI thread.
|
||||
type Picking = Pin<Box<dyn Future<Output = Vec<rfd::FileHandle>> + Send>>;
|
||||
|
||||
/// Shows the dialogs the app queued; lives in the eframe app, which has the window.
|
||||
pub struct Launcher {
|
||||
queue: Receiver<Request>,
|
||||
ctx: egui::Context,
|
||||
cancel: CancelHandle,
|
||||
}
|
||||
|
||||
/// The hook for [`Services::file_dialog`](wordcraft_ui_egui::Services::file_dialog) and the
|
||||
/// launcher that shows what it queues.
|
||||
pub fn hook(ctx: &egui::Context) -> (Hook, Launcher) {
|
||||
let (queue_tx, queue) = channel::<Request>();
|
||||
let hook: Hook = Box::new(move |req| {
|
||||
let (answer, rx) = channel();
|
||||
// If the launcher is gone, the dropped answer reads as "cancelled" in the app.
|
||||
let _ = queue_tx.send((req, answer));
|
||||
rx
|
||||
});
|
||||
(hook, Launcher { queue, ctx: ctx.clone(), cancel: CancelHandle::default() })
|
||||
}
|
||||
|
||||
impl Launcher {
|
||||
/// A handle that cancels the portal Save dialog the launcher is waiting on, if any.
|
||||
pub fn cancel_handle(&self) -> CancelHandle {
|
||||
self.cancel.clone()
|
||||
}
|
||||
|
||||
/// Show the queued dialogs with the window as their parent, so the portal (or the system)
|
||||
/// keeps them on top of it. Call after every pass that may ask for one.
|
||||
pub fn show(&self, parent: &eframe::Frame) {
|
||||
while let Ok((req, answer)) = self.queue.try_recv() {
|
||||
// Built here, on the UI thread: macOS shows the panel as a sheet on the window now.
|
||||
let picking = picker(rfd::AsyncFileDialog::new().set_parent(parent), &req);
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
let unparented = picker(rfd::AsyncFileDialog::new(), &req);
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
let parent_id = {
|
||||
use eframe::wgpu::rwh::HasWindowHandle;
|
||||
crate::portal_save::parent_id(parent.window_handle().ok().map(|h| h.as_raw()))
|
||||
};
|
||||
// Armed before the thread starts, so giving the dialog up cannot race its start.
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
let portal_arm = matches!(&req, FileDialogRequest::Save { .. }).then(|| self.cancel.arm());
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
let portal_id = portal_arm.as_ref().map(|armed| armed.id);
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
let cancel_handle = self.cancel.clone();
|
||||
let ctx = self.ctx.clone();
|
||||
let waiting = std::thread::Builder::new().name("file dialog".into()).spawn(move || {
|
||||
// The pickers only start when first polled: without a system dialog they never do.
|
||||
let picked = match no_system_dialog() {
|
||||
Some(reason) => Err(reason),
|
||||
None => {
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
{
|
||||
if let FileDialogRequest::Save { name, dir } = &req {
|
||||
let cancel = portal_arm.as_ref().map(|armed| armed.token.clone());
|
||||
let portal_req = crate::portal_save::SaveRequest {
|
||||
parent: parent_id,
|
||||
name: Some(name.clone()),
|
||||
suggested: Some(name.clone()),
|
||||
folder: dir.clone().map(std::path::PathBuf::from),
|
||||
filters: save_filters(name),
|
||||
current: Some(0),
|
||||
cancel,
|
||||
timeout: None,
|
||||
};
|
||||
let portal_res = zbus::blocking::Connection::session()
|
||||
.map_err(|e| e.to_string())
|
||||
.and_then(|conn| crate::portal_save::save_as(&conn, portal_req));
|
||||
match portal_res {
|
||||
Ok(Some(path)) => Ok(vec![path.to_string_lossy().into_owned()]),
|
||||
Ok(None) => Ok(Vec::new()),
|
||||
Err(e) if crate::portal_save::is_cancelled_error(&e) => Ok(Vec::new()),
|
||||
Err(e) if crate::portal_save::is_ambiguous_filter_error(&e) => {
|
||||
log::warn!("portal save format ambiguous ({e}); cancelling save without explicit format choice");
|
||||
Ok(Vec::new())
|
||||
}
|
||||
Err(e) => {
|
||||
// Giving the dialog up cancels the request. A portal that then
|
||||
// fails with another error must not open the rfd dialog, which
|
||||
// nothing would be waiting for.
|
||||
if portal_arm.as_ref().is_some_and(|armed| armed.token.is_cancelled()) {
|
||||
log::info!("portal save dialog given up ({e})");
|
||||
Ok(Vec::new())
|
||||
} else {
|
||||
log::info!("portal save dialog unavailable ({e}), using rfd");
|
||||
let picked = pick(picking, unparented, TOO_QUICK);
|
||||
picked.map(|f| f.iter().map(|f| f.path().to_string_lossy().to_string()).collect())
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Only the portal folds a failure into "cancelled" (#2999).
|
||||
let picked = pick(picking, unparented, TOO_QUICK);
|
||||
picked.map(|f| f.iter().map(|f| f.path().to_string_lossy().to_string()).collect())
|
||||
}
|
||||
}
|
||||
#[cfg(not(all(unix, not(target_os = "macos"))))]
|
||||
{
|
||||
let picked: Result<_, String> = Ok(pollster::block_on(picking));
|
||||
picked.map(|f| f.iter().map(|f| f.path().to_string_lossy().to_string()).collect())
|
||||
}
|
||||
}
|
||||
};
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
if let Some(armed) = &portal_arm {
|
||||
cancel_handle.disarm(armed.id);
|
||||
}
|
||||
let _ = answer.send(picked);
|
||||
ctx.request_repaint();
|
||||
});
|
||||
// The answer's sender went with the closure, so the app sees the dialog as cancelled.
|
||||
if let Err(e) = waiting {
|
||||
log::error!("couldn't wait for the file dialog: {e}");
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
if let Some(id) = portal_id {
|
||||
self.cancel.disarm(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The picker for `req` on `dialog`.
|
||||
fn picker(dialog: rfd::AsyncFileDialog, req: &FileDialogRequest) -> Picking {
|
||||
match req.clone() {
|
||||
FileDialogRequest::Open { purpose } => Box::pin(async move { open_filters(dialog, &purpose).pick_file().await.into_iter().collect() }),
|
||||
FileDialogRequest::OpenMany { purpose } => Box::pin(async move { open_filters(dialog, &purpose).pick_files().await.unwrap_or_default() }),
|
||||
FileDialogRequest::Save { name, dir } => {
|
||||
let mut dialog = dialog.set_file_name(name.clone());
|
||||
// Save as Word Template starts in the user templates folder (#2852).
|
||||
if let Some(dir) = dir.filter(|d| std::path::Path::new(d).is_dir()) {
|
||||
dialog = dialog.set_directory(dir);
|
||||
}
|
||||
for (label, exts) in save_filters(&name) {
|
||||
dialog = dialog.add_filter(label, &exts);
|
||||
}
|
||||
Box::pin(async move { dialog.save_file().await.into_iter().collect() })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Quicker than anyone can see a dialog and dismiss it.
|
||||
// ponytail: a timing heuristic, as rfd folds the portal's failure code into "cancelled". A portal
|
||||
// failing slower than this still reads as a cancel; ask rfd for the response code if it matters.
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
const TOO_QUICK: std::time::Duration = std::time::Duration::from_millis(300);
|
||||
|
||||
/// Wait for `picking`. Nothing picked within `too_quick` is a portal that failed to show its
|
||||
/// dialog (#2999), not a person cancelling: try `unparented`, as a portal may fail on the parent
|
||||
/// window; if that too comes back at once, an error, so the app shows its built-in browser.
|
||||
/// Linux and the BSDs only (built everywhere for its test).
|
||||
#[cfg(any(test, all(unix, not(target_os = "macos"))))]
|
||||
fn pick<T>(
|
||||
picking: impl Future<Output = Vec<T>>,
|
||||
unparented: impl Future<Output = Vec<T>>,
|
||||
too_quick: std::time::Duration,
|
||||
) -> Result<Vec<T>, String> {
|
||||
fn timed<T>(f: impl Future<Output = Vec<T>>, too_quick: std::time::Duration) -> (Vec<T>, bool) {
|
||||
let start = std::time::Instant::now();
|
||||
let picked = pollster::block_on(f);
|
||||
let quick = picked.is_empty() && start.elapsed() < too_quick;
|
||||
(picked, quick)
|
||||
}
|
||||
match timed(picking, too_quick) {
|
||||
(_, true) => log::warn!("the system file dialog closed at once; asking again without a parent window"),
|
||||
(picked, false) => return Ok(picked),
|
||||
}
|
||||
match timed(unparented, too_quick) {
|
||||
(_, true) => Err("the system file dialog closed at once".into()),
|
||||
(picked, false) => Ok(picked),
|
||||
}
|
||||
}
|
||||
|
||||
/// The file types Open offers (shared with the built-in browser).
|
||||
fn open_filters(mut d: rfd::AsyncFileDialog, purpose: &str) -> rfd::AsyncFileDialog {
|
||||
for (name, exts) in wordcraft_ui_egui::open_filters(purpose) {
|
||||
d = d.add_filter(*name, exts);
|
||||
}
|
||||
d
|
||||
}
|
||||
|
||||
/// Why no system file dialog can be shown, if it can't (#576); run off the UI thread.
|
||||
fn no_system_dialog() -> Option<String> {
|
||||
if std::env::var_os("WORDCRAFT_FILE_DIALOG").is_some_and(|v| v == "builtin") {
|
||||
return Some("WORDCRAFT_FILE_DIALOG=builtin".into());
|
||||
}
|
||||
portal_or_zenity_missing()
|
||||
}
|
||||
|
||||
/// Linux and the BSDs: rfd needs a file chooser portal or zenity. When `dbus-send` can't ask
|
||||
/// the session bus, the answer is unknown and rfd gets to try.
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
fn portal_or_zenity_missing() -> Option<String> {
|
||||
if on_path("zenity") {
|
||||
return None;
|
||||
}
|
||||
let portal = std::process::Command::new("dbus-send")
|
||||
.args([
|
||||
"--session",
|
||||
"--print-reply=literal",
|
||||
"--reply-timeout=10000",
|
||||
"--dest=org.freedesktop.portal.Desktop",
|
||||
"/org/freedesktop/portal/desktop",
|
||||
"org.freedesktop.DBus.Properties.Get",
|
||||
"string:org.freedesktop.portal.FileChooser",
|
||||
"string:version",
|
||||
])
|
||||
.stdin(std::process::Stdio::null())
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::null())
|
||||
.status();
|
||||
match portal {
|
||||
Ok(status) if !status.success() => Some("no xdg-desktop-portal FileChooser on the session bus and no zenity".into()),
|
||||
Ok(_) => None,
|
||||
Err(e) => {
|
||||
log::debug!("couldn't ask D-Bus for the file chooser portal: {e}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Windows and macOS always have their system dialog.
|
||||
#[cfg(not(all(unix, not(target_os = "macos"))))]
|
||||
fn portal_or_zenity_missing() -> Option<String> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Whether an executable named `program` is in a `PATH` folder.
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
fn on_path(program: &str) -> bool {
|
||||
std::env::var_os("PATH").is_some_and(|paths| std::env::split_paths(&paths).any(|dir| dir.join(program).is_file()))
|
||||
}
|
||||
|
||||
/// The file types Save As offers: every format the engine saves, with the suggested name's own
|
||||
/// format first. rfd makes a filter's first extension the dialog's default, which the Windows,
|
||||
/// macOS and Linux panels append to a file name the user typed without one; with no filter at
|
||||
/// all the name came back bare and the save failed, since the format is chosen by extension
|
||||
/// (#689).
|
||||
fn save_exts(name: &str) -> Vec<String> {
|
||||
let suggested = std::path::Path::new(name)
|
||||
.extension()
|
||||
.and_then(std::ffi::OsStr::to_str)
|
||||
.map(str::to_ascii_lowercase)
|
||||
// A .markdown file is under Markdown's one entry in the list.
|
||||
.map(|e| if e == "markdown" { "md".to_string() } else { e })
|
||||
.filter(|e| wordcraft_engine::io::SAVE_EXTS.contains(&e.as_str()))
|
||||
.unwrap_or_else(|| "docx".to_string());
|
||||
let mut exts: Vec<String> = Vec::with_capacity(wordcraft_engine::io::SAVE_EXTS.len());
|
||||
exts.push(suggested.clone());
|
||||
exts.extend(wordcraft_engine::io::SAVE_EXTS.iter().filter(|e| **e != suggested).map(|e| (*e).to_string()));
|
||||
exts
|
||||
}
|
||||
|
||||
/// The "Save as type" list (#1399): one named entry per format, the suggested one first (see
|
||||
/// [`save_exts`] for why the order matters).
|
||||
///
|
||||
/// On Linux and the BSDs, [`crate::portal_save`] asks the portal directly over D-Bus and gives a
|
||||
/// name the dialog left alone the chosen type's extension (#6180). When falling back to `rfd`, the
|
||||
/// extension in the name wins, as `rfd` doesn't report which entry the user picked.
|
||||
fn save_filters(name: &str) -> Vec<(String, Vec<String>)> {
|
||||
save_exts(name).into_iter().map(|e| (format!("{} (*.{e})", format_name(&e)), vec![e])).collect()
|
||||
}
|
||||
|
||||
/// A readable name for a save format's extension.
|
||||
fn format_name(ext: &str) -> String {
|
||||
match ext {
|
||||
"docx" => "Word Document".into(),
|
||||
"docm" => "Word Macro-Enabled Document".into(),
|
||||
"dotx" => "Word Template".into(),
|
||||
"dotm" => "Word Macro-Enabled Template".into(),
|
||||
"pdf" => "PDF".into(),
|
||||
"txt" => "Plain Text".into(),
|
||||
"md" => "Markdown".into(),
|
||||
"html" => "Web Page".into(),
|
||||
"rtf" => "Rich Text Format".into(),
|
||||
"odt" => "OpenDocument Text".into(),
|
||||
"ott" => "OpenDocument Text Template".into(),
|
||||
"fodt" => "Flat OpenDocument Text".into(),
|
||||
"tex" => "LaTeX".into(),
|
||||
"png" => "PNG Image".into(),
|
||||
"json" => "JSON".into(),
|
||||
"xml" => "XML".into(),
|
||||
other => other.to_ascii_uppercase(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{pick, save_exts, save_filters};
|
||||
use std::time::Duration;
|
||||
|
||||
/// #2999: a dialog that "cancels" at once is a portal that failed: asked again without a
|
||||
/// parent, then the built-in browser. A pick, or a cancel after a while, is the answer.
|
||||
#[test]
|
||||
fn an_instant_cancel_retries_then_falls_back() {
|
||||
let quick = Duration::from_millis(200);
|
||||
let slow_cancel = || async {
|
||||
// The test polls this future by hand, with no async runtime, so a blocking sleep
|
||||
// models a slow portal response.
|
||||
std::thread::sleep(Duration::from_millis(250)); // NOSONAR
|
||||
Vec::<u8>::new()
|
||||
};
|
||||
assert_eq!(pick(async { vec![1u8] }, async { vec![2] }, quick), Ok(vec![1]));
|
||||
assert_eq!(pick(async { vec![] }, async { vec![2u8] }, quick), Ok(vec![2]), "asked again without a parent");
|
||||
assert!(pick(async { Vec::<u8>::new() }, async { vec![] }, quick).is_err(), "the built-in browser");
|
||||
assert_eq!(pick(slow_cancel(), async { vec![2u8] }, quick), Ok(vec![]), "a real cancel isn't asked again");
|
||||
assert_eq!(pick(async { vec![] }, slow_cancel(), quick), Ok(vec![]), "the second dialog cancelled for real");
|
||||
}
|
||||
|
||||
/// Giving the portal Save dialog up cancels the request the launcher armed, and a request
|
||||
/// that has already answered is not affected by a later cancel.
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
#[test]
|
||||
fn cancelling_a_pending_portal_request_marks_its_token() {
|
||||
let handle = super::CancelHandle::default();
|
||||
let armed = handle.arm();
|
||||
assert!(!armed.token.is_cancelled());
|
||||
handle.cancel();
|
||||
assert!(armed.token.is_cancelled());
|
||||
|
||||
let answered = handle.arm();
|
||||
handle.disarm(answered.id);
|
||||
handle.cancel();
|
||||
assert!(!answered.token.is_cancelled(), "an answered request is no longer cancelled");
|
||||
}
|
||||
|
||||
/// A request that finishes late must not disarm the token of a request started after it:
|
||||
/// otherwise the newer Save dialog would become uncancellable.
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
#[test]
|
||||
fn a_late_answer_keeps_the_newer_requests_token() {
|
||||
let handle = super::CancelHandle::default();
|
||||
let abandoned = handle.arm();
|
||||
let newer = handle.arm();
|
||||
handle.disarm(abandoned.id);
|
||||
handle.cancel();
|
||||
assert!(newer.token.is_cancelled(), "the newer request is still armed");
|
||||
assert!(!abandoned.token.is_cancelled(), "only the armed request is cancelled");
|
||||
}
|
||||
|
||||
/// #1399: the Save dialog's type list has one named entry per format, the suggested one first,
|
||||
/// every savable extension exactly once.
|
||||
#[test]
|
||||
fn save_dialog_lists_one_named_type_per_format() {
|
||||
let filters = save_filters("report.odt");
|
||||
assert_eq!(filters.len(), wordcraft_engine::io::SAVE_EXTS.len());
|
||||
assert_eq!(filters[0].1, vec!["odt".to_string()]);
|
||||
assert!(filters[0].0.contains("OpenDocument"), "{}", filters[0].0);
|
||||
let all: Vec<&String> = filters.iter().flat_map(|(_, e)| e).collect();
|
||||
for e in wordcraft_engine::io::SAVE_EXTS {
|
||||
assert_eq!(all.iter().filter(|x| x.as_str() == *e).count(), 1, "{e}");
|
||||
}
|
||||
assert!(filters.iter().all(|(l, e)| !l.trim().is_empty() && e.len() == 1));
|
||||
let mut labels: Vec<&String> = filters.iter().map(|(l, _)| l).collect();
|
||||
labels.sort();
|
||||
labels.dedup();
|
||||
assert_eq!(labels.len(), filters.len(), "labels are distinct");
|
||||
// Unknown names fall back to Word's format first.
|
||||
assert_eq!(save_filters("no extension")[0].1, vec!["docx".to_string()]);
|
||||
}
|
||||
|
||||
/// #689: the Save dialog's default extension is the suggested name's own format, so a file
|
||||
/// name the user types without one is saved in the document's format instead of coming back
|
||||
/// bare and failing.
|
||||
#[test]
|
||||
fn save_dialog_defaults_to_the_suggested_format() {
|
||||
assert_eq!(save_exts("novel.docx")[0], "docx");
|
||||
assert_eq!(save_exts("report.odt")[0], "odt");
|
||||
assert_eq!(save_exts("annual report.pdf")[0], "pdf");
|
||||
assert_eq!(save_exts("notes.md")[0], "md");
|
||||
assert_eq!(save_exts("notes.markdown")[0], "md");
|
||||
// A suggested name always has an extension; anything unreadable falls back to Word's.
|
||||
assert_eq!(save_exts("no extension")[0], "docx");
|
||||
assert_eq!(save_exts("mystery.rtf2")[0], "docx");
|
||||
// Every savable format is still offered, once.
|
||||
let exts = save_exts("novel.docx");
|
||||
assert!(wordcraft_engine::io::SAVE_EXTS.iter().all(|e| exts.iter().any(|x| x == e)));
|
||||
assert_eq!(exts.len(), wordcraft_engine::io::SAVE_EXTS.len());
|
||||
}
|
||||
}
|
||||
@@ -1,330 +0,0 @@
|
||||
//! Graphics instance configuration applied before wgpu can initialize any driver: Windows
|
||||
//! backends and the DirectX 12 shader compiler, and the Intel Mac indirect-validation skip.
|
||||
// On macOS only the indirect-validation items are used outside tests. Elsewhere it is the other
|
||||
// way round, so those two carry their own `allow`.
|
||||
#![cfg_attr(target_os = "macos", allow(dead_code))]
|
||||
|
||||
use eframe::{
|
||||
NativeOptions,
|
||||
egui_wgpu::WgpuSetup,
|
||||
wgpu::{Backends, DeviceType, Dx12Compiler, InstanceFlags},
|
||||
};
|
||||
|
||||
/// wgpu compiles its indirect-call validation compute shaders inside `request_device`. On old
|
||||
/// Intel Macs (HD Graphics 5000 on Big Sur, #2652) Metal's Intel
|
||||
/// compiler aborts on them, the device is lost and eframe exits before the window opens. WordCraft
|
||||
/// issues no indirect draws or dispatches, so Intel Macs skip them; every other GPU keeps wgpu's
|
||||
/// default. Same fix as PhotoCraft's storytold/PhotoCraft#3171.
|
||||
///
|
||||
/// `x86_64` is the build's architecture. An x86_64 build also runs on Apple silicon under Rosetta
|
||||
/// (#5199), so it skips only when the machine itself isn't Apple silicon.
|
||||
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
|
||||
pub fn skips_indirect_validation(macos: bool, x86_64: bool) -> bool {
|
||||
// Short-circuits: only x86_64 macOS builds ask the system.
|
||||
macos && x86_64 && !runs_on_apple_silicon()
|
||||
}
|
||||
|
||||
/// Whether the machine is Apple silicon, also when this process is translated by Rosetta:
|
||||
/// `hw.optional.arm64` describes the hardware, not the process. Assumes not (an Intel Mac) when
|
||||
/// the system can't tell.
|
||||
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
|
||||
fn runs_on_apple_silicon() -> bool {
|
||||
cfg!(target_os = "macos")
|
||||
&& std::process::Command::new("/usr/sbin/sysctl")
|
||||
.args(["-n", "hw.optional.arm64"])
|
||||
.output()
|
||||
.is_ok_and(|out| out.status.success() && out.stdout.trim_ascii() == b"1")
|
||||
}
|
||||
|
||||
/// Leaves wgpu's indirect-call validation out of the instance eframe creates when `skip`.
|
||||
/// `WGPU_VALIDATION_INDIRECT_CALL=1` still turns it back on.
|
||||
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
|
||||
pub fn configure_indirect_validation(options: &mut NativeOptions, skip: bool) {
|
||||
if !skip {
|
||||
return;
|
||||
}
|
||||
if let WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup {
|
||||
create.instance_descriptor.flags = create.instance_descriptor.flags.difference(InstanceFlags::VALIDATION_INDIRECT_CALL).with_env();
|
||||
}
|
||||
}
|
||||
|
||||
/// What the start-up probe learned about one DirectX 12 adapter.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Dx12Adapter {
|
||||
/// `Cpu` is WARP (Microsoft's software rasteriser): it works, but every frame is drawn on the
|
||||
/// processor, which makes the app lag on older machines (#316).
|
||||
pub device_type: DeviceType,
|
||||
/// Whether the adapter offers the limits eframe will ask for when it creates the device.
|
||||
pub meets_limits: bool,
|
||||
}
|
||||
|
||||
/// The backends to initialize on Windows.
|
||||
///
|
||||
/// An explicit `backend_override` (normally `Backends::from_env()`, i.e. `WGPU_BACKEND`) always
|
||||
/// wins. Otherwise DirectX 12 only, as long as `dx12_graphics` is set and `dx12_adapters` (what a
|
||||
/// DirectX 12-only probe found) contains a usable hardware GPU. Without one, OpenGL is the way to
|
||||
/// the GPU: graphics chips whose driver has no DirectX 12 support (Intel 4th generation on Windows
|
||||
/// 11, #316) still have an OpenGL driver, and GL can't reach the AMD driver crash described in
|
||||
/// [`configure_backends`], because an AMD GPU with a driver shows up as a DirectX 12 adapter and
|
||||
/// keeps us on DirectX 12. When DirectX 12 offers only WARP, it stays enabled next to GL as a last
|
||||
/// resort for machines without an OpenGL driver either (virtual machines): wgpu prefers any GPU
|
||||
/// over a software adapter, so it's only picked when GL has nothing better.
|
||||
///
|
||||
/// `dx12_graphics` is false on 32-bit Windows. wgpu creates the graphics pipeline through
|
||||
/// `ID3D12Device2::CreatePipelineState`, and that stream is aligned to 8 bytes. The 32-bit runtime
|
||||
/// expects pointer alignment (4), so creation returns `E_INVALIDARG` ("The parameter is incorrect")
|
||||
/// and the process exits before the first frame. Compute pipelines use the older API and succeed,
|
||||
/// which is why startup gets as far as the egui pipeline and then quits. OpenGL does not use that
|
||||
/// stream.
|
||||
pub fn choose_backends(backend_override: Option<Backends>, dx12_adapters: &[Dx12Adapter], dx12_graphics: bool) -> Backends {
|
||||
if let Some(backends) = backend_override {
|
||||
return backends;
|
||||
}
|
||||
if !dx12_graphics {
|
||||
return Backends::GL;
|
||||
}
|
||||
let hardware = |a: &&Dx12Adapter| a.device_type != DeviceType::Cpu;
|
||||
if dx12_adapters.iter().filter(hardware).any(|a| a.meets_limits) {
|
||||
Backends::DX12
|
||||
} else if !dx12_adapters.is_empty() && !dx12_adapters.iter().any(|a| hardware(&a)) {
|
||||
Backends::DX12 | Backends::GL
|
||||
} else {
|
||||
// No DirectX 12 adapter at all, or only GPUs that can't run the app: GL alone, so a
|
||||
// DirectX 12 GPU that would fail device creation isn't picked over the OpenGL one.
|
||||
Backends::GL
|
||||
}
|
||||
}
|
||||
|
||||
/// Restricts the wgpu instance eframe creates to `backends`.
|
||||
pub fn configure_backends(options: &mut NativeOptions, backends: Backends) {
|
||||
if let WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup {
|
||||
// eframe's default includes GL. Creating that backend can crash inside AMD's
|
||||
// atio6axx.dll before adapter selection or any Rust error handling runs, so the
|
||||
// window never appears. Choosing an adapter afterwards is too late: only leaving GL
|
||||
// out of the instance avoids it. This matches the verified WGPU_BACKEND=dx12
|
||||
// workaround without mutating process environment variables.
|
||||
create.instance_descriptor.backends = backends;
|
||||
}
|
||||
}
|
||||
|
||||
/// The DirectX 12 shader compiler: FXC (`d3dcompiler_47.dll`, part of Windows) unless `env`
|
||||
/// (normally `WGPU_DX12_COMPILER`, wgpu's own variable: `fxc`, `dxc`, `auto`…) names another.
|
||||
///
|
||||
/// #603: wgpu's default (`Auto`) uses DXC, loading whichever `dxcompiler.dll` the DLL search path
|
||||
/// finds first. WordCraft ships none, so that copy belongs to another program. Without a matching
|
||||
/// `dxil.dll` beside it, DXC warns that the DXIL is unsigned; wgpu takes the warning for a compile
|
||||
/// error, its own indirect-validation pipeline fails, the device is lost and eframe exits before
|
||||
/// the first frame. FXC is always there and compiles everything egui's shaders need.
|
||||
pub fn dx12_compiler(env: Option<&str>) -> Dx12Compiler {
|
||||
let Some(value) = env else { return Dx12Compiler::Fxc };
|
||||
value.parse().unwrap_or_else(|e| {
|
||||
log::warn!("graphics: WGPU_DX12_COMPILER={value:?} ignored ({e}), using FXC");
|
||||
Dx12Compiler::Fxc
|
||||
})
|
||||
}
|
||||
|
||||
/// Makes the wgpu instance eframe creates compile DirectX 12 shaders with `compiler`.
|
||||
pub fn configure_dx12_compiler(options: &mut NativeOptions, compiler: Dx12Compiler) {
|
||||
if let WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup {
|
||||
create.instance_descriptor.backend_options.dx12.shader_compiler = compiler;
|
||||
}
|
||||
}
|
||||
|
||||
/// Chooses the backends ([`choose_backends`]) and applies them to `options`. Without a
|
||||
/// `backend_override` this first probes DirectX 12 with a short-lived instance of its own, which
|
||||
/// is dropped before eframe creates the real one.
|
||||
#[cfg(target_os = "windows")]
|
||||
pub fn configure(options: &mut NativeOptions, backend_override: Option<Backends>) {
|
||||
// First, so the probe's instance doesn't load a stray `dxcompiler.dll` either.
|
||||
let compiler = dx12_compiler(std::env::var("WGPU_DX12_COMPILER").ok().as_deref());
|
||||
log::info!("graphics: DirectX 12 shader compiler {compiler:?}");
|
||||
configure_dx12_compiler(options, compiler);
|
||||
let backends = match backend_override {
|
||||
Some(backends) => {
|
||||
log::info!("graphics: WGPU_BACKEND override, backends {backends:?}");
|
||||
backends
|
||||
}
|
||||
None => {
|
||||
// 32-bit: skip the DirectX 12 probe. A capable GPU would be selected, then
|
||||
// CreatePipelineState fails and the app exits with no window.
|
||||
let dx12_graphics = cfg!(not(target_arch = "x86"));
|
||||
let adapters = if dx12_graphics { probe_dx12(options) } else { Vec::new() };
|
||||
let backends = choose_backends(None, &adapters, dx12_graphics);
|
||||
if dx12_graphics {
|
||||
log::info!("graphics: {} DirectX 12 adapter(s) {adapters:?}, backends {backends:?}", adapters.len());
|
||||
} else {
|
||||
log::info!("graphics: 32-bit Windows uses OpenGL; DirectX 12 graphics pipeline creation fails");
|
||||
}
|
||||
backends
|
||||
}
|
||||
};
|
||||
configure_backends(options, backends);
|
||||
}
|
||||
|
||||
/// Lists the DirectX 12 adapters, checking each against the limits eframe's device descriptor
|
||||
/// will require. Empty when this build has no DirectX 12 backend.
|
||||
#[cfg(target_os = "windows")]
|
||||
fn probe_dx12(options: &NativeOptions) -> Vec<Dx12Adapter> {
|
||||
use eframe::wgpu::{Instance, InstanceDescriptor};
|
||||
// `Instance::new` panics when the build has no backend for the platform.
|
||||
if !Instance::enabled_backend_features().contains(Backends::DX12) {
|
||||
return Vec::new();
|
||||
}
|
||||
let WgpuSetup::CreateNew(create) = &options.wgpu_options.wgpu_setup else {
|
||||
return Vec::new();
|
||||
};
|
||||
let instance = Instance::new(InstanceDescriptor {
|
||||
backends: Backends::DX12,
|
||||
backend_options: create.instance_descriptor.backend_options.clone(),
|
||||
..InstanceDescriptor::new_without_display_handle()
|
||||
});
|
||||
pollster::block_on(instance.enumerate_adapters(Backends::DX12))
|
||||
.iter()
|
||||
.map(|adapter| {
|
||||
let info = adapter.get_info();
|
||||
let required = (create.device_descriptor)(adapter).required_limits;
|
||||
let meets_limits = required.check_limits(&adapter.limits());
|
||||
log::info!("graphics: DirectX 12 adapter {:?} ({:?}, driver {:?}), limits ok: {meets_limits}", info.name, info.device_type, info.driver);
|
||||
Dx12Adapter { device_type: info.device_type, meets_limits }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn intel_macs_skip_the_indirect_validation_shaders() {
|
||||
// #2652: Metal's Intel compiler aborted on them, losing the device before the window opened.
|
||||
// An x86_64 build on Apple silicon (Rosetta) isn't an Intel Mac (#5199).
|
||||
assert_eq!(skips_indirect_validation(true, true), !host_is_apple_silicon());
|
||||
// Apple silicon, Windows and Linux keep wgpu's validation.
|
||||
for (macos, intel) in [(true, false), (false, true), (false, false)] {
|
||||
assert!(!skips_indirect_validation(macos, intel), "macos={macos} intel={intel}");
|
||||
}
|
||||
let mut options = NativeOptions::default();
|
||||
let WgpuSetup::CreateNew(before) = &options.wgpu_options.wgpu_setup else {
|
||||
panic!("default native options must create a wgpu instance");
|
||||
};
|
||||
let before = before.instance_descriptor.flags;
|
||||
configure_indirect_validation(&mut options, false);
|
||||
let WgpuSetup::CreateNew(create) = &options.wgpu_options.wgpu_setup else {
|
||||
panic!("default native options must create a wgpu instance");
|
||||
};
|
||||
assert_eq!(create.instance_descriptor.flags, before, "flags untouched when not skipping");
|
||||
if std::env::var_os("WGPU_VALIDATION_INDIRECT_CALL").is_none() {
|
||||
configure_indirect_validation(&mut options, true);
|
||||
let WgpuSetup::CreateNew(create) = &options.wgpu_options.wgpu_setup else {
|
||||
panic!("default native options must create a wgpu instance");
|
||||
};
|
||||
assert!(!create.instance_descriptor.flags.contains(InstanceFlags::VALIDATION_INDIRECT_CALL));
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the machine running the tests is Apple silicon, whatever this build's architecture.
|
||||
fn host_is_apple_silicon() -> bool {
|
||||
cfg!(target_os = "macos")
|
||||
&& std::process::Command::new("/usr/sbin/sysctl")
|
||||
.args(["-n", "hw.optional.arm64"])
|
||||
.output()
|
||||
.is_ok_and(|out| out.status.success() && out.stdout.trim_ascii() == b"1")
|
||||
}
|
||||
|
||||
/// #5199: an x86_64 build running under Rosetta on Apple silicon isn't an Intel Mac and keeps
|
||||
/// wgpu's indirect-call validation.
|
||||
#[test]
|
||||
fn x86_64_builds_on_apple_silicon_keep_indirect_validation() {
|
||||
if !host_is_apple_silicon() {
|
||||
return;
|
||||
}
|
||||
// What main.rs passes from an x86_64 build.
|
||||
assert!(!skips_indirect_validation(true, true), "Rosetta build on Apple silicon must keep validation");
|
||||
let mut options = NativeOptions::default();
|
||||
let WgpuSetup::CreateNew(before) = &options.wgpu_options.wgpu_setup else {
|
||||
panic!("default native options must create a wgpu instance");
|
||||
};
|
||||
let before = before.instance_descriptor.flags;
|
||||
configure_indirect_validation(&mut options, skips_indirect_validation(true, true));
|
||||
let WgpuSetup::CreateNew(create) = &options.wgpu_options.wgpu_setup else {
|
||||
panic!("default native options must create a wgpu instance");
|
||||
};
|
||||
assert_eq!(create.instance_descriptor.flags, before, "indirect-call validation kept");
|
||||
}
|
||||
|
||||
fn configured_backends(backends: Backends) -> Backends {
|
||||
let mut options = NativeOptions::default();
|
||||
configure_backends(&mut options, backends);
|
||||
let WgpuSetup::CreateNew(create) = options.wgpu_options.wgpu_setup else {
|
||||
panic!("default native options must create a wgpu instance");
|
||||
};
|
||||
create.instance_descriptor.backends
|
||||
}
|
||||
|
||||
const fn adapter(device_type: DeviceType, meets_limits: bool) -> Dx12Adapter {
|
||||
Dx12Adapter { device_type, meets_limits }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_default_initializes_only_dx12() {
|
||||
// eframe's own default (PRIMARY | GL) would initialize OpenGL as well.
|
||||
let WgpuSetup::CreateNew(eframe_default) = NativeOptions::default().wgpu_options.wgpu_setup else {
|
||||
panic!("default native options must create a wgpu instance");
|
||||
};
|
||||
assert!(eframe_default.instance_descriptor.backends.contains(Backends::GL));
|
||||
let gpu = [adapter(DeviceType::IntegratedGpu, true)];
|
||||
assert_eq!(configured_backends(choose_backends(None, &gpu, true)), Backends::DX12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_backend_override_is_preserved() {
|
||||
let warp_only = [adapter(DeviceType::Cpu, true)];
|
||||
for backends in [Backends::VULKAN, Backends::GL, Backends::DX12, Backends::VULKAN | Backends::DX12, Backends::empty()] {
|
||||
// Whatever the probe would have found, the override wins (the probe doesn't run then).
|
||||
assert_eq!(choose_backends(Some(backends), &[], true), backends);
|
||||
assert_eq!(choose_backends(Some(backends), &warp_only, true), backends);
|
||||
assert_eq!(configured_backends(backends), backends);
|
||||
}
|
||||
}
|
||||
|
||||
/// #603: DirectX 12 shaders compile with FXC, never a `dxcompiler.dll` found on the search
|
||||
/// path, unless `WGPU_DX12_COMPILER` asks for it.
|
||||
#[test]
|
||||
fn dx12_compiles_with_fxc_unless_asked() {
|
||||
assert!(matches!(dx12_compiler(None), Dx12Compiler::Fxc));
|
||||
assert!(matches!(dx12_compiler(Some("bogus")), Dx12Compiler::Fxc));
|
||||
assert!(matches!(dx12_compiler(Some("FXC")), Dx12Compiler::Fxc));
|
||||
assert!(matches!(dx12_compiler(Some("dxc")), Dx12Compiler::DynamicDxc { .. }));
|
||||
assert!(matches!(dx12_compiler(Some("auto")), Dx12Compiler::Auto));
|
||||
let mut options = NativeOptions::default();
|
||||
configure_dx12_compiler(&mut options, dx12_compiler(None));
|
||||
let WgpuSetup::CreateNew(create) = options.wgpu_options.wgpu_setup else {
|
||||
panic!("default native options must create a wgpu instance");
|
||||
};
|
||||
assert!(matches!(create.instance_descriptor.backend_options.dx12.shader_compiler, Dx12Compiler::Fxc));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gl_when_dx12_has_no_usable_gpu() {
|
||||
// #316: no DirectX 12 driver, so DirectX 12 offers only WARP (or nothing) and lags.
|
||||
let warp_only = [adapter(DeviceType::Cpu, true)];
|
||||
assert_eq!(choose_backends(None, &warp_only, true), Backends::GL | Backends::DX12);
|
||||
assert_eq!(choose_backends(None, &[], true), Backends::GL);
|
||||
// A GPU that can't create eframe's device: GL alone, so it isn't picked over the GL one.
|
||||
let weak_gpu = [adapter(DeviceType::IntegratedGpu, false), adapter(DeviceType::Cpu, true)];
|
||||
assert_eq!(choose_backends(None, &weak_gpu, true), Backends::GL);
|
||||
// Any usable GPU keeps DirectX 12 only, next to WARP or a weaker GPU.
|
||||
let mixed = [adapter(DeviceType::Cpu, true), adapter(DeviceType::IntegratedGpu, false), adapter(DeviceType::DiscreteGpu, true)];
|
||||
assert_eq!(choose_backends(None, &mixed, true), Backends::DX12);
|
||||
}
|
||||
|
||||
/// 32-bit Windows: a usable DirectX 12 GPU still starts on OpenGL. `WGPU_BACKEND` still wins.
|
||||
#[test]
|
||||
fn x86_uses_opengl_even_with_a_usable_gpu() {
|
||||
let gpu = [adapter(DeviceType::IntegratedGpu, true)];
|
||||
assert_eq!(choose_backends(None, &gpu, false), Backends::GL);
|
||||
assert_eq!(choose_backends(Some(Backends::DX12), &gpu, false), Backends::DX12);
|
||||
assert_eq!(choose_backends(Some(Backends::VULKAN), &[], false), Backends::VULKAN);
|
||||
assert_eq!(configured_backends(choose_backends(None, &gpu, false)), Backends::GL);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
//! 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());
|
||||
}
|
||||
}
|
||||
@@ -1,298 +0,0 @@
|
||||
//! Linux: draw on the GPU that drives the screen.
|
||||
//!
|
||||
//! egui-wgpu picks the discrete GPU by default (`PowerPreference::HighPerformance`). On a laptop
|
||||
//! whose integrated GPU drives the panel, every frame drawn on the discrete one is copied across
|
||||
//! to it, and the discrete GPU leaves its idle state whenever the window redraws: on an Intel HD
|
||||
//! 530 + NVIDIA Quadro M4000M laptop, from 7 W at P8 to over 20 W at P0/P1. Forcing the integrated
|
||||
//! GPU instead breaks desktops whose screen is on the discrete card (storytold/pdfcraft#96), and a
|
||||
//! desktop with a monitor on each card needs the discrete one (storytold/pdfcraft#445). So the
|
||||
//! choice follows the connected displays, as in craft-anything (storytold/craft-anything#571):
|
||||
//!
|
||||
//! 1. `WGPU_ADAPTER_NAME` (part of the adapter's name) or `WGPU_POWER_PREF` (`high`, `low`,
|
||||
//! `none`), when set, decide;
|
||||
//! 2. a connected built-in panel: the GPU behind it;
|
||||
//! 3. displays on only one GPU: that GPU;
|
||||
//! 4. otherwise (displays on several GPUs, or nothing readable): the discrete GPU, as before.
|
||||
|
||||
mod drm;
|
||||
|
||||
use drm::DisplayCard;
|
||||
use eframe::wgpu::{DeviceType, PowerPreference};
|
||||
|
||||
/// What we know of one adapter wgpu offers.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) struct Candidate {
|
||||
pub name: String,
|
||||
pub vendor: u32,
|
||||
pub device: u32,
|
||||
/// `0000:05:00.0`, lowercase; empty when the driver doesn't say (always, under GL).
|
||||
pub pci_slot: String,
|
||||
pub device_type: DeviceType,
|
||||
pub gl: bool,
|
||||
}
|
||||
|
||||
/// What the person asked for through wgpu's environment variables.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub(crate) struct Asked {
|
||||
pub adapter_name: Option<String>,
|
||||
pub power: Option<PowerPreference>,
|
||||
}
|
||||
|
||||
/// Why an adapter was chosen, for the log.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum Why {
|
||||
AskedByName,
|
||||
AskedPower,
|
||||
BuiltInPanel,
|
||||
OnlyGpuWithDisplays,
|
||||
Fallback,
|
||||
}
|
||||
|
||||
/// The index of the adapter to draw with, and why; `None` when there is none.
|
||||
pub(crate) fn choose(candidates: &[Candidate], cards: &[DisplayCard], asked: &Asked) -> Option<(usize, Why)> {
|
||||
if let Some(want) = asked.adapter_name.as_deref().map(str::to_lowercase).filter(|w| !w.is_empty()) {
|
||||
// As wgpu's own `WGPU_ADAPTER_NAME`: part of the name, any case. No match: the usual choice.
|
||||
if let Some(i) = candidates.iter().position(|c| c.name.to_lowercase().contains(&want)) {
|
||||
return Some((i, Why::AskedByName));
|
||||
}
|
||||
log::warn!("WGPU_ADAPTER_NAME={want}: no graphics adapter has that in its name");
|
||||
}
|
||||
if let Some(power) = asked.power {
|
||||
return by_kind(candidates, power).map(|i| (i, Why::AskedPower));
|
||||
}
|
||||
let panels: Vec<&DisplayCard> = cards.iter().filter(|c| c.built_in_panel).collect();
|
||||
let with_displays: Vec<&DisplayCard> = cards.iter().filter(|c| c.displays > 0).collect();
|
||||
let target = if !panels.is_empty() {
|
||||
Some((panels, Why::BuiltInPanel))
|
||||
} else if with_displays.len() == 1 {
|
||||
Some((with_displays, Why::OnlyGpuWithDisplays))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some((wanted, why)) = target {
|
||||
// Vulkan before GL for the same card; otherwise wgpu's order.
|
||||
let found = candidates.iter().enumerate().filter(|(_, c)| wanted.iter().any(|card| drives(card, c, cards))).min_by_key(|(_, c)| c.gl);
|
||||
if let Some((i, _)) = found {
|
||||
return Some((i, why));
|
||||
}
|
||||
}
|
||||
by_kind(candidates, PowerPreference::HighPerformance).map(|i| (i, Why::Fallback))
|
||||
}
|
||||
|
||||
/// Whether `card` is the GPU behind `adapter`: by PCI address when the driver gives one, else by
|
||||
/// PCI ids, which count only when no other card has the same ids (two cards of one model); GL
|
||||
/// gives only a vendor, which counts only when no other card has that vendor.
|
||||
fn drives(card: &DisplayCard, adapter: &Candidate, all: &[DisplayCard]) -> bool {
|
||||
if !adapter.pci_slot.is_empty() && !card.pci_slot.is_empty() {
|
||||
return adapter.pci_slot == card.pci_slot;
|
||||
}
|
||||
if adapter.device != 0 {
|
||||
return adapter.vendor == card.vendor
|
||||
&& adapter.device == card.device
|
||||
&& all.iter().filter(|c| c.vendor == card.vendor && c.device == card.device).count() == 1;
|
||||
}
|
||||
adapter.vendor != 0 && adapter.vendor == card.vendor && all.iter().filter(|c| c.vendor == card.vendor).count() == 1
|
||||
}
|
||||
|
||||
/// The first adapter in wgpu's own order for that power preference.
|
||||
fn by_kind(candidates: &[Candidate], power: PowerPreference) -> Option<usize> {
|
||||
let rank = |t: DeviceType| match (power, t) {
|
||||
(PowerPreference::None, _) => 0,
|
||||
(PowerPreference::LowPower, DeviceType::IntegratedGpu) | (PowerPreference::HighPerformance, DeviceType::DiscreteGpu) => 1,
|
||||
(_, DeviceType::IntegratedGpu | DeviceType::DiscreteGpu) => 2,
|
||||
(_, DeviceType::Other) => 3,
|
||||
(_, DeviceType::VirtualGpu) => 4,
|
||||
(_, DeviceType::Cpu) => 5,
|
||||
};
|
||||
candidates.iter().enumerate().min_by_key(|(_, c)| rank(c.device_type)).map(|(i, _)| i)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
impl Candidate {
|
||||
fn of(info: &eframe::wgpu::AdapterInfo) -> Self {
|
||||
Candidate {
|
||||
name: info.name.clone(),
|
||||
vendor: info.vendor,
|
||||
device: info.device,
|
||||
pci_slot: info.device_pci_bus_id.to_ascii_lowercase(),
|
||||
device_type: info.device_type,
|
||||
gl: info.backend == eframe::wgpu::Backend::Gl,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
impl Asked {
|
||||
fn from_env() -> Self {
|
||||
Asked { adapter_name: std::env::var("WGPU_ADAPTER_NAME").ok(), power: PowerPreference::from_env() }
|
||||
}
|
||||
}
|
||||
|
||||
/// The adapter that draws the window, among those that can draw to it.
|
||||
#[cfg(target_os = "linux")]
|
||||
pub(crate) fn pick_adapter(adapters: &[eframe::wgpu::Adapter], surface: Option<&eframe::wgpu::Surface<'_>>) -> Result<eframe::wgpu::Adapter, String> {
|
||||
let usable: Vec<&eframe::wgpu::Adapter> = adapters.iter().filter(|a| surface.is_none_or(|s| a.is_surface_supported(s))).collect();
|
||||
let candidates: Vec<Candidate> = usable.iter().map(|a| Candidate::of(&a.get_info())).collect();
|
||||
let cards = drm::display_cards();
|
||||
let picked = choose(&candidates, &cards, &Asked::from_env()).and_then(|(i, why)| Some((*usable.get(i)?, why)));
|
||||
match picked {
|
||||
Some((a, why)) => {
|
||||
log::info!("drawing with {:?} ({why:?}); displays: {cards:?}", a.get_info());
|
||||
Ok(a.clone())
|
||||
}
|
||||
None => Err(format!("None of the {} graphics adapters found can draw this window.", adapters.len())),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const AMD: (u32, u32, &str) = (0x1002, 0x1638, "0000:05:00.0");
|
||||
const NVIDIA: (u32, u32, &str) = (0x10de, 0x25a2, "0000:01:00.0");
|
||||
const INTEL: (u32, u32, &str) = (0x8086, 0xa780, "0000:00:02.0");
|
||||
|
||||
fn vulkan(name: &str, (vendor, device, slot): (u32, u32, &str), device_type: DeviceType) -> Candidate {
|
||||
Candidate { name: name.into(), vendor, device, pci_slot: slot.into(), device_type, gl: false }
|
||||
}
|
||||
|
||||
fn gl(name: &str, vendor: u32, device_type: DeviceType) -> Candidate {
|
||||
Candidate { name: name.into(), vendor, device: 0, pci_slot: String::new(), device_type, gl: true }
|
||||
}
|
||||
|
||||
fn card((vendor, device, slot): (u32, u32, &str), displays: u32, built_in_panel: bool) -> DisplayCard {
|
||||
DisplayCard { vendor, device, pci_slot: slot.into(), displays, built_in_panel }
|
||||
}
|
||||
|
||||
/// What wgpu offers on a laptop whose AMD iGPU drives the panel, in its order (Vulkan, then GL).
|
||||
fn laptop_adapters() -> Vec<Candidate> {
|
||||
vec![
|
||||
vulkan("AMD Radeon Graphics (RADV RENOIR)", AMD, DeviceType::IntegratedGpu),
|
||||
vulkan("NVIDIA GeForce RTX 3050 Laptop GPU", NVIDIA, DeviceType::DiscreteGpu),
|
||||
gl("AMD Radeon Graphics (radeonsi, renoir)", 0x1002, DeviceType::IntegratedGpu),
|
||||
]
|
||||
}
|
||||
|
||||
/// The iGPU drives the panel; egui-wgpu's default drew on the discrete GPU.
|
||||
#[test]
|
||||
fn a_laptop_draws_on_the_gpu_behind_its_panel() {
|
||||
let cards = [card(NVIDIA, 0, false), card(AMD, 1, true)];
|
||||
assert_eq!(choose(&laptop_adapters(), &cards, &Asked::default()), Some((0, Why::BuiltInPanel)));
|
||||
// The same with the discrete GPU listed first.
|
||||
let mut swapped = laptop_adapters();
|
||||
swapped.swap(0, 1);
|
||||
assert_eq!(choose(&swapped, &cards, &Asked::default()), Some((1, Why::BuiltInPanel)));
|
||||
}
|
||||
|
||||
/// The panel's GPU stays the choice with an external monitor on the discrete card as well.
|
||||
#[test]
|
||||
fn the_panel_wins_over_a_monitor_on_the_other_card() {
|
||||
let cards = [card(NVIDIA, 1, false), card(AMD, 1, true)];
|
||||
assert_eq!(choose(&laptop_adapters(), &cards, &Asked::default()), Some((0, Why::BuiltInPanel)));
|
||||
}
|
||||
|
||||
/// A desktop with its monitor on the discrete card and the iGPU left on (a low-power default
|
||||
/// draws on the iGPU there, and the window can't start: the case the panel rule must not break).
|
||||
#[test]
|
||||
fn a_desktop_draws_on_the_only_card_with_a_monitor() {
|
||||
let adapters =
|
||||
[vulkan("Intel(R) Graphics (RPL-S)", INTEL, DeviceType::IntegratedGpu), vulkan("NVIDIA GeForce RTX", NVIDIA, DeviceType::DiscreteGpu)];
|
||||
let cards = [card(INTEL, 0, false), card(NVIDIA, 1, false)];
|
||||
assert_eq!(choose(&adapters, &cards, &Asked::default()), Some((1, Why::OnlyGpuWithDisplays)));
|
||||
// And on the iGPU when that's where the only monitor is.
|
||||
let cards = [card(INTEL, 2, false), card(NVIDIA, 0, false)];
|
||||
assert_eq!(choose(&adapters, &cards, &Asked::default()), Some((0, Why::OnlyGpuWithDisplays)));
|
||||
}
|
||||
|
||||
/// A desktop with a monitor on each card: the discrete GPU, as before (an iGPU choice there
|
||||
/// lost its surface as soon as it was set up).
|
||||
#[test]
|
||||
fn monitors_on_two_cards_keep_the_discrete_gpu() {
|
||||
let adapters =
|
||||
[vulkan("Intel(R) Graphics (RPL-S)", INTEL, DeviceType::IntegratedGpu), vulkan("NVIDIA GeForce RTX", NVIDIA, DeviceType::DiscreteGpu)];
|
||||
let cards = [card(INTEL, 1, false), card(NVIDIA, 1, false)];
|
||||
assert_eq!(choose(&adapters, &cards, &Asked::default()), Some((1, Why::Fallback)));
|
||||
}
|
||||
|
||||
/// Nothing readable (no `/sys`, or a card the drivers don't name): the discrete GPU, as before.
|
||||
#[test]
|
||||
fn without_display_facts_the_old_choice_stands() {
|
||||
assert_eq!(choose(&laptop_adapters(), &[], &Asked::default()), Some((1, Why::Fallback)));
|
||||
let unknown = [card((0x1234, 0x1, "0000:09:00.0"), 1, true)];
|
||||
assert_eq!(choose(&laptop_adapters(), &unknown, &Asked::default()), Some((1, Why::Fallback)));
|
||||
assert_eq!(choose(&[], &[card(AMD, 1, true)], &Asked::default()), None);
|
||||
}
|
||||
|
||||
/// The environment variables still decide: prime-run style requests reach the NVIDIA card.
|
||||
#[test]
|
||||
fn wgpu_environment_variables_decide_when_set() {
|
||||
let cards = [card(NVIDIA, 0, false), card(AMD, 1, true)];
|
||||
let asked = |name: Option<&str>, power: Option<PowerPreference>| Asked { adapter_name: name.map(Into::into), power };
|
||||
assert_eq!(choose(&laptop_adapters(), &cards, &asked(None, Some(PowerPreference::HighPerformance))), Some((1, Why::AskedPower)));
|
||||
assert_eq!(choose(&laptop_adapters(), &cards, &asked(None, Some(PowerPreference::LowPower))), Some((0, Why::AskedPower)));
|
||||
assert_eq!(choose(&laptop_adapters(), &cards, &asked(None, Some(PowerPreference::None))), Some((0, Why::AskedPower)));
|
||||
assert_eq!(choose(&laptop_adapters(), &cards, &asked(Some("nvidia"), None)), Some((1, Why::AskedByName)));
|
||||
assert_eq!(choose(&laptop_adapters(), &cards, &asked(Some("RadeonSI"), Some(PowerPreference::HighPerformance))), Some((2, Why::AskedByName)));
|
||||
// A name nothing has: the usual choice, not a failure.
|
||||
assert_eq!(choose(&laptop_adapters(), &cards, &asked(Some("matrox"), None)), Some((0, Why::BuiltInPanel)));
|
||||
assert_eq!(choose(&laptop_adapters(), &cards, &asked(Some(""), None)), Some((0, Why::BuiltInPanel)));
|
||||
}
|
||||
|
||||
/// Under `WGPU_BACKEND=gl` there's no PCI address or device id: the vendor alone finds the
|
||||
/// card, but only when no other card shares it.
|
||||
#[test]
|
||||
fn gl_adapters_are_matched_by_vendor_only_when_unambiguous() {
|
||||
let adapters =
|
||||
[gl("NVIDIA GeForce RTX 3050", 0x10de, DeviceType::Other), gl("AMD Radeon Graphics (radeonsi)", 0x1002, DeviceType::IntegratedGpu)];
|
||||
let cards = [card(NVIDIA, 0, false), card(AMD, 1, true)];
|
||||
assert_eq!(choose(&adapters, &cards, &Asked::default()), Some((1, Why::BuiltInPanel)));
|
||||
// Two AMD cards: the vendor can't tell them apart, so the old choice stands.
|
||||
let two_amd = [card((0x1002, 0x73df, "0000:03:00.0"), 0, false), card(AMD, 1, true)];
|
||||
let adapters = [gl("AMD Radeon RX 6700", 0x1002, DeviceType::Other), gl("AMD Radeon Graphics", 0x1002, DeviceType::IntegratedGpu)];
|
||||
assert_eq!(choose(&adapters, &two_amd, &Asked::default()), Some((1, Why::Fallback)));
|
||||
}
|
||||
|
||||
/// Two adapters for the panel's card (Vulkan and GL): Vulkan, whatever the order.
|
||||
#[test]
|
||||
fn vulkan_comes_before_gl_for_the_same_card() {
|
||||
let adapters = [
|
||||
gl("AMD Radeon Graphics (radeonsi)", 0x1002, DeviceType::IntegratedGpu),
|
||||
vulkan("AMD Radeon Graphics (RADV RENOIR)", AMD, DeviceType::IntegratedGpu),
|
||||
];
|
||||
assert_eq!(choose(&adapters, &[card(AMD, 1, true)], &Asked::default()), Some((1, Why::BuiltInPanel)));
|
||||
}
|
||||
|
||||
/// A laptop with the lid closed and a monitor on the NVIDIA card: the switched-off panel isn't
|
||||
/// read as one (`drm` skips it), so the card with the monitor draws.
|
||||
#[test]
|
||||
fn a_closed_laptop_draws_on_the_card_with_the_monitor() {
|
||||
let cards = [card(NVIDIA, 1, false), card(AMD, 0, false)];
|
||||
assert_eq!(choose(&laptop_adapters(), &cards, &Asked::default()), Some((1, Why::OnlyGpuWithDisplays)));
|
||||
}
|
||||
|
||||
/// Two cards of one model have the same PCI ids: only the PCI address tells them apart. Without
|
||||
/// one from the driver the display rule gives way to the old choice instead of guessing.
|
||||
#[test]
|
||||
fn identical_cards_are_told_apart_only_by_pci_address() {
|
||||
const SECOND: (u32, u32, &str) = (0x10de, 0x25a2, "0000:02:00.0");
|
||||
let cards = [card(NVIDIA, 0, false), card(SECOND, 1, false)];
|
||||
let with_slots = [vulkan("NVIDIA A", NVIDIA, DeviceType::DiscreteGpu), vulkan("NVIDIA B", SECOND, DeviceType::DiscreteGpu)];
|
||||
assert_eq!(choose(&with_slots, &cards, &Asked::default()), Some((1, Why::OnlyGpuWithDisplays)));
|
||||
let without: Vec<Candidate> = with_slots.iter().cloned().map(|c| Candidate { pci_slot: String::new(), ..c }).collect();
|
||||
assert_eq!(choose(&without, &cards, &Asked::default()), Some((0, Why::Fallback)));
|
||||
}
|
||||
|
||||
/// The laptop this was measured on: Intel HD 530 behind the panel (`card2-eDP-1`), a Quadro
|
||||
/// M4000M with nothing connected, and the Quadro offered first by wgpu.
|
||||
#[test]
|
||||
fn an_intel_and_nvidia_laptop_draws_on_intel() {
|
||||
const HD530: (u32, u32, &str) = (0x8086, 0x191b, "0000:00:02.0");
|
||||
const M4000M: (u32, u32, &str) = (0x10de, 0x13f9, "0000:01:00.0");
|
||||
let adapters = [
|
||||
vulkan("Quadro M4000M", M4000M, DeviceType::DiscreteGpu),
|
||||
vulkan("Intel(R) HD Graphics 530 (SKL GT2)", HD530, DeviceType::IntegratedGpu),
|
||||
];
|
||||
let cards = [card(M4000M, 0, false), card(HD530, 1, true)];
|
||||
assert_eq!(choose(&adapters, &cards, &Asked::default()), Some((1, Why::BuiltInPanel)));
|
||||
}
|
||||
}
|
||||
@@ -1,237 +0,0 @@
|
||||
//! Which graphics cards drive displays, as the system reports them (Linux: `/sys/class/drm`).
|
||||
//!
|
||||
//! A window drawn on one card and shown on a screen attached to another is copied across on every
|
||||
//! frame, so the app draws on the card that drives the screen (see the parent module).
|
||||
|
||||
use std::io::Read as _;
|
||||
use std::path::Path;
|
||||
|
||||
/// A graphics card and the displays connected to it.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) struct DisplayCard {
|
||||
/// PCI vendor id: 0x1002 AMD, 0x10de NVIDIA, 0x8086 Intel.
|
||||
pub vendor: u32,
|
||||
/// PCI device id.
|
||||
pub device: u32,
|
||||
/// PCI address in the form `0000:05:00.0`, lowercase; empty when the system doesn't give one.
|
||||
pub pci_slot: String,
|
||||
/// Connected displays that are switched on, of any kind, built-in panel included.
|
||||
pub displays: u32,
|
||||
/// A connected, switched-on built-in panel (eDP, LVDS or DSI): this card drives a laptop's
|
||||
/// own screen.
|
||||
pub built_in_panel: bool,
|
||||
}
|
||||
|
||||
/// Connector kinds that are a computer's own screen rather than a monitor plugged into it.
|
||||
const BUILT_IN_PANELS: &[&str] = &["eDP", "LVDS", "DSI"];
|
||||
|
||||
/// At most this many entries are read from the DRM folder.
|
||||
const MAX_ENTRIES: usize = 512;
|
||||
|
||||
/// At most this many bytes are read from one sysfs file.
|
||||
const MAX_FILE: u64 = 4096;
|
||||
|
||||
/// The graphics cards on this computer and what's connected to them. Empty where the system
|
||||
/// doesn't say (a sandbox without `/sys`).
|
||||
#[cfg(target_os = "linux")]
|
||||
pub(crate) fn display_cards() -> Vec<DisplayCard> {
|
||||
display_cards_in(Path::new("/sys/class/drm"))
|
||||
}
|
||||
|
||||
/// [`display_cards`] read from a DRM folder laid out like `/sys/class/drm`: a `cardN` entry per
|
||||
/// card, with the card's PCI ids in `cardN/device/uevent`, and a `cardN-<kind>-<n>` entry per
|
||||
/// connector, with `connected` or `disconnected` in its `status` and, where the kernel gives it,
|
||||
/// `enabled` or `disabled` in its `enabled`. Cards without PCI ids (a firmware framebuffer) are
|
||||
/// left out.
|
||||
pub(crate) fn display_cards_in(drm: &Path) -> Vec<DisplayCard> {
|
||||
let Ok(entries) = std::fs::read_dir(drm) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut names: Vec<String> = entries.take(MAX_ENTRIES).filter_map(|e| e.ok()?.file_name().into_string().ok()).collect();
|
||||
names.sort();
|
||||
let cards = names.iter().filter(|n| is_card(n));
|
||||
cards
|
||||
.filter_map(|card| {
|
||||
let uevent = read_small(&drm.join(card).join("device").join("uevent"))?;
|
||||
let (vendor, device) = pci_ids(&uevent)?;
|
||||
let pci_slot = uevent_value(&uevent, "PCI_SLOT_NAME").unwrap_or_default().to_ascii_lowercase();
|
||||
let prefix = format!("{card}-");
|
||||
let mut out = DisplayCard { vendor, device, pci_slot, displays: 0, built_in_panel: false };
|
||||
for connector in names.iter().filter_map(|n| n.strip_prefix(&prefix)) {
|
||||
let dir = drm.join(format!("{prefix}{connector}"));
|
||||
let status = read_small(&dir.join("status")).unwrap_or_default();
|
||||
// A panel can be connected but switched off (a closed lid with a monitor in use):
|
||||
// `enabled` then reads `disabled`, and it drives nothing. No `enabled`: as before.
|
||||
let enabled = read_small(&dir.join("enabled")).unwrap_or_default();
|
||||
if status.trim() != "connected" || enabled.trim() == "disabled" {
|
||||
continue;
|
||||
}
|
||||
out.displays = out.displays.saturating_add(1);
|
||||
if BUILT_IN_PANELS.contains(&connector_kind(connector)) {
|
||||
out.built_in_panel = true;
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `card0`, `card12`: a card, not a connector (`card0-eDP-1`) or a render node.
|
||||
fn is_card(name: &str) -> bool {
|
||||
name.strip_prefix("card").is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))
|
||||
}
|
||||
|
||||
/// `eDP-1` → `eDP`, `HDMI-A-1` → `HDMI-A`: the connector's name without its number.
|
||||
fn connector_kind(connector: &str) -> &str {
|
||||
match connector.rsplit_once('-') {
|
||||
Some((kind, n)) if !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()) => kind,
|
||||
_ => connector,
|
||||
}
|
||||
}
|
||||
|
||||
/// `PCI_ID=1002:1638` → (0x1002, 0x1638).
|
||||
fn pci_ids(uevent: &str) -> Option<(u32, u32)> {
|
||||
let (vendor, device) = uevent_value(uevent, "PCI_ID")?.split_once(':')?;
|
||||
Some((u32::from_str_radix(vendor.trim(), 16).ok()?, u32::from_str_radix(device.trim(), 16).ok()?))
|
||||
}
|
||||
|
||||
fn uevent_value<'a>(uevent: &'a str, key: &str) -> Option<&'a str> {
|
||||
uevent.lines().find_map(|l| l.strip_prefix(key)?.strip_prefix('=')).map(str::trim)
|
||||
}
|
||||
|
||||
fn read_small(path: &Path) -> Option<String> {
|
||||
let mut text = String::new();
|
||||
std::fs::File::open(path).ok()?.take(MAX_FILE).read_to_string(&mut text).ok()?;
|
||||
Some(text)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
/// A folder of its own under the system's temporary folder, removed when dropped.
|
||||
struct TempDir(PathBuf);
|
||||
|
||||
impl TempDir {
|
||||
fn new() -> Self {
|
||||
static NEXT: AtomicUsize = AtomicUsize::new(0);
|
||||
let n = NEXT.fetch_add(1, Ordering::Relaxed);
|
||||
let dir = std::env::temp_dir().join(format!("wordcraft-drm-test-{}-{n}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(&dir).expect("temp dir");
|
||||
TempDir(dir)
|
||||
}
|
||||
|
||||
fn path(&self) -> &Path {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// A fake `/sys/class/drm`: cards as (name, PCI_ID, PCI_SLOT_NAME), connectors as
|
||||
/// (name, status).
|
||||
fn drm(cards: &[(&str, &str, &str)], connectors: &[(&str, &str)]) -> TempDir {
|
||||
let dir = TempDir::new();
|
||||
for (card, id, slot) in cards {
|
||||
let device = dir.path().join(card).join("device");
|
||||
fs::create_dir_all(&device).expect("card folder");
|
||||
fs::write(device.join("uevent"), format!("DRIVER=x\nPCI_CLASS=30000\nPCI_ID={id}\nPCI_SLOT_NAME={slot}\n")).expect("uevent");
|
||||
}
|
||||
for (connector, status) in connectors {
|
||||
let c = dir.path().join(connector);
|
||||
fs::create_dir_all(&c).expect("connector folder");
|
||||
fs::write(c.join("status"), format!("{status}\n")).expect("status");
|
||||
}
|
||||
fs::create_dir_all(dir.path().join("renderD128")).expect("render node");
|
||||
fs::write(dir.path().join("version"), "drm 1.1.0\n").expect("version");
|
||||
dir
|
||||
}
|
||||
|
||||
/// A laptop whose AMD iGPU drives the panel, with an NVIDIA card that has no outputs.
|
||||
#[test]
|
||||
fn a_laptop_panel_is_found_on_the_integrated_gpu() {
|
||||
let d = drm(
|
||||
&[("card0", "10DE:25A2", "0000:01:00.0"), ("card1", "1002:1638", "0000:05:00.0")],
|
||||
&[("card1-DP-1", "disconnected"), ("card1-eDP-1", "connected"), ("card1-HDMI-A-1", "disconnected")],
|
||||
);
|
||||
let cards = display_cards_in(d.path());
|
||||
assert_eq!(
|
||||
cards,
|
||||
vec![
|
||||
DisplayCard { vendor: 0x10de, device: 0x25a2, pci_slot: "0000:01:00.0".into(), displays: 0, built_in_panel: false },
|
||||
DisplayCard { vendor: 0x1002, device: 0x1638, pci_slot: "0000:05:00.0".into(), displays: 1, built_in_panel: true },
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/// A desktop with a monitor on each card: displays on both, no built-in panel.
|
||||
#[test]
|
||||
fn monitors_on_two_cards_are_counted_on_each() {
|
||||
let d = drm(
|
||||
&[("card0", "8086:A780", "0000:00:02.0"), ("card1", "10de:2206", "0000:01:00.0")],
|
||||
&[("card0-HDMI-A-1", "connected"), ("card1-DP-1", "connected"), ("card1-DP-2", "connected"), ("card1-DP-3", "disconnected")],
|
||||
);
|
||||
let cards = display_cards_in(d.path());
|
||||
assert_eq!(cards.iter().map(|c| (c.displays, c.built_in_panel)).collect::<Vec<_>>(), vec![(1, false), (2, false)]);
|
||||
}
|
||||
|
||||
/// `card10` is a different card from `card1`, and its connectors aren't `card1`'s.
|
||||
#[test]
|
||||
fn card_numbers_are_not_prefixes_of_each_other() {
|
||||
let d = drm(&[("card1", "1002:1638", "0000:05:00.0"), ("card10", "10de:25a2", "0000:01:00.0")], &[("card10-DP-1", "connected")]);
|
||||
let cards = display_cards_in(d.path());
|
||||
assert_eq!(cards.iter().map(|c| (c.vendor, c.displays)).collect::<Vec<_>>(), vec![(0x1002, 0), (0x10de, 1)]);
|
||||
}
|
||||
|
||||
/// LVDS and DSI panels are built in too; HDMI-A is a monitor, whatever its number.
|
||||
#[test]
|
||||
fn built_in_panels_are_told_from_monitors_by_connector_kind() {
|
||||
assert_eq!(connector_kind("eDP-1"), "eDP");
|
||||
assert_eq!(connector_kind("HDMI-A-1"), "HDMI-A");
|
||||
assert_eq!(connector_kind("DSI-12"), "DSI");
|
||||
assert_eq!(connector_kind("Virtual"), "Virtual");
|
||||
let d = drm(&[("card0", "8086:9a49", "0000:00:02.0")], &[("card0-LVDS-1", "connected")]);
|
||||
assert!(display_cards_in(d.path()).iter().all(|c| c.built_in_panel));
|
||||
}
|
||||
|
||||
/// A firmware framebuffer has no PCI ids; unreadable or odd entries are skipped, never a panic.
|
||||
#[test]
|
||||
fn what_cant_be_read_is_left_out() {
|
||||
let d = drm(&[("card0", "nonsense", ""), ("card1", "1002:", "")], &[("card0-Virtual-1", "connected")]);
|
||||
fs::create_dir_all(d.path().join("card2")).expect("card without device");
|
||||
fs::create_dir_all(d.path().join("card")).expect("bare name");
|
||||
assert!(display_cards_in(d.path()).is_empty());
|
||||
assert!(display_cards_in(&d.path().join("missing")).is_empty());
|
||||
assert_eq!(pci_ids("PCI_ID=10de:25a2"), Some((0x10de, 0x25a2)));
|
||||
assert_eq!(pci_ids("PCI_IDX=10de:25a2"), None);
|
||||
}
|
||||
|
||||
/// A status of `unknown` (some virtual outputs) isn't a connected display.
|
||||
#[test]
|
||||
fn only_connected_counts() {
|
||||
let d = drm(&[("card0", "1af4:1050", "0000:00:01.0")], &[("card0-Virtual-1", "unknown")]);
|
||||
assert_eq!(display_cards_in(d.path()).first().map(|c| c.displays), Some(0));
|
||||
}
|
||||
|
||||
/// A laptop with its lid closed and a monitor on the discrete card: the panel still reads
|
||||
/// `connected` but is switched off, so it neither counts nor marks its card as the panel's.
|
||||
#[test]
|
||||
fn a_switched_off_panel_does_not_count() {
|
||||
let d = drm(
|
||||
&[("card0", "10de:25a2", "0000:01:00.0"), ("card1", "1002:1638", "0000:05:00.0")],
|
||||
&[("card0-HDMI-A-1", "connected"), ("card1-eDP-1", "connected")],
|
||||
);
|
||||
fs::write(d.path().join("card0-HDMI-A-1").join("enabled"), "enabled\n").expect("enabled");
|
||||
fs::write(d.path().join("card1-eDP-1").join("enabled"), "disabled\n").expect("enabled");
|
||||
let cards = display_cards_in(d.path());
|
||||
assert_eq!(cards.iter().map(|c| (c.vendor, c.displays, c.built_in_panel)).collect::<Vec<_>>(), vec![(0x10de, 1, false), (0x1002, 0, false)]);
|
||||
}
|
||||
}
|
||||
@@ -1,349 +0,0 @@
|
||||
//! The desktop app's logger: `log::` records go to standard error and to a log file.
|
||||
//!
|
||||
//! Without a logger every `log::warn!`/`log::error!` in the workspace (an unreadable part of a
|
||||
//! .docx, a picture or font a PDF export had to leave out, a PNG that would not encode) vanished. A
|
||||
//! launch from a desktop menu has no terminal, so the file is what a bug report can attach:
|
||||
//! `<settings dir>/logs/wordcraft.log`, next to the preferences (`prefs_path` in `main.rs`). Each
|
||||
//! start moves the previous log to `wordcraft.1.log` (and that one to `.2`), so the log of a run
|
||||
//! that crashed survives the next launch. Runs without preferences (`WORDCRAFT_NO_PREFS`) log to
|
||||
//! standard error only.
|
||||
//!
|
||||
//! Levels: `info` for WordCraft's own crates, `warn` for everything else (wgpu and naga are
|
||||
//! chatty). `RUST_LOG` replaces that with env_logger-style directives: `debug`,
|
||||
//! `warn,wordcraft_docx=trace`, `wgpu_core=info`. A directive ending in `*` matches every target
|
||||
//! that starts with it (`wordcraft*=debug`).
|
||||
//!
|
||||
//! Records logged before the settings directory is known are kept (up to [`MAX_PENDING`]) and
|
||||
//! written once the file is attached. Writing never panics: a file that can't be created or
|
||||
//! written leaves standard error as the only sink.
|
||||
//!
|
||||
//! The panic hook ([`install_panic_hook`]) reports every panic, caught by `Session::run`'s guard or
|
||||
//! not, through this logger. Text a panic message quotes between backticks (a slice of a string,
|
||||
//! which can be the user's writing) is left out.
|
||||
|
||||
use std::fs::File;
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Mutex, OnceLock, PoisonError};
|
||||
use std::time::SystemTime;
|
||||
|
||||
use log::LevelFilter;
|
||||
|
||||
/// The current log file's name inside the log directory.
|
||||
pub const LOG_FILE: &str = "wordcraft.log";
|
||||
/// How many previous logs are kept (`wordcraft.1.log` … `wordcraft.<KEEP>.log`).
|
||||
pub const KEEP: usize = 2;
|
||||
/// The log file stops growing past this size (a runaway warning can't fill the disk).
|
||||
pub const MAX_FILE_BYTES: u64 = 16 * 1024 * 1024;
|
||||
/// Records kept in memory until the log file is attached.
|
||||
pub const MAX_PENDING: usize = 512;
|
||||
/// The built-in filter when `RUST_LOG` is unset or empty.
|
||||
pub const DEFAULT_FILTER: &str = "warn,wordcraft*=info";
|
||||
|
||||
/// Per-target level filter parsed from env_logger-style directives.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Filter {
|
||||
default: LevelFilter,
|
||||
directives: Vec<(String, LevelFilter)>,
|
||||
}
|
||||
|
||||
impl Filter {
|
||||
/// Parse `spec`; unknown levels and empty parts are skipped. Without a bare level, targets no
|
||||
/// directive names log errors only.
|
||||
pub fn parse(spec: &str) -> Filter {
|
||||
let mut f = Filter { default: LevelFilter::Error, directives: Vec::new() };
|
||||
for part in spec.split(',').map(str::trim).filter(|p| !p.is_empty()) {
|
||||
match part.split_once('=') {
|
||||
Some((name, level)) => {
|
||||
let name = name.trim();
|
||||
if let (false, Some(level)) = (name.is_empty(), parse_level(level)) {
|
||||
f.directives.push((name.to_owned(), level));
|
||||
}
|
||||
}
|
||||
None => match parse_level(part) {
|
||||
Some(level) => f.default = level,
|
||||
// A bare target name: everything from it (env_logger does the same).
|
||||
None => f.directives.push((part.to_owned(), LevelFilter::Trace)),
|
||||
},
|
||||
}
|
||||
}
|
||||
f
|
||||
}
|
||||
|
||||
/// The level that applies to `target` (the most specific matching directive wins).
|
||||
pub fn level_for(&self, target: &str) -> LevelFilter {
|
||||
self.directives.iter().filter(|(name, _)| matches(name, target)).max_by_key(|(name, _)| name.len()).map_or(self.default, |(_, level)| *level)
|
||||
}
|
||||
|
||||
/// The most verbose level any target can reach (for `log::set_max_level`).
|
||||
pub fn max(&self) -> LevelFilter {
|
||||
self.directives.iter().map(|(_, level)| *level).fold(self.default, Ord::max)
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_level(s: &str) -> Option<LevelFilter> {
|
||||
s.trim().parse().ok()
|
||||
}
|
||||
|
||||
/// `name` matches `target` itself and its submodules (`a` matches `a` and `a::b`, not `ab`);
|
||||
/// `name*` matches every target starting with `name`.
|
||||
fn matches(name: &str, target: &str) -> bool {
|
||||
match name.strip_suffix('*') {
|
||||
Some(prefix) => target.starts_with(prefix),
|
||||
None => target.strip_prefix(name).is_some_and(|rest| rest.is_empty() || rest.starts_with("::")),
|
||||
}
|
||||
}
|
||||
|
||||
/// `2026-10-08T07:59:17.728Z` (UTC, milliseconds). A clock before 1970 reads as the epoch (the
|
||||
/// `duration_since` clamp); past the last date chrono can represent (year 262143) the proleptic
|
||||
/// Gregorian date is kept via the 400-year cycle rather than falling back to the epoch, so the
|
||||
/// output never changes for a value the old formatter accepted and logging never panics.
|
||||
pub fn timestamp(t: SystemTime) -> String {
|
||||
let since = t.duration_since(std::time::UNIX_EPOCH).unwrap_or_default();
|
||||
let secs = since.as_secs();
|
||||
let (days, rem) = (secs / 86_400, secs % 86_400);
|
||||
let (y, m, d) = civil_from_days(days);
|
||||
format!("{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}.{:03}Z", rem / 3600, rem % 3600 / 60, rem % 60, since.subsec_millis())
|
||||
}
|
||||
|
||||
/// Days since 1970-01-01 → proleptic Gregorian (year, month, day).
|
||||
///
|
||||
/// `timestamp` clamps a pre-1970 clock to the epoch, so `days` is an unsigned count that can run
|
||||
/// past `NaiveDate`'s ±262143-year range. The Gregorian calendar repeats every 400 years
|
||||
/// (146_097 days), so chrono converts the day within one cycle and whole cycles go back into the
|
||||
/// year (an `i128`, then saturated into `i64`), keeping chrono as the only calendar logic and
|
||||
/// reproducing the old `civil_from_days` result exactly without hand-rolled day math. 1970-01-01
|
||||
/// is `num_days_from_ce` 719_163.
|
||||
fn civil_from_days(days: u64) -> (i64, u32, u32) {
|
||||
use chrono::Datelike;
|
||||
let (cycles, rest) = (days / 146_097, days % 146_097);
|
||||
// `rest + 719_163` is 719_163..865_259, always a valid CE day.
|
||||
match i32::try_from(rest + 719_163).ok().and_then(chrono::NaiveDate::from_num_days_from_ce_opt) {
|
||||
Some(d) => {
|
||||
let y = i128::from(d.year()) + i128::from(cycles) * 400;
|
||||
(i64::try_from(y).unwrap_or(i64::MAX), d.month(), d.day())
|
||||
}
|
||||
None => (1970, 1, 1), // unreachable
|
||||
}
|
||||
}
|
||||
|
||||
fn numbered(dir: &Path, n: usize) -> PathBuf {
|
||||
if n == 0 { dir.join(LOG_FILE) } else { dir.join(format!("wordcraft.{n}.log")) }
|
||||
}
|
||||
|
||||
/// Shift the previous logs up one (`.log` → `.1.log` → … → `.<KEEP>.log`, the oldest dropped)
|
||||
/// and create a fresh, empty log file in `dir` (created if missing).
|
||||
pub fn rotate(dir: &Path) -> std::io::Result<(PathBuf, File)> {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
for n in (1..=KEEP).rev() {
|
||||
match std::fs::rename(numbered(dir, n - 1), numbered(dir, n)) {
|
||||
Err(e) if e.kind() != std::io::ErrorKind::NotFound => return Err(e),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let path = numbered(dir, 0);
|
||||
let file = File::create(&path)?;
|
||||
Ok((path, file))
|
||||
}
|
||||
|
||||
/// One formatted log line: `<timestamp> <LEVEL> [<thread>] <target>: <message>\n`.
|
||||
pub fn format_line(ts: &str, level: log::Level, thread: &str, target: &str, message: &str) -> String {
|
||||
let message = message.strip_suffix('\n').unwrap_or(message);
|
||||
format!("{ts} {level:<5} [{thread}] {target}: {message}\n")
|
||||
}
|
||||
|
||||
/// Where formatted lines go besides standard error: kept in memory until a file is attached,
|
||||
/// then appended to it until it reaches its size cap.
|
||||
pub struct Sink {
|
||||
file: Option<File>,
|
||||
pending: Vec<String>,
|
||||
dropped: usize,
|
||||
written: u64,
|
||||
max_bytes: u64,
|
||||
capped: bool,
|
||||
}
|
||||
|
||||
impl Sink {
|
||||
pub fn new(max_bytes: u64) -> Sink {
|
||||
Sink { file: None, pending: Vec::new(), dropped: 0, written: 0, max_bytes, capped: false }
|
||||
}
|
||||
|
||||
/// Append `line` to the file, or keep it until [`Sink::attach`].
|
||||
pub fn write(&mut self, line: &str) {
|
||||
if self.file.is_none() {
|
||||
if self.capped {
|
||||
// No file is coming ([`Sink::no_file`]): standard error had the line.
|
||||
} else if self.pending.len() < MAX_PENDING {
|
||||
self.pending.push(line.to_owned());
|
||||
} else {
|
||||
self.dropped = self.dropped.saturating_add(1);
|
||||
}
|
||||
return;
|
||||
}
|
||||
self.append(line);
|
||||
}
|
||||
|
||||
/// Start writing to `file` (a fresh one: the size cap starts over), first the lines kept so far.
|
||||
pub fn attach(&mut self, file: File) {
|
||||
self.file = Some(file);
|
||||
self.written = 0;
|
||||
self.capped = false;
|
||||
for line in std::mem::take(&mut self.pending) {
|
||||
self.append(&line);
|
||||
}
|
||||
if self.dropped > 0 {
|
||||
let note = format!("{} earlier log lines were dropped before the log file was opened\n", self.dropped);
|
||||
self.dropped = 0;
|
||||
self.append(¬e);
|
||||
}
|
||||
}
|
||||
|
||||
/// There will be no log file: forget the lines kept for it and keep no more.
|
||||
pub fn no_file(&mut self) {
|
||||
self.file = None;
|
||||
self.pending = Vec::new();
|
||||
self.dropped = 0;
|
||||
self.capped = true;
|
||||
}
|
||||
|
||||
fn append(&mut self, line: &str) {
|
||||
if self.capped {
|
||||
return;
|
||||
}
|
||||
let Some(file) = self.file.as_mut() else { return };
|
||||
let len = u64::try_from(line.len()).unwrap_or(u64::MAX);
|
||||
let text = if self.written.saturating_add(len) > self.max_bytes {
|
||||
self.capped = true;
|
||||
format!("log file reached {} bytes; later records go to standard error only\n", self.max_bytes)
|
||||
} else {
|
||||
self.written = self.written.saturating_add(len);
|
||||
line.to_owned()
|
||||
};
|
||||
// A full disk or a vanished file must not take the app down: drop the file sink.
|
||||
if file.write_all(text.as_bytes()).is_err() {
|
||||
self.file = None;
|
||||
self.capped = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The installed logger: a [`Filter`], standard error and a [`Sink`].
|
||||
pub struct AppLogger {
|
||||
filter: Filter,
|
||||
stderr: bool,
|
||||
sink: Mutex<Sink>,
|
||||
}
|
||||
|
||||
impl AppLogger {
|
||||
pub fn new(filter: Filter, stderr: bool) -> AppLogger {
|
||||
AppLogger { filter, stderr, sink: Mutex::new(Sink::new(MAX_FILE_BYTES)) }
|
||||
}
|
||||
|
||||
/// Rotate the logs in `dir` and send records to the fresh file; returns its path. On an error
|
||||
/// standard error stays the only sink.
|
||||
pub fn attach_dir(&self, dir: &Path) -> Result<PathBuf, String> {
|
||||
// A thread that panicked while logging leaves the sink usable: take it back.
|
||||
let mut sink = self.sink.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
match rotate(dir) {
|
||||
Ok((path, file)) => {
|
||||
sink.attach(file);
|
||||
Ok(path)
|
||||
}
|
||||
Err(e) => {
|
||||
sink.no_file();
|
||||
Err(format!("{}: {e}", dir.display()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// No log file for this run (runs without preferences): log to standard error only.
|
||||
pub fn no_file(&self) {
|
||||
self.sink.lock().unwrap_or_else(PoisonError::into_inner).no_file();
|
||||
}
|
||||
}
|
||||
|
||||
impl log::Log for AppLogger {
|
||||
fn enabled(&self, metadata: &log::Metadata<'_>) -> bool {
|
||||
metadata.level() <= self.filter.level_for(metadata.target())
|
||||
}
|
||||
|
||||
fn log(&self, record: &log::Record<'_>) {
|
||||
if !self.enabled(record.metadata()) {
|
||||
return;
|
||||
}
|
||||
// Formatted before the sink is locked, so a message that logs while it is formatted can't deadlock.
|
||||
let thread = std::thread::current();
|
||||
let line =
|
||||
format_line(×tamp(SystemTime::now()), record.level(), thread.name().unwrap_or("?"), record.target(), &record.args().to_string());
|
||||
if self.stderr {
|
||||
// No terminal (a Windows GUI build, a closed pipe) is not an error worth reporting.
|
||||
let _ = std::io::stderr().write_all(line.as_bytes());
|
||||
}
|
||||
self.sink.lock().unwrap_or_else(PoisonError::into_inner).write(&line);
|
||||
}
|
||||
|
||||
fn flush(&self) {}
|
||||
}
|
||||
|
||||
/// Install the logger (filter from `RUST_LOG`, else [`DEFAULT_FILTER`]); `None` when another
|
||||
/// logger was installed first. Call [`AppLogger::attach_dir`] once the settings directory is known.
|
||||
pub fn install() -> Option<&'static AppLogger> {
|
||||
static LOGGER: OnceLock<AppLogger> = OnceLock::new();
|
||||
let spec = std::env::var("RUST_LOG").ok().filter(|s| !s.trim().is_empty());
|
||||
let filter = Filter::parse(spec.as_deref().unwrap_or(DEFAULT_FILTER));
|
||||
let max = filter.max();
|
||||
let logger = LOGGER.get_or_init(|| AppLogger::new(filter, true));
|
||||
log::set_logger(logger).ok()?;
|
||||
log::set_max_level(max);
|
||||
Some(logger)
|
||||
}
|
||||
|
||||
/// Replace text a panic message quotes between backticks with `…`: std quotes the string it was
|
||||
/// slicing (`byte index 5 is not a char boundary; … of `<the string>``), and that string can be
|
||||
/// the user's writing. An unpaired backtick leaves the rest of the message out too.
|
||||
pub fn redact_quoted(message: &str) -> String {
|
||||
let mut out = String::with_capacity(message.len());
|
||||
for (i, part) in message.split('`').enumerate() {
|
||||
if i % 2 == 1 {
|
||||
out.push_str("`…");
|
||||
} else {
|
||||
if i > 0 {
|
||||
out.push('`');
|
||||
}
|
||||
out.push_str(part);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The text the panic hook logs: where it happened, the redacted message and, when captured
|
||||
/// (`RUST_BACKTRACE`), the backtrace.
|
||||
pub fn panic_report(location: Option<&str>, message: Option<&str>, backtrace: Option<&str>) -> String {
|
||||
let message = message.map_or_else(|| "(no message)".to_owned(), redact_quoted);
|
||||
let mut report = format!("panic at {}: {message}", location.unwrap_or("an unknown place"));
|
||||
if let Some(trace) = backtrace {
|
||||
report.push('\n');
|
||||
report.push_str(trace.trim_end());
|
||||
}
|
||||
report
|
||||
}
|
||||
|
||||
/// Report every panic (caught by `Session::run`'s guard or not) through the logger, so it reaches
|
||||
/// the log file too; standard error alone when `RUST_LOG` turned errors off.
|
||||
pub fn install_panic_hook() {
|
||||
std::panic::set_hook(Box::new(|info| {
|
||||
let location = info.location().map(ToString::to_string);
|
||||
let trace = std::backtrace::Backtrace::capture();
|
||||
let trace = (trace.status() == std::backtrace::BacktraceStatus::Captured).then(|| trace.to_string());
|
||||
let report = panic_report(location.as_deref(), info.payload_as_str(), trace.as_deref());
|
||||
if log::log_enabled!(log::Level::Error) {
|
||||
log::error!("{report}");
|
||||
} else {
|
||||
// `eprintln!` panics on a broken stderr pipe, and a panic inside the panic hook aborts.
|
||||
let _ = std::io::Write::write_fmt(&mut std::io::stderr(), format_args!("wordcraft: {report}\n"));
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -1,332 +0,0 @@
|
||||
use super::*;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::time::{Duration, UNIX_EPOCH};
|
||||
|
||||
fn temp_dir(tag: &str) -> PathBuf {
|
||||
static N: AtomicUsize = AtomicUsize::new(0);
|
||||
let d = std::env::temp_dir().join(format!("wordcraft-logging-{tag}-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed)));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
d
|
||||
}
|
||||
|
||||
fn read(path: &Path) -> String {
|
||||
std::fs::read_to_string(path).expect("read log")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_default_filter_shows_wordcraft_info_and_other_crates_warnings() {
|
||||
let f = Filter::parse(DEFAULT_FILTER);
|
||||
assert_eq!(f.level_for("wordcraft"), LevelFilter::Info);
|
||||
assert_eq!(f.level_for("wordcraft::control_server"), LevelFilter::Info);
|
||||
assert_eq!(f.level_for("wordcraft_docx::package"), LevelFilter::Info);
|
||||
assert_eq!(f.level_for("wordcraft_ui_egui"), LevelFilter::Info);
|
||||
assert_eq!(f.level_for("wgpu_core::device"), LevelFilter::Warn);
|
||||
assert_eq!(f.level_for("naga"), LevelFilter::Warn);
|
||||
assert_eq!(f.max(), LevelFilter::Info);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn directives_follow_env_logger_and_the_most_specific_one_wins() {
|
||||
let f = Filter::parse("info,wgpu_core=error,wordcraft_pdf=trace,wordcraft_pdf::fonts=off");
|
||||
assert_eq!(f.level_for("eframe"), LevelFilter::Info);
|
||||
assert_eq!(f.level_for("wgpu_core::instance"), LevelFilter::Error);
|
||||
assert_eq!(f.level_for("wordcraft_pdf::images"), LevelFilter::Trace);
|
||||
assert_eq!(f.level_for("wordcraft_pdf::fonts"), LevelFilter::Off);
|
||||
assert_eq!(f.max(), LevelFilter::Trace);
|
||||
// A module name is matched at `::` boundaries, not as a bare prefix.
|
||||
assert_eq!(f.level_for("wgpu_core_extra"), LevelFilter::Info);
|
||||
// A trailing `*` is a prefix.
|
||||
assert_eq!(Filter::parse("wordcraft*=debug").level_for("wordcraft_layout::lines"), LevelFilter::Debug);
|
||||
assert_eq!(Filter::parse("wordcraft*=debug").level_for("eframe"), LevelFilter::Error);
|
||||
// A bare target name sets that target to the most verbose level, as env_logger does.
|
||||
assert_eq!(Filter::parse("naga").level_for("naga::front"), LevelFilter::Trace);
|
||||
assert_eq!(Filter::parse("naga").level_for("eframe"), LevelFilter::Error);
|
||||
// Levels are case-insensitive and surrounding blanks are ignored.
|
||||
assert_eq!(Filter::parse(" WARN , wordcraft = Debug ").level_for("wordcraft"), LevelFilter::Debug);
|
||||
assert_eq!(Filter::parse(" WARN , wordcraft = Debug ").level_for("eframe"), LevelFilter::Warn);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_specs_never_panic_and_fall_back_sensibly() {
|
||||
let long = "x".repeat(100_000);
|
||||
let many = "a=info,".repeat(10_000);
|
||||
for spec in [
|
||||
"",
|
||||
",,,",
|
||||
"=",
|
||||
"==",
|
||||
"=debug",
|
||||
"wordcraft=",
|
||||
"nonsense=loud",
|
||||
"🦀=info",
|
||||
"*",
|
||||
"*=",
|
||||
"=*",
|
||||
"a=b=c",
|
||||
"warn,,wordcraft=DEBUG",
|
||||
"\0",
|
||||
"é::ü=trace",
|
||||
&long,
|
||||
&many,
|
||||
] {
|
||||
let f = Filter::parse(spec);
|
||||
for target in ["", "wordcraft", "🦀", "a::b", "*"] {
|
||||
let _ = f.level_for(target);
|
||||
}
|
||||
let _ = f.max();
|
||||
}
|
||||
assert_eq!(Filter::parse("warn,,wordcraft=DEBUG").level_for("wordcraft"), LevelFilter::Debug);
|
||||
// An unknown level is skipped: that target keeps the default.
|
||||
assert_eq!(Filter::parse("nonsense=loud").level_for("nonsense"), LevelFilter::Error);
|
||||
assert_eq!(Filter::parse("wordcraft=").level_for("wordcraft"), LevelFilter::Error);
|
||||
assert_eq!(Filter::parse("=debug").max(), LevelFilter::Error);
|
||||
assert_eq!(Filter::parse("🦀=info").level_for("🦀::claw"), LevelFilter::Info);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn timestamps_are_utc_with_milliseconds() {
|
||||
assert_eq!(timestamp(UNIX_EPOCH), "1970-01-01T00:00:00.000Z");
|
||||
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_millis(1_791_446_357_728)), "2026-10-08T07:59:17.728Z");
|
||||
// Leap day, and the day after it.
|
||||
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(1_709_164_800)), "2024-02-29T00:00:00.000Z");
|
||||
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(1_709_251_199)), "2024-02-29T23:59:59.000Z");
|
||||
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(1_709_251_200)), "2024-03-01T00:00:00.000Z");
|
||||
// 2000 is a leap year (divisible by 400), 2100 is not.
|
||||
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(951_782_400)), "2000-02-29T00:00:00.000Z");
|
||||
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(4_107_542_400)), "2100-03-01T00:00:00.000Z");
|
||||
// Before the epoch (a clock set wrong) clamps to the epoch instead of panicking.
|
||||
assert_eq!(timestamp(UNIX_EPOCH - Duration::from_secs(5)), "1970-01-01T00:00:00.000Z");
|
||||
// Past chrono's range (a clock set absurdly far ahead) keeps the proleptic Gregorian date
|
||||
// the old formatter gave, rather than falling back to the epoch. FredApps' counterexample:
|
||||
// UNIX_EPOCH + 10_000_000_000_000 s was 318857-05-20T17:46:40.000Z and must stay so.
|
||||
// Windows' SystemTime holds only up to about year 30828, so this is checked where it fits.
|
||||
if let Some(far) = UNIX_EPOCH.checked_add(Duration::from_secs(10_000_000_000_000)) {
|
||||
assert_eq!(timestamp(far), "318857-05-20T17:46:40.000Z");
|
||||
}
|
||||
// Windows' SystemTime can't hold u64::MAX / 2 seconds, so it is only checked where it exists.
|
||||
if let Some(far) = UNIX_EPOCH.checked_add(Duration::from_secs(u64::MAX / 2)) {
|
||||
assert_eq!(timestamp(far), "292277026596-12-04T15:30:07.000Z");
|
||||
}
|
||||
// Years past 9999 keep the plain zero-padded year (no `+`).
|
||||
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(253_402_300_800)), "10000-01-01T00:00:00.000Z");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_carries_time_level_thread_target_and_message() {
|
||||
assert_eq!(
|
||||
format_line("2026-10-08T07:59:17.728Z", log::Level::Warn, "main", "wordcraft_docx::package", "skipping unreadable zip entry 3"),
|
||||
"2026-10-08T07:59:17.728Z WARN [main] wordcraft_docx::package: skipping unreadable zip entry 3\n"
|
||||
);
|
||||
// A multi-line message keeps its lines; the record still ends in one newline.
|
||||
assert!(format_line("t", log::Level::Error, "w", "x", "a\nb\n").ends_with("x: a\nb\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotation_keeps_the_previous_logs_and_starts_an_empty_file() {
|
||||
let dir = temp_dir("rotate");
|
||||
for run in 1..=4 {
|
||||
let (path, _file) = rotate(&dir).expect("rotate");
|
||||
assert_eq!(path, dir.join(LOG_FILE));
|
||||
assert_eq!(read(&path), "");
|
||||
std::fs::write(&path, format!("run {run}")).expect("write");
|
||||
}
|
||||
assert_eq!(read(&dir.join(LOG_FILE)), "run 4");
|
||||
assert_eq!(read(&dir.join("wordcraft.1.log")), "run 3");
|
||||
assert_eq!(read(&dir.join("wordcraft.2.log")), "run 2");
|
||||
assert!(!dir.join("wordcraft.3.log").exists(), "only {KEEP} old logs are kept");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotation_into_an_unusable_directory_is_an_error_not_a_panic() {
|
||||
let dir = temp_dir("blocked");
|
||||
std::fs::create_dir_all(dir.parent().expect("parent")).expect("tmp");
|
||||
std::fs::write(&dir, "a file where the directory should be").expect("block");
|
||||
assert!(rotate(&dir).is_err());
|
||||
let _ = std::fs::remove_file(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lines_logged_before_the_file_exists_are_written_when_it_is_attached() {
|
||||
let dir = temp_dir("pending");
|
||||
let (path, file) = rotate(&dir).expect("rotate");
|
||||
let mut sink = Sink::new(MAX_FILE_BYTES);
|
||||
sink.write("early 1\n");
|
||||
sink.write("early 2\n");
|
||||
sink.attach(file);
|
||||
sink.write("late\n");
|
||||
assert_eq!(read(&path), "early 1\nearly 2\nlate\n");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_pending_buffer_is_bounded_and_says_how_much_it_dropped() {
|
||||
let dir = temp_dir("bounded");
|
||||
let (path, file) = rotate(&dir).expect("rotate");
|
||||
let mut sink = Sink::new(MAX_FILE_BYTES);
|
||||
for i in 0..MAX_PENDING + 5 {
|
||||
sink.write(&format!("line {i}\n"));
|
||||
}
|
||||
sink.attach(file);
|
||||
let text = read(&path);
|
||||
assert_eq!(text.lines().filter(|l| l.starts_with("line ")).count(), MAX_PENDING);
|
||||
assert!(text.contains("5 earlier log lines were dropped"), "{text}");
|
||||
assert!(text.contains("line 0\n") && !text.contains(&format!("line {MAX_PENDING}\n")));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exactly_a_full_pending_buffer_drops_nothing() {
|
||||
let dir = temp_dir("full");
|
||||
let (path, file) = rotate(&dir).expect("rotate");
|
||||
let mut sink = Sink::new(MAX_FILE_BYTES);
|
||||
for i in 0..MAX_PENDING {
|
||||
sink.write(&format!("line {i}\n"));
|
||||
}
|
||||
sink.attach(file);
|
||||
let text = read(&path);
|
||||
assert_eq!(text.lines().count(), MAX_PENDING);
|
||||
assert!(!text.contains("dropped"), "{text}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_a_file_nothing_is_kept_in_memory() {
|
||||
let mut sink = Sink::new(MAX_FILE_BYTES);
|
||||
sink.write("early\n");
|
||||
sink.no_file();
|
||||
sink.write("late\n");
|
||||
assert!(sink.pending.is_empty() && sink.dropped == 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_file_stops_at_its_size_cap_with_one_note() {
|
||||
let dir = temp_dir("cap");
|
||||
let (path, file) = rotate(&dir).expect("rotate");
|
||||
let mut sink = Sink::new(100);
|
||||
sink.attach(file);
|
||||
for i in 0..50 {
|
||||
sink.write(&format!("line {i:02} with some padding\n"));
|
||||
}
|
||||
let text = read(&path);
|
||||
assert_eq!(text.lines().filter(|l| l.starts_with("line ")).count(), 3, "{text}");
|
||||
assert_eq!(text.matches("log file reached").count(), 1, "{text}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_logger_filters_records_and_writes_them_to_the_attached_file() {
|
||||
use log::Log;
|
||||
let dir = temp_dir("logger");
|
||||
let logger = AppLogger::new(Filter::parse(DEFAULT_FILTER), false);
|
||||
let record = |level, target: &'static str, msg: &'static str| {
|
||||
logger.log(&log::Record::builder().level(level).target(target).args(format_args!("{msg}")).build());
|
||||
};
|
||||
record(log::Level::Info, "wordcraft", "before the settings directory");
|
||||
record(log::Level::Info, "wgpu_core::device", "too chatty");
|
||||
let path = logger.attach_dir(&dir).expect("attach");
|
||||
assert_eq!(path, dir.join(LOG_FILE));
|
||||
record(log::Level::Warn, "wgpu_hal::vulkan", "a real warning");
|
||||
record(log::Level::Error, "wordcraft_render", "PNG encode: bad size 0×0");
|
||||
record(log::Level::Debug, "wordcraft", "below info");
|
||||
let text = read(&path);
|
||||
let lines: Vec<&str> = text.lines().collect();
|
||||
assert_eq!(lines.len(), 3, "{text}");
|
||||
assert!(lines[0].contains(" INFO [") && lines[0].ends_with("wordcraft: before the settings directory"), "{text}");
|
||||
assert!(lines[1].ends_with("wgpu_hal::vulkan: a real warning"), "{text}");
|
||||
assert!(lines[2].contains(" ERROR [") && lines[2].ends_with("wordcraft_render: PNG encode: bad size 0×0"), "{text}");
|
||||
assert!(logger.enabled(&log::Metadata::builder().level(log::Level::Info).target("wordcraft_ui_egui").build()));
|
||||
assert!(!logger.enabled(&log::Metadata::builder().level(log::Level::Info).target("naga").build()));
|
||||
// Attaching again rotates: the first log becomes `.1`.
|
||||
logger.attach_dir(&dir).expect("attach again");
|
||||
assert_eq!(read(&dir.join("wordcraft.1.log")), text);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn records_from_many_threads_are_whole_lines() {
|
||||
use log::Log;
|
||||
let dir = temp_dir("threads");
|
||||
let logger = std::sync::Arc::new(AppLogger::new(Filter::parse("info"), false));
|
||||
let path = logger.attach_dir(&dir).expect("attach");
|
||||
let workers: Vec<_> = (0..8)
|
||||
.map(|t| {
|
||||
let l = std::sync::Arc::clone(&logger);
|
||||
std::thread::spawn(move || {
|
||||
for i in 0..100 {
|
||||
l.log(&log::Record::builder().level(log::Level::Info).target("wordcraft").args(format_args!("thread {t} record {i}")).build());
|
||||
}
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
for w in workers {
|
||||
w.join().expect("worker");
|
||||
}
|
||||
let text = read(&path);
|
||||
assert_eq!(text.lines().count(), 800);
|
||||
assert!(text.lines().all(|l| l.contains(" wordcraft: thread ")), "{text}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn attaching_to_an_unusable_directory_reports_an_error_and_keeps_logging() {
|
||||
use log::Log;
|
||||
let dir = temp_dir("unusable");
|
||||
std::fs::create_dir_all(dir.parent().expect("parent")).expect("tmp");
|
||||
std::fs::write(&dir, "not a directory").expect("block");
|
||||
let logger = AppLogger::new(Filter::parse("info"), false);
|
||||
logger.log(&log::Record::builder().level(log::Level::Error).target("x").args(format_args!("early")).build());
|
||||
assert!(logger.attach_dir(&dir).is_err());
|
||||
logger.log(&log::Record::builder().level(log::Level::Error).target("x").args(format_args!("still fine")).build());
|
||||
// Nothing waits in memory for a file that won't come.
|
||||
let sink = logger.sink.lock().expect("sink");
|
||||
assert!(sink.pending.is_empty() && sink.file.is_none());
|
||||
drop(sink);
|
||||
let _ = std::fs::remove_file(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_poisoned_sink_still_logs() {
|
||||
use log::Log;
|
||||
let dir = temp_dir("poison");
|
||||
let logger = std::sync::Arc::new(AppLogger::new(Filter::parse("info"), false));
|
||||
let l = std::sync::Arc::clone(&logger);
|
||||
let _ = std::thread::spawn(move || {
|
||||
let _guard = l.sink.lock().expect("lock");
|
||||
panic!("poison the sink");
|
||||
})
|
||||
.join();
|
||||
assert!(logger.sink.is_poisoned());
|
||||
let path = logger.attach_dir(&dir).expect("attach");
|
||||
logger.log(&log::Record::builder().level(log::Level::Warn).target("wordcraft").args(format_args!("after the poison")).build());
|
||||
assert!(read(&path).contains("wordcraft: after the poison"));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn panic_messages_leave_out_quoted_text() {
|
||||
// What std says when a string is sliced inside a character: the string is the user's text.
|
||||
let msg = "byte index 5 is not a char boundary; it is inside 'é' (bytes 4..6) of `Dear Ms Smith, my secret`";
|
||||
assert_eq!(redact_quoted(msg), "byte index 5 is not a char boundary; it is inside 'é' (bytes 4..6) of `…`");
|
||||
assert_eq!(redact_quoted("byte index 99 is out of range of `my diary`[...]"), "byte index 99 is out of range of `…`[...]");
|
||||
assert_eq!(redact_quoted("a `b` c `d` e"), "a `…` c `…` e");
|
||||
// An unpaired backtick hides the rest rather than risk leaking it.
|
||||
assert_eq!(redact_quoted("of `half a sentence"), "of `…");
|
||||
assert_eq!(
|
||||
redact_quoted("no quotes: index out of bounds: the len is 3 but the index is 5"),
|
||||
"no quotes: index out of bounds: the len is 3 but the index is 5"
|
||||
);
|
||||
assert_eq!(redact_quoted(""), "");
|
||||
assert_eq!(redact_quoted("``"), "`…`");
|
||||
assert_eq!(redact_quoted("🦀`🦀`🦀"), "🦀`…`🦀");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_panic_report_names_the_place_and_the_redacted_message() {
|
||||
assert_eq!(
|
||||
panic_report(Some("crates/engine/src/cmd/edit.rs:12:5"), Some("of `secret`"), None),
|
||||
"panic at crates/engine/src/cmd/edit.rs:12:5: of `…`"
|
||||
);
|
||||
assert_eq!(panic_report(None, None, None), "panic at an unknown place: (no message)");
|
||||
assert_eq!(panic_report(Some("a.rs:1:1"), Some("boom"), Some(" 0: main\n")), "panic at a.rs:1:1: boom\n 0: main");
|
||||
}
|
||||
+731
-558
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,266 @@
|
||||
//! App-private Nightly session health, not telemetry or a Launcher protocol.
|
||||
//! A live owner holds a separate persistent lease; secondary launches never rewrite its record.
|
||||
//! Dropping the guard does not clear the marker. Only the app's controlled return path does.
|
||||
|
||||
use std::fs::{File, OpenOptions};
|
||||
use std::io::{self, Read};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
|
||||
const RECORD: &str = "nightly-session.json";
|
||||
const LEASE: &str = "nightly-session.lock";
|
||||
const MAX_METADATA_BYTES: usize = 256;
|
||||
|
||||
pub struct Session {
|
||||
_lease: File,
|
||||
path: PathBuf,
|
||||
own_record: Vec<u8>,
|
||||
previous_unclean: bool,
|
||||
}
|
||||
|
||||
fn regular_or_missing(path: &Path) -> io::Result<bool> {
|
||||
match std::fs::symlink_metadata(path) {
|
||||
Ok(metadata) if metadata.file_type().is_file() && !metadata.file_type().is_symlink() => Ok(true),
|
||||
Ok(_) => Err(io::Error::other("Nightly session state must be a regular file, not an alias or directory")),
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
}
|
||||
|
||||
/// Write `bytes` to `path` through a fresh temporary file in the same folder and a rename: the
|
||||
/// destination entry is replaced, never followed, so a link planted at `path` is not written
|
||||
/// through. The file is synced and the folder is synced after the rename.
|
||||
fn write_no_follow(path: &Path, bytes: &[u8]) -> io::Result<()> {
|
||||
static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
|
||||
let directory = path.parent().ok_or_else(|| io::Error::other("the session record has no folder"))?;
|
||||
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let temporary = directory.join(format!(".{name}.{}-{}", std::process::id(), NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)));
|
||||
let mut file = OpenOptions::new().write(true).create_new(true).open(&temporary)?;
|
||||
let written = std::io::Write::write_all(&mut file, bytes).and_then(|()| file.sync_all());
|
||||
drop(file);
|
||||
if let Err(error) = written {
|
||||
let _ = std::fs::remove_file(&temporary);
|
||||
return Err(error);
|
||||
}
|
||||
if let Err(error) = std::fs::rename(&temporary, path) {
|
||||
let _ = std::fs::remove_file(&temporary);
|
||||
return Err(error);
|
||||
}
|
||||
if let Ok(directory) = File::open(directory) {
|
||||
let _ = directory.sync_all();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The owner's session, shared by the app's exit hook (macOS: a quit ends the process inside
|
||||
/// AppKit's terminate) and the code after the event loop.
|
||||
pub type Shared = Arc<Mutex<Option<Session>>>;
|
||||
|
||||
/// The controlled return ([`Session::finish`]) by whichever path comes first; later calls do nothing.
|
||||
pub fn finish_once(shared: &Shared, unclean_notice_shown: bool) {
|
||||
let watch = shared.lock().unwrap_or_else(PoisonError::into_inner).take();
|
||||
if let Some(watch) = watch
|
||||
&& let Err(error) = watch.finish(unclean_notice_shown)
|
||||
{
|
||||
log::warn!("Nightly session state was left intact: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// The warning belongs to this window: a busy secondary has no health-record coverage,
|
||||
/// while Stable and a lease-owning Nightly window preserve their existing result.
|
||||
pub fn begin_with_health(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result<(Option<Self>, bool)> {
|
||||
let watch = Self::begin(root, version, commit)?;
|
||||
let unavailable = root.is_some() && watch.is_none();
|
||||
Ok((watch, unavailable))
|
||||
}
|
||||
|
||||
/// `None` is stable or another owner of this profile. Neither case touches the record.
|
||||
/// The supplied root must already be the validated private Nightly profile.
|
||||
pub fn begin(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result<Option<Self>> {
|
||||
let Some(root) = root else { return Ok(None) };
|
||||
if version.is_empty() || version.len() > MAX_METADATA_BYTES || commit.is_some_and(|value| value.len() > MAX_METADATA_BYTES) {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidInput, "Nightly session provenance is missing or too large"));
|
||||
}
|
||||
let lease_path = root.join(LEASE);
|
||||
regular_or_missing(&lease_path)?;
|
||||
let lease = OpenOptions::new().read(true).write(true).create(true).truncate(false).open(lease_path)?;
|
||||
match lease.try_lock() {
|
||||
Ok(()) => {}
|
||||
Err(std::fs::TryLockError::WouldBlock) => return Ok(None),
|
||||
Err(std::fs::TryLockError::Error(error)) => return Err(error),
|
||||
}
|
||||
let path = root.join(RECORD);
|
||||
let previous_unclean = regular_or_missing(&path)?;
|
||||
let own_record = serde_json::to_vec(&serde_json::json!({
|
||||
"schema_version": 1,
|
||||
"channel": "nightly-v1",
|
||||
"version": version,
|
||||
"commit": commit.filter(|value| !value.is_empty()),
|
||||
}))?;
|
||||
write_no_follow(&path, &own_record)?;
|
||||
Ok(Some(Self { _lease: lease, path, own_record, previous_unclean }))
|
||||
}
|
||||
|
||||
pub fn previous_unclean(&self) -> bool {
|
||||
self.previous_unclean
|
||||
}
|
||||
|
||||
/// Controlled return. If an earlier session's interruption was detected but no window showed
|
||||
/// it yet, the record is left for the next owner to report; otherwise this is [`Self::complete`].
|
||||
pub fn finish(self, unclean_notice_shown: bool) -> io::Result<()> {
|
||||
if self.previous_unclean && !unclean_notice_shown {
|
||||
return Ok(());
|
||||
}
|
||||
self.complete()
|
||||
}
|
||||
|
||||
/// Controlled event-loop completion includes a handled startup error, not only exit 0.
|
||||
/// An unwind, abort, forced exit or killed process never calls this method.
|
||||
pub fn complete(self) -> io::Result<()> {
|
||||
if !regular_or_missing(&self.path)? {
|
||||
return Ok(());
|
||||
}
|
||||
let mut current = Vec::new();
|
||||
File::open(&self.path)?.take(self.own_record.len() as u64 + 1).read_to_end(&mut current)?;
|
||||
if current != self.own_record {
|
||||
return Err(io::Error::other("Nightly session state changed; leaving it intact"));
|
||||
}
|
||||
std::fs::remove_file(&self.path)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
struct Fixture(PathBuf);
|
||||
impl Fixture {
|
||||
fn new() -> Self {
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
loop {
|
||||
let path =
|
||||
std::env::temp_dir().join(format!("wordcraft-nightly-session-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
|
||||
match std::fs::create_dir(&path) {
|
||||
Ok(()) => return Self(path),
|
||||
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
|
||||
Err(error) => panic!("cannot create owned fixture: {error}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Drop for Fixture {
|
||||
fn drop(&mut self) {
|
||||
std::fs::remove_dir_all(&self.0).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn busy_secondary_reports_unavailable_without_replacing_the_owner_record() {
|
||||
let fixture = Fixture::new();
|
||||
let (stable, warning) = Session::begin_with_health(None, "stable", None).unwrap();
|
||||
assert!(stable.is_none() && !warning);
|
||||
let (first, warning) = Session::begin_with_health(Some(&fixture.0), "nightly", Some("owned-commit")).unwrap();
|
||||
assert!(!warning);
|
||||
let first = first.unwrap();
|
||||
let record = std::fs::read(fixture.0.join(RECORD)).unwrap();
|
||||
let (secondary, warning) = Session::begin_with_health(Some(&fixture.0), "secondary", None).unwrap();
|
||||
assert!(secondary.is_none() && warning, "a secondary window cannot claim recorded exit/crash coverage");
|
||||
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record);
|
||||
first.complete().unwrap();
|
||||
assert!(!fixture.0.join(RECORD).exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn controlled_completion_is_clean_but_an_unfinished_owner_is_reported_next_time() {
|
||||
let fixture = Fixture::new();
|
||||
let first = Session::begin(Some(&fixture.0), "first", Some("recorded-commit")).unwrap().unwrap();
|
||||
assert!(!first.previous_unclean());
|
||||
let own = std::fs::read(fixture.0.join(RECORD)).unwrap();
|
||||
assert!(Session::begin(Some(&fixture.0), "secondary", None).unwrap().is_none());
|
||||
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), own, "a busy secondary must not replace the owner's record");
|
||||
first.complete().unwrap();
|
||||
assert!(!fixture.0.join(RECORD).exists());
|
||||
let unimportant = Session::begin(Some(&fixture.0), "second", None).unwrap().unwrap();
|
||||
assert!(!unimportant.previous_unclean());
|
||||
drop(unimportant); // Unwind/abnormal-path ownership release, not a controlled completion.
|
||||
let next = Session::begin(Some(&fixture.0), "third", None).unwrap().unwrap();
|
||||
assert!(next.previous_unclean());
|
||||
next.complete().unwrap();
|
||||
assert!(!fixture.0.join(RECORD).exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_interruption_no_window_showed_survives_a_handled_startup_failure() {
|
||||
let fixture = Fixture::new();
|
||||
drop(Session::begin(Some(&fixture.0), "crashed", None).unwrap().unwrap());
|
||||
// The window never started: no notice was shown.
|
||||
let failed = Session::begin(Some(&fixture.0), "startup-failed", None).unwrap().unwrap();
|
||||
assert!(failed.previous_unclean());
|
||||
failed.finish(false).unwrap();
|
||||
// The next start still sees the interruption and shows it.
|
||||
let next = Session::begin(Some(&fixture.0), "next", None).unwrap().unwrap();
|
||||
assert!(next.previous_unclean());
|
||||
next.finish(true).unwrap();
|
||||
assert!(!fixture.0.join(RECORD).exists(), "a session that showed the notice clears its record");
|
||||
let clean = Session::begin(Some(&fixture.0), "clean", None).unwrap().unwrap();
|
||||
assert!(!clean.previous_unclean());
|
||||
clean.finish(false).unwrap();
|
||||
assert!(!fixture.0.join(RECORD).exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_exit_hook_and_the_return_path_finish_the_session_once() {
|
||||
let fixture = Fixture::new();
|
||||
let shared: Shared = Arc::new(Mutex::new(Session::begin(Some(&fixture.0), "quitting", None).unwrap()));
|
||||
// The exit hook (macOS quit: the only path that runs there).
|
||||
finish_once(&shared, false);
|
||||
assert!(!fixture.0.join(RECORD).exists(), "a quit that ran the exit hook is a clean exit");
|
||||
// Elsewhere the return path runs too, by then possibly after a successor took the profile.
|
||||
let successor = Session::begin(Some(&fixture.0), "successor", None).unwrap().unwrap();
|
||||
assert!(!successor.previous_unclean());
|
||||
let record = std::fs::read(fixture.0.join(RECORD)).unwrap();
|
||||
finish_once(&shared, false);
|
||||
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record, "the second finish must not touch a successor's record");
|
||||
successor.complete().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cleanup_never_removes_an_unknown_changed_record() {
|
||||
let fixture = Fixture::new();
|
||||
let watch = Session::begin(Some(&fixture.0), "nightly", None).unwrap().unwrap();
|
||||
std::fs::write(fixture.0.join(RECORD), b"replacement owned by someone else").unwrap();
|
||||
assert!(watch.complete().is_err());
|
||||
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), b"replacement owned by someone else");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provenance_is_bounded_and_never_collects_documents_paths_or_diagnostics() {
|
||||
let fixture = Fixture::new();
|
||||
assert!(Session::begin(Some(&fixture.0), &"x".repeat(MAX_METADATA_BYTES + 1), None).is_err());
|
||||
assert_eq!(std::fs::read_dir(&fixture.0).unwrap().count(), 0);
|
||||
assert!(Session::begin(None, "", None).unwrap().is_none(), "stable has no session-health side effects");
|
||||
let watch = Session::begin(Some(&fixture.0), "nightly", None).unwrap().unwrap();
|
||||
let data: serde_json::Value = serde_json::from_slice(&std::fs::read(fixture.0.join(RECORD)).unwrap()).unwrap();
|
||||
let fields = data.as_object().unwrap().keys().map(String::as_str).collect::<std::collections::BTreeSet<_>>();
|
||||
assert_eq!(fields, ["schema_version", "channel", "version", "commit"].into_iter().collect());
|
||||
assert!(data["commit"].is_null(), "missing provenance must not be invented");
|
||||
watch.complete().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn reserved_state_aliases_do_not_modify_external_files() {
|
||||
let fixture = Fixture::new();
|
||||
let external = fixture.0.join("stable-document");
|
||||
std::fs::write(&external, b"stable bytes").unwrap();
|
||||
for name in [LEASE, RECORD] {
|
||||
let alias = fixture.0.join(name);
|
||||
std::os::unix::fs::symlink(&external, &alias).unwrap();
|
||||
assert!(Session::begin(Some(&fixture.0), "nightly", None).is_err());
|
||||
assert_eq!(std::fs::read(&external).unwrap(), b"stable bytes");
|
||||
std::fs::remove_file(alias).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,906 +0,0 @@
|
||||
//! File › Save As through the XDG desktop portal on Linux and BSDs (#6180).
|
||||
//!
|
||||
//! The GTK file chooser behind the portal keeps the typed name when the user picks another file
|
||||
//! type, and `rfd` 0.17 reads only the file name from the portal's answer, so `Document1.docx`
|
||||
//! with PDF picked in the dropdown came back as `Document1.docx` and was saved as a Word document.
|
||||
//! The portal's answer does say which type was picked (`current_filter`), so Save As asks the portal
|
||||
//! itself over D-Bus via `zbus` and gives a name the dialog left alone that type's extension
|
||||
//! ([`with_chosen_type`]). `rfd` stays the fallback (zenity, or no portal), and this can go once an
|
||||
//! `rfd` release reads the picked type (upstream PolyMeilex/rfd#341).
|
||||
//!
|
||||
//! The dialog is attached to the window on X11 (`x11:<xid>`). On Wayland it has no parent: naming the
|
||||
//! window to the portal needs an xdg-foreign handle, which takes `unsafe` code the workspace forbids.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
use std::time::Duration;
|
||||
|
||||
use zbus::blocking::{MessageIterator, Proxy};
|
||||
use zbus::zvariant::{OwnedObjectPath, OwnedValue, Value};
|
||||
|
||||
/// One file type in the dialog: its label and extensions (`("PDF (*.pdf)", ["pdf"])`).
|
||||
pub type Filter = (String, Vec<String>);
|
||||
|
||||
/// Quicker than anyone can see a dialog and dismiss it (#2999).
|
||||
const TOO_QUICK: Duration = Duration::from_millis(300);
|
||||
|
||||
/// A thread-safe cancellation token to signal cancellation of an ongoing save request.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct CancelToken(std::sync::Arc<std::sync::atomic::AtomicBool>);
|
||||
|
||||
impl CancelToken {
|
||||
/// Creates a new cancellation token in the active (not cancelled) state.
|
||||
pub fn new() -> Self {
|
||||
Self(std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)))
|
||||
}
|
||||
|
||||
/// Signals that the active save request should be cancelled.
|
||||
pub fn cancel(&self) {
|
||||
self.0.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Returns `true` if cancellation has been requested.
|
||||
pub fn is_cancelled(&self) -> bool {
|
||||
self.0.load(std::sync::atomic::Ordering::Relaxed)
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for CancelToken {
|
||||
/// Compares two cancellation tokens by their current cancellation status.
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.is_cancelled() == other.is_cancelled()
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for CancelToken {}
|
||||
|
||||
/// A Save dialog request to pass to the desktop portal.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct SaveRequest {
|
||||
/// The portal's parent window identifier (`x11:<xid>`), or empty.
|
||||
pub parent: String,
|
||||
/// The name the dialog shows: the suggested file name (`Document1.docx`).
|
||||
pub name: Option<String>,
|
||||
/// The suggested file's name (`Document1.docx`): a name that comes back with its extension still
|
||||
/// takes the extension of the type picked ([`with_chosen_type`]).
|
||||
pub suggested: Option<String>,
|
||||
/// The initial folder to open in, if any.
|
||||
pub folder: Option<PathBuf>,
|
||||
/// The list of filters offered in the dropdown.
|
||||
pub filters: Vec<Filter>,
|
||||
/// The index of the filter the dialog starts on.
|
||||
pub current: Option<usize>,
|
||||
/// Optional cancellation token allowing the caller to cancel a pending save request.
|
||||
pub cancel: Option<CancelToken>,
|
||||
/// Optional timeout after which a request waiting for a response is considered stalled.
|
||||
pub timeout: Option<Duration>,
|
||||
}
|
||||
|
||||
/// What the portal dialog returned: the path, as typed, and the filter chosen in the dropdown.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Saved {
|
||||
/// The filesystem path chosen in the dialog.
|
||||
pub path: PathBuf,
|
||||
/// The filter chosen in the dropdown, if reported by the portal: `(label, extensions)`.
|
||||
pub filter: Option<Filter>,
|
||||
}
|
||||
|
||||
/// The portal's parent window identifier for `window`: `x11:<xid>` on X11, empty elsewhere.
|
||||
///
|
||||
/// On Wayland, exporting an xdg-foreign handle requires `unsafe` code forbidden by workspace rules
|
||||
/// (`#![forbid(unsafe_code)]`, Rust Rule 1), so Wayland dialogs remain unparented, matching
|
||||
/// PhotoCraft and VectorCraft.
|
||||
pub fn parent_id(window: Option<eframe::wgpu::rwh::RawWindowHandle>) -> String {
|
||||
use eframe::wgpu::rwh::RawWindowHandle;
|
||||
match window {
|
||||
Some(RawWindowHandle::Xlib(h)) => format!("x11:{:x}", h.window),
|
||||
Some(RawWindowHandle::Xcb(h)) => format!("x11:{:x}", h.window.get()),
|
||||
_ => String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts a filter tuple into the portal's wire format: label and a list of `(0, "*.ext")` glob pairs.
|
||||
fn wire(filter: &Filter) -> (String, Vec<(u32, String)>) {
|
||||
let globs = filter.1.iter().map(|e| (0u32, if e.is_empty() || e == "*" { "*".to_string() } else { format!("*.{e}") })).collect();
|
||||
(filter.0.clone(), globs)
|
||||
}
|
||||
|
||||
/// The `SaveFile` options dictionary for `req`, answering on `token`.
|
||||
fn options<'a>(req: &'a SaveRequest, token: &'a str) -> HashMap<&'static str, Value<'a>> {
|
||||
let mut o: HashMap<&'static str, Value<'a>> = HashMap::from([("handle_token", Value::from(token)), ("modal", Value::from(true))]);
|
||||
if let Some(name) = &req.name {
|
||||
o.insert("current_name", Value::from(name.as_str()));
|
||||
}
|
||||
if let Some(folder) = &req.folder {
|
||||
// A byte string with its terminating NUL, as the portal specifies.
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
let mut bytes = folder.as_os_str().as_bytes().to_vec();
|
||||
bytes.push(0);
|
||||
o.insert("current_folder", Value::from(bytes));
|
||||
}
|
||||
if !req.filters.is_empty() {
|
||||
let wired = req.filters.iter().map(wire).collect::<Vec<_>>();
|
||||
o.insert("filters", Value::from(wired));
|
||||
}
|
||||
if let Some(f) = req.current.and_then(|i| req.filters.get(i)).or_else(|| req.filters.first()) {
|
||||
o.insert("current_filter", Value::from(wire(f)));
|
||||
}
|
||||
o
|
||||
}
|
||||
|
||||
/// Reads the portal's `Response`: code 0 with the first `uris` entry. 1 is Cancel, and 2 a dialog
|
||||
/// closed some other way (e.g. Esc in GNOME): no file either. When code 2 arrives quicker than
|
||||
/// [`TOO_QUICK`], the portal failed to show its dialog (#2999) and an error is returned so the
|
||||
/// caller can fall back.
|
||||
fn answer(code: u32, results: &HashMap<String, OwnedValue>, elapsed: Duration) -> Result<Option<Saved>, String> {
|
||||
match code {
|
||||
0 => {}
|
||||
1 => return Ok(None),
|
||||
2 if elapsed < TOO_QUICK => return Err("the save dialog closed at once".to_string()),
|
||||
2 => return Ok(None),
|
||||
_ => return Err(format!("the save dialog failed (portal response {code})")),
|
||||
}
|
||||
let uris: Vec<String> = results
|
||||
.get("uris")
|
||||
.ok_or_else(|| "no file in the portal's answer".to_string())?
|
||||
.try_clone()
|
||||
.map_err(|e| e.to_string())?
|
||||
.try_into()
|
||||
.map_err(|e: zbus::zvariant::Error| e.to_string())?;
|
||||
let uri = uris.first().ok_or_else(|| "no file in the portal's answer".to_string())?;
|
||||
let path = file_uri_path(uri).ok_or_else(|| format!("not a local file: {uri}"))?;
|
||||
let filter = results.get("current_filter").and_then(|v| {
|
||||
let val = v.try_clone().ok()?;
|
||||
if let Ok((label, globs)) = <(String, Vec<(u32, String)>)>::try_from(val.clone()) {
|
||||
let mut exts = Vec::new();
|
||||
for (_, g) in globs {
|
||||
let s = g.trim_start_matches('*').trim_start_matches('.');
|
||||
if !s.is_empty() && s != "*" {
|
||||
exts.push(s.to_ascii_lowercase());
|
||||
}
|
||||
}
|
||||
if exts.is_empty() {
|
||||
exts.extend(extract_exts_from_label(&label));
|
||||
}
|
||||
Some((label, exts))
|
||||
} else if let Ok((label, exts)) = <(String, Vec<String>)>::try_from(val.clone()) {
|
||||
Some((label, exts.into_iter().map(|s| s.to_ascii_lowercase()).collect()))
|
||||
} else if let Ok(label) = String::try_from(val) {
|
||||
let exts = extract_exts_from_label(&label);
|
||||
Some((label, exts))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
});
|
||||
Ok(Some(Saved { path, filter }))
|
||||
}
|
||||
|
||||
/// Extracts file extensions from a filter label such as `"PDF (*.pdf)"` or `"*.pdf"`.
|
||||
fn extract_exts_from_label(label: &str) -> Vec<String> {
|
||||
let text = if let Some(inside) = label.split('(').nth(1).and_then(|s| s.split(')').next()) { inside } else { label };
|
||||
text.split(|c: char| c == ';' || c == ',' || c.is_whitespace())
|
||||
.filter_map(|part| {
|
||||
let s = part.trim().trim_start_matches('*').trim_start_matches('.');
|
||||
if s.is_empty() || s == "*" || s.contains('/') || s.contains('\\') { None } else { Some(s.to_ascii_lowercase()) }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Converts a `file://` URI from the portal into a local `PathBuf`.
|
||||
/// Returns `None` for non-local URIs or invalid percent-encoding.
|
||||
pub fn file_uri_path(uri: &str) -> Option<PathBuf> {
|
||||
let rest = uri.strip_prefix("file://")?;
|
||||
// Only local files: `file:///…` or `file://localhost/…`.
|
||||
let rest = rest.strip_prefix("localhost").unwrap_or(rest);
|
||||
if !rest.starts_with('/') {
|
||||
return None;
|
||||
}
|
||||
let bytes = rest.as_bytes();
|
||||
let mut out = Vec::with_capacity(bytes.len());
|
||||
let mut i = 0;
|
||||
while i < bytes.len() {
|
||||
if bytes.get(i) == Some(&b'%') {
|
||||
let hex = bytes.get(i + 1..i + 3).and_then(|h| std::str::from_utf8(h).ok()).and_then(|h| u8::from_str_radix(h, 16).ok())?;
|
||||
out.push(hex);
|
||||
i = i.saturating_add(3);
|
||||
} else if let Some(&b) = bytes.get(i) {
|
||||
out.push(b);
|
||||
i = i.saturating_add(1);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
Some(PathBuf::from(std::ffi::OsString::from_vec(out)))
|
||||
}
|
||||
|
||||
/// Returns the index of the chosen filter in `filters` by matching the picked index, or the first filter
|
||||
/// if only one was offered.
|
||||
fn chosen_type(filters: &[Filter], picked: Option<usize>) -> Option<usize> {
|
||||
match picked {
|
||||
Some(i) if i < filters.len() => Some(i),
|
||||
None if filters.len() == 1 => Some(0),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns `path` with the extension of the file type picked in the save dialog (`chosen`),
|
||||
/// where the dialog left the suggested name's extension alone (#6180).
|
||||
///
|
||||
/// The GTK file chooser keeps the typed name when another type is picked. Only a name that
|
||||
/// still has the extension the dialog opened with (`opened_with`, e.g. `Document1.docx` with
|
||||
/// PDF picked) or none gets the type's extension, as PolyMeilex/rfd#341 does. An extension the
|
||||
/// user explicitly typed that WordCraft saves (e.g. `art.txt` with PDF untouched) is kept,
|
||||
/// and so does one of the type's own extensions. Any extension that WordCraft does not save
|
||||
/// (e.g. `scan.2024`) is treated as part of the stem, and the type's extension is added.
|
||||
pub fn with_chosen_type(path: &Path, opened_with: Option<&str>, chosen: &[String]) -> PathBuf {
|
||||
let Some(first) = chosen.first() else { return path.to_path_buf() };
|
||||
let ext = path.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase);
|
||||
let opened_ext = opened_with
|
||||
.and_then(|n| Path::new(n).extension())
|
||||
.and_then(|e| e.to_str())
|
||||
.map(str::to_ascii_lowercase)
|
||||
.filter(|e| wordcraft_engine::io::SAVE_EXTS.contains(&e.as_str()));
|
||||
match ext {
|
||||
Some(ext) if chosen.contains(&ext) => path.to_path_buf(),
|
||||
Some(ext) if opened_ext.as_ref() == Some(&ext) => path.with_extension(first),
|
||||
Some(ext) if wordcraft_engine::io::SAVE_EXTS.contains(&ext.as_str()) => path.to_path_buf(),
|
||||
_ => {
|
||||
let mut name = path.as_os_str().to_owned();
|
||||
name.push(".");
|
||||
name.push(first);
|
||||
PathBuf::from(name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns true if `path` exists as a file, directory, or symlink on disk.
|
||||
fn entry_exists(path: &Path) -> bool {
|
||||
match path.symlink_metadata() {
|
||||
Ok(_) => true,
|
||||
Err(e) => e.kind() != std::io::ErrorKind::NotFound,
|
||||
}
|
||||
}
|
||||
|
||||
/// Closes the active portal request handle by calling `org.freedesktop.portal.Request.Close`.
|
||||
pub fn close_request(conn: &zbus::blocking::Connection, portal: Option<&str>, handle: &OwnedObjectPath) {
|
||||
const DESKTOP: &str = "org.freedesktop.portal.Desktop";
|
||||
const REQUEST: &str = "org.freedesktop.portal.Request";
|
||||
let dest = portal.unwrap_or(DESKTOP);
|
||||
if let Ok(proxy) = Proxy::new(conn, dest, handle.as_str(), REQUEST) {
|
||||
let _ = proxy.call_method("Close", &());
|
||||
}
|
||||
}
|
||||
|
||||
/// RAII guard that closes an open portal request handle if dropped before being disarmed.
|
||||
struct RequestGuard<'a> {
|
||||
conn: &'a zbus::blocking::Connection,
|
||||
portal: Option<String>,
|
||||
handle: Option<OwnedObjectPath>,
|
||||
}
|
||||
|
||||
impl<'a> RequestGuard<'a> {
|
||||
/// Creates a new guard for the given request `handle`.
|
||||
fn new(conn: &'a zbus::blocking::Connection, portal: Option<String>, handle: OwnedObjectPath) -> Self {
|
||||
Self { conn, portal, handle: Some(handle) }
|
||||
}
|
||||
|
||||
/// Disarms the guard when a response has been successfully received, preventing `Close` from being called on drop.
|
||||
fn disarm(&mut self) {
|
||||
self.handle = None;
|
||||
}
|
||||
|
||||
/// Returns a reference to the request handle, if still active.
|
||||
fn handle(&self) -> Option<&OwnedObjectPath> {
|
||||
self.handle.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Drop for RequestGuard<'a> {
|
||||
/// Closes the active portal request handle when dropped unless disarmed.
|
||||
fn drop(&mut self) {
|
||||
if let Some(handle) = self.handle.take() {
|
||||
close_request(self.conn, self.portal.as_deref(), &handle);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Asks the XDG desktop portal on `conn` for the `SaveFile` dialog of `req` and waits for its answer.
|
||||
pub fn save_file(conn: &zbus::blocking::Connection, req: &SaveRequest) -> Result<Option<Saved>, String> {
|
||||
const DESKTOP: &str = "org.freedesktop.portal.Desktop";
|
||||
const REQUEST: &str = "org.freedesktop.portal.Request";
|
||||
static NEXT: AtomicU32 = AtomicU32::new(0);
|
||||
let token = format!("wordcraft_save_{}_{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed));
|
||||
|
||||
// Listen before asking, on every request path: a portal older than version 0.9 ignores
|
||||
// `handle_token` and answers on the request path it returns, and its answer can come before
|
||||
// the call's reply. The stream keeps every `Response` from the time it is registered.
|
||||
let dbus = zbus::blocking::fdo::DBusProxy::new(conn).map_err(|e| e.to_string())?;
|
||||
let rule = zbus::MatchRule::builder()
|
||||
.msg_type(zbus::message::Type::Signal)
|
||||
.sender(DESKTOP)
|
||||
.and_then(|b| b.interface(REQUEST))
|
||||
.and_then(|b| b.member("Response"))
|
||||
.map_err(|e| e.to_string())?
|
||||
.build();
|
||||
dbus.add_match_rule(rule).map_err(|e| e.to_string())?;
|
||||
|
||||
let owner_rule = zbus::MatchRule::builder()
|
||||
.msg_type(zbus::message::Type::Signal)
|
||||
.sender("org.freedesktop.DBus")
|
||||
.and_then(|b| b.interface("org.freedesktop.DBus"))
|
||||
.and_then(|b| b.member("NameOwnerChanged"))
|
||||
.map_err(|e| e.to_string())?
|
||||
.build();
|
||||
dbus.add_match_rule(owner_rule).map_err(|e| e.to_string())?;
|
||||
|
||||
let responses = MessageIterator::from(conn);
|
||||
let chooser = Proxy::new(conn, DESKTOP, "/org/freedesktop/portal/desktop", "org.freedesktop.portal.FileChooser").map_err(|e| e.to_string())?;
|
||||
|
||||
let start = std::time::Instant::now();
|
||||
let call = chooser.call_method("SaveFile", &(req.parent.as_str(), "Save As", options(req, &token))).map_err(|e| e.to_string())?;
|
||||
let handle: OwnedObjectPath = call.body().deserialize().map_err(|e| e.to_string())?;
|
||||
let portal = call.header().sender().map(|s| s.as_str().to_string());
|
||||
|
||||
let mut guard = RequestGuard::new(conn, portal.clone(), handle);
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let _listener = std::thread::Builder::new().name("portal save listener".into()).spawn(move || {
|
||||
for msg in responses.filter_map(Result::ok) {
|
||||
if tx.send(msg).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let reply = loop {
|
||||
if req.cancel.as_ref().is_some_and(CancelToken::is_cancelled) {
|
||||
return Err(ERR_CANCELLED.to_string());
|
||||
}
|
||||
match rx.recv_timeout(Duration::from_millis(100)) {
|
||||
Ok(m) => {
|
||||
let header = m.header();
|
||||
if header.path().map(|p| p.as_str()) == guard.handle().map(|h| h.as_str()) && header.sender().map(|s| s.as_str()) == portal.as_deref()
|
||||
{
|
||||
break Ok(m);
|
||||
}
|
||||
#[allow(clippy::collapsible_if)]
|
||||
if header.interface().map(|i| i.as_str()) == Some("org.freedesktop.DBus")
|
||||
&& header.member().map(|m| m.as_str()) == Some("NameOwnerChanged")
|
||||
{
|
||||
if let Ok((name, old_owner, "")) = m.body().deserialize::<(&str, &str, &str)>() {
|
||||
if (name == DESKTOP || portal.as_deref() == Some(name)) && (portal.is_none() || portal.as_deref() == Some(old_owner)) {
|
||||
break Err("the desktop portal terminated while the save dialog was open".to_string());
|
||||
}
|
||||
if name.starts_with("org.freedesktop.impl.portal.desktop") {
|
||||
break Err("the desktop portal backend terminated while the save dialog was open".to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {
|
||||
if req.timeout.is_some_and(|t| start.elapsed() >= t) {
|
||||
break Err("the save dialog request timed out".to_string());
|
||||
}
|
||||
}
|
||||
Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => {
|
||||
break Err("the save dialog closed without an answer".to_string());
|
||||
}
|
||||
}
|
||||
}?;
|
||||
|
||||
guard.disarm();
|
||||
let elapsed = start.elapsed();
|
||||
let (code, results): (u32, HashMap<String, OwnedValue>) = reply.body().deserialize().map_err(|e| e.to_string())?;
|
||||
answer(code, &results, elapsed)
|
||||
}
|
||||
|
||||
/// Returns true if `path` is located in the XDG document portal (`/run/user/<uid>/doc/…`, or
|
||||
/// `/run/flatpak/doc/…` inside a Flatpak sandbox).
|
||||
fn is_document_portal(path: &Path) -> bool {
|
||||
let s = path.to_string_lossy();
|
||||
((s.starts_with("/run/user/") || s.starts_with("/var/run/user/")) && s.contains("/doc/")) || s.starts_with("/run/flatpak/doc/")
|
||||
}
|
||||
|
||||
/// Error message returned when a pending save request was cancelled by the caller.
|
||||
pub const ERR_CANCELLED: &str = "the save dialog request was cancelled";
|
||||
|
||||
/// Returns true if `err` represents a save request cancelled by the caller (not a cancel in the
|
||||
/// dialog itself, which is `Ok(None)`).
|
||||
pub fn is_cancelled_error(err: &str) -> bool {
|
||||
err == ERR_CANCELLED
|
||||
}
|
||||
|
||||
/// Error message returned when the portal dialog does not report the selected filter and
|
||||
/// the saved filename does not explicitly specify a distinct format.
|
||||
pub const ERR_AMBIGUOUS_FILTER: &str = "the save dialog did not report which file type was picked";
|
||||
|
||||
/// Returns true if `err` represents an ambiguous filter error from the desktop portal.
|
||||
pub fn is_ambiguous_filter_error(err: &str) -> bool {
|
||||
err == ERR_AMBIGUOUS_FILTER
|
||||
}
|
||||
|
||||
/// Finds the index of the filter in `filters` matching `saved_filter`, first by exact label,
|
||||
/// then by unambiguous match against the filter's extensions.
|
||||
fn match_filter(filters: &[Filter], saved_filter: Option<&Filter>) -> Option<usize> {
|
||||
let (label, exts) = saved_filter?;
|
||||
if let Some(pos) = filters.iter().position(|(l, _)| l == label) {
|
||||
return Some(pos);
|
||||
}
|
||||
if !exts.is_empty() {
|
||||
let matching: Vec<usize> = filters
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, (_, f_exts))| exts.iter().any(|e| f_exts.iter().any(|fe| fe.eq_ignore_ascii_case(e))))
|
||||
.map(|(i, _)| i)
|
||||
.collect();
|
||||
if matching.len() == 1 {
|
||||
return matching.first().copied();
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Returns true if the portal did not provide a unique matching filter when multiple filters were offered
|
||||
/// and the user did not explicitly type a filename with a distinct supported format extension.
|
||||
pub fn is_ambiguous_filter(saved: &Saved, req: &SaveRequest) -> bool {
|
||||
if req.filters.len() <= 1 {
|
||||
return false;
|
||||
}
|
||||
if match_filter(&req.filters, saved.filter.as_ref()).is_some() {
|
||||
return false;
|
||||
}
|
||||
let ext = saved.path.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase);
|
||||
let suggested_ext = req
|
||||
.suggested
|
||||
.as_deref()
|
||||
.and_then(|n| Path::new(n).extension())
|
||||
.and_then(|e| e.to_str())
|
||||
.map(str::to_ascii_lowercase)
|
||||
.filter(|e| wordcraft_engine::io::SAVE_EXTS.contains(&e.as_str()));
|
||||
match ext {
|
||||
Some(ext) if wordcraft_engine::io::SAVE_EXTS.contains(&ext.as_str()) => suggested_ext.as_ref() == Some(&ext),
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Save As on Linux and BSDs: the portal's dialog, with the file name given the extension of the
|
||||
/// file type picked in the dropdown. When that changes the name to one that already exists on disk,
|
||||
/// the dialog opens again under the new name, so the portal asks before replacing it (it asked only
|
||||
/// about the typed name).
|
||||
pub fn save_as(conn: &zbus::blocking::Connection, mut req: SaveRequest) -> Result<Option<PathBuf>, String> {
|
||||
loop {
|
||||
let Some(saved) = save_file(conn, &req)? else { return Ok(None) };
|
||||
if is_ambiguous_filter(&saved, &req) {
|
||||
return Err(ERR_AMBIGUOUS_FILTER.to_string());
|
||||
}
|
||||
let picked = match_filter(&req.filters, saved.filter.as_ref());
|
||||
let exts: &[String] = match chosen_type(&req.filters, picked) {
|
||||
Some(i) => req.filters.get(i).map(|(_, e)| e.as_slice()).unwrap_or(&[]),
|
||||
None => &[],
|
||||
};
|
||||
let path = with_chosen_type(&saved.path, req.suggested.as_deref(), exts);
|
||||
let needs_reopen = entry_exists(&path) || (path != saved.path && is_document_portal(&saved.path));
|
||||
if path == saved.path || !needs_reopen {
|
||||
return Ok(Some(path));
|
||||
}
|
||||
req.name = path.file_name().map(|n| n.to_string_lossy().into_owned());
|
||||
req.suggested = req.name.clone();
|
||||
req.folder = path.parent().map(Path::to_path_buf);
|
||||
req.current = picked;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// #6180: the file type picked in the save dialog gives the name its extension where the
|
||||
/// dialog left the one it opened with, and only there.
|
||||
#[test]
|
||||
fn the_picked_file_type_gives_the_name_its_extension() {
|
||||
let exts = |e: &[&str]| e.iter().map(|s| s.to_string()).collect::<Vec<_>>();
|
||||
let (pdf, docx) = (exts(&["pdf"]), exts(&["docx", "docm"]));
|
||||
let opened = Some("Document1.docx");
|
||||
let cases = [
|
||||
// PDF picked, the name as the dialog opened (or renamed, its extension kept).
|
||||
("/docs/Document1.docx", opened, &pdf, "/docs/Document1.pdf"),
|
||||
("/docs/letter.docx", opened, &pdf, "/docs/letter.pdf"),
|
||||
("/docs/LETTER.DOCX", opened, &pdf, "/docs/LETTER.pdf"),
|
||||
// No extension: takes the picked type's extension.
|
||||
("/docs/report", opened, &pdf, "/docs/report.pdf"),
|
||||
// An extension WordCraft doesn't save is part of the name.
|
||||
("/docs/scan.2024", opened, &pdf, "/docs/scan.2024.pdf"),
|
||||
// An opened extension WordCraft doesn't save (e.g. .5 in Report 1.5) is kept as part of the stem.
|
||||
("/docs/Report 1.5", Some("Report 1.5"), &docx, "/docs/Report 1.5.docx"),
|
||||
// Typed, an extension WordCraft saves is the user's: kept, whatever the type says.
|
||||
("/docs/notes.txt", opened, &pdf, "/docs/notes.txt"),
|
||||
("/docs/page.html", opened, &pdf, "/docs/page.html"),
|
||||
("/docs/file.rtf", opened, &pdf, "/docs/file.rtf"),
|
||||
// Already the type's: kept.
|
||||
("/docs/letter.pdf", opened, &pdf, "/docs/letter.pdf"),
|
||||
("/docs/letter.PDF", opened, &pdf, "/docs/letter.PDF"),
|
||||
// The dialog opened on a .dotx template: that is the extension the type replaces.
|
||||
("/docs/memo.dotx", Some("memo.dotx"), &pdf, "/docs/memo.pdf"),
|
||||
("/docs/doc.docx", Some("memo.dotx"), &pdf, "/docs/doc.docx"),
|
||||
// Word document picked for a file named without extension.
|
||||
("/docs/contract", opened, &docx, "/docs/contract.docx"),
|
||||
];
|
||||
for (typed, opened_with, chosen, want) in cases {
|
||||
assert_eq!(
|
||||
with_chosen_type(Path::new(typed), opened_with, chosen),
|
||||
PathBuf::from(want),
|
||||
"failed for typed={typed}, opened_with={opened_with:?}"
|
||||
);
|
||||
}
|
||||
// No type picked: the name as typed is kept.
|
||||
assert_eq!(with_chosen_type(Path::new("/docs/report.docx"), opened, &[]), PathBuf::from("/docs/report.docx"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_uris_become_local_paths() {
|
||||
assert_eq!(file_uri_path("file:///home/me/Document1.docx"), Some(PathBuf::from("/home/me/Document1.docx")));
|
||||
assert_eq!(file_uri_path("file:///home/me/A%20b%C3%A9.pdf"), Some(PathBuf::from("/home/me/A bé.pdf")));
|
||||
assert_eq!(file_uri_path("file://localhost/tmp/x.pdf"), Some(PathBuf::from("/tmp/x.pdf")));
|
||||
assert_eq!(file_uri_path("file:///tmp/a%ZZ.pdf"), None);
|
||||
assert_eq!(file_uri_path("file:///tmp/a%"), None);
|
||||
assert_eq!(file_uri_path("file:///tmp/a%2"), None);
|
||||
assert_eq!(file_uri_path("sftp://host/x.pdf"), None);
|
||||
assert_eq!(file_uri_path("file://host/x.pdf"), None);
|
||||
assert_eq!(file_uri_path("http://example.com/doc.pdf"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn x11_windows_are_named_to_the_portal() {
|
||||
use eframe::wgpu::rwh::{RawWindowHandle, XlibWindowHandle};
|
||||
assert_eq!(parent_id(Some(RawWindowHandle::Xlib(XlibWindowHandle::new(0x3a0000f)))), "x11:3a0000f");
|
||||
assert_eq!(parent_id(None), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn answer_parses_portal_response_or_errors_on_quick_failure() {
|
||||
let mut results = HashMap::new();
|
||||
let uris: Vec<String> = vec!["file:///tmp/doc.docx".to_string()];
|
||||
results.insert("uris".to_string(), OwnedValue::try_from(Value::from(uris)).unwrap());
|
||||
let globs: Vec<(u32, String)> = vec![(0u32, "*.docx".to_string())];
|
||||
let filter: (String, Vec<(u32, String)>) = ("Word Document (*.docx)".to_string(), globs);
|
||||
results.insert("current_filter".to_string(), OwnedValue::try_from(Value::from(filter)).unwrap());
|
||||
|
||||
// Code 0 with filter
|
||||
let ans = answer(0, &results, Duration::from_millis(1000)).unwrap();
|
||||
assert_eq!(
|
||||
ans,
|
||||
Some(Saved { path: PathBuf::from("/tmp/doc.docx"), filter: Some(("Word Document (*.docx)".to_string(), vec!["docx".to_string()])) })
|
||||
);
|
||||
|
||||
// Code 0 without filter
|
||||
let mut results_no_filter = HashMap::new();
|
||||
results_no_filter.insert("uris".to_string(), results.get("uris").unwrap().clone());
|
||||
let ans_no_filter = answer(0, &results_no_filter, Duration::from_millis(1000)).unwrap();
|
||||
assert_eq!(ans_no_filter, Some(Saved { path: PathBuf::from("/tmp/doc.docx"), filter: None }));
|
||||
|
||||
// Code 1 (Cancel)
|
||||
assert_eq!(answer(1, &results, Duration::from_millis(50)).unwrap(), None);
|
||||
|
||||
// Code 2 quick (< TOO_QUICK)
|
||||
assert!(answer(2, &results, Duration::from_millis(100)).is_err());
|
||||
|
||||
// Code 2 slow (>= TOO_QUICK)
|
||||
assert_eq!(answer(2, &results, Duration::from_millis(500)).unwrap(), None);
|
||||
|
||||
// Code 3 (failure)
|
||||
assert!(answer(3, &results, Duration::from_millis(1000)).is_err());
|
||||
}
|
||||
|
||||
struct KillOnDrop(std::process::Child);
|
||||
|
||||
impl Drop for KillOnDrop {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.0.kill();
|
||||
let _ = self.0.wait();
|
||||
}
|
||||
}
|
||||
|
||||
/// Configuration for spawning a mock portal daemon.
|
||||
struct MockPortalConfig {
|
||||
code: u32,
|
||||
delay_reply: Option<Duration>,
|
||||
exit_after_reply: bool,
|
||||
send_response: bool,
|
||||
close_called: Option<std::sync::Arc<std::sync::atomic::AtomicBool>>,
|
||||
emit_backend_owner_loss: bool,
|
||||
}
|
||||
|
||||
impl Default for MockPortalConfig {
|
||||
fn default() -> Self {
|
||||
Self { code: 0, delay_reply: None, exit_after_reply: false, send_response: true, close_called: None, emit_backend_owner_loss: false }
|
||||
}
|
||||
}
|
||||
|
||||
/// Spawns a mock portal daemon that answers `SaveFile` and handles `Close` according to `config`.
|
||||
fn mock_portal_with_config(config: MockPortalConfig) -> Option<(zbus::blocking::Connection, KillOnDrop)> {
|
||||
use std::io::BufRead as _;
|
||||
|
||||
let daemon = std::process::Command::new("dbus-daemon")
|
||||
.args(["--session", "--nofork", "--print-address=1"])
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.spawn()
|
||||
.ok()?;
|
||||
let mut guard = KillOnDrop(daemon);
|
||||
let mut address = String::new();
|
||||
std::io::BufReader::new(guard.0.stdout.take()?).read_line(&mut address).ok()?;
|
||||
let address = address.trim().to_string();
|
||||
let server =
|
||||
zbus::blocking::connection::Builder::address(address.as_str()).ok()?.name("org.freedesktop.portal.Desktop").ok()?.build().ok()?;
|
||||
let incoming = zbus::blocking::MessageIterator::from(&server);
|
||||
let thread_address = address.clone();
|
||||
std::thread::spawn(move || {
|
||||
for msg in incoming {
|
||||
let Ok(msg) = msg else { break };
|
||||
let header = msg.header();
|
||||
if header.message_type() != zbus::message::Type::MethodCall {
|
||||
continue;
|
||||
}
|
||||
if header.member().map(|m| m.as_str()) == Some("Close") {
|
||||
if let Some(flag) = &config.close_called {
|
||||
flag.store(true, Ordering::Relaxed);
|
||||
}
|
||||
let _ = server.reply(&header, &());
|
||||
continue;
|
||||
}
|
||||
if header.member().map(|m| m.as_str()) != Some("SaveFile") {
|
||||
continue;
|
||||
}
|
||||
let Ok((_parent, _title, options)) = msg.body().deserialize::<(String, String, HashMap<String, OwnedValue>)>() else {
|
||||
break;
|
||||
};
|
||||
let text = |key: &str| options.get(key).and_then(|v| String::try_from(v.try_clone().ok()?).ok());
|
||||
let Some(sender) = header.sender().map(|s| s.as_str().trim_start_matches(':').replace('.', "_")) else { break };
|
||||
let token = text("handle_token").unwrap_or_default();
|
||||
let path = format!("/org/freedesktop/portal/desktop/request/{sender}/{token}");
|
||||
let Ok(handle) = OwnedObjectPath::try_from(path.as_str()) else { break };
|
||||
|
||||
if config.exit_after_reply {
|
||||
let _ = server.reply(&header, &handle);
|
||||
drop(server);
|
||||
break;
|
||||
}
|
||||
|
||||
if config.emit_backend_owner_loss {
|
||||
let _ = server.reply(&header, &handle);
|
||||
let addr = thread_address.clone();
|
||||
std::thread::spawn(move || {
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
if let Ok(backend) = zbus::blocking::connection::Builder::address(addr.as_str())
|
||||
.and_then(|b| b.name("org.freedesktop.impl.portal.desktop.gtk"))
|
||||
.and_then(|b| b.build())
|
||||
{
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
drop(backend);
|
||||
}
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
if config.send_response {
|
||||
let to = header.sender().cloned().map(zbus::names::BusName::from);
|
||||
let results: HashMap<&str, Value<'_>> = HashMap::new();
|
||||
let _ = server.emit_signal(to, path.as_str(), "org.freedesktop.portal.Request", "Response", &(config.code, &results));
|
||||
}
|
||||
|
||||
if let Some(delay) = config.delay_reply {
|
||||
std::thread::sleep(delay);
|
||||
}
|
||||
if server.reply(&header, &handle).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
let client = zbus::blocking::connection::Builder::address(address.as_str()).ok()?.build().ok()?;
|
||||
Some((client, guard))
|
||||
}
|
||||
|
||||
/// Spawns a mock portal daemon that answers `SaveFile`.
|
||||
/// If `delay_reply` is set, it emits the Response signal immediately and delays the method
|
||||
/// reply by that duration. If `exit_after_reply` is set, it replies to `SaveFile` and exits
|
||||
/// without sending a `Response`.
|
||||
fn mock_portal(code: u32, delay_reply: Option<Duration>, exit_after_reply: bool) -> Option<(zbus::blocking::Connection, KillOnDrop)> {
|
||||
mock_portal_with_config(MockPortalConfig {
|
||||
code,
|
||||
delay_reply,
|
||||
exit_after_reply,
|
||||
send_response: true,
|
||||
close_called: None,
|
||||
emit_backend_owner_loss: false,
|
||||
})
|
||||
}
|
||||
|
||||
/// A delayed SaveFile method reply with an already-queued response code 2 measures elapsed time
|
||||
/// from before calling SaveFile, so it is treated as a user cancellation rather than a quick
|
||||
/// portal failure that re-opens another dialog.
|
||||
#[test]
|
||||
fn delayed_method_reply_with_queued_cancel_is_not_treated_as_quick_failure() {
|
||||
let Some((client, _daemon)) = mock_portal(2, Some(Duration::from_millis(350)), false) else {
|
||||
eprintln!("no dbus-daemon: skipped");
|
||||
return;
|
||||
};
|
||||
let req = SaveRequest {
|
||||
name: Some("test.docx".to_string()),
|
||||
suggested: Some("test.docx".to_string()),
|
||||
filters: vec![("Word Document (*.docx)".to_string(), vec!["docx".to_string()])],
|
||||
..Default::default()
|
||||
};
|
||||
let res = save_file(&client, &req);
|
||||
assert_eq!(res, Ok(None));
|
||||
}
|
||||
|
||||
/// If the desktop portal terminates while a save dialog is open (e.g. crashing after replying
|
||||
/// to SaveFile), save_file detects NameOwnerChanged and returns an error immediately.
|
||||
#[test]
|
||||
fn portal_terminating_while_open_returns_error() {
|
||||
let Some((client, _daemon)) = mock_portal(0, None, true) else {
|
||||
eprintln!("no dbus-daemon: skipped");
|
||||
return;
|
||||
};
|
||||
let req = SaveRequest {
|
||||
name: Some("test.docx".to_string()),
|
||||
suggested: Some("test.docx".to_string()),
|
||||
filters: vec![("Word Document (*.docx)".to_string(), vec!["docx".to_string()])],
|
||||
..Default::default()
|
||||
};
|
||||
let res = save_file(&client, &req);
|
||||
assert!(res.is_err(), "portal termination returns an error so rfd fallback runs: got {res:?}");
|
||||
}
|
||||
|
||||
/// If the desktop portal backend implementation (e.g. GTK, GNOME, KDE) terminates while the
|
||||
/// dialog is open, save_file detects NameOwnerChanged on the implementation service and returns
|
||||
/// an error immediately so the rfd fallback can run.
|
||||
#[test]
|
||||
fn portal_backend_terminating_while_open_returns_error() {
|
||||
let Some((client, _daemon)) =
|
||||
mock_portal_with_config(MockPortalConfig { emit_backend_owner_loss: true, send_response: false, ..Default::default() })
|
||||
else {
|
||||
eprintln!("no dbus-daemon: skipped");
|
||||
return;
|
||||
};
|
||||
let req = SaveRequest {
|
||||
name: Some("test.docx".to_string()),
|
||||
suggested: Some("test.docx".to_string()),
|
||||
filters: vec![("Word Document (*.docx)".to_string(), vec!["docx".to_string()])],
|
||||
..Default::default()
|
||||
};
|
||||
let res = save_file(&client, &req);
|
||||
assert!(res.is_err(), "backend termination returns an error so rfd fallback runs: got {res:?}");
|
||||
assert!(res.as_ref().unwrap_err().contains("backend terminated"), "expected backend termination error: got {res:?}");
|
||||
}
|
||||
|
||||
/// When a save request is cancelled via `CancelToken`, save_file aborts waiting for the response,
|
||||
/// calls Close on the portal request object path, and returns a cancellation error immediately.
|
||||
#[test]
|
||||
fn save_file_cancellation_closes_request_and_returns_error() {
|
||||
let close_called = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let Some((client, _daemon)) =
|
||||
mock_portal_with_config(MockPortalConfig { send_response: false, close_called: Some(close_called.clone()), ..Default::default() })
|
||||
else {
|
||||
eprintln!("no dbus-daemon: skipped");
|
||||
return;
|
||||
};
|
||||
let cancel = CancelToken::new();
|
||||
let cancel_thread = cancel.clone();
|
||||
std::thread::spawn(move || {
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
cancel_thread.cancel();
|
||||
});
|
||||
let req = SaveRequest {
|
||||
name: Some("test.docx".to_string()),
|
||||
suggested: Some("test.docx".to_string()),
|
||||
filters: vec![("Word Document (*.docx)".to_string(), vec!["docx".to_string()])],
|
||||
cancel: Some(cancel),
|
||||
..Default::default()
|
||||
};
|
||||
let res = save_file(&client, &req);
|
||||
assert!(res.is_err(), "cancelled request returns error: got {res:?}");
|
||||
assert!(res.as_ref().unwrap_err().contains("cancelled"), "expected cancellation error: got {res:?}");
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
assert!(close_called.load(Ordering::Relaxed), "Close must be called on portal request handle");
|
||||
}
|
||||
|
||||
/// When a save request times out waiting for a stalled portal backend response, save_file aborts,
|
||||
/// calls Close on the portal request object path, and returns a timeout error.
|
||||
#[test]
|
||||
fn save_file_timeout_closes_request_and_returns_error() {
|
||||
let close_called = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let Some((client, _daemon)) =
|
||||
mock_portal_with_config(MockPortalConfig { send_response: false, close_called: Some(close_called.clone()), ..Default::default() })
|
||||
else {
|
||||
eprintln!("no dbus-daemon: skipped");
|
||||
return;
|
||||
};
|
||||
let req = SaveRequest {
|
||||
name: Some("test.docx".to_string()),
|
||||
suggested: Some("test.docx".to_string()),
|
||||
filters: vec![("Word Document (*.docx)".to_string(), vec!["docx".to_string()])],
|
||||
timeout: Some(Duration::from_millis(50)),
|
||||
..Default::default()
|
||||
};
|
||||
let res = save_file(&client, &req);
|
||||
assert!(res.is_err(), "timed out request returns error: got {res:?}");
|
||||
assert!(res.as_ref().unwrap_err().contains("timed out"), "expected timeout error: got {res:?}");
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
assert!(close_called.load(Ordering::Relaxed), "Close must be called on portal request handle");
|
||||
}
|
||||
|
||||
/// `entry_exists` detects existing files and dangling symlinks, distinguishing them from
|
||||
/// absent entries.
|
||||
#[test]
|
||||
fn entry_exists_detects_dangling_symlinks() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let target = dir.path().join("nonexistent_target.txt");
|
||||
let link = dir.path().join("dangling_link.txt");
|
||||
#[cfg(unix)]
|
||||
{
|
||||
std::os::unix::fs::symlink(&target, &link).unwrap();
|
||||
assert!(!link.exists(), "target does not exist so exists() is false");
|
||||
assert!(entry_exists(&link), "symlink entry exists so entry_exists() is true");
|
||||
}
|
||||
assert!(!entry_exists(&target), "nonexistent file does not exist");
|
||||
}
|
||||
|
||||
/// `is_document_portal` identifies paths within the XDG document portal mount, including the
|
||||
/// `/run/flatpak/doc` mount a Flatpak sandbox sees.
|
||||
#[test]
|
||||
fn is_document_portal_detects_portal_fuse_paths() {
|
||||
assert!(is_document_portal(Path::new("/run/user/1000/doc/1234abcd/test.docx")));
|
||||
assert!(is_document_portal(Path::new("/var/run/user/1000/doc/by-app/app/test.docx")));
|
||||
assert!(is_document_portal(Path::new("/run/flatpak/doc/1234abcd/test.docx")));
|
||||
assert!(!is_document_portal(Path::new("/home/user/Documents/test.docx")));
|
||||
assert!(!is_document_portal(Path::new("/tmp/doc/test.docx")));
|
||||
assert!(!is_document_portal(Path::new("/run/flatpak/other/test.docx")));
|
||||
}
|
||||
|
||||
/// When the portal omits `current_filter`, ambiguous saves (unchanged suggested extension or bare name)
|
||||
/// are rejected, while an explicitly typed different format is accepted.
|
||||
#[test]
|
||||
fn ambiguous_filters_require_explicit_format() {
|
||||
let exts = |e: &[&str]| e.iter().map(|s| s.to_string()).collect::<Vec<_>>();
|
||||
let filters = vec![("Word Document (*.docx)".into(), exts(&["docx"])), ("PDF (*.pdf)".into(), exts(&["pdf"]))];
|
||||
let req = SaveRequest { filters: filters.clone(), suggested: Some("Document1.docx".into()), ..Default::default() };
|
||||
|
||||
// Reported filter with matching label is not ambiguous.
|
||||
let with_filter = Saved { path: PathBuf::from("/docs/Document1.docx"), filter: Some(("Word Document (*.docx)".into(), exts(&["docx"]))) };
|
||||
assert_eq!(match_filter(&filters, with_filter.filter.as_ref()), Some(0));
|
||||
assert!(!is_ambiguous_filter(&with_filter, &req));
|
||||
|
||||
// Reported filter with unmatched label but unambiguous extension (e.g. KDE *.pdf) is not ambiguous.
|
||||
let kde_pdf_filter = Saved { path: PathBuf::from("/docs/Document1.docx"), filter: Some(("*.pdf".into(), exts(&["pdf"]))) };
|
||||
assert_eq!(match_filter(&filters, kde_pdf_filter.filter.as_ref()), Some(1));
|
||||
assert!(!is_ambiguous_filter(&kde_pdf_filter, &req));
|
||||
|
||||
// Reported filter with unrecognized extensions and unchanged suggested extension is ambiguous.
|
||||
let unknown_filter = Saved { path: PathBuf::from("/docs/Document1.docx"), filter: Some(("Custom (*.xyz)".into(), exts(&["xyz"]))) };
|
||||
assert_eq!(match_filter(&filters, unknown_filter.filter.as_ref()), None);
|
||||
assert!(is_ambiguous_filter(&unknown_filter, &req));
|
||||
|
||||
// Multiple filters matching same extension is ambiguous when label doesn't match.
|
||||
let duplicate_filters = vec![("Plain Text (*.txt)".into(), exts(&["txt"])), ("Text Document (*.txt)".into(), exts(&["txt"]))];
|
||||
let dup_filter = ("*.txt".to_string(), exts(&["txt"]));
|
||||
assert_eq!(match_filter(&duplicate_filters, Some(&dup_filter)), None);
|
||||
|
||||
// Missing filter with unchanged suggested extension is ambiguous.
|
||||
let unchanged = Saved { path: PathBuf::from("/docs/Document1.docx"), filter: None };
|
||||
assert!(is_ambiguous_filter(&unchanged, &req));
|
||||
|
||||
// Missing filter with bare filename is ambiguous.
|
||||
let bare = Saved { path: PathBuf::from("/docs/Document1"), filter: None };
|
||||
assert!(is_ambiguous_filter(&bare, &req));
|
||||
|
||||
// Missing filter but user explicitly typed a different format is NOT ambiguous.
|
||||
let explicit = Saved { path: PathBuf::from("/docs/Document1.pdf"), filter: None };
|
||||
assert!(!is_ambiguous_filter(&explicit, &req));
|
||||
|
||||
// Single filter offered is never ambiguous even if filter is omitted.
|
||||
let single_req =
|
||||
SaveRequest { filters: vec![("PDF (*.pdf)".into(), exts(&["pdf"]))], suggested: Some("Document1.docx".into()), ..Default::default() };
|
||||
assert!(!is_ambiguous_filter(&unchanged, &single_req));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
//! Where WordCraft keeps its settings and the files beside them: the settings store (with the
|
||||
//! one-time import of the old `ui.json`), the custom dictionary and the user's fonts.
|
||||
//!
|
||||
//! Every path comes from [`wordcraft_control_key::settings_dir`], the one settings-folder rule,
|
||||
//! so `config.toml`, `window.json`, logs, recovery, fonts and templates share a folder. Runs
|
||||
//! without preferences (`WORDCRAFT_NO_PREFS`, agents' test runs) neither read nor write any of it.
|
||||
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use craft::settings::{LegacyFile, LoadReport, Location, OpenOptions, SettingsStore, SharedSettings, Source};
|
||||
use craft::window::restore::Store;
|
||||
use wordcraft_ui_egui::prefs::{Prefs, import_legacy_window, legacy_ui_json};
|
||||
|
||||
/// 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.
|
||||
pub fn enabled() -> bool {
|
||||
crate::launch_profile::current().is_nightly() || std::env::var_os("WORDCRAFT_NO_PREFS").is_none()
|
||||
}
|
||||
|
||||
/// `custom-dictionary.txt` in the settings folder: the words Add to Dictionary kept (#40).
|
||||
pub fn user_dict_path() -> Option<PathBuf> {
|
||||
wordcraft_control_key::settings_dir().map(|b| b.join(wordcraft_engine::Session::USER_DICT_FILE))
|
||||
}
|
||||
|
||||
/// Opens the settings store in the settings folder, or in memory when `enabled` is false or there
|
||||
/// is no folder. On a first run after the move from `ui.json` the old file's settings are
|
||||
/// imported, and its window entry goes into `placement`, which `LegacyFile::parse` cannot reach.
|
||||
pub fn open(enabled: bool, placement: &mut Store) -> (SharedSettings<Prefs>, LoadReport) {
|
||||
open_in(wordcraft_control_key::settings_dir().filter(|_| enabled), placement)
|
||||
}
|
||||
|
||||
/// [`open`] over an explicit settings folder (`None` keeps everything in memory).
|
||||
fn open_in(dir: Option<PathBuf>, placement: &mut Store) -> (SharedSettings<Prefs>, LoadReport) {
|
||||
let mut options = match &dir {
|
||||
Some(dir) => OpenOptions::new(Location::Dir(dir.clone())),
|
||||
None => OpenOptions::new(Location::Memory),
|
||||
};
|
||||
if let Some(dir) = &dir {
|
||||
options = options.legacy(vec![LegacyFile { path: dir.join("ui.json"), parse: legacy_ui_json }]);
|
||||
}
|
||||
let (store, report) = SettingsStore::<Prefs>::open_with(options);
|
||||
if let Source::Legacy(path) = &report.source {
|
||||
import_window(path, placement);
|
||||
}
|
||||
(SharedSettings::new(store), report)
|
||||
}
|
||||
|
||||
/// Moves the window place of the legacy file at `path` into `placement` and saves it.
|
||||
fn import_window(path: &Path, placement: &mut Store) {
|
||||
let mut bytes = Vec::new();
|
||||
if let Err(e) = std::fs::File::open(path).and_then(|f| f.take(LEGACY_LIMIT).read_to_end(&mut bytes)) {
|
||||
log::debug!("preferences: cannot read {} for its window place: {e}", path.display());
|
||||
return;
|
||||
}
|
||||
import_legacy_window(&bytes, placement);
|
||||
if let Err(e) = placement.save() {
|
||||
log::warn!("window place: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Loads the custom dictionary into the spell checker and counts its words as loaded settings:
|
||||
/// the words only the file has are in `Prefs::dictionary`, so the app's preferences list is the
|
||||
/// whole dictionary (#3773). `default_path` is `custom-dictionary.txt` in the settings folder.
|
||||
///
|
||||
/// A bound custom dictionary file (`editing.custom_dictionary`, #5840) that reads is the source of
|
||||
/// truth and the write target. If it is missing or unreadable, the default file is read for
|
||||
/// spelling only and `user_dict_path` stays unset, so later writes never go to the default file
|
||||
/// while the setting still names the custom one. With no custom file, the default is read and written.
|
||||
pub fn load_user_dictionary(session: &mut wordcraft_engine::Session, settings: &SharedSettings<Prefs>, default_path: PathBuf) {
|
||||
session.default_user_dict_path = Some(default_path.clone());
|
||||
let custom = settings.lock().get().editing.custom_dictionary.as_ref().map(PathBuf::from);
|
||||
let mut words = Vec::new();
|
||||
let mut loaded = false;
|
||||
if let Some(p) = &custom {
|
||||
if p.is_file() {
|
||||
match wordcraft_engine::custom_dict::load_custom_dictionary_replacing(p) {
|
||||
Ok(w) => {
|
||||
words = w;
|
||||
session.user_dict_path = Some(p.clone());
|
||||
loaded = true;
|
||||
}
|
||||
Err(e) => log::warn!("custom dictionary: failed to load '{}': {e}", p.display()),
|
||||
}
|
||||
} else {
|
||||
log::warn!("custom dictionary: '{}' is not a regular file", p.display());
|
||||
}
|
||||
}
|
||||
if !loaded {
|
||||
if default_path.is_file() {
|
||||
if custom.is_some() {
|
||||
match wordcraft_engine::custom_dict::load_custom_dictionary_replacing(&default_path) {
|
||||
Ok(w) => words = w,
|
||||
Err(e) => log::warn!("default dictionary: failed to load '{}': {e}", default_path.display()),
|
||||
}
|
||||
} else {
|
||||
words = wordcraft_proof::load_user_dictionary(&default_path);
|
||||
session.user_dict_path = Some(default_path);
|
||||
}
|
||||
} else if custom.is_none() {
|
||||
// A missing default file is not a replacement: keep any words restored from preferences.
|
||||
session.user_dict_path = Some(default_path);
|
||||
}
|
||||
}
|
||||
settings.lock().update(|prefs| {
|
||||
for word in words {
|
||||
if !prefs.dictionary.contains(&word) {
|
||||
prefs.dictionary.push(word);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Fonts the user added (#582) live in `fonts` in the settings folder: load them, and store fonts
|
||||
/// added later there. Runs without preferences neither read nor keep them.
|
||||
pub fn load_user_fonts() {
|
||||
if !enabled() {
|
||||
return;
|
||||
}
|
||||
let Some(dir) = wordcraft_control_key::settings_dir().map(|d| d.join("fonts")) else { return };
|
||||
let (loaded, skipped) = wordcraft_fonts::FontDb::global().load_user_fonts(&dir);
|
||||
if !loaded.is_empty() || !skipped.is_empty() {
|
||||
log::info!("user fonts: {} loaded, {} skipped from {}", loaded.len(), skipped.len(), dir.display());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A store over `dir`, as another WordCraft process opens it.
|
||||
fn process(dir: &Path) -> SharedSettings<Prefs> {
|
||||
open_in(Some(dir.to_path_buf()), &mut Store::in_memory()).0
|
||||
}
|
||||
|
||||
/// The settings the next process loads from `dir`.
|
||||
fn reloaded(dir: &Path) -> Prefs {
|
||||
process(dir).lock().get().clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_loaded_preferences_include_the_words_of_the_dictionary_file() {
|
||||
// A word only `custom-dictionary.txt` has is loaded, not added here: it is in the
|
||||
// preferences' list like the words `ui.json` held, so a save keeps both.
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let dict = dir.path().join("custom-dictionary.txt");
|
||||
std::fs::write(dir.path().join("ui.json"), br#"{"dictionary": ["zqxinjson"]}"#).unwrap();
|
||||
std::fs::write(&dict, "zqxinfile\n").unwrap();
|
||||
let (settings, report) = open_in(Some(dir.path().to_path_buf()), &mut Store::in_memory());
|
||||
assert!(matches!(report.source, Source::Legacy(_)), "ui.json is imported: {:?}", report.source);
|
||||
load_user_dictionary(&mut wordcraft_engine::Session::new(wordcraft_doc::Document::new()), &settings, dict.clone());
|
||||
let words = settings.lock().get().dictionary.clone();
|
||||
for word in ["zqxinjson", "zqxinfile"] {
|
||||
assert!(words.iter().any(|w| w == word), "{word}: {words:?}");
|
||||
}
|
||||
wordcraft_engine::proof::remove_word("zqxinjson");
|
||||
wordcraft_engine::proof::remove_word("zqxinfile");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn autocorrect_entries_and_exceptions_from_both_processes_are_kept() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
// Both processes start from the same file.
|
||||
let first = process(dir.path());
|
||||
first.lock().update(|p| {
|
||||
p.editing.autocorrect.entries = vec![("teh".into(), "the".into())];
|
||||
p.editing.autocorrect.exceptions = vec!["approx.".into()];
|
||||
});
|
||||
first.lock().flush().unwrap();
|
||||
let (a, b) = (process(dir.path()), process(dir.path()));
|
||||
// B adds an entry and an exception and exits first; A adds another entry and removes `approx.`.
|
||||
b.lock().update(|p| {
|
||||
p.editing.autocorrect.entries.push(("teh2".into(), "the".into()));
|
||||
p.editing.autocorrect.exceptions.push("fig.".into());
|
||||
});
|
||||
b.lock().flush().unwrap();
|
||||
a.lock().update(|p| {
|
||||
p.editing.autocorrect.entries.push(("adn".into(), "and".into()));
|
||||
p.editing.autocorrect.exceptions.retain(|e| e != "approx.");
|
||||
});
|
||||
a.lock().flush().unwrap();
|
||||
let ac = reloaded(dir.path()).editing.autocorrect;
|
||||
for from in ["teh", "teh2", "adn"] {
|
||||
assert!(ac.entries.iter().any(|(f, _)| f == from), "{from}: {:?}", ac.entries);
|
||||
}
|
||||
assert_eq!(ac.exceptions, ["fig."], "A's removal stays and B's addition is kept");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_toolbar_reset_by_one_process_stays_reset() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let first = process(dir.path());
|
||||
first.lock().update(|p| p.ribbon.qat = Some(vec!["file.save".into(), "format.bold".into()]));
|
||||
first.lock().flush().unwrap();
|
||||
let (a, b) = (process(dir.path()), process(dir.path()));
|
||||
// B resets the toolbar to the default; A, which left it alone, changes something else.
|
||||
b.lock().update(|p| p.ribbon.qat = None);
|
||||
b.lock().flush().unwrap();
|
||||
a.lock().update(|p| p.dictionary.push("zqxtoolbar".into()));
|
||||
a.lock().flush().unwrap();
|
||||
let now = reloaded(dir.path());
|
||||
assert_eq!(now.ribbon.qat, None, "A's old copy of the toolbar does not bring it back");
|
||||
assert!(now.dictionary.iter().any(|w| w == "zqxtoolbar"), "A's own change is kept");
|
||||
}
|
||||
|
||||
/// The tests that bind a custom dictionary replace the spell checker's words, which every
|
||||
/// test shares: one at a time.
|
||||
static CUSTOM_DICT: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
|
||||
/// #5840: while the setting names a custom file that is missing, the default file is read
|
||||
/// for spelling only. Nothing becomes the write target, so Add to Dictionary never moves the
|
||||
/// person's words into `custom-dictionary.txt` behind the setting's back.
|
||||
#[test]
|
||||
fn a_missing_custom_dictionary_leaves_no_write_target() {
|
||||
let _one = CUSTOM_DICT.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let default = dir.path().join("custom-dictionary.txt");
|
||||
std::fs::write(&default, "zqxfallbackword\n").unwrap();
|
||||
let (settings, _) = open_in(Some(dir.path().to_path_buf()), &mut Store::in_memory());
|
||||
let missing = dir.path().join("gone").join("CUSTOM.DIC");
|
||||
settings.lock().update(|p| p.editing.custom_dictionary = Some(missing.to_string_lossy().into_owned()));
|
||||
let mut session = wordcraft_engine::Session::new(wordcraft_doc::Document::new());
|
||||
load_user_dictionary(&mut session, &settings, default.clone());
|
||||
assert_eq!(session.user_dict_path, None, "no write target while the custom file is missing");
|
||||
assert_eq!(session.default_user_dict_path.as_deref(), Some(default.as_path()));
|
||||
assert!(wordcraft_engine::proof::user_dictionary().iter().any(|w| w == "zqxfallbackword"), "the default file still spells");
|
||||
wordcraft_engine::proof::remove_word("zqxfallbackword");
|
||||
}
|
||||
|
||||
/// #5840: a custom file that is set but missing, with no default file either: nothing is a
|
||||
/// write target (the `custom.is_none()` arm does not claim the default), and nothing panics.
|
||||
#[test]
|
||||
fn a_missing_custom_and_default_dictionary_leave_no_write_target() {
|
||||
let _one = CUSTOM_DICT.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let default = dir.path().join("custom-dictionary.txt");
|
||||
let (settings, _) = open_in(Some(dir.path().to_path_buf()), &mut Store::in_memory());
|
||||
let missing = dir.path().join("gone").join("CUSTOM.DIC");
|
||||
settings.lock().update(|p| p.editing.custom_dictionary = Some(missing.to_string_lossy().into_owned()));
|
||||
let mut session = wordcraft_engine::Session::new(wordcraft_doc::Document::new());
|
||||
load_user_dictionary(&mut session, &settings, default.clone());
|
||||
assert_eq!(session.user_dict_path, None, "no write target while the custom file is missing");
|
||||
assert_eq!(session.default_user_dict_path.as_deref(), Some(default.as_path()));
|
||||
assert_eq!(settings.lock().get().editing.custom_dictionary.as_deref(), Some(&*missing.to_string_lossy()), "the setting is kept");
|
||||
}
|
||||
|
||||
/// #5840: with no custom file set, the default file is the write target, whether or not it
|
||||
/// exists yet; a readable custom file is the write target when it is set.
|
||||
#[test]
|
||||
fn the_write_target_is_the_default_file_unless_a_custom_one_reads() {
|
||||
let _one = CUSTOM_DICT.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let default = dir.path().join("custom-dictionary.txt");
|
||||
let (settings, _) = open_in(Some(dir.path().to_path_buf()), &mut Store::in_memory());
|
||||
let mut session = wordcraft_engine::Session::new(wordcraft_doc::Document::new());
|
||||
load_user_dictionary(&mut session, &settings, default.clone());
|
||||
assert_eq!(session.user_dict_path.as_deref(), Some(default.as_path()), "a missing default file is still the target");
|
||||
|
||||
std::fs::write(&default, "zqxdefaultword\n").unwrap();
|
||||
let mut session = wordcraft_engine::Session::new(wordcraft_doc::Document::new());
|
||||
load_user_dictionary(&mut session, &settings, default.clone());
|
||||
assert_eq!(session.user_dict_path.as_deref(), Some(default.as_path()));
|
||||
|
||||
let custom = dir.path().join("CUSTOM.DIC");
|
||||
std::fs::write(&custom, "zqxcustomword\r\n").unwrap();
|
||||
settings.lock().update(|p| p.editing.custom_dictionary = Some(custom.to_string_lossy().into_owned()));
|
||||
let mut session = wordcraft_engine::Session::new(wordcraft_doc::Document::new());
|
||||
load_user_dictionary(&mut session, &settings, default.clone());
|
||||
assert_eq!(session.user_dict_path.as_deref(), Some(custom.as_path()), "a readable custom file is the target");
|
||||
let words = wordcraft_engine::proof::user_dictionary();
|
||||
assert!(words.iter().any(|w| w == "zqxcustomword") && !words.iter().any(|w| w == "zqxdefaultword"), "{words:?}");
|
||||
wordcraft_engine::proof::remove_word("zqxcustomword");
|
||||
wordcraft_engine::proof::remove_word("zqxdefaultword");
|
||||
}
|
||||
}
|
||||
@@ -1,550 +0,0 @@
|
||||
//! Several WordCraft processes share one `ui.json` (opening a file from the file manager starts
|
||||
//! another). Each reads it at start-up and writes it at exit (and when a change must survive a
|
||||
//! crash, like taking a document off the recent list), so without a merge the process that writes
|
||||
//! last writes back what it loaded and loses the others' changes (#3773).
|
||||
//!
|
||||
//! The policy: when saving, read `ui.json` again as this version reads it ([`as_read`]: a setting
|
||||
//! of the wrong type reads as its default, and keys it doesn't know or reads only to migrate are
|
||||
//! left out), and write it with only what this process changed since it last loaded or saved its
|
||||
//! preferences (`base`). Every other setting keeps what the file holds now, including the absence
|
||||
//! of one another process removed (a shortcut, a task pane's place).
|
||||
//!
|
||||
//! - A setting both changed takes this process's value.
|
||||
//! - Groups of settings (editing options, AutoCorrect's switches, keyboard shortcuts, the ribbon,
|
||||
//! task pane places) merge entry by entry ([`rule`]). Any other object is one setting: the
|
||||
//! window's size and place, or one task pane's place, are never mixed from two processes.
|
||||
//! - Lists of user entries (AutoCorrect entries by the text they replace, its exceptions, removed
|
||||
//! built-in shortcuts, ribbon tabs by name, Quick Access Toolbar commands, caption labels, pens,
|
||||
//! custom dictionary words) merge entry by entry too ([`merge_entries`]): entries either process
|
||||
//! added are kept, entries either process removed stay removed, and an entry both changed takes
|
||||
//! this process's version. A ribbon or toolbar left as it comes counts as its default entries.
|
||||
//! - Recent lists (documents, symbols, colours, fonts) take the entries this process added or used
|
||||
//! again first, then the file's, without duplicates, without the entries this process removed,
|
||||
//! and within each list's limit ([`merge_recent`]).
|
||||
//! - Any other list (the task panes' order, a floating pane's rectangle) is one setting.
|
||||
//!
|
||||
//! What this process changed is found by comparing with `base`, not by recording each change: a
|
||||
//! setting changed and then changed back counts as untouched, so the file's value stays, and a
|
||||
//! recent entry used again without moving (it was already first) counts as not used.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use serde_json::{Map, Value};
|
||||
use wordcraft_engine::ribbon::{DEFAULT_QAT, RibbonLayout};
|
||||
use wordcraft_ui_egui::{MAX_RECENT, MAX_RECENT_FONTS, UiState, colors, dialogs_insert};
|
||||
|
||||
/// Whether two entries of a recent list are the same entry.
|
||||
type Same = fn(&Value, &Value) -> bool;
|
||||
|
||||
/// What tells an entry of a list of user entries from the others. Entries with the same key are
|
||||
/// told apart by their order ([`ids`]).
|
||||
type Key = fn(&Value) -> String;
|
||||
|
||||
/// How a setting this process changed merges with the file's.
|
||||
#[derive(Clone, Copy)]
|
||||
enum Rule {
|
||||
/// A group of settings: each entry on its own.
|
||||
Group,
|
||||
/// A recent list, most recent first: how many entries it keeps, and when two are the same.
|
||||
Recent(usize, Same),
|
||||
/// A list of user entries: each entry on its own.
|
||||
Entries(Key),
|
||||
/// One setting: this process's value.
|
||||
Whole,
|
||||
}
|
||||
|
||||
/// The rule for the setting at `path` (`ui.json`'s keys from the top).
|
||||
fn rule(path: &[&str]) -> Rule {
|
||||
match path {
|
||||
[] | ["editing" | "keyboard" | "ribbon" | "panePlaces"] | ["editing", "markup" | "marks" | "autocorrect"] | ["keyboard", "assigned"] => {
|
||||
Rule::Group
|
||||
}
|
||||
["recent"] => Rule::Recent(MAX_RECENT, same_entry),
|
||||
["recentSymbols"] => Rule::Recent(dialogs_insert::RECENT_SYMBOLS, same_entry),
|
||||
["recentColors"] => Rule::Recent(colors::RECENT_MAX, same_entry),
|
||||
["recentFonts"] => Rule::Recent(MAX_RECENT_FONTS, same_font),
|
||||
["editing", "autocorrect", "entries"] => Rule::Entries(replaced_text),
|
||||
["ribbon", "tabs"] => Rule::Entries(tab_name),
|
||||
["editing", "autocorrect", "removed" | "exceptions" | "exceptionsRemoved" | "initialCapsExceptions"]
|
||||
| ["keyboard", "removed"]
|
||||
| ["ribbon", "qat"]
|
||||
| ["captionLabels" | "inkPens" | "dictionary"] => Rule::Entries(whole_entry),
|
||||
_ => Rule::Whole,
|
||||
}
|
||||
}
|
||||
|
||||
/// What a setting saved only when it isn't its default stands for when it is missing: the
|
||||
/// default ribbon tabs and Quick Access Toolbar, so that two processes customizing them from the
|
||||
/// default merge entry by entry.
|
||||
fn when_missing(path: &[&str]) -> Option<Value> {
|
||||
match path {
|
||||
["ribbon", "tabs"] => serde_json::to_value(RibbonLayout::default().tabs()).ok(),
|
||||
["ribbon", "qat"] => serde_json::to_value(DEFAULT_QAT).ok(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Entries saved alike (colours are saved normalised, `colors::push_recent`).
|
||||
fn same_entry(a: &Value, b: &Value) -> bool {
|
||||
a == b
|
||||
}
|
||||
|
||||
/// Font names ignoring case, as `push_recent_font` compares them.
|
||||
fn same_font(a: &Value, b: &Value) -> bool {
|
||||
match (a.as_str(), b.as_str()) {
|
||||
(Some(a), Some(b)) => a.to_lowercase() == b.to_lowercase(),
|
||||
_ => a == b,
|
||||
}
|
||||
}
|
||||
|
||||
/// The entry as saved.
|
||||
fn whole_entry(v: &Value) -> String {
|
||||
v.to_string()
|
||||
}
|
||||
|
||||
/// An AutoCorrect entry `[from, to]` by the text it replaces.
|
||||
fn replaced_text(v: &Value) -> String {
|
||||
v.get(0).unwrap_or(v).to_string()
|
||||
}
|
||||
|
||||
/// A ribbon tab by its name, ignoring case as the ribbon does.
|
||||
fn tab_name(v: &Value) -> String {
|
||||
v.get("name").and_then(Value::as_str).map_or_else(|| v.to_string(), str::to_lowercase)
|
||||
}
|
||||
|
||||
/// `ui.json`'s bytes as this version reads them, saved again: `None` when they aren't
|
||||
/// preferences at all.
|
||||
pub fn as_read(bytes: &[u8]) -> Option<Value> {
|
||||
serde_json::to_value(UiState::from_json(bytes)?).ok()
|
||||
}
|
||||
|
||||
/// The preferences to write: `ours` (this process's, now), with every value it left as it was in
|
||||
/// `base` (what it last loaded or saved) taken from `disk` (what `ui.json` holds now, [`as_read`]).
|
||||
pub fn merge(base: &Value, ours: Value, disk: &Value) -> Value {
|
||||
let fallback = ours.clone();
|
||||
merge_setting(&mut Vec::new(), Some(base), Some(ours), Some(disk)).unwrap_or(fallback)
|
||||
}
|
||||
|
||||
/// One setting, at `path`. `None` for a setting left out (this process removed it, or it left it
|
||||
/// alone and another process removed it).
|
||||
fn merge_setting(path: &mut Vec<String>, base: Option<&Value>, ours: Option<Value>, disk: Option<&Value>) -> Option<Value> {
|
||||
if base == ours.as_ref() {
|
||||
// Unchanged here: whatever the file holds now.
|
||||
return disk.cloned();
|
||||
}
|
||||
let ours = ours?;
|
||||
let keys: Vec<&str> = path.iter().map(String::as_str).collect();
|
||||
Some(match (rule(&keys), ours, base, disk) {
|
||||
(Rule::Group, Value::Object(ours), Some(Value::Object(base)), Some(Value::Object(disk))) => {
|
||||
Value::Object(merge_group(path, base, ours, disk))
|
||||
}
|
||||
(Rule::Recent(cap, same), Value::Array(ours), Some(Value::Array(base)), Some(Value::Array(disk))) => {
|
||||
Value::Array(merge_recent(base, ours, disk, cap, same))
|
||||
}
|
||||
(Rule::Entries(key), Value::Array(ours), Some(Value::Array(base)), Some(Value::Array(disk))) => {
|
||||
Value::Array(merge_entries(base, &ours, disk, key))
|
||||
}
|
||||
(_, ours, ..) => ours,
|
||||
})
|
||||
}
|
||||
|
||||
/// A group of settings, entry by entry: this process's entries in their order, then those only
|
||||
/// the file or `base` has.
|
||||
fn merge_group(path: &mut Vec<String>, base: &Map<String, Value>, mut ours: Map<String, Value>, disk: &Map<String, Value>) -> Map<String, Value> {
|
||||
let mut names: Vec<String> = ours.keys().cloned().collect();
|
||||
let mut seen: HashSet<String> = names.iter().cloned().collect();
|
||||
for k in disk.keys().chain(base.keys()) {
|
||||
if seen.insert(k.clone()) {
|
||||
names.push(k.clone());
|
||||
}
|
||||
}
|
||||
let mut merged = Map::new();
|
||||
for k in names {
|
||||
path.push(k.clone());
|
||||
let keys: Vec<&str> = path.iter().map(String::as_str).collect();
|
||||
let missing = when_missing(&keys);
|
||||
let base_v = base.get(&k).cloned().or_else(|| missing.clone());
|
||||
let disk_v = disk.get(&k).cloned().or_else(|| missing.clone());
|
||||
let ours_v = ours.remove(&k).or_else(|| missing.clone());
|
||||
let v = merge_setting(path, base_v.as_ref(), ours_v, disk_v.as_ref());
|
||||
path.pop();
|
||||
// A setting saved only when it isn't its default is left out when it is.
|
||||
if let Some(v) = v.filter(|v| Some(v) != missing.as_ref()) {
|
||||
merged.insert(k, v);
|
||||
}
|
||||
}
|
||||
merged
|
||||
}
|
||||
|
||||
/// A list entry: its key, and how many entries before it have the same key.
|
||||
type Id = (String, usize);
|
||||
|
||||
/// The entries of `list` told apart by `key`, in order.
|
||||
fn ids(list: &[Value], key: Key) -> Vec<Id> {
|
||||
let mut seen: HashMap<String, usize> = HashMap::new();
|
||||
list.iter()
|
||||
.map(|v| {
|
||||
let k = key(v);
|
||||
let n = seen.entry(k.clone()).or_default();
|
||||
*n += 1;
|
||||
(k, *n - 1)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A list of user entries, entry by entry. An entry either process added is kept, one either
|
||||
/// removed stays removed, and one this process changed takes its version (else the file's). The
|
||||
/// order is this process's if it reordered the entries it loaded, else the file's; an entry only
|
||||
/// the other list has goes after the entry it follows there.
|
||||
fn merge_entries(base: &[Value], ours: &[Value], disk: &[Value], key: Key) -> Vec<Value> {
|
||||
let (base_ids, ours_ids, disk_ids) = (ids(base, key), ids(ours, key), ids(disk, key));
|
||||
let index = |ids: &[Id], list: &[Value]| -> HashMap<Id, Value> { ids.iter().cloned().zip(list.iter().cloned()).collect() };
|
||||
let (b, o, d) = (index(&base_ids, base), index(&ours_ids, ours), index(&disk_ids, disk));
|
||||
let value = |id: &Id| -> Option<&Value> {
|
||||
match (b.get(id), o.get(id), d.get(id)) {
|
||||
// Left alone here: the file's, or gone if the other process removed it.
|
||||
(Some(b), Some(o), d) if b == o => d,
|
||||
// Added or changed here.
|
||||
(_, Some(o), _) => Some(o),
|
||||
// Removed here.
|
||||
(Some(_), None, _) => None,
|
||||
// Added there.
|
||||
(None, None, d) => d,
|
||||
}
|
||||
};
|
||||
let common = |ids: &[Id], other: &HashMap<Id, Value>| -> Vec<Id> { ids.iter().filter(|id| other.contains_key(*id)).cloned().collect() };
|
||||
let reordered = common(&ours_ids, &b) != common(&base_ids, &o);
|
||||
let (first, second) = if reordered { (&ours_ids, &disk_ids) } else { (&disk_ids, &ours_ids) };
|
||||
let in_first: HashSet<&Id> = first.iter().collect();
|
||||
let kept: HashSet<&Id> = first.iter().filter(|id| value(id).is_some()).collect();
|
||||
// Entries only `second` has, by the kept entry they follow there (`None`: at the start).
|
||||
let mut after: HashMap<Option<&Id>, Vec<&Id>> = HashMap::new();
|
||||
let mut anchor = None;
|
||||
for id in second {
|
||||
if kept.contains(id) {
|
||||
anchor = Some(id);
|
||||
} else if !in_first.contains(id) && value(id).is_some() {
|
||||
after.entry(anchor).or_default().push(id);
|
||||
}
|
||||
}
|
||||
let mut merged = Vec::new();
|
||||
let mut emit = |ids: &[&Id]| merged.extend(ids.iter().filter_map(|id| value(id).cloned()));
|
||||
emit(after.get(&None).map_or(&[], Vec::as_slice));
|
||||
for id in first.iter().filter(|id| kept.contains(id)) {
|
||||
emit(&[id]);
|
||||
emit(after.get(&Some(id)).map_or(&[], Vec::as_slice));
|
||||
}
|
||||
merged
|
||||
}
|
||||
|
||||
/// The entries this process put at the front of `ours` ([`touched_len`]), then `disk`'s, leaving
|
||||
/// out what this process removed (in `base` but no longer in `ours`), without duplicates and at
|
||||
/// most `cap` entries. Entries are told apart by `same`.
|
||||
fn merge_recent(base: &[Value], ours: Vec<Value>, disk: &[Value], cap: usize, same: Same) -> Vec<Value> {
|
||||
let has = |list: &[Value], v: &Value| list.iter().any(|x| same(x, v));
|
||||
let removed = |v: &Value| has(base, v) && !has(&ours, v);
|
||||
let touched = &ours[..touched_len(base, &ours, same)];
|
||||
let mut merged: Vec<Value> = Vec::new();
|
||||
for v in touched.iter().cloned().chain(disk.iter().filter(|v| !removed(v)).cloned()) {
|
||||
if merged.len() == cap {
|
||||
break;
|
||||
}
|
||||
if !has(&merged, &v) {
|
||||
merged.push(v);
|
||||
}
|
||||
}
|
||||
merged
|
||||
}
|
||||
|
||||
/// How many of `ours`'s first entries this process added or used again. Each use moves an entry
|
||||
/// to the front of a recent list, so what it left alone is a tail of `ours` in `base`'s order: the
|
||||
/// longest such tail is untouched, and everything before it (new entries, and entries that moved
|
||||
/// ahead of one loaded before them) was touched. A use that leaves the order as it was loaded
|
||||
/// (the first entry used again) can't be told from no use, and merges as none.
|
||||
fn touched_len(base: &[Value], ours: &[Value], same: Same) -> usize {
|
||||
let mut end = base.len();
|
||||
for (i, v) in ours.iter().enumerate().rev() {
|
||||
match base[..end].iter().rposition(|b| same(b, v)) {
|
||||
Some(at) => end = at,
|
||||
None => return i + 1,
|
||||
}
|
||||
}
|
||||
0
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::{Value, json};
|
||||
use wordcraft_ui_egui::UiState;
|
||||
|
||||
use super::{as_read, merge};
|
||||
|
||||
/// The preferences a process holds after loading a `ui.json` with `settings` (every other
|
||||
/// setting at its default), as it saves them.
|
||||
fn prefs(settings: Value) -> Value {
|
||||
as_read(&serde_json::to_vec(&settings).unwrap()).unwrap()
|
||||
}
|
||||
|
||||
/// What the next process loads from the merged preferences.
|
||||
fn reloaded(merged: &Value) -> UiState {
|
||||
UiState::from_json(&serde_json::to_vec(merged).unwrap()).unwrap()
|
||||
}
|
||||
|
||||
/// `ui.json` after B and then A, which both loaded `loaded`, save `b` and `a`.
|
||||
fn b_then_a(loaded: &Value, b: Value, a: Value) -> Value {
|
||||
let after_b = merge(loaded, b, loaded);
|
||||
merge(loaded, a, &after_b)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_processes_keep_each_others_changes() {
|
||||
// #3773: A and B both start from the same file.
|
||||
let loaded =
|
||||
json!({"theme": "light", "author": "Ann", "recent": ["a.docx", "b.docx"], "editing": {"smartQuotes": true, "autoCapitalize": true}});
|
||||
// B changes the theme and opens c.docx, then exits first.
|
||||
let b = json!({"theme": "dark", "author": "Ann", "recent": ["c.docx", "a.docx", "b.docx"], "editing": {"smartQuotes": false, "autoCapitalize": true}});
|
||||
// A changes the author name and opens d.docx, then exits.
|
||||
let a = json!({"theme": "light", "author": "Bo", "recent": ["d.docx", "a.docx", "b.docx"], "editing": {"smartQuotes": true, "autoCapitalize": false}});
|
||||
assert_eq!(
|
||||
b_then_a(&loaded, b, a),
|
||||
json!({"theme": "dark", "author": "Bo", "recent": ["d.docx", "c.docx", "a.docx", "b.docx"], "editing": {"smartQuotes": false, "autoCapitalize": false}})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_process_that_changed_nothing_writes_the_file_back_as_it_is() {
|
||||
let loaded = json!({"theme": "light", "recent": ["a.docx"]});
|
||||
let disk = json!({"theme": "dark", "recent": ["b.docx", "a.docx"]});
|
||||
assert_eq!(merge(&loaded, loaded.clone(), &disk), disk);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn this_process_wins_a_setting_both_changed() {
|
||||
let loaded = json!({"theme": "light"});
|
||||
assert_eq!(merge(&loaded, json!({"theme": "system"}), &json!({"theme": "dark"})), json!({"theme": "system"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_setting_changed_and_changed_back_counts_as_untouched() {
|
||||
// Changes are found by comparing with what was loaded: A switched to dark and back.
|
||||
let loaded = json!({"theme": "light"});
|
||||
assert_eq!(merge(&loaded, json!({"theme": "light"}), &json!({"theme": "dark"})), json!({"theme": "dark"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_recent_entry_removed_here_stays_removed() {
|
||||
let loaded = json!({"recent": ["a.docx", "b.docx"]});
|
||||
let ours = json!({"recent": ["b.docx"]});
|
||||
let disk = json!({"recent": ["c.docx", "a.docx", "b.docx"]});
|
||||
assert_eq!(merge(&loaded, ours, &disk), json!({"recent": ["c.docx", "b.docx"]}));
|
||||
// Clear Recent clears what the other process had added too only if it was loaded here.
|
||||
assert_eq!(merge(&loaded, json!({"recent": []}), &json!({"recent": ["c.docx", "a.docx", "b.docx"]})), json!({"recent": ["c.docx"]}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_recent_entry_used_again_here_moves_to_the_front() {
|
||||
// Applying a font already in Recently Used Fonts moves it to the front without adding one.
|
||||
let loaded = json!({"recentFonts": ["A", "B"]});
|
||||
assert_eq!(merge(&loaded, json!({"recentFonts": ["B", "A"]}), &loaded), json!({"recentFonts": ["B", "A"]}));
|
||||
// Here C was used again, D opened and A removed; the other process used B again and added E.
|
||||
let loaded = json!({"recent": ["a.docx", "b.docx", "c.docx"]});
|
||||
let ours = json!({"recent": ["d.docx", "c.docx", "b.docx"]});
|
||||
let disk = json!({"recent": ["e.docx", "b.docx", "a.docx", "c.docx"]});
|
||||
assert_eq!(merge(&loaded, ours, &disk), json!({"recent": ["d.docx", "c.docx", "e.docx", "b.docx"]}));
|
||||
// Entries this process only kept, in the order it loaded them, don't override the file's order.
|
||||
let loaded = json!({"recentSymbols": ["x", "y", "z"]});
|
||||
let ours = json!({"recentSymbols": ["w", "x", "z"]});
|
||||
let disk = json!({"recentSymbols": ["z", "x", "y"]});
|
||||
assert_eq!(merge(&loaded, ours, &disk), json!({"recentSymbols": ["w", "z", "x"]}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recent_fonts_are_one_entry_whatever_their_case() {
|
||||
// Recently Used Fonts ignores case (`push_recent_font`): Arial applied here as `arial` and
|
||||
// there as `ARIAL` is one entry, and doesn't push a distinct font out of the ten.
|
||||
let loaded = json!({"recentFonts": ["A", "B", "C", "D", "E", "F", "G", "H", "I", "Arial"]});
|
||||
let ours = json!({"recentFonts": ["arial", "A", "B", "C", "D", "E", "F", "G", "H", "I"]});
|
||||
let disk = json!({"recentFonts": ["ARIAL", "A", "B", "C", "D", "E", "F", "G", "H", "I"]});
|
||||
assert_eq!(merge(&loaded, ours, &disk), json!({"recentFonts": ["arial", "A", "B", "C", "D", "E", "F", "G", "H", "I"]}));
|
||||
// Other lists compare their entries as saved.
|
||||
let loaded = json!({"recent": ["a.docx"]});
|
||||
assert_eq!(merge(&loaded, json!({"recent": ["A.docx", "a.docx"]}), &loaded), json!({"recent": ["A.docx", "a.docx"]}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merged_recent_lists_keep_their_limit() {
|
||||
// Recently Used Fonts keeps ten.
|
||||
let loaded = json!({"recentFonts": ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]});
|
||||
let ours = json!({"recentFonts": ["X", "A", "B", "C", "D", "E", "F", "G", "H", "I"]});
|
||||
let disk = json!({"recentFonts": ["Y", "A", "B", "C", "D", "E", "F", "G", "H", "I"]});
|
||||
assert_eq!(merge(&loaded, ours, &disk), json!({"recentFonts": ["X", "Y", "A", "B", "C", "D", "E", "F", "G", "H"]}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bad_recent_entry_in_the_file_is_not_carried_forward() {
|
||||
// A non-string entry makes the whole list read as empty (`options::lenient` falls back per
|
||||
// setting). Merging it in would keep Recent empty in every later session; instead the
|
||||
// list reads as this version reads it, and the next save heals it.
|
||||
let loaded = prefs(json!({"recent": []}));
|
||||
let ours = prefs(json!({"recent": ["x.docx"]}));
|
||||
let disk = as_read(br#"{"recent": [{"path": "y.docx"}, "z.docx"]}"#).unwrap();
|
||||
let merged = merge(&loaded, ours, &disk);
|
||||
assert_eq!(merged["recent"], json!(["x.docx"]));
|
||||
assert_eq!(loaded_recent(&merged), ["x.docx"]);
|
||||
// Same for recent symbols.
|
||||
let ours = prefs(json!({"recentSymbols": [{"ch": "§", "font": "Arial"}]}));
|
||||
let disk = as_read(r#"{"recentSymbols": [{"ch": "¶", "font": "Arial"}, 7]}"#.as_bytes()).unwrap();
|
||||
assert_eq!(reloaded(&merge(&prefs(json!({})), ours, &disk)).recent_symbols.len(), 1);
|
||||
}
|
||||
|
||||
/// The recent documents the next process loads.
|
||||
fn loaded_recent(merged: &Value) -> Vec<String> {
|
||||
reloaded(merged).recent
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_keys_this_version_writes_are_kept() {
|
||||
// A legacy key read once to migrate, and junk, are not written back, even from the file.
|
||||
let loaded = prefs(json!({"theme": "light"}));
|
||||
let disk = as_read(br#"{"theme": "light", "dark": true, "interfaceSize": 120, "junk": 1}"#).unwrap();
|
||||
let merged = merge(&loaded, loaded.clone(), &disk);
|
||||
for gone in ["dark", "interfaceSize", "junk"] {
|
||||
assert!(merged.get(gone).is_none(), "{gone}");
|
||||
}
|
||||
assert_eq!(merged["theme"], "light");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_another_process_damaged_gives_way_to_ours() {
|
||||
let loaded = json!({"theme": "light", "recent": ["a.docx"]});
|
||||
let ours = json!({"theme": "dark", "recent": ["a.docx"]});
|
||||
// Not preferences at all: everything comes from this process.
|
||||
assert_eq!(as_read(b"\"garbage\""), None);
|
||||
assert_eq!(merge(&loaded, ours.clone(), &json!("garbage")), ours);
|
||||
// A list replaced by something else keeps ours.
|
||||
assert_eq!(merge(&loaded, json!({"recent": ["b.docx", "a.docx"]}), &json!({"recent": 3})), json!({"recent": ["b.docx", "a.docx"]}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn autocorrect_entries_and_exceptions_from_both_processes_are_kept() {
|
||||
let loaded = prefs(json!({"editing": {"autocorrect": {"entries": [["teh", "the"]], "exceptions": ["approx."]}}}));
|
||||
// B adds an entry and an exception; A adds another entry, changes `teh`'s replacement and
|
||||
// removes `approx.`. Each added entry follows the entry it was added after.
|
||||
let b = prefs(json!({"editing": {"autocorrect": {"entries": [["teh", "the"], ["teh2", "the"]], "exceptions": ["approx.", "fig."]}}}));
|
||||
let a = prefs(json!({"editing": {"autocorrect": {"entries": [["teh", "THE"], ["adn", "and"]], "exceptions": []}}}));
|
||||
let ac = reloaded(&b_then_a(&loaded, b, a)).editing.autocorrect;
|
||||
let entries: Vec<(&str, &str)> = ac.entries.iter().map(|(f, t)| (f.as_str(), t.as_str())).collect();
|
||||
assert_eq!(entries, [("teh", "THE"), ("adn", "and"), ("teh2", "the")]);
|
||||
assert_eq!(ac.exceptions, ["fig."]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keyboard_customisations_merge_key_by_key() {
|
||||
let loaded = prefs(json!({"keyboard": {"assigned": {"Mod+Shift+K": "format.bold"}, "removed": []}}));
|
||||
// B takes Ctrl+B off Bold and deletes its own Mod+Shift+K; A takes Ctrl+I off Italic and
|
||||
// assigns Mod+Shift+J.
|
||||
let b = prefs(json!({"keyboard": {"assigned": {}, "removed": ["Mod+B"]}}));
|
||||
let a = prefs(json!({"keyboard": {"assigned": {"Mod+Shift+K": "format.bold", "Mod+Shift+J": "format.italic"}, "removed": ["Mod+I"]}}));
|
||||
let keys = reloaded(&b_then_a(&loaded, b, a)).keyboard;
|
||||
assert_eq!(keys.assigned.into_iter().collect::<Vec<_>>(), [("Mod+Shift+J".to_string(), "format.italic".to_string())]);
|
||||
assert_eq!(keys.removed.into_iter().collect::<Vec<_>>(), ["Mod+B", "Mod+I"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ribbon_changes_from_both_processes_are_kept() {
|
||||
// Both start from the default ribbon. B hides Draw; A adds a custom tab after Home.
|
||||
let loaded = prefs(json!({}));
|
||||
let b = prefs(json!({"ribbon": {"tabs": hide(default_tabs(), "Draw")}}));
|
||||
let mut a_tabs = default_tabs();
|
||||
a_tabs.insert(1, json!({"name": "Mine", "custom": true}));
|
||||
let a = prefs(json!({"ribbon": {"tabs": a_tabs}}));
|
||||
let mut want = hide(default_tabs(), "Draw");
|
||||
want.insert(1, json!({"name": "Mine", "custom": true}));
|
||||
assert_eq!(serde_json::to_value(loaded_ribbon(&b_then_a(&loaded, b, a)).tabs).unwrap(), Value::Array(want));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_toolbar_reset_by_one_process_stays_reset() {
|
||||
// B resets its custom Quick Access Toolbar to the default; A, which left it alone, adds a
|
||||
// custom tab. The toolbar stays the default.
|
||||
let loaded = prefs(json!({"ribbon": {"qat": ["file.save", "format.bold"]}}));
|
||||
let b = prefs(json!({}));
|
||||
let mut a_tabs = default_tabs();
|
||||
a_tabs.push(json!({"name": "Mine", "custom": true}));
|
||||
let a = prefs(json!({"ribbon": {"tabs": a_tabs, "qat": ["file.save", "format.bold"]}}));
|
||||
let merged = b_then_a(&loaded, b, a);
|
||||
assert!(merged["ribbon"].get("qat").is_none(), "{}", merged["ribbon"]);
|
||||
let ribbon = loaded_ribbon(&merged);
|
||||
assert_eq!(ribbon.qat, None);
|
||||
assert!(ribbon.tabs.iter().any(|t| t.name == "Mine"));
|
||||
// Two processes customizing the default toolbar: both commands, Save removed by A gone.
|
||||
let loaded = prefs(json!({}));
|
||||
let b = prefs(json!({"ribbon": {"qat": ["file.save", "edit.undo", "edit.redo", "format.bold"]}}));
|
||||
let a = prefs(json!({"ribbon": {"qat": ["edit.undo", "edit.redo", "format.italic"]}}));
|
||||
assert_eq!(loaded_ribbon(&b_then_a(&loaded, b, a)).qat.unwrap(), ["edit.undo", "edit.redo", "format.italic", "format.bold"]);
|
||||
}
|
||||
|
||||
/// The default ribbon tabs, as saved once the ribbon is customized.
|
||||
fn default_tabs() -> Vec<Value> {
|
||||
serde_json::from_value(serde_json::to_value(wordcraft_engine::RibbonLayout::default().tabs()).unwrap()).unwrap()
|
||||
}
|
||||
|
||||
/// `tabs` with the tab `name` hidden.
|
||||
fn hide(mut tabs: Vec<Value>, name: &str) -> Vec<Value> {
|
||||
for t in &mut tabs {
|
||||
if t["name"] == name {
|
||||
t["hidden"] = json!(true);
|
||||
}
|
||||
}
|
||||
tabs
|
||||
}
|
||||
|
||||
/// The ribbon the next process loads.
|
||||
fn loaded_ribbon(merged: &Value) -> wordcraft_engine::RibbonLayout {
|
||||
reloaded(merged).ribbon
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pane_order_changed_by_the_other_process_is_kept() {
|
||||
// `paneOrder` is saved only when it isn't the default. B reorders; A leaves it alone and
|
||||
// switches to dark.
|
||||
let loaded = prefs(json!({}));
|
||||
let order = json!(["styles", "navigation"]);
|
||||
let b = prefs(json!({"paneOrder": order}));
|
||||
let merged = b_then_a(&loaded, b, prefs(json!({"theme": "dark"})));
|
||||
assert_eq!((&merged["paneOrder"], &merged["theme"]), (&order, &json!("dark")));
|
||||
// B goes back to the default order; A, which loaded B's order and left it, doesn't bring
|
||||
// it back.
|
||||
let loaded = prefs(json!({"paneOrder": order}));
|
||||
let merged = b_then_a(&loaded, prefs(json!({})), prefs(json!({"paneOrder": order, "theme": "dark"})));
|
||||
assert!(merged.get("paneOrder").is_none(), "{merged}");
|
||||
assert_eq!(merged["theme"], "dark");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_window_and_a_pane_place_are_one_setting_each() {
|
||||
// A moved its window and B resized its own: the window is A's, not A's place with B's size.
|
||||
let window = |x: f32, width: f32| json!({"window": {"position": [x, 10.0], "width": width, "height": 600.0, "maximized": false}});
|
||||
let loaded = prefs(window(0.0, 800.0));
|
||||
let merged = b_then_a(&loaded, prefs(window(0.0, 1000.0)), prefs(window(300.0, 800.0)));
|
||||
assert_eq!(merged["window"], prefs(window(300.0, 800.0))["window"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pens_labels_and_dictionary_words_from_both_processes_are_kept() {
|
||||
let pen = |color: &str| json!({"kind": "pen", "color": color, "width": 1.0});
|
||||
let loaded = prefs(json!({"inkPens": [pen("FF0000"), pen("FF0000")], "captionLabels": ["Plate"], "dictionary": ["foo", "bar"]}));
|
||||
// B adds a third red pen, a label and a word; A adds a blue pen, removes `bar` and adds a
|
||||
// label of its own. Identical pens stay apart, by their order.
|
||||
let b = prefs(
|
||||
json!({"inkPens": [pen("FF0000"), pen("FF0000"), pen("FF0000")], "captionLabels": ["Plate", "Chart"], "dictionary": ["foo", "bar", "baz"]}),
|
||||
);
|
||||
let a = prefs(json!({"inkPens": [pen("FF0000"), pen("FF0000"), pen("0000FF")], "captionLabels": ["Plate", "Map"], "dictionary": ["foo"]}));
|
||||
let merged = b_then_a(&loaded, b, a);
|
||||
let ui = reloaded(&merged);
|
||||
let colors: Vec<String> = ui.ink_pens.iter().map(|p| serde_json::to_value(p).unwrap()["color"].as_str().unwrap().to_string()).collect();
|
||||
assert_eq!(colors, ["FF0000", "FF0000", "0000FF", "FF0000"]);
|
||||
assert_eq!(ui.caption_labels, ["Plate", "Map", "Chart"]);
|
||||
assert_eq!(merged["dictionary"], json!(["foo", "baz"]));
|
||||
}
|
||||
}
|
||||
@@ -1,179 +0,0 @@
|
||||
//! Desktop spooler adapter. Discovery and submission never run on the UI thread.
|
||||
#[cfg(any(windows, test))]
|
||||
pub(crate) mod isolated;
|
||||
|
||||
use wordcraft_ui_egui::printing::{Discover, Duplex, Printer, Settings, Submit};
|
||||
|
||||
/// Returns a discovery callback that enumerates spooler printers on a named worker thread and
|
||||
/// sends the list through a channel, keeping spooler calls off the UI thread.
|
||||
///
|
||||
/// The Print panel needs only names and the default, so the list comes from
|
||||
/// `craft_print::printer_queues`, which asks no printer driver anything: on Windows a networked
|
||||
/// printer in power save can hold a driver's capability query for a long time, and the list must
|
||||
/// not wait on it (#5710). Submission still checks the job's options with the driver.
|
||||
pub fn discover() -> Discover {
|
||||
Box::new(|| {
|
||||
let (sender, receiver) = std::sync::mpsc::channel();
|
||||
let _ = std::thread::Builder::new().name("print-discovery".into()).spawn(move || {
|
||||
let printers = craft_print::printer_queues()
|
||||
.into_iter()
|
||||
.map(|printer| Printer { name: printer.name, label: printer.description, default: printer.default })
|
||||
.collect();
|
||||
let _ = sender.send(printers);
|
||||
});
|
||||
receiver
|
||||
})
|
||||
}
|
||||
|
||||
/// A submission worker and how to stop its job: `true` when it will never be sent, `false` when
|
||||
/// it was already being sent.
|
||||
struct Job {
|
||||
worker: std::thread::JoinHandle<()>,
|
||||
cancel: Box<dyn Fn() -> bool + Send>,
|
||||
// Acknowledged helper cancellation permits joining it to reap the process and its input PDF.
|
||||
isolated: bool,
|
||||
}
|
||||
|
||||
// Keep submission workers reachable until normal app shutdown; dropping a JoinHandle would
|
||||
// let process exit end an in-process Windows job or the CUPS hand-off before the spooler has it.
|
||||
static JOBS: std::sync::Mutex<Vec<Job>> = std::sync::Mutex::new(Vec::new());
|
||||
|
||||
fn jobs() -> std::sync::MutexGuard<'static, Vec<Job>> {
|
||||
JOBS.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// Waits for the jobs already being sent, so the spooler has them before the process exits. A
|
||||
/// job still waiting (on a sleeping printer's driver, say: #5710) is cancelled instead, so it is
|
||||
/// never sent and quitting doesn't wait on the driver.
|
||||
pub fn finish_pending_jobs() {
|
||||
let pending = std::mem::take(&mut *jobs());
|
||||
// Cancel them all first: a job left waiting while another is joined could start sending.
|
||||
let finishing: Vec<_> = pending
|
||||
.into_iter()
|
||||
.filter(|job| {
|
||||
let cancelled = (job.cancel)();
|
||||
job.isolated || !cancelled
|
||||
})
|
||||
.collect();
|
||||
for job in finishing {
|
||||
if job.worker.join().is_err() {
|
||||
log::error!("the print worker stopped unexpectedly during shutdown");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The Print page's Cancel: stops the job being submitted (the Print page submits one at a
|
||||
/// time, the latest) unless it has started reaching the spooler. `true` when it will never be
|
||||
/// sent. A job that has finished sending answers `false`, so its receipt is still shown.
|
||||
pub fn cancel() -> Box<dyn Fn() -> bool> {
|
||||
Box::new(|| jobs().last().is_none_or(|job| (job.cancel)()))
|
||||
}
|
||||
|
||||
/// Submit off the UI thread, isolating Windows drivers while retaining CUPS token cancellation.
|
||||
pub fn submit() -> Submit {
|
||||
Box::new(|bytes, settings: Settings, collate, options| {
|
||||
let (sender, receiver) = std::sync::mpsc::channel();
|
||||
#[cfg(not(windows))]
|
||||
let cancel = craft_print::Cancel::new();
|
||||
#[cfg(windows)]
|
||||
let cancel = isolated::Submission::new();
|
||||
let token = cancel.clone();
|
||||
let worker = std::thread::Builder::new().name("print-submit".into()).spawn(move || {
|
||||
let job = craft_print::Job {
|
||||
printer: Some(settings.printer),
|
||||
copies: settings.copies.clamp(1, 999),
|
||||
collate,
|
||||
duplex: settings.duplex.map(|value| match value {
|
||||
Duplex::LongEdge => craft_print::Duplex::LongEdge,
|
||||
Duplex::ShortEdge => craft_print::Duplex::ShortEdge,
|
||||
Duplex::Off => craft_print::Duplex::Off,
|
||||
}),
|
||||
grayscale: settings.grayscale,
|
||||
grey_pages: false,
|
||||
scaling: craft_print::Scaling::ShrinkToFit,
|
||||
title: "WordCraft document".into(),
|
||||
options,
|
||||
driver_settings: None,
|
||||
};
|
||||
#[cfg(not(windows))]
|
||||
let sent = craft_print::submit_cancellable(&bytes, &job, &mut |_, _| {}, &token).map_err(|error| error.to_string());
|
||||
#[cfg(windows)]
|
||||
let sent = token.submit(&bytes, &job);
|
||||
let _ = sender.send(sent);
|
||||
});
|
||||
if let Ok(worker) = worker {
|
||||
let mut jobs = jobs();
|
||||
jobs.retain(|job| !job.worker.is_finished());
|
||||
jobs.push(Job { worker, cancel: Box::new(move || cancel.cancel()), isolated: cfg!(windows) });
|
||||
}
|
||||
receiver
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
/// A worker that waits until released, then reports that it finished.
|
||||
fn worker() -> (std::thread::JoinHandle<()>, std::sync::mpsc::Sender<()>, std::sync::mpsc::Receiver<()>) {
|
||||
let (release, wait) = std::sync::mpsc::channel();
|
||||
let (completed, completion) = std::sync::mpsc::channel();
|
||||
let worker = std::thread::spawn(move || {
|
||||
let _ = wait.recv();
|
||||
let _ = completed.send(());
|
||||
});
|
||||
(worker, release, completion)
|
||||
}
|
||||
|
||||
/// A cancel action that records when it was asked and answers `stops`.
|
||||
fn asked(stops: bool) -> (Box<dyn Fn() -> bool + Send>, std::sync::Arc<std::sync::atomic::AtomicBool>) {
|
||||
let flag = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let set = flag.clone();
|
||||
let cancel = Box::new(move || {
|
||||
set.store(true, std::sync::atomic::Ordering::SeqCst);
|
||||
stops
|
||||
});
|
||||
(cancel, flag)
|
||||
}
|
||||
|
||||
/// Shutdown waits for a job already being sent, so the spooler has it before the process
|
||||
/// exits, but not for one still waiting on a driver (a sleeping printer, #5710): that one is
|
||||
/// cancelled, so it is never sent, and quitting doesn't hang on it. Every job is cancelled
|
||||
/// before any is waited for, so a waiting job can't start sending meanwhile. The Print page's
|
||||
/// Cancel asks only the latest job. One test, because JOBS is global.
|
||||
#[test]
|
||||
fn shutdown_waits_for_jobs_being_sent_and_cancels_the_rest() {
|
||||
let (sending, release_sending, sent) = worker();
|
||||
let (stuck, release_stuck, _) = worker();
|
||||
let (stop_sending, sending_asked) = asked(false);
|
||||
let (stop_stuck, cancelled) = asked(true);
|
||||
// The job being sent comes first, so a one-at-a-time shutdown would join it before
|
||||
// cancelling the waiting one.
|
||||
*JOBS.lock().unwrap() =
|
||||
vec![Job { worker: sending, cancel: stop_sending, isolated: false }, Job { worker: stuck, cancel: stop_stuck, isolated: false }];
|
||||
// Cancel from the Print page asks the latest job only.
|
||||
assert!(cancel()(), "the latest job was still waiting: never sent");
|
||||
assert!(!sending_asked.load(std::sync::atomic::Ordering::SeqCst), "an earlier job isn't the one being submitted");
|
||||
cancelled.store(false, std::sync::atomic::Ordering::SeqCst);
|
||||
let (finished, shutdown) = std::sync::mpsc::channel();
|
||||
std::thread::spawn(move || {
|
||||
finish_pending_jobs();
|
||||
let _ = finished.send(());
|
||||
});
|
||||
let wait = std::time::Duration::from_millis(200);
|
||||
assert!(shutdown.recv_timeout(wait).is_err(), "shutdown waits for the job being sent");
|
||||
assert!(cancelled.load(std::sync::atomic::Ordering::SeqCst), "the waiting job was cancelled before the wait");
|
||||
release_sending.send(()).unwrap();
|
||||
assert!(shutdown.recv_timeout(std::time::Duration::from_secs(10)).is_ok(), "shutdown doesn't wait for the stuck job");
|
||||
sent.recv().unwrap();
|
||||
assert!(JOBS.lock().unwrap().is_empty(), "shutdown took every job");
|
||||
// A job that has already been sent answers false, so the Print page keeps its receipt.
|
||||
let (done, release_done, finished) = worker();
|
||||
release_done.send(()).unwrap();
|
||||
finished.recv().unwrap();
|
||||
*JOBS.lock().unwrap() = vec![Job { worker: done, cancel: Box::new(|| false), isolated: false }];
|
||||
assert!(!cancel()(), "a sent job isn't reported as cancelled");
|
||||
JOBS.lock().unwrap().clear();
|
||||
// The stuck worker was left behind without blocking shutdown; let it end.
|
||||
release_stuck.send(()).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -1,624 +0,0 @@
|
||||
//! One Windows driver submission per process: a cancelled driver cannot retain another
|
||||
//! job's provider lock. The child acknowledges its Cancel token before it exits.
|
||||
|
||||
use std::{
|
||||
io::{BufRead, BufReader, Read, Write},
|
||||
path::Path,
|
||||
process::{Child, ChildStdin, Command, Stdio},
|
||||
sync::{Arc, Condvar, Mutex},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[cfg(windows)]
|
||||
const FLAG: &str = "--wordcraft-print-worker";
|
||||
const PREFIX: &str = "WORDCRAFT_PRINT:";
|
||||
const MAX_MESSAGE: u64 = 64 * 1024;
|
||||
/// The job's options, and a driver's settings of up to 1 MiB written as hex.
|
||||
const MAX_REQUEST: u64 = MAX_MESSAGE + 2 * 1024 * 1024;
|
||||
const MAX_PDF: u64 = 512 * 1024 * 1024;
|
||||
const CANCELLED: &str = "the print job was cancelled before anything was sent to the printer";
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Duplex {
|
||||
Off,
|
||||
LongEdge,
|
||||
ShortEdge,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct Request {
|
||||
printer: Option<String>,
|
||||
copies: u32,
|
||||
collate: bool,
|
||||
duplex: Option<Duplex>,
|
||||
grayscale: bool,
|
||||
grey_pages: bool,
|
||||
shrink: bool,
|
||||
title: String,
|
||||
options: Vec<(String, String)>,
|
||||
/// The printer the driver's settings were chosen for, and their DEVMODE as hex.
|
||||
driver_settings: Option<(String, String)>,
|
||||
}
|
||||
|
||||
impl Request {
|
||||
/// Preserve all spooler options in a platform-independent wire representation.
|
||||
fn from_job(job: &craft_print::Job) -> Self {
|
||||
Self {
|
||||
printer: job.printer.clone(),
|
||||
copies: job.copies,
|
||||
collate: job.collate,
|
||||
duplex: job.duplex.map(|d| match d {
|
||||
craft_print::Duplex::Off => Duplex::Off,
|
||||
craft_print::Duplex::LongEdge => Duplex::LongEdge,
|
||||
craft_print::Duplex::ShortEdge => Duplex::ShortEdge,
|
||||
}),
|
||||
grayscale: job.grayscale,
|
||||
grey_pages: job.grey_pages,
|
||||
shrink: job.scaling == craft_print::Scaling::ShrinkToFit,
|
||||
title: job.title.clone(),
|
||||
options: job.options.clone(),
|
||||
driver_settings: job.driver_settings.as_ref().map(|settings| (settings.printer().to_owned(), settings.dev_mode().to_hex())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Restore the job without substituting printer defaults or changing copy semantics.
|
||||
fn job(self) -> Result<craft_print::Job, String> {
|
||||
let driver_settings = match self.driver_settings {
|
||||
Some((printer, hex)) => Some(craft_print::DriverSettings::new(printer, craft_print::rgb::DevMode::from_hex(&hex).map_err(error)?)),
|
||||
None => None,
|
||||
};
|
||||
Ok(craft_print::Job {
|
||||
printer: self.printer,
|
||||
copies: self.copies,
|
||||
collate: self.collate,
|
||||
duplex: self.duplex.map(|d| match d {
|
||||
Duplex::Off => craft_print::Duplex::Off,
|
||||
Duplex::LongEdge => craft_print::Duplex::LongEdge,
|
||||
Duplex::ShortEdge => craft_print::Duplex::ShortEdge,
|
||||
}),
|
||||
grayscale: self.grayscale,
|
||||
grey_pages: self.grey_pages,
|
||||
scaling: if self.shrink { craft_print::Scaling::ShrinkToFit } else { craft_print::Scaling::Exact },
|
||||
title: self.title,
|
||||
options: self.options,
|
||||
driver_settings,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Event {
|
||||
Ready,
|
||||
Cancelled,
|
||||
Sending,
|
||||
Done(Result<String, String>),
|
||||
}
|
||||
|
||||
enum State {
|
||||
Starting,
|
||||
Waking(Arc<Mutex<Child>>),
|
||||
Running(ChildStdin),
|
||||
Sending(ChildStdin),
|
||||
Cancelled,
|
||||
Finished,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct Submission(Arc<(Mutex<State>, Condvar)>);
|
||||
|
||||
impl Submission {
|
||||
/// Create one submission whose driver cannot run until the parent grants startup.
|
||||
pub(crate) fn new() -> Self {
|
||||
Self(Arc::new((Mutex::new(State::Starting), Condvar::new())))
|
||||
}
|
||||
|
||||
/// Recover the lifecycle state after poisoning without invoking another driver call.
|
||||
fn state(&self) -> std::sync::MutexGuard<'_, State> {
|
||||
self.0.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// Only an acknowledgement of the child's token can cancel a running helper. A timeout
|
||||
/// is a refusal, never permission to kill a process that may already be sending.
|
||||
pub(crate) fn cancel(&self) -> bool {
|
||||
let mut state = self.state();
|
||||
match &mut *state {
|
||||
State::Starting => {
|
||||
*state = State::Cancelled;
|
||||
return true;
|
||||
}
|
||||
State::Waking(child) => {
|
||||
let _ = child.lock().unwrap_or_else(std::sync::PoisonError::into_inner).kill();
|
||||
*state = State::Cancelled;
|
||||
return true;
|
||||
}
|
||||
State::Cancelled => return true,
|
||||
State::Finished | State::Sending(_) => return false,
|
||||
State::Running(input) => {
|
||||
if input.write_all(b"cancel\n").and_then(|_| input.flush()).is_err() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
let (state, _) = self
|
||||
.0
|
||||
.1
|
||||
.wait_timeout_while(state, Duration::from_secs(1), |s| matches!(s, State::Running(_)))
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
matches!(*state, State::Cancelled)
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
/// Submit through this executable's private helper mode and await its final receipt.
|
||||
pub(crate) fn submit(&self, pdf: &[u8], job: &craft_print::Job) -> Result<String, String> {
|
||||
self.submit_with(pdf, job, |directory| {
|
||||
let mut command = Command::new(std::env::current_exe()?);
|
||||
command.arg(FLAG).arg(directory);
|
||||
Ok(command)
|
||||
})
|
||||
}
|
||||
|
||||
/// Publish a terminal state on every result, waking a cancellation caller awaiting an ack.
|
||||
fn submit_with(&self, pdf: &[u8], job: &craft_print::Job, command: impl FnOnce(&Path) -> std::io::Result<Command>) -> Result<String, String> {
|
||||
let result = self.run(pdf, job, command);
|
||||
let mut state = self.state();
|
||||
if !matches!(*state, State::Cancelled) {
|
||||
*state = State::Finished;
|
||||
}
|
||||
self.0.1.notify_all();
|
||||
if matches!(*state, State::Cancelled) { Err(CANCELLED.into()) } else { result }
|
||||
}
|
||||
|
||||
/// Own the private inputs and child until receipt, acknowledged cancellation or failure.
|
||||
fn run(&self, pdf: &[u8], job: &craft_print::Job, command: impl FnOnce(&Path) -> std::io::Result<Command>) -> Result<String, String> {
|
||||
if matches!(*self.state(), State::Cancelled) {
|
||||
return Err(CANCELLED.into());
|
||||
}
|
||||
if pdf.len() as u64 > MAX_PDF {
|
||||
return Err("the print PDF exceeds the 512 MiB helper limit".into());
|
||||
}
|
||||
let request = serde_json::to_vec(&Request::from_job(job)).map_err(error)?;
|
||||
if request.len() as u64 > MAX_REQUEST {
|
||||
return Err("the print settings exceed the helper message limit".into());
|
||||
}
|
||||
let directory = tempfile::tempdir().map_err(error)?;
|
||||
std::fs::write(directory.path().join("job.json"), request).map_err(error)?;
|
||||
std::fs::write(directory.path().join("input.pdf"), pdf).map_err(error)?;
|
||||
let child =
|
||||
command(directory.path()).map_err(error)?.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null()).spawn().map_err(error)?;
|
||||
let child = Arc::new(Mutex::new(child));
|
||||
let outcome = (|| {
|
||||
let (input, output) = {
|
||||
let mut process = child.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
(process.stdin.take().ok_or("print helper has no input pipe")?, process.stdout.take().ok_or("print helper has no output pipe")?)
|
||||
};
|
||||
{
|
||||
let mut state = self.state();
|
||||
if matches!(*state, State::Cancelled) {
|
||||
return Err(CANCELLED.into());
|
||||
}
|
||||
*state = State::Waking(child.clone());
|
||||
}
|
||||
let mut output = BufReader::new(output);
|
||||
loop {
|
||||
let message = line(&mut output)?.ok_or("the print helper stopped before it was ready")?;
|
||||
let Some((_, json)) = message.split_once(PREFIX) else { continue };
|
||||
if !matches!(serde_json::from_str::<Event>(json).map_err(error)?, Event::Ready) {
|
||||
return Err("the print helper did not acknowledge startup".into());
|
||||
}
|
||||
break;
|
||||
}
|
||||
{
|
||||
let mut state = self.state();
|
||||
if matches!(*state, State::Cancelled) {
|
||||
return Err(CANCELLED.into());
|
||||
}
|
||||
*state = State::Running(input);
|
||||
if let State::Running(input) = &mut *state {
|
||||
input.write_all(b"start\n").and_then(|_| input.flush()).map_err(error)?;
|
||||
}
|
||||
}
|
||||
while let Some(line) = line(&mut output)? {
|
||||
let Some((_, json)) = line.split_once(PREFIX) else { continue };
|
||||
match serde_json::from_str::<Event>(json).map_err(error)? {
|
||||
Event::Ready => return Err("the print helper repeated its startup acknowledgement".into()),
|
||||
Event::Cancelled => {
|
||||
*self.state() = State::Cancelled;
|
||||
self.0.1.notify_all();
|
||||
return Err(CANCELLED.into());
|
||||
}
|
||||
Event::Sending => {
|
||||
let mut state = self.state();
|
||||
let previous = std::mem::replace(&mut *state, State::Finished);
|
||||
*state = match previous {
|
||||
State::Running(input) | State::Sending(input) => State::Sending(input),
|
||||
other => other,
|
||||
};
|
||||
self.0.1.notify_all();
|
||||
}
|
||||
Event::Done(result) => return result,
|
||||
}
|
||||
}
|
||||
Err("the print helper stopped without a receipt".into())
|
||||
})();
|
||||
// A cancelled child has acknowledged that it cannot send. Other outcomes are terminal
|
||||
// receipts or a broken protocol/pipe; reap the process and its private input files.
|
||||
if outcome.is_err() {
|
||||
let _ = child.lock().unwrap_or_else(std::sync::PoisonError::into_inner).kill();
|
||||
}
|
||||
let status = child.lock().unwrap_or_else(std::sync::PoisonError::into_inner).wait().map_err(error)?;
|
||||
if outcome.is_ok() && !status.success() {
|
||||
return Err("the print helper failed after its receipt".into());
|
||||
}
|
||||
outcome
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep helper transport failures distinct from a printer's own error message.
|
||||
fn error(error: impl std::fmt::Display) -> String {
|
||||
format!("print helper: {error}")
|
||||
}
|
||||
|
||||
/// Read at most one byte beyond the cap so oversized files fail without unbounded allocation.
|
||||
fn bounded(mut input: impl Read, limit: u64) -> Result<Vec<u8>, String> {
|
||||
let mut bytes = Vec::new();
|
||||
input.by_ref().take(limit.saturating_add(1)).read_to_end(&mut bytes).map_err(error)?;
|
||||
if bytes.len() as u64 > limit { Err("print helper input exceeds its limit".into()) } else { Ok(bytes) }
|
||||
}
|
||||
|
||||
/// Read one bounded UTF-8 protocol record, distinguishing EOF from an oversized message.
|
||||
fn line(input: &mut impl BufRead) -> Result<Option<String>, String> {
|
||||
let mut bytes = Vec::new();
|
||||
input.take(MAX_MESSAGE + 1).read_until(b'\n', &mut bytes).map_err(error)?;
|
||||
if bytes.len() as u64 > MAX_MESSAGE {
|
||||
return Err("print helper message exceeds its limit".into());
|
||||
}
|
||||
if bytes.is_empty() { Ok(None) } else { String::from_utf8(bytes).map(|s| Some(s.trim_end().to_owned())).map_err(error) }
|
||||
}
|
||||
|
||||
/// Serialize complete events under stdout's lock so the driver and listener cannot interleave.
|
||||
fn emit(event: &Event) -> Result<(), String> {
|
||||
let mut output = std::io::stdout().lock();
|
||||
write!(output, "{PREFIX}").map_err(error)?;
|
||||
serde_json::to_writer(&mut output, event).map_err(error)?;
|
||||
writeln!(output).and_then(|_| output.flush()).map_err(error)
|
||||
}
|
||||
|
||||
/// Remove both plaintext inputs even when one fails; already-removed inputs count as success.
|
||||
fn remove_inputs(directory: &Path) -> Result<(), String> {
|
||||
let mut first_error = None;
|
||||
for name in ["job.json", "input.pdf"] {
|
||||
if let Err(failure) = std::fs::remove_file(directory.join(name))
|
||||
&& failure.kind() != std::io::ErrorKind::NotFound
|
||||
{
|
||||
first_error.get_or_insert_with(|| error(format!("could not remove {name}: {failure}")));
|
||||
}
|
||||
}
|
||||
first_error.map_or(Ok(()), Err)
|
||||
}
|
||||
|
||||
/// Load and erase the private inputs before driver work, while an independent listener can cancel.
|
||||
fn helper(
|
||||
directory: &Path,
|
||||
cancel_request: impl Fn(&craft_print::Cancel) -> bool + Send + 'static,
|
||||
submit: impl FnOnce(&[u8], &craft_print::Job, &craft_print::Cancel) -> Result<String, String>,
|
||||
) -> Result<(), String> {
|
||||
let mut input = BufReader::new(std::io::stdin());
|
||||
emit(&Event::Ready)?;
|
||||
if line(&mut input)?.as_deref() != Some("start") {
|
||||
return Err("print helper requires a start acknowledgement".into());
|
||||
}
|
||||
let cancel = craft_print::Cancel::new();
|
||||
let listener = cancel.clone();
|
||||
std::thread::Builder::new()
|
||||
.name("print-cancel".into())
|
||||
.spawn(move || {
|
||||
loop {
|
||||
match line(&mut input) {
|
||||
Ok(Some(command)) if command == "cancel" => {
|
||||
if cancel_request(&listener) {
|
||||
let _ = emit(&Event::Cancelled);
|
||||
std::process::exit(0);
|
||||
}
|
||||
if emit(&Event::Sending).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
// If the parent disappears, never leave a waiting driver process behind. Sending
|
||||
// jobs finish normally so the OS gets their pages even if the UI has gone away.
|
||||
if cancel_request(&listener) {
|
||||
std::process::exit(0);
|
||||
}
|
||||
})
|
||||
.map_err(error)?;
|
||||
let request: Request =
|
||||
serde_json::from_slice(&bounded(std::fs::File::open(directory.join("job.json")).map_err(error)?, MAX_REQUEST)?).map_err(error)?;
|
||||
let pdf = bounded(std::fs::File::open(directory.join("input.pdf")).map_err(error)?, MAX_PDF)?;
|
||||
remove_inputs(directory)?;
|
||||
let result = submit(&pdf, &request.job()?, &cancel);
|
||||
emit(&Event::Done(result))
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
/// Handle only the private first-argument flag, before logging or GUI initialization.
|
||||
pub(crate) fn helper_mode() -> Option<i32> {
|
||||
let mut args = std::env::args_os().skip(1);
|
||||
if args.next().as_deref() != Some(std::ffi::OsStr::new(FLAG)) {
|
||||
return None;
|
||||
}
|
||||
let result = args.next().ok_or_else(|| "print helper directory missing".to_owned()).and_then(|dir| {
|
||||
helper(Path::new(&dir), craft_print::Cancel::cancel, |pdf, job, cancel| {
|
||||
craft_print::submit_cancellable(pdf, job, &mut |_, _| {}, cancel).map_err(error)
|
||||
})
|
||||
});
|
||||
if let Err(message) = &result {
|
||||
let _ = emit(&Event::Done(Err(message.clone())));
|
||||
}
|
||||
Some(i32::from(result.is_err()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A real test child exercises production pipes, token handling and process cleanup.
|
||||
#[test]
|
||||
#[ignore = "launched by the process protocol tests"]
|
||||
fn helper_process() {
|
||||
let Some(directory) = std::env::var_os("WORDCRAFT_TEST_PRINT_DIR") else { return };
|
||||
if std::env::var("WORDCRAFT_TEST_PRINT_MODE").as_deref() == Ok("waking") {
|
||||
std::fs::write(Path::new(&directory).join("waking"), b"starting").unwrap();
|
||||
loop {
|
||||
std::thread::park();
|
||||
}
|
||||
}
|
||||
let result = helper(
|
||||
Path::new(&directory),
|
||||
|token| {
|
||||
if std::env::var("WORDCRAFT_TEST_PRINT_MODE").as_deref() == Ok("sending") { false } else { token.cancel() }
|
||||
},
|
||||
|pdf, job, _token| {
|
||||
assert_eq!(pdf, b"synthetic PDF");
|
||||
assert_eq!(job.printer.as_deref(), Some("test queue"));
|
||||
match std::env::var("WORDCRAFT_TEST_PRINT_MODE").as_deref() {
|
||||
Ok("held") => {
|
||||
let _provider = Mutex::new(());
|
||||
let _held = _provider.lock().unwrap();
|
||||
std::fs::write(Path::new(&directory).join("held"), b"driver entered").unwrap();
|
||||
loop {
|
||||
std::thread::park();
|
||||
}
|
||||
}
|
||||
Ok("crash") => std::process::exit(7),
|
||||
Ok("sending") => {
|
||||
std::fs::write(Path::new(&directory).join("sending"), b"sending").unwrap();
|
||||
while !Path::new(&directory).join("release").exists() {
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
Ok("spooled synthetic job".into())
|
||||
}
|
||||
_ => Ok("spooled synthetic job".into()),
|
||||
}
|
||||
},
|
||||
);
|
||||
std::process::exit(i32::from(result.is_err()));
|
||||
}
|
||||
|
||||
/// Launch just the ignored helper entry, without invoking printer hardware.
|
||||
fn command(directory: &Path, mode: &str) -> std::io::Result<Command> {
|
||||
let mut command = Command::new(std::env::current_exe()?);
|
||||
let name = module_path!().split_once("::").map_or(module_path!(), |(_, name)| name);
|
||||
command.args(["--ignored", "--exact", &format!("{name}::helper_process"), "--nocapture"]);
|
||||
command.env("WORDCRAFT_TEST_PRINT_DIR", directory).env("WORDCRAFT_TEST_PRINT_MODE", mode);
|
||||
Ok(command)
|
||||
}
|
||||
|
||||
/// Give the child a literal printer identity to verify transport.
|
||||
fn job() -> craft_print::Job {
|
||||
craft_print::Job { printer: Some("test queue".into()), ..Default::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// Cancelling before submission cannot launch a driver process.
|
||||
fn cancelled_start_never_launches_a_helper() {
|
||||
let submission = Submission::new();
|
||||
assert!(submission.cancel());
|
||||
let result = submission.submit_with(b"synthetic PDF", &job(), |_| Err(std::io::Error::other("must not launch")));
|
||||
assert_eq!(result, Err(CANCELLED.into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// A cancellation during creation withholds the start grant and removes private inputs.
|
||||
fn cancellation_during_startup_never_starts_the_driver() {
|
||||
let submission = Submission::new();
|
||||
let worker = submission.clone();
|
||||
let (started, starting) = std::sync::mpsc::channel();
|
||||
let (release, wait) = std::sync::mpsc::channel();
|
||||
let running = std::thread::spawn(move || {
|
||||
worker.submit_with(b"synthetic PDF", &job(), |directory| {
|
||||
started.send(directory.to_path_buf()).unwrap();
|
||||
wait.recv().unwrap();
|
||||
command(directory, "held")
|
||||
})
|
||||
});
|
||||
let directory = starting.recv_timeout(Duration::from_secs(10)).unwrap();
|
||||
assert!(submission.cancel());
|
||||
release.send(()).unwrap();
|
||||
assert_eq!(running.join().unwrap(), Err(CANCELLED.into()));
|
||||
assert!(!directory.exists(), "startup cancellation reaps the child and removes its inputs");
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// A hung startup has no permission to send and can be killed without a token ack.
|
||||
fn an_unresponsive_starting_process_can_be_stopped_without_an_acknowledgement() {
|
||||
let submission = Submission::new();
|
||||
let worker = submission.clone();
|
||||
let (path_tx, path_rx) = std::sync::mpsc::channel();
|
||||
let running = std::thread::spawn(move || {
|
||||
worker.submit_with(b"synthetic PDF", &job(), |dir| {
|
||||
path_tx.send(dir.to_path_buf()).unwrap();
|
||||
command(dir, "waking")
|
||||
})
|
||||
});
|
||||
let directory = path_rx.recv_timeout(Duration::from_secs(10)).unwrap();
|
||||
let deadline = std::time::Instant::now() + Duration::from_secs(10);
|
||||
while !directory.join("waking").exists() && std::time::Instant::now() < deadline {
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
assert!(directory.join("waking").exists());
|
||||
assert!(submission.cancel(), "a process without a start grant cannot send anything");
|
||||
assert_eq!(running.join().unwrap(), Err(CANCELLED.into()));
|
||||
assert!(!directory.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// Job transport preserves every explicit setting, including Unicode, duplex direction and the
|
||||
/// driver's own settings.
|
||||
fn job_options_survive_the_process_boundary() {
|
||||
// A DEVMODEW header of 156 bytes (`dmSize` at 68) and a 4-byte private part (`dmDriverExtra` at 70).
|
||||
let mut dev_mode = vec![0u8; 160];
|
||||
dev_mode[68..70].copy_from_slice(&156u16.to_le_bytes());
|
||||
dev_mode[70..72].copy_from_slice(&4u16.to_le_bytes());
|
||||
dev_mode[156..].copy_from_slice(&[1, 2, 3, 4]);
|
||||
let dev_mode = craft_print::rgb::DevMode::from_bytes(dev_mode).unwrap();
|
||||
let expected = craft_print::Job {
|
||||
printer: Some("Office λ".into()),
|
||||
copies: 3,
|
||||
collate: false,
|
||||
duplex: Some(craft_print::Duplex::ShortEdge),
|
||||
grayscale: true,
|
||||
grey_pages: true,
|
||||
scaling: craft_print::Scaling::ShrinkToFit,
|
||||
title: "A document".into(),
|
||||
options: vec![("media".into(), "iso_a4_210x297mm".into())],
|
||||
driver_settings: Some(craft_print::DriverSettings::new("Office λ", dev_mode)),
|
||||
};
|
||||
let bytes = serde_json::to_vec(&Request::from_job(&expected)).unwrap();
|
||||
let received: Request = serde_json::from_slice(&bytes).unwrap();
|
||||
assert_eq!(received.job(), Ok(expected));
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// Damaged driver settings on the wire are an error, not a job printed with other settings.
|
||||
fn damaged_driver_settings_are_refused() {
|
||||
for hex in ["", "0", "zz", "00"] {
|
||||
let mut request = Request::from_job(&job());
|
||||
request.driver_settings = Some(("Office".into(), hex.into()));
|
||||
assert!(request.job().is_err(), "{hex:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// Retry succeeds immediately after cancellation, before joining the old worker.
|
||||
fn cancelled_driver_does_not_block_the_next_process() {
|
||||
let submission = Submission::new();
|
||||
let worker = submission.clone();
|
||||
let (path_tx, path_rx) = std::sync::mpsc::channel();
|
||||
let running = std::thread::spawn(move || {
|
||||
worker.submit_with(b"synthetic PDF", &job(), |dir| {
|
||||
path_tx.send(dir.to_path_buf()).unwrap();
|
||||
command(dir, "held")
|
||||
})
|
||||
});
|
||||
let directory = path_rx.recv_timeout(Duration::from_secs(10)).unwrap();
|
||||
let deadline = std::time::Instant::now() + Duration::from_secs(10);
|
||||
while !directory.join("held").exists() && std::time::Instant::now() < deadline {
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
assert!(directory.join("held").exists(), "the child is held inside its driver");
|
||||
assert!(!directory.join("input.pdf").exists(), "the stalled driver retains no plaintext PDF");
|
||||
assert!(!directory.join("job.json").exists(), "loaded settings were erased before driver work");
|
||||
assert!(submission.cancel(), "a stalled driver still acknowledges cancellation");
|
||||
let next = Submission::new();
|
||||
assert_eq!(next.submit_with(b"synthetic PDF", &job(), |dir| command(dir, "ready")), Ok("spooled synthetic job".into()));
|
||||
assert_eq!(running.join().unwrap(), Err(CANCELLED.into()));
|
||||
assert!(!directory.exists(), "the reaped helper's PDF and settings were removed");
|
||||
assert!(!next.cancel(), "a completed job keeps its receipt");
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// A refused cancellation keeps the sending process alive until its receipt.
|
||||
fn cancellation_refusal_preserves_the_sending_job() {
|
||||
let submission = Submission::new();
|
||||
let worker = submission.clone();
|
||||
let (path_tx, path_rx) = std::sync::mpsc::channel();
|
||||
let running = std::thread::spawn(move || {
|
||||
worker.submit_with(b"synthetic PDF", &job(), |dir| {
|
||||
path_tx.send(dir.to_path_buf()).unwrap();
|
||||
command(dir, "sending")
|
||||
})
|
||||
});
|
||||
let directory = path_rx.recv_timeout(Duration::from_secs(10)).unwrap();
|
||||
let deadline = std::time::Instant::now() + Duration::from_secs(10);
|
||||
while !directory.join("sending").exists() && std::time::Instant::now() < deadline {
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
assert!(directory.join("sending").exists());
|
||||
assert!(!submission.cancel(), "a sending job refuses cancellation");
|
||||
assert!(matches!(*submission.state(), State::Sending(_)));
|
||||
assert!(!running.is_finished(), "the child is retained until it finishes sending");
|
||||
std::fs::write(directory.join("release"), b"continue").unwrap();
|
||||
assert_eq!(running.join().unwrap(), Ok("spooled synthetic job".into()));
|
||||
assert!(!directory.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// Closing the parent's pipe stops a waiting driver and permits parent-side cleanup.
|
||||
fn parent_disconnect_stops_a_waiting_driver() {
|
||||
let submission = Submission::new();
|
||||
let worker = submission.clone();
|
||||
let (path_tx, path_rx) = std::sync::mpsc::channel();
|
||||
let running = std::thread::spawn(move || {
|
||||
worker.submit_with(b"synthetic PDF", &job(), |dir| {
|
||||
path_tx.send(dir.to_path_buf()).unwrap();
|
||||
command(dir, "held")
|
||||
})
|
||||
});
|
||||
let directory = path_rx.recv_timeout(Duration::from_secs(10)).unwrap();
|
||||
let deadline = std::time::Instant::now() + Duration::from_secs(10);
|
||||
while !directory.join("held").exists() && std::time::Instant::now() < deadline {
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
assert!(directory.join("held").exists());
|
||||
*submission.state() = State::Finished; // Drops the parent's pipe as on process exit.
|
||||
assert_eq!(running.join().unwrap(), Err("the print helper stopped without a receipt".into()));
|
||||
assert!(!directory.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// Helper failure removes its input directory; input limits reject oversize data.
|
||||
fn helper_crashes_are_errors_and_inputs_are_bounded() {
|
||||
let submission = Submission::new();
|
||||
let mut inputs = None;
|
||||
assert_eq!(
|
||||
submission.submit_with(b"synthetic PDF", &job(), |dir| {
|
||||
inputs = Some(dir.to_path_buf());
|
||||
command(dir, "crash")
|
||||
}),
|
||||
Err("the print helper stopped without a receipt".into())
|
||||
);
|
||||
assert!(!inputs.unwrap().exists(), "a helper crash removes the PDF and settings");
|
||||
assert_eq!(bounded(&b"abcd"[..], 3), Err("print helper input exceeds its limit".into()));
|
||||
assert_eq!(bounded(&b"abc"[..], 3), Ok(b"abc".to_vec()));
|
||||
}
|
||||
|
||||
/// Cleanup is repeatable and reports real failures while still attempting both inputs.
|
||||
#[test]
|
||||
fn input_cleanup_tolerates_missing_files_and_reports_failures() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
std::fs::write(directory.path().join("job.json"), b"settings").unwrap();
|
||||
std::fs::write(directory.path().join("input.pdf"), b"private PDF").unwrap();
|
||||
assert_eq!(remove_inputs(directory.path()), Ok(()));
|
||||
assert_eq!(remove_inputs(directory.path()), Ok(()));
|
||||
assert!(!directory.path().join("input.pdf").exists());
|
||||
std::fs::create_dir(directory.path().join("job.json")).unwrap();
|
||||
std::fs::write(directory.path().join("input.pdf"), b"private PDF").unwrap();
|
||||
let error = remove_inputs(directory.path()).unwrap_err();
|
||||
assert!(error.contains("could not remove job.json"), "{error}");
|
||||
assert!(!directory.path().join("input.pdf").exists(), "a settings cleanup failure does not retain the PDF");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
//! Set the immutable nightly Windows identity before any native window or COM service.
|
||||
//! Stable deliberately leaves its implicit shortcut/path identity unchanged.
|
||||
|
||||
use std::sync::OnceLock;
|
||||
|
||||
#[derive(Clone, Debug, thiserror::Error)]
|
||||
pub enum IdentityError {
|
||||
#[error("{0}")]
|
||||
Configuration(String),
|
||||
}
|
||||
|
||||
pub fn initialize(nightly: bool, app_id: &str) -> Result<(), IdentityError> {
|
||||
configure(nightly && cfg!(windows), app_id, |id| {
|
||||
static RESULT: OnceLock<Result<(), String>> = OnceLock::new();
|
||||
RESULT
|
||||
.get_or_init(|| {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
winsafe::SetCurrentProcessExplicitAppUserModelID(id)
|
||||
.map_err(|error| format!("cannot set the nightly Windows identity: {error}"))?;
|
||||
let actual = winsafe::GetCurrentProcessExplicitAppUserModelID()
|
||||
.map_err(|error| format!("cannot read back the nightly Windows identity: {error}"))?;
|
||||
if actual != id {
|
||||
return Err("the native Windows identity did not match the selected nightly channel".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
let _ = id;
|
||||
Ok(())
|
||||
}
|
||||
})
|
||||
.clone()
|
||||
})
|
||||
.map_err(IdentityError::Configuration)
|
||||
}
|
||||
|
||||
fn configure(explicit_nightly: bool, app_id: &str, set: impl FnOnce(&str) -> Result<(), String>) -> Result<(), String> {
|
||||
if explicit_nightly { set(app_id) } else { Ok(()) }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn stable_does_not_call_the_explicit_identity_api() {
|
||||
configure(false, "nightly-id", |_| panic!("stable identity must remain implicit")).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_applies_the_supplied_identity_once() {
|
||||
let calls = std::cell::Cell::new(0);
|
||||
configure(true, "nightly-id", |id| {
|
||||
assert_eq!(id, "nightly-id");
|
||||
calls.set(calls.get() + 1);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(calls.get(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_identity_failure_is_returned_instead_of_starting_a_window() {
|
||||
let started = std::cell::Cell::new(false);
|
||||
let result = configure(true, "nightly-id", |_| Err("native identity refused".into())).map(|()| started.set(true));
|
||||
assert_eq!(result.unwrap_err(), "native identity refused");
|
||||
assert!(!started.get());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,535 @@
|
||||
//! 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");
|
||||
}
|
||||
}
|
||||
@@ -1,30 +1,19 @@
|
||||
//! The system region new documents follow (#838): the paper File › New starts on, the default
|
||||
//! measurement unit and the decimal separator.
|
||||
//!
|
||||
//! - Windows: the preferred language with the home location from Settings › Time & language ›
|
||||
//! Region (`GlobalizationPreferences.HomeGeographicRegion`, a safe Windows Runtime API), since
|
||||
//! the language list alone says `en-US` for an English interface in Poland.
|
||||
//! - Elsewhere: the locale the UI crate reads ([`wordcraft_ui_egui::i18n::system_region`]).
|
||||
//! `WORDCRAFT_REGION` names a region outright; otherwise it is the system's regional format,
|
||||
//! read once for desktop and web by [`wordcraft_ui_egui::i18n::system_region`].
|
||||
|
||||
/// The system region.
|
||||
pub fn system() -> wordcraft_engine::Region {
|
||||
let named = std::env::var("WORDCRAFT_REGION").ok().filter(|v| !v.trim().is_empty());
|
||||
// Runs without preferences (agents' and screenshot runs) behave the same on every machine:
|
||||
// en-US unless `WORDCRAFT_REGION` says otherwise.
|
||||
if std::env::var_os("WORDCRAFT_NO_PREFS").is_some() && std::env::var_os("WORDCRAFT_REGION").is_none() {
|
||||
if std::env::var_os("WORDCRAFT_NO_PREFS").is_some() && named.is_none() {
|
||||
return wordcraft_engine::Region::default();
|
||||
}
|
||||
let region = wordcraft_ui_egui::i18n::system_region();
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
if std::env::var_os("WORDCRAFT_REGION").is_none() {
|
||||
return match windows::System::UserProfile::GlobalizationPreferences::HomeGeographicRegion() {
|
||||
Ok(home) => region.with_territory(&home.to_string()),
|
||||
Err(e) => {
|
||||
log::debug!("system home region: {e}");
|
||||
region
|
||||
}
|
||||
};
|
||||
}
|
||||
if let Some(tag) = named {
|
||||
return wordcraft_engine::Region::from_tag(&tag);
|
||||
}
|
||||
region
|
||||
wordcraft_ui_egui::i18n::system_region()
|
||||
}
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
//! Where AppKit puts the traffic lights, so the integrated title bar fits around them (macOS).
|
||||
//!
|
||||
//! The lights' size and position change between macOS versions (they grew in macOS 26), so the
|
||||
//! title bar measures the real buttons instead of assuming the old 28 pt layout. These calls are
|
||||
//! safe in the `objc2-app-kit` bindings (our workspace forbids unsafe).
|
||||
|
||||
use objc2::MainThreadMarker;
|
||||
use objc2_app_kit::{NSApplication, NSWindowButton};
|
||||
use wordcraft_ui_egui::chrome::MacTitleBar;
|
||||
|
||||
/// The title bar around the app window's traffic lights, or `None` before the window exists or
|
||||
/// when AppKit has no zoom button to measure (the caller keeps the standard layout).
|
||||
pub fn title_bar() -> Option<MacTitleBar> {
|
||||
let mtm = MainThreadMarker::new()?;
|
||||
let window = NSApplication::sharedApplication(mtm).windows().firstObject()?;
|
||||
let zoom = window.standardWindowButton(NSWindowButton::ZoomButton)?;
|
||||
// In window coordinates, which count up from the bottom.
|
||||
let frame = zoom.convertRect_toView(zoom.bounds(), None);
|
||||
let window_height = window.frame().size.height;
|
||||
let right = frame.origin.x + frame.size.width;
|
||||
let centre_from_top = window_height - (frame.origin.y + frame.size.height / 2.0);
|
||||
if !(right.is_finite() && centre_from_top.is_finite() && right > 0.0 && centre_from_top > 0.0) {
|
||||
return None;
|
||||
}
|
||||
Some(MacTitleBar::around_lights(right as f32, centre_from_top as f32, frame.size.height as f32))
|
||||
}
|
||||
@@ -31,21 +31,12 @@ fn app(args: &[&str]) -> Output {
|
||||
|
||||
#[test]
|
||||
fn a_bad_port_is_an_error_naming_it() {
|
||||
let cases: [(&[&str], &str); 8] = [
|
||||
(&["--control", "-99999999999999999999"], ", got \"-99999999999999999999\""),
|
||||
(&["--control", "abc"], ", got \"abc\""),
|
||||
(&["--control", "79811"], ", got \"79811\""),
|
||||
(&["--control", "0"], ", got \"0\""),
|
||||
(&["--control", "-5"], ", got \"-5\""),
|
||||
(&["--control", "abc", "--control", "7981"], ", got \"abc\""),
|
||||
(&["--control"], ""),
|
||||
(&["--control", "--sample"], ""),
|
||||
];
|
||||
for (args, got) in cases {
|
||||
let cases: [&[&str]; 4] = [&["--control", "abc"], &["--control", "0"], &["--control"], &["--control", "--sample"]];
|
||||
for args in cases {
|
||||
let out = app(args);
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
assert_eq!(out.status.code(), Some(2), "{args:?}: stderr: {stderr}");
|
||||
assert_eq!(stderr, format!("wordcraft: --control needs a port number from 1 to 65535{got}\n"), "{args:?}");
|
||||
assert!(stderr.contains("--control"), "{args:?}: stderr: {stderr}");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
# WordCraft app icon
|
||||
|
||||
A **page and pen**: a sheet of paper with a folded corner and ruled lines, with a fountain pen
|
||||
lying across its lower right, on the app's blue field. It is drawn in the canvas palette the app's
|
||||
own artwork uses (`#3b5bdb` field, `#efe9dc` paper, `#0b0b0c` ink).
|
||||
|
||||
`wordcraft.svg` is the canonical master: a full-bleed 512-unit tile with a rounded square
|
||||
(`rx=112`) and no border. Windows and Linux use the tile as it is; the macOS renders sit on
|
||||
Apple's grid, an 824/1024 body with a transparent margin.
|
||||
|
||||
## Files
|
||||
|
||||
- `wordcraft.svg`: canonical master (also the hicolor scalable icon).
|
||||
- `wordcraft-1024.png`: 1024 px full-bleed render.
|
||||
- `wordcraft-macos-512.png`: the padded macOS render (Dock, window icon; embedded by the app).
|
||||
- `wordcraft.icns`: macOS bundle icon (`CFBundleIconFile`), padded frames.
|
||||
- `wordcraft.ico`: Windows icon, 16–256 px, embedded in `wordcraft.exe` by
|
||||
`apps/wordcraft/build.rs`.
|
||||
- `hicolor/<size>/apps/ai.storyteller.wordcraft.png` (16–512) and `hicolor/scalable/...svg`:
|
||||
Linux icon theme.
|
||||
|
||||
## Regenerate
|
||||
|
||||
Replace `wordcraft.svg`, then run `packaging/icons.sh`. It needs `resvg`, plus `iconutil` on macOS;
|
||||
`cargo run -p xtask -- ico` packs the Windows icon.
|
||||
|
||||
## Nightly channel
|
||||
|
||||
The Nightly icons keep the drawing, its alpha and the macOS padding exactly as the stable renders
|
||||
have them. Only the background contribution changes: from the app blue to the deeper Nightly
|
||||
background `#232c67`. There is no letter badge, crescent or other mark; the app and the Launcher
|
||||
name the channel in text.
|
||||
|
||||
`packaging/nightly-icons.py` derives the four files from the committed stable renders (the `.ico`
|
||||
frames, the `.icns` slots, the 256 px hicolor render and the padded 512 px macOS master) and
|
||||
records their hashes in [`nightly-provenance.json`](nightly-provenance.json). `--check` re-derives
|
||||
them and compares. The three smallest macOS slots (16, 32 and 64 px) are box-filtered from the
|
||||
padded master; every other frame is the same size as the stable frame it comes from, so nothing is
|
||||
upscaled. The stable files are not modified.
|
||||
@@ -0,0 +1,72 @@
|
||||
{
|
||||
"title": "WordCraft nightly deep-background icons",
|
||||
"author": "@skylartaylor",
|
||||
"license": "MIT OR Apache-2.0",
|
||||
"source_commit": null,
|
||||
"inputs": [
|
||||
{
|
||||
"path": "assets/app-icon/hicolor/256x256/apps/ai.storyteller.wordcraft.png",
|
||||
"sha256": "7c1791408282d01e8c5d0cb1f4080971eaa412c60518694a1cec1e60b23c7406",
|
||||
"purpose": "Windows/Linux native256 master"
|
||||
},
|
||||
{
|
||||
"path": "assets/app-icon/wordcraft.ico",
|
||||
"sha256": "53a23dcf66260f44d87d4d143d633395f3e967f391eda47e6e9cc3a52f820225",
|
||||
"purpose": "nine full-bleed frames, 16-256 px"
|
||||
},
|
||||
{
|
||||
"path": "assets/app-icon/wordcraft.icns",
|
||||
"sha256": "02ac9dcb7ee06858416c7ef70ca2b359cad38dbef4a0b526bb1f28953d90170f",
|
||||
"purpose": "padded macOS frames, 32-1024 px"
|
||||
},
|
||||
{
|
||||
"path": "assets/app-icon/wordcraft-macos-512.png",
|
||||
"sha256": "5a8a4476c1fb67123f803a8ab7a7a0dbd9912675ae54d695c17e74454913ceae",
|
||||
"purpose": "padded macOS master (box-filtered down to the 16/32/64 px slots, never upscaled)"
|
||||
}
|
||||
],
|
||||
"method": {
|
||||
"kind": "derived from the project-owned stable renders by a committed, reproducible script",
|
||||
"original_palette": {
|
||||
"ink": "#0b0b0c",
|
||||
"paper": "#efe9dc",
|
||||
"background": "#3b5bdb"
|
||||
},
|
||||
"nightly_background": "#232c67",
|
||||
"transform": "Decompose every pixel in the stable three-colour palette (ink, paper, background) and rebuild it with the Nightly background, keeping the ink and paper weights, alpha and padding. Clamped and renormalised where an antialiased pixel falls outside the triangle. No crescent, letter or badge.",
|
||||
"generator": "packaging/nightly-icons.py",
|
||||
"generator_sha256": "7a31bc6d3a00d991cf4fd6b1f2ce06b3bdc9201525d207ba84a935a877ee8e4a",
|
||||
"reproduce": "python3 packaging/nightly-icons.py --check"
|
||||
},
|
||||
"outputs": {
|
||||
"assets/app-icon/wordcraft-nightly.png": "43a002255f6db703599de99224cd47274905b8742d92f91d0f7c41c8cb5656e2",
|
||||
"assets/app-icon/wordcraft-nightly.ico": "f4bb314bb6c8c131c7250e441407be5e22e645579881f0a80fe7bd963adda54a",
|
||||
"assets/app-icon/wordcraft-nightly-1024.png": "36e21d31b852ac222c787ee27af45667882353eb9b1c3bfb62a9038c17843b25",
|
||||
"assets/app-icon/wordcraft-nightly.icns": "0b359aa7f07fda079298a97215da207486ca092bbe9c6b277a5de3d3fbc4f9ef"
|
||||
},
|
||||
"ico_frame_sizes": [
|
||||
16,
|
||||
20,
|
||||
24,
|
||||
32,
|
||||
40,
|
||||
48,
|
||||
64,
|
||||
128,
|
||||
256
|
||||
],
|
||||
"icns_png_slots": {
|
||||
"icp4": 16,
|
||||
"icp5": 32,
|
||||
"icp6": 64,
|
||||
"ic07": 128,
|
||||
"ic08": 256,
|
||||
"ic13": 256,
|
||||
"ic09": 512,
|
||||
"ic14": 512,
|
||||
"ic10": 1024,
|
||||
"ic11": 32,
|
||||
"ic12": 64
|
||||
},
|
||||
"validation": "Every output is re-derived from the committed inputs by the committed script (--check) and compared by SHA-256; the frames' pixel dimensions and the containers' members are checked while deriving; the foreground and padding were compared visually against the stable renders. Native Explorer/Finder qualification is unrun."
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 22 KiB |
Binary file not shown.
Binary file not shown.
|
After Width: | Height: | Size: 13 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 4.1 KiB |
@@ -209,5 +209,7 @@ real_name = "Helen Kwok"
|
||||
[people.ashokram-si]
|
||||
real_name = "Ashok Ram"
|
||||
|
||||
[people.reubgr]
|
||||
real_name = "Reuben Grinberg"
|
||||
[people.benandez]
|
||||
sync_github_name = true
|
||||
|
||||
@@ -1,17 +1,37 @@
|
||||
//! The control channel's key file, one rule for the app (which writes it) and the MCP bridge
|
||||
//! (which reads it): `<settings>/control-key.<instance>`. See `docs/control-protocol.md`, Keys.
|
||||
//! The control channel's token file, one rule for the app (which writes it) and the MCP bridge
|
||||
//! (which reads it): `<settings>/control-key.<instance>`. See `docs/control-protocol.md`, Token.
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// The app's settings folder (preferences, logs, key files): macOS
|
||||
/// The folder the desktop app chose before any of its state was read: a Launcher-selected
|
||||
/// Nightly profile (`launch_profile`). Set once, at startup, before the first [`settings_dir`]
|
||||
/// call; tests and the CLI leave it unset.
|
||||
static CHOSEN: std::sync::OnceLock<PathBuf> = std::sync::OnceLock::new();
|
||||
|
||||
/// Point [`settings_dir`] at `dir` for this process. Fails when a folder was already chosen.
|
||||
pub fn use_settings_dir(dir: PathBuf) -> Result<(), String> {
|
||||
CHOSEN.set(dir).map_err(|_| "the settings folder was already selected".into())
|
||||
}
|
||||
|
||||
/// The app's settings folder (preferences, logs, token files): macOS
|
||||
/// `~/Library/Application Support/WordCraft`, Windows `%APPDATA%\WordCraft`, otherwise
|
||||
/// `$XDG_CONFIG_HOME/wordcraft` or `~/.config/wordcraft`.
|
||||
/// `WORDCRAFT_PROFILE_DIR` overrides the entire folder for isolated runs.
|
||||
/// A folder chosen by the app through [`use_settings_dir`] wins: it is a launch decision, not
|
||||
/// an environment variable a child or a wrapper might have inherited. `WORDCRAFT_PROFILE_DIR`
|
||||
/// overrides the entire folder for isolated runs otherwise.
|
||||
pub fn settings_dir() -> Option<PathBuf> {
|
||||
if let Some(path) = CHOSEN.get() {
|
||||
return Some(path.clone());
|
||||
}
|
||||
if let Some(path) = std::env::var_os("WORDCRAFT_PROFILE_DIR").filter(|p| !p.is_empty()) {
|
||||
return Some(PathBuf::from(path));
|
||||
}
|
||||
platform_settings_dir()
|
||||
}
|
||||
|
||||
/// The platform's own folder, when nothing chose one (see [`settings_dir`]).
|
||||
fn platform_settings_dir() -> Option<PathBuf> {
|
||||
if cfg!(target_os = "macos") {
|
||||
std::env::var_os("HOME").map(|h| PathBuf::from(h).join("Library/Application Support/WordCraft"))
|
||||
} else if cfg!(windows) {
|
||||
@@ -36,8 +56,8 @@ pub fn instance_id() -> Option<String> {
|
||||
parse_instance_id(&std::fs::read_to_string("/.flatpak-info").ok()?)
|
||||
}
|
||||
|
||||
/// `<settings>/control-key.<instance>`, with `<instance>` the Flatpak instance id or
|
||||
/// `local-<port>`.
|
||||
/// The token file `<settings>/control-key.<instance>`, with `<instance>` the Flatpak instance id
|
||||
/// or `local-<port>`.
|
||||
pub fn key_path(settings: &Path, port: u16) -> PathBuf {
|
||||
key_path_for(settings, instance_id().as_deref(), port)
|
||||
}
|
||||
@@ -67,6 +87,18 @@ mod tests {
|
||||
assert_eq!(parse_instance_id("app=ai.storyteller.wordcraft\n"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_chosen_folder_wins_over_the_environment() {
|
||||
// The chosen folder is process-wide and set once, so this test only reads the rule when
|
||||
// nothing chose one (the crate's own tests and the CLI never do).
|
||||
if CHOSEN.get().is_none() {
|
||||
assert_eq!(settings_dir(), super::platform_settings_dir());
|
||||
assert!(use_settings_dir(PathBuf::from("/chosen/profile")).is_ok());
|
||||
assert_eq!(settings_dir().as_deref(), Some(std::path::Path::new("/chosen/profile")));
|
||||
assert!(use_settings_dir(PathBuf::from("/other")).is_err(), "the folder is selected once");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn key_file_per_instance() {
|
||||
let dir = Path::new("/settings/wordcraft");
|
||||
@@ -77,12 +109,4 @@ mod tests {
|
||||
assert_eq!(key_path(dir, 7981), dir.join("control-key.local-7981"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_dir_is_the_apps_folder() {
|
||||
if let Some(d) = settings_dir() {
|
||||
let name = d.file_name().and_then(|n| n.to_str()).unwrap_or("");
|
||||
assert!(name == "wordcraft" || name == "WordCraft", "{}", d.display());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+230
-24
@@ -7,7 +7,7 @@ use std::sync::Arc;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::para::{InlineObject, Run};
|
||||
use crate::para::{InlineObject, OBJ, Run};
|
||||
use crate::props::{CharProps, ParaProps};
|
||||
use crate::{Block, Blocks, DocError, Document, Paragraph, Part, PartKind, Path, Pos, Result, para_block};
|
||||
use crate::{Table, table::MAX_TABLE_DEPTH};
|
||||
@@ -26,8 +26,41 @@ pub struct Fragment {
|
||||
}
|
||||
|
||||
impl Fragment {
|
||||
/// Text box story IDs referenced by the fragment's objects in document order, falling
|
||||
/// back to the parts map's keys if no inline objects reference them.
|
||||
fn text_box_ids(&self) -> Vec<u32> {
|
||||
let mut ids = Vec::new();
|
||||
for b in &self.blocks {
|
||||
each_para(b, 0, &mut |p| {
|
||||
for o in &p.objects {
|
||||
for id in o.text_boxes() {
|
||||
if self.parts.get(&id).is_some_and(|part| part.kind == crate::PartKind::TextBox) {
|
||||
ids.push(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
if ids.is_empty() {
|
||||
ids.extend(self.parts.iter().filter(|(_, p)| p.kind == crate::PartKind::TextBox).map(|(id, _)| *id));
|
||||
}
|
||||
ids
|
||||
}
|
||||
|
||||
/// The plain text representation of the fragment's body, falling back to text box part stories
|
||||
/// when the body text has no real text (empty or only whitespace/object markers).
|
||||
pub fn plain_text(&self) -> String {
|
||||
self.to_document().plain_text(crate::StoryRef::Body)
|
||||
let d = self.to_document();
|
||||
let text = d.plain_text(crate::StoryRef::Body);
|
||||
let has_body_text = text.chars().any(|c| !c.is_whitespace() && c != OBJ);
|
||||
if !has_body_text && !self.parts.is_empty() {
|
||||
let parts: Vec<String> =
|
||||
self.text_box_ids().into_iter().map(|id| d.plain_text(crate::StoryRef::Part(id))).filter(|s| !s.is_empty()).collect();
|
||||
if !parts.is_empty() {
|
||||
return parts.join("\n");
|
||||
}
|
||||
}
|
||||
text
|
||||
}
|
||||
/// The fragment as the body of a new document (default styles).
|
||||
pub fn to_document(&self) -> Document {
|
||||
@@ -67,9 +100,20 @@ impl Fragment {
|
||||
found
|
||||
}
|
||||
/// The text a copy puts on the clipboard: [`Self::plain_text`] with symbol-font characters
|
||||
/// (Wingdings…) as their Unicode equivalents.
|
||||
/// (Wingdings…) as their Unicode equivalents. Falls back to text box part stories when body
|
||||
/// text has no real text (empty or only whitespace/object markers).
|
||||
pub fn clipboard_text(&self) -> String {
|
||||
self.to_document().shown_text(crate::StoryRef::Body)
|
||||
let d = self.to_document();
|
||||
let text = d.shown_text(crate::StoryRef::Body);
|
||||
let has_body_text = text.chars().any(|c| !c.is_whitespace() && c != OBJ);
|
||||
if !has_body_text && !self.parts.is_empty() {
|
||||
let parts: Vec<String> =
|
||||
self.text_box_ids().into_iter().map(|id| d.shown_text(crate::StoryRef::Part(id))).filter(|s| !s.is_empty()).collect();
|
||||
if !parts.is_empty() {
|
||||
return parts.join("\n");
|
||||
}
|
||||
}
|
||||
text
|
||||
}
|
||||
/// Add `piece` at the end, followed by a paragraph mark unless it already ends with one: how
|
||||
/// Word's Spike collects what it cuts. The piece's text box stories get ids after this
|
||||
@@ -603,6 +647,48 @@ 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
|
||||
@@ -1340,6 +1426,22 @@ impl Document {
|
||||
out
|
||||
}
|
||||
|
||||
/// Copy paragraphs in linear document order between `a` and `b` inclusive (#5906).
|
||||
fn copy_para_range(&self, a: &Pos, b: &Pos) -> Vec<Block> {
|
||||
let (a, b) = order(a, b);
|
||||
let mut out = Vec::new();
|
||||
for p in self.paths_between(&a, &b) {
|
||||
if let Some(para) = self.para(a.story, &p) {
|
||||
let from = if p == a.path { a.off } else { 0 };
|
||||
let to = if p == b.path { b.off } else { para.len() };
|
||||
let clear = p == b.path && b.off < para.len();
|
||||
out.push(Block::Para(trim_para(para, from, to, clear)));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Copy blocks spanning `a..b`, preserving whole tables when covered across containers (#5906).
|
||||
fn copy_blocks(&self, a: &Pos, b: &Pos) -> Vec<Block> {
|
||||
let (a, b) = order(a, b);
|
||||
let mut out = Vec::new();
|
||||
@@ -1352,21 +1454,17 @@ impl Document {
|
||||
let Some(blk) = bl.get(i) else { break };
|
||||
match &**blk {
|
||||
Block::Para(p) => {
|
||||
let mut p = p.clone();
|
||||
let to = if i == b.path.last() { b.off } else { p.len() };
|
||||
let from = if i == a.path.last() { a.off } else { 0 };
|
||||
let _ = p.delete(to.min(p.len()), p.len());
|
||||
let _ = p.delete(0, from.min(p.len()));
|
||||
if i == b.path.last() && to < self.para(a.story, &b.path).map(Paragraph::len).unwrap_or(0) {
|
||||
p.section = None;
|
||||
}
|
||||
out.push(Block::Para(p));
|
||||
let clear = i == b.path.last() && to < p.len();
|
||||
out.push(Block::Para(trim_para(p, from, to, clear)));
|
||||
}
|
||||
Block::Table(t) => out.push(Block::Table(t.clone())),
|
||||
Block::Table(_) => out.push((**blk).clone()),
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// Across the cells of a whole table: the table itself, not its cells' paragraphs (#1744).
|
||||
if let Some(tp) = self.whole_table(&a, &b)
|
||||
&& let Some(blk) = self.block(a.story, &tp)
|
||||
@@ -1374,17 +1472,92 @@ impl Document {
|
||||
out.push(blk.clone());
|
||||
return out;
|
||||
}
|
||||
for p in self.paths_between(&a, &b) {
|
||||
if let Some(para) = self.para(a.story, &p) {
|
||||
let mut q = para.clone();
|
||||
let to = if p == b.path { b.off } else { q.len() };
|
||||
let from = if p == a.path { a.off } else { 0 };
|
||||
let _ = q.delete(to.min(q.len()), q.len());
|
||||
let _ = q.delete(0, from.min(q.len()));
|
||||
q.section = None;
|
||||
out.push(Block::Para(q));
|
||||
|
||||
// Find the lowest common ancestor container.
|
||||
let common = a.path.0.iter().zip(&b.path.0).take_while(|(x, y)| x == y).count();
|
||||
let level = common.saturating_sub(common % 3);
|
||||
let prefix = a.path.0.get(..level).unwrap_or_default().to_vec();
|
||||
let block_path = |i: usize| {
|
||||
let mut v = prefix.clone();
|
||||
v.push(i as u32);
|
||||
Path(v)
|
||||
};
|
||||
|
||||
let (Some(&ia), Some(&ib)) = (a.path.0.get(level), b.path.0.get(level)) else {
|
||||
return self.copy_para_range(&a, &b);
|
||||
};
|
||||
let (ia, ib) = (ia as usize, ib as usize);
|
||||
if ia >= ib {
|
||||
return self.copy_para_range(&a, &b);
|
||||
}
|
||||
|
||||
let Some(bl) = self.container(a.story, &block_path(ia)) else {
|
||||
return self.copy_para_range(&a, &b);
|
||||
};
|
||||
|
||||
let edge_para = |i: usize, last: bool| -> Option<Path> {
|
||||
let blk = bl.get(i)?;
|
||||
if matches!(&**blk, Block::Para(_)) {
|
||||
return None;
|
||||
}
|
||||
let mut pre = block_path(i).0;
|
||||
edge_para_in_block(blk, &mut pre, level / 3, last)
|
||||
};
|
||||
let walked = |i: usize| bl.get(i).is_some_and(|b| !deeper_than_walk(b, level / 3));
|
||||
|
||||
let a_covers = if a.path.0.len() == level + 1 {
|
||||
a.off == 0
|
||||
} else {
|
||||
a.path.0.len() > level + 1 && a.off == 0 && walked(ia) && edge_para(ia, false).as_ref() == Some(&a.path)
|
||||
};
|
||||
|
||||
let b_at_end = self.para(b.story, &b.path).is_some_and(|p| p.len() == b.off);
|
||||
let b_covers = if b.path.0.len() == level + 1 {
|
||||
b_at_end
|
||||
} else {
|
||||
b.path.0.len() > level + 1 && walked(ib) && edge_para(ib, true).as_ref() == Some(&b.path) && b_at_end
|
||||
};
|
||||
|
||||
// Start block ia:
|
||||
if a_covers {
|
||||
if let Some(blk) = bl.get(ia) {
|
||||
out.push((**blk).clone());
|
||||
}
|
||||
} else if a.path.0.len() == level + 1 {
|
||||
if let Some(blk) = bl.get(ia)
|
||||
&& let Block::Para(p) = &**blk
|
||||
{
|
||||
out.push(Block::Para(trim_para(p, a.off, p.len(), false)));
|
||||
}
|
||||
} else if let Some(last_in_a) = edge_para(ia, true) {
|
||||
let end_pos = Pos { story: a.story, path: last_in_a.clone(), off: self.para(a.story, &last_in_a).map_or(0, Paragraph::len) };
|
||||
out.extend(self.copy_para_range(&a, &end_pos));
|
||||
}
|
||||
|
||||
// Blocks strictly between ia and ib: whole blocks
|
||||
for i in ia + 1..ib {
|
||||
if let Some(blk) = bl.get(i) {
|
||||
out.push((**blk).clone());
|
||||
}
|
||||
}
|
||||
|
||||
// End block ib:
|
||||
if b_covers {
|
||||
if let Some(blk) = bl.get(ib) {
|
||||
out.push((**blk).clone());
|
||||
}
|
||||
} else if b.path.0.len() == level + 1 {
|
||||
if let Some(blk) = bl.get(ib)
|
||||
&& let Block::Para(p) = &**blk
|
||||
{
|
||||
let clear = b.off < p.len();
|
||||
out.push(Block::Para(trim_para(p, 0, b.off, clear)));
|
||||
}
|
||||
} else if let Some(first_in_b) = edge_para(ib, false) {
|
||||
let start_pos = Pos { story: b.story, path: first_in_b, off: 0 };
|
||||
out.extend(self.copy_para_range(&start_pos, &b));
|
||||
}
|
||||
|
||||
out
|
||||
}
|
||||
|
||||
@@ -1509,9 +1682,12 @@ impl Document {
|
||||
if blocks.is_empty() {
|
||||
return Ok(pos.clone());
|
||||
}
|
||||
if self.para_at(pos).is_none() {
|
||||
let Some(dest_para) = self.para_at(pos) else {
|
||||
return Err(DocError::BadPath(pos.path.to_string()));
|
||||
}
|
||||
};
|
||||
let is_dest_empty = dest_para.is_empty();
|
||||
let table_para = table_style_para(self, pos);
|
||||
let destination_shading = self.styles.resolve_para_in(&dest_para.props, table_para.as_ref()).shading;
|
||||
let mut parts = frag.parts.clone();
|
||||
if !media_remap.is_empty() {
|
||||
for b in &mut blocks {
|
||||
@@ -1538,6 +1714,7 @@ impl Document {
|
||||
&& let Some(Block::Para(src)) = blocks.first()
|
||||
{
|
||||
let src = src.clone();
|
||||
let src_shading = self.styles.resolve_para(&src.props).shading;
|
||||
let target = self.para_mut(pos.story, &pos.path)?;
|
||||
let tail = target.split_off(pos.off)?;
|
||||
let added = src.len();
|
||||
@@ -1548,6 +1725,13 @@ impl Document {
|
||||
target.append(src);
|
||||
target.append(tail);
|
||||
target.props = keep;
|
||||
// Paragraph shading is the pasted text's background (HTML container backgrounds
|
||||
// become paragraph shading), so an empty unshaded destination takes the source's.
|
||||
// A paste without a paragraph mark into an existing paragraph leaves the
|
||||
// destination paragraph's formatting unchanged (#6157).
|
||||
if is_dest_empty && destination_shading.is_none() {
|
||||
target.props.shading = src_shading;
|
||||
}
|
||||
target.section = sect;
|
||||
return Ok(Pos { off: pos.off + added, ..pos.clone() });
|
||||
}
|
||||
@@ -1559,13 +1743,28 @@ impl Document {
|
||||
let mut idx = left.last() + 1;
|
||||
match first {
|
||||
Block::Para(p) => {
|
||||
let src_shading = self.styles.resolve_para(&p.props).shading;
|
||||
let l = self.para_mut(pos.story, &left)?;
|
||||
let keep = l.props.clone();
|
||||
let keep_empty = keep.is_empty();
|
||||
let keep_shading = keep.shading;
|
||||
let mut p2 = p;
|
||||
let pprops = p2.props.clone();
|
||||
p2.section = None;
|
||||
l.append(p2);
|
||||
l.props = if keep.is_empty() { pprops } else { keep };
|
||||
l.props = if keep_empty { pprops } else { keep };
|
||||
if destination_shading.is_some() {
|
||||
// When adopting a source paragraph style into an empty destination,
|
||||
// preserve the destination background as a direct override so the
|
||||
// source style's shading does not win over it (#6157).
|
||||
if keep_empty && l.props.style.is_some() {
|
||||
l.props.shading = destination_shading;
|
||||
} else {
|
||||
l.props.shading = keep_shading;
|
||||
}
|
||||
} else if is_dest_empty && !keep_empty && l.props.shading.is_none() {
|
||||
l.props.shading = src_shading;
|
||||
}
|
||||
}
|
||||
t @ Block::Table(_) => {
|
||||
self.insert_block(pos.story, &left.with_last(idx), t)?;
|
||||
@@ -1606,6 +1805,13 @@ impl Document {
|
||||
}
|
||||
}
|
||||
|
||||
/// Paragraph formatting of the table style enclosing `pos`, if any.
|
||||
fn table_style_para(doc: &Document, pos: &Pos) -> Option<ParaProps> {
|
||||
let (tp, _, _) = pos.path.cell()?;
|
||||
let id = doc.table(pos.story, &tp)?.props.style.as_deref()?;
|
||||
Some(doc.styles.table_style(id)?.para.clone())
|
||||
}
|
||||
|
||||
/// Take the drop cap (and its options) off a paragraph's properties.
|
||||
fn clear_drop_cap(props: &mut crate::props::ParaProps) {
|
||||
props.drop_cap = None;
|
||||
|
||||
@@ -118,6 +118,182 @@ fn copy_paste_round_trip() {
|
||||
assert!(d.plain_text(StoryRef::Body).starts_with("XYalpha"));
|
||||
}
|
||||
|
||||
/// Shading a pasted paragraph gets from its style is kept as direct shading on an empty unshaded destination (#6157).
|
||||
#[test]
|
||||
fn paste_keeps_source_style_shading() {
|
||||
let mut d = doc(&[""]);
|
||||
Arc::make_mut(&mut d.styles).upsert(crate::Style {
|
||||
id: "SourceShaded".into(),
|
||||
name: "Source Shaded".into(),
|
||||
kind: crate::StyleKind::Paragraph,
|
||||
based_on: Some("Normal".into()),
|
||||
para: ParaProps { shading: Some(crate::Rgb(0x33, 0x33, 0x33)), ..Default::default() },
|
||||
..Default::default()
|
||||
});
|
||||
let mut src = Paragraph::with_text("X", CharProps::default());
|
||||
src.props.style = Some("SourceShaded".into());
|
||||
let one = Fragment { blocks: vec![Block::Para(src)], ..Default::default() };
|
||||
d.insert_fragment(&Pos::body(0, 0), &one).unwrap();
|
||||
let p = d.para(StoryRef::Body, &Path::top(0)).unwrap();
|
||||
assert_eq!(p.props.shading, Some(crate::Rgb(0x33, 0x33, 0x33)), "source style shading is kept on empty destination");
|
||||
}
|
||||
|
||||
/// A one-line paste without a paragraph mark into a non-empty paragraph leaves destination shading unshaded (#6157).
|
||||
#[test]
|
||||
fn single_block_paste_into_non_empty_paragraph_leaves_destination_unshaded() {
|
||||
let mut d = doc(&["plain"]);
|
||||
Arc::make_mut(&mut d.styles).upsert(crate::Style {
|
||||
id: "SourceShaded".into(),
|
||||
name: "Source Shaded".into(),
|
||||
kind: crate::StyleKind::Paragraph,
|
||||
based_on: Some("Normal".into()),
|
||||
para: ParaProps { shading: Some(crate::Rgb(0x33, 0x33, 0x33)), ..Default::default() },
|
||||
..Default::default()
|
||||
});
|
||||
let mut src = Paragraph::with_text("X", CharProps::default());
|
||||
src.props.style = Some("SourceShaded".into());
|
||||
let one = Fragment { blocks: vec![Block::Para(src)], ..Default::default() };
|
||||
d.insert_fragment(&Pos::body(0, 5), &one).unwrap();
|
||||
let p = d.para(StoryRef::Body, &Path::top(0)).unwrap();
|
||||
assert_eq!(p.props.shading, None, "one-line paste without a paragraph mark must not shade destination paragraph");
|
||||
}
|
||||
|
||||
/// An empty destination with direct properties keeps the first pasted paragraph's style shading (#6157).
|
||||
#[test]
|
||||
fn multi_block_paste_keeps_source_style_shading() {
|
||||
let mut d = doc(&[""]);
|
||||
Arc::make_mut(&mut d.styles).upsert(crate::Style {
|
||||
id: "SourceShaded".into(),
|
||||
name: "Source Shaded".into(),
|
||||
kind: crate::StyleKind::Paragraph,
|
||||
based_on: Some("Normal".into()),
|
||||
para: ParaProps { shading: Some(crate::Rgb(0x33, 0x33, 0x33)), ..Default::default() },
|
||||
..Default::default()
|
||||
});
|
||||
let mut a = Paragraph::with_text("A", CharProps::default());
|
||||
a.props.style = Some("SourceShaded".into());
|
||||
let b = Paragraph::with_text("B", CharProps::default());
|
||||
let frag = Fragment { blocks: vec![Block::Para(a), Block::Para(b)], ..Default::default() };
|
||||
d.para_mut(StoryRef::Body, &Path::top(0)).unwrap().props.align = Some(crate::props::Align::Center);
|
||||
d.insert_fragment(&Pos::body(0, 0), &frag).unwrap();
|
||||
let p = d.para(StoryRef::Body, &Path::top(0)).unwrap();
|
||||
assert_eq!(p.props.shading, Some(crate::Rgb(0x33, 0x33, 0x33)), "first pasted paragraph keeps its style shading");
|
||||
}
|
||||
|
||||
/// The destination's resolved (default) shading is not replaced by the source's direct shading (#6157).
|
||||
#[test]
|
||||
fn multi_block_paste_keeps_destination_default_shading() {
|
||||
let mut d = doc(&["plain"]);
|
||||
Arc::make_mut(&mut d.styles).default_para.shading = Some(crate::Rgb(0x22, 0x22, 0x22));
|
||||
let mut a = Paragraph::with_text("A", CharProps::default());
|
||||
a.props.shading = Some(crate::Rgb(0x11, 0x11, 0x11));
|
||||
let b = Paragraph::with_text("B", CharProps::default());
|
||||
let frag = Fragment { blocks: vec![Block::Para(a), Block::Para(b)], ..Default::default() };
|
||||
d.insert_fragment(&Pos::body(0, 5), &frag).unwrap();
|
||||
let p = d.para(StoryRef::Body, &Path::top(0)).unwrap();
|
||||
assert_eq!(p.props.shading, None, "source direct shading must not override the destination default");
|
||||
assert_eq!(d.styles.resolve_para(&p.props).shading, Some(crate::Rgb(0x22, 0x22, 0x22)));
|
||||
}
|
||||
|
||||
/// An empty destination with inherited shading keeps its shading when pasting a differently shaded source style (#6157).
|
||||
#[test]
|
||||
fn multi_block_paste_keeps_destination_inherited_shading_over_source_style() {
|
||||
let mut d = doc(&["plain"]);
|
||||
Arc::make_mut(&mut d.styles).default_para.shading = Some(crate::Rgb(0x22, 0x22, 0x22));
|
||||
Arc::make_mut(&mut d.styles).upsert(crate::Style {
|
||||
id: "SourceShaded".into(),
|
||||
name: "Source Shaded".into(),
|
||||
kind: crate::StyleKind::Paragraph,
|
||||
based_on: Some("Normal".into()),
|
||||
para: ParaProps { shading: Some(crate::Rgb(0x33, 0x33, 0x33)), ..Default::default() },
|
||||
..Default::default()
|
||||
});
|
||||
let mut a = Paragraph::with_text("A", CharProps::default());
|
||||
a.props.style = Some("SourceShaded".into());
|
||||
let b = Paragraph::with_text("B", CharProps::default());
|
||||
let frag = Fragment { blocks: vec![Block::Para(a), Block::Para(b)], ..Default::default() };
|
||||
d.insert_fragment(&Pos::body(0, 5), &frag).unwrap();
|
||||
let p = d.para(StoryRef::Body, &Path::top(0)).unwrap();
|
||||
assert_eq!(p.props.shading, Some(crate::Rgb(0x22, 0x22, 0x22)), "destination inherited shading is preserved as a direct override");
|
||||
assert_eq!(
|
||||
d.styles.resolve_para(&p.props).shading,
|
||||
Some(crate::Rgb(0x22, 0x22, 0x22)),
|
||||
"resolved shading must match the destination background, not the source style"
|
||||
);
|
||||
}
|
||||
|
||||
/// Multi-block paste into an empty unshaded destination keeps a shaded source style without
|
||||
/// duplicating its color into direct paragraph shading (#6157).
|
||||
#[test]
|
||||
fn multi_block_paste_into_empty_destination_keeps_source_style_without_direct_shading() {
|
||||
let mut d = doc(&[""]);
|
||||
Arc::make_mut(&mut d.styles).upsert(crate::Style {
|
||||
id: "SourceShaded".into(),
|
||||
name: "Source Shaded".into(),
|
||||
kind: crate::StyleKind::Paragraph,
|
||||
based_on: Some("Normal".into()),
|
||||
para: ParaProps { shading: Some(crate::Rgb(0x33, 0x33, 0x33)), ..Default::default() },
|
||||
..Default::default()
|
||||
});
|
||||
let mut a = Paragraph::with_text("A", CharProps::default());
|
||||
a.props.style = Some("SourceShaded".into());
|
||||
let mut b = Paragraph::with_text("B", CharProps::default());
|
||||
b.props.style = Some("SourceShaded".into());
|
||||
let frag = Fragment { blocks: vec![Block::Para(a), Block::Para(b)], ..Default::default() };
|
||||
d.insert_fragment(&Pos::body(0, 0), &frag).unwrap();
|
||||
for idx in [0, 1] {
|
||||
let p = d.para(StoryRef::Body, &Path::top(idx)).unwrap();
|
||||
assert_eq!(p.props.style.as_deref(), Some("SourceShaded"));
|
||||
assert_eq!(p.props.shading, None, "paragraph {idx} inherits from its style without redundant direct shading");
|
||||
assert_eq!(d.styles.resolve_para(&p.props).shading, Some(crate::Rgb(0x33, 0x33, 0x33)));
|
||||
}
|
||||
}
|
||||
|
||||
/// Paragraph shading inherited from an enclosing table's style is preserved as destination shading (#6157).
|
||||
#[test]
|
||||
fn paste_keeps_destination_table_style_shading() {
|
||||
let mut d = doc(&["outside"]);
|
||||
Arc::make_mut(&mut d.styles).upsert(crate::Style {
|
||||
id: "ShadedGrid".into(),
|
||||
name: "Shaded Grid".into(),
|
||||
kind: crate::StyleKind::Table,
|
||||
para: ParaProps { shading: Some(crate::Rgb(0x22, 0x22, 0x22)), ..Default::default() },
|
||||
..Default::default()
|
||||
});
|
||||
Arc::make_mut(&mut d.styles).upsert(crate::Style {
|
||||
id: "SourceShaded".into(),
|
||||
name: "Source Shaded".into(),
|
||||
kind: crate::StyleKind::Paragraph,
|
||||
based_on: Some("Normal".into()),
|
||||
para: ParaProps { shading: Some(crate::Rgb(0x44, 0x44, 0x44)), ..Default::default() },
|
||||
..Default::default()
|
||||
});
|
||||
let mut t = Table::new(1, 2, 200.0);
|
||||
t.props.style = Some("ShadedGrid".into());
|
||||
d.insert_block(StoryRef::Body, &Path::top(0), Block::Table(t)).unwrap();
|
||||
|
||||
// Single-block paste into cell (0, 0): table-style paragraph shading is not overridden.
|
||||
let mut src = Paragraph::with_text("cell1", CharProps::default());
|
||||
src.props.shading = Some(crate::Rgb(0x1e, 0x1e, 0x1e));
|
||||
let one = Fragment { blocks: vec![Block::Para(src)], ..Default::default() };
|
||||
let cell0 = Pos { story: StoryRef::Body, path: Path(vec![0, 0, 0, 0]), off: 0 };
|
||||
d.insert_fragment(&cell0, &one).unwrap();
|
||||
let p0 = d.para(StoryRef::Body, &cell0.path).unwrap();
|
||||
assert_eq!(p0.props.shading, None);
|
||||
let tp = &d.styles.table_style("ShadedGrid").unwrap().para;
|
||||
assert_eq!(d.styles.resolve_para_in(&p0.props, Some(tp)).shading, Some(crate::Rgb(0x22, 0x22, 0x22)));
|
||||
|
||||
// Multi-block paste with a differently shaded source style into empty cell (0, 1).
|
||||
let mut a = Paragraph::with_text("A", CharProps::default());
|
||||
a.props.style = Some("SourceShaded".into());
|
||||
let b = Paragraph::with_text("B", CharProps::default());
|
||||
let multi = Fragment { blocks: vec![Block::Para(a), Block::Para(b)], ..Default::default() };
|
||||
let cell1 = Pos { story: StoryRef::Body, path: Path(vec![0, 0, 1, 0]), off: 0 };
|
||||
d.insert_fragment(&cell1, &multi).unwrap();
|
||||
let p1 = d.para(StoryRef::Body, &cell1.path).unwrap();
|
||||
assert_eq!(d.styles.resolve_para_in(&p1.props, Some(tp)).shading, Some(crate::Rgb(0x22, 0x22, 0x22)));
|
||||
}
|
||||
|
||||
/// The first paragraph of the deepest cell, following the first table at each level.
|
||||
fn deepest(d: &Document) -> Path {
|
||||
let (mut path, mut blocks) = (Vec::new(), &d.body);
|
||||
@@ -304,6 +480,33 @@ fn fragment_without_parts_never_shows_an_unrelated_story() {
|
||||
assert_eq!(got[2], None, "a header isn't a text box");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fragment_extracts_text_box_stories_in_object_order() {
|
||||
let mut p = Paragraph::new();
|
||||
p.insert_object(0, box_shape(Some(20)), &CharProps::default()).unwrap();
|
||||
p.insert_object(p.text.len(), box_shape(Some(10)), &CharProps::default()).unwrap();
|
||||
let mut parts = BTreeMap::new();
|
||||
parts.insert(
|
||||
10,
|
||||
crate::Part {
|
||||
kind: PartKind::TextBox,
|
||||
blocks: vec![para_block(Paragraph::with_text("Second", CharProps::default()))],
|
||||
body: Default::default(),
|
||||
},
|
||||
);
|
||||
parts.insert(
|
||||
20,
|
||||
crate::Part {
|
||||
kind: PartKind::TextBox,
|
||||
blocks: vec![para_block(Paragraph::with_text("First", CharProps::default()))],
|
||||
body: Default::default(),
|
||||
},
|
||||
);
|
||||
let f = Fragment { blocks: vec![Block::Para(p)], parts, ..Default::default() };
|
||||
assert_eq!(f.plain_text(), "First\nSecond");
|
||||
assert_eq!(f.clipboard_text(), "First\nSecond");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn self_nested_text_box_paste_is_bounded() {
|
||||
let mut d = doc(&["x"]);
|
||||
@@ -1023,3 +1226,130 @@ fn split_paragraph_keeps_the_drop_cap_on_the_first_paragraph_only() {
|
||||
d.split_paragraph(&Pos::body(0, 0)).unwrap();
|
||||
assert_eq!((drop_cap(&d, 0), drop_cap(&d, 1)), (cap.clone(), cap));
|
||||
}
|
||||
|
||||
/// #5906: Copying a range spanning from inside a table to an outside paragraph preserves the table.
|
||||
#[test]
|
||||
fn copy_range_preserves_table_structure_across_blocks() {
|
||||
let mut d = Document::new();
|
||||
let mut t = Table::new(2, 2, 200.0);
|
||||
t.rows[0].cells[0].blocks = vec![para_block(Paragraph::with_text("A1", CharProps::default()))];
|
||||
t.rows[0].cells[1].blocks = vec![para_block(Paragraph::with_text("B1", CharProps::default()))];
|
||||
t.rows[1].cells[0].blocks = vec![para_block(Paragraph::with_text("A2", CharProps::default()))];
|
||||
t.rows[1].cells[1].blocks = vec![para_block(Paragraph::with_text("B2", CharProps::default()))];
|
||||
d.body = vec![Arc::new(Block::Table(t)), Arc::new(Block::Para(Paragraph::with_text("Trailing", CharProps::default())))];
|
||||
let start = d.start_of(StoryRef::Body);
|
||||
let end = d.end_of(StoryRef::Body);
|
||||
let frag = d.copy_range(&start, &end);
|
||||
assert_eq!(frag.blocks.len(), 2, "expected table and trailing paragraph, got {:?}", frag.blocks);
|
||||
let Block::Table(tbl) = &frag.blocks[0] else { panic!("first block should be Table") };
|
||||
assert_eq!(tbl.rows.len(), 2, "copied table row count");
|
||||
assert_eq!(tbl.cols(), 2, "copied table col count");
|
||||
let c00 = tbl.rows[0].cells[0].blocks.first().and_then(|b| match &**b {
|
||||
Block::Para(p) => Some(p.text.as_str()),
|
||||
_ => None,
|
||||
});
|
||||
assert_eq!(c00, Some("A1"), "cell (0, 0) text");
|
||||
let Block::Para(trail) = &frag.blocks[1] else { panic!("second block should be Para") };
|
||||
assert_eq!(trail.text.as_str(), "Trailing");
|
||||
}
|
||||
|
||||
/// #5906: Copying a range enclosing a table between paragraphs preserves the table block.
|
||||
#[test]
|
||||
fn copy_range_preserves_table_between_paragraphs() {
|
||||
let mut d = Document::new();
|
||||
let mut t = Table::new(2, 2, 200.0);
|
||||
t.rows[0].cells[0].blocks = vec![para_block(Paragraph::with_text("A1", CharProps::default()))];
|
||||
t.rows[0].cells[1].blocks = vec![para_block(Paragraph::with_text("B1", CharProps::default()))];
|
||||
t.rows[1].cells[0].blocks = vec![para_block(Paragraph::with_text("A2", CharProps::default()))];
|
||||
t.rows[1].cells[1].blocks = vec![para_block(Paragraph::with_text("B2", CharProps::default()))];
|
||||
d.body = vec![
|
||||
Arc::new(Block::Para(Paragraph::with_text("Intro", CharProps::default()))),
|
||||
Arc::new(Block::Table(t)),
|
||||
Arc::new(Block::Para(Paragraph::with_text("Outro", CharProps::default()))),
|
||||
];
|
||||
let start = Pos { story: StoryRef::Body, path: Path(vec![0]), off: 0 };
|
||||
let end = d.end_of(StoryRef::Body);
|
||||
let frag = d.copy_range(&start, &end);
|
||||
assert_eq!(frag.blocks.len(), 3, "expected intro, table, and outro, got {:?}", frag.blocks);
|
||||
assert!(matches!(&frag.blocks[0], Block::Para(p) if p.text == "Intro"));
|
||||
let Block::Table(tbl) = &frag.blocks[1] else { panic!("second block should be Table") };
|
||||
assert_eq!(tbl.rows.len(), 2, "copied table row count");
|
||||
assert_eq!(tbl.cols(), 2, "copied table col count");
|
||||
assert!(matches!(&frag.blocks[2], Block::Para(p) if p.text == "Outro"));
|
||||
}
|
||||
|
||||
/// #5906: Copy range across cells inside a table preserves all traversed paragraphs in linear order.
|
||||
#[test]
|
||||
fn copy_range_linear_cross_cells_preserves_all_traversed_paragraphs() {
|
||||
let mut d = Document::new();
|
||||
let mut t = Table::new(3, 3, 300.0);
|
||||
for (r, row) in t.rows.iter_mut().enumerate() {
|
||||
for (c, cell) in row.cells.iter_mut().enumerate() {
|
||||
cell.blocks = vec![para_block(Paragraph::with_text(&format!("R{r}C{c}"), CharProps::default()))];
|
||||
}
|
||||
}
|
||||
d.body = vec![Arc::new(Block::Table(t))];
|
||||
// Start at (0, 1) offset 1 ("0C1"), end at (1, 1) offset 3 ("R1C")
|
||||
let a = Pos { story: StoryRef::Body, path: Path(vec![0, 0, 1, 0]), off: 1 };
|
||||
let b = Pos { story: StoryRef::Body, path: Path(vec![0, 1, 1, 0]), off: 3 };
|
||||
let frag = d.copy_range(&a, &b);
|
||||
assert_eq!(frag.blocks.len(), 4, "all 4 traversed cells in linear order");
|
||||
let texts: Vec<&str> = frag
|
||||
.blocks
|
||||
.iter()
|
||||
.filter_map(|b| match b {
|
||||
Block::Para(p) => Some(p.text.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(texts, vec!["0C1", "R0C2", "R1C0", "R1C"]);
|
||||
}
|
||||
|
||||
/// #5906: Copy range from paragraph before table into non-corner cell preserves all traversed text in linear order.
|
||||
#[test]
|
||||
fn copy_range_from_para_before_table_to_non_corner_cell() {
|
||||
let mut d = Document::new();
|
||||
let mut t = Table::new(3, 3, 300.0);
|
||||
for (r, row) in t.rows.iter_mut().enumerate() {
|
||||
for (c, cell) in row.cells.iter_mut().enumerate() {
|
||||
cell.blocks = vec![para_block(Paragraph::with_text(&format!("R{r}C{c}"), CharProps::default()))];
|
||||
}
|
||||
}
|
||||
d.body = vec![Arc::new(Block::Para(Paragraph::with_text("LeadingText", CharProps::default()))), Arc::new(Block::Table(t))];
|
||||
let a = Pos { story: StoryRef::Body, path: Path(vec![0]), off: 7 };
|
||||
let b = Pos { story: StoryRef::Body, path: Path(vec![1, 1, 1, 0]), off: 3 };
|
||||
let frag = d.copy_range(&a, &b);
|
||||
let texts: Vec<&str> = frag
|
||||
.blocks
|
||||
.iter()
|
||||
.filter_map(|b| match b {
|
||||
Block::Para(p) => Some(p.text.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(texts, vec!["Text", "R0C0", "R0C1", "R0C2", "R1C0", "R1C"]);
|
||||
}
|
||||
|
||||
/// #5906: Copy range from non-corner cell into following paragraph preserves all traversed text in linear order.
|
||||
#[test]
|
||||
fn copy_range_from_cell_into_para_after_table() {
|
||||
let mut d = Document::new();
|
||||
let mut t = Table::new(2, 2, 200.0);
|
||||
t.rows[0].cells[0].blocks = vec![para_block(Paragraph::with_text("Hello", CharProps::default()))];
|
||||
t.rows[0].cells[1].blocks = vec![para_block(Paragraph::with_text("World", CharProps::default()))];
|
||||
t.rows[1].cells[0].blocks = vec![para_block(Paragraph::with_text("Foo", CharProps::default()))];
|
||||
t.rows[1].cells[1].blocks = vec![para_block(Paragraph::with_text("Bar", CharProps::default()))];
|
||||
d.body = vec![Arc::new(Block::Table(t)), Arc::new(Block::Para(Paragraph::with_text("Trailing", CharProps::default())))];
|
||||
let a = Pos { story: StoryRef::Body, path: Path(vec![0, 0, 1, 0]), off: 1 };
|
||||
let b = Pos { story: StoryRef::Body, path: Path(vec![1]), off: 5 };
|
||||
let frag = d.copy_range(&a, &b);
|
||||
let texts: Vec<&str> = frag
|
||||
.blocks
|
||||
.iter()
|
||||
.filter_map(|b| match b {
|
||||
Block::Para(p) => Some(p.text.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(texts, vec!["orld", "Foo", "Bar", "Trail"]);
|
||||
}
|
||||
|
||||
@@ -118,8 +118,13 @@ impl ResolvedChar {
|
||||
font_cs: c.font_cs.clone().or_else(|| c.font.clone()).unwrap_or_else(|| crate::styles::BODY_FONT.to_string()),
|
||||
font_ea: c.font_ea.clone(),
|
||||
size_cs: c.size_cs.or(c.size).unwrap_or(crate::props::DEFAULT_FONT_SIZE).clamp(1.0, 1638.0),
|
||||
bold_cs: c.bold_cs.or(c.bold).unwrap_or(false),
|
||||
italic_cs: c.italic_cs.or(c.italic).unwrap_or(false),
|
||||
// A run marked complex script (`w:cs`) is bold and italic only by `w:bCs` and `w:iCs`:
|
||||
// Word draws Thai with `<w:b/><w:cs/>` and no `w:bCs` upright and plain (measured in
|
||||
// Word for Windows). Other runs, including those no DOCX marked, still borrow the
|
||||
// Latin values. The size keeps borrowing `w:sz` until generated styles carry a
|
||||
// `w:szCs` (#4197).
|
||||
bold_cs: c.bold_cs.or(c.bold.filter(|_| c.cs != Some(true))).unwrap_or(false),
|
||||
italic_cs: c.italic_cs.or(c.italic.filter(|_| c.cs != Some(true))).unwrap_or(false),
|
||||
}
|
||||
}
|
||||
/// The formatting complex-script text in this run is drawn with: the complex-script font,
|
||||
|
||||
@@ -142,6 +142,34 @@ fn complex_script_direct_properties_leave_latin_defaults_inherited() {
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn complex_script_runs_take_bold_and_italic_only_from_bcs_and_ics() {
|
||||
// Word draws Thai marked `w:cs` with `<w:b/><w:i/>` and no `w:bCs`/`w:iCs` neither bold nor
|
||||
// italic, through a style too; a run not marked `w:cs`, as older writers leave Hebrew, still
|
||||
// borrows the Latin values (Word draws such Hebrew bold). The Latin text of every run keeps
|
||||
// `w:b` and `w:i`. Measured in Word for Windows.
|
||||
let styles = r#"
|
||||
<w:style w:type="paragraph" w:styleId="LatinBold"><w:name w:val="LatinBold"/><w:rPr><w:b/><w:i/></w:rPr></w:style>
|
||||
<w:style w:type="paragraph" w:styleId="BothBold"><w:name w:val="BothBold"/><w:rPr><w:bCs/><w:iCs/></w:rPr></w:style>"#;
|
||||
let cases = [
|
||||
(r#"<w:b/><w:i/><w:cs/>"#, "", false),
|
||||
(r#"<w:cs/>"#, r#"<w:pStyle w:val="LatinBold"/>"#, false),
|
||||
(r#"<w:b/><w:i/><w:cs/>"#, r#"<w:pStyle w:val="BothBold"/>"#, true),
|
||||
(r#"<w:b/><w:bCs/><w:i/><w:iCs/><w:cs/>"#, "", true),
|
||||
(r#"<w:b/><w:i/>"#, "", true),
|
||||
];
|
||||
for (run, style, complex) in cases {
|
||||
check_generations(&package(run, "", styles, style), |d| {
|
||||
let p = paragraph(d);
|
||||
let c = d.styles.resolve_char(p.props.style.as_deref(), &p.runs[0].props);
|
||||
let cs = c.complex();
|
||||
assert_eq!((cs.bold, cs.italic), (complex, complex), "{run} {style}");
|
||||
let latin = run.contains("<w:b/>") || style.contains("LatinBold");
|
||||
assert_eq!((c.bold, c.italic), (latin, latin), "Latin text: {run} {style}");
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tracked_formatting_keeps_independent_complex_script_values() {
|
||||
let defaults = r#"<w:szCs w:val="36"/><w:bCs/><w:iCs/>"#;
|
||||
|
||||
@@ -2124,9 +2124,10 @@ fn rotated_ole_objects_round_trip() {
|
||||
let body = text(&unzip(&out), "word/document.xml");
|
||||
assert_eq!(attr_values(&body, "a:xfrm", "rot"), ["5400000"]);
|
||||
assert_eq!(attr_values(&body, "a:xfrm", "flipH"), ["1"]);
|
||||
// 72 × 36 pt turned 90°: 18 pt narrower each side, 18 pt taller each side.
|
||||
assert_eq!(attr_values(&body, "wp:effectExtent", "l"), ["-228600"]);
|
||||
assert_eq!(attr_values(&body, "wp:effectExtent", "t"), ["228600"]);
|
||||
// 72 × 36 pt turned 90°: Word measures that against the frame turned with it, so a quarter
|
||||
// turn adds no effect extent.
|
||||
assert_eq!(attr_values(&body, "wp:effectExtent", "l"), ["0"]);
|
||||
assert_eq!(attr_values(&body, "wp:effectExtent", "t"), ["0"]);
|
||||
let back = wordcraft_docx::read(&out).unwrap();
|
||||
let o = ¶s(&back)[0].objects[0];
|
||||
assert!(matches!(o, InlineObject::Image { ole: Some(_), .. }), "{o:?}");
|
||||
@@ -3316,7 +3317,7 @@ fn native_ink_markup_limit_does_not_write_a_dangling_reference() {
|
||||
fn native_ink_preserves_inner_transform_and_rotation_padding_on_unrelated_saves() {
|
||||
let mut files = unzip(&ink_docx(false, false));
|
||||
let body = text(&files, "word/document.xml")
|
||||
.replace("<wp:docPr", r#"<wp:effectExtent l="55468" t="512668" r="55468" b="512668"/><wp:docPr"#)
|
||||
.replace("<wp:docPr", r#"<wp:effectExtent l="512668" t="55468" r="512668" b="55468"/><wp:docPr"#)
|
||||
.replace("<q:xfrm>", r#"<q:xfrm rot="2700000">"#)
|
||||
.replace(r#"<a:off x="0" y="0"/><a:ext cx="1828800" cy="914400"/>"#, r#"<a:off x="127000" y="254000"/><a:ext cx="914400" cy="457200"/>"#);
|
||||
files.insert("word/document.xml".into(), body.into_bytes());
|
||||
|
||||
@@ -64,7 +64,7 @@ fn save(doc: &wordcraft_doc::Document) -> BTreeMap<String, Vec<u8>> {
|
||||
}
|
||||
|
||||
const SETTINGS: &str = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<w:settings xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml" xmlns:w15="http://schemas.microsoft.com/office/word/2012/wordml" mc:Ignorable="w14 w15"><w:zoom w:percent="120"/><w:removePersonalInformation/><w:removeDateAndTime/><w:proofState w:spelling="clean" w:grammar="clean"/><w:mailMerge><w:mainDocumentType w:val="formLetters"/><w:dataSource r:id="rId9"/></w:mailMerge><w:trackRevisions/><w:defaultTabStop w:val="708"/><w:hyphenationZone w:val="425"/><w:characterSpacingControl w:val="doNotCompress"/><w:compat><w:compatSetting w:name="compatibilityMode" w:uri="http://schemas.microsoft.com/office/word" w:val="15"/><w:compatSetting w:name="overrideTableStyleFontSizeAndJustification" w:uri="http://schemas.microsoft.com/office/word" w:val="1"/><w:compatSetting w:name="enableOpenTypeFeatures" w:uri="http://schemas.microsoft.com/office/word" w:val="1"/></w:compat><w:docVars><w:docVar w:name="ClauseSet" w:val="B"/></w:docVars><w:rsids><w:rsidRoot w:val="00A1B2C3"/><w:rsid w:val="00A1B2C3"/></w:rsids><m:mathPr><m:mathFont m:val="Cambria Math"/><m:smallFrac m:val="0"/></m:mathPr><w:themeFontLang w:val="pl-PL"/><w:decimalSymbol w:val=","/><w:listSeparator w:val=";"/><w14:docId w14:val="1A2B3C4D"/></w:settings>"#;
|
||||
<w:settings xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml" xmlns:w15="http://schemas.microsoft.com/office/word/2012/wordml" mc:Ignorable="w14 w15"><w:zoom w:percent="120"/><w:removePersonalInformation/><w:removeDateAndTime/><w:proofState w:spelling="clean" w:grammar="clean"/><w:trackRevisions/><w:defaultTabStop w:val="708"/><w:hyphenationZone w:val="425"/><w:characterSpacingControl w:val="doNotCompress"/><w:compat><w:compatSetting w:name="compatibilityMode" w:uri="http://schemas.microsoft.com/office/word" w:val="15"/><w:compatSetting w:name="overrideTableStyleFontSizeAndJustification" w:uri="http://schemas.microsoft.com/office/word" w:val="1"/><w:compatSetting w:name="enableOpenTypeFeatures" w:uri="http://schemas.microsoft.com/office/word" w:val="1"/></w:compat><w:docVars><w:docVar w:name="ClauseSet" w:val="B"/></w:docVars><w:rsids><w:rsidRoot w:val="00A1B2C3"/><w:rsid w:val="00A1B2C3"/></w:rsids><m:mathPr><m:mathFont m:val="Cambria Math"/><m:smallFrac m:val="0"/></m:mathPr><w:themeFontLang w:val="pl-PL"/><w:decimalSymbol w:val=","/><w:listSeparator w:val=";"/><w14:docId w14:val="1A2B3C4D"/></w:settings>"#;
|
||||
|
||||
fn pos(s: &str, needle: &str) -> usize {
|
||||
s.find(needle).unwrap_or_else(|| panic!("{needle} missing from {s}"))
|
||||
|
||||
@@ -66,7 +66,15 @@ const SETTINGS: &str = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?
|
||||
<w:settings xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml" xmlns:w15="http://schemas.microsoft.com/office/word/2012/wordml" mc:Ignorable="w14 w15"><w:zoom w:percent="120"/><w:removePersonalInformation/><w:removeDateAndTime/><w:proofState w:spelling="clean" w:grammar="clean"/><w:mailMerge><w:mainDocumentType w:val="formLetters"/><w:dataSource r:id="rId9"/></w:mailMerge><w:trackRevisions/><w:defaultTabStop w:val="708"/><w:hyphenationZone w:val="425"/><w:characterSpacingControl w:val="doNotCompress"/><w:compat><w:compatSetting w:name="compatibilityMode" w:uri="http://schemas.microsoft.com/office/word" w:val="15"/><w:compatSetting w:name="overrideTableStyleFontSizeAndJustification" w:uri="http://schemas.microsoft.com/office/word" w:val="1"/><w:compatSetting w:name="enableOpenTypeFeatures" w:uri="http://schemas.microsoft.com/office/word" w:val="1"/></w:compat><w:docVars><w:docVar w:name="ClauseSet" w:val="B"/></w:docVars><w:rsids><w:rsidRoot w:val="00A1B2C3"/><w:rsid w:val="00A1B2C3"/></w:rsids><m:mathPr><m:mathFont m:val="Cambria Math"/><m:smallFrac m:val="0"/></m:mathPr><w:themeFontLang w:val="pl-PL"/><w:decimalSymbol w:val=","/><w:listSeparator w:val=";"/><w14:docId w14:val="1A2B3C4D"/></w:settings>"#;
|
||||
|
||||
fn with_settings(settings: &str) -> Vec<u8> {
|
||||
package("<w:p><w:r><w:t>Text</w:t></w:r></w:p>", &[("rId1", &format!("{REL}/settings"), "settings.xml")], &[], &[("word/settings.xml", settings)])
|
||||
let sources = format!(
|
||||
r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId9" Type="{REL}/mailMergeSource" Target="file:///__wordcraft_missing_source__/letters.xlsx" TargetMode="External"/></Relationships>"#
|
||||
);
|
||||
package(
|
||||
"<w:p><w:r><w:t>Text</w:t></w:r></w:p>",
|
||||
&[("rId1", &format!("{REL}/settings"), "settings.xml")],
|
||||
&[],
|
||||
&[("word/settings.xml", settings), ("word/_rels/settings.xml.rels", &sources)],
|
||||
)
|
||||
}
|
||||
|
||||
fn pos(s: &str, needle: &str) -> usize {
|
||||
@@ -97,11 +105,22 @@ fn unmodelled_settings_survive_a_save_and_owned_ones_follow_the_model() {
|
||||
] {
|
||||
assert!(s.contains(kept), "{kept} lost: {s}");
|
||||
}
|
||||
// Owned: Track Changes was turned off; one compatibility mode; the mail merge source (a
|
||||
// relationship that isn't carried) is dropped rather than left dangling.
|
||||
// Owned: Track Changes was turned off; one compatibility mode. Mail merge keeps its external
|
||||
// source relationship.
|
||||
assert!(!s.contains("trackRevisions"), "{s}");
|
||||
assert_eq!(s.matches("compatibilityMode").count(), 1, "{s}");
|
||||
assert!(!s.contains("mailMerge") && !s.contains("rId9"), "{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}");
|
||||
// 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}");
|
||||
@@ -123,6 +142,37 @@ fn unmodelled_settings_survive_a_save_and_owned_ones_follow_the_model() {
|
||||
assert_eq!(text(&save(&again), "word/settings.xml"), s);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changed_zoom_survives_merged_settings_and_reads_back_as_page_width() {
|
||||
let old_zoom = r#"<w:zoom w:percent="120"/>"#;
|
||||
let updated_zoom = r#"<w:zoom w:val="bestFit" w:percent="145"/>"#;
|
||||
for original in [SETTINGS.to_string(), SETTINGS.replace(old_zoom, "")] {
|
||||
let mut doc = wordcraft_docx::read(&with_settings(&original)).unwrap();
|
||||
assert!(doc.passthrough.contains_key("wordcraft:settings.orig"));
|
||||
doc.settings.zoom = Some(wordcraft_doc::Zoom { percent: 145, fit: Some(wordcraft_doc::ZoomFit::PageWidth) });
|
||||
let bytes = wordcraft_docx::write(&doc).unwrap();
|
||||
let settings = text(&unzip(&bytes), "word/settings.xml");
|
||||
assert_eq!(settings.matches("<w:zoom ").count(), 1, "{settings}");
|
||||
assert!(settings.contains(updated_zoom), "{settings}");
|
||||
// The retained root and unrelated child bytes still belong to the original file.
|
||||
let root_end = original.find("><w:").unwrap() + 1;
|
||||
assert!(settings.starts_with(&original[..root_end]), "{settings}");
|
||||
for kept in [
|
||||
r#"<w:proofState w:spelling="clean" w:grammar="clean"/>"#,
|
||||
r#"<w:docVars><w:docVar w:name="ClauseSet" w:val="B"/></w:docVars>"#,
|
||||
r#"<w:rsids><w:rsidRoot w:val="00A1B2C3"/><w:rsid w:val="00A1B2C3"/></w:rsids>"#,
|
||||
] {
|
||||
assert!(settings.contains(kept), "{kept} lost: {settings}");
|
||||
}
|
||||
assert!(pos(&settings, "<w:zoom ") < pos(&settings, "<w:proofState"));
|
||||
let again = wordcraft_docx::read(&bytes).unwrap();
|
||||
let zoom = again.settings.zoom.unwrap();
|
||||
assert_eq!(zoom.percent, 145);
|
||||
assert!(matches!(zoom.fit, Some(wordcraft_doc::ZoomFit::PageWidth)));
|
||||
assert_eq!(text(&save(&again), "word/settings.xml"), settings);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_written_by_wordcraft_keep_no_original() {
|
||||
let doc = wordcraft_doc::Document::new();
|
||||
|
||||
@@ -16,6 +16,8 @@ test-support = []
|
||||
|
||||
[dependencies]
|
||||
craft-mime.workspace = true
|
||||
craft-keymap.workspace = true
|
||||
craft-codepage.workspace = true
|
||||
wordcraft-geom = { workspace = true, features = ["image"] }
|
||||
wordcraft-doc = { workspace = true }
|
||||
wordcraft-fonts = { workspace = true }
|
||||
|
||||
@@ -33,6 +33,7 @@ pub mod packs;
|
||||
pub mod page;
|
||||
pub mod para;
|
||||
pub mod paste;
|
||||
pub mod paste_cells;
|
||||
pub mod phonetic;
|
||||
pub mod protect;
|
||||
pub mod references;
|
||||
@@ -376,6 +377,12 @@ pub fn type_text_with_lang(s: &mut Session, text: &str, language: Option<&str>)
|
||||
/// right-to-left direction when its first strong letter is RTL, and returns whether content or state
|
||||
/// changed.
|
||||
fn insert_text(s: &mut Session, text: &str, enter: bool, language: Option<&str>) -> Result<InsertEffect, CmdError> {
|
||||
// Formatting Backspace carried over is for typing at the place it was deleted (#6518).
|
||||
if enter {
|
||||
s.drop_stale_carried();
|
||||
} else {
|
||||
s.forget_carried();
|
||||
}
|
||||
let mut props = s.typing_props();
|
||||
if s.sel.is_collapsed() {
|
||||
s.sel = crate::Selection::caret(s.doc.past_field_ends(&s.sel.focus));
|
||||
@@ -437,6 +444,10 @@ fn insert_text(s: &mut Session, text: &str, enter: bool, language: Option<&str>)
|
||||
}
|
||||
}
|
||||
}
|
||||
// Formatting Backspace carried over goes on applying to the text typed after this (#6518).
|
||||
if s.pending_at.is_some() {
|
||||
s.pending_at = Some(at.clone());
|
||||
}
|
||||
s.sel = crate::Selection::caret(at);
|
||||
s.goal_x = None;
|
||||
let content_changed = deletion.content_changed || inserted;
|
||||
|
||||
@@ -35,6 +35,32 @@ pub fn selected_member(s: &Session) -> Option<(Pos, usize, &InlineObject)> {
|
||||
Some((pos, m.index, &c.obj))
|
||||
}
|
||||
|
||||
/// The canvas member whose text box story the caret is in (when no inner object is selected):
|
||||
/// the canvas's position, the member's index and the member.
|
||||
pub fn text_box_member(s: &Session) -> Option<(Pos, usize, &InlineObject)> {
|
||||
if super::objects::selected(s).is_some() {
|
||||
return None;
|
||||
}
|
||||
let StoryRef::Part(id) = s.sel.focus.story else { return None };
|
||||
if !s.doc.parts.get(&id).is_some_and(|p| p.kind == PartKind::TextBox) {
|
||||
return None;
|
||||
}
|
||||
let after = s.doc.text_box_anchor(id)?;
|
||||
let pos = Pos { off: after.off.checked_sub(wordcraft_doc::para::OBJ.len_utf8())?, ..after };
|
||||
let InlineObject::Group { children, canvas: Some(_), .. } = s.doc.para_at(&pos)?.object_at(pos.off)? else {
|
||||
return None;
|
||||
};
|
||||
let (index, c) =
|
||||
children.iter().enumerate().find(|(_, c)| pickable(c) && matches!(&c.obj, InlineObject::Shape { story: Some(sid), .. } if *sid == id))?;
|
||||
Some((pos, index, &c.obj))
|
||||
}
|
||||
|
||||
/// The canvas member object commands act on: one picked with `select.member`, or the text box
|
||||
/// member whose text the caret is in.
|
||||
pub(crate) fn active_member(s: &Session) -> Option<(Pos, usize, &InlineObject)> {
|
||||
selected_member(s).or_else(|| text_box_member(s))
|
||||
}
|
||||
|
||||
/// Whether a member can be picked on its own: a picture, shape or text box that is drawn (a
|
||||
/// group inside a canvas isn't, nor a hidden member).
|
||||
pub fn pickable(c: &GroupChild) -> bool {
|
||||
@@ -295,7 +321,13 @@ pub(crate) fn member_command(s: &mut Session, id: &str, _: &Value) -> Option<Cmd
|
||||
let replaces = (id.starts_with("text.") && id != "text.overtype")
|
||||
|| matches!(
|
||||
id,
|
||||
"edit.paste" | "edit.pasteText" | "edit.pasteMerge" | "edit.pasteSpecial" | "edit.pasteClipboardItem" | "edit.pasteAllClipboard"
|
||||
"edit.paste"
|
||||
| "edit.pasteText"
|
||||
| "edit.pasteMerge"
|
||||
| "edit.pasteNestedTable"
|
||||
| "edit.pasteSpecial"
|
||||
| "edit.pasteClipboardItem"
|
||||
| "edit.pasteAllClipboard"
|
||||
);
|
||||
if !replaces && !matches!(id, "edit.cut" | "edit.copy") {
|
||||
return None;
|
||||
@@ -350,7 +382,7 @@ fn remove_member(s: &mut Session, pos: &Pos, index: usize) -> Result<(), CmdErro
|
||||
/// Move or Resize with a member picked: `x`/`y` (the page point of its top-left, as dragging its
|
||||
/// frame gives it) and the size become its place and size in the canvas. `None`: no member.
|
||||
pub(crate) fn member_bounds(s: &mut Session, v: &Value) -> Option<CmdResult> {
|
||||
let (pos, index, obj) = selected_member(s)?;
|
||||
let (pos, index, obj) = active_member(s)?;
|
||||
let (w0, h0, _) = obj.frame()?;
|
||||
let min = super::objects::min_size(obj);
|
||||
let to = match (p::f32(v, "x"), p::f32(v, "y")) {
|
||||
@@ -381,7 +413,7 @@ pub(crate) fn member_bounds(s: &mut Session, v: &Value) -> Option<CmdResult> {
|
||||
|
||||
/// Nudge with a member picked: it moves inside the canvas. `None`: no member.
|
||||
pub(crate) fn member_nudge(s: &mut Session, dx: f32, dy: f32) -> Option<CmdResult> {
|
||||
let (pos, index, _) = selected_member(s)?;
|
||||
let (pos, index, _) = active_member(s)?;
|
||||
Some(edit_member(s, &pos, index, |_, (sx, sy), c| {
|
||||
c.x = (c.x + dx / sx).clamp(-MAX_SIDE, MAX_SIDE);
|
||||
c.y = (c.y + dy / sy).clamp(-MAX_SIDE, MAX_SIDE);
|
||||
@@ -406,10 +438,10 @@ fn edit_member(s: &mut Session, pos: &Pos, index: usize, f: impl FnOnce(wordcraf
|
||||
Ok(json!({"object": member, "pos": super::pos_json(pos), "member": index}))
|
||||
}
|
||||
|
||||
/// Change the picked member's own object (Shape Format, Size, Rotate, Alt Text) when `pos` is its
|
||||
/// canvas. `None`: no member picked there.
|
||||
/// Change the active member's own object (Shape Format, Size, Rotate, Alt Text) when `pos` is its
|
||||
/// canvas. `None`: no active member there.
|
||||
pub(crate) fn edit_member_object(s: &mut Session, pos: &Pos, f: impl Fn(&mut InlineObject)) -> Option<Result<InlineObject, CmdError>> {
|
||||
let (at, index, _) = selected_member(s).filter(|(at, ..)| at == pos)?;
|
||||
let (at, index, _) = active_member(s).filter(|(at, ..)| at == pos)?;
|
||||
let mut out = None;
|
||||
let r = edit_canvas(s, &at, |_, _, children| {
|
||||
if let Some(c) = children.get_mut(index) {
|
||||
|
||||
@@ -182,6 +182,9 @@ pub(crate) fn dispatch(s: &mut Session, id: &str, mutates: bool, run: fn(&mut Se
|
||||
_ if cells && (id.starts_with("table.") || matches!(id, "text.tab" | "text.backTab")) => run(s, v),
|
||||
// Copy and Cut of whole cells take a table of them (#1744).
|
||||
"edit.copy" | "edit.cut" if cells => run(s, v),
|
||||
// Paste can lay a copied table over the selected cells. Let it inspect the selection
|
||||
// before the ordinary column replacement deletes it.
|
||||
"edit.paste" if cells => run(s, v),
|
||||
"edit.copy" => copy(s, &segs),
|
||||
"edit.cut" => {
|
||||
let r = copy(s, &segs)?;
|
||||
@@ -209,6 +212,16 @@ pub(crate) fn dispatch(s: &mut Session, id: &str, mutates: bool, run: fn(&mut Se
|
||||
}
|
||||
}
|
||||
|
||||
/// Delete the pieces of a selected cell rectangle for an ordinary Paste replacement.
|
||||
pub(super) fn delete_cell_segments(s: &mut Session) -> Result<(), CmdError> {
|
||||
if s.cell_range().is_some()
|
||||
&& let Some(segments) = s.column_segments().map(<[(Pos, Pos)]>::to_vec)
|
||||
{
|
||||
delete(s, &segments)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Copy: one paragraph per block row (formatting kept); the plain text joins rows with newlines.
|
||||
fn copy(s: &mut Session, segs: &[(Pos, Pos)]) -> CmdResult {
|
||||
let mut blocks = Vec::new();
|
||||
|
||||
@@ -155,14 +155,20 @@ fn style_set(s: &mut Session, v: &Value) -> CmdResult {
|
||||
match name {
|
||||
"basic" if heading => {
|
||||
st.chr.color = Some(TextColor::Rgb(Rgb(0x26, 0x26, 0x26)));
|
||||
// Both scripts, as Word's own heading styles carry `w:b` with `w:bCs`: a Thai
|
||||
// heading in a run marked `w:cs` is drawn bold too.
|
||||
st.chr.bold = Some(true);
|
||||
st.chr.bold_cs = Some(true);
|
||||
}
|
||||
"lines" if st.id == "Heading1" || st.id == "Title" => st.para.borders = Some(Borders { bottom: Some(line), ..Default::default() }),
|
||||
"shaded" if st.id == "Heading1" => {
|
||||
st.para.shading = Some(accent);
|
||||
st.chr.color = Some(TextColor::Rgb(Rgb::WHITE));
|
||||
}
|
||||
"casual" if heading => st.chr.italic = Some(true),
|
||||
"casual" if heading => {
|
||||
st.chr.italic = Some(true);
|
||||
st.chr.italic_cs = Some(true);
|
||||
}
|
||||
"centered" if heading => st.para.align = Some(wordcraft_doc::Align::Center),
|
||||
"minimalist" if heading => {
|
||||
st.chr.caps = Some(true);
|
||||
|
||||
@@ -39,7 +39,7 @@ fn has_text_sel(s: &Session) -> Option<&'static str> {
|
||||
if s.sel.is_collapsed() { Some("nothing is selected") } else { None }
|
||||
}
|
||||
|
||||
/// Something to cut: text, or whole table cells (an empty cell's selection has no length, #1744).
|
||||
/// Something to cut: text, an object, or whole table cells (an empty cell's selection has no length, #1744).
|
||||
fn has_sel(s: &Session) -> Option<&'static str> {
|
||||
if s.sel.is_collapsed() && s.cell_range().is_none() { Some("nothing is selected") } else { None }
|
||||
}
|
||||
@@ -73,7 +73,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.key("Mod+Y / Mod+Shift+Z")
|
||||
.pure(),
|
||||
CommandSpec::new("edit.cut", "Cut", "Home › Clipboard", cut).key("Mod+X").when(has_sel),
|
||||
CommandSpec::new("edit.copy", "Copy", "Home › Clipboard", copy).key("Mod+C / Mod+Insert").pure(),
|
||||
CommandSpec::new("edit.copy", "Copy", "Home › Clipboard", copy).key("Mod+C / Mod+Insert").pure().when(has_sel),
|
||||
// Word's Spike (Ctrl+F3, Ctrl+Shift+F3; ⌘ on the Mac): the AutoText entry "Spike", so Quick
|
||||
// Parts and AutoText insert it without emptying it, as in Word.
|
||||
CommandSpec::new("edit.spike", "Spike", "Editing", spike).key("Mod+F3").when(has_text_sel),
|
||||
@@ -89,6 +89,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
CommandSpec::new("edit.paste", "Paste", "Home › Clipboard", paste)
|
||||
.key("Mod+V / Shift+Insert")
|
||||
.params(r#"{"text"?: string, "html"?: string, "rtf"?: string, "privateClipboard"?: bool}"#),
|
||||
CommandSpec::new("edit.pasteNestedTable", "Paste as Nested Table", "Home › Clipboard › Paste", paste_nested)
|
||||
.params(r#"{"text"?: string, "html"?: string, "rtf"?: string, "privateClipboard"?: bool} (a copied table with the caret in a table cell nests in that cell; Paste instead inserts its rows or overwrites the cells from the caret's)"#),
|
||||
CommandSpec::new("edit.pasteText", "Paste: Keep Text Only", "Home › Clipboard › Paste", paste_text)
|
||||
.params(r#"{"text"?: string}"#)
|
||||
.key("Mod+Shift+Alt+V"),
|
||||
@@ -185,6 +187,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
]
|
||||
}
|
||||
|
||||
/// Copy the selected text, object, or table cells to the clipboard.
|
||||
fn copy(s: &mut Session, _: &Value) -> CmdResult {
|
||||
let whole = super::table::selected_table(s);
|
||||
copy_with(s, whole.as_ref())
|
||||
@@ -218,6 +221,7 @@ pub(crate) fn copy_result(s: &mut Session) -> Value {
|
||||
(s.clipboard_html, s.clipboard_rtf) = match &s.clipboard {
|
||||
Some(f) => {
|
||||
let mut d = f.to_document();
|
||||
d.styles = s.doc.styles.clone();
|
||||
if d.media.is_empty() {
|
||||
d.media = s.doc.media.clone();
|
||||
}
|
||||
@@ -241,6 +245,7 @@ pub(crate) fn copy_result(s: &mut Session) -> Value {
|
||||
r
|
||||
}
|
||||
|
||||
/// Cut the selection, selected object, or whole table cells to the clipboard and remove it from the document.
|
||||
fn cut(s: &mut Session, _: &Value) -> CmdResult {
|
||||
let whole = super::table::selected_table(s);
|
||||
let r = copy_with(s, whole.as_ref())?;
|
||||
@@ -301,13 +306,30 @@ fn insert_spike(s: &mut Session, _: &Value) -> CmdResult {
|
||||
/// else another program's HTML or RTF (#687). The system clipboard's text has none, so it pastes
|
||||
/// as Keep Text Only does.
|
||||
fn paste(s: &mut Session, v: &Value) -> CmdResult {
|
||||
match super::paste::paste_content(s, v)? {
|
||||
let pasted = super::paste::paste_content(s, v)?;
|
||||
if let super::paste::Pasted::Fragment(frag) = &pasted
|
||||
&& super::paste_cells::paste_over_selection(s, frag)?
|
||||
{
|
||||
return sel_result(s);
|
||||
}
|
||||
super::column::delete_cell_segments(s)?;
|
||||
match pasted {
|
||||
super::paste::Pasted::Fragment(frag) => super::paste::insert(s, frag)?,
|
||||
super::paste::Pasted::Text(text) => super::paste::insert_text(s, &text)?,
|
||||
}
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
/// Paste as Nested Table: like Paste, but a copied table goes inside the cell the caret is in
|
||||
/// instead of laying its rows or cells over the table (#6739).
|
||||
fn paste_nested(s: &mut Session, v: &Value) -> CmdResult {
|
||||
match super::paste::paste_content(s, v)? {
|
||||
super::paste::Pasted::Fragment(frag) => super::paste::insert_as_is(s, frag)?,
|
||||
super::paste::Pasted::Text(text) => super::paste::insert_text(s, &text)?,
|
||||
}
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
/// Merge Formatting: the pasted text takes the destination's formatting, keeping its emphasis.
|
||||
fn paste_merge(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let mut frag = super::paste::paste_fragment(s, v)?;
|
||||
@@ -444,11 +466,17 @@ fn paste_clip_item(s: &mut Session, v: &Value) -> CmdResult {
|
||||
/// Every collected item, in the order they were copied (one undo step).
|
||||
fn paste_all_clips(s: &mut Session, _: &Value) -> CmdResult {
|
||||
let all: Vec<Fragment> = s.clip_history.items.iter().rev().map(|x| x.fragment.clone()).collect();
|
||||
let mut r = sel_result(s)?;
|
||||
let multiple = all.len() > 1;
|
||||
for f in all {
|
||||
r = paste_clip(s, f)?;
|
||||
if multiple {
|
||||
// Insert each item at the end of the last one. Cell paste can overwrite a
|
||||
// previous item or insert rows ahead of it.
|
||||
super::paste::insert_as_is(s, f)?;
|
||||
} else {
|
||||
return paste_clip(s, f);
|
||||
}
|
||||
}
|
||||
Ok(r)
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
fn paste_text(s: &mut Session, v: &Value) -> CmdResult {
|
||||
@@ -910,7 +938,7 @@ fn paste_format(s: &mut Session, _: &Value) -> CmdResult {
|
||||
#[cfg(test)]
|
||||
mod shortcut_tests {
|
||||
use super::*;
|
||||
use crate::{KeyMap, Registry};
|
||||
use crate::Registry;
|
||||
|
||||
#[test]
|
||||
fn copy_format_web_alias_is_unique_and_keeps_existing_shortcuts() {
|
||||
@@ -921,34 +949,38 @@ mod shortcut_tests {
|
||||
let registry = Registry::new(commands);
|
||||
let mut seen = std::collections::BTreeSet::new();
|
||||
for command in registry.all() {
|
||||
for key in command.shortcut.split(" / ").filter_map(crate::keymap::normalize) {
|
||||
assert!(seen.insert(key.clone()), "duplicate binding: {key}");
|
||||
for key in command.shortcut.split(" / ").filter_map(|k| craft_keymap::Chord::parse(k).ok()) {
|
||||
assert!(seen.insert(key), "duplicate binding: {key:?}");
|
||||
}
|
||||
}
|
||||
let keys = KeyMap::default();
|
||||
let resolve = |key| keys.resolve(®istry, key).map(|c| c.id);
|
||||
assert_eq!(resolve("Mod+Shift+C"), Some("edit.copyFormat"));
|
||||
assert_eq!(resolve("Mod+Alt+Shift+C"), web.then_some("edit.copyFormat"));
|
||||
assert_eq!(resolve("Mod+Shift+V"), Some("edit.pasteFormat"));
|
||||
assert_eq!(resolve("Mod+Alt+Shift+V"), Some("edit.pasteText"));
|
||||
if !cfg!(target_os = "macos") {
|
||||
assert_eq!(resolve("Mod+Alt+C"), Some("text.copyright"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[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 keys = KeyMap::default();
|
||||
assert_eq!(keys.keys_for(®istry, "edit.copyFormat").first().map(String::as_str), Some("Mod+Alt+Shift+C"));
|
||||
assert!(keys.remove(®istry, "edit.copyFormat", "Mod+Alt+Shift+C").unwrap());
|
||||
assert!(keys.resolve(®istry, "Mod+Alt+Shift+C").is_none());
|
||||
keys.assign(®istry, "format.bold", "Mod+Alt+Shift+C").unwrap();
|
||||
let restored = KeyMap::from_value(&serde_json::to_value(&keys).unwrap());
|
||||
assert_eq!(restored.resolve(®istry, "Mod+Alt+Shift+C").map(|c| c.id), Some("format.bold"));
|
||||
assert_eq!(restored.resolve(®istry, "Mod+Shift+C").map(|c| c.id), Some("edit.copyFormat"));
|
||||
|
||||
let mut keymap = crate::keymap::registry_keymap(®istry, &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(©_cmd).iter().any(|b| b.trigger.chord == chord));
|
||||
assert!(keymap.remove(©_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(®istry, &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"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -774,6 +774,18 @@ fn set(s: &mut Session, v: &Value) -> CmdResult {
|
||||
result(s)
|
||||
}
|
||||
|
||||
/// The equation at the caret (the one being edited, else one beside the caret) as `(display, linear)`, read without
|
||||
/// running a command. A surface that shows the equation's state every frame reads this: a command, even a query,
|
||||
/// would consume the replacement an input method's deletion promised (`Session::join_next_equation_edit`), whose
|
||||
/// commit can arrive in a later frame.
|
||||
pub fn at_caret(s: &Session) -> Option<(bool, &str)> {
|
||||
let at = equation_at_caret(s)?;
|
||||
match s.doc.para_at(&at).and_then(|p| p.object_at(at.off)) {
|
||||
Some(InlineObject::Equation { linear, display, .. }) => Some((*display, linear.as_str())),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn get(s: &mut Session, _: &Value) -> CmdResult {
|
||||
let at = equation_at_caret(s).ok_or_else(|| CmdError::Disabled("no equation at the caret".into()))?;
|
||||
let Some(InlineObject::Equation { linear, display, math }) = s.doc.para_at(&at).and_then(|p| p.object_at(at.off)) else {
|
||||
|
||||
@@ -403,18 +403,18 @@ mod tests {
|
||||
#[test]
|
||||
fn f11_is_full_screen_and_alt_f1_walks_fields() {
|
||||
let s = Session::new(wordcraft_doc::Document::new());
|
||||
let key = |k: &str| s.keymap.resolve(&s.registry, k).map(|c| c.id);
|
||||
assert_eq!(key("F11"), Some("view.fullScreen"));
|
||||
assert_eq!(key("Alt+F1"), Some("fields.next"));
|
||||
assert_eq!(key("Alt+Shift+F1"), Some("fields.previous"));
|
||||
assert_eq!(key("Shift+F11"), Some("fields.previous"));
|
||||
assert_eq!(key("Mod+F11"), Some("fields.lock"));
|
||||
// ⌃⌘F is macOS' own full-screen key; elsewhere Mod is Ctrl, so "Mod+Ctrl+F" would read
|
||||
// Ctrl+Ctrl+F: F11 only there.
|
||||
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"), Some("view.fullScreen"));
|
||||
assert_eq!(key("Mod+Ctrl+F").as_deref(), Some("view.fullScreen"));
|
||||
} else {
|
||||
assert_eq!(shortcut, Some("F11"));
|
||||
}
|
||||
|
||||
@@ -131,7 +131,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.pure(),
|
||||
CommandSpec::new("file.printPdf", "Print to PDF", "File › Print", crate::print::print_pdf_to_file)
|
||||
.params(
|
||||
r#"{"path": string, "pagesPerSheet"?: 1 | 2 | 4 | 6 | 9 | 16 | "booklet" | "bookletReverse", "range"?: "all" | "current" | "selection" (the pages the selection touches) | "custom", "pages"?: "1-3,5" (implies custom), "parity"?: "all" | "odd" | "even", "copies"?: 1-999, "collate"?: bool (default true), "paper"?: "none" | "Letter" | "Legal" | "A4" | … (a Layout › Size name: scale every page to this paper, centred; the document keeps its size)}"#,
|
||||
r#"{"path": string, "pagesPerSheet"?: 1 | 2 | 4 | 6 | 9 | 16 | "booklet" | "bookletReverse", "range"?: "all" | "current" | "selection" (the pages the selection touches) | "custom", "pages"?: "1-3,5" (implies custom), "parity"?: "all" | "odd" | "even", "copies"?: 1-999, "collate"?: bool (default true), "paper"?: "none" | "Letter" | "Legal" | "A4" | … (a Layout › Size name: scale every page to this paper, centred; the document keeps its size), "compress"?: bool (default true: compress the PDF's content streams; false writes the same pages uncompressed, which is larger)"#,
|
||||
)
|
||||
.pure(),
|
||||
CommandSpec::new("file.print", "Print", "File", |s, _| {
|
||||
@@ -485,8 +485,8 @@ fn save_as(s: &mut Session, v: &Value) -> CmdResult {
|
||||
}
|
||||
|
||||
/// How a copy is written: Print Markup from the command's `markup`, else the File › Print
|
||||
/// setting (`file.printMarkup`); comments as Track Changes Options show them; digits as the
|
||||
/// Numeral setting shows them on screen.
|
||||
/// setting (`file.printMarkup`); comments and revision marks/colours as Track Changes Options show them;
|
||||
/// digits as the Numeral setting shows them on screen.
|
||||
pub fn export_options(s: &Session, v: &Value) -> crate::io::ExportOptions {
|
||||
let markup = p::bool(v, "markup").unwrap_or(s.prefs.print_markup);
|
||||
crate::io::ExportOptions {
|
||||
@@ -494,6 +494,7 @@ pub fn export_options(s: &Session, v: &Value) -> crate::io::ExportOptions {
|
||||
comments: markup && s.prefs.markup.comments,
|
||||
word2003: p::str(v, "format") == Some(FORMAT_WORD_2003),
|
||||
numeral: s.view.numeral.resolve(crate::session::system_locale()),
|
||||
revisions: s.prefs.markup.clone(),
|
||||
strict: p::bool(v, "strict").unwrap_or(false),
|
||||
}
|
||||
}
|
||||
@@ -517,7 +518,10 @@ fn strict_report(s: &mut Session, v: &Value) -> CmdResult {
|
||||
if l.pages.get(page).is_none() {
|
||||
return Err(CmdError::Params(format!("no page {}", page + 1)));
|
||||
}
|
||||
crate::strict::strict_report(&s.doc, &l, &crate::strict::png_display(), Some(page..=page), wordcraft_layout::StrictOutput::Png)
|
||||
// The page image `file.exportPng` writes: the printed page, tracked changes marked as
|
||||
// Track Changes Options mark them.
|
||||
let display = crate::io_ext::page_image_options(&opts).display;
|
||||
crate::strict::strict_report(&s.doc, &l, &display, Some(page..=page), wordcraft_layout::StrictOutput::Png)
|
||||
}
|
||||
None => {
|
||||
let out = super::references::output_fields(&s.doc);
|
||||
@@ -527,6 +531,7 @@ fn strict_report(s: &mut Session, v: &Value) -> CmdResult {
|
||||
Ok(report.to_json())
|
||||
}
|
||||
|
||||
/// Exports a page of the current document as a PNG image at the requested scale.
|
||||
fn export_png(s: &mut Session, v: &Value) -> CmdResult {
|
||||
// No path: the app asks where to save, as file.exportPdf does (#2313).
|
||||
let Some(path) = p::str(v, "path") else {
|
||||
@@ -536,11 +541,13 @@ fn export_png(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let page = crate::p::page_index(p::u64(v, "page").unwrap_or(1));
|
||||
let strict = p::bool(v, "strict").unwrap_or(false);
|
||||
let scale = p::f32(v, "scale").unwrap_or(2.0).clamp(0.1, 8.0);
|
||||
let l = s.export_layout_with(export_options(s, v).markup);
|
||||
let export = export_options(s, v);
|
||||
let l = s.export_layout_with(export.markup);
|
||||
let pg = l.pages.get(page).ok_or_else(|| CmdError::Params(format!("no page {}", page + 1)))?;
|
||||
// A page image is the printed page: headers and footers at full strength. Dimming them is
|
||||
// the on-screen cue while editing the body, not part of the page.
|
||||
let opts = wordcraft_render::RenderOptions { display: crate::strict::png_display(), ..Default::default() };
|
||||
// the on-screen cue while editing the body, not part of the page. Tracked changes are marked
|
||||
// as Track Changes Options mark them on screen.
|
||||
let opts = crate::io_ext::page_image_options(&export);
|
||||
if !path.to_ascii_lowercase().ends_with(".png") {
|
||||
return Err(CmdError::Params("path must end in .png".into()));
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
toggle(
|
||||
s,
|
||||
v,
|
||||
|r| r.bold,
|
||||
shown_bold,
|
||||
|c, on| {
|
||||
c.bold = Some(on);
|
||||
c.bold_cs = Some(on);
|
||||
@@ -34,7 +34,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
toggle(
|
||||
s,
|
||||
v,
|
||||
|r| r.italic,
|
||||
shown_italic,
|
||||
|c, on| {
|
||||
c.italic = Some(on);
|
||||
c.italic_cs = Some(on);
|
||||
@@ -281,7 +281,10 @@ fn resolved(s: &Session) -> Vec<ResolvedChar> {
|
||||
return out;
|
||||
}
|
||||
}
|
||||
let Some((a, b)) = selected_text_box(s).or_else(|| target(s)) else {
|
||||
// Formatting waiting at a caret is what the caret shows, also inside a word: after Backspace
|
||||
// it is the deleted character's (#6518), as Word's buttons show it.
|
||||
let waiting = s.sel.is_collapsed() && s.waiting().is_some();
|
||||
let Some((a, b)) = selected_text_box(s).or_else(|| target(s)).filter(|_| !waiting) else {
|
||||
let f = &s.sel.focus;
|
||||
let style = s.doc.para_at(f).and_then(|p| p.props.style.clone());
|
||||
out.push(s.doc.styles.resolve_char(style.as_deref(), &s.typing_props()));
|
||||
@@ -310,6 +313,18 @@ fn resolved(s: &Session) -> Vec<ResolvedChar> {
|
||||
out
|
||||
}
|
||||
|
||||
/// Bold as drawn: a run marked complex script (`w:cs`) or right to left (`w:rtl`) shows its
|
||||
/// complex-script bold.
|
||||
fn shown_bold(r: &ResolvedChar) -> bool {
|
||||
if r.cs || r.rtl { r.bold_cs } else { r.bold }
|
||||
}
|
||||
|
||||
/// Italic as drawn: a run marked complex script (`w:cs`) or right to left (`w:rtl`) shows its
|
||||
/// complex-script italic.
|
||||
fn shown_italic(r: &ResolvedChar) -> bool {
|
||||
if r.cs || r.rtl { r.italic_cs } else { r.italic }
|
||||
}
|
||||
|
||||
fn toggle(s: &mut Session, v: &Value, get: fn(&ResolvedChar) -> bool, set: fn(&mut CharProps, bool)) -> CmdResult {
|
||||
let on = match p::bool(v, "value") {
|
||||
Some(b) => b,
|
||||
@@ -887,8 +902,8 @@ pub fn state(s: &Session) -> Value {
|
||||
"fontShownAs": shown_as,
|
||||
"fontEastAsia": same(&|r| json!(r.font_ea)),
|
||||
"size": same(&|r| json!(r.size)),
|
||||
"bold": all.iter().all(|r| r.bold),
|
||||
"italic": all.iter().all(|r| r.italic),
|
||||
"bold": all.iter().all(shown_bold),
|
||||
"italic": all.iter().all(shown_italic),
|
||||
"underline": all.iter().all(|r| r.underline != Underline::None),
|
||||
"underlineColor": same(&|r| json!(r.underline_color.map_or_else(|| "auto".to_string(), |c| c.hex()))),
|
||||
"strike": all.iter().all(|r| r.strike),
|
||||
|
||||
@@ -16,7 +16,8 @@ mod objects;
|
||||
pub(crate) use header_footer::saved_copy;
|
||||
use header_footer::{create_hf, edit_hf, header_footer, new_empty_headers, strip_headers};
|
||||
pub use items::{
|
||||
DropCapState, default_date_picture, drop_cap_state, format_date, format_date_at, format_date_in, format_date_parts, format_date_parts_in,
|
||||
DropCapState, default_date_picture, drop_cap_state, format_date, format_date_at, format_date_at_in, format_date_in, format_date_parts,
|
||||
format_date_parts_in,
|
||||
};
|
||||
use items::{cover_page, date_time, drop_cap, drop_cap_off, field, page_number, symbol};
|
||||
use links::{bookmark, delete_bookmark, link, link_targets};
|
||||
|
||||
@@ -114,7 +114,7 @@ fn place_picture(s: &mut Session, bytes: Vec<u8>, width: Option<f32>, alt: &str)
|
||||
Err(wordcraft_geom::picture::Refusal::Unsupported(why)) => return Err(CmdError::Failed(why.into())),
|
||||
Err(_) => match wordcraft_render::metafile_size(&bytes) {
|
||||
Some(size) => size,
|
||||
None => return Err(CmdError::Failed("not a supported image (PNG, JPEG, GIF, WebP, BMP, WMF, EMF)".into())),
|
||||
None => return Err(CmdError::Failed("not a supported image (PNG, JPEG, GIF, WebP, BMP, TIFF, WMF, EMF)".into())),
|
||||
},
|
||||
};
|
||||
let key = s.doc.add_media(bytes, ext);
|
||||
|
||||
@@ -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};
|
||||
pub use select::{min_size, object_selection, picked_objects, selected, selected_all, selected_or_text_box, target_objects};
|
||||
#[cfg(test)]
|
||||
use shape::can_link;
|
||||
pub(crate) use shape::set_text_body;
|
||||
pub use shape::text_box_target;
|
||||
pub use shape::{text_box_target, text_box_targets};
|
||||
pub use specs::specs;
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::select::{edit_float, min_size, movable_story, obj_size, select_object, selected, with_obj};
|
||||
use super::select::{edit_float, min_size, movable_story, obj_size, select_object, selected_or_text_box, with_obj};
|
||||
use super::{CmdError, CmdResult, Float, InlineObject, Pos, Selection, Session, StoryRef, Value, Wrap, json, p};
|
||||
|
||||
/// Largest object offset or move, points.
|
||||
@@ -9,7 +9,7 @@ pub(super) fn bounds(s: &mut Session, v: &Value) -> CmdResult {
|
||||
if let Some(r) = crate::cmd::canvas::member_bounds(s, v) {
|
||||
return r;
|
||||
}
|
||||
let (pos, obj) = selected(s).ok_or_else(|| CmdError::Disabled("no picture or shape selected".into()))?;
|
||||
let (pos, obj) = selected_or_text_box(s).ok_or_else(|| CmdError::Disabled("no picture or shape selected".into()))?;
|
||||
let to = match (p::f32(v, "x"), p::f32(v, "y")) {
|
||||
(Some(x), Some(y)) => Some((x, y)),
|
||||
(None, None) => None,
|
||||
@@ -88,7 +88,7 @@ fn move_in_text(s: &mut Session, pos: Pos, to: &Pos) -> Result<Pos, CmdError> {
|
||||
/// (x, y), or for an In Line with Text object put it at the text position `to`, leaving the
|
||||
/// original in place and the clipboard alone. The copy is selected.
|
||||
pub(super) fn copy_to(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let (pos, obj) = selected(s).ok_or_else(|| CmdError::Disabled("no picture or shape selected".into()))?;
|
||||
let (pos, obj) = selected_or_text_box(s).ok_or_else(|| CmdError::Disabled("no picture or shape selected".into()))?;
|
||||
let len = wordcraft_doc::para::OBJ.len_utf8();
|
||||
let end = Pos { off: pos.off + len, ..pos.clone() };
|
||||
if let Some(to) = text_target(v, &obj)? {
|
||||
@@ -219,7 +219,7 @@ fn move_object_once(s: &mut Session, pos: &Pos, page: usize, x: f32, y: f32, (w,
|
||||
/// column / paragraph that keeps it where it is, so it can be moved by an offset.
|
||||
pub(super) fn unalign(s: &mut Session) -> Result<(), CmdError> {
|
||||
use wordcraft_doc::para::Anchor;
|
||||
let (pos, obj) = selected(s).ok_or_else(|| CmdError::Disabled("no picture or shape selected".into()))?;
|
||||
let (pos, obj) = selected_or_text_box(s).ok_or_else(|| CmdError::Disabled("no picture or shape selected".into()))?;
|
||||
let Some((_, _, float)) = obj.frame() else { return Ok(()) };
|
||||
if float.h_align.is_none() && float.v_align.is_none() {
|
||||
return Ok(());
|
||||
@@ -260,7 +260,7 @@ pub fn moves_with_text(f: &Float) -> bool {
|
||||
/// object's vertical position to its paragraph or to the page, keeping it where it is now.
|
||||
pub(super) fn move_with_text(s: &mut Session, with_text: bool) -> CmdResult {
|
||||
use wordcraft_doc::para::Anchor;
|
||||
let (pos, obj) = selected(s).ok_or_else(|| CmdError::Disabled("no picture or shape selected".into()))?;
|
||||
let (pos, obj) = selected_or_text_box(s).ok_or_else(|| CmdError::Disabled("no picture or shape selected".into()))?;
|
||||
let Some((_, _, float)) = obj.frame() else { return Err(CmdError::Disabled("select a floating picture or shape first".into())) };
|
||||
if moves_with_text(float) == with_text {
|
||||
return Ok(json!({"object": serde_json::to_value(&obj).unwrap_or(Value::Null)}));
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::select::{obj_size, selected, with_obj};
|
||||
use super::{CmdError, CmdResult, InlineObject, Rgb, Session, Value, Wrap, p};
|
||||
use super::select::{edit_obj, is_shape_or_canvas, obj_size, selected, target_objects, with_obj};
|
||||
use super::{CmdError, CmdResult, InlineObject, Pos, Rgb, Session, Value, Wrap, json, p};
|
||||
use wordcraft_doc::picfx::PicFx;
|
||||
|
||||
/// `picture.crop`: the crop, and optionally the new display size, as one edit. With a size, a
|
||||
@@ -70,19 +70,15 @@ pub fn cropped_original_size(s: &Session, o: &InlineObject) -> Option<(f32, f32)
|
||||
Some((orig.w * part(crop[0], crop[2]), orig.h * part(crop[1], crop[3])))
|
||||
}
|
||||
|
||||
/// Size: `scale` is a percentage of the current size, or with `original` of what the crop leaves
|
||||
/// of the original size (`original` alone gives that back: the Size dialog's Reset); then `width`
|
||||
/// and `height`, where one alone keeps the proportions unless `lockAspect` is false.
|
||||
pub(super) fn size(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let (_, o) = selected(s).ok_or_else(|| CmdError::Disabled("no object".into()))?;
|
||||
fn planned_size(s: &Session, o: &InlineObject, v: &Value) -> Result<(f32, f32), CmdError> {
|
||||
let lock = p::bool(v, "lockAspect").unwrap_or(true);
|
||||
let (w0, h0) = obj_size(&o);
|
||||
let (w0, h0) = obj_size(o);
|
||||
let (mut w, mut h) = (w0, h0);
|
||||
let scale = p::f32(v, "scale");
|
||||
let original = p::bool(v, "original").unwrap_or(false);
|
||||
if original {
|
||||
let (ow, oh) =
|
||||
cropped_original_size(s, &o).ok_or_else(|| CmdError::Disabled("only a picture whose image can be read has an original size".into()))?;
|
||||
cropped_original_size(s, o).ok_or_else(|| CmdError::Disabled("only a picture whose image can be read has an original size".into()))?;
|
||||
let k = scale.unwrap_or(100.0) / 100.0;
|
||||
(w, h) = (ow * k, oh * k);
|
||||
} else if let Some(sc) = scale {
|
||||
@@ -118,21 +114,55 @@ pub(super) fn size(s: &mut Session, v: &Value) -> CmdResult {
|
||||
// Sides set in proportion (from the original, or from a size whose sides both have a length)
|
||||
// fit the limits together. Otherwise each side the call sets fits on its own, and a side it
|
||||
// leaves as it was keeps its size, a straight line's 0 too.
|
||||
let (w, h) = if keep && (original || (w0 > 0.0 && h0 > 0.0 && (w, h) != (w0, h0))) {
|
||||
fit_size(w, h, true)
|
||||
if keep && (original || (w0 > 0.0 && h0 > 0.0 && (w, h) != (w0, h0))) {
|
||||
Ok(fit_size(w, h, true))
|
||||
} else {
|
||||
let (fw, fh) = fit_size(w, h, false);
|
||||
let left = |new: f32, old: f32| !original && new == old;
|
||||
(if left(w, w0) { w } else { fw }, if left(h, h0) { h } else { fh })
|
||||
};
|
||||
Ok((if left(w, w0) { w } else { fw }, if left(h, h0) { h } else { fh }))
|
||||
}
|
||||
}
|
||||
|
||||
fn size_matching(s: &mut Session, v: &Value, pred: impl Fn(&InlineObject) -> bool, empty_msg: &str) -> CmdResult {
|
||||
let targets = target_objects(s, pred);
|
||||
if targets.is_empty() {
|
||||
return Err(CmdError::Disabled(empty_msg.into()));
|
||||
}
|
||||
let planned: Vec<(Pos, f32, f32)> =
|
||||
targets.into_iter().map(|(pos, o)| planned_size(s, &o, v).map(|(w, h)| (pos, w, h))).collect::<Result<Vec<_>, _>>()?;
|
||||
// Any drawing: a group's members scale with its frame (its child space is kept); a chart or
|
||||
// SmartArt graphic lays itself out again at the new size.
|
||||
let theme = s.doc.settings.theme_colors.clone();
|
||||
with_obj(s, |o| {
|
||||
o.set_size(w, h);
|
||||
crate::cmd::chart::redraw(o, &theme);
|
||||
crate::cmd::smart_art::redraw(o, &theme);
|
||||
})
|
||||
let mut last = Value::Null;
|
||||
for (pos, w, h) in &planned {
|
||||
let o = edit_obj(s, pos, |o| {
|
||||
o.set_size(*w, *h);
|
||||
crate::cmd::chart::redraw(o, &theme);
|
||||
crate::cmd::smart_art::redraw(o, &theme);
|
||||
})?;
|
||||
last = serde_json::to_value(o).unwrap_or(Value::Null);
|
||||
}
|
||||
Ok(json!({"object": last, "count": planned.len()}))
|
||||
}
|
||||
|
||||
/// Size: `scale` is a percentage of the current size, or with `original` of what the crop leaves
|
||||
/// of the original size (`original` alone gives that back: the Size dialog's Reset); then `width`
|
||||
/// and `height`, where one alone keeps the proportions unless `lockAspect` is false.
|
||||
pub(super) fn size(s: &mut Session, v: &Value) -> CmdResult {
|
||||
size_matching(
|
||||
s,
|
||||
v,
|
||||
|o| match o {
|
||||
InlineObject::Graphic { graphic, .. } => graphic.chart.is_some() || graphic.smart_art.is_some(),
|
||||
_ => o.is_drawing(),
|
||||
},
|
||||
"no object",
|
||||
)
|
||||
}
|
||||
|
||||
/// Shape Size: resizes only selected shapes, text boxes, and drawing canvases (or the active text box).
|
||||
pub(super) fn shape_size(s: &mut Session, v: &Value) -> CmdResult {
|
||||
size_matching(s, v, is_shape_or_canvas, "no shape selected")
|
||||
}
|
||||
|
||||
/// An object size within 1–4000 pt. With `keep`, both sides scale by one factor, the one nearest
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user