mirror of
https://github.com/storytold/wordcraft.git
synced 2026-11-25 21:19:50 +00:00
Compare commits
111
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 | ||
|
|
1094d3c35e | ||
|
|
cc9778ebe1 | ||
|
|
442d1c3f53 | ||
|
|
3e0b11df2f | ||
|
|
ecb3633aff |
@@ -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": null,
|
||||
"producer_workflow_path": ".github/workflows/nightly.yml",
|
||||
"producer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea",
|
||||
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@605d58766e8f536564da8fc81d3676ac86816dea",
|
||||
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
|
||||
"signer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea",
|
||||
"release_branch": "release",
|
||||
"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,42 @@
|
||||
name: WordCraft release-ref nightly signer
|
||||
|
||||
# Enabled for supervised manual dispatch on release. Main/release contents must match.
|
||||
# A reusable callee does not change context; this must be a real top-level release 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 release branch.
|
||||
if: >-
|
||||
github.repository == 'storytold/wordcraft' &&
|
||||
github.event_name == 'workflow_dispatch' &&
|
||||
github.ref == 'refs/heads/release' && 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@605d58766e8f536564da8fc81d3676ac86816dea
|
||||
with:
|
||||
tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea
|
||||
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 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@605d58766e8f536564da8fc81d3676ac86816dea
|
||||
with:
|
||||
tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea
|
||||
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 #339 (bounded lineage compares), on top of the
|
||||
# Linux/macOS signer (#342).
|
||||
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,24 @@ 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
|
||||
|
||||
@@ -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__/
|
||||
|
||||
@@ -26,6 +26,12 @@ The UI icons are SVG files in `crates/ui-egui/icons/`, one row each below. Gener
|
||||
| `assets/app-icon/hicolor/scalable/apps/ai.storyteller.wordcraft.svg` | WordCraft contributors | original artwork drawn in SVG (`assets/app-icon/wordcraft.svg`), rendered by `packaging/icons.sh` | MIT OR Apache-2.0 | Placeholder app icon until the WordCraft mascot drawing lands |
|
||||
| `assets/app-icon/hicolor/48x48/apps/ai.storyteller.wordcraft.png` | WordCraft contributors | original artwork drawn in SVG (`assets/app-icon/wordcraft.svg`), rendered by `packaging/icons.sh` | MIT OR Apache-2.0 | Placeholder app icon until the WordCraft mascot drawing lands |
|
||||
| `assets/app-icon/hicolor/512x512/apps/ai.storyteller.wordcraft.png` | WordCraft contributors | original artwork drawn in SVG (`assets/app-icon/wordcraft.svg`), rendered by `packaging/icons.sh` | MIT OR Apache-2.0 | Placeholder app icon until the WordCraft mascot drawing lands |
|
||||
| `assets/app-icon/wordcraft-nightly.png` | WordCraft contributors | derived from `assets/app-icon/hicolor/256x256/apps/ai.storyteller.wordcraft.png` by `packaging/nightly-icons.py` (nightly field `#232c67`); input hashes and the recipe are in `assets/app-icon/nightly-provenance.json` | MIT OR Apache-2.0 | Nightly 256 px render; the icon the Linux Nightly tar ships |
|
||||
| `assets/app-icon/wordcraft-nightly-1024.png` | WordCraft contributors | derived from `assets/app-icon/wordcraft-1024.png` by `packaging/nightly-icons.py` | MIT OR Apache-2.0 | 1024 px master the Nightly `.icns` is generated from |
|
||||
| `assets/app-icon/wordcraft-nightly.ico` | WordCraft contributors | derived from `assets/app-icon/wordcraft.ico` by `packaging/nightly-icons.py` | MIT OR Apache-2.0 | Windows Nightly icon (16-256 px), embedded by `apps/wordcraft/build.rs` into the Nightly executable only |
|
||||
| `assets/app-icon/wordcraft-nightly.icns` | WordCraft contributors | derived from `assets/app-icon/wordcraft.icns` by `packaging/nightly-icons.py` | MIT OR Apache-2.0 | macOS Nightly bundle icon (`CFBundleIconFile wordcraft-nightly`) |
|
||||
| `assets/app-icon/nightly-provenance.json` | WordCraft contributors | original work for this repository | MIT OR Apache-2.0 | The exact inputs, palette and transform that produced the Nightly icon set |
|
||||
| `assets/app-icon/README.md` | WordCraft contributors | original description of this repository's own icon artwork | MIT OR Apache-2.0 | Names the master, the sizes and the regeneration steps |
|
||||
| `assets/fonts/Inter-Medium.ttf` | Rasmus Andersson / The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) | Open-source typeface (Latin UI/document font, carried over from DesignCraft) |
|
||||
| `assets/fonts/Inter-Regular.ttf` | Rasmus Andersson / The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) | Open-source typeface (Latin UI/document font, carried over from DesignCraft) |
|
||||
| `assets/fonts/Inter-SemiBold.ttf` | Rasmus Andersson / The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) | Open-source typeface (Latin UI/document font, carried over from DesignCraft) |
|
||||
@@ -135,6 +141,7 @@ The UI icons are SVG files in `crates/ui-egui/icons/`, one row each below. Gener
|
||||
| `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 |
|
||||
|
||||
Generated
+184
-281
File diff suppressed because it is too large
Load Diff
+52
-52
@@ -37,20 +37,20 @@ 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 = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
|
||||
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
|
||||
craft-ssip = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
|
||||
wordcraft-proof = { package = "craft-proof", git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-ssip = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
wordcraft-engine = { path = "crates/engine" }
|
||||
wordcraft-mcp = { path = "crates/mcp" }
|
||||
wordcraft-zotero = { path = "crates/zotero" }
|
||||
wordcraft-control-key = { path = "crates/control-key" }
|
||||
wordcraft-ui-egui = { path = "crates/ui-egui" }
|
||||
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
|
||||
craft = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0", default-features = false }
|
||||
craft-ui-test-kit = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
|
||||
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
|
||||
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0", default-features = false }
|
||||
craft-ui-test-kit = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
|
||||
# foundation
|
||||
kurbo = { version = "0.13", features = ["serde"] }
|
||||
@@ -81,28 +81,28 @@ wuff = "0.2.9"
|
||||
brotli-decompressor = "5"
|
||||
vello_cpu = "0.2"
|
||||
image = { version = "0.25", default-features = false }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0", default-features = false, features = ["write"] }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0", default-features = false, features = ["write"] }
|
||||
|
||||
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
|
||||
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
|
||||
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
|
||||
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0", features = ["doc"] }
|
||||
craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
|
||||
craft-flow = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
|
||||
craft-odf = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0", features = ["text"] }
|
||||
craft-markdown = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
|
||||
craft-html = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0", features = ["flow"] }
|
||||
craft-latex = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
|
||||
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0", features = ["detect"] }
|
||||
craft-sheet = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
|
||||
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
|
||||
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
|
||||
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
|
||||
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
|
||||
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0", features = ["doc"] }
|
||||
craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-flow = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-odf = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0", features = ["text"] }
|
||||
craft-markdown = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-html = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0", features = ["flow"] }
|
||||
craft-latex = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0", features = ["detect"] }
|
||||
craft-sheet = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
# zlib streams (compressed metafile pictures in `.doc` drawings); already in the lock as a dependency of other crates.
|
||||
miniz_oxide = "0.9"
|
||||
cfb = "0.15"
|
||||
@@ -170,27 +170,27 @@ debug = 0
|
||||
# The framework's patches, which Cargo does not carry over to dependents: its vendored crates from craft-libs,
|
||||
# and the egui and winit forks it builds with.
|
||||
[patch.crates-io]
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38" }
|
||||
hayro = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49" }
|
||||
hayro = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
|
||||
|
||||
|
||||
+12
-3
File diff suppressed because one or more lines are too long
@@ -897,8 +897,21 @@ fn parity_markdown(p: &Value) -> String {
|
||||
s
|
||||
}
|
||||
|
||||
/// The Launcher's Nightly bootstrap belongs to the desktop app: a CLI must not accept it, in the
|
||||
/// separate-token or `=` form, so a mis-routed launch fails loudly instead of editing stable data.
|
||||
fn launcher_profile_flag(args: &[OsString]) -> bool {
|
||||
args.iter().any(|arg| {
|
||||
let arg = arg.to_string_lossy();
|
||||
arg == "--launch-profile" || arg == "--profile-root" || arg.starts_with("--launch-profile=") || arg.starts_with("--profile-root=")
|
||||
})
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let args: Vec<OsString> = std::env::args_os().skip(1).collect();
|
||||
if launcher_profile_flag(&args) {
|
||||
eprintln!("wordcraft-cli: --launch-profile and --profile-root are the desktop app's Nightly bootstrap, not a CLI option");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
// Language packs installed in the suite's font store are used; `proof.installPack` installs
|
||||
// only while the person has turned downloading on in the app.
|
||||
wordcraft_engine::packs::use_font_store(false);
|
||||
|
||||
@@ -1,6 +1,23 @@
|
||||
use super::*;
|
||||
use std::io::Read;
|
||||
|
||||
/// The desktop app's Nightly bootstrap is never a CLI option, in either spelling.
|
||||
#[test]
|
||||
fn the_launcher_profile_bootstrap_is_refused_in_both_forms() {
|
||||
for argv in [
|
||||
&["--launch-profile", "nightly-v1", "--profile-root", "/nightly/profiles/wordcraft", "--version"][..],
|
||||
&["--launch-profile=nightly-v1", "--profile-root=/nightly/profiles/wordcraft"][..],
|
||||
&["--profile-root", "/nightly/profiles/wordcraft"][..],
|
||||
] {
|
||||
let argv: Vec<std::ffi::OsString> = argv.iter().map(std::ffi::OsString::from).collect();
|
||||
assert!(launcher_profile_flag(&argv), "{argv:?}");
|
||||
}
|
||||
for argv in [&["--version"][..], &["proof.check", "--launch-profiles"][..], &["--profile-roots"][..]] {
|
||||
let argv: Vec<std::ffi::OsString> = argv.iter().map(std::ffi::OsString::from).collect();
|
||||
assert!(!launcher_profile_flag(&argv), "{argv:?}");
|
||||
}
|
||||
}
|
||||
|
||||
fn args(values: &[&str]) -> Vec<String> {
|
||||
values.iter().map(|value| (*value).into()).collect()
|
||||
}
|
||||
|
||||
@@ -37,7 +37,7 @@ use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
|
||||
use craft::host::{FileError, Files, PickId, PickRequest, Picked};
|
||||
use craft::host::{FileError, Files, PickId, PickRequest, Picked, WriteIntent};
|
||||
use craft::platform::browser_files::BrowserFiles;
|
||||
use craft::platform::open::{DropTarget, DroppedFile, IntakeSender};
|
||||
use craft::web_host::web::{FileData, Host, Message};
|
||||
@@ -175,8 +175,8 @@ impl Files for HostedFiles {
|
||||
self.inner.read(path)
|
||||
}
|
||||
|
||||
fn write(&self, path: &Path, bytes: &[u8]) -> Result<(), FileError> {
|
||||
self.inner.write(path, bytes)
|
||||
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> {
|
||||
|
||||
@@ -25,6 +25,9 @@ eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "
|
||||
egui = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
log = { workspace = true }
|
||||
# The nightly launch profile's refusal dialog (a native message box, like the app's other OS errors).
|
||||
rfd = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
# The suite's shared libraries: the runtime hooks (`ui`, `ui-app`), file dialogs, the control
|
||||
# channel's arguments, the GPU choice, printing, settings and window placement, the OS appearance
|
||||
# reader and the system clipboard.
|
||||
@@ -68,3 +71,6 @@ xkbcommon-dl = { version = "0.4.2", features = ["x11"] }
|
||||
# The update helper: a copy of this program started with `--finish-update`
|
||||
# (`craft::update::self_update::finish`).
|
||||
craft = { workspace = true, features = ["update"] }
|
||||
# The nightly Windows identity: an explicit AppUserModelID, so Nightly gets its own taskbar
|
||||
# button instead of sharing the stable app's (#16335's rule for the suite).
|
||||
winsafe = { version = "=0.0.29", default-features = false, features = ["user", "shell"] }
|
||||
|
||||
+43
-5
@@ -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}");
|
||||
|
||||
@@ -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(&[]));
|
||||
}
|
||||
}
|
||||
@@ -123,4 +123,167 @@ mod tests {
|
||||
assert!(supplied.exists());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
|
||||
|
||||
fn boot() -> (u16, Receiver<ControlRequest>, Control) {
|
||||
let options = ControlOptions { token: Some(TOKEN.to_string()), ..ControlOptions::default() };
|
||||
let (rx, control) = start(&options, 0, host(), None).unwrap();
|
||||
let port = control.listening.addr.port();
|
||||
(port, rx, control)
|
||||
}
|
||||
|
||||
/// Answer the next request that reaches the UI with `ok`, and return it.
|
||||
fn answer(rx: &Receiver<ControlRequest>) -> ControlRequest {
|
||||
let req = rx.recv_timeout(std::time::Duration::from_secs(5)).unwrap();
|
||||
let _ = req.reply.send(serde_json::json!({"ok": true, "result": {}}));
|
||||
req
|
||||
}
|
||||
|
||||
/// One connection, several lines.
|
||||
struct Conn(std::io::BufReader<std::net::TcpStream>, std::net::TcpStream);
|
||||
|
||||
impl Conn {
|
||||
fn open(port: u16) -> Self {
|
||||
let s = std::net::TcpStream::connect(("127.0.0.1", port)).unwrap();
|
||||
s.set_read_timeout(Some(std::time::Duration::from_secs(5))).unwrap();
|
||||
Self(std::io::BufReader::new(s.try_clone().unwrap()), s)
|
||||
}
|
||||
fn send(&mut self, line: &str) {
|
||||
use std::io::Write;
|
||||
writeln!(self.1, "{line}").unwrap();
|
||||
}
|
||||
fn recv(&mut self) -> serde_json::Value {
|
||||
use std::io::BufRead;
|
||||
let mut r = String::new();
|
||||
let n = self.0.read_line(&mut r).expect("read reply line");
|
||||
assert!(n > 0, "unexpected EOF while waiting for reply");
|
||||
serde_json::from_str(&r).expect("reply is valid JSON")
|
||||
}
|
||||
fn call(&mut self, line: &str) -> serde_json::Value {
|
||||
self.send(line);
|
||||
self.recv()
|
||||
}
|
||||
/// The server closed the connection.
|
||||
fn closed(&mut self) -> bool {
|
||||
use std::io::BufRead;
|
||||
let mut r = String::new();
|
||||
match self.0.read_line(&mut r) {
|
||||
Ok(0) => true,
|
||||
Err(e) => matches!(
|
||||
e.kind(),
|
||||
std::io::ErrorKind::ConnectionReset
|
||||
| std::io::ErrorKind::ConnectionAborted
|
||||
| std::io::ErrorKind::NotConnected
|
||||
| std::io::ErrorKind::BrokenPipe
|
||||
),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Post-#7101 adaptation of `the_key_on_each_request` (#124, tracked under #7317 / #7720):
|
||||
/// `craft::automation::server` replaced the legacy per-request `"key"` field with one-time
|
||||
/// per-connection token authentication (`docs/control-protocol.md`, Token).
|
||||
#[test]
|
||||
fn a_connection_authenticates_once_with_the_token_and_unauthenticated_requests_are_refused() {
|
||||
let (port, rx, control) = boot();
|
||||
|
||||
// Authenticate once per connection with `params.token`.
|
||||
let mut c = Conn::open(port);
|
||||
let auth_resp = c.call(&format!(r#"{{"id":1,"method":"auth","params":{{"token":"{TOKEN}"}}}}"#));
|
||||
assert_eq!(auth_resp, serde_json::json!({"id": 1, "ok": true, "result": {"authenticated": true}}));
|
||||
|
||||
// Subsequent requests on the authenticated connection carry no token and reach the UI.
|
||||
c.send(r#"{"id":7,"method":"document.inspect","params":{"text":true}}"#);
|
||||
let req = answer(&rx);
|
||||
assert_eq!((req.method.as_str(), &req.params), ("document.inspect", &serde_json::json!({"text": true})));
|
||||
let r = c.recv();
|
||||
assert_eq!((&r["ok"], &r["id"]), (&serde_json::json!(true), &serde_json::json!(7)));
|
||||
|
||||
c.send(r#"{"id":8,"method":"document.inspect","params":{"text":false}}"#);
|
||||
let req = answer(&rx);
|
||||
assert_eq!((req.method.as_str(), &req.params), ("document.inspect", &serde_json::json!({"text": false})));
|
||||
let r = c.recv();
|
||||
assert_eq!((&r["ok"], &r["id"]), (&serde_json::json!(true), &serde_json::json!(8)));
|
||||
drop(c);
|
||||
|
||||
// An unauthenticated connection is refused and closed without reaching the UI.
|
||||
let mut unauth = Conn::open(port);
|
||||
let r = unauth.call(r#"{"id":9,"method":"document.inspect"}"#);
|
||||
assert_eq!(r, serde_json::json!({"id": 9, "ok": false, "error": "authentication required"}));
|
||||
assert!(unauth.closed());
|
||||
assert!(rx.try_recv().is_err(), "unauthenticated request must not reach the UI");
|
||||
drop(unauth);
|
||||
|
||||
// Legacy pre-#7101 per-request `"key"` does not bypass `auth` and closes the connection.
|
||||
let mut legacy = Conn::open(port);
|
||||
let r = legacy.call(&format!(r#"{{"id":10,"key":"{TOKEN}","method":"document.inspect","params":{{"text":true}}}}"#));
|
||||
assert_eq!(r, serde_json::json!({"id": 10, "ok": false, "error": "authentication required"}));
|
||||
assert!(legacy.closed());
|
||||
assert!(rx.try_recv().is_err(), "legacy per-request key must not reach the UI");
|
||||
drop(legacy);
|
||||
|
||||
control.shut_down();
|
||||
}
|
||||
|
||||
/// Post-#7101 adaptation of `params_key_is_only_a_secret_for_auth` (#124, tracked under #7317 / #7729):
|
||||
/// `craft::automation::server` replaced legacy `"key"` / `params.key` secrets with one-time
|
||||
/// per-connection `auth` using `params.token` (`docs/control-protocol.md`, Token).
|
||||
#[test]
|
||||
fn params_token_is_only_a_secret_for_auth() {
|
||||
let (port, rx, control) = boot();
|
||||
|
||||
// Neither `params.token` on a non-`auth` method nor legacy `params.key` on
|
||||
// `document.inspect` or `auth` authenticates.
|
||||
for (id, line) in [
|
||||
(1, format!(r#"{{"id":1,"method":"document.inspect","params":{{"token":"{TOKEN}"}}}}"#)),
|
||||
(2, format!(r#"{{"id":2,"method":"document.inspect","params":{{"key":"{TOKEN}"}}}}"#)),
|
||||
(3, format!(r#"{{"id":3,"method":"auth","params":{{"key":"{TOKEN}"}}}}"#)),
|
||||
] {
|
||||
let mut c = Conn::open(port);
|
||||
assert_eq!(c.call(&line), serde_json::json!({"id": id, "ok": false, "error": "authentication required"}));
|
||||
assert!(c.closed());
|
||||
}
|
||||
assert!(rx.try_recv().is_err(), "refused requests must not reach the UI");
|
||||
|
||||
// Authenticate once with `params.token`; `params.key` and `params.token` on subsequent
|
||||
// non-`auth` methods are forwarded untouched as ordinary parameters.
|
||||
let mut c = Conn::open(port);
|
||||
let auth_resp = c.call(&format!(r#"{{"id":1,"method":"auth","params":{{"token":"{TOKEN}"}}}}"#));
|
||||
assert_eq!(auth_resp, serde_json::json!({"id": 1, "ok": true, "result": {"authenticated": true}}));
|
||||
|
||||
c.send(r#"{"id":2,"method":"ui.key","params":{"key":"Enter"}}"#);
|
||||
let req = answer(&rx);
|
||||
assert_eq!((req.method.as_str(), &req.params), ("ui.key", &serde_json::json!({"key": "Enter"})));
|
||||
let r = c.recv();
|
||||
assert_eq!((&r["ok"], &r["id"]), (&serde_json::json!(true), &serde_json::json!(2)));
|
||||
|
||||
c.send(r#"{"id":3,"method":"document.inspect","params":{"token":"ordinary"}}"#);
|
||||
let req = answer(&rx);
|
||||
assert_eq!((req.method.as_str(), &req.params), ("document.inspect", &serde_json::json!({"token": "ordinary"})));
|
||||
let r = c.recv();
|
||||
assert_eq!((&r["ok"], &r["id"]), (&serde_json::json!(true), &serde_json::json!(3)));
|
||||
drop(c);
|
||||
|
||||
control.shut_down();
|
||||
}
|
||||
|
||||
/// Post-#7101 adaptation of `a_wrong_key_is_refused_and_closed` (#124, tracked under #7317):
|
||||
/// wrong, short, and long `params.token` values are refused and close the connection without
|
||||
/// reaching the UI.
|
||||
#[test]
|
||||
fn a_wrong_token_is_refused_and_closed() {
|
||||
let (port, rx, control) = boot();
|
||||
let wrong = TOKEN.replace('0', "1");
|
||||
let long = format!("{TOKEN}0");
|
||||
for token in ["nope", wrong.as_str(), &TOKEN[..63], long.as_str()] {
|
||||
let mut c = Conn::open(port);
|
||||
let resp = c.call(&format!(r#"{{"id":1,"method":"auth","params":{{"token":"{token}"}}}}"#));
|
||||
assert_eq!(resp, serde_json::json!({"id": 1, "ok": false, "error": "authentication required"}), "{token}");
|
||||
assert!(c.closed(), "{token}");
|
||||
}
|
||||
assert!(rx.try_recv().is_err(), "refused auth attempts must not reach the UI");
|
||||
control.shut_down();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,6 +54,23 @@ pub fn identity() -> AppIdentity {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Every type the button claims is included in identity, and plain text/Markdown are never claimed.
|
||||
#[test]
|
||||
fn xdg_mime_sets_every_word_type_in_one_call() {
|
||||
let id = identity();
|
||||
assert_eq!(id.desktop_id, "ai.storyteller.wordcraft.desktop");
|
||||
assert_eq!(id.registered_name, "WordCraft");
|
||||
for t in [
|
||||
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||
"application/msword",
|
||||
"application/rtf",
|
||||
"application/vnd.oasis.opendocument.text",
|
||||
] {
|
||||
assert!(id.mime_types.iter().any(|a| a == t), "{t}");
|
||||
}
|
||||
assert!(!id.mime_types.iter().any(|a| a == "text/plain" || a == "text/markdown"), "plain text and Markdown are never claimed");
|
||||
}
|
||||
|
||||
/// Every type the button claims is one the desktop entry declares, or desktops ignore it.
|
||||
#[test]
|
||||
fn the_desktop_entry_declares_every_claimed_type() {
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
//! 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)
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
if cfg!(windows) { r"C:\NightlyData\profiles\wordcraft" } else { "/nightly-data/profiles/wordcraft" }
|
||||
}
|
||||
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());
|
||||
}
|
||||
}
|
||||
|
||||
#[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());
|
||||
}
|
||||
}
|
||||
+191
-22
@@ -14,9 +14,16 @@
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
mod appimage_env;
|
||||
#[cfg(test)]
|
||||
mod build_channel;
|
||||
mod build_flavor;
|
||||
mod control_server;
|
||||
mod default_apps;
|
||||
mod launch_profile;
|
||||
mod nightly_session;
|
||||
mod prefs;
|
||||
mod process_identity;
|
||||
mod profile_root;
|
||||
mod region;
|
||||
|
||||
use std::path::PathBuf;
|
||||
@@ -58,6 +65,9 @@ struct App {
|
||||
spool: Spool,
|
||||
/// The control server, when `--control` started one; it removes the token file it made.
|
||||
control: Option<control_server::Control>,
|
||||
/// The app binary's last step as the app leaves, run once at the end of `finish` (a Nightly
|
||||
/// quit ends the process inside AppKit's terminate, after eframe's `on_exit`).
|
||||
exit: Option<Box<dyn FnOnce()>>,
|
||||
}
|
||||
|
||||
impl App {
|
||||
@@ -95,7 +105,12 @@ impl App {
|
||||
if let Some(control) = self.control.take() {
|
||||
control.shut_down();
|
||||
}
|
||||
self.app.start_pending_update();
|
||||
if !launch_profile::current().is_nightly() {
|
||||
self.app.start_pending_update();
|
||||
}
|
||||
if let Some(exit) = self.exit.take() {
|
||||
exit();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -202,10 +217,12 @@ type MakeDefault = Box<dyn Fn() -> Result<DefaultApp, DefaultAppError>>;
|
||||
/// What the app takes from its host beyond the runtime: File › Print through the system spooler,
|
||||
/// personal templates (#2852, made on first save in `Templates` in the settings folder), and making
|
||||
/// WordCraft the default app for Word documents (#295; macOS has no way to, so no button there).
|
||||
fn services(spool: Spool, intake: FileIntake) -> Services {
|
||||
fn services(spool: Spool, intake: FileIntake, nightly: bool) -> Services {
|
||||
// Nightly never claims the stable app's file associations: the button would rewrite the same
|
||||
// OS registration the stable WordCraft owns.
|
||||
#[cfg(any(unix, windows))]
|
||||
let make_default_app =
|
||||
(!cfg!(target_os = "macos")).then(|| -> MakeDefault { Box::new(|| craft::platform::default_app::make_default(&default_apps::identity())) });
|
||||
let make_default_app = (!cfg!(target_os = "macos") && !nightly)
|
||||
.then(|| -> MakeDefault { Box::new(|| craft::platform::default_app::make_default(&default_apps::identity())) });
|
||||
#[cfg(not(any(unix, windows)))]
|
||||
let make_default_app: Option<MakeDefault> = None;
|
||||
Services {
|
||||
@@ -258,9 +275,9 @@ fn build_sha() -> &'static str {
|
||||
|
||||
/// The arguments as text, and apart the files whose names aren't valid Unicode, such as a Latin-1
|
||||
/// one (#1440). A `--control` port, a token or a token file that isn't is an error.
|
||||
fn text_args() -> (Vec<String>, Vec<std::path::PathBuf>) {
|
||||
fn text_args(arguments: Vec<std::ffi::OsString>) -> (Vec<String>, Vec<std::path::PathBuf>) {
|
||||
let (mut args, mut files) = (Vec::new(), Vec::new());
|
||||
for (i, a) in std::env::args_os().skip(1).enumerate() {
|
||||
for (i, a) in arguments.into_iter().enumerate() {
|
||||
match a.into_string() {
|
||||
Ok(a) => args.push(a),
|
||||
Err(a) if args.last().is_some_and(|p| matches!(p.as_str(), "--control" | "--control-token" | "--control-token-file")) => {
|
||||
@@ -318,18 +335,96 @@ fn complain(message: std::fmt::Arguments<'_>) {
|
||||
let _ = std::io::Write::write_fmt(&mut std::io::stderr(), format_args!("wordcraft: {message}\n"));
|
||||
}
|
||||
|
||||
fn initialize_nightly_process_identity() -> Result<(), process_identity::IdentityError> {
|
||||
process_identity::initialize(
|
||||
build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1,
|
||||
wordcraft_ui_egui::os_window::id_for(wordcraft_ui_egui::os_window::LaunchIdentity::NightlyV1),
|
||||
)
|
||||
}
|
||||
|
||||
/// Tell the person why a Launcher launch was refused, with a native message box on a desktop
|
||||
/// session (a Launcher start has no terminal to read standard error from).
|
||||
fn report_launch_profile_error(error: &str) {
|
||||
complain(format_args!("launch profile: {error}"));
|
||||
let desktop_session = cfg!(windows)
|
||||
|| cfg!(target_os = "macos")
|
||||
|| (cfg!(target_os = "linux") && ["DISPLAY", "WAYLAND_DISPLAY"].into_iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty())));
|
||||
if build_flavor::needs_native_error(build_flavor::COMPILED, desktop_session) {
|
||||
if let Err(identity) = initialize_nightly_process_identity() {
|
||||
complain(format_args!("launch profile: {identity}"));
|
||||
return;
|
||||
}
|
||||
let _ = rfd::MessageDialog::new()
|
||||
.set_title("WordCraft Nightly")
|
||||
.set_description(error)
|
||||
.set_level(rfd::MessageLevel::Error)
|
||||
.set_buttons(rfd::MessageButtons::Ok)
|
||||
.show();
|
||||
}
|
||||
}
|
||||
|
||||
/// Select the immutable launch profile before any startup service or side effect.
|
||||
fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
|
||||
// The trusted Launcher protocol is decided before logging, crash handling, the update helper,
|
||||
// fonts, preferences or the settings folder.
|
||||
let argv: Vec<_> = std::env::args_os().skip(1).collect();
|
||||
// Plain `--version`, or the Launcher's `--launch-profile nightly-v1 --profile-root <dir>
|
||||
// --version`: answered before root validation, process identity, IPC or any window.
|
||||
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv))
|
||||
{
|
||||
let line = build_flavor::version(build_flavor::COMPILED, env!("WORDCRAFT_BUILT_VERSION"));
|
||||
let _ = std::io::Write::write_all(&mut std::io::stdout(), format!("{line}\n").as_bytes());
|
||||
return None;
|
||||
}
|
||||
let early = launch_profile::parse(argv)
|
||||
.and_then(|launch| {
|
||||
build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?;
|
||||
initialize_nightly_process_identity().map_err(|error| error.to_string())?;
|
||||
Ok(launch)
|
||||
})
|
||||
.and_then(|launch| launch_profile::prepare(launch, launch_profile::validate_root))
|
||||
.unwrap_or_else(|error| {
|
||||
report_launch_profile_error(&error);
|
||||
std::process::exit(2)
|
||||
});
|
||||
let identity = if early.profile.is_nightly() {
|
||||
wordcraft_ui_egui::os_window::LaunchIdentity::NightlyV1
|
||||
} else {
|
||||
wordcraft_ui_egui::os_window::LaunchIdentity::Stable
|
||||
};
|
||||
if let Err(error) = launch_profile::install(early.profile).and_then(|()| wordcraft_ui_egui::os_window::select_identity(identity)) {
|
||||
report_launch_profile_error(&error);
|
||||
std::process::exit(2);
|
||||
}
|
||||
// One data root for everything the app keeps: preferences, window place, logs, recovery,
|
||||
// fonts, templates, dictionaries and control token files all come from it.
|
||||
if let Some(root) = launch_profile::current().root()
|
||||
&& let Err(error) = wordcraft_control_key::use_settings_dir(root.to_path_buf())
|
||||
{
|
||||
report_launch_profile_error(&error);
|
||||
std::process::exit(2);
|
||||
}
|
||||
Some(early.args)
|
||||
}
|
||||
|
||||
/// Parses the command line, installs logging and the panic hook, restores preferences and window
|
||||
/// geometry, opens requested documents or the Start screen, starts the control server when
|
||||
/// asked, and runs the eframe event loop.
|
||||
fn main() -> eframe::Result {
|
||||
// Windows: the print helper is a copy of this program that runs one job in its own process.
|
||||
// It reads only its own job folder, so it runs before the launch profile is parsed: a Nightly
|
||||
// wants a profile on every start, and the helper must print without one.
|
||||
#[cfg(windows)]
|
||||
if let Some(code) = craft::print::spool::isolated::helper_main() {
|
||||
std::process::exit(code);
|
||||
}
|
||||
let Some(arguments) = prepare_launch() else { return Ok(()) };
|
||||
// Windows: the update helper is a copy of this program started with `--finish-update`.
|
||||
// A Nightly never updates itself: the Launcher owns its updates.
|
||||
#[cfg(windows)]
|
||||
if let Some(result) = craft::update::self_update::finish(&wordcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::<Vec<_>>()) {
|
||||
if !launch_profile::current().is_nightly()
|
||||
&& let Some(result) = craft::update::self_update::finish(&wordcraft_ui_egui::UPDATE_APP, &arguments)
|
||||
{
|
||||
std::process::exit(i32::from(result.is_err()));
|
||||
}
|
||||
// Linux: before anything reads another program's AppImage variables, or a thread starts (#5653).
|
||||
@@ -352,7 +447,7 @@ fn main() -> eframe::Result {
|
||||
let mut flags = ControlOptions::default();
|
||||
let mut files = Vec::new();
|
||||
let mut sample = false;
|
||||
let (args, other_files) = text_args();
|
||||
let (args, other_files) = text_args(arguments);
|
||||
// Only macOS (Finder / LaunchServices) adds these; elsewhere `-NS…` could be a real file name.
|
||||
let args = if cfg!(target_os = "macos") { without_launch_args(args) } else { args };
|
||||
let mut bad_control: Option<Option<String>> = None;
|
||||
@@ -388,6 +483,7 @@ fn main() -> eframe::Result {
|
||||
},
|
||||
"--sample" => sample = true,
|
||||
"--version" => {
|
||||
// A nightly build reported its channel line before this parser ran.
|
||||
println!("wordcraft {} ({})", env!("CARGO_PKG_VERSION"), build_sha());
|
||||
return Ok(());
|
||||
}
|
||||
@@ -422,6 +518,13 @@ fn main() -> eframe::Result {
|
||||
complain(format_args!("--control needs a port number from 1 to 65535, got \"0\""));
|
||||
std::process::exit(2);
|
||||
}
|
||||
// Nightly runs the Launcher's documents only: no control server, token file or automation
|
||||
// switch, and none inherited from a stable launch's environment.
|
||||
if launch_profile::current().is_nightly() && (control.port.is_some() || control.token.is_some() || control.token_file.is_some()) {
|
||||
complain(format_args!("a WordCraft Nightly window does not start a control server; open documents through ArtCraft Launcher"));
|
||||
std::process::exit(2);
|
||||
}
|
||||
let nightly = launch_profile::current().is_nightly();
|
||||
let settings_dir = wordcraft_control_key::settings_dir();
|
||||
// The log file lives in the settings directory, next to the preferences; opened after the
|
||||
// arguments, so `--version` leaves no file behind. Records logged until now are written to it
|
||||
@@ -440,10 +543,16 @@ fn main() -> eframe::Result {
|
||||
None => logger.stderr_only(),
|
||||
}
|
||||
}
|
||||
// A Nightly window always carries its own id; a stable one keeps the Flatpak sandbox's id
|
||||
// when it runs inside one (so docks match the flatpak's desktop file).
|
||||
let app_id = match launch_profile::current().root() {
|
||||
Some(_) => wordcraft_ui_egui::os_window::app_id().to_string(),
|
||||
None => std::env::var("FLATPAK_ID").ok().filter(|id| !id.is_empty()).unwrap_or_else(|| wordcraft_ui_egui::os_window::APP_ID.to_string()),
|
||||
};
|
||||
let mut options = eframe::NativeOptions {
|
||||
viewport: egui::ViewportBuilder::default()
|
||||
.with_title("WordCraft")
|
||||
.with_app_id("ai.storyteller.wordcraft")
|
||||
.with_title(wordcraft_ui_egui::os_window::name_for(wordcraft_ui_egui::os_window::identity()))
|
||||
.with_app_id(app_id)
|
||||
.with_inner_size([1440.0, 920.0])
|
||||
.with_min_inner_size(wordcraft_ui_egui::window_geometry::MIN_SIZE)
|
||||
.with_drag_and_drop(true)
|
||||
@@ -504,9 +613,33 @@ fn main() -> eframe::Result {
|
||||
let _apple_events = craft::platform::open::apple_events::install(sender);
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
drop(sender);
|
||||
// Nightly's own health record: one owner per profile, cleared only by a controlled return.
|
||||
let (nightly_record, health_unavailable) = match nightly_session::Session::begin_with_health(
|
||||
launch_profile::current().root(),
|
||||
env!("WORDCRAFT_BUILT_VERSION"),
|
||||
option_env!("WORDCRAFT_BUILD_SHA"),
|
||||
) {
|
||||
Ok(pair) => pair,
|
||||
Err(error) => {
|
||||
log::warn!("Nightly session health is unavailable: {error}");
|
||||
(None, launch_profile::current().is_nightly())
|
||||
}
|
||||
};
|
||||
let session_health_warning: Option<String> = health_unavailable.then(|| {
|
||||
"WordCraft Nightly could not record session health in its private profile. You can still edit, but abnormal-exit detection is unavailable."
|
||||
.to_string()
|
||||
});
|
||||
let previous_nightly_unclean = nightly_record.as_ref().is_some_and(nightly_session::Session::previous_unclean);
|
||||
let nightly_watch: nightly_session::Shared = Arc::new(Mutex::new(nightly_record));
|
||||
let unclean_notice_shown = Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
// The window body and its exit hook each take a clone of the flag; the return path keeps the
|
||||
// other, so a start that created no window can still finish the record.
|
||||
let session_for_exit = nightly_watch.clone();
|
||||
let noticed_for_exit = unclean_notice_shown.clone();
|
||||
let noticed_in_window = unclean_notice_shown.clone();
|
||||
let exit_settings = settings.clone();
|
||||
let result = eframe::run_native(
|
||||
"WordCraft",
|
||||
wordcraft_ui_egui::os_window::name_for(wordcraft_ui_egui::os_window::identity()),
|
||||
options,
|
||||
Box::new(move |cc| {
|
||||
let ctx = cc.egui_ctx.clone();
|
||||
@@ -528,7 +661,7 @@ fn main() -> eframe::Result {
|
||||
);
|
||||
let shell = ShellInfo::current().backend(if x11 { Backend::X11 } else { Backend::from_env() });
|
||||
let spec = InstallSpec::new(shell, Arc::new(SystemWindows))
|
||||
.app_id("ai.storyteller.wordcraft")
|
||||
.app_id(wordcraft_ui_egui::os_window::app_id())
|
||||
.system(SystemReader::start(wake))
|
||||
.clipboard(Clipboard::new(SystemClipboard::new().decoder(decode_png)))
|
||||
.placement(placement);
|
||||
@@ -547,19 +680,31 @@ fn main() -> eframe::Result {
|
||||
prefs::load_user_dictionary(&mut session, &settings, path);
|
||||
}
|
||||
let spool = Spool::new(host.jobs_shared().clone());
|
||||
let mut app = WordApp::new(session, services(spool.clone(), intake)).with_host(host).with_settings(settings.clone());
|
||||
let mut app = WordApp::new(session, services(spool.clone(), intake, nightly)).with_host(host).with_settings(settings.clone());
|
||||
// PLAN: writer note 9 puts `with_settings` after `with_control`; it comes first here because
|
||||
// the region check below reads the saved region the settings apply.
|
||||
if std::env::var("WORDCRAFT_FILE_DIALOG").is_ok_and(|v| v.trim().eq_ignore_ascii_case("builtin")) {
|
||||
app = app.with_fallback_chooser(true);
|
||||
}
|
||||
app.set_startup_update_check(true);
|
||||
// After the preferences, so the reason it gives is in the interface language.
|
||||
if updates_unsafe {
|
||||
app.disable_self_update();
|
||||
if nightly {
|
||||
// The Launcher installs Nightly; Help › Check for Updates says so instead.
|
||||
app.use_launcher_updates();
|
||||
} else {
|
||||
app.set_startup_update_check(true);
|
||||
// After the preferences, so the reason it gives is in the interface language.
|
||||
if updates_unsafe {
|
||||
app.disable_self_update();
|
||||
}
|
||||
}
|
||||
// Language packs from the suite's font store; an Install click is the person's own.
|
||||
wordcraft_engine::packs::use_font_store(true);
|
||||
// Nightly keeps its own store in the profile, so a pack installed there is not a
|
||||
// change to the stable apps' shared fonts.
|
||||
match launch_profile::current().root() {
|
||||
Some(root) => wordcraft_engine::packs::use_font_store_in(root.join("FontStore"), true),
|
||||
None => {
|
||||
wordcraft_engine::packs::use_font_store(true);
|
||||
}
|
||||
}
|
||||
// A region chosen in File › Options replaces the system's for the first blank
|
||||
// document too (#838).
|
||||
if !sample && app.session.prefs.region.is_some() {
|
||||
@@ -576,7 +721,8 @@ fn main() -> eframe::Result {
|
||||
}
|
||||
}
|
||||
let mut control_server = None;
|
||||
if let Some(port) = control.port
|
||||
if !nightly
|
||||
&& let Some(port) = control.port
|
||||
&& let Some((rx, started)) =
|
||||
control_server::start(&control, port, WindowHost::of(&ctx), wordcraft_control_key::settings_dir().as_deref())
|
||||
{
|
||||
@@ -598,9 +744,32 @@ fn main() -> eframe::Result {
|
||||
for f in other_files {
|
||||
open_non_unicode(&mut app, &f);
|
||||
}
|
||||
Ok(Box::new(App { app, panels, drops, settings, spool, control: control_server }))
|
||||
// The personal agent files, the session record and the control token all live in the
|
||||
// profile; the app's own services are built with the nightly rule in mind.
|
||||
if let Some(warning) = &session_health_warning {
|
||||
app.status_long(warning.clone());
|
||||
}
|
||||
if previous_nightly_unclean {
|
||||
app.status_long(
|
||||
"The previous WordCraft Nightly session did not finish normally. You can report a problem from Help › About. No diagnostics have been sent.",
|
||||
);
|
||||
noticed_in_window.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
Ok(Box::new(App {
|
||||
app,
|
||||
panels,
|
||||
drops,
|
||||
settings,
|
||||
spool,
|
||||
control: control_server,
|
||||
exit: Some(Box::new(move || {
|
||||
nightly_session::finish_once(&session_for_exit, noticed_for_exit.load(std::sync::atomic::Ordering::Relaxed));
|
||||
})),
|
||||
}))
|
||||
}),
|
||||
);
|
||||
// The exit hook has run; this is the no-op fallback for a start that created no window.
|
||||
nightly_session::finish_once(&nightly_watch, unclean_notice_shown.load(std::sync::atomic::Ordering::Relaxed));
|
||||
// The app is dropped by now: whatever it saved on the way out is in the store.
|
||||
if let Err(e) = exit_settings.lock().flush() {
|
||||
log::warn!("preferences: {e}");
|
||||
@@ -802,8 +971,8 @@ mod smoke {
|
||||
let (intake, sender) = FileIntake::new(Wake::new(|| {}));
|
||||
let drops = intake.sender();
|
||||
let session = Session::new(wordcraft_doc::Document::new());
|
||||
let app = WordApp::new(session, services(spool.clone(), intake)).with_host(host).with_settings(settings.clone());
|
||||
Run { app: App { app, panels, drops, settings, spool, control: None }, frames, ctx, sender }
|
||||
let app = WordApp::new(session, services(spool.clone(), intake, false)).with_host(host).with_settings(settings.clone());
|
||||
Run { app: App { app, panels, drops, settings, spool, control: None, exit: None }, frames, ctx, sender }
|
||||
}
|
||||
|
||||
/// One frame as eframe runs it: the input hook once, the logic once, the UI per pass.
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -15,9 +15,11 @@ 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.
|
||||
/// Whether this run reads and writes preferences. `WORDCRAFT_NO_PREFS` turns them off; a Nightly
|
||||
/// profile always keeps its own, so an inherited developer switch cannot leave the app with no
|
||||
/// preferences folder at all.
|
||||
pub fn enabled() -> bool {
|
||||
std::env::var_os("WORDCRAFT_NO_PREFS").is_none()
|
||||
crate::launch_profile::current().is_nightly() || std::env::var_os("WORDCRAFT_NO_PREFS").is_none()
|
||||
}
|
||||
|
||||
/// `custom-dictionary.txt` in the settings folder: the words Add to Dictionary kept (#40).
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -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 |
@@ -4,14 +4,34 @@
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// The folder the desktop app chose before any of its state was read: a Launcher-selected
|
||||
/// Nightly profile (`launch_profile`). Set once, at startup, before the first [`settings_dir`]
|
||||
/// call; tests and the CLI leave it unset.
|
||||
static CHOSEN: std::sync::OnceLock<PathBuf> = std::sync::OnceLock::new();
|
||||
|
||||
/// Point [`settings_dir`] at `dir` for this process. Fails when a folder was already chosen.
|
||||
pub fn use_settings_dir(dir: PathBuf) -> Result<(), String> {
|
||||
CHOSEN.set(dir).map_err(|_| "the settings folder was already selected".into())
|
||||
}
|
||||
|
||||
/// The app's settings folder (preferences, logs, token files): macOS
|
||||
/// `~/Library/Application Support/WordCraft`, Windows `%APPDATA%\WordCraft`, otherwise
|
||||
/// `$XDG_CONFIG_HOME/wordcraft` or `~/.config/wordcraft`.
|
||||
/// `WORDCRAFT_PROFILE_DIR` overrides the entire folder for isolated runs.
|
||||
/// A folder chosen by the app through [`use_settings_dir`] wins: it is a launch decision, not
|
||||
/// an environment variable a child or a wrapper might have inherited. `WORDCRAFT_PROFILE_DIR`
|
||||
/// overrides the entire folder for isolated runs otherwise.
|
||||
pub fn settings_dir() -> Option<PathBuf> {
|
||||
if let Some(path) = CHOSEN.get() {
|
||||
return Some(path.clone());
|
||||
}
|
||||
if let Some(path) = std::env::var_os("WORDCRAFT_PROFILE_DIR").filter(|p| !p.is_empty()) {
|
||||
return Some(PathBuf::from(path));
|
||||
}
|
||||
platform_settings_dir()
|
||||
}
|
||||
|
||||
/// The platform's own folder, when nothing chose one (see [`settings_dir`]).
|
||||
fn platform_settings_dir() -> Option<PathBuf> {
|
||||
if cfg!(target_os = "macos") {
|
||||
std::env::var_os("HOME").map(|h| PathBuf::from(h).join("Library/Application Support/WordCraft"))
|
||||
} else if cfg!(windows) {
|
||||
@@ -67,6 +87,18 @@ mod tests {
|
||||
assert_eq!(parse_instance_id("app=ai.storyteller.wordcraft\n"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_chosen_folder_wins_over_the_environment() {
|
||||
// The chosen folder is process-wide and set once, so this test only reads the rule when
|
||||
// nothing chose one (the crate's own tests and the CLI never do).
|
||||
if CHOSEN.get().is_none() {
|
||||
assert_eq!(settings_dir(), super::platform_settings_dir());
|
||||
assert!(use_settings_dir(PathBuf::from("/chosen/profile")).is_ok());
|
||||
assert_eq!(settings_dir().as_deref(), Some(std::path::Path::new("/chosen/profile")));
|
||||
assert!(use_settings_dir(PathBuf::from("/other")).is_err(), "the folder is selected once");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn key_file_per_instance() {
|
||||
let dir = Path::new("/settings/wordcraft");
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -927,4 +927,32 @@ mod shortcut_tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copy_format_web_alias_respects_user_removal_and_reassignment() {
|
||||
use craft_keymap::{Binding, Chord, CommandRef, Overrides, Policy};
|
||||
|
||||
let mut commands = super::super::registry().all().to_vec();
|
||||
commands.iter_mut().find(|c| c.id == "edit.copyFormat").unwrap().shortcut = copy_format_shortcut(true);
|
||||
let registry = Registry::new(commands);
|
||||
|
||||
let mut keymap = crate::keymap::registry_keymap(®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"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -398,6 +398,28 @@ mod tests {
|
||||
assert!(!page_text(&mut s).contains("{ AUTHOR }"));
|
||||
}
|
||||
|
||||
/// #980: F11 is full screen, as people expect of a desktop app; the field walk keeps Word's
|
||||
/// other keys, Alt+F1 and Alt+Shift+F1 (and Shift+F11).
|
||||
#[test]
|
||||
fn f11_is_full_screen_and_alt_f1_walks_fields() {
|
||||
let s = Session::new(wordcraft_doc::Document::new());
|
||||
let keymap = crate::keymap::registry_keymap(&s.registry, s.keymap());
|
||||
let chord = |c: &str| craft_keymap::Chord::parse(c).unwrap();
|
||||
let key = |k: &str| keymap.holder(&chord(k)).map(|c| c.id);
|
||||
assert_eq!(key("F11").as_deref(), Some("view.fullScreen"));
|
||||
assert_eq!(key("Alt+F1").as_deref(), Some("fields.next"));
|
||||
assert_eq!(key("Alt+Shift+F1").as_deref(), Some("fields.previous"));
|
||||
assert_eq!(key("Shift+F11").as_deref(), Some("fields.previous"));
|
||||
assert_eq!(key("Mod+F11").as_deref(), Some("fields.lock"));
|
||||
let shortcut = s.registry.get("view.fullScreen").map(|c| c.shortcut);
|
||||
if cfg!(target_os = "macos") {
|
||||
assert_eq!(shortcut, Some("Mod+Ctrl+F / F11"));
|
||||
assert_eq!(key("Mod+Ctrl+F").as_deref(), Some("view.fullScreen"));
|
||||
} else {
|
||||
assert_eq!(shortcut, Some("F11"));
|
||||
}
|
||||
}
|
||||
|
||||
/// Editing a code changes the instruction and the result; lock keeps a result through updates;
|
||||
/// unlink turns the field into its text in one undo step; Alt+F1/Shift+F11 walk the fields.
|
||||
#[test]
|
||||
|
||||
@@ -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};
|
||||
|
||||
@@ -188,6 +188,30 @@ fn layout_table_block(input: TableBlockContext<'_, '_, '_>) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// Whether `story` is a header in a document of Word 2010's layout or older (compatibility mode
|
||||
/// below 15), whose text keeps its place beside the header's own floating objects (#6805).
|
||||
fn is_legacy_header(ctx: &Ctx, story: StoryRef) -> bool {
|
||||
ctx.doc.settings.compat_mode < wordcraft_doc::COMPAT_MODE_CURRENT
|
||||
&& matches!(story, StoryRef::Part(id) if ctx.doc.parts.get(&id).is_some_and(|p| p.kind == wordcraft_doc::PartKind::Header))
|
||||
}
|
||||
|
||||
/// Where a top and bottom object at `r` starts and ends for such a header.
|
||||
/// The distance below it counts (Word: 14.4 pt more for 14.4 pt); the one above neither moves it
|
||||
/// nor makes the header taller.
|
||||
fn legacy_reach_of(float: &wordcraft_doc::para::Float, r: Rect) -> Option<(f32, f32)> {
|
||||
let below = if float.dist_bottom.is_finite() { float.dist_bottom.clamp(0.0, 1584.0) } else { 0.0 };
|
||||
let bounds = float.spin().bounds(r);
|
||||
(float.wrap == Wrap::TopAndBottom).then_some((bounds.y, bounds.bottom() + below))
|
||||
}
|
||||
|
||||
/// The bottom of the lowest top and bottom object (`reach`) that starts above `text_bottom`, the
|
||||
/// end of the header's text with the space after its last paragraph (Word counts an object
|
||||
/// starting in it). Word also counts one starting a little further down (about 25 pt below one
|
||||
/// line of text), not modelled here. Zero when there is none.
|
||||
fn legacy_header_reach(text_bottom: f32, reach: &[(f32, f32)]) -> f32 {
|
||||
reach.iter().filter(|(top, _)| *top < text_bottom).map(|(_, bottom)| *bottom).fold(0.0, f32::max)
|
||||
}
|
||||
|
||||
/// Lay out a block list into a free-standing box of `width` (no page breaks): table cells,
|
||||
/// headers, footers, notes, text boxes. Returns items relative to (0, 0) and the height. `frame`
|
||||
/// says where the box sits on its page, for floating objects positioned relative to the page or
|
||||
@@ -217,6 +241,14 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
|
||||
// bottom edge (#3108). Behind-text and in-front-of-text objects don't: a page-anchored logo or
|
||||
// watermark behind a cell's text must not stretch its row (see `align_h` in table.rs).
|
||||
let mut float_objects_bottom = 0.0f32;
|
||||
// A header in a document of Word 2010's layout or older (compatibility mode below 15): its
|
||||
// text keeps its place beside its own objects, which wrap nothing, and only a top and bottom
|
||||
// object reaching down from the text makes the header taller (#6805). Not in a table cell.
|
||||
let legacy_header = !in_cell && is_legacy_header(ctx, story);
|
||||
// Contour wraps were measured in mode 14; earlier modes keep using their existing rule.
|
||||
let legacy_header_contours = legacy_header && ctx.doc.settings.compat_mode == 14;
|
||||
// Top and bottom objects of such a header: where each starts and ends.
|
||||
let mut legacy_reach: Vec<(f32, f32)> = Vec::new();
|
||||
let mut table_areas = Vec::new();
|
||||
let mut page_table_wraps = Vec::new();
|
||||
let mut y = 0.0f32;
|
||||
@@ -307,8 +339,15 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
|
||||
{
|
||||
r.x = keep_in_cell(r.x, r.w, left, right);
|
||||
}
|
||||
let outline = ctx.wrap_outline(o);
|
||||
excl.extend(wrap_area(r, float, outline.as_deref().map(Vec::as_slice)));
|
||||
if (legacy_header && matches!(float.wrap, Wrap::TopAndBottom | Wrap::Square))
|
||||
|| (legacy_header_contours && matches!(float.wrap, Wrap::Tight | Wrap::Through))
|
||||
{
|
||||
// These objects do not reflow the legacy header's own text in Word.
|
||||
legacy_reach.extend(legacy_reach_of(float, r));
|
||||
} else {
|
||||
let outline = ctx.wrap_outline(o);
|
||||
excl.extend(wrap_area(r, float, outline.as_deref().map(Vec::as_slice)));
|
||||
}
|
||||
floats.insert(oi, r);
|
||||
}
|
||||
let rel = rel_exclusions(&excl, 0.0, y);
|
||||
@@ -403,6 +442,7 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
|
||||
}
|
||||
}
|
||||
}
|
||||
y = y.max(legacy_header_reach(y, &legacy_reach));
|
||||
let floats_bottom = float_tables.iter().map(|r| r.bottom()).fold(float_objects_bottom, f32::max);
|
||||
ctx.hide_deleted = outer_hide;
|
||||
BoxLayout { items, height: y.max(0.0), floats_bottom, last_top: last_top.max(0.0), table_areas, page_table_wraps }
|
||||
|
||||
+178
-25
@@ -346,10 +346,19 @@ impl<'a> Flow<'a> {
|
||||
if !(rp.keep_lines || (rp.keep_next && pb.y + height <= pb.bottom + 0.01)) {
|
||||
return before;
|
||||
}
|
||||
let need = height + if rp.keep_next { next_first_line(ctx, self.block, self.width, 0, &mut ctx.counters.clone()) } else { 0.0 };
|
||||
// A paragraph closing a section that the next one starts on a new page keeps with
|
||||
// nothing: what follows is not on this page (Word ignores Keep with next there; measured for a next-page break, odd and even by analogy).
|
||||
let closes_page = pb.next_starts_page && self.p.section.is_some();
|
||||
let need = height
|
||||
+ if rp.keep_next && !closes_page {
|
||||
next_first_line(ctx, self.block, self.laid_width, 0, pb.next_starts_page, &mut ctx.counters.clone())
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
// (Against the whole column: balanced columns grow to hold it.)
|
||||
// With the 0.01 pt of slack the other fit checks take.
|
||||
if pb.y + need > pb.bottom + 0.01 && !pb.fresh() && need <= pb.next_room(self.body_top) {
|
||||
// With the 0.01 pt of slack the other fit checks take. Balancing from Word 2013's layout
|
||||
// keeps the lines and the next paragraph together at the top of a column too (#6821).
|
||||
if pb.y + need > pb.bottom + 0.01 && (!pb.fresh() || Self::strict_widow_control(ctx, pb)) && need <= pb.next_room(self.body_top) {
|
||||
pb.advance(self.block, self.body_top);
|
||||
pb.y += rp.space_before.min(0.0);
|
||||
return rp.space_before.min(0.0);
|
||||
@@ -357,6 +366,25 @@ impl<'a> Flow<'a> {
|
||||
before
|
||||
}
|
||||
|
||||
/// Balancing from Word 2013's layout, a paragraph that was moved to the top of a column by
|
||||
/// the lines before it (not by `keep_together`) keeps its lines, or itself with the next
|
||||
/// paragraph, together there too: asks again, and places the paragraph's floats again where it
|
||||
/// ends up (#6821).
|
||||
fn keep_again(&mut self, ctx: &mut Ctx, pb: &mut PageBuilder, rooms: Rooms) {
|
||||
while self.l0 == 0 && (self.pl.rp.keep_lines || self.pl.rp.keep_next) && pb.fresh() && Self::strict_widow_control(ctx, pb) {
|
||||
let (col, pages) = (pb.col, pb.pages.len());
|
||||
let before = self.keep_together(ctx, pb, rooms, 0.0);
|
||||
if (pb.col, pb.pages.len()) == (col, pages) {
|
||||
break;
|
||||
}
|
||||
// Reflow before testing the new column: wraps can change the paragraph's height.
|
||||
let y0 = pb.y;
|
||||
self.reanchor(ctx, pb, (y0, before), &[]);
|
||||
self.anchor_y = y0 - before;
|
||||
(self.rechecked, self.forced) = (false, Vec::new());
|
||||
}
|
||||
}
|
||||
|
||||
/// The lines going into a new column (or page) were broken around the wrap areas where the
|
||||
/// paragraph started: break them again around this column's (the lines before stay as they
|
||||
/// were, and so do the paragraph's own floating objects), when they differ (#1374).
|
||||
@@ -447,14 +475,19 @@ impl<'a> Flow<'a> {
|
||||
fit
|
||||
}
|
||||
|
||||
/// Whether the line may overflow the page: one holding nothing but a page or column break stays
|
||||
/// at the bottom of the page even when it doesn't fit (it only ends the page, and moving it
|
||||
/// would leave a blank page behind it, as in Word), and so does an empty paragraph closing a
|
||||
/// section before a new page (measured in Word: it stays on a full page instead of starting
|
||||
/// one of its own).
|
||||
/// Whether the line (the paragraph's line `l0`) may overflow the page: one holding nothing but
|
||||
/// a page or column break, with text after it in the paragraph, stays at the bottom of the
|
||||
/// page even when it doesn't fit (it only ends the page, and moving it would leave a blank
|
||||
/// page behind it, as in Word), and so does an empty paragraph closing a section before a new
|
||||
/// page (measured in Word: it stays on a full page instead of starting one of its own).
|
||||
/// Measured in Word: a paragraph of only a page break is an ordinary line, and when its mark's
|
||||
/// text doesn't fit it goes to the next page, blank page and all.
|
||||
fn stays_at_bottom(&self, pb: &PageBuilder, l: ¶::Line) -> bool {
|
||||
let p = self.p;
|
||||
let mark_only_after =
|
||||
l.end == LineEnd::PageBreak && self.pl.lines.get(self.l0 + 1..).is_some_and(|rest| rest.iter().all(|m| only_markers(p, m.start..m.stop)));
|
||||
let only_break = matches!(l.end, LineEnd::PageBreak | LineEnd::ColumnBreak)
|
||||
&& !mark_only_after
|
||||
&& p.text
|
||||
.get(l.start..l.stop)
|
||||
.is_some_and(|t| t.chars().all(|c| matches!(c, wordcraft_doc::para::PAGE_BREAK | wordcraft_doc::para::COLUMN_BREAK)));
|
||||
@@ -477,25 +510,46 @@ impl<'a> Flow<'a> {
|
||||
|
||||
/// The end of the lines on this page after widow/orphan control, and keeping the rows beside
|
||||
/// floating objects together.
|
||||
fn settled_end(&self, pb: &PageBuilder, fit: &Fit) -> usize {
|
||||
/// Also says whether, balancing from Word 2013's layout, widow/orphan control alone moved every
|
||||
/// line back (the next column has them, #6821).
|
||||
fn settled_end(&self, ctx: &Ctx, pb: &PageBuilder, fit: &Fit) -> (usize, bool) {
|
||||
let (n, l0, mut l1) = (self.n(), self.l0, fit.l1);
|
||||
// Widow/orphan control (2-line minimum at either end).
|
||||
// Widow/orphan control (2-line minimum at either end). Balancing the columns of a
|
||||
// section's last page from Word 2013's layout (compatibility mode 15) applies it at the
|
||||
// top of a column too, where moving on is no loss, and never leaves one line of a
|
||||
// paragraph that goes on in the next column, even when the paragraph began in an earlier
|
||||
// one (#6821).
|
||||
let strict = Self::strict_widow_control(ctx, pb);
|
||||
if fit.forced.is_none() && l1 < n && self.pl.rp.widow_control && n >= 2 {
|
||||
if l1 - l0 == 1 && l0 == 0 && !pb.fresh() {
|
||||
if l1 - l0 == 1 && l0 == 0 && (!pb.fresh() || strict) {
|
||||
l1 = l0; // orphan: move the first line to the next page
|
||||
} else if n - l1 == 1 && (l1 - l0 >= 3 || (l0 > 0 && l1 - l0 >= 2)) {
|
||||
l1 -= 1; // widow: take one more line along
|
||||
} else if n - l1 == 1 && l0 == 0 && l1 - l0 == 2 && !pb.fresh() {
|
||||
} else if n - l1 == 1 && l0 == 0 && l1 - l0 == 2 && (!pb.fresh() || strict) {
|
||||
// Neither split of a three-line paragraph is allowed (two and a widow, or an
|
||||
// orphan and two): it moves whole, as in Word.
|
||||
l1 = l0;
|
||||
}
|
||||
// One line of a continued paragraph, with more after it (what was left of two lines
|
||||
// after the widow line went along included): the rest moves with it.
|
||||
if strict && l0 > 0 && l1 - l0 == 1 && l1 < n {
|
||||
l1 = l0;
|
||||
}
|
||||
}
|
||||
let moved_on = strict && fit.l1 > l0 && l1 == l0;
|
||||
// A row (text both sides of a floating object) stays together.
|
||||
while l1 > l0 && l1 < n && self.pl.lines.get(l1).is_some_and(|l| l.beside) {
|
||||
l1 -= 1;
|
||||
}
|
||||
l1
|
||||
(l1, moved_on)
|
||||
}
|
||||
|
||||
/// Whether the columns of this page are being balanced (`balance_columns`) and the document
|
||||
/// has Word 2013's layout: Word then keeps the lines of a paragraph together that widow or
|
||||
/// orphan control would split, at the top of a column as anywhere (#6821). Before compatibility
|
||||
/// mode 15 it splits them.
|
||||
fn strict_widow_control(ctx: &Ctx, pb: &PageBuilder) -> bool {
|
||||
ctx.doc.settings.compat_mode >= 15 && !pb.relaxed && pb.balance.is_some_and(|(page, _)| page + 1 == pb.pages.len())
|
||||
}
|
||||
|
||||
/// Nothing fits on this page: move to the next column or page, and place the floats again
|
||||
@@ -656,16 +710,16 @@ impl<'a> Flow<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Late floats placed for lines that went on after all (past `l1`) wait for the next piece;
|
||||
/// one whose own wrap pushed its line on stays, as before. Whether the lines from `l0` are to
|
||||
/// be broken again without them. Does nothing once the wrap relays are used up
|
||||
/// Late floats placed for lines past `l1` wait for the next piece. An overflow line keeps
|
||||
/// its floats because it is still emitted here. Whether the lines from `l0` are to be broken
|
||||
/// again without the released floats. Does nothing once the wrap relays are used up
|
||||
/// ([`MAX_WRAP_RELAYS`]).
|
||||
fn settle_late(&mut self, pb: &mut PageBuilder, l1: usize) -> bool {
|
||||
fn settle_late(&mut self, pb: &mut PageBuilder, l1: usize, overflow: bool) -> bool {
|
||||
let l0 = self.l0;
|
||||
if l0 == 0 || pb.web || self.late.placed.is_empty() || self.wrap_relays >= MAX_WRAP_RELAYS {
|
||||
return false;
|
||||
}
|
||||
let end = if l1 == l0 && pb.fresh() { l0 + 1 } else { l1 }; // what the overflow keeps
|
||||
let end = l1 + usize::from(overflow);
|
||||
let moved = self.late.release(self.p, &self.pl, end, &mut pb.excl) || self.late.keep_back(self.p, &self.pl, l0..end);
|
||||
moved && l1 > l0
|
||||
}
|
||||
@@ -850,6 +904,7 @@ fn place_para_in_flow(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block:
|
||||
f.anchor_y = y0 - applied_before;
|
||||
}
|
||||
while f.l0 < f.n() {
|
||||
f.keep_again(ctx, pb, rooms);
|
||||
f.place_due_late(ctx, pb);
|
||||
f.relay_wrap(ctx, pb);
|
||||
f.relay_pages(ctx, pb);
|
||||
@@ -860,12 +915,20 @@ fn place_para_in_flow(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block:
|
||||
let lead = if f.l0 == 0 { first.top.max(0.0) + rooms.top } else { 0.0 };
|
||||
let notes = para_notes(ctx.doc, p, &f.pl);
|
||||
let mut fit = f.fit_lines(ctx, pb, ¬es, lead);
|
||||
fit.l1 = f.settled_end(pb, &fit);
|
||||
if f.settle_late(pb, fit.l1) {
|
||||
let (end, widowed) = f.settled_end(ctx, pb, &fit);
|
||||
fit.l1 = end;
|
||||
// On a fresh column an unfitting line can overflow. Strict widow control instead moves
|
||||
// the lines on without emitting anything and must release their late floats as well.
|
||||
let overflow = end == f.l0 && pb.fresh() && !widowed;
|
||||
if f.settle_late(pb, end, overflow) {
|
||||
continue;
|
||||
}
|
||||
if fit.l1 == f.l0 {
|
||||
if !pb.fresh() {
|
||||
// Balancing: widow/orphan control moved all the lines that fit on to the next column
|
||||
// (or, short of room, the page after, which fails the try), where the lines of a
|
||||
// column's first paragraph would otherwise overflow it. Lines pushed back for a row
|
||||
// beside a floating object keep the overflow as before.
|
||||
if !overflow {
|
||||
f.move_on(ctx, pb);
|
||||
continue;
|
||||
}
|
||||
@@ -1005,8 +1068,9 @@ fn space_after_kept(ctx: &Ctx, block: usize, rp: &wordcraft_doc::resolve::Resolv
|
||||
/// of a three-line one under that control (two would leave a widow), or all
|
||||
/// of it under keep lines together — or all of it and what it keeps with in turn when it is
|
||||
/// kept with the next too (a chain moves together in Word). Word carries a kept heading over
|
||||
/// when the paragraph after it cannot start on the page (#966).
|
||||
fn next_first_line(ctx: &mut Ctx, block: usize, width: f32, depth: usize, counters: &mut Counters) -> f32 {
|
||||
/// when the paragraph after it cannot start on the page (#966). `new_page`: the next section starts
|
||||
/// on a new page, so the chain ends at the paragraph closing this one.
|
||||
fn next_first_line(ctx: &mut Ctx, block: usize, width: f32, depth: usize, new_page: bool, counters: &mut Counters) -> f32 {
|
||||
match ctx.doc.body.get(block + 1).map(|b| &**b) {
|
||||
Some(Block::Para(p)) => {
|
||||
// Keep list indents and label metrics without consuming the document counters.
|
||||
@@ -1041,9 +1105,16 @@ fn next_first_line(ctx: &mut Ctx, block: usize, width: f32, depth: usize, counte
|
||||
// Its border room, unless it joins the paragraph before (or after) in one box.
|
||||
let own = Edges::own(&pl, 0, pl.lines.len());
|
||||
let top = if joined(ctx.doc, &ctx.doc.body, block + 1, Some(block), None) { 0.0 } else { own.top };
|
||||
if pl.rp.keep_next && depth < 8 {
|
||||
// The paragraph closing the section, when the next section starts a new page, keeps
|
||||
// with nothing on this page (Word ignores its Keep with next).
|
||||
if pl.rp.keep_next && depth < 8 && !(new_page && p.section.is_some()) {
|
||||
let bottom = if joined(ctx.doc, &ctx.doc.body, block + 1, Some(block + 2), None) { 0.0 } else { own.bottom };
|
||||
pl.rp.space_before + top + pl.height + bottom + pl.rp.space_after + next_first_line(ctx, block + 1, width, depth + 1, counters)
|
||||
pl.rp.space_before
|
||||
+ top
|
||||
+ pl.height
|
||||
+ bottom
|
||||
+ pl.rp.space_after
|
||||
+ next_first_line(ctx, block + 1, width, depth + 1, new_page, counters)
|
||||
} else {
|
||||
// The room this one needs to start on the page with the kept paragraph before
|
||||
// it (#966).
|
||||
@@ -1067,3 +1138,85 @@ fn next_first_line(ctx: &mut Ctx, block: usize, width: f32, depth: usize, counte
|
||||
None => 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use wordcraft_doc::Pos;
|
||||
use wordcraft_doc::para::{Anchor, Float, LINE_BREAK, Wrap, WrapText};
|
||||
use wordcraft_doc::props::LineSpacing;
|
||||
|
||||
#[test]
|
||||
fn strict_balancing_remeasures_kept_lines_in_the_next_column() {
|
||||
crate::test_fonts();
|
||||
let mut doc = Document::new();
|
||||
doc.settings.compat_mode = 15;
|
||||
doc.last_section.columns.count = 2;
|
||||
let mut p = Paragraph::with_text("One two three four five six", Default::default());
|
||||
p.props.line_spacing = Some(LineSpacing::Exactly(14.0));
|
||||
p.props.keep_lines = Some(true);
|
||||
doc.body = vec![wordcraft_doc::para_block(p)];
|
||||
let p = doc.body[0].as_para().unwrap();
|
||||
|
||||
crate::pass::with_flow_page(&doc, |ctx, pb| {
|
||||
let top = pb.top;
|
||||
pb.balance = Some((0, 28.1));
|
||||
pb.cap_columns();
|
||||
// A preceding floating object leaves a narrow strip of the first column, but does
|
||||
// not occupy the second column. The same kept paragraph fits there in one line.
|
||||
pb.excl.push((Rect::new(pb.col_x(), top, pb.col_w() - 26.0, 100.0), false, None, WrapText::BothSides, false));
|
||||
place_para_in_flow(ctx, pb, p, 0, top);
|
||||
|
||||
assert_eq!(pb.pages.len(), 1, "a fitting candidate kept the balance attempt on its page");
|
||||
assert_eq!(pb.col, 1);
|
||||
assert!(
|
||||
pb.pages[0]
|
||||
.items
|
||||
.iter()
|
||||
.any(|item| { matches!(item, Placed::Lines { x, l0: 0, l1: 1, story: StoryRef::Body, .. } if (*x - pb.col_x()).abs() < 0.01) })
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_widow_control_releases_a_late_float_when_no_line_is_emitted() {
|
||||
crate::test_fonts();
|
||||
let mut doc = Document::new();
|
||||
doc.settings.compat_mode = 15;
|
||||
doc.last_section.columns.count = 2;
|
||||
let mut p = Paragraph::with_text(&format!("First{LINE_BREAK}Second{LINE_BREAK}Third"), Default::default());
|
||||
p.props.line_spacing = Some(LineSpacing::Exactly(14.0));
|
||||
p.props.widow_control = Some(true);
|
||||
doc.body = vec![wordcraft_doc::para_block(p)];
|
||||
let anchor = Pos::body(0, "First".len() + LINE_BREAK.len_utf8());
|
||||
let float = Float { wrap: Wrap::Square, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, ..Default::default() };
|
||||
doc.insert_object(&anchor, crate::tests::rect_shape(20.0, 20.0, float), &Default::default()).unwrap();
|
||||
let p = doc.body[0].as_para().unwrap();
|
||||
|
||||
crate::pass::with_flow_page(&doc, |ctx, pb| {
|
||||
let top = pb.top;
|
||||
let height = 14.1;
|
||||
pb.advance(0, top); // start in the last column of the previous page
|
||||
pb.bottom = top + height;
|
||||
pb.balance = Some((1, height));
|
||||
let mut flow = Flow::new(ctx, pb, p, (0, top));
|
||||
assert!(pb.excl.is_empty(), "the float waits for its anchor line");
|
||||
|
||||
// Continue after the first line. The balance attempt can fit only one of the two lines left.
|
||||
flow.l0 = 1;
|
||||
pb.advance(0, top);
|
||||
assert!(pb.fresh());
|
||||
assert!((pb.bottom - pb.top - height).abs() < 0.01);
|
||||
flow.place_due_late(ctx, pb);
|
||||
assert_eq!(pb.excl.len(), 1, "the anchor line fits before widow control");
|
||||
|
||||
let fit = flow.fit_lines(ctx, pb, &[], 0.0);
|
||||
assert_eq!(fit.l1, 2);
|
||||
let (end, widowed) = flow.settled_end(ctx, pb, &fit);
|
||||
assert_eq!((end, widowed), (1, true));
|
||||
let overflow = end == flow.l0 && pb.fresh() && !widowed;
|
||||
assert!(!flow.settle_late(pb, end, overflow));
|
||||
assert!(pb.excl.is_empty(), "no text is emitted here, so no wrap area may remain here");
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,6 +71,9 @@ pub(crate) struct PageBuilder<'a> {
|
||||
/// Balancing columns: (page index, column height) — that page's columns end `height` below
|
||||
/// the top of the section on it.
|
||||
pub(crate) balance: Option<(usize, f32)>,
|
||||
/// Balancing without the strict widow/orphan and keep rules of Word 2013's layout (#6821): the
|
||||
/// last try when even the full column height does not hold the text with them.
|
||||
pub(crate) relaxed: bool,
|
||||
/// The page with the last explicit column break.
|
||||
pub(crate) col_break_page: Option<usize>,
|
||||
/// The section's footnotes go right below its text, not at the page bottom ...
|
||||
|
||||
@@ -856,8 +856,11 @@ fn break_positions(text: &str, rp: &wordcraft_doc::resolve::ResolvedPara) -> Vec
|
||||
// keeps a hyphen and a number together (LB25), and when a slash and a letter follow
|
||||
// ("Dataprotection-" / "/Secrecyviolation", #3408), where LB13 forbids a break before the
|
||||
// slash: add those positions back. Word keeps "fitness-/1589" whole, so a slash before a digit
|
||||
// gains no break. Only U+002D is added here; a non-breaking hyphen (U+2011) and a minus sign
|
||||
// (U+2212) stay unbreakable, and the other dashes keep their ordinary UAX #14 breaks.
|
||||
// gains no break. Word also breaks between two hyphens in a row ("--------" is a ruled line
|
||||
// that wraps at any hyphen), where UAX #14 keeps them together (LB21): without it a row of
|
||||
// hyphens after a gap moves to the next line whole instead of filling the line first. Only
|
||||
// U+002D is added here; a non-breaking hyphen (U+2011) and a minus sign (U+2212) stay
|
||||
// unbreakable, and the other dashes keep their ordinary UAX #14 breaks.
|
||||
let hyphen_breaks: Vec<usize> = text
|
||||
.match_indices('-')
|
||||
.filter_map(|(pos, _)| {
|
||||
@@ -866,6 +869,7 @@ fn break_positions(text: &str, rp: &wordcraft_doc::resolve::ResolvedPara) -> Vec
|
||||
match next.next() {
|
||||
Some(n) if n.is_ascii_digit() => Some(i),
|
||||
Some('/') => next.next().is_some_and(char::is_alphabetic).then_some(i),
|
||||
Some('-') => Some(i),
|
||||
_ => None,
|
||||
}
|
||||
})
|
||||
|
||||
@@ -225,6 +225,7 @@ fn new_page_builder<'p>(
|
||||
max_y: 0.0,
|
||||
content_bottom: 0.0,
|
||||
balance: None,
|
||||
relaxed: false,
|
||||
col_break_page: None,
|
||||
sect_beneath: false,
|
||||
beneath: false,
|
||||
@@ -236,6 +237,18 @@ fn new_page_builder<'p>(
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) fn with_flow_page(doc: &Document, test: impl FnOnce(&mut Ctx<'_>, &mut PageBuilder<'_>)) {
|
||||
let mut cache = LayoutCache::new();
|
||||
let opts = LayoutOptions::default();
|
||||
let mut ctx = new_ctx(doc, &mut cache, &opts, (&HashMap::new(), None, &Totals::first_guess(1)));
|
||||
let sect = &doc.last_section;
|
||||
let early = EarlyFloats::new();
|
||||
let mut page = new_page_builder(sect, sect.page_num_format, &early, false, false);
|
||||
page.new_page(0, sect.margin_top);
|
||||
test(&mut ctx, &mut page);
|
||||
}
|
||||
|
||||
/// Endnotes in document order, with the section of their reference; placed at the end of a
|
||||
/// section that keeps them there, else at the end of the document.
|
||||
fn endnote_queue(ctx: &Ctx) -> VecDeque<(u32, usize)> {
|
||||
@@ -694,7 +707,9 @@ fn balance_pass<'a>(
|
||||
(page, top, h): (usize, f32, f32),
|
||||
body_top: f32,
|
||||
) -> bool {
|
||||
let relaxed = pb.relaxed;
|
||||
snap.restore(pb, ctx);
|
||||
pb.relaxed = relaxed;
|
||||
pb.balance = Some((page, h));
|
||||
pb.cap_columns();
|
||||
for block in first..end {
|
||||
@@ -773,13 +788,26 @@ fn balance_columns<'a>(ctx: &mut Ctx, pb: &mut PageBuilder<'a>, blocks: (usize,
|
||||
last = Some((mid, ok));
|
||||
}
|
||||
// End on the best height (the full column, as laid out first, when none was shorter).
|
||||
let mut fits = true;
|
||||
if last != Some((hi, true)) {
|
||||
thrown = discard(ctx);
|
||||
if !pass(ctx, pb, hi) && hi < full {
|
||||
fits = pass(ctx, pb, hi);
|
||||
if !fits && hi < full {
|
||||
thrown = discard(ctx);
|
||||
pass(ctx, pb, full);
|
||||
fits = pass(ctx, pb, full);
|
||||
}
|
||||
}
|
||||
// From Word 2013's layout the strict widow/orphan and keep rules (`Flow::strict_widow_control`)
|
||||
// can push text past even the full column (on a page whose columns are only a couple of lines
|
||||
// high, where moving a line on to the next column never helps). The layout first made, without
|
||||
// them, always fit it, so lay the page out as it was then rather than leave the pass that
|
||||
// spilled to a new page.
|
||||
if !fits {
|
||||
thrown = discard(ctx);
|
||||
pb.relaxed = true;
|
||||
pass(ctx, pb, full);
|
||||
pb.relaxed = false;
|
||||
}
|
||||
thrown
|
||||
}
|
||||
|
||||
|
||||
@@ -926,6 +926,18 @@ fn split_row_with(row: &RowLayout, cut: f32, whole_cells: bool) -> Option<(RowLa
|
||||
let own_depth = row.items.iter().filter_map(|it| if let Placed::Cell { table, .. } = it { Some(table.0.len()) } else { None }).min();
|
||||
// The first line of each paragraph that moves on (`l1` when all of them stay), by cell and
|
||||
// item.
|
||||
// The top of a cell's text on this page decides which paragraph starts the cell's part of the
|
||||
// page. Only text in the flow counts: a floating picture or shape anchored in the cell can sit
|
||||
// above it without the text being any less the first.
|
||||
let content_top = |it: &Placed| -> Option<f32> {
|
||||
if background(it) {
|
||||
return None;
|
||||
}
|
||||
if let Some((_, _, _, y)) = text_lines(it) {
|
||||
return Some(y);
|
||||
}
|
||||
it.turned_bounds().map(|r| r.y)
|
||||
};
|
||||
let splits: Vec<Vec<usize>> = cells
|
||||
.iter()
|
||||
.zip(&ends)
|
||||
@@ -933,13 +945,18 @@ fn split_row_with(row: &RowLayout, cut: f32, whole_cells: bool) -> Option<(RowLa
|
||||
// Where the cell's text ends: the paragraph ending lowest is the cell's last.
|
||||
let lowest =
|
||||
items.iter().filter_map(|it| text_lines(it).and_then(|(p, l0, l1, y)| crate::item_bottom(y, p, l0, l1))).fold(f32::MIN, f32::max);
|
||||
// The top of what the cell holds on this page: a paragraph there starts the cell's
|
||||
// part of the page, so a row that doesn't start below other content has nowhere to
|
||||
// move it to (see `line_split`).
|
||||
let cell_top = items.iter().filter_map(&content_top).fold(f32::MAX, f32::min);
|
||||
items
|
||||
.iter()
|
||||
.map(|it| {
|
||||
let Some((para, l0, l1, y)) = text_lines(it) else { return 0 };
|
||||
// The cell's last paragraph ends with the cell's content (its space after).
|
||||
let last = l1 == para.lines.len() && crate::item_bottom(y, para, l0, l1).is_some_and(|b| b >= lowest - 0.01);
|
||||
line_split(para, (l0, l1), y, limit, end.filter(|_| last))
|
||||
let first = !whole_cells && y <= cell_top + 0.01;
|
||||
line_split(para, (l0, l1), y, limit, end.filter(|_| last), first)
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
@@ -1262,7 +1279,16 @@ fn text_lines(it: &Placed) -> Option<(&ParaLayout, usize, usize, f32)> {
|
||||
/// above `limit`: the last line of a cell's last paragraph needs room down to the cell's content
|
||||
/// `end`, its space after. Widow control keeps two lines on either side of the break, or moves
|
||||
/// the paragraph on whole.
|
||||
fn line_split(para: &ParaLayout, (l0, l1): (usize, usize), y: f32, limit: f32, end: Option<f32>) -> usize {
|
||||
///
|
||||
/// `first`: the paragraph is the topmost content of its cell on a page the row doesn't start
|
||||
/// below other content on (the row continues from the page before, or starts the page). Moving
|
||||
/// it whole would gain nothing, and Word then splits it where the lines fall (measured with
|
||||
/// synthetic documents, Word for Windows 16.0, compatibility mode 15): a lone first line stays,
|
||||
/// and a three-line paragraph with room for two splits two and one, not leaving the first line
|
||||
/// alone (a continuation's lone line stays too). A paragraph of four lines or more still takes
|
||||
/// one more line along with its widow.
|
||||
/// Without this, nothing was kept and the row ran off the bottom of the page (#6823).
|
||||
fn line_split(para: &ParaLayout, (l0, l1): (usize, usize), y: f32, limit: f32, end: Option<f32>, first: bool) -> usize {
|
||||
let n = para.lines.len();
|
||||
let mut k = l0;
|
||||
while k < l1 {
|
||||
@@ -1276,12 +1302,16 @@ fn line_split(para: &ParaLayout, (l0, l1): (usize, usize), y: f32, limit: f32, e
|
||||
// The body's rule differs: there a widow takes a line along only when three or more lines are
|
||||
// on the page (`place_para_in_flow`).
|
||||
if para.rp.widow_control && k > l0 && k < l1 {
|
||||
// A widow: take one more line along.
|
||||
// A widow: take one more line along, unless that leaves nothing of a paragraph that
|
||||
// starts the page on it, or its first line alone.
|
||||
if n - k == 1 {
|
||||
k -= 1;
|
||||
let taken = k - 1;
|
||||
if !(first && (taken <= l0 || (l0 == 0 && taken == 1))) {
|
||||
k = taken;
|
||||
}
|
||||
}
|
||||
// An orphan (the first line alone): the paragraph moves on whole.
|
||||
if l0 == 0 && k == 1 {
|
||||
if l0 == 0 && k == 1 && !first {
|
||||
k = 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -255,6 +255,13 @@ pub(crate) fn place_table(ctx: &mut Ctx, pb: &mut PageBuilder, t: &wordcraft_doc
|
||||
.rows
|
||||
.get(ri)
|
||||
.is_some_and(|r| r.props.cant_split || (r.props.height_rule == HeightRule::Exact && r.props.height.is_some_and(|h| h > 0.0)));
|
||||
// A Can't Split row (not an exact one) that is taller than a page splits where the page
|
||||
// ends, as in Word (measured with synthetic documents): it moves to a new page first
|
||||
// when it fits there, and only on a page it still doesn't fit does it break.
|
||||
let splits_when_too_tall = ri >= header_rows.len()
|
||||
&& t.rows
|
||||
.get(ri)
|
||||
.is_some_and(|r| r.props.cant_split && !(r.props.height_rule == HeightRule::Exact && r.props.height.is_some_and(|h| h > 0.0)));
|
||||
let mut rest: Option<table::RowLayout> = None;
|
||||
// On a new page holding only the repeated header rows.
|
||||
let mut fresh = false;
|
||||
@@ -290,7 +297,9 @@ pub(crate) fn place_table(ctx: &mut Ctx, pb: &mut PageBuilder, t: &wordcraft_doc
|
||||
// (#4272): moving on can give the cell room there.
|
||||
let first_part = rest.is_none() && !pb.at_top() && !fresh && !under_top_headers;
|
||||
let moves_on = first_part && short_of_min(ri, room);
|
||||
let split = match (splittable && !moves_on && !defer_kept, first_part) {
|
||||
// A row that fits the room but for the border below it is still placed whole.
|
||||
let too_tall_to_keep = splits_when_too_tall && !first_part && cur.height > room + 0.01;
|
||||
let split = match ((splittable || too_tall_to_keep) && !moves_on && !defer_kept, first_part) {
|
||||
(false, _) => None,
|
||||
(true, true) => split_keeping_nested(ctx.doc, cur, room),
|
||||
// On a fresh page, a nested row taller than the room splits rather than overflowing.
|
||||
|
||||
+100
-1
@@ -5,12 +5,15 @@ use wordcraft_doc::props::{Align, Border, BorderStyle, Borders, ParaProps, TextD
|
||||
use wordcraft_doc::{Pos, Table};
|
||||
|
||||
mod autospace;
|
||||
mod balanced_tail;
|
||||
mod bidi;
|
||||
mod budget;
|
||||
mod cell_floats;
|
||||
mod complex;
|
||||
mod float_top;
|
||||
mod grid;
|
||||
mod header_legacy_float;
|
||||
mod keep_next_section;
|
||||
mod ligature;
|
||||
pub(crate) mod linear;
|
||||
mod missing_glyphs;
|
||||
@@ -20,6 +23,7 @@ mod numeral;
|
||||
mod pages;
|
||||
mod styleref;
|
||||
mod table_contact;
|
||||
mod table_first_line;
|
||||
mod textbox;
|
||||
mod vertical;
|
||||
|
||||
@@ -4664,7 +4668,8 @@ fn tall_rows_split_across_pages() {
|
||||
.find_map(|i| if let Placed::Lines { path, para, .. } = i { (path.0 == vec![1, 0, 0, 0]).then_some(para.lines.len()) } else { None })
|
||||
.unwrap_or(0);
|
||||
assert_eq!(total, n);
|
||||
// "Can't split" rows move whole instead.
|
||||
// A "can't split" row taller than a page splits too, from the top of a page, as in Word (#6823);
|
||||
// a shorter one moves on whole (`table_first_line`).
|
||||
let mut d2 = Document::from_text("before\nafter");
|
||||
t.rows[0].props.cant_split = true;
|
||||
d2.insert_block(StoryRef::Body, &Path::top(1), wordcraft_doc::Block::Table(t)).unwrap();
|
||||
@@ -8023,6 +8028,46 @@ fn a_page_break_at_the_bottom_of_a_full_page_leaves_no_blank_page() {
|
||||
assert!(last_on_2, "the text after the break is on page 2");
|
||||
}
|
||||
|
||||
/// Measured in Word for Mac: a paragraph holding only a page break is an ordinary line. When it
|
||||
/// doesn't fit at the bottom of a full page it goes to the next one, and its break leaves that
|
||||
/// page blank. Only a break with text after it in its paragraph stays on the full page (#534).
|
||||
/// WordCraft kept both on the page, so a paper's references started a page early.
|
||||
#[test]
|
||||
fn a_paragraph_of_only_a_page_break_moves_when_it_does_not_fit() {
|
||||
use wordcraft_doc::props::LineSpacing;
|
||||
let chr = wordcraft_doc::CharProps { font: Some("Source Sans 3".into()), size: Some(12.0), ..Default::default() };
|
||||
let doc = |spacing: LineSpacing, room: f32, tail: &[&str]| {
|
||||
let para = |text: &str| {
|
||||
let mut p = wordcraft_doc::Paragraph::with_text(text, chr.clone());
|
||||
p.mark = chr.clone();
|
||||
p.props = ParaProps { line_spacing: Some(spacing), space_before: Some(0.0), space_after: Some(0.0), ..Default::default() };
|
||||
wordcraft_doc::para_block(p)
|
||||
};
|
||||
let mut d = Document::new();
|
||||
d.body = (0..20).map(|i| para(&format!("Line {i}"))).chain(tail.iter().map(|t| para(t))).collect();
|
||||
let l = lay(&d);
|
||||
let pitch = l.caret(&Pos::body(1, 0)).unwrap().top - l.caret(&Pos::body(0, 0)).unwrap().top;
|
||||
d.last_section.margin_bottom = d.last_section.page_h - d.last_section.margin_top - 20.0 * pitch - room;
|
||||
d
|
||||
};
|
||||
let pages = |d: &Document| lay(d).pages.len();
|
||||
let single = {
|
||||
let l = lay(&doc(LineSpacing::Multiple(1.0), 600.0, &[]));
|
||||
l.caret(&Pos::body(1, 0)).unwrap().top - l.caret(&Pos::body(0, 0)).unwrap().top
|
||||
};
|
||||
let only = ["\u{000C}", "After"];
|
||||
let start = ["\u{000C}After"];
|
||||
// Exactly 24 pt lines, 10 pt left: the break's own paragraph moves, a blank page follows.
|
||||
assert_eq!(pages(&doc(LineSpacing::Exactly(24.0), 10.0, &only)), 3, "exact, break only");
|
||||
assert_eq!(pages(&doc(LineSpacing::Exactly(24.0), 10.0, &start)), 2, "exact, break before text");
|
||||
// Double spacing: the paragraph moves when its text cannot fit. Its leading can hang into
|
||||
// the bottom margin once the paragraph mark fits.
|
||||
assert_eq!(pages(&doc(LineSpacing::Multiple(2.0), single - 0.2, &only)), 3, "double, text doesn't fit");
|
||||
assert_eq!(pages(&doc(LineSpacing::Multiple(2.0), single + 0.2, &only)), 2, "double, leading hangs");
|
||||
assert_eq!(pages(&doc(LineSpacing::Multiple(2.0), 2.0 * single + 0.2, &only)), 2, "double, line fits");
|
||||
assert_eq!(pages(&doc(LineSpacing::Multiple(2.0), single - 0.2, &start)), 2, "double, break before text");
|
||||
}
|
||||
|
||||
/// #534: indents in characters (`w:firstLineChars`) are measured in the paragraph mark's font
|
||||
/// size and win over the indent in points.
|
||||
#[test]
|
||||
@@ -15205,6 +15250,60 @@ fn a_hyphen_before_a_slash_is_a_break_opportunity_like_word() {
|
||||
panic!("no width in the sweep wrapped the paragraph");
|
||||
}
|
||||
|
||||
/// A row of hyphens wraps at any hyphen in Word: after a gap, the row first fills the line and
|
||||
/// its rest goes on the next, where UAX #14 (LB21) keeps the hyphens together and the whole row
|
||||
/// moved to the next line. The first width that wraps must leave `Deed ` and part of the row on
|
||||
/// the first line. A row of non-breaking hyphens (U+2011) stays whole, so the first wrap moves it
|
||||
/// whole, breaking at the space.
|
||||
#[test]
|
||||
fn a_row_of_hyphens_wraps_at_any_hyphen_like_word() {
|
||||
let lines_of = |text: &str, margin_right: f32| -> Vec<String> {
|
||||
let mut d = Document::from_text(text);
|
||||
d.last_section.margin_right = margin_right;
|
||||
let l = lay(&d);
|
||||
l.pages[0]
|
||||
.items
|
||||
.iter()
|
||||
.filter_map(|it| {
|
||||
if let Placed::Lines { para, l0, l1, .. } = it {
|
||||
Some(para.lines[*l0..*l1].iter().map(|line| text[line.start..line.stop].to_string()).collect::<Vec<_>>())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.flatten()
|
||||
.collect()
|
||||
};
|
||||
|
||||
let text = format!("Deed {}", "-".repeat(16));
|
||||
let mut wrapped = false;
|
||||
for m in 100..=540 {
|
||||
let lines = lines_of(&text, m as f32);
|
||||
if lines.len() < 2 {
|
||||
continue; // still fits on one line at this width
|
||||
}
|
||||
assert!(lines[0].starts_with("Deed -"), "the first line takes part of the row: {lines:?}");
|
||||
assert!(lines[1].starts_with('-'), "the rest of the row follows: {lines:?}");
|
||||
assert_eq!(lines.concat(), text, "no hyphen is lost or added: {lines:?}");
|
||||
wrapped = true;
|
||||
break;
|
||||
}
|
||||
assert!(wrapped, "no width in the sweep wrapped the row of hyphens");
|
||||
|
||||
let row = "\u{2011}".repeat(16);
|
||||
let text = format!("Deed {row}");
|
||||
for m in 100..=540 {
|
||||
let lines = lines_of(&text, m as f32);
|
||||
if lines.len() < 2 {
|
||||
continue; // still fits on one line at this width
|
||||
}
|
||||
assert_eq!(lines[0], "Deed ", "the only break is at the space: {lines:?}");
|
||||
assert_eq!(lines[1], row, "the row of non-breaking hyphens stays whole: {lines:?}");
|
||||
return;
|
||||
}
|
||||
panic!("no width in the sweep wrapped the non-breaking row");
|
||||
}
|
||||
|
||||
/// docxide-pdf `dot-open-token*`: UAX #14 allows a break between a full stop and an opening
|
||||
/// parenthesis, Word doesn't. The first width that wraps `Deed 2023.(Example` breaks at the space.
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,376 @@
|
||||
//! The last page of a section whose columns are balanced before a continuous break, when it holds
|
||||
//! only the end of a paragraph that began on the page before, or a whole paragraph of two or three
|
||||
//! lines (#6821). Measured in Word for Windows with exact 14 pt lines and no spacing, in three and
|
||||
//! in two columns, one case per document, saved as compatibility mode 15 and as 14: from mode 15
|
||||
//! Word keeps such lines together in the first column that can hold them (the later columns may be
|
||||
//! left short or empty), keeps a paragraph with "keep lines together" or "keep with next" whole
|
||||
//! there when those rules fit, including in a section that starts and ends on one page. In mode
|
||||
//! 14 Word splits two lines one per column. Synthetic tests also cover a footnote and a floating
|
||||
//! picture. Mode 14's other layouts (a three-line tail, two and one; the text after the section)
|
||||
//! and keep with next on the last lines of a paragraph that began on the page before remain open.
|
||||
use crate::*;
|
||||
use wordcraft_doc::para::{Anchor, Float, InlineObject, NoteKind, ShapeKind, Wrap};
|
||||
use wordcraft_doc::props::{LineSpacing, ParaProps};
|
||||
use wordcraft_doc::section::{SectionProps, SectionStart};
|
||||
use wordcraft_doc::{PartKind, Pos, para_block};
|
||||
|
||||
const LINE: f32 = 14.0;
|
||||
|
||||
fn lay(doc: &Document) -> DocLayout {
|
||||
let mut c = LayoutCache::new();
|
||||
layout(doc, &mut c, &LayoutOptions::default())
|
||||
}
|
||||
|
||||
fn para_with(text: &str, keep_lines: bool, keep_next: bool) -> Arc<Block> {
|
||||
let chr = wordcraft_doc::CharProps { font: Some("Source Sans 3".into()), size: Some(12.0), ..Default::default() };
|
||||
let mut p = Paragraph::with_text(text, chr);
|
||||
p.props = ParaProps {
|
||||
space_before: Some(0.0),
|
||||
space_after: Some(0.0),
|
||||
line_spacing: Some(LineSpacing::Exactly(LINE)),
|
||||
keep_lines: keep_lines.then_some(true),
|
||||
keep_next: keep_next.then_some(true),
|
||||
..Default::default()
|
||||
};
|
||||
para_block(p)
|
||||
}
|
||||
|
||||
fn para(text: &str) -> Arc<Block> {
|
||||
para_with(text, false, false)
|
||||
}
|
||||
|
||||
/// A paragraph of `k` lines, each ended by a line break: "P1", "P2"…
|
||||
fn lines_text(k: usize) -> String {
|
||||
(1..=k).map(|i| format!("P{i}")).collect::<Vec<_>>().join(&wordcraft_doc::para::LINE_BREAK.to_string())
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum Keep {
|
||||
No,
|
||||
Lines,
|
||||
Next,
|
||||
}
|
||||
|
||||
/// What follows the filler paragraphs: a paragraph of `k` lines ("P1"…), then optionally one more
|
||||
/// line ("Q1"), all in `cols` columns, then "After" in one column.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Case {
|
||||
cols: u32,
|
||||
/// How many one-line paragraphs come first, relative to the lines on a page: `-3` leaves room
|
||||
/// for three lines of the paragraph, `0` starts the paragraph on the next page, `1` puts one
|
||||
/// more line before it there. With `intro` it is the plain number of them.
|
||||
from_page_end: i32,
|
||||
k: usize,
|
||||
q: bool,
|
||||
compat: u32,
|
||||
/// A footnote referenced at the end of the paragraph.
|
||||
note: bool,
|
||||
/// A floating 28 pt tall picture-sized shape anchored in "Q1" (needs `q`).
|
||||
float: Option<Wrap>,
|
||||
/// This many lines of text and a one-column section break before the columns: the section
|
||||
/// starts mid-page and ends on the same page.
|
||||
intro: usize,
|
||||
/// Columns closed by a continuous break (balanced) or running to the end of the document.
|
||||
balanced: bool,
|
||||
keep: Keep,
|
||||
/// A page of this many lines of text (for a page too short for the rules).
|
||||
page_lines: Option<i32>,
|
||||
}
|
||||
|
||||
impl Case {
|
||||
fn new(cols: u32, from_page_end: i32, k: usize) -> Case {
|
||||
Case { cols, from_page_end, k, q: false, compat: 15, note: false, float: None, intro: 0, balanced: true, keep: Keep::No, page_lines: None }
|
||||
}
|
||||
}
|
||||
|
||||
/// The document of a case, the index of the `k`-line paragraph and of "Q1", and the offsets of the
|
||||
/// paragraph's lines.
|
||||
fn build(c: &Case) -> (Document, usize, Option<usize>, Vec<usize>) {
|
||||
crate::test_fonts();
|
||||
let mut d = Document::new();
|
||||
d.settings.compat_mode = c.compat;
|
||||
let mut s = SectionProps { start: SectionStart::Continuous, ..Default::default() };
|
||||
s.columns.count = c.cols;
|
||||
if let Some(n) = c.page_lines {
|
||||
s.page_h = s.margin_top + s.margin_bottom + n as f32 * LINE + 0.5;
|
||||
d.last_section.page_h = s.page_h;
|
||||
}
|
||||
let per_col = ((s.page_h - s.margin_top - s.margin_bottom) / LINE).floor() as i32;
|
||||
let fillers = if c.intro > 0 { c.from_page_end.max(0) } else { (per_col * c.cols as i32 + c.from_page_end).max(0) } as usize;
|
||||
let mut body: Vec<Arc<Block>> = (0..c.intro).map(|i| para(&format!("i{i}"))).collect();
|
||||
if c.intro > 0 {
|
||||
let mut one = SectionProps { start: SectionStart::Continuous, ..Default::default() };
|
||||
one.columns.count = 1;
|
||||
let mut mark = para("");
|
||||
if let Block::Para(p) = Arc::make_mut(&mut mark) {
|
||||
p.section = Some(Box::new(one));
|
||||
}
|
||||
body.push(mark);
|
||||
}
|
||||
body.extend((0..fillers).map(|i| para(&format!("r{i}"))));
|
||||
let first = body.len();
|
||||
let text = lines_text(c.k);
|
||||
body.push(para_with(&text, c.keep == Keep::Lines, c.keep == Keep::Next));
|
||||
let q = c.q.then_some(body.len());
|
||||
if c.q {
|
||||
body.push(para("Q1"));
|
||||
}
|
||||
let mark = body.len();
|
||||
if c.balanced {
|
||||
body.push(para(""));
|
||||
body.push(para("After"));
|
||||
}
|
||||
d.body = body;
|
||||
if c.balanced {
|
||||
if let Some(Block::Para(p)) = d.body.get_mut(mark).map(Arc::make_mut) {
|
||||
p.section = Some(Box::new(s));
|
||||
}
|
||||
d.last_section.start = SectionStart::Continuous;
|
||||
} else {
|
||||
d.last_section.columns.count = c.cols;
|
||||
}
|
||||
if let (Some(w), Some(qi)) = (c.float, q) {
|
||||
let float = Float { wrap: w, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, x: 0.0, y: 0.0, ..Default::default() };
|
||||
let shape = InlineObject::Shape {
|
||||
kind: ShapeKind::Rectangle,
|
||||
w: if w == Wrap::TopAndBottom { 100.0 } else { 60.0 },
|
||||
h: 28.0,
|
||||
fill: None,
|
||||
stroke: None,
|
||||
stroke_width: 1.0,
|
||||
float,
|
||||
story: None,
|
||||
freeform: None,
|
||||
effects: Default::default(),
|
||||
extra: Default::default(),
|
||||
};
|
||||
d.insert_object(&Pos::body(qi, 0), shape, &Default::default()).unwrap();
|
||||
}
|
||||
let breaks = text.char_indices().filter(|(_, ch)| *ch == wordcraft_doc::para::LINE_BREAK);
|
||||
let starts: Vec<usize> = std::iter::once(0).chain(breaks.map(|(i, ch)| i + ch.len_utf8())).collect();
|
||||
if c.note {
|
||||
let id = d.add_part(PartKind::Footnote, vec![para("Note")]);
|
||||
let end = text.len();
|
||||
d.insert_object(&Pos::body(first, end), InlineObject::NoteRef { kind: NoteKind::Footnote, id, custom: String::new() }, &Default::default())
|
||||
.unwrap();
|
||||
}
|
||||
(d, first, q, starts)
|
||||
}
|
||||
|
||||
/// The columns of the lines of the `k`-line paragraph (counted from the left, 0 to `cols - 1`),
|
||||
/// of "Q1" if there is one, and the number of pages.
|
||||
fn columns(c: &Case) -> (Vec<usize>, Option<usize>, usize) {
|
||||
let (d, first, q, starts) = build(c);
|
||||
let l = lay(&d);
|
||||
let carets: Vec<_> = starts.iter().map(|&o| l.caret(&Pos::body(first, o)).unwrap()).collect();
|
||||
let q_caret = q.map(|qi| l.caret(&Pos::body(qi, 0)).unwrap());
|
||||
// The columns' left edges, from the section's declared geometry so that an empty column keeps
|
||||
// its place. A line beside a float starts right of its column's edge, so a position is in the
|
||||
// last edge at or left of it.
|
||||
let sp = SectionProps::default();
|
||||
let n = c.cols.max(1);
|
||||
let width = (sp.page_w - sp.margin_left - sp.margin_right - sp.gutter - sp.columns.space * (n - 1) as f32) / n as f32;
|
||||
let xs: Vec<f32> = (0..n).map(|i| sp.margin_left + i as f32 * (width + sp.columns.space)).collect();
|
||||
let col = |x: f32| xs.iter().rposition(|e| *e <= x + 1.0).unwrap_or(usize::MAX);
|
||||
(carets.iter().map(|c| col(c.x)).collect(), q_caret.map(|c| col(c.x)), l.pages.len())
|
||||
}
|
||||
|
||||
fn of(c: &Case) -> Vec<usize> {
|
||||
columns(c).0
|
||||
}
|
||||
|
||||
// A: the last two lines of a paragraph whose first three lines closed the page before.
|
||||
#[test]
|
||||
fn the_last_two_lines_of_a_continued_paragraph_stay_in_the_first_column() {
|
||||
for cols in [3, 2] {
|
||||
let (v, _, pages) = columns(&Case::new(cols, -3, 5));
|
||||
assert_eq!(pages, 2, "{cols} columns");
|
||||
assert_eq!(v[3..], [0, 0], "{cols} columns: lines 4 and 5 together");
|
||||
}
|
||||
}
|
||||
|
||||
// B: three lines stay together too: not two and one, nor one and two.
|
||||
#[test]
|
||||
fn the_last_three_lines_of_a_continued_paragraph_stay_in_the_first_column() {
|
||||
for cols in [3, 2] {
|
||||
assert_eq!(of(&Case::new(cols, -3, 6))[3..], [0, 0, 0], "{cols} columns");
|
||||
}
|
||||
}
|
||||
|
||||
// L: five lines are three and two (not two, one and two).
|
||||
#[test]
|
||||
fn the_last_five_lines_of_a_continued_paragraph_are_three_and_two() {
|
||||
for cols in [3, 2] {
|
||||
assert_eq!(of(&Case::new(cols, -3, 8))[3..], [0, 0, 0, 1, 1], "{cols} columns");
|
||||
}
|
||||
}
|
||||
|
||||
// N: a one-line paragraph after the two lines goes to the second column.
|
||||
#[test]
|
||||
fn a_line_after_the_continued_two_lines_goes_to_the_next_column() {
|
||||
for cols in [3, 2] {
|
||||
let (v, q, _) = columns(&Case { q: true, ..Case::new(cols, -3, 5) });
|
||||
assert_eq!((v[3..].to_vec(), q), (vec![0, 0], Some(1)), "{cols} columns");
|
||||
}
|
||||
}
|
||||
|
||||
// K, E: a paragraph of three lines (or two) that begins the last page stays together.
|
||||
#[test]
|
||||
fn a_whole_paragraph_of_two_or_three_lines_at_the_top_of_the_last_page_stays_together() {
|
||||
for cols in [3, 2] {
|
||||
assert_eq!(of(&Case::new(cols, 0, 3)), [0, 0, 0], "{cols} columns, three lines");
|
||||
assert_eq!(of(&Case::new(cols, 0, 2)), [0, 0], "{cols} columns, two lines");
|
||||
}
|
||||
}
|
||||
|
||||
// K2: the same after one line of another paragraph in the first column: it starts the second.
|
||||
#[test]
|
||||
fn a_three_line_paragraph_after_one_line_on_the_last_page_stays_together() {
|
||||
for cols in [3, 2] {
|
||||
let (v, _, pages) = columns(&Case::new(cols, 1, 3));
|
||||
assert_eq!((v, pages), (vec![1, 1, 1], 2), "{cols} columns");
|
||||
}
|
||||
}
|
||||
|
||||
// F: with a footnote on the last page, referenced at the end of the paragraph.
|
||||
#[test]
|
||||
fn a_footnote_on_the_last_page_leaves_the_tail_together() {
|
||||
for cols in [3, 2] {
|
||||
let n = |off, k| of(&Case { note: true, ..Case::new(cols, off, k) });
|
||||
assert_eq!(n(-3, 5)[3..], [0, 0], "{cols} columns, two lines");
|
||||
assert_eq!(n(-3, 6)[3..], [0, 0, 0], "{cols} columns, three lines");
|
||||
assert_eq!(n(0, 2), [0, 0], "{cols} columns, whole paragraph of two lines");
|
||||
assert_eq!(n(0, 3), [0, 0, 0], "{cols} columns, whole paragraph of three lines");
|
||||
}
|
||||
}
|
||||
|
||||
// L2: beside a square-wrapped float in the next paragraph; a top-and-bottom one is the guard.
|
||||
#[test]
|
||||
fn a_square_wrapped_float_after_the_tail_leaves_it_together() {
|
||||
for cols in [3, 2] {
|
||||
let sq = |off, k| columns(&Case { q: true, float: Some(Wrap::Square), ..Case::new(cols, off, k) });
|
||||
let (v, q, _) = sq(-3, 5);
|
||||
assert_eq!((v[3..].to_vec(), q), (vec![0, 0], Some(1)), "{cols} columns, two lines");
|
||||
let (v, q, _) = sq(0, 3);
|
||||
assert_eq!((v, q), (vec![0, 0, 0], Some(1)), "{cols} columns, whole paragraph of three lines");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_top_and_bottom_float_after_the_tail_is_laid_out_as_before() {
|
||||
for cols in [3, 2] {
|
||||
let tb = |off, k| columns(&Case { q: true, float: Some(Wrap::TopAndBottom), ..Case::new(cols, off, k) });
|
||||
let (v, q, _) = tb(-3, 5);
|
||||
assert_eq!((v[3..].to_vec(), q), (vec![0, 0], Some(1)), "{cols} columns, two lines");
|
||||
let (v, q, _) = tb(0, 3);
|
||||
assert_eq!((v, q), (vec![0, 0, 0], Some(1)), "{cols} columns, whole paragraph of three lines");
|
||||
}
|
||||
}
|
||||
|
||||
// M: a section that starts and ends on one page (after two lines of text in one column).
|
||||
#[test]
|
||||
fn a_five_line_paragraph_balanced_mid_page_is_three_and_two() {
|
||||
assert_eq!(of(&Case { intro: 2, ..Case::new(3, 0, 5) }), [0, 0, 0, 1, 1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_section_balanced_mid_page_is_laid_out_as_before() {
|
||||
let mid = |cols, filler, k| of(&Case { intro: 2, ..Case::new(cols, filler, k) });
|
||||
assert_eq!(mid(3, 0, 2), [0, 0]);
|
||||
assert_eq!(mid(3, 0, 3), [0, 0, 0]);
|
||||
assert_eq!(mid(3, 0, 4), [0, 0, 1, 1]);
|
||||
assert_eq!(mid(3, 0, 6), [0, 0, 1, 1, 2, 2]);
|
||||
assert_eq!(mid(2, 0, 3), [0, 0, 0]);
|
||||
assert_eq!(mid(2, 0, 5), [0, 0, 0, 1, 1]);
|
||||
assert_eq!(mid(2, 0, 6), [0, 0, 0, 1, 1, 1]);
|
||||
// After one more line.
|
||||
assert_eq!(mid(3, 1, 3), [1, 1, 1]);
|
||||
assert_eq!(mid(3, 1, 4), [1, 1, 2, 2]);
|
||||
assert_eq!(mid(3, 1, 5), [0, 0, 1, 1, 1]);
|
||||
assert_eq!(mid(2, 1, 4), [0, 0, 1, 1]);
|
||||
assert_eq!(mid(2, 1, 6), [0, 0, 0, 1, 1, 1]);
|
||||
}
|
||||
|
||||
// X: keep lines together, and keep with next, hold the paragraph whole in the first column.
|
||||
#[test]
|
||||
fn a_paragraph_kept_together_stays_whole_in_the_first_balanced_column() {
|
||||
for cols in [3, 2] {
|
||||
let kept = |off, k| of(&Case { keep: Keep::Lines, ..Case::new(cols, off, k) });
|
||||
assert_eq!(kept(0, 3), [0, 0, 0], "{cols} columns, three lines at the top");
|
||||
// Keep lines together moved it whole onto the last page.
|
||||
assert_eq!(kept(-3, 5), [0, 0, 0, 0, 0], "{cols} columns, five lines");
|
||||
assert_eq!(kept(-3, 6), [0, 0, 0, 0, 0, 0], "{cols} columns, six lines");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_paragraph_kept_with_the_next_stays_with_it_in_the_first_balanced_column() {
|
||||
for cols in [3, 2] {
|
||||
let (v, q, _) = columns(&Case { keep: Keep::Next, q: true, ..Case::new(cols, 0, 3) });
|
||||
assert_eq!((v, q), (vec![0, 0, 0], Some(0)), "{cols} columns");
|
||||
}
|
||||
}
|
||||
|
||||
// Guards, the same in Word and before the change.
|
||||
|
||||
// C, M: four lines are two and two, six are two, two and two.
|
||||
#[test]
|
||||
fn longer_tails_are_balanced_as_before() {
|
||||
for cols in [3, 2] {
|
||||
assert_eq!(of(&Case::new(cols, -3, 7))[3..], [0, 0, 1, 1], "{cols} columns, four lines");
|
||||
}
|
||||
assert_eq!(of(&Case::new(3, -3, 9))[3..], [0, 0, 1, 1, 2, 2], "three columns, six lines");
|
||||
}
|
||||
|
||||
// O: a four-line paragraph that begins the last page is two and two.
|
||||
#[test]
|
||||
fn a_four_line_paragraph_at_the_top_of_the_last_page_is_two_and_two() {
|
||||
for cols in [3, 2] {
|
||||
assert_eq!(of(&Case::new(cols, 0, 4)), [0, 0, 1, 1], "{cols} columns");
|
||||
}
|
||||
}
|
||||
|
||||
// Columns not balanced (nothing follows them): the lines are not split without need.
|
||||
#[test]
|
||||
fn unbalanced_columns_keep_the_tail_in_the_first_column() {
|
||||
for cols in [3, 2] {
|
||||
let c = Case { balanced: false, ..Case::new(cols, -3, 5) };
|
||||
assert_eq!(of(&c)[3..], [0, 0], "{cols} columns");
|
||||
}
|
||||
}
|
||||
|
||||
// Before Word 2013's layout (mode 14) the two lines are split one per column, as Word does.
|
||||
#[test]
|
||||
fn mode_14_still_splits_the_last_two_lines_of_a_continued_paragraph() {
|
||||
for cols in [3, 2] {
|
||||
let c = Case { compat: 14, ..Case::new(cols, -3, 5) };
|
||||
assert_eq!(of(&c)[3..], [0, 1], "{cols} columns");
|
||||
}
|
||||
}
|
||||
|
||||
/// How many lines of body text are laid out, and on how many pages.
|
||||
fn shape(c: &Case) -> (usize, usize) {
|
||||
let (d, ..) = build(c);
|
||||
let l = lay(&d);
|
||||
let lines = l
|
||||
.pages
|
||||
.iter()
|
||||
.flat_map(|p| p.items.iter())
|
||||
.map(|it| match it {
|
||||
Placed::Lines { story: StoryRef::Body, l0, l1, .. } => l1 - l0,
|
||||
_ => 0,
|
||||
})
|
||||
.sum();
|
||||
(l.pages.len(), lines)
|
||||
}
|
||||
|
||||
// A page whose columns hold two lines is too short for the rules that keep three lines together:
|
||||
// not even the full column holds the paragraph with them, so the columns are laid out as before
|
||||
// (mode 14), with every line placed and no more pages.
|
||||
#[test]
|
||||
fn a_page_too_short_for_the_strict_rules_is_laid_out_as_in_mode_14() {
|
||||
let tiny = |compat| Case { compat, page_lines: Some(2), ..Case::new(2, 0, 3) };
|
||||
let (pages, lines) = shape(&tiny(14));
|
||||
assert!(lines >= 4, "the paragraph's three lines and After: {lines}");
|
||||
assert_eq!(shape(&tiny(15)), (pages, lines));
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
//! A header in a document of Word 2010's layout or older (compatibility mode below 15) keeps its
|
||||
//! text where it is beside its own floating objects, which wrap nothing there: a top and bottom
|
||||
//! object only makes the header taller when it starts above the end of the text (#6805). From
|
||||
//! Word 2013's layout (mode 15) the header's text goes below such an object.
|
||||
//!
|
||||
//! Measured in Word for Windows 16.0 on synthetic files (A4, Arial 10 pt, a header 17.3 pt down,
|
||||
//! 20 pt top margin or more, a text box 451.65 x 29.55 pt anchored to the header's paragraph and
|
||||
//! set 7.2 pt below its top, top and bottom wrapping, one line of text): at mode 14 the line stays
|
||||
//! at the header's top and the body's first line starts at 54.3 pt (the box's bottom, 54.05, and
|
||||
//! the line's rounding); at mode 15 the line goes below the box and the body starts at 65.9.
|
||||
//! A box set 78 pt below a 39 pt line changes nothing in either mode. A wrap distance below the
|
||||
//! box counts at both modes (14.4 pt: the body 14.4 pt lower), the one above changes nothing. A
|
||||
//! box starting in the space after the last paragraph makes the header end at its bottom. With
|
||||
//! three paragraphs and a box set 26 pt down the page, anchored in the second, no paragraph moves
|
||||
//! at mode 14 and the body starts at the box's bottom (55.9 pt). Square wrapping at mode 14 leaves
|
||||
//! the text as it is. Mode 11 (Word 2003's layout, measured on .doc files) behaves like 14: the
|
||||
//! single line stays at the top and the body starts at 54.0 pt (mode 12: 54.0, mode 14: 54.8), and
|
||||
//! no paragraph of the three-paragraph header moves. A 60 pt logo with Square, Tight or Through
|
||||
//! wrap leaves three short header paragraphs in place at mode 14. At mode 15 each line shifts
|
||||
//! right of the logo. Footers (which differ) and header table cells are outside this test.
|
||||
|
||||
use super::{lay, rect_shape};
|
||||
use crate::{DocLayout, Placed, StoryRef};
|
||||
use wordcraft_doc::para::{Anchor, Float, Wrap};
|
||||
use wordcraft_doc::props::LineSpacing;
|
||||
use wordcraft_doc::{Document, ParaProps, Paragraph, PartKind, Path, para_block};
|
||||
|
||||
const HEADER_TOP: f32 = 17.3;
|
||||
const BOX_H: f32 = 29.55;
|
||||
|
||||
/// A page whose header holds one line of text with a text-box-sized shape anchored to it, set
|
||||
/// `offset` below the paragraph's top with `wrap` (`None`: no shape), laid out as `mode` says.
|
||||
fn page(mode: u32, wrap: Option<Wrap>, offset: f32) -> DocLayout {
|
||||
page_with(mode, wrap, offset, (0.0, 0.0))
|
||||
}
|
||||
|
||||
/// [`page`] with a wrap distance below the object and a space after the header's paragraph.
|
||||
fn page_with(mode: u32, wrap: Option<Wrap>, offset: f32, (dist_bottom, after): (f32, f32)) -> DocLayout {
|
||||
crate::test_fonts();
|
||||
let mut d = Document::from_text("Body text.");
|
||||
d.settings.compat_mode = mode;
|
||||
d.last_section.header = HEADER_TOP;
|
||||
d.last_section.margin_top = 20.0;
|
||||
let mut p = Paragraph::with_text("Header line", Default::default());
|
||||
p.props = ParaProps { space_before: Some(0.0), space_after: Some(after), ..Default::default() };
|
||||
if let Some(wrap) = wrap {
|
||||
let float = Float { wrap, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, x: 31.6, y: offset, dist_bottom, ..Default::default() };
|
||||
p.insert_object(0, rect_shape(451.65, BOX_H, float), &Default::default()).unwrap();
|
||||
}
|
||||
let id = d.add_part(PartKind::Header, vec![para_block(p)]);
|
||||
d.last_section.headers.default = Some(id);
|
||||
lay(&d)
|
||||
}
|
||||
|
||||
fn body_top(l: &DocLayout) -> f32 {
|
||||
l.pages[0].items.iter().find_map(|i| if let Placed::Lines { y, story: StoryRef::Body, .. } = i { Some(*y) } else { None }).unwrap()
|
||||
}
|
||||
|
||||
fn header_line_top(l: &DocLayout) -> f32 {
|
||||
l.pages[0].header.iter().find_map(|i| if let Placed::Lines { y, story: StoryRef::Part(_), .. } = i { Some(*y) } else { None }).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mode_14_header_text_stays_beside_its_own_top_and_bottom_object() {
|
||||
let (old, new, none) = (page(14, Some(Wrap::TopAndBottom), 7.2), page(15, Some(Wrap::TopAndBottom), 7.2), page(14, None, 0.0));
|
||||
// The line stays at the header's top at mode 14, below the box at mode 15.
|
||||
assert!((header_line_top(&old) - header_line_top(&none)).abs() < 0.5, "line at {}", header_line_top(&old));
|
||||
assert!(header_line_top(&new) > HEADER_TOP + 7.2 + BOX_H - 0.5, "line at {}", header_line_top(&new));
|
||||
// The body starts below the box at mode 14 (it reaches past the text), a line lower at 15.
|
||||
assert!((body_top(&old) - (HEADER_TOP + 7.2 + BOX_H)).abs() < 0.5, "body at {}", body_top(&old));
|
||||
assert!(body_top(&new) > body_top(&old) + 5.0, "mode 15 body at {}, mode 14 at {}", body_top(&new), body_top(&old));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mode_14_object_set_below_the_header_text_adds_no_height() {
|
||||
// Starting 78 pt down, under the line: no room taken in either mode.
|
||||
let none = body_top(&page(14, None, 0.0));
|
||||
for mode in [14, 15] {
|
||||
let t = body_top(&page(mode, Some(Wrap::TopAndBottom), 78.0));
|
||||
assert!((t - none).abs() < 0.5, "mode {mode}: body at {t}, {none} without the object");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mode_14_square_object_leaves_header_text_and_height() {
|
||||
let (sq, none) = (page(14, Some(Wrap::Square), 7.2), page(14, None, 0.0));
|
||||
assert!((header_line_top(&sq) - header_line_top(&none)).abs() < 0.5, "line at {}", header_line_top(&sq));
|
||||
assert!((body_top(&sq) - body_top(&none)).abs() < 0.5, "body at {}, {} without", body_top(&sq), body_top(&none));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mode_14_header_text_ignores_a_narrow_logo_with_square_tight_or_through_wrap() {
|
||||
crate::test_fonts();
|
||||
let layout = |mode, wrap| {
|
||||
let mut d = Document::from_text("Body text.");
|
||||
d.settings.compat_mode = mode;
|
||||
d.last_section.header = 30.0;
|
||||
d.last_section.margin_top = 72.0;
|
||||
let mut blocks = Vec::new();
|
||||
for (i, text) in ["First line", "Second line", "Third line"].into_iter().enumerate() {
|
||||
let mut p = Paragraph::with_text(text, Default::default());
|
||||
p.props =
|
||||
ParaProps { space_before: Some(0.0), space_after: Some(0.0), line_spacing: Some(LineSpacing::Exactly(12.0)), ..Default::default() };
|
||||
if i == 0
|
||||
&& let Some(wrap) = wrap
|
||||
{
|
||||
let float = Float { wrap, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, dist: 8.0, ..Default::default() };
|
||||
p.insert_object(0, rect_shape(60.0, 60.0, float), &Default::default()).unwrap();
|
||||
}
|
||||
blocks.push(para_block(p));
|
||||
}
|
||||
let id = d.add_part(PartKind::Header, blocks);
|
||||
d.last_section.headers.default = Some(id);
|
||||
lay(&d)
|
||||
};
|
||||
let header_positions = |layout: &DocLayout| {
|
||||
layout.pages[0]
|
||||
.header
|
||||
.iter()
|
||||
.filter_map(|item| match item {
|
||||
Placed::Lines { x, y, para, l0, .. } => para.lines.get(*l0).map(|line| (x + line.left, *y)),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
for mode in [11, 12, 13, 14, 15] {
|
||||
let plain = layout(mode, None);
|
||||
let control = header_positions(&plain);
|
||||
assert_eq!(control.len(), 3);
|
||||
for wrap in [Wrap::Square, Wrap::Tight, Wrap::Through] {
|
||||
let with_logo = layout(mode, Some(wrap));
|
||||
let positions = header_positions(&with_logo);
|
||||
assert_eq!(positions.len(), control.len(), "mode {mode}, {wrap:?}: {positions:?}");
|
||||
for (&(x, y), &(plain_x, plain_y)) in positions.iter().zip(&control) {
|
||||
assert!((y - plain_y).abs() < 0.5, "mode {mode}, {wrap:?}: line moved vertically from {plain_y} to {y}");
|
||||
if mode == 14 || (mode < 14 && wrap == Wrap::Square) {
|
||||
assert!((x - plain_x).abs() < 0.5, "mode {mode}, {wrap:?}: line moved from {plain_x} to {x}");
|
||||
} else {
|
||||
assert!(x > plain_x + 59.5, "mode {mode}, {wrap:?}: line at {x} does not clear the logo");
|
||||
}
|
||||
}
|
||||
assert!((body_top(&with_logo) - body_top(&plain)).abs() < 0.5, "mode {mode}, {wrap:?}: body moved vertically");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mode_14_body_text_still_goes_below_its_own_top_and_bottom_object() {
|
||||
crate::test_fonts();
|
||||
let top = |mode| {
|
||||
let mut d = Document::from_text("Body text.");
|
||||
d.settings.compat_mode = mode;
|
||||
d.last_section.margin_top = 20.0;
|
||||
let float = Float { wrap: Wrap::TopAndBottom, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, x: 31.6, y: 7.2, ..Default::default() };
|
||||
let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
|
||||
p.insert_object(0, rect_shape(451.65, BOX_H, float), &Default::default()).unwrap();
|
||||
body_top(&lay(&d))
|
||||
};
|
||||
let (old, new) = (top(14), top(15));
|
||||
assert!((old - new).abs() < 0.5 && old > 20.0 + 7.2 + BOX_H - 0.5, "mode 14 body line at {old}, mode 15 at {new}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mode_14_distance_below_the_object_counts_and_a_start_in_the_space_after_extends() {
|
||||
// Word: 14.4 pt below the box make the body 14.4 pt lower.
|
||||
let (plain, spaced) = (body_top(&page(14, Some(Wrap::TopAndBottom), 7.2)), body_top(&page_with(14, Some(Wrap::TopAndBottom), 7.2, (14.4, 0.0))));
|
||||
assert!((spaced - plain - 14.4).abs() < 0.5, "body at {spaced}, {plain} without the distance");
|
||||
// A box starting 15 pt down, past the 11.5 pt line but inside its 10 pt space after: the
|
||||
// header ends at the box's bottom (Word: 62.1 from the page's top).
|
||||
let inside = page_with(14, Some(Wrap::TopAndBottom), 15.0, (0.0, 10.0));
|
||||
assert!((body_top(&inside) - (HEADER_TOP + 15.0 + BOX_H)).abs() < 0.5, "body at {}", body_top(&inside));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mode_14_no_header_paragraph_moves_for_an_object_set_down_the_page_from_the_second() {
|
||||
crate::test_fonts();
|
||||
let lines = |mode: u32, object: bool| {
|
||||
let mut d = Document::from_text("Body text.");
|
||||
d.settings.compat_mode = mode;
|
||||
d.last_section.header = HEADER_TOP;
|
||||
d.last_section.margin_top = 20.0;
|
||||
let tight = ParaProps { space_before: Some(0.0), space_after: Some(0.0), ..Default::default() };
|
||||
let mut blocks = Vec::new();
|
||||
for (i, t) in ["First line", "Second line", "Third line"].into_iter().enumerate() {
|
||||
let mut p = Paragraph::with_text(t, Default::default());
|
||||
p.props = tight.clone();
|
||||
if object && i == 1 {
|
||||
let float = Float { wrap: Wrap::TopAndBottom, h_rel: Anchor::Page, v_rel: Anchor::Page, x: 72.0, y: 60.0, ..Default::default() };
|
||||
p.insert_object(0, rect_shape(451.65, BOX_H, float), &Default::default()).unwrap();
|
||||
}
|
||||
blocks.push(para_block(p));
|
||||
}
|
||||
let id = d.add_part(PartKind::Header, blocks);
|
||||
d.last_section.headers.default = Some(id);
|
||||
let l = lay(&d);
|
||||
let tops: Vec<f32> = l.pages[0].header.iter().filter_map(|i| if let Placed::Lines { y, .. } = i { Some(*y) } else { None }).collect();
|
||||
(tops, body_top(&l))
|
||||
};
|
||||
let ((plain, _), (with, body)) = (lines(14, false), lines(14, true));
|
||||
assert_eq!(plain.len(), with.len());
|
||||
for (a, b) in plain.iter().zip(&with) {
|
||||
assert!((a - b).abs() < 0.5, "header lines at {with:?}, {plain:?} without the object");
|
||||
}
|
||||
// The box is 60 pt down the page, over the third line (the test font's lines are taller than
|
||||
// Word's 11.5 pt, so the box is set lower than the 26 pt measured): the body starts at its bottom.
|
||||
assert!((body - (60.0 + BOX_H)).abs() < 0.5, "body at {body}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mode_11_header_text_stays_beside_its_own_top_and_bottom_object_like_mode_14() {
|
||||
// Word: modes 11, 12 and 14 keep the line at the header's top; mode 15 moves it below the box.
|
||||
let (m11, m12, m14, m15) = (
|
||||
page(11, Some(Wrap::TopAndBottom), 7.2),
|
||||
page(12, Some(Wrap::TopAndBottom), 7.2),
|
||||
page(14, Some(Wrap::TopAndBottom), 7.2),
|
||||
page(15, Some(Wrap::TopAndBottom), 7.2),
|
||||
);
|
||||
for l in [&m11, &m12] {
|
||||
assert!((header_line_top(l) - header_line_top(&m14)).abs() < 0.5, "line at {}, {} at mode 14", header_line_top(l), header_line_top(&m14));
|
||||
assert!((body_top(l) - body_top(&m14)).abs() < 0.5, "body at {}, {} at mode 14", body_top(l), body_top(&m14));
|
||||
}
|
||||
assert!(header_line_top(&m15) > header_line_top(&m11) + 5.0, "mode 15 line at {}, mode 11 at {}", header_line_top(&m15), header_line_top(&m11));
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
//! Keep with next on the paragraph that closes a section (#6834). When the next section starts
|
||||
//! on a new page, the paragraph after it is not on this page, so Keep with next has nothing to
|
||||
//! keep it with: it stays at the bottom of its page. Moving it over for want of the next
|
||||
//! section's first line left a page holding only that section's paragraph. Only a next-page
|
||||
//! break was measured in Word; odd-page and even-page breaks follow by analogy (not measured).
|
||||
//! Fixed page size and exact line heights, so no font metrics are assumed. Invented text only.
|
||||
|
||||
use crate::*;
|
||||
use wordcraft_doc::props::LineSpacing;
|
||||
use wordcraft_doc::section::{SectionProps, SectionStart};
|
||||
use wordcraft_doc::{ParaProps, Paragraph};
|
||||
|
||||
fn lay(doc: &Document) -> DocLayout {
|
||||
let mut c = LayoutCache::new();
|
||||
layout(doc, &mut c, &LayoutOptions::default())
|
||||
}
|
||||
|
||||
/// A 400 x 300 pt page with 50 pt margins: 200 pt of body, ten 20 pt lines.
|
||||
fn small_page(start: SectionStart) -> SectionProps {
|
||||
SectionProps {
|
||||
start,
|
||||
page_w: 400.0,
|
||||
page_h: 300.0,
|
||||
margin_top: 50.0,
|
||||
margin_bottom: 50.0,
|
||||
margin_left: 50.0,
|
||||
margin_right: 50.0,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn exact(text: &str, height: f32, keep: bool) -> Paragraph {
|
||||
let mut p = Paragraph::with_text(text, Default::default());
|
||||
p.props = ParaProps {
|
||||
line_spacing: Some(LineSpacing::Exactly(height)),
|
||||
space_before: Some(0.0),
|
||||
space_after: Some(0.0),
|
||||
keep_next: keep.then_some(true),
|
||||
..Default::default()
|
||||
};
|
||||
p
|
||||
}
|
||||
|
||||
/// `filler` exact 20 pt paragraphs, then the closing paragraph (15 pt, block index `filler`,
|
||||
/// kept with the next when `keep`), then one 20 pt paragraph. When `closes`, the closing
|
||||
/// paragraph ends section one and the second section starts as `start`; otherwise the second
|
||||
/// paragraph is in the same section.
|
||||
fn build(filler: usize, keep: bool, start: SectionStart, closes: bool, empty: bool) -> Document {
|
||||
let mut d = Document::new();
|
||||
d.body.clear();
|
||||
for i in 0..filler {
|
||||
d.body.push(wordcraft_doc::para_block(exact(&format!("Filler line {i}"), 20.0, false)));
|
||||
}
|
||||
let mut last = exact(if empty { "" } else { "Closing paragraph of the first part" }, 15.0, keep);
|
||||
if closes {
|
||||
last.section = Some(Box::new(small_page(SectionStart::NextPage)));
|
||||
}
|
||||
d.body.push(wordcraft_doc::para_block(last));
|
||||
d.body.push(wordcraft_doc::para_block(exact("First paragraph of the second part", 20.0, false)));
|
||||
d.last_section = small_page(if closes { start } else { SectionStart::NextPage });
|
||||
d
|
||||
}
|
||||
|
||||
/// The page (0-based) that holds the body paragraph `block`.
|
||||
fn page_of(l: &DocLayout, block: u32) -> Option<usize> {
|
||||
l.pages.iter().position(|p| p.items.iter().any(|it| matches!(it, Placed::Lines { story: StoryRef::Body, path, .. } if path.0 == [block])))
|
||||
}
|
||||
|
||||
const NEXT_BREAKS: [SectionStart; 3] = [SectionStart::NextPage, SectionStart::OddPage, SectionStart::EvenPage];
|
||||
|
||||
/// The issue's case: nine 20 pt lines, an empty 15 pt kept closing paragraph that fits at the
|
||||
/// bottom (195 of 200 pt) while the next section's first line (20 pt) would not, then one
|
||||
/// paragraph of the next section. Two pages, none empty.
|
||||
#[test]
|
||||
fn an_empty_kept_closing_paragraph_leaves_no_empty_page() {
|
||||
crate::test_fonts();
|
||||
let l = lay(&build(9, true, SectionStart::NextPage, true, true));
|
||||
assert_eq!(l.pages.len(), 2);
|
||||
assert_eq!(page_of(&l, 9), Some(0), "the closing paragraph moved to the next page");
|
||||
assert_eq!(page_of(&l, 10), Some(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_kept_closing_paragraph_stays_on_its_page_and_adds_no_page() {
|
||||
crate::test_fonts();
|
||||
for start in NEXT_BREAKS {
|
||||
for empty in [true, false] {
|
||||
for n in 0..25 {
|
||||
let kept = lay(&build(n, true, start, true, empty));
|
||||
let plain = lay(&build(n, false, start, true, empty));
|
||||
assert_eq!(kept.pages.len(), plain.pages.len(), "{start:?}, {n} filler paragraphs, empty {empty}: keep with next added a page");
|
||||
assert_eq!(page_of(&kept, n as u32), page_of(&plain, n as u32), "{start:?}, {n} filler paragraphs, empty {empty}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keep_with_next_still_moves_an_ordinary_paragraph_with_its_next_line() {
|
||||
crate::test_fonts();
|
||||
// No section ends here: the 15 pt paragraph fits (195 of 200 pt) but the 20 pt one after it
|
||||
// does not, so the pair goes to page 2 together.
|
||||
let kept = lay(&build(9, true, SectionStart::NextPage, false, false));
|
||||
let plain = lay(&build(9, false, SectionStart::NextPage, false, false));
|
||||
assert_eq!(page_of(&plain, 9), Some(0));
|
||||
assert_eq!(page_of(&kept, 9), Some(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keep_with_next_before_a_continuous_section_still_keeps_with_its_next_line() {
|
||||
crate::test_fonts();
|
||||
// The next section continues on this page, so its first line is what the paragraph keeps
|
||||
// with (not measured in Word; the earlier behaviour stays).
|
||||
let kept = lay(&build(9, true, SectionStart::Continuous, true, false));
|
||||
let plain = lay(&build(9, false, SectionStart::Continuous, true, false));
|
||||
assert_eq!(page_of(&plain, 9), Some(0));
|
||||
assert_eq!(page_of(&kept, 9), Some(1));
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
//! A paragraph that starts a cell's part of a page, in a row split across pages, is split where
|
||||
//! its lines fall, as in Word (#6823): moving it on whole would gain nothing, and keeping
|
||||
//! widow/orphan control left the cell with nothing on the page, so the row was placed whole and
|
||||
//! ran off the bottom. A paragraph below other content of its cell keeps the rule, and so does a
|
||||
//! row that starts below other content of the page. A "can't split" row taller than a page
|
||||
//! splits too.
|
||||
//!
|
||||
//! The expectations were measured in Word for Windows 16.0 (compatibility mode 15, widow control
|
||||
//! on, Letter with 1 inch margins) on synthetic documents laid out like these.
|
||||
use crate::*;
|
||||
use wordcraft_doc::para::{Anchor, Float, InlineObject, Wrap};
|
||||
use wordcraft_doc::props::{LineSpacing, ParaProps};
|
||||
use wordcraft_doc::{Table, para_block};
|
||||
|
||||
fn lay(doc: &Document) -> DocLayout {
|
||||
let mut c = LayoutCache::new();
|
||||
layout(doc, &mut c, &LayoutOptions::default())
|
||||
}
|
||||
|
||||
fn exact(height: f32, widow: bool) -> ParaProps {
|
||||
ParaProps {
|
||||
line_spacing: Some(LineSpacing::Exactly(height)),
|
||||
space_before: Some(0.0),
|
||||
space_after: Some(0.0),
|
||||
widow_control: Some(widow),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn lines_para(lines: usize, height: f32, widow: bool, name: &str) -> Arc<Block> {
|
||||
para_block(lines_paragraph(lines, height, widow, name))
|
||||
}
|
||||
|
||||
fn lines_paragraph(lines: usize, height: f32, widow: bool, name: &str) -> Paragraph {
|
||||
let text: Vec<String> = (1..=lines).map(|i| format!("{name}{i}")).collect();
|
||||
let mut p = Paragraph::with_text(&text.join(&wordcraft_doc::para::LINE_BREAK.to_string()), Default::default());
|
||||
p.props = exact(height, widow);
|
||||
p
|
||||
}
|
||||
|
||||
/// What the table is made of: `pre` one-line paragraphs of 16 pt before it, an optional repeated
|
||||
/// header row, a row (can't split or not) whose second cell holds `fill` lines of `fill_height`,
|
||||
/// the paragraphs `before` (lines and line height) and last a paragraph `last` of lines of a
|
||||
/// height. The last two are inside a nested table when `nested` is set.
|
||||
struct Case {
|
||||
pre: usize,
|
||||
header: bool,
|
||||
cant_split: bool,
|
||||
nested: bool,
|
||||
fill: usize,
|
||||
fill_height: f32,
|
||||
before: Vec<(usize, f32)>,
|
||||
last: (usize, f32),
|
||||
widow: bool,
|
||||
/// A picture floating through the text, anchored in the last paragraph and placed above it.
|
||||
float_above: bool,
|
||||
}
|
||||
|
||||
impl Case {
|
||||
fn new(last: (usize, f32)) -> Case {
|
||||
Case {
|
||||
pre: 0,
|
||||
header: false,
|
||||
cant_split: false,
|
||||
nested: false,
|
||||
fill: 45,
|
||||
fill_height: 14.0,
|
||||
before: Vec::new(),
|
||||
last,
|
||||
widow: true,
|
||||
float_above: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The lines of the last paragraph on each page.
|
||||
fn per_page(&self) -> Vec<usize> {
|
||||
crate::test_fonts();
|
||||
let w = self.widow;
|
||||
let mut d = Document::from_text("After");
|
||||
for i in 0..self.pre {
|
||||
let mut p = Paragraph::with_text(&format!("F{i}"), Default::default());
|
||||
p.props = exact(16.0, w);
|
||||
d.insert_block(StoryRef::Body, &Path::top(i), Block::Para(p)).unwrap();
|
||||
}
|
||||
let mut t = Table::new(1 + usize::from(self.header), 2, 400.0);
|
||||
t.props.cell_margins = Some([0.0, 5.4, 0.0, 5.4]);
|
||||
let row = usize::from(self.header);
|
||||
if self.header {
|
||||
t.rows[0].props.header = true;
|
||||
for c in &mut t.rows[0].cells {
|
||||
c.blocks = vec![lines_para(1, 14.0, w, "H")];
|
||||
}
|
||||
}
|
||||
t.rows[row].props.cant_split = self.cant_split;
|
||||
let mut inner: Vec<Arc<Block>> = self.before.iter().map(|&(n, h)| lines_para(n, h, w, "P")).collect();
|
||||
let mut last = lines_paragraph(self.last.0, self.last.1, w, "B");
|
||||
if self.float_above {
|
||||
let float = Float { wrap: Wrap::Through, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, x: 250.0, y: -6.0, ..Default::default() };
|
||||
let picture = InlineObject::Image {
|
||||
media: "float".into(),
|
||||
w: 20.0,
|
||||
h: 20.0,
|
||||
alt: "float".into(),
|
||||
float,
|
||||
crop: [0.0; 4],
|
||||
fx: Default::default(),
|
||||
ole: None,
|
||||
};
|
||||
last.insert_object(0, picture, &Default::default()).unwrap();
|
||||
}
|
||||
inner.push(para_block(last));
|
||||
// Without a fill paragraph the cell starts with `inner`.
|
||||
let mut blocks = if self.fill > 0 { vec![lines_para(self.fill, self.fill_height, w, "A")] } else { Vec::new() };
|
||||
let mut at = vec![self.pre as u32, row as u32, 1, (blocks.len() + inner.len()) as u32 - 1];
|
||||
if self.nested {
|
||||
let mut nested = Table::new(1, 1, 200.0);
|
||||
nested.rows[0].cells[0].blocks = inner.clone();
|
||||
at = vec![self.pre as u32, row as u32, 1, blocks.len() as u32, 0, 0, inner.len() as u32 - 1];
|
||||
blocks.push(Arc::new(Block::Table(nested)));
|
||||
blocks.push(lines_para(1, 1.0, w, "Z"));
|
||||
} else {
|
||||
blocks.extend(inner);
|
||||
}
|
||||
t.rows[row].cells[1].blocks = blocks;
|
||||
d.insert_block(StoryRef::Body, &Path::top(self.pre), Block::Table(t)).unwrap();
|
||||
lay(&d)
|
||||
.pages
|
||||
.iter()
|
||||
.map(|p| {
|
||||
p.items
|
||||
.iter()
|
||||
.filter_map(|it| match it {
|
||||
Placed::Lines { path, l0, l1, .. } if path.0 == at => Some(l1 - l0),
|
||||
_ => None,
|
||||
})
|
||||
.sum()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// A three-line paragraph at the top of a page with room for its first line only keeps that line
|
||||
/// there (the next two go on, one to a page here).
|
||||
#[test]
|
||||
fn a_first_line_alone_at_the_top_of_a_page_stays_in_a_split_row() {
|
||||
assert_eq!(Case::new((3, 400.0)).per_page(), vec![0, 1, 1, 1]);
|
||||
}
|
||||
|
||||
/// Two lines, room for one: one and one.
|
||||
#[test]
|
||||
fn a_two_line_paragraph_at_the_top_of_a_page_splits_one_and_one() {
|
||||
assert_eq!(Case::new((2, 400.0)).per_page(), vec![0, 1, 1]);
|
||||
}
|
||||
|
||||
/// Three lines, room for two: two and one (not the whole paragraph on, which is no better at the
|
||||
/// top of a page, and not one and two).
|
||||
#[test]
|
||||
fn a_three_line_paragraph_at_the_top_of_a_page_with_room_for_two_splits_two_and_one() {
|
||||
assert_eq!(Case::new((3, 300.0)).per_page(), vec![0, 2, 1]);
|
||||
}
|
||||
|
||||
/// Guard (passes without the fix): four lines with room for three still keep two for the widow.
|
||||
#[test]
|
||||
fn four_lines_at_the_top_of_a_page_with_room_for_three_still_keep_two_for_the_widow() {
|
||||
assert_eq!(Case::new((4, 200.0)).per_page(), vec![0, 2, 2]);
|
||||
}
|
||||
|
||||
/// Guard (passes without the fix): a paragraph below another one of its cell on the page keeps
|
||||
/// the orphan rule, so its single line there moves on with the rest.
|
||||
#[test]
|
||||
fn a_paragraph_below_other_content_of_its_cell_still_moves_on_whole_instead_of_an_orphan() {
|
||||
let mut c = Case::new((3, 200.0));
|
||||
c.before = vec![(1, 300.0)];
|
||||
assert_eq!(c.per_page(), vec![0, 0, 3]);
|
||||
}
|
||||
|
||||
/// Where only the later paragraphs of a cell continue, the one that moved to the top of a page
|
||||
/// splits at its lines (two and one), the paragraph before it having stayed.
|
||||
#[test]
|
||||
fn a_later_paragraph_moved_to_the_top_of_a_page_splits_where_its_lines_fall() {
|
||||
let mut c = Case::new((3, 300.0));
|
||||
c.before = vec![(1, 100.0)];
|
||||
assert_eq!(c.per_page(), vec![0, 0, 2, 1]);
|
||||
}
|
||||
|
||||
/// Guard (passes without the fix): four lines below a paragraph, room for three, keep two.
|
||||
#[test]
|
||||
fn four_lines_below_other_content_with_room_for_three_still_keep_two_for_the_widow() {
|
||||
let mut c = Case::new((4, 200.0));
|
||||
c.before = vec![(1, 40.0)];
|
||||
assert_eq!(c.per_page(), vec![0, 2, 2]);
|
||||
}
|
||||
|
||||
/// Guard (passes without the fix): without widow control the paragraph always split where it fell.
|
||||
#[test]
|
||||
fn without_widow_control_the_lines_split_where_they_fall() {
|
||||
let mut c = Case::new((3, 400.0));
|
||||
c.widow = false;
|
||||
assert_eq!(c.per_page(), vec![0, 1, 1, 1]);
|
||||
}
|
||||
|
||||
/// A paragraph of a nested table splits the same way.
|
||||
#[test]
|
||||
fn a_nested_paragraph_at_the_top_of_a_page_splits_where_its_lines_fall() {
|
||||
let mut c = Case::new((3, 300.0));
|
||||
c.nested = true;
|
||||
assert_eq!(c.per_page(), vec![0, 2, 1]);
|
||||
let mut c = Case::new((2, 400.0));
|
||||
c.nested = true;
|
||||
assert_eq!(c.per_page(), vec![0, 1, 1]);
|
||||
}
|
||||
|
||||
/// A nested paragraph below another one of the nested cell moves on whole, then splits at the top
|
||||
/// of the page.
|
||||
#[test]
|
||||
fn a_nested_paragraph_below_other_content_moves_on_then_splits() {
|
||||
let mut c = Case::new((3, 300.0));
|
||||
c.nested = true;
|
||||
c.before = vec![(1, 100.0)];
|
||||
assert_eq!(c.per_page(), vec![0, 0, 2, 1]);
|
||||
}
|
||||
|
||||
/// Under a repeated header row the paragraph that starts the page splits at its lines too. The
|
||||
/// lines per page are Word's; Word leaves the header off some of the pages, which is not covered.
|
||||
#[test]
|
||||
fn under_a_repeated_header_row_the_paragraph_starting_the_page_splits_where_its_lines_fall() {
|
||||
let mut c = Case::new((3, 300.0));
|
||||
c.header = true;
|
||||
c.fill = 44;
|
||||
assert_eq!(c.per_page(), vec![0, 2, 1]);
|
||||
let mut c = Case::new((3, 300.0));
|
||||
c.header = true;
|
||||
c.fill = 44;
|
||||
c.before = vec![(1, 100.0)];
|
||||
assert_eq!(c.per_page(), vec![0, 0, 2, 1]);
|
||||
}
|
||||
|
||||
/// Guard (passes without the fix): under a header row, four lines with room for three keep two.
|
||||
#[test]
|
||||
fn under_a_repeated_header_row_four_lines_still_keep_two_for_the_widow() {
|
||||
let mut c = Case::new((4, 200.0));
|
||||
c.header = true;
|
||||
c.fill = 44;
|
||||
assert_eq!(c.per_page(), vec![0, 2, 2]);
|
||||
}
|
||||
|
||||
/// A can't split row taller than a page splits where the pages end.
|
||||
#[test]
|
||||
fn a_cant_split_row_taller_than_a_page_splits_where_the_page_ends() {
|
||||
let mut c = Case::new((3, 400.0));
|
||||
c.cant_split = true;
|
||||
assert_eq!(c.per_page(), vec![0, 1, 1, 1]);
|
||||
}
|
||||
|
||||
/// A can't split row taller than a page that starts below text goes to the next page first, then
|
||||
/// splits there.
|
||||
#[test]
|
||||
fn a_tall_cant_split_row_below_text_starts_the_next_page_and_splits_there() {
|
||||
let mut c = Case::new((3, 400.0));
|
||||
c.cant_split = true;
|
||||
c.pre = 20;
|
||||
assert_eq!(c.per_page(), vec![0, 0, 1, 1, 1]);
|
||||
}
|
||||
|
||||
/// Guard (passes without the fix): a can't split row that fits the next page moves there whole.
|
||||
#[test]
|
||||
fn a_cant_split_row_that_fits_the_next_page_moves_there_whole() {
|
||||
let mut c = Case::new((3, 16.0));
|
||||
c.cant_split = true;
|
||||
c.pre = 38;
|
||||
c.fill = 5;
|
||||
c.fill_height = 16.0;
|
||||
assert_eq!(c.per_page(), vec![0, 3]);
|
||||
}
|
||||
|
||||
/// A picture floating above the paragraph that starts the cell doesn't make it any less the
|
||||
/// first: only the text in the flow decides. (Floats are placed with the first piece of their
|
||||
/// paragraph, so this is the table's first page.)
|
||||
#[test]
|
||||
fn a_floating_picture_above_the_first_paragraph_doesnt_keep_it_from_splitting() {
|
||||
let mut c = Case::new((3, 400.0));
|
||||
c.fill = 0;
|
||||
c.float_above = true;
|
||||
assert_eq!(c.per_page(), vec![1, 1, 1]);
|
||||
}
|
||||
|
||||
/// Guard (passes without the fix): a can't split row that fits a page with room to spare stays
|
||||
/// whole on it, whatever the border below it needs.
|
||||
#[test]
|
||||
fn a_cant_split_row_that_fits_a_page_is_left_whole() {
|
||||
let mut c = Case::new((1, 10.0));
|
||||
c.cant_split = true;
|
||||
assert_eq!(c.per_page(), vec![1, 0], "the row stays on page 1 (the paragraph after it is on page 2)");
|
||||
}
|
||||
@@ -302,8 +302,10 @@ fn inline_box_that_resizes_to_fit_takes_its_texts_height() {
|
||||
}
|
||||
|
||||
/// Filler paragraphs before the box in [`inline_box_that_resizes_to_fit_takes_its_texts_height`]:
|
||||
/// enough that a 10 cm box no longer leaves room for the page break on the first page.
|
||||
const FILLER: usize = 22;
|
||||
/// enough that a 10 cm box no longer leaves room for the page break on the first page, while the
|
||||
/// box fitted to its three lines does (a paragraph of only a page break that doesn't fit goes to
|
||||
/// the next page, as in Word).
|
||||
const FILLER: usize = 20;
|
||||
|
||||
/// A floating box that resizes to fit its text takes its text's height too, both where it is
|
||||
/// drawn and the room the text beside it wraps around (an OpenDocument frame without a height).
|
||||
|
||||
@@ -16,7 +16,7 @@ craft = { workspace = true, features = [
|
||||
"color", "color-ui", "control", "draw", "font-manager", "gpu", "menu", "pages", "print", "review", "table", "text",
|
||||
"text-find", "web-api", "web-host", "window",
|
||||
] }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38" }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49" }
|
||||
wordcraft-geom = { workspace = true, features = ["image"] }
|
||||
wordcraft-doc = { workspace = true }
|
||||
wordcraft-fonts = { workspace = true }
|
||||
@@ -65,13 +65,18 @@ wordcraft-engine = { workspace = true, features = ["test-support"] }
|
||||
# kittest's own dev-dependencies do not propagate their font features. Declare the fonts the
|
||||
# interface tests lay out explicitly: default faces plus monochrome emoji fallbacks.
|
||||
egui = { workspace = true, features = ["default_fonts", "monochrome_emoji_fonts"] }
|
||||
egui_kittest = { workspace = true, features = ["wgpu", "snapshot"] }
|
||||
egui_kittest = { workspace = true, features = ["wgpu", "snapshot", "eframe"] }
|
||||
# The app-window tests run `WordApp` as an `eframe::App` (`test_harness`), so the runtime gets the app's input before
|
||||
# every pass as on the desktop. The desktop app's feature set, so a workspace build shares one eframe.
|
||||
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "clipboard", "wayland", "x11", "links"] }
|
||||
craft-zip = { workspace = true }
|
||||
# The window tests' frame driver for child viewports; it is not part of the `craft` facade.
|
||||
craft-ui-test-kit = { workspace = true }
|
||||
# The interface tests' fixture and access tree (`craft::ui::testing`).
|
||||
craft = { workspace = true, features = ["ui-testing"] }
|
||||
|
||||
[build-dependencies]
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", features = ["subset"] }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", features = ["subset"] }
|
||||
serde_json = { workspace = true }
|
||||
toml = "1"
|
||||
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" width="20" height="20">
|
||||
<path d="M3 6 L7 3.5 L13 3.5 L17 6 L17.5 14 L13.5 16.5 L6.5 16.5 L2.5 14 Z M6 10.5 A1.5 1.5 0 1 0 9 10.5 A1.5 1.5 0 1 0 6 10.5 Z M11 10.5 A1.5 1.5 0 1 0 14 10.5 A1.5 1.5 0 1 0 11 10.5 Z" fill="currentColor" fill-rule="evenodd"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 322 B |
@@ -6,6 +6,7 @@ use super::{
|
||||
theme, updates_ui, window_ui, windows, zotero,
|
||||
};
|
||||
use craft::platform::clock::monotonic_ms;
|
||||
use craft::theme::ComponentSet;
|
||||
use craft::ui::runtime::commands::CommandInput;
|
||||
use craft::ui::runtime::env::{AltCodePages, ResolvedRoot, RootEnv, WheelSpeed};
|
||||
use craft::ui::runtime::frame::{FrameInput, FrameOutput};
|
||||
@@ -101,6 +102,8 @@ impl WordApp {
|
||||
command_catalog_lang: "",
|
||||
key_overrides: Default::default(),
|
||||
command_states: Default::default(),
|
||||
command_states_cache: None,
|
||||
keytip_cache: None,
|
||||
fonts_frames: 0,
|
||||
clipboard_published: false,
|
||||
printing: Default::default(),
|
||||
@@ -184,7 +187,7 @@ impl WordApp {
|
||||
}
|
||||
|
||||
/// This frame's root values: the wheel speed, the Alt-code pages, the interface mode,
|
||||
/// motion, scale and direction. Built from the saved settings every frame, so a change
|
||||
/// motion, scale, direction and the component set (WordCraft takes the productivity set). Built from the saved settings every frame, so a change
|
||||
/// applies at once.
|
||||
pub fn root_env(&self) -> RootEnv {
|
||||
let lang = i18n::Lang::from_pref(&self.ui.language);
|
||||
@@ -204,7 +207,8 @@ impl WordApp {
|
||||
.direction(direction)
|
||||
.mode(self.ui.theme.mode())
|
||||
.wheel_speed(WheelSpeed::new(line, point))
|
||||
.alt_code_pages(AltCodePages::new(ansi, oem));
|
||||
.alt_code_pages(AltCodePages::new(ansi, oem))
|
||||
.set(ComponentSet::Productivity);
|
||||
env.motion = self.ui.animations.motion();
|
||||
env.sizes = std::sync::Arc::clone(&APP_SIZES);
|
||||
env
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! The app's side of the framework command runtime: the catalog of commands and their default
|
||||
//! chords, the per-frame state (enabled, checked, hint) and the running of what the runtime fired.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft::keymap::Overrides;
|
||||
@@ -52,6 +52,21 @@ const GATED_UI_COMMANDS: &[(&str, &str)] = &[
|
||||
("ui.zotero.removeCodes", "Unlink Citations"),
|
||||
];
|
||||
|
||||
/// Word feature catalog entries whose command is not yet registered in `registry`: each gets a
|
||||
/// catalog entry without a chord (preventing unregistered-command warnings) and a disabled state
|
||||
/// until an engine command takes its id.
|
||||
fn unimplemented_catalog_commands(registry: &wordcraft_engine::Registry) -> impl Iterator<Item = (&'static str, &'static str)> + '_ {
|
||||
let mut seen = HashSet::new();
|
||||
wordcraft_engine::catalog::CATALOG.lines().filter_map(move |line| {
|
||||
let mut parts = line.split('|');
|
||||
let _tab = parts.next()?;
|
||||
let _group = parts.next()?;
|
||||
let feature = parts.next()?;
|
||||
let id = parts.next()?;
|
||||
(registry.get(id).is_none() && seen.insert(id)).then_some((id, feature))
|
||||
})
|
||||
}
|
||||
|
||||
/// The default chords of an engine command: its `shortcut`, one binding per `" / "` piece.
|
||||
fn default_bindings(shortcut: &str) -> impl Iterator<Item = Binding> + '_ {
|
||||
shortcut.split(" / ").filter(|piece| !piece.is_empty()).filter_map(|piece| Binding::parse(piece).ok())
|
||||
@@ -68,6 +83,62 @@ fn with_word_chords(catalog: AppCatalog) -> AppCatalog {
|
||||
.fold(catalog, |catalog, command| catalog.replace_defaults(command.id(), Vec::new()))
|
||||
}
|
||||
|
||||
/// Precomputed command references, translated hints, and last gate results for
|
||||
/// [`WordApp::command_input`], rebuilt when the engine registry or interface language changes.
|
||||
///
|
||||
/// Every command's gate predicate still runs on every frame so enabled/disabled state is never
|
||||
/// stale; only the per-frame `CATALOG.lines()` parsing, `i18n` hint formatting, and full
|
||||
/// `CommandStates` map rebuild are skipped when nothing changed.
|
||||
pub(crate) struct CommandStatesCache {
|
||||
registry: Arc<wordcraft_engine::Registry>,
|
||||
lang: &'static str,
|
||||
/// `(id, location, label, prebuilt CommandRef, last (enabled, reason))` for every registered
|
||||
/// engine command, in registry order.
|
||||
registered: Vec<(&'static str, &'static str, &'static str, CommandRef, Option<(bool, Option<&'static str>)>)>,
|
||||
/// `(id, prebuilt CommandRef, last enabled)` for gated `ui.*` commands.
|
||||
ui_commands: Vec<(&'static str, CommandRef, Option<bool>)>,
|
||||
/// `(id, prebuilt CommandRef, last enabled)` for unimplemented Word catalog commands.
|
||||
unimplemented: Vec<(&'static str, CommandRef, Option<bool>)>,
|
||||
/// Precomputed `CommandRef` and last enabled state for `ui.dialog {"name": "commands"}`.
|
||||
commands_dialog: (CommandRef, Option<bool>),
|
||||
/// Translated fallback hint shared by all unimplemented catalog commands.
|
||||
unavailable_hint: Option<Arc<str>>,
|
||||
/// Cached translated hints by `(spec index, disabled reason)` for the current language.
|
||||
hints: HashMap<(usize, Option<&'static str>), Option<Arc<str>>>,
|
||||
}
|
||||
|
||||
impl CommandStatesCache {
|
||||
fn new(registry: Arc<wordcraft_engine::Registry>, lang: &'static str) -> Self {
|
||||
let registered = registry.all().iter().map(|spec| (spec.id, spec.location, spec.label, CommandRef::new(spec.id), None)).collect();
|
||||
let ui_commands = ["ui.collapseRibbon", "ui.resetInterfaceSize", "ui.print", "ui.printSubmit"]
|
||||
.into_iter()
|
||||
.chain(GATED_UI_COMMANDS.iter().map(|(id, _)| *id))
|
||||
.map(|id| (id, CommandRef::new(id), None))
|
||||
.collect();
|
||||
let unimplemented = unimplemented_catalog_commands(®istry).map(|(id, _)| (id, CommandRef::new(id), None)).collect();
|
||||
let commands_dialog = (CommandRef::with_params("ui.dialog", json!({"name": "commands"})), None);
|
||||
let unavailable_hint = crate::widgets::command_hint("", "", Some("")).map(Arc::from);
|
||||
CommandStatesCache { registry, lang, registered, ui_commands, unimplemented, commands_dialog, unavailable_hint, hints: HashMap::new() }
|
||||
}
|
||||
|
||||
fn matches(&self, registry: &Arc<wordcraft_engine::Registry>, lang: &'static str) -> bool {
|
||||
self.lang == lang && Arc::ptr_eq(&self.registry, registry)
|
||||
}
|
||||
|
||||
fn hint_for(&mut self, idx: usize, location: &str, label: &str, reason: Option<&'static str>) -> Option<Arc<str>> {
|
||||
self.hints.entry((idx, reason)).or_insert_with(|| crate::widgets::command_hint(location, label, reason).map(Arc::from)).clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// Gate check for a command known to live in `app.session.registry` (skips the extra registry lookup).
|
||||
fn gate_registered(app: &WordApp, id: &str) -> (bool, Option<&'static str>) {
|
||||
if !app.has_document() && !super::commands::works_without_document(id) {
|
||||
return (false, None);
|
||||
}
|
||||
let reason = app.session.why_disabled(id);
|
||||
(reason.is_none(), reason)
|
||||
}
|
||||
|
||||
impl WordApp {
|
||||
/// The app's commands as the keymap knows them: every engine command with its default
|
||||
/// chords, then the interface commands. The interface commands come last because a tie in the
|
||||
@@ -123,6 +194,11 @@ impl WordApp {
|
||||
for (id, label) in GATED_UI_COMMANDS {
|
||||
defs.push(CommandDef::new(CommandRef::new(*id), tl!(*label), Scope::app()));
|
||||
}
|
||||
for (id, feature) in unimplemented_catalog_commands(®istry) {
|
||||
if seen.insert(id) {
|
||||
defs.push(CommandDef::new(CommandRef::new(id), tl!(feature), Scope::app()));
|
||||
}
|
||||
}
|
||||
// Word's Alt chords (Alt+Q, Alt+F7, Ctrl+Alt+1…) fire while the person types in the page:
|
||||
// plain keys type, and every modified chord is offered to the keymap first.
|
||||
match AppCatalog::new(defs, generation) {
|
||||
@@ -157,28 +233,78 @@ impl WordApp {
|
||||
if let Some(catalog) = self.catalog() {
|
||||
input = input.catalog(catalog);
|
||||
}
|
||||
let mut states = CommandStates::new();
|
||||
for spec in registry.all() {
|
||||
let (enabled, reason) = gate(self, spec.id); // A toggle's checked state is bound at its ribbon button, not here.
|
||||
let mut state = CommandState::new().enabled(enabled);
|
||||
if let Some(hint) = crate::widgets::command_hint(spec.location, spec.label, reason) {
|
||||
state = state.hint(hint);
|
||||
let lang = crate::i18n::current().code();
|
||||
let (mut cache, fresh_cache) = match self.command_states_cache.take() {
|
||||
Some(cache) if cache.matches(®istry, lang) => (cache, false),
|
||||
_ => (CommandStatesCache::new(registry, lang), true),
|
||||
};
|
||||
|
||||
// Re-evaluate every command's gate without allocating on idle frames. A fresh cache has
|
||||
// `None` in every `last` slot, so the same compare pass collects every entry for it.
|
||||
let mut reg_changes: Vec<(usize, bool, Option<&'static str>)> = Vec::new();
|
||||
for (i, &(id, _, _, _, last)) in cache.registered.iter().enumerate() {
|
||||
let current = gate_registered(self, id);
|
||||
if last != Some(current) {
|
||||
reg_changes.push((i, current.0, current.1));
|
||||
}
|
||||
states.set(CommandRef::new(spec.id), state);
|
||||
}
|
||||
// Print acts on the document, so with none open it is off like the engine's commands (#1129); a command with
|
||||
// no state here resolves as enabled.
|
||||
let ids = ["ui.collapseRibbon", "ui.resetInterfaceSize", "ui.print", "ui.printSubmit"]
|
||||
.into_iter()
|
||||
.chain(GATED_UI_COMMANDS.iter().map(|(id, _)| *id));
|
||||
for id in ids {
|
||||
states.set(CommandRef::new(id), CommandState::new().enabled(command_enabled(self, id)));
|
||||
let mut ui_changes: Vec<(usize, bool)> = Vec::new();
|
||||
for (i, &(id, _, last)) in cache.ui_commands.iter().enumerate() {
|
||||
let enabled = command_enabled(self, id);
|
||||
if last != Some(enabled) {
|
||||
ui_changes.push((i, enabled));
|
||||
}
|
||||
}
|
||||
let commands = CommandRef::with_params("ui.dialog", json!({"name": "commands"}));
|
||||
states.set(commands, CommandState::new().enabled(command_enabled(self, "ui.dialog")));
|
||||
if *self.command_states != states {
|
||||
self.command_states.edit(|kept| *kept = states);
|
||||
let mut unimpl_changes: Vec<(usize, bool)> = Vec::new();
|
||||
for (i, &(id, _, last)) in cache.unimplemented.iter().enumerate() {
|
||||
let enabled = command_enabled(self, id);
|
||||
if last != Some(enabled) {
|
||||
unimpl_changes.push((i, enabled));
|
||||
}
|
||||
}
|
||||
let dialog_enabled = command_enabled(self, "ui.dialog");
|
||||
let dialog_changed = cache.commands_dialog.1 != Some(dialog_enabled);
|
||||
|
||||
let any_changed = !reg_changes.is_empty() || !ui_changes.is_empty() || !unimpl_changes.is_empty() || dialog_changed;
|
||||
if fresh_cache || any_changed {
|
||||
let apply = |kept: &mut CommandStates| {
|
||||
for (i, enabled, reason) in reg_changes {
|
||||
let (_, location, label, _, _) = cache.registered[i];
|
||||
cache.registered[i].4 = Some((enabled, reason));
|
||||
let mut state = CommandState::new().enabled(enabled);
|
||||
if let Some(hint) = cache.hint_for(i, location, label, reason) {
|
||||
state = state.hint(hint);
|
||||
}
|
||||
kept.set(cache.registered[i].3.clone(), state);
|
||||
}
|
||||
for (i, enabled) in ui_changes {
|
||||
cache.ui_commands[i].2 = Some(enabled);
|
||||
kept.set(cache.ui_commands[i].1.clone(), CommandState::new().enabled(enabled));
|
||||
}
|
||||
for (i, enabled) in unimpl_changes {
|
||||
cache.unimplemented[i].2 = Some(enabled);
|
||||
let mut state = CommandState::new().enabled(enabled);
|
||||
if let Some(hint) = cache.unavailable_hint.as_ref() {
|
||||
state = state.hint(Arc::clone(hint));
|
||||
}
|
||||
kept.set(cache.unimplemented[i].1.clone(), state);
|
||||
}
|
||||
if dialog_changed {
|
||||
cache.commands_dialog.1 = Some(dialog_enabled);
|
||||
kept.set(cache.commands_dialog.0.clone(), CommandState::new().enabled(dialog_enabled));
|
||||
}
|
||||
};
|
||||
if fresh_cache {
|
||||
let mut states = CommandStates::new();
|
||||
apply(&mut states);
|
||||
if *self.command_states != states {
|
||||
self.command_states.edit(|kept| *kept = states);
|
||||
}
|
||||
} else {
|
||||
self.command_states.edit(apply);
|
||||
}
|
||||
}
|
||||
self.command_states_cache = Some(cache);
|
||||
input.states(&self.command_states)
|
||||
}
|
||||
|
||||
@@ -277,4 +403,80 @@ mod tests {
|
||||
crate::undo_marks::apply_edits(&mut app, end, apply);
|
||||
assert_eq!(app.session.undo_depth(), after_undo, "the late Commit of the taken-back gesture adds no step");
|
||||
}
|
||||
|
||||
/// #7310: unimplemented Word feature catalog commands publish a disabled state so ribbon
|
||||
/// buttons and keytips bound to them resolve disabled instead of falling back to enabled.
|
||||
#[test]
|
||||
fn unimplemented_catalog_commands_publish_disabled_state() {
|
||||
let mut app = WordApp::new(Session::new(wordcraft_doc::Document::new()), Default::default());
|
||||
let _ = app.command_input();
|
||||
for id in ["tools.dictate", "draw.inkToMath", "review.translate", "review.blockAuthors"] {
|
||||
assert!(app.session.registry.get(id).is_none(), "{id} is still an unimplemented stub");
|
||||
let state = app.command_states.get(&CommandRef::new(id));
|
||||
assert!(
|
||||
state.is_some_and(|s| !s.is_enabled()),
|
||||
"unimplemented catalog command {id} must publish an explicit disabled state, got {state:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Cached `command_input()` keeps steady-state idle calls zero-change while immediately reflecting
|
||||
/// table/context transitions and document-open state changes.
|
||||
#[test]
|
||||
fn command_input_cache_tracks_state_transitions_and_is_noop_when_idle() {
|
||||
let mut app = WordApp::new(Session::new(wordcraft_doc::Document::new()), Default::default());
|
||||
let _ = app.command_input();
|
||||
let rev_after_first = app.command_states.revision();
|
||||
assert!(
|
||||
!app.command_states.get(&CommandRef::new("table.deleteRow")).unwrap().is_enabled(),
|
||||
"table.deleteRow starts disabled outside a table"
|
||||
);
|
||||
assert!(app.command_states.get(&CommandRef::new("format.bold")).unwrap().is_enabled(), "format.bold starts enabled");
|
||||
|
||||
// Repeated idle calls must not mutate `command_states` or bump its revision.
|
||||
for _ in 0..5 {
|
||||
let _ = app.command_input();
|
||||
}
|
||||
assert_eq!(app.command_states.revision(), rev_after_first, "idle frames leave command_states revision untouched");
|
||||
|
||||
// Entering a table enables `table.deleteRow` immediately on the next `command_input()`.
|
||||
app.run("insert.table", json!({"rows": 2, "cols": 2})).unwrap();
|
||||
let _ = app.command_input();
|
||||
let rev_after_table = app.command_states.revision();
|
||||
assert_ne!(rev_after_table, rev_after_first, "state change bumps command_states revision");
|
||||
assert!(app.command_states.get(&CommandRef::new("table.deleteRow")).unwrap().is_enabled(), "table.deleteRow is enabled inside a table");
|
||||
|
||||
// Closing the document disables document commands immediately.
|
||||
app.no_document = Some(app.session.document_id());
|
||||
let _ = app.command_input();
|
||||
assert!(!app.command_states.get(&CommandRef::new("format.bold")).unwrap().is_enabled(), "format.bold disables when no document is open");
|
||||
|
||||
// Dropping the cache and rebuilding from scratch must produce the exact same `CommandStates`.
|
||||
let incremental = (*app.command_states).clone();
|
||||
app.command_states_cache = None;
|
||||
let _ = app.command_input();
|
||||
assert_eq!(*app.command_states, incremental, "incremental cache matches full rebuild exactly");
|
||||
|
||||
// Swapping the registry rebuilds `command_states` cleanly and drops commands that are no
|
||||
// longer registered.
|
||||
app.no_document = None;
|
||||
let full_registry = app.session.registry.clone();
|
||||
app.session.registry = std::sync::Arc::new(wordcraft_engine::Registry::new(vec![wordcraft_engine::CommandSpec::new(
|
||||
"test.ephemeral",
|
||||
"Ephemeral",
|
||||
"Home",
|
||||
|_, _| Ok(json!({})),
|
||||
)]));
|
||||
let _ = app.command_input();
|
||||
assert!(
|
||||
app.command_states.get(&CommandRef::new("test.ephemeral")).is_some_and(|s| s.is_enabled()),
|
||||
"custom registry command is published when registered"
|
||||
);
|
||||
app.session.registry = full_registry;
|
||||
let _ = app.command_input();
|
||||
assert!(
|
||||
app.command_states.get(&CommandRef::new("test.ephemeral")).is_none(),
|
||||
"swapping back to the default registry clears removed commands from command_states"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -181,6 +181,7 @@ impl WordApp {
|
||||
/// Close prompt `id` from outside and drop the answer that leaves behind.
|
||||
pub(crate) fn close_prompt(&mut self, id: DialogId) {
|
||||
if let Some(ctx) = self.ctx.clone() {
|
||||
crate::dialogs::chrome::forget_nudge(&ctx, id);
|
||||
self.dialog_host.cancel_by_id(&ctx, id);
|
||||
}
|
||||
let _ = self.dialog_host.take_by_id::<UnsavedChangesDialog>(id);
|
||||
@@ -191,6 +192,9 @@ impl WordApp {
|
||||
pub(crate) fn pump_close_prompt(&mut self) {
|
||||
let Some(id) = self.closing.as_ref().and_then(|c| c.prompt) else { return };
|
||||
let Some(result) = self.dialog_host.take_by_id::<UnsavedChangesDialog>(id) else { return };
|
||||
if let Some(ctx) = self.ctx.as_ref() {
|
||||
crate::dialogs::chrome::forget_nudge(ctx, id);
|
||||
}
|
||||
if let Some(closing) = self.closing.as_mut() {
|
||||
closing.prompt = None;
|
||||
}
|
||||
@@ -633,7 +637,7 @@ impl WordApp {
|
||||
for item in intake.take() {
|
||||
match item {
|
||||
Intake::Dropped { files, target } => self.open_dropped(&files, target),
|
||||
Intake::Open(paths) => {
|
||||
Intake::Open(paths) | Intake::OpenFor { paths, .. } => {
|
||||
for p in paths {
|
||||
// A path that is not Unicode cannot be passed on as text: skipped.
|
||||
if let Some(path) = p.to_str()
|
||||
@@ -649,6 +653,14 @@ impl WordApp {
|
||||
Intake::Quit => {
|
||||
self.quit();
|
||||
}
|
||||
// An OS open request that arrived as bytes, with no path.
|
||||
Intake::Bytes { name, bytes } => {
|
||||
let data = wordcraft_engine::cmd::insert::base64_encode(bytes.as_ref());
|
||||
if let Err(e) = self.run("file.open", json!({"path": name, "data": data})) {
|
||||
self.report_open_failure(&name, &e);
|
||||
}
|
||||
self.ui.backstage = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -158,4 +158,145 @@ mod tests {
|
||||
let missing = missing_glyphs(&stack, &FontRef::proportional(), samples, false);
|
||||
assert!(missing.is_empty(), "symbols without a glyph: {missing:#?}");
|
||||
}
|
||||
|
||||
/// An installed Arabic font is asked for only when Arabic text needs one (and no embedded
|
||||
/// Arabic face covers it): neither installing the UI font stack for English/CJK/Arabic nor
|
||||
/// triggering CJK on-demand fallback ever asks for an Arabic system font, and Arabic on-demand
|
||||
/// fallback never asks for a CJK system font.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn the_installed_arabic_font_is_asked_for_by_arabic_alone() {
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Mutex;
|
||||
|
||||
use craft::host::Wake;
|
||||
use craft::i18n::Han;
|
||||
use craft::ui::fonts::{FontCandidates, on_demand_registered};
|
||||
|
||||
struct RecordingCandidates {
|
||||
scripts: Mutex<Vec<String>>,
|
||||
}
|
||||
|
||||
impl RecordingCandidates {
|
||||
fn new() -> Arc<Self> {
|
||||
Arc::new(Self { scripts: Mutex::new(Vec::new()) })
|
||||
}
|
||||
|
||||
fn scripts(&self) -> Vec<String> {
|
||||
self.scripts.lock().map(|guard| guard.clone()).unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
impl FontCandidates for RecordingCandidates {
|
||||
fn files(&self, script: &str, han: Option<Han>) -> Vec<PathBuf> {
|
||||
if let Ok(mut scripts) = self.scripts.lock() {
|
||||
scripts.push(script.to_owned());
|
||||
}
|
||||
SystemCandidates.files(script, han)
|
||||
}
|
||||
|
||||
fn covers(&self, data: &[u8], c: char) -> Option<u32> {
|
||||
SystemCandidates.covers(data, c)
|
||||
}
|
||||
|
||||
fn pending(&self) -> bool {
|
||||
SystemCandidates.pending()
|
||||
}
|
||||
|
||||
fn wake_when_ready(&self, wake: Wake) {
|
||||
SystemCandidates.wake_when_ready(wake);
|
||||
}
|
||||
}
|
||||
|
||||
let paint = |ctx: &egui::Context, text: &str| {
|
||||
for _ in 0..6 {
|
||||
ctx.run_ui(egui::RawInput::default(), |ui| {
|
||||
ui.label(text);
|
||||
})
|
||||
.drop_without_applying_deltas();
|
||||
}
|
||||
};
|
||||
let is_cjk_script = |script: &str| matches!(script, "Hani" | "Hira" | "Kana" | "Hang" | "Bopo");
|
||||
|
||||
let en = Lang::EN;
|
||||
let ja = crate::i18n::fixture_lang("ja", "\tHome\tホーム\n");
|
||||
let ar = crate::i18n::fixture_lang("ar", "\tHome\tالرئيسية\n");
|
||||
|
||||
// Installing the production `ui_fonts` stack and painting Latin text never requests or
|
||||
// loads an installed Arabic or CJK system font up front.
|
||||
for lang in [en, ja, ar] {
|
||||
let ctx = egui::Context::default();
|
||||
let spy = RecordingCandidates::new();
|
||||
ui_fonts(lang).on_demand(Arc::clone(&spy) as Arc<dyn FontCandidates>).install(&ctx);
|
||||
assert!(on_demand_registered(&ctx).is_empty(), "{}: installing ui_fonts reads no system font eagerly", lang.code());
|
||||
assert!(spy.scripts().is_empty(), "{}: installing ui_fonts requests no system font candidates", lang.code());
|
||||
paint(&ctx, "Hello");
|
||||
assert!(on_demand_registered(&ctx).is_empty(), "{}: Latin UI text reads no system font", lang.code());
|
||||
assert!(spy.scripts().is_empty(), "{}: Latin UI text requests no system font candidates", lang.code());
|
||||
}
|
||||
|
||||
let embedded_arabic: Vec<String> = CRAFT_FONTS.iter().filter(|f| f.has_script("Arab")).map(EmbeddedFace::name).collect();
|
||||
let ar_ctx = egui::Context::default();
|
||||
let ar_stack = ui_fonts(ar).install(&ar_ctx);
|
||||
let en_stack = ui_fonts(en).stack();
|
||||
let ja_stack = ui_fonts(ja).stack();
|
||||
if !embedded_arabic.is_empty() {
|
||||
assert!(
|
||||
ar_stack.chain(&FontRef::proportional()).first().is_some_and(|name| embedded_arabic.contains(name)),
|
||||
"Arabic UI leads with its embedded Arabic face"
|
||||
);
|
||||
assert!(
|
||||
!en_stack.chain(&FontRef::proportional()).first().is_some_and(|name| embedded_arabic.contains(name)),
|
||||
"English UI does not lead with an Arabic face"
|
||||
);
|
||||
assert!(
|
||||
!ja_stack.chain(&FontRef::proportional()).first().is_some_and(|name| embedded_arabic.contains(name)),
|
||||
"CJK UI does not lead with an Arabic face"
|
||||
);
|
||||
paint(&ar_ctx, "مرحبا");
|
||||
assert!(ar_ctx.fonts_mut(|f| f.has_glyph(&egui::FontId::proportional(14.0), 'ع')), "embedded Arabic face draws Arabic text");
|
||||
assert!(on_demand_registered(&ar_ctx).is_empty(), "no installed Arabic system font is read when an embedded Arabic face covers Arabic");
|
||||
} else {
|
||||
paint(&ar_ctx, "مرحبا");
|
||||
let registered = on_demand_registered(&ar_ctx);
|
||||
let arabic_candidates = SystemCandidates.files("Arab", None);
|
||||
assert!(!registered.is_empty() || cfg!(not(any(target_os = "macos", windows))), "macOS and Windows ship an installed Arabic font");
|
||||
if !registered.is_empty() {
|
||||
assert_eq!(registered.len(), 1, "Arabic text registers one installed Arabic face");
|
||||
assert!(arabic_candidates.contains(®istered[0].1), "registered face {:?} came from Arabic system candidates", registered[0].1);
|
||||
assert!(ar_ctx.fonts_mut(|f| f.has_glyph(&egui::FontId::proportional(14.0), 'ع')), "installed Arabic system font draws Arabic text");
|
||||
}
|
||||
}
|
||||
|
||||
// CJK on-demand lookup through `ui_fonts` never asks for an Arabic system font (U+3400 is
|
||||
// CJK Extension A, outside embedded catalog subsets, so it exercises CJK on-demand lookup
|
||||
// even in builds with `CRAFT_FONTS_DIR`).
|
||||
let cjk_spy = RecordingCandidates::new();
|
||||
let cjk_ctx = egui::Context::default();
|
||||
ui_fonts(ja).on_demand(Arc::clone(&cjk_spy) as Arc<dyn FontCandidates>).install(&cjk_ctx);
|
||||
paint(&cjk_ctx, "日本語 㐀");
|
||||
let cjk_scripts = cjk_spy.scripts();
|
||||
assert!(!cjk_scripts.iter().any(|s| s == "Arab"), "CJK fallback never asks for an Arabic font: {cjk_scripts:?}");
|
||||
if !cjk_ctx.fonts_mut(|f| f.has_glyph(&egui::FontId::proportional(14.0), '\u{3400}')) || !on_demand_registered(&cjk_ctx).is_empty() {
|
||||
assert!(cjk_scripts.iter().any(|s| is_cjk_script(s)), "uncovered CJK text asks for CJK candidates: {cjk_scripts:?}");
|
||||
}
|
||||
|
||||
// Arabic on-demand lookup when no embedded Arabic face is present asks for Arabic alone
|
||||
// and never triggers a CJK system-font lookup.
|
||||
let ar_spy = RecordingCandidates::new();
|
||||
let ar_no_embed_ctx = egui::Context::default();
|
||||
if embedded_arabic.is_empty() {
|
||||
ui_fonts(ar).on_demand(Arc::clone(&ar_spy) as Arc<dyn FontCandidates>).install(&ar_no_embed_ctx);
|
||||
} else {
|
||||
UiFonts::new(&I18nScripts)
|
||||
.languages(&["en", "ja", "ar"])
|
||||
.ui_language(ar.code())
|
||||
.on_demand(Arc::clone(&ar_spy) as Arc<dyn FontCandidates>)
|
||||
.install(&ar_no_embed_ctx);
|
||||
}
|
||||
paint(&ar_no_embed_ctx, "مرحبا");
|
||||
let ar_scripts = ar_spy.scripts();
|
||||
assert!(ar_scripts.iter().any(|s| s == "Arab"), "Arabic text without an embedded Arabic face asks for Arab: {ar_scripts:?}");
|
||||
assert!(!ar_scripts.iter().any(|s| is_cjk_script(s)), "Arabic fallback never asks for a CJK font: {ar_scripts:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -81,6 +81,7 @@ impl WordApp {
|
||||
let mode = self.screen_mode();
|
||||
let dropped = self.ribbon_dropped;
|
||||
let key = self.windows.window_key();
|
||||
let ribbon_out = std::cell::RefCell::new(None);
|
||||
let shell = AppShell::new(key)
|
||||
.mode_set(ScreenModeSet::Document)
|
||||
.screen_mode(Bind::given(mode))
|
||||
@@ -94,12 +95,12 @@ impl WordApp {
|
||||
// tabs and collapsed every one of them.
|
||||
.top(Slot::new("ribbonDrop").drops().size(SlotSize::Content), |ui, _cx, app: &mut WordApp| {
|
||||
if !stale(app) {
|
||||
ribbon_slot(app, ui);
|
||||
*ribbon_out.borrow_mut() = Some(ribbon::show(app, ui));
|
||||
}
|
||||
})
|
||||
.top(Slot::new("ribbon").size(SlotSize::Content), |ui, _cx, app: &mut WordApp| {
|
||||
if !stale(app) {
|
||||
ribbon_slot(app, ui);
|
||||
*ribbon_out.borrow_mut() = Some(ribbon::show(app, ui));
|
||||
}
|
||||
})
|
||||
// As tall as the bar: a failure's line under the message puts Install below the first line, and a slot of
|
||||
@@ -132,6 +133,11 @@ impl WordApp {
|
||||
self.follow_screen_mode(out.screen_mode);
|
||||
}
|
||||
self.ribbon_dropped = out.dropped;
|
||||
// Keytips run outside the ribbon slots so legacy sequences and their hint still work when
|
||||
// no ribbon shows (Focus, Full Screen View) and anchor under the slim screen bar.
|
||||
let ribbon = ribbon_out.into_inner().unwrap_or_else(ribbon::no_ribbon);
|
||||
let screen_bar = out.regions.slots.iter().find(|(slot, _)| *slot == "screenBar").map(|(_, rect)| *rect);
|
||||
crate::keytips::show(ui, self, &ribbon, screen_bar);
|
||||
out.regions
|
||||
}
|
||||
|
||||
@@ -145,20 +151,22 @@ impl WordApp {
|
||||
// PLAN: assumed `updates_ui::run(app: &mut WordApp)` (shell-w13, sh.A20) opens the updater's dialogs on the host.
|
||||
updates_ui::run(self);
|
||||
crate::dialogs::host::prepare(self);
|
||||
let had_dialogs = !self.dialog_host.is_empty();
|
||||
self.dialog_host.run(ui);
|
||||
crate::dialogs::host::settle(self, ctx);
|
||||
crate::dialogs::chrome::apply_modal_nudge(self, ui);
|
||||
if moved(self) {
|
||||
return;
|
||||
}
|
||||
if had_dialogs && self.dialog_host.is_empty() && !self.file_dialog_open() && !self.ui.backstage {
|
||||
self.canvas.focus_page(ctx);
|
||||
self.canvas.focus_pending = true;
|
||||
self.canvas.focus_page_after_pass();
|
||||
ctx.request_repaint();
|
||||
}
|
||||
self.refocus_after_chrome_click(ctx, regions);
|
||||
if let Some(url) = self.canvas.open_url.take() {
|
||||
ctx.open_url(egui::OpenUrl::new_tab(url));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The ribbon, then its keytips, in a top slot: the keytips read what the ribbon recorded this pass.
|
||||
fn ribbon_slot(app: &mut WordApp, ui: &mut egui::Ui) {
|
||||
let out = ribbon::show(app, ui);
|
||||
crate::keytips::show(ui, app, &out);
|
||||
}
|
||||
|
||||
@@ -4,7 +4,8 @@
|
||||
use craft::ui::buttons::Button;
|
||||
use craft::ui::contract::{Bind, Props as _, Show as _, clicked};
|
||||
use craft::ui::shell::{RecentFile, RecentList, RecentSort, RecentView, StartAction, StartLayout, StartScreen, Template};
|
||||
use egui::Ui;
|
||||
use craft::ui::style::DataColor;
|
||||
use egui::{Color32, Ui};
|
||||
use serde_json::json;
|
||||
|
||||
use super::{HOME_TEMPLATES, TEMPLATES, TemplateThumbs, error_line, heading, label, open_recent, thumbs};
|
||||
@@ -77,7 +78,9 @@ pub(super) fn home(ui: &mut Ui, app: &mut WordApp) {
|
||||
let recent = recent_files(app);
|
||||
let cards = template_cards(&TEMPLATES[..HOME_TEMPLATES.min(TEMPLATES.len())]);
|
||||
let store = thumbs::store(&ctx);
|
||||
let source = TemplateThumbs { region: app.session.region() };
|
||||
let region = app.session.region();
|
||||
let (wide, high) = thumbs::page_aspect(®ion);
|
||||
let source = TemplateThumbs { region };
|
||||
let (mut view, mut sort) = (RecentView::List, RecentSort::Opened);
|
||||
let out = StartScreen::new(Bind::bound(&mut view), Bind::bound(&mut sort), &recent)
|
||||
.layout(StartLayout::Greeting)
|
||||
@@ -85,6 +88,9 @@ pub(super) fn home(ui: &mut Ui, app: &mut WordApp) {
|
||||
.templates(&cards)
|
||||
.more_templates(label("More templates →"))
|
||||
.max_recent(app.ui.recent_shown())
|
||||
.picture_aspect(wide, high)
|
||||
.card_zoom(1.0)
|
||||
.page_paper(DataColor::new(Color32::WHITE))
|
||||
.thumbnails(&store, &source)
|
||||
.show(ui);
|
||||
run_actions(app, &ctx, out.actions);
|
||||
@@ -112,12 +118,6 @@ pub(super) fn open(ui: &mut Ui, app: &mut WordApp) {
|
||||
error_line(ui, &error);
|
||||
}
|
||||
let recent = recent_files(app);
|
||||
let store = thumbs::store(&ctx);
|
||||
let source = TemplateThumbs { region: app.session.region() };
|
||||
let out = RecentList::new(&recent)
|
||||
.max_recent(app.ui.recent_shown())
|
||||
.empty(label("Documents you open will show up here."))
|
||||
.thumbnails(&store, &source)
|
||||
.show(ui);
|
||||
let out = RecentList::new(&recent).max_recent(app.ui.recent_shown()).empty(label("Documents you open will show up here.")).show(ui);
|
||||
run_actions(app, &ctx, out.actions);
|
||||
}
|
||||
|
||||
@@ -12,12 +12,13 @@ use craft::ui::contract::{
|
||||
use craft::ui::layout_components::Stack;
|
||||
use craft::ui::list::ThumbAspect;
|
||||
use craft::ui::notices::Notice;
|
||||
use craft::ui::primitives::IconSpec;
|
||||
use craft::ui::primitives::{ContentPainterCx, IconSpec};
|
||||
use craft::ui::runtime::env::Label;
|
||||
use craft::ui::shell::{Template, ThumbKey};
|
||||
use craft::ui::style::DataColor;
|
||||
use craft::ui::text::TextField;
|
||||
use craft::ui::tile_grid::{CaptionPlace, Tile, TileGrid};
|
||||
use egui::Ui;
|
||||
use egui::{Color32, Rect, Shape, Ui, vec2};
|
||||
use serde_json::json;
|
||||
|
||||
use super::home::template_cards;
|
||||
@@ -30,13 +31,13 @@ const PAGE_WIDE: u16 = 3;
|
||||
const PAGE_HIGH: u16 = 4;
|
||||
|
||||
/// A grid of template tiles, one per card, that reports the chosen key.
|
||||
fn grid(name: Label) -> TileGrid<'static, String> {
|
||||
fn grid(name: Label, wide: u16, high: u16) -> TileGrid<'static, String> {
|
||||
TileGrid::<String>::new(name)
|
||||
.select(SelectMode::Single)
|
||||
.activate(ActivateOn::Click)
|
||||
.caption(CaptionPlace::Below)
|
||||
.card()
|
||||
.aspect(f32::from(PAGE_WIDE) / f32::from(PAGE_HIGH))
|
||||
.aspect(f32::from(wide) / f32::from(high))
|
||||
.sizing(Sizing::FillWidth)
|
||||
.natural_height(true)
|
||||
}
|
||||
@@ -58,6 +59,14 @@ fn read_listing(app: &WordApp) -> PersonalListing {
|
||||
PersonalListing { key, folder, templates }
|
||||
}
|
||||
|
||||
/// Paints a personal template card thumbnail: a white page surface with a centered 44×44 pt
|
||||
/// `documentTemplate` icon (#7373).
|
||||
pub(super) fn paint_personal_card(cx: &ContentPainterCx, rect: Rect) {
|
||||
cx.data_shapes([Shape::rect_filled(rect, 2.0, Color32::WHITE)]);
|
||||
let icon_rect = Rect::from_center_size(rect.center(), vec2(44.0, 44.0));
|
||||
cx.icon(icon_rect, &IconSpec::svg(IconId::new("documentTemplate")).data_color(DataColor::new(Color32::from_gray(150))));
|
||||
}
|
||||
|
||||
/// New: the whole template gallery with a search box, then the personal templates (#2852); no
|
||||
/// Recent list (that is on Home and Open). The search covers both.
|
||||
///
|
||||
@@ -87,16 +96,18 @@ pub(super) fn show(ui: &mut Ui, app: &mut WordApp) {
|
||||
return;
|
||||
}
|
||||
let store = thumbs::store(&ctx);
|
||||
let source = thumbs::TemplateThumbs { region: app.session.region() };
|
||||
let region = app.session.region();
|
||||
let (wide, high) = thumbs::page_aspect(®ion);
|
||||
let source = thumbs::TemplateThumbs { region };
|
||||
if !found.is_empty() {
|
||||
let (store, source) = (&store, &source);
|
||||
let cards = template_cards(&found);
|
||||
let items = keyed(&cards, |t: &Template| t.id.clone()).with_text(|t| Cow::Borrowed(t.name.as_str()));
|
||||
let out = grid(label("Templates")).show_items(ui, &items, &mut |id, _| {
|
||||
let out = grid(label("Templates"), wide, high).show_items(ui, &items, &mut |id, _| {
|
||||
let Some(card) = cards.iter().find(|c| &c.id == id) else { return Tile::new(Label::Empty) };
|
||||
let thumb = ThumbKey::Template(card.id.clone());
|
||||
Tile::new(Label::from(card.name.clone()))
|
||||
.thumb(ThumbAspect::new(PAGE_WIDE, PAGE_HIGH), move |cx, rect| thumbs::paint(cx, rect, store, source, &thumb))
|
||||
.thumb(ThumbAspect::new(wide, high), move |cx, rect| thumbs::paint(cx, rect, store, source, &thumb))
|
||||
});
|
||||
for id in activated(out.response.events) {
|
||||
let _ = app.run("file.new", json!({"template": id}));
|
||||
@@ -131,9 +142,9 @@ pub(super) fn show(ui: &mut Ui, app: &mut WordApp) {
|
||||
let tiles: Vec<&PersonalTemplate> = personal_found.iter().filter(|p| p.category == category).collect();
|
||||
let items = keyed(&tiles, |p: &&PersonalTemplate| p.path.clone()).with_text(|p| Cow::Borrowed(p.label.as_str()));
|
||||
let name = if category.is_empty() { label("Personal templates") } else { Label::from(category.to_owned()) };
|
||||
let out = grid(name).id_salt(("personal-templates", category.to_owned())).show_items(ui, &items, &mut |path, _| {
|
||||
let out = grid(name, PAGE_WIDE, PAGE_HIGH).id_salt(("personal-templates", category.to_owned())).show_items(ui, &items, &mut |path, _| {
|
||||
let Some(p) = tiles.iter().find(|p| &p.path == path) else { return Tile::new(Label::Empty) };
|
||||
Tile::new(Label::from(p.label.clone())).icon(IconSpec::svg(IconId::new("documentTemplate"))).tooltip(p.path.clone())
|
||||
Tile::new(Label::from(p.label.clone())).thumb(ThumbAspect::new(PAGE_WIDE, PAGE_HIGH), paint_personal_card).tooltip(p.path.clone())
|
||||
});
|
||||
for path in activated(out.response.events) {
|
||||
let failed = open_personal(app, &path, &ctx).err();
|
||||
|
||||
@@ -353,6 +353,21 @@ fn new_lists_personal_templates_and_opens_one() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// #7373: Personal template cards in File › New paint a white page surface and document icon.
|
||||
#[test]
|
||||
fn personal_template_cards_render_as_page_cards() {
|
||||
let dir = personal_dir("card-paint");
|
||||
let memo = dir.join("Proposal.dotx");
|
||||
write_template(&memo, "Proposal template text");
|
||||
let h = new_page_harness(Some(dir.clone()));
|
||||
let card = h.query_by_label("Proposal");
|
||||
assert!(card.is_some(), "personal template tile exists");
|
||||
let rect = card.unwrap().rect();
|
||||
assert!(rect.height() > rect.width(), "personal template card is portrait oriented");
|
||||
drop(h);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// An empty (or not yet made) templates folder says where templates come from; no folder (the
|
||||
/// web) shows no Personal section. Home keeps only the built-ins.
|
||||
#[test]
|
||||
@@ -840,3 +855,40 @@ fn a_file_pages_title_is_productions_size() {
|
||||
assert!(title.size > section.size + 6.0, "the title stands above a section heading: {title:?} over {section:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The template cards on File › Home and File › New use the portrait aspect of the active region,
|
||||
/// and Home cards use card_zoom(1.0) so they do not stretch across the row (#7372, #7149 items 2-3).
|
||||
#[test]
|
||||
fn backstage_template_cards_aspect_and_zoom() {
|
||||
let mut letter_app = new_app();
|
||||
letter_app.session.system_region = wordcraft_geom::Region::from_tag("en-US");
|
||||
let (wide_us, high_us) = super::thumbs::page_aspect(&letter_app.session.region());
|
||||
assert_eq!((wide_us, high_us), (17, 22), "US region uses 17:22 (Letter) aspect");
|
||||
|
||||
let mut a4_app = new_app();
|
||||
a4_app.session.system_region = wordcraft_geom::Region::from_tag("en-GB");
|
||||
let (wide_gb, high_gb) = super::thumbs::page_aspect(&a4_app.session.region());
|
||||
assert_eq!((wide_gb, high_gb), (70, 99), "GB region uses 70:99 (A4) aspect");
|
||||
|
||||
// Home template cards: portrait and narrow (~150 pt wide, not stretched across the row)
|
||||
let h = file_page(new_app(), "home");
|
||||
let card = h.get_by_label("Blank document").rect();
|
||||
assert!(card.height() > card.width(), "Home template card is portrait: {card:?}");
|
||||
assert!(card.width() < 300.0, "card zoom keeps cards narrow instead of filling row: {card:?}");
|
||||
}
|
||||
|
||||
/// File › Open presents the recent list without thumbnail letterboxing (#7372).
|
||||
#[test]
|
||||
fn file_open_recent_list_has_no_thumbnail_letterboxing() {
|
||||
let app = new_app();
|
||||
let h = file_page(app, "open");
|
||||
assert!(h.query_by_label("Browse…").is_some(), "Browse button exists");
|
||||
assert!(h.query_all_by_label("Recent").next().is_some(), "Recent section exists");
|
||||
assert!(h.query_by_label("Documents you open will show up here.").is_some(), "empty state message exists");
|
||||
|
||||
let mut populated = new_app();
|
||||
populated.ui.recent = vec!["/tmp/sample.docx".into()];
|
||||
let h2 = file_page(populated, "open");
|
||||
let row = recent_row(&h2, "sample.docx").expect("recent row renders");
|
||||
assert!(row.rect().height() > 0.0, "recent row has non-zero height: {:?}", row.rect());
|
||||
}
|
||||
|
||||
@@ -1,11 +1,18 @@
|
||||
//! The template thumbnails of the File page: the first page of each built-in template, drawn in a
|
||||
//! throwaway session so the user's document is never touched.
|
||||
|
||||
use craft::ui::primitives::{ContentPainterCx, Priority, Revision, ThumbPaint, ThumbRender, ThumbRequest, ThumbSource, ThumbnailOptions, Thumbnails};
|
||||
use craft::ui::primitives::{
|
||||
ContentPainterCx, Priority, Revision, ThumbFit, ThumbPaint, ThumbRender, ThumbRequest, ThumbSource, ThumbnailOptions, Thumbnails,
|
||||
};
|
||||
use craft::ui::shell::ThumbKey;
|
||||
use craft::ui::style::{Corners, SurfaceKind};
|
||||
use craft::ui::style::{Corners, DataColor, SurfaceKind};
|
||||
use serde_json::json;
|
||||
|
||||
/// The shape of a document page in `region`, wide to high (Letter 17:22 or A4 70:99).
|
||||
pub(crate) fn page_aspect(region: &wordcraft_geom::Region) -> (u16, u16) {
|
||||
if region.uses_letter() { (17, 22) } else { (70, 99) }
|
||||
}
|
||||
|
||||
/// The salt every reader of the File page's thumbnails asks the store with, so New, Home and the
|
||||
/// recent rows share one loader and one set of pictures.
|
||||
const SALT: &str = "wordcraft.templates";
|
||||
@@ -20,7 +27,8 @@ pub(crate) fn store(ctx: &egui::Context) -> Thumbnails<ThumbKey> {
|
||||
pub(crate) fn paint(cx: &ContentPainterCx, rect: egui::Rect, store: &Thumbnails<ThumbKey>, source: &dyn ThumbSource<ThumbKey>, key: &ThumbKey) {
|
||||
let request = ThumbRequest::for_cell(rect.width().max(rect.height()), cx.pixels_per_point());
|
||||
let state = store.state(cx.painter.ctx(), source, key, &request, Priority::VISIBLE);
|
||||
if !store.paint(cx, rect, &state, &ThumbPaint::default()) {
|
||||
let paint = ThumbPaint::default().fit(ThumbFit::Cover).checker(false).paper(DataColor::new(egui::Color32::WHITE));
|
||||
if !store.paint(cx, rect, &state, &paint) {
|
||||
cx.surface(rect, SurfaceKind::Sunken, Corners::None);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ use std::sync::Arc;
|
||||
use craft::behavior::kurbo::{Point, Size};
|
||||
use craft::pages::layout::{Fit, LayoutOptions, PageDisplay, SCREEN_POINTS_PER_POINT};
|
||||
use craft::pages::ui::reading::{ReadingMetrics, reading_size};
|
||||
use craft::pages::ui::{MarkArea, MarkKind, PageBody, PageView, PageViewState, PlacedPage, ReadingNav, ReadingState, ReadingView, TextMarks};
|
||||
use craft::pages::ui::{GoTo, MarkArea, MarkKind, PageBody, PageView, PageViewState, PlacedPage, ReadingNav, ReadingState, ReadingView, TextMarks};
|
||||
use craft::ui::canvas::{Autoscroll, ContextSource, MiddleButton, NavigationOptions, ToolHost, ToolHostResponse, ToolPass, WheelScheme};
|
||||
use craft::ui::contract::Show as _;
|
||||
|
||||
@@ -156,6 +156,10 @@ pub struct CanvasState {
|
||||
pub(crate) read_force_reflow: bool,
|
||||
/// Web Layout's width follows the window once a drag has settled, not on every frame of it.
|
||||
web_viewport: reading::Settle,
|
||||
/// Side gutter the last `PageView` pass laid pages out with (`PageSpacing::side`), in screen points.
|
||||
pub(crate) page_side: Option<f32>,
|
||||
/// `PageView`'s side gutter changed since the last Web Layout pass, so Web Layout must reflow at once.
|
||||
web_force_reflow: bool,
|
||||
/// First text position on the column currently leading the reading view, captured from the last
|
||||
/// pass's layout. Survives changing page sizes, even when the caret stays elsewhere.
|
||||
pub(crate) read_first_visible: Option<Pos>,
|
||||
@@ -371,7 +375,7 @@ impl CanvasState {
|
||||
|
||||
/// The comment whose balloon is selected, as the document's comment id.
|
||||
pub fn selected_balloon(&self) -> Option<u32> {
|
||||
self.comments.selected.and_then(|id| u32::try_from(id.0).ok())
|
||||
self.comments.selected.lead.and_then(|id| u32::try_from(id.0).ok())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -405,6 +409,8 @@ impl Default for CanvasState {
|
||||
nav_to_caret: false,
|
||||
read_force_reflow: false,
|
||||
web_viewport: Default::default(),
|
||||
page_side: None,
|
||||
web_force_reflow: false,
|
||||
read_first_visible: None,
|
||||
dragging: false,
|
||||
column_drag: None,
|
||||
@@ -465,16 +471,19 @@ fn update_viewport(app: &mut WordApp, full: Rect, metrics: &ReadingMetrics, side
|
||||
// Without an anchor (Read Mode was just entered) the view starts at the caret.
|
||||
app.canvas.scroll_to_caret |= reflow_anchor.is_none();
|
||||
}
|
||||
app.canvas.web_force_reflow = false;
|
||||
} else {
|
||||
if app.session.view.mode == wordcraft_layout::ViewMode::Web {
|
||||
// Web Layout wraps to the work area (#1876).
|
||||
let scale = app.session.view.zoom.clamp(0.1, 5.0) * PX_PER_PT;
|
||||
// The page view keeps its side gutter (the rail width) clear on both sides of a page, so the page
|
||||
// The page view keeps its side gutter (`PageSpacing::side`) clear on both sides of a page, so the page
|
||||
// fits the window only when its width leaves that room.
|
||||
let w = web_layout_width((full.width() - 2.0 * side).max(0.0), scale);
|
||||
let changed = (app.session.view.web_width - w).abs() > 0.5;
|
||||
// At once on entry or a zoom (the viewport holds still), after a window drag has settled.
|
||||
if app.canvas.web_viewport.apply(full.size(), ctx.input(|i| i.time), changed, false) {
|
||||
let forced = std::mem::take(&mut app.canvas.web_force_reflow);
|
||||
// At once on entry, a zoom, or a page-spacing change (the viewport holds still), after a window drag
|
||||
// has settled.
|
||||
if app.canvas.web_viewport.apply(full.size(), ctx.input(|i| i.time), changed, forced) {
|
||||
app.session.view.web_width = w;
|
||||
// The pixel offset no longer points at the same text: keep the caret's line in view.
|
||||
app.canvas.scroll_to_caret = true;
|
||||
@@ -483,6 +492,7 @@ fn update_viewport(app: &mut WordApp, full: Rect, metrics: &ReadingMetrics, side
|
||||
}
|
||||
} else {
|
||||
app.canvas.web_viewport.leave();
|
||||
app.canvas.web_force_reflow = false;
|
||||
}
|
||||
app.canvas.read_force_reflow = false;
|
||||
app.canvas.read_first_visible = None;
|
||||
@@ -609,7 +619,7 @@ fn mark_areas(app: &mut WordApp, layout: &DocLayout, selected: &[(usize, wordcra
|
||||
fn navigation_options() -> NavigationOptions {
|
||||
let mut options = NavigationOptions::default();
|
||||
options.middle_button =
|
||||
if cfg!(any(target_os = "macos", target_os = "ios", target_arch = "wasm32")) { MiddleButton::Pan } else { MiddleButton::Autoscroll };
|
||||
if cfg!(any(target_os = "macos", target_os = "ios", target_arch = "wasm32")) { MiddleButton::Pan } else { MiddleButton::AutoScroll };
|
||||
options.wheel = WheelScheme::Document;
|
||||
options
|
||||
}
|
||||
@@ -732,7 +742,8 @@ fn show_reading(app: &mut WordApp, ui: &mut Ui, layout: &Arc<DocLayout>, full: R
|
||||
pub fn show(app: &mut WordApp, ui: &mut Ui) {
|
||||
let full = ui.available_rect_before_wrap();
|
||||
let Some(metrics) = reading_metrics::read(ui) else { return };
|
||||
let layout = prepare_layout(app, full, &metrics, Env::of(ui).tokens.size.rail.width, ui.ctx());
|
||||
let side = app.canvas.page_side.unwrap_or(0.0);
|
||||
let layout = prepare_layout(app, full, &metrics, side, ui.ctx());
|
||||
if app.session.view.read_mode {
|
||||
show_reading(app, ui, &layout, full, &metrics);
|
||||
} else {
|
||||
@@ -754,7 +765,7 @@ fn show_pages(app: &mut WordApp, ui: &mut Ui, layout: &Arc<DocLayout>, full: Rec
|
||||
if let Some(c) = c
|
||||
&& let Some(page) = layout.pages.get(c.page)
|
||||
{
|
||||
state.go_to = Some((c.page, f64::from(c.top / page.h.max(1.0))));
|
||||
state.go_to = Some(GoTo::Top { page: c.page, fraction: f64::from(c.top / page.h.max(1.0)) });
|
||||
state.current = c.page;
|
||||
}
|
||||
}
|
||||
@@ -864,13 +875,27 @@ fn show_pages(app: &mut WordApp, ui: &mut Ui, layout: &Arc<DocLayout>, full: Rec
|
||||
} else {
|
||||
screen_rects(&selected, body.pages)
|
||||
};
|
||||
app.canvas.mini_anchor = crate::mini_toolbar::visible_anchor(anchor_rects, body.view.rect);
|
||||
app.canvas.mini_anchor = crate::mini_toolbar::visible_anchor(anchor_rects, body.view.rect, crate::mini_toolbar::starts_rtl(app));
|
||||
// The bar is its own floating layer: shown after the host, it keeps its buttons' presses (S-L410).
|
||||
crate::mini_toolbar::show(app, ui, body);
|
||||
}
|
||||
});
|
||||
let caret = caret_after.or(caret);
|
||||
app.canvas.page_keys = source.into_keys();
|
||||
let side = out.spacing.side as f32;
|
||||
if side.is_finite() {
|
||||
let side = side.max(0.0);
|
||||
if app.canvas.page_side.is_none_or(|prev| (prev - side).abs() > 0.01) {
|
||||
app.canvas.page_side = Some(side);
|
||||
if app.session.view.mode == wordcraft_layout::ViewMode::Web {
|
||||
app.canvas.web_force_reflow = true;
|
||||
ui.ctx().request_discard("page view side gutter changed");
|
||||
if !ui.ctx().will_discard() {
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// This pass's own input changed the document under the pages it drew: run the pass again, so the frame that
|
||||
// delivers a key paints its text (production laid out and painted in the one pass) rather than the next frame.
|
||||
if ran && !Arc::ptr_eq(&laid_before, &app.session.layout()) {
|
||||
@@ -908,7 +933,7 @@ fn show_pages(app: &mut WordApp, ui: &mut Ui, layout: &Arc<DocLayout>, full: Rec
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
if let Some(go) = fix.go_to {
|
||||
state.go_to = Some(go);
|
||||
state.go_to = Some(GoTo::Top { page: go.0, fraction: go.1 });
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
// Dragging a selection past the view's edge scrolls on.
|
||||
@@ -920,7 +945,9 @@ fn show_pages(app: &mut WordApp, ui: &mut Ui, layout: &Arc<DocLayout>, full: Rec
|
||||
let per_unit = v.zoom.max(f64::EPSILON);
|
||||
let size = Size::new(out.layout.size.width / per_unit, out.layout.size.height / per_unit);
|
||||
if Autoscroll::scroll(&mut v, step, size).is_some() {
|
||||
out.adopt(&mut state, &v);
|
||||
// The view moved in document units; the state keeps screen points.
|
||||
state.offset.0 += (v.center.x - view.center.x) * view.zoom;
|
||||
state.offset.1 += (v.center.y - view.center.y) * view.zoom;
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
//! and its drafts are `CanvasState::comments`, the one copy the Comments pane shares.
|
||||
|
||||
use craft::review::ui::{BalloonItem, BalloonPlace, CommentBalloons, CommentEdit};
|
||||
use craft::review::{CommentAnchor, CommentMessage, CommentThread, ReviewStatus, Revision, RevisionKind, ThreadId};
|
||||
use craft::review::{CommentAnchor, CommentMessage, CommentThread, Revision, RevisionKind, ThreadId};
|
||||
|
||||
use super::geometry::{FLOAT_WIDTH, floating_comments, markup_width, shown_comment};
|
||||
use super::{Color32, CommentDisplay, DocLayout, Env, Pos, Pos2, StoryRef, Ui, WordApp, json};
|
||||
@@ -68,7 +68,8 @@ pub(crate) fn balloons(app: &mut WordApp, ui: &mut Ui, out: &craft::pages::ui::P
|
||||
/// Applies what a card reported through the commands the Comments pane uses.
|
||||
fn apply(app: &mut WordApp, cards: &[Card], edit: CommentEdit) {
|
||||
match edit {
|
||||
CommentEdit::Select(thread) => {
|
||||
CommentEdit::Select(threads) => {
|
||||
let Some(thread) = threads.first().copied() else { return };
|
||||
let Some(id) = app_id(thread) else { return };
|
||||
focus_balloon(app, id);
|
||||
let pos = cards.iter().find_map(|c| match &c.what {
|
||||
@@ -149,7 +150,7 @@ fn thread_of(app: &WordApp, id: u32, page: usize, anchor: Pos2, color: Color32)
|
||||
let c = app.session.doc.comments.get(&cid)?;
|
||||
let created = c.date_utc.as_deref().map(unix_seconds).filter(|t| *t > 0).unwrap_or_else(|| unix_seconds(&c.date));
|
||||
let text = app.session.doc.plain_text(StoryRef::Part(c.part)).trim().to_string();
|
||||
Some(CommentMessage { author: author_name(&c.author), created, modified: None, text, reactions: Vec::new(), read: true })
|
||||
Some(CommentMessage { author: author_name(&c.author), created, modified: None, text, reactions: Vec::new(), read: true, deletable: true })
|
||||
})
|
||||
.collect();
|
||||
Some(CommentThread {
|
||||
@@ -158,7 +159,8 @@ fn thread_of(app: &WordApp, id: u32, page: usize, anchor: Pos2, color: Color32)
|
||||
kind: None,
|
||||
color: Some([color.r(), color.g(), color.b()]),
|
||||
messages,
|
||||
status: ReviewStatus::None,
|
||||
statuses: Vec::new(),
|
||||
reply_statuses: Vec::new(),
|
||||
marked: false,
|
||||
locked: false,
|
||||
resolved: root.resolved,
|
||||
@@ -253,7 +255,7 @@ fn focus_balloon(app: &mut WordApp, id: u32) {
|
||||
let text = app.session.doc.comments.get(&id).filter(|_| editable).map(|c| app.session.doc.plain_text(StoryRef::Part(c.part)));
|
||||
let thread = thread_id(id);
|
||||
let comments = &mut app.canvas.comments;
|
||||
comments.selected = Some(thread);
|
||||
comments.selected = craft::behavior::Selection::single(thread);
|
||||
if comments.editing.as_ref().is_none_or(|(t, ..)| *t != thread) {
|
||||
comments.editing = text.map(|t| (thread, 0, t));
|
||||
}
|
||||
@@ -275,5 +277,5 @@ pub fn deselect_balloon(app: &mut WordApp) {
|
||||
// What was written is cleared by the write; a draft the document refused (read-only protection) stays, with its
|
||||
// reason on the status line, for when the balloon is selected again or the document is saved or closed (#1348).
|
||||
write_back(app, id);
|
||||
app.canvas.comments.selected = None;
|
||||
app.canvas.comments.selected = craft::behavior::Selection::default();
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ use craft::behavior::{Input, Metrics};
|
||||
use craft::pages::ui::{PageBody, PlacedPage};
|
||||
use craft::ui::canvas::ToolPass;
|
||||
use craft::ui::contract::{Access, Common, Component, Cx, MeasureCx, NoValue, Outcome, PaintUi, Props as _, Role, Show as _};
|
||||
use craft::ui::fonts::{FaceBytes, MAX_INTERFACE_FACE_BYTES};
|
||||
use craft::ui::fonts::FaceBytes;
|
||||
use craft::ui::primitives::{FaceRun, PaintShape, StrokeWidth, TextRun};
|
||||
use craft::ui::runtime::env::Label;
|
||||
use craft::ui::style::{ComponentStyle, DataColor, StyleColor, StyleCx};
|
||||
@@ -293,14 +293,10 @@ pub(crate) fn face_key(face: wordcraft_fonts::FaceRef) -> String {
|
||||
format!("wordcraft-face:{}", face.id())
|
||||
}
|
||||
|
||||
/// The bytes, index and variation setting of `face`, read the first time it is drawn. A file larger than the framework
|
||||
/// draws over the interface fonts is not copied: the composition stays in the interface font (a document's CJK
|
||||
/// fallback can be 19 MB).
|
||||
/// The bytes, index and variation setting of `face`, read the first time it is drawn. The framework's document-face
|
||||
/// registry keeps the faces within its byte budget.
|
||||
fn face_bytes(face: wordcraft_fonts::FaceRef) -> Option<FaceBytes> {
|
||||
let data = face.data();
|
||||
if data.len() > MAX_INTERFACE_FACE_BYTES {
|
||||
return None;
|
||||
}
|
||||
Some(FaceBytes::new(std::sync::Arc::from(data), face.index()).coords(face.coords.iter().copied()))
|
||||
}
|
||||
|
||||
|
||||
@@ -253,6 +253,24 @@ fn drawing_over_the_pages_follows_the_read_mode_page_color() {
|
||||
assert_eq!(blank(&a), Rgb::WHITE, "the paper under the raster, not the page color");
|
||||
}
|
||||
|
||||
/// #299: the caret's colour is worked out only when the caret is drawn: with text selected
|
||||
/// there is no caret, so the page's draw list isn't built for it.
|
||||
#[test]
|
||||
fn caret_colour_is_not_worked_out_while_the_caret_is_hidden() {
|
||||
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::from_text("Hello WordCraft")), Default::default());
|
||||
a.run("select.text", json!({"text": "Hello"})).unwrap();
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|
||||
|ui, app: &mut WordApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
a,
|
||||
);
|
||||
h.run_steps(4);
|
||||
assert!(h.state().canvas.caret_bg.is_none(), "no caret, no colour lookup");
|
||||
}
|
||||
|
||||
/// Show revisions in balloons: a document whose only revision is a deletion gets the markup
|
||||
/// area for its balloon; the other modes have nothing to show there, and neither does the view
|
||||
/// while the Comments pane is open.
|
||||
@@ -427,20 +445,20 @@ fn selection_bar_clicks_select_lines() {
|
||||
page_to_screen(h.state_mut(), c.page, 30.0, c.top + c.height * (li + 0.5)).expect("on screen")
|
||||
};
|
||||
let line_start = |h: &mut H, at: Pos2| {
|
||||
let placed = *h.state().canvas.shown.pages.iter().find(|p| p.rect.contains(at)).expect("page");
|
||||
let placed = h.state().canvas.shown.pages.iter().find(|p| p.rect.contains(at)).expect("page").clone();
|
||||
let p = placed.to_page(at);
|
||||
let layout = h.state_mut().session.layout();
|
||||
layout.selection_bar_at(placed.page, p.x as f32, p.y as f32).expect("in the selection bar")
|
||||
};
|
||||
let span = |h: &mut H, pos: &Pos| h.state_mut().session.layout().line_span(pos, 0).expect("line");
|
||||
let button = |at: Pos2, pressed: bool| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() };
|
||||
let clicks_drag = |h: &mut H, from: Pos2, to: Pos2, clicks: usize| {
|
||||
let button = |at: Pos2, pressed: bool, modifiers: Modifiers| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers };
|
||||
let clicks_drag = |h: &mut H, from: Pos2, to: Pos2, clicks: usize, mods: Modifiers| {
|
||||
h.event(Event::PointerMoved(from));
|
||||
for i in 0..clicks {
|
||||
h.event(button(from, true));
|
||||
h.event(button(from, true, mods));
|
||||
h.app_frame();
|
||||
if i + 1 < clicks {
|
||||
h.event(button(from, false));
|
||||
h.event(button(from, false, mods));
|
||||
h.app_frame();
|
||||
}
|
||||
}
|
||||
@@ -448,7 +466,7 @@ fn selection_bar_clicks_select_lines() {
|
||||
h.event(Event::PointerMoved(from + (to - from) * (k as f32 / 4.0)));
|
||||
h.app_frame();
|
||||
}
|
||||
h.event(button(to, false));
|
||||
h.event(button(to, false, mods));
|
||||
for _ in 0..3 {
|
||||
h.app_frame();
|
||||
}
|
||||
@@ -462,22 +480,22 @@ fn selection_bar_clicks_select_lines() {
|
||||
let at = margin(&mut h, Pos::body(0, 0), 1.0);
|
||||
let l2 = line_start(&mut h, at);
|
||||
assert!(l2.off > 0 && l2.path == wordcraft_doc::Path::top(0));
|
||||
clicks_drag(&mut h, at, at, 1);
|
||||
clicks_drag(&mut h, at, at, 1, Modifiers::NONE);
|
||||
let (_, l2_end, _) = span(&mut h, &l2);
|
||||
assert_eq!(h.state().session.sel.ordered(), (l2.clone(), l2_end.clone()), "the line");
|
||||
// Double-click: the paragraph, mark included.
|
||||
pause(&mut h);
|
||||
clicks_drag(&mut h, at, at, 2);
|
||||
clicks_drag(&mut h, at, at, 2, Modifiers::NONE);
|
||||
assert_eq!(h.state().session.sel.ordered(), (Pos::body(0, 0), Pos::body(1, 0)), "the paragraph");
|
||||
// Triple-click: the whole document.
|
||||
pause(&mut h);
|
||||
clicks_drag(&mut h, at, at, 3);
|
||||
clicks_drag(&mut h, at, at, 3, Modifiers::NONE);
|
||||
assert_eq!(h.state().session.sel.ordered(), (Pos::body(0, 0), Pos::body(2, 10)), "everything");
|
||||
// Drag from beside the first line down past the third: three whole lines.
|
||||
pause(&mut h);
|
||||
let (from, to) = (margin(&mut h, Pos::body(0, 0), 0.0), margin(&mut h, Pos::body(0, 0), 2.0));
|
||||
let l3 = line_start(&mut h, to);
|
||||
clicks_drag(&mut h, from, to, 1);
|
||||
clicks_drag(&mut h, from, to, 1, Modifiers::NONE);
|
||||
let (_, l3_end, _) = span(&mut h, &l3);
|
||||
let sel = h.state().session.sel.clone();
|
||||
assert_eq!((sel.anchor, sel.focus), (Pos::body(0, 0), l3_end), "three lines");
|
||||
@@ -486,7 +504,7 @@ fn selection_bar_clicks_select_lines() {
|
||||
let second = margin(&mut h, Pos::body(1, 0), 0.0);
|
||||
h.event(Event::ModifiersChanged(Modifiers::SHIFT));
|
||||
h.app_frame();
|
||||
clicks_drag(&mut h, second, second, 1);
|
||||
clicks_drag(&mut h, second, second, 1, Modifiers::SHIFT);
|
||||
h.event(Event::ModifiersChanged(Modifiers::default()));
|
||||
h.app_frame();
|
||||
let sel = h.state().session.sel.clone();
|
||||
@@ -1227,15 +1245,14 @@ fn a_cjk_composition_uses_the_cjk_ui_font() {
|
||||
assert_eq!(row.glyphs.len(), 3, "one glyph per composed kana");
|
||||
let family = composition_font(&drawn).map(|f| f.family).expect("a font");
|
||||
assert_eq!(family, egui::FontFamily::Name(format!("face+ui:{}", super::caret::face_key(run.requested_face)).into()), "in the text's face");
|
||||
let (chain, interface) = h.ctx.fonts(|f| {
|
||||
let families = &f.definitions().families;
|
||||
(families.get(&family).cloned().unwrap_or_default(), families.get(&egui::FontFamily::Proportional).cloned().unwrap_or_default())
|
||||
});
|
||||
// The framework serves the face with the interface fonts behind it; what the face lacks is drawn from them, so each
|
||||
// kana has a full-width glyph (a missing one would be a narrow box or nothing).
|
||||
let size = composition_font(&drawn).map(|f| f.size).expect("a size");
|
||||
assert!(
|
||||
!interface.is_empty() && interface.iter().all(|f| chain.contains(f)),
|
||||
"the face's chain goes on with the interface fonts: {chain:?} {interface:?}"
|
||||
row.glyphs.iter().all(|g| g.advance_width >= size * 0.8),
|
||||
"the kana come from the interface fonts: {:?}",
|
||||
row.glyphs.iter().map(|g| g.advance_width).collect::<Vec<_>>()
|
||||
);
|
||||
assert_eq!(chain.len(), interface.len() + 1, "and no other document face is borrowed: {chain:?}");
|
||||
}
|
||||
|
||||
/// The composition is drawn in the font and size of the text it goes into, as Word draws it, its
|
||||
|
||||
@@ -259,7 +259,7 @@ fn comment_harness() -> (H, u32) {
|
||||
/// Click comment `id`'s balloon (from no selected balloon): the card is selected and its own
|
||||
/// edit has the keyboard in its field.
|
||||
fn click_balloon(h: &mut H, id: u32) {
|
||||
h.state_mut().canvas.comments.selected = None;
|
||||
h.state_mut().canvas.comments.selected = craft::behavior::Selection::default();
|
||||
steps(h, 2);
|
||||
let card = h.state().canvas.balloon_rects.iter().find(|(i, _)| *i == id).map(|(_, r)| *r).expect("the comment has a balloon");
|
||||
click_at(h, card.left_top() + vec2(30.0, 8.0));
|
||||
|
||||
@@ -260,6 +260,19 @@ fn table_gridlines_skip_edges_a_border_draws() {
|
||||
);
|
||||
}
|
||||
|
||||
/// #5967: a new table has borders on every edge, so it shows no gridline at all; with its
|
||||
/// borders removed every edge shows one.
|
||||
#[test]
|
||||
fn a_bordered_table_shows_no_gridlines() {
|
||||
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
|
||||
a.run("insert.table", json!({"rows": 2, "cols": 3})).unwrap();
|
||||
assert!(a.session.view.table_gridlines, "View Gridlines is on by default");
|
||||
let segs = |a: &mut WordApp| gridline_segments(&a.session.layout().pages[0], true, None).len();
|
||||
assert_eq!(segs(&mut a), 0);
|
||||
a.run("table.borders", json!({"kind": "none"})).unwrap();
|
||||
assert_eq!(segs(&mut a), 6 * 4, "every edge of the six cells");
|
||||
}
|
||||
|
||||
/// The drawing grid the page shows starts at the text area's top left, stays inside it, spaces
|
||||
/// its lines by the settings the same both ways or differently across and down, and falls back
|
||||
/// to the spec's 1/8 inch for a missing spacing.
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
use craft::behavior::IconId;
|
||||
use craft::ui::buttons::IconButton;
|
||||
use craft::ui::contract::{BodyCx, Props as _, Show as _, TooltipSpec};
|
||||
use craft::ui::runtime::inspect;
|
||||
use egui::Ui;
|
||||
use serde_json::json;
|
||||
|
||||
@@ -11,9 +10,9 @@ use super::Screen;
|
||||
use crate::WordApp;
|
||||
|
||||
/// Fills the screen-bar slot. Focus: a `more` button that drops the ribbon down over the page. Immersive: the
|
||||
/// command search field. The bar is an inspected region, where the keytips hang their hint while no ribbon shows.
|
||||
/// command search field.
|
||||
pub(crate) fn show(ui: &mut Ui, _cx: &mut BodyCx<'_>, app: &mut WordApp) {
|
||||
inspect::record(ui, crate::keytips::screen_bar_region(), |ui| match Screen::of(&app.session.view) {
|
||||
match Screen::of(&app.session.view) {
|
||||
Screen::Focus => {
|
||||
let out = IconButton::new(IconId::new("wordcraft.more"))
|
||||
.label(tl!("Show the ribbon").to_string())
|
||||
@@ -27,5 +26,5 @@ pub(crate) fn show(ui: &mut Ui, _cx: &mut BodyCx<'_>, app: &mut WordApp) {
|
||||
_ => {
|
||||
super::search::show(app, ui, false);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,11 +5,13 @@ use std::cell::RefCell;
|
||||
|
||||
use craft::behavior::IconId;
|
||||
use craft::keymap::CommandRef;
|
||||
use craft::theme::ControlSize;
|
||||
use craft::theme::variant::Variant;
|
||||
use craft::ui::bars::{Bar, BarKind};
|
||||
use craft::ui::buttons::{Button, ButtonOutput, IconButton, ToggleButton};
|
||||
use craft::ui::contract::{Bind, BodyCx, Props as _, Show as _, ShowContainer as _, TooltipSpec, Trigger};
|
||||
use craft::ui::contract::{Bind, BodyCx, Gap, Props as _, Show as _, ShowContainer as _, TooltipSpec, Trigger};
|
||||
use craft::ui::display::{Divider, Text};
|
||||
use craft::ui::layout_components::Row;
|
||||
use craft::ui::menu::{Menu, MenuItem};
|
||||
use craft::ui::value_drag::{Slider, SliderScale};
|
||||
use egui::Ui;
|
||||
@@ -209,85 +211,92 @@ fn missing_fonts(app: &mut WordApp, ui: &mut Ui) {
|
||||
fn controls(app: &mut WordApp, ui: &mut Ui, fit: usize) -> Option<egui::Rect> {
|
||||
use craft::ui::contract::Outcome as _;
|
||||
let mut rects = Vec::new();
|
||||
let focus = if fit >= 2 {
|
||||
IconButton::command(IconId::new("focus"), CommandRef::new("view.focus")).label(tl!("Focus").to_string()).show(ui).response
|
||||
} else {
|
||||
Button::command(CommandRef::new("view.focus"))
|
||||
.label(tl!("Focus").to_string())
|
||||
.icon(IconId::new("focus"))
|
||||
.variant(Variant::GHOST)
|
||||
.show(ui)
|
||||
.response
|
||||
};
|
||||
rects.push(focus.rect);
|
||||
// Icons only, Read Mode first and Web Layout last, each named in its tooltip, the current view on (prod
|
||||
// `chrome.rs:925-943`).
|
||||
let (mode, read) = (app.session.view.mode, app.session.view.read_mode);
|
||||
for (id, icon, name, on) in [
|
||||
("view.readMode", "readMode", tl!("Read Mode"), read),
|
||||
("view.printLayout", "printLayout", tl!("Print Layout"), mode == wordcraft_layout::ViewMode::Print && !read),
|
||||
("view.webLayout", "webLayout", tl!("Web Layout"), mode == wordcraft_layout::ViewMode::Web),
|
||||
] {
|
||||
// No command carries a checked state, so the view is given at the button (S-L415).
|
||||
let out = ToggleButton::new(name.to_string(), Bind::given(on))
|
||||
.command(CommandRef::new(id))
|
||||
.icon(crate::icons::id(icon))
|
||||
.icon_only()
|
||||
.tooltip(TooltipSpec::new(name.to_string()))
|
||||
.show(ui);
|
||||
rects.push(out.response().rect);
|
||||
}
|
||||
let reading = app.session.view.read_mode;
|
||||
// Reading zoom changes only reading presentation, never the normal view zoom.
|
||||
let current = if reading { f64::from(app.session.view.read_zoom) } else { app.canvas.zoom() };
|
||||
let percent = (current * 100.0).round();
|
||||
let step = |app: &mut WordApp, plus: bool| {
|
||||
if reading {
|
||||
let value = if plus { (percent + 10.0).min(150.0) } else { (percent - 10.0).max(75.0) };
|
||||
let _ = app.run("view.readTextSize", json!({"value": value}));
|
||||
let _ = Row::new().gap(Gap::Section).show(ui, |ui, _| {
|
||||
let focus = if fit >= 2 {
|
||||
IconButton::command(IconId::new("focus"), CommandRef::new("view.focus")).label(tl!("Focus").to_string()).show(ui).response
|
||||
} else {
|
||||
let _ = app.run(if plus { "view.zoomIn" } else { "view.zoomOut" }, json!({}));
|
||||
}
|
||||
};
|
||||
let out = IconButton::new(IconId::new("wordcraft.minus"))
|
||||
.label(tl!("Zoom Out").to_string())
|
||||
.tooltip(TooltipSpec::new(tl!("Zoom Out").to_string()))
|
||||
.show(ui);
|
||||
rects.push(out.response.rect);
|
||||
if out.response.clicked() {
|
||||
step(app, false);
|
||||
}
|
||||
if fit < 1 {
|
||||
let mut value = current;
|
||||
let range = if reading { 0.75..=1.5 } else { 0.1..=5.0 };
|
||||
let name = if reading { tl!("Text Size") } else { tl!("Zoom") };
|
||||
let slider = Slider::new(Bind::bound(&mut value), range)
|
||||
.scale(if reading { SliderScale::Linear } else { SliderScale::Log })
|
||||
// A plain rail, as the old zoom slider's (prod `chrome.rs:911`): no fill up to the thumb.
|
||||
.fill(false)
|
||||
.label(name.to_string())
|
||||
.show(ui);
|
||||
rects.push(slider.response().rect);
|
||||
if let Some(v) = slider.value() {
|
||||
let command = if reading { "view.readTextSize" } else { "view.zoom" };
|
||||
let _ = app.run(command, json!({"value": (*v * 100.0).round()}));
|
||||
}
|
||||
}
|
||||
let out = IconButton::new(IconId::new("wordcraft.plus"))
|
||||
.label(tl!("Zoom In").to_string())
|
||||
.tooltip(TooltipSpec::new(tl!("Zoom In").to_string()))
|
||||
.show(ui);
|
||||
rects.push(out.response.rect);
|
||||
if out.response.clicked() {
|
||||
step(app, true);
|
||||
}
|
||||
if !reading {
|
||||
// PLAN: assumed Button::room_for (ribbon-w2, S-L418)
|
||||
let out = Button::new(format!("{percent}%")).variant(Variant::GHOST).room_for(format!("{MOST_ZOOM_PERCENT}%")).show(ui);
|
||||
rects.push(out.response.rect);
|
||||
if out.clicked() {
|
||||
let _ = app.run("ui.dialog", json!({"name": "zoom"}));
|
||||
}
|
||||
}
|
||||
Button::command(CommandRef::new("view.focus"))
|
||||
.label(tl!("Focus").to_string())
|
||||
.icon(IconId::new("focus"))
|
||||
.variant(Variant::GHOST)
|
||||
.show(ui)
|
||||
.response
|
||||
};
|
||||
rects.push(focus.rect);
|
||||
// Icons only, Read Mode first and Web Layout last, each named in its tooltip, the current view on (prod
|
||||
// `chrome.rs:925-943`).
|
||||
let _ = Row::new().gap(Gap::Item).show(ui, |ui, _| {
|
||||
let (mode, read) = (app.session.view.mode, app.session.view.read_mode);
|
||||
for (id, icon, name, on) in [
|
||||
("view.readMode", "readMode", tl!("Read Mode"), read),
|
||||
("view.printLayout", "printLayout", tl!("Print Layout"), mode == wordcraft_layout::ViewMode::Print && !read),
|
||||
("view.webLayout", "webLayout", tl!("Web Layout"), mode == wordcraft_layout::ViewMode::Web),
|
||||
] {
|
||||
// No command carries a checked state, so the view is given at the button (S-L415).
|
||||
let out = ToggleButton::new(name.to_string(), Bind::given(on))
|
||||
.command(CommandRef::new(id))
|
||||
.icon(crate::icons::id(icon))
|
||||
.icon_only()
|
||||
.tooltip(TooltipSpec::new(name.to_string()))
|
||||
.show(ui);
|
||||
rects.push(out.response().rect);
|
||||
}
|
||||
});
|
||||
let reading = app.session.view.read_mode;
|
||||
// Reading zoom changes only reading presentation, never the normal view zoom.
|
||||
let current = if reading { f64::from(app.session.view.read_zoom) } else { app.canvas.zoom() };
|
||||
let percent = (current * 100.0).round();
|
||||
let step = |app: &mut WordApp, plus: bool| {
|
||||
if reading {
|
||||
let value = if plus { (percent + 10.0).min(150.0) } else { (percent - 10.0).max(75.0) };
|
||||
let _ = app.run("view.readTextSize", json!({"value": value}));
|
||||
} else {
|
||||
let _ = app.run(if plus { "view.zoomIn" } else { "view.zoomOut" }, json!({}));
|
||||
}
|
||||
};
|
||||
let _ = Row::new().show(ui, |ui, _| {
|
||||
let out = IconButton::new(IconId::new("wordcraft.minus"))
|
||||
.label(tl!("Zoom Out").to_string())
|
||||
.tooltip(TooltipSpec::new(tl!("Zoom Out").to_string()))
|
||||
.show(ui);
|
||||
rects.push(out.response.rect);
|
||||
if out.response.clicked() {
|
||||
step(app, false);
|
||||
}
|
||||
if fit < 1 {
|
||||
let mut value = current;
|
||||
let range = if reading { 0.75..=1.5 } else { 0.1..=5.0 };
|
||||
let name = if reading { tl!("Text Size") } else { tl!("Zoom") };
|
||||
let slider = Slider::new(Bind::bound(&mut value), range)
|
||||
.size(ControlSize::Md)
|
||||
.scale(if reading { SliderScale::Linear } else { SliderScale::Log })
|
||||
// A plain rail, as the old zoom slider's (prod `chrome.rs:911`): no fill up to the thumb.
|
||||
.fill(false)
|
||||
.label(name.to_string())
|
||||
.show(ui);
|
||||
rects.push(slider.response().rect);
|
||||
if let Some(v) = slider.value() {
|
||||
let command = if reading { "view.readTextSize" } else { "view.zoom" };
|
||||
let _ = app.run(command, json!({"value": (*v * 100.0).round()}));
|
||||
}
|
||||
}
|
||||
let out = IconButton::new(IconId::new("wordcraft.plus"))
|
||||
.label(tl!("Zoom In").to_string())
|
||||
.tooltip(TooltipSpec::new(tl!("Zoom In").to_string()))
|
||||
.show(ui);
|
||||
rects.push(out.response.rect);
|
||||
if out.response.clicked() {
|
||||
step(app, true);
|
||||
}
|
||||
if !reading {
|
||||
// PLAN: assumed Button::room_for (ribbon-w2, S-L418)
|
||||
let out = Button::new(format!("{percent}%")).variant(Variant::GHOST).room_for(format!("{MOST_ZOOM_PERCENT}%")).show(ui);
|
||||
rects.push(out.response.rect);
|
||||
if out.clicked() {
|
||||
let _ = app.run("ui.dialog", json!({"name": "zoom"}));
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
super::union(rects)
|
||||
}
|
||||
|
||||
@@ -76,6 +76,34 @@ fn new_app() -> WordApp {
|
||||
WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), crate::Services::default())
|
||||
}
|
||||
|
||||
/// A saved .docx (so AutoSave can cover it) in the harness.
|
||||
fn autosave_harness() -> (egui_kittest::Harness<'static, WordApp>, std::path::PathBuf) {
|
||||
let dir = std::env::temp_dir().join(format!("wordcraft-ui-autosave-label-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("draft.docx");
|
||||
let mut a = new_app();
|
||||
a.run("text.insert", json!({"text": "Hello"})).unwrap();
|
||||
a.run("file.save", json!({"path": path.to_string_lossy()})).unwrap();
|
||||
assert!(a.autosaves(), "a saved .docx is covered by AutoSave");
|
||||
let h = harness(a);
|
||||
(h, dir)
|
||||
}
|
||||
|
||||
/// #3370: clicking the AutoSave switch label toggles AutoSave on and off.
|
||||
#[test]
|
||||
fn clicking_the_autosave_label_toggles_autosave() {
|
||||
let (mut h, dir) = autosave_harness();
|
||||
assert!(h.state().autosaves());
|
||||
h.get_by_label("AutoSave").click();
|
||||
crate::test_harness::frames(&mut h, 2);
|
||||
assert!(!h.state().autosaves(), "clicking the text turns AutoSave off");
|
||||
h.get_by_label("AutoSave").click();
|
||||
crate::test_harness::frames(&mut h, 2);
|
||||
assert!(h.state().autosaves(), "and clicking it again turns it back on");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// #701: the arrow beside Undo lists the session's undo steps, newest first; clicking the third
|
||||
/// row undoes three steps at once.
|
||||
#[test]
|
||||
@@ -103,6 +131,39 @@ fn undo_list_matches_the_session_and_undoes_up_to_the_clicked_row() {
|
||||
assert_eq!(h.query_all_by_role(Role::ListBoxOption).count(), 0, "the list closes");
|
||||
}
|
||||
|
||||
/// #3040: clicking a row in the Undo History popover undoes the step and returns keyboard focus
|
||||
/// to the document so typing continues immediately.
|
||||
#[test]
|
||||
fn undo_list_row_returns_focus_to_the_document() {
|
||||
use egui::accesskit::Role;
|
||||
let mut a = new_app();
|
||||
a.run("text.insert", json!({"text": "Hello"})).unwrap();
|
||||
assert_eq!(a.session.undo_history().len(), 1);
|
||||
|
||||
let mut h = harness(a);
|
||||
assert!(h.state().canvas.focused(&h.ctx), "canvas starts focused");
|
||||
|
||||
let arrow = h.get_by_label("Undo History").rect().center();
|
||||
click_at(&mut h, arrow, egui::PointerButton::Primary);
|
||||
assert_eq!(h.query_all_by_role(Role::ListBoxOption).count(), 1, "the arrow opens the Undo list");
|
||||
assert!(!h.state().canvas.focused(&h.ctx), "the open Undo list holds the keyboard");
|
||||
|
||||
let row = h.get_by_role_and_label(Role::ListBoxOption, "Typing").rect().center();
|
||||
click_at(&mut h, row, egui::PointerButton::Primary);
|
||||
assert_eq!(h.query_all_by_role(Role::ListBoxOption).count(), 0, "picking a row closes the Undo list");
|
||||
assert!(h.state().session.undo_history().is_empty(), "the step was undone");
|
||||
assert_eq!(h.state().session.doc.plain_text(wordcraft_doc::StoryRef::Body), "", "the undone text is gone");
|
||||
assert!(h.state().canvas.focused(&h.ctx), "the row click returns focus to the document");
|
||||
|
||||
h.event(egui::Event::Text("!".into()));
|
||||
crate::test_harness::frames(&mut h, 2);
|
||||
assert_eq!(
|
||||
h.state().session.doc.plain_text(wordcraft_doc::StoryRef::Body),
|
||||
"!",
|
||||
"typing reaches the document immediately after picking an Undo list row"
|
||||
);
|
||||
}
|
||||
|
||||
/// #1975: the zoom percentage gains and loses digits (9% → 100% → 500%); the controls to its
|
||||
/// left must not shift with it.
|
||||
#[test]
|
||||
@@ -436,3 +497,376 @@ fn status_bar_texts_stop_before_the_controls_in_a_narrow_window() {
|
||||
let focus = wide.get_by_role_and_label(egui::accesskit::Role::Button, "Focus").rect();
|
||||
assert!(painted_on_row_of(&wide, focus).iter().any(|(t, _)| t == "Track Changes: On"), "a wide window shows everything");
|
||||
}
|
||||
|
||||
/// Finds the painted track and knob rects inside a rendered `craft::ui::choice::Switch`.
|
||||
/// `Switch` sets `PARTS = false` and exposes only its `Role::Switch` node and toggled state, so
|
||||
/// the thumb position is read from the unblurred filled shapes painted inside the switch rect.
|
||||
fn switch_track_and_knob(shapes: &[egui::epaint::ClippedShape], switch_rect: egui::Rect) -> (egui::Rect, egui::Rect) {
|
||||
fn filled_rects(shape: &egui::Shape, inside: egui::Rect, out: &mut Vec<egui::Rect>) {
|
||||
match shape {
|
||||
egui::Shape::Vec(children) => children.iter().for_each(|c| filled_rects(c, inside, out)),
|
||||
egui::Shape::Rect(r) if r.blur_width == 0.0 && r.fill != egui::Color32::TRANSPARENT && inside.contains_rect(r.rect) => {
|
||||
out.push(r.rect);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut rects = Vec::new();
|
||||
for clipped in shapes {
|
||||
filled_rects(&clipped.shape, switch_rect.expand(1.0), &mut rects);
|
||||
}
|
||||
let track = rects
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|r| r.width() > r.height())
|
||||
.max_by(|a, b| a.area().total_cmp(&b.area()))
|
||||
.unwrap_or_else(|| panic!("expected painted switch track inside {switch_rect:?}: {rects:?}"));
|
||||
let knob = rects
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|r| track.contains_rect(*r) && r.width() < track.width())
|
||||
.max_by(|a, b| a.area().total_cmp(&b.area()))
|
||||
.unwrap_or_else(|| panic!("expected painted switch knob inside track {track:?}: {rects:?}"));
|
||||
(track, knob)
|
||||
}
|
||||
|
||||
/// The AutoSave switch renders its knob on the right when on and on the left when off in a
|
||||
/// left-to-right interface, and mirrors through `WordApp::root_env()` for an Arabic interface.
|
||||
#[test]
|
||||
fn the_autosave_knob_sits_right_when_on_and_mirrors_right_to_left() {
|
||||
use craft::i18n::Direction;
|
||||
use egui::accesskit::{Role, Toggled};
|
||||
|
||||
struct ResetLang;
|
||||
impl Drop for ResetLang {
|
||||
fn drop(&mut self) {
|
||||
crate::i18n::apply_language(crate::i18n::Lang::EN);
|
||||
}
|
||||
}
|
||||
let _reset = ResetLang;
|
||||
|
||||
let mut a = new_app();
|
||||
a.ui.animations = crate::theme::Animations::Off;
|
||||
a.ui.language = "en".into();
|
||||
// Mark the document as saved here without touching disk (`session.dirty` stays false).
|
||||
let path = std::path::PathBuf::from("draft.docx");
|
||||
a.session.path = Some(path.clone());
|
||||
a.autosave_path = Some(path);
|
||||
|
||||
let mut h = harness(a);
|
||||
// Arabic UI labels draw even when built without `CRAFT_FONTS_DIR` (embedded Arabic faces).
|
||||
h.ctx.set_missing_glyph_policy(egui::MissingGlyphPolicy::Tofu);
|
||||
let mut measure = |lang: crate::i18n::Lang, on: bool| -> (egui::Rect, egui::Rect) {
|
||||
h.state_mut().run("ui.language", json!({"value": lang.code()})).unwrap();
|
||||
h.state_mut().run("file.autosave", json!({"value": on})).unwrap();
|
||||
let want_dir = if lang.rtl() { Direction::Rtl } else { Direction::Ltr };
|
||||
assert_eq!(h.state().root_env().direction, want_dir, "root_env supplies direction for {}", lang.code());
|
||||
assert_eq!(h.state().autosaves(), on);
|
||||
crate::test_harness::frames(&mut h, 4);
|
||||
|
||||
let label = crate::i18n::tr(lang, "AutoSave");
|
||||
let node = h.get_by_role_and_label(Role::Switch, label);
|
||||
assert_eq!(node.accesskit_node().toggled(), Some(if on { Toggled::True } else { Toggled::False }));
|
||||
switch_track_and_knob(&h.output().shapes, node.rect())
|
||||
};
|
||||
|
||||
let (ltr_on_track, ltr_on_knob) = measure(crate::i18n::Lang::EN, true);
|
||||
let (ltr_off_track, ltr_off_knob) = measure(crate::i18n::Lang::EN, false);
|
||||
assert!(ltr_on_knob.center().x > ltr_on_track.center().x, "left to right, on: knob sits right ({ltr_on_knob:?} in {ltr_on_track:?})");
|
||||
assert!(ltr_off_knob.center().x < ltr_off_track.center().x, "left to right, off: knob sits left ({ltr_off_knob:?} in {ltr_off_track:?})");
|
||||
|
||||
let Some(ar) = crate::i18n::Lang::from_code("ar") else {
|
||||
eprintln!("skipped RTL check: built without the craft-i18n Arabic catalog (set CRAFT_I18N_DIR to a checkout)");
|
||||
return;
|
||||
};
|
||||
let (rtl_on_track, rtl_on_knob) = measure(ar, true);
|
||||
let (rtl_off_track, rtl_off_knob) = measure(ar, false);
|
||||
assert!(rtl_on_knob.center().x < rtl_on_track.center().x, "right to left, on: knob sits left ({rtl_on_knob:?} in {rtl_on_track:?})");
|
||||
assert!(rtl_off_knob.center().x > rtl_off_track.center().x, "right to left, off: knob sits right ({rtl_off_knob:?} in {rtl_off_track:?})");
|
||||
assert!(rtl_on_track.center().x > ltr_on_track.center().x, "right to left mirrors the AutoSave switch toward the start (right) edge");
|
||||
assert!(((ltr_on_knob.center().x - ltr_on_track.min.x) - (rtl_on_track.max.x - rtl_on_knob.center().x)).abs() <= 0.5);
|
||||
assert!(((ltr_off_knob.center().x - ltr_off_track.min.x) - (rtl_off_track.max.x - rtl_off_knob.center().x)).abs() <= 0.5);
|
||||
}
|
||||
|
||||
/// #7311: the title bar's Discord community button keeps its solid accent fill and contrasting
|
||||
/// `on_strong` icon/label in both wide (pill with label) and narrow (compact icon-only) windows,
|
||||
/// across Light and Dark themes, and still dispatches `ui.discord` when clicked.
|
||||
#[test]
|
||||
fn title_bar_discord_button_keeps_accent_fill_and_icon_contrast_in_wide_and_narrow_windows() {
|
||||
use egui::accesskit::Role;
|
||||
|
||||
fn to_color32(rgba: craft::theme::Rgba) -> egui::Color32 {
|
||||
egui::Color32::from(craft::theme::Srgba::from(rgba))
|
||||
}
|
||||
|
||||
fn collect_shapes<'a>(shapes: &'a [egui::epaint::ClippedShape], out: &mut Vec<&'a egui::Shape>) {
|
||||
for clipped in shapes {
|
||||
fn walk<'a>(shape: &'a egui::Shape, out: &mut Vec<&'a egui::Shape>) {
|
||||
match shape {
|
||||
egui::Shape::Vec(children) => {
|
||||
for child in children {
|
||||
walk(child, out);
|
||||
}
|
||||
}
|
||||
other => out.push(other),
|
||||
}
|
||||
}
|
||||
walk(&clipped.shape, out);
|
||||
}
|
||||
}
|
||||
|
||||
for theme in ["light", "dark"] {
|
||||
for (width, expect_compact) in [(1440.0_f32, false), (520.0_f32, true)] {
|
||||
let mut a = new_app();
|
||||
a.ui.show_discord = true;
|
||||
a.run("ui.theme", json!({"value": theme})).unwrap();
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(width, 700.0)).build_ui_state(app_frame, a);
|
||||
crate::test_harness::frames(&mut h, 10);
|
||||
|
||||
let node = h.get_by_role_and_label(Role::Button, "Discord");
|
||||
let rect = node.rect();
|
||||
assert!(rect.is_positive(), "{theme} {width}: Discord button must be laid out");
|
||||
if expect_compact {
|
||||
assert!(rect.width() <= rect.height() + 4.0, "{theme} {width}: expected compact icon-only Discord button, got {rect:?}");
|
||||
} else {
|
||||
assert!(rect.width() > rect.height() + 10.0, "{theme} {width}: expected full labelled Discord pill, got {rect:?}");
|
||||
}
|
||||
|
||||
let env = craft::ui::runtime::env::Env::of_root(&h.ctx);
|
||||
let accent_strong = to_color32(env.tokens.color.accent.strong);
|
||||
let on_strong = to_color32(env.tokens.color.text.on_strong);
|
||||
|
||||
let mut shapes = Vec::new();
|
||||
collect_shapes(&h.output().shapes, &mut shapes);
|
||||
|
||||
let bg = shapes.iter().find_map(|s| match s {
|
||||
egui::Shape::Rect(r)
|
||||
if (r.rect.min.x - rect.min.x).abs() <= 1.5
|
||||
&& (r.rect.max.x - rect.max.x).abs() <= 1.5
|
||||
&& (r.rect.min.y - rect.min.y).abs() <= 1.5
|
||||
&& (r.rect.max.y - rect.max.y).abs() <= 1.5
|
||||
&& r.fill != egui::Color32::TRANSPARENT =>
|
||||
{
|
||||
Some(r)
|
||||
}
|
||||
_ => None,
|
||||
});
|
||||
let bg = bg.unwrap_or_else(|| panic!("{theme} {width}: expected a filled background rect for Discord button {rect:?}"));
|
||||
assert_eq!(bg.fill, accent_strong, "{theme} {width}: Discord button fill should be accent.strong");
|
||||
if !expect_compact {
|
||||
let min_pill_radius = (rect.height() / 2.0 - 1.5).floor().max(0.0) as u8;
|
||||
assert!(
|
||||
bg.corner_radius.nw >= min_pill_radius,
|
||||
"{theme} {width}: wide Discord button should have pill corners (>= {min_pill_radius}), got {:?}",
|
||||
bg.corner_radius
|
||||
);
|
||||
}
|
||||
|
||||
let icon_tinted_on_strong = shapes.iter().any(|s| match s {
|
||||
egui::Shape::Mesh(mesh) => {
|
||||
let bounds = mesh.calc_bounds();
|
||||
rect.expand(1.5).contains_rect(bounds) && !mesh.vertices.is_empty() && mesh.vertices.iter().all(|v| v.color == on_strong)
|
||||
}
|
||||
_ => false,
|
||||
});
|
||||
assert!(
|
||||
icon_tinted_on_strong,
|
||||
"{theme} {width}: Discord icon inside {rect:?} must paint in text.on_strong ({on_strong:?}), not accent ink"
|
||||
);
|
||||
|
||||
if !expect_compact {
|
||||
let has_label = shapes.iter().any(|s| match s {
|
||||
egui::Shape::Text(t) => rect.expand(1.5).contains_rect(s.visual_bounding_rect()) && t.galley.text() == "Discord",
|
||||
_ => false,
|
||||
});
|
||||
assert!(has_label, "{theme} {width}: wide Discord pill must paint its \"Discord\" label");
|
||||
}
|
||||
|
||||
// Clicking the button dispatches `ui.discord` and opens the community URL.
|
||||
h.get_by_role_and_label(Role::Button, "Discord").click();
|
||||
let mut opened = None;
|
||||
for _ in 0..4 {
|
||||
crate::test_harness::step(&mut h);
|
||||
for cmd in &h.output().platform_output.commands {
|
||||
if let egui::OutputCommand::OpenUrl(url) = cmd {
|
||||
opened = Some(url.url.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
opened.as_deref(),
|
||||
Some("https://discord.gg/artcraft"),
|
||||
"{theme} {width}: clicking the Discord button should open the community URL"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// #7445: the title bar's Discord community button uses the dedicated single-ink `discordPill` icon
|
||||
/// with `on_strong` contrast over the solid accent pill, while the ribbon's Review › Help › Community
|
||||
/// Discord button retains the branded `discord` icon with `class="accent"` ink.
|
||||
#[test]
|
||||
fn discord_icons_distinguish_title_bar_pill_and_ribbon_accent() {
|
||||
use egui::accesskit::Role;
|
||||
|
||||
fn to_color32(rgba: craft::theme::Rgba) -> egui::Color32 {
|
||||
egui::Color32::from(craft::theme::Srgba::from(rgba))
|
||||
}
|
||||
|
||||
fn collect_shapes<'a>(shapes: &'a [egui::epaint::ClippedShape], out: &mut Vec<&'a egui::Shape>) {
|
||||
for clipped in shapes {
|
||||
fn walk<'a>(shape: &'a egui::Shape, out: &mut Vec<&'a egui::Shape>) {
|
||||
match shape {
|
||||
egui::Shape::Vec(children) => {
|
||||
for child in children {
|
||||
walk(child, out);
|
||||
}
|
||||
}
|
||||
other => out.push(other),
|
||||
}
|
||||
}
|
||||
walk(&clipped.shape, out);
|
||||
}
|
||||
}
|
||||
|
||||
for theme in ["light", "dark"] {
|
||||
let mut a = new_app();
|
||||
a.ui.show_discord = true;
|
||||
a.ui.language = "en".into();
|
||||
a.run("ui.theme", json!({"value": theme})).unwrap();
|
||||
a.run("ui.tab", json!({"tab": "Help"})).unwrap();
|
||||
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 700.0)).build_ui_state(app_frame, a);
|
||||
crate::test_harness::frames(&mut h, 6);
|
||||
|
||||
let env = craft::ui::runtime::env::Env::of_root(&h.ctx);
|
||||
let on_strong = to_color32(env.tokens.color.text.on_strong);
|
||||
let accent_solid = to_color32(env.tokens.color.accent.solid);
|
||||
|
||||
let mut shapes = Vec::new();
|
||||
collect_shapes(&h.output().shapes, &mut shapes);
|
||||
|
||||
// 1. Title-bar button uses discordPill icon (single-ink text.on_strong).
|
||||
let title_bar_node = h.get_by_role_and_label(Role::Button, "Discord");
|
||||
let title_bar_rect = title_bar_node.rect();
|
||||
assert!(title_bar_rect.is_positive(), "{theme}: Title-bar Discord button must be laid out");
|
||||
|
||||
let title_bar_icon_on_strong = shapes.iter().any(|s| match s {
|
||||
egui::Shape::Mesh(mesh) => {
|
||||
let bounds = mesh.calc_bounds();
|
||||
title_bar_rect.expand(1.5).contains_rect(bounds) && !mesh.vertices.is_empty() && mesh.vertices.iter().all(|v| v.color == on_strong)
|
||||
}
|
||||
_ => false,
|
||||
});
|
||||
assert!(title_bar_icon_on_strong, "{theme}: Title-bar Discord icon inside {title_bar_rect:?} must paint in text.on_strong ({on_strong:?})");
|
||||
|
||||
// 2. Ribbon Help › Community Discord button uses discord icon with class="accent".
|
||||
let ribbon_node = h
|
||||
.query_all_by_role(Role::Button)
|
||||
.find(|n| n.accesskit_node().label().is_some_and(|l| l.contains("Discord")) && n.rect() != title_bar_rect)
|
||||
.expect("Ribbon Community Discord button");
|
||||
let ribbon_rect = ribbon_node.rect();
|
||||
assert!(ribbon_rect.is_positive(), "{theme}: Ribbon Community Discord button must be laid out");
|
||||
|
||||
let ribbon_icon_accent = shapes.iter().any(|s| match s {
|
||||
egui::Shape::Mesh(mesh) => {
|
||||
let bounds = mesh.calc_bounds();
|
||||
ribbon_rect.expand(1.5).contains_rect(bounds) && !mesh.vertices.is_empty() && mesh.vertices.iter().all(|v| v.color == accent_solid)
|
||||
}
|
||||
_ => false,
|
||||
});
|
||||
assert!(ribbon_icon_accent, "{theme}: Ribbon Community Discord icon inside {ribbon_rect:?} must paint in accent.solid ({accent_solid:?})");
|
||||
}
|
||||
}
|
||||
|
||||
/// #7319: view mode toggle buttons (Read Mode, Print Layout, Web Layout) in the status bar are grouped
|
||||
/// with `Gap::Item` intra-group spacing, separated from Focus and Zoom controls via `Gap::Section`.
|
||||
/// The Zoom slider has size `ControlSize::Md`, giving its thumb a 14 pt grab affordance matching sibling `IconButton`s.
|
||||
#[test]
|
||||
fn status_bar_view_mode_toggles_and_zoom_slider_proportions() {
|
||||
use egui::accesskit::Role;
|
||||
let h = harness(new_app());
|
||||
|
||||
let focus = h.get_by_role_and_label(Role::Button, "Focus").rect();
|
||||
let read_mode = h.get_by_role_and_label(Role::Button, "Read Mode").rect();
|
||||
let print_layout = h.get_by_role_and_label(Role::Button, "Print Layout").rect();
|
||||
let web_layout = h.get_by_role_and_label(Role::Button, "Web Layout").rect();
|
||||
let zoom_out = h.get_by_role_and_label(Role::Button, "Zoom Out").rect();
|
||||
let slider = h.get_by_role_and_label(Role::Slider, "Zoom").rect();
|
||||
let zoom_in = h.get_by_role_and_label(Role::Button, "Zoom In").rect();
|
||||
|
||||
let env = craft::ui::runtime::env::Env::of_root(&h.ctx);
|
||||
let gap_section = env.tokens.space.gap.section;
|
||||
let gap_item = env.tokens.space.gap.item;
|
||||
let gap_row = env.tokens.space.gap.row;
|
||||
let glyph_md = env.tokens.size.icon.glyph_md;
|
||||
|
||||
// 1. Spacing and grouping:
|
||||
// Focus -> View modes group gap is Gap::Section.
|
||||
let focus_to_views_gap = read_mode.min.x - focus.max.x;
|
||||
assert!(
|
||||
(focus_to_views_gap - gap_section).abs() <= 0.5,
|
||||
"Focus and Read Mode should be separated by Gap::Section ({gap_section} pt), got {focus_to_views_gap}"
|
||||
);
|
||||
|
||||
// Intra-group spacing between view mode toggle buttons is Gap::Item.
|
||||
let read_to_print_gap = print_layout.min.x - read_mode.max.x;
|
||||
let print_to_web_gap = web_layout.min.x - print_layout.max.x;
|
||||
assert!(
|
||||
(read_to_print_gap - gap_item).abs() <= 0.5,
|
||||
"Read Mode and Print Layout intra-group spacing should be Gap::Item ({gap_item} pt), got {read_to_print_gap}"
|
||||
);
|
||||
assert!(
|
||||
(print_to_web_gap - gap_item).abs() <= 0.5,
|
||||
"Print Layout and Web Layout intra-group spacing should be Gap::Item ({gap_item} pt), got {print_to_web_gap}"
|
||||
);
|
||||
|
||||
// View modes group -> Zoom controls group gap is Gap::Section.
|
||||
let views_to_zoom_gap = zoom_out.min.x - web_layout.max.x;
|
||||
assert!(
|
||||
(views_to_zoom_gap - gap_section).abs() <= 0.5,
|
||||
"Web Layout and Zoom Out should be separated by Gap::Section ({gap_section} pt), got {views_to_zoom_gap}"
|
||||
);
|
||||
|
||||
// Zoom controls intra-group spacing is default row gap (Gap::Row).
|
||||
let zoom_out_to_slider_gap = slider.min.x - zoom_out.max.x;
|
||||
let slider_to_zoom_in_gap = zoom_in.min.x - slider.max.x;
|
||||
assert!(
|
||||
(zoom_out_to_slider_gap - gap_row).abs() <= 0.5,
|
||||
"Zoom Out and Zoom Slider intra-group spacing should be Gap::Row ({gap_row} pt), got {zoom_out_to_slider_gap}"
|
||||
);
|
||||
assert!(
|
||||
(slider_to_zoom_in_gap - gap_row).abs() <= 0.5,
|
||||
"Zoom Slider and Zoom In intra-group spacing should be Gap::Row ({gap_row} pt), got {slider_to_zoom_in_gap}"
|
||||
);
|
||||
|
||||
// 2. Zoom slider thumb proportions:
|
||||
// Slider thumb is rendered as a round knob sized at glyph_md (14 pt) for ControlSize::Md.
|
||||
fn collect_shapes<'a>(shapes: &'a [egui::epaint::ClippedShape], out: &mut Vec<&'a egui::Shape>) {
|
||||
for clipped in shapes {
|
||||
fn walk<'a>(shape: &'a egui::Shape, out: &mut Vec<&'a egui::Shape>) {
|
||||
match shape {
|
||||
egui::Shape::Vec(children) => {
|
||||
for child in children {
|
||||
walk(child, out);
|
||||
}
|
||||
}
|
||||
other => out.push(other),
|
||||
}
|
||||
}
|
||||
walk(&clipped.shape, out);
|
||||
}
|
||||
}
|
||||
|
||||
let mut shapes = Vec::new();
|
||||
collect_shapes(&h.output().shapes, &mut shapes);
|
||||
|
||||
let has_14pt_knob = shapes.iter().any(|s| match s {
|
||||
egui::Shape::Rect(r) => {
|
||||
let rect = r.rect;
|
||||
slider.expand(2.0).contains_rect(rect) && (rect.width() - glyph_md).abs() <= 0.5 && (rect.height() - glyph_md).abs() <= 0.5
|
||||
}
|
||||
_ => false,
|
||||
});
|
||||
assert!(has_14pt_knob, "Zoom slider should paint a {glyph_md} pt thumb (ControlSize::Md) matching 14 pt IconButton icons inside {slider:?}");
|
||||
}
|
||||
|
||||
@@ -6,7 +6,10 @@ use craft::behavior::IconId;
|
||||
use craft::keymap::CommandRef;
|
||||
use craft::menu::RibbonMenuRequest;
|
||||
use craft::review::ui::Avatar;
|
||||
use craft::theme::ControlSize;
|
||||
use craft::theme::variant::Tone;
|
||||
use craft::theme::{ControlSize, CustomVariant, Emphasis, RadiusStep, Tokens, Variant, VariantLook};
|
||||
use craft::ui::buttons::button::ButtonStyleKey;
|
||||
use craft::ui::buttons::icon_button::IconButtonStyleKey;
|
||||
use craft::ui::buttons::{Button, IconButton};
|
||||
use craft::ui::choice::Switch;
|
||||
use craft::ui::contract::{Bind, BodyCx, Props as _, Show as _, ShowCollection as _, ShowContainer as _, TooltipSpec, Trigger};
|
||||
@@ -197,6 +200,11 @@ fn undo_arrow(app: &mut WordApp, ui: &mut Ui, enabled: bool) -> egui::Rect {
|
||||
app.chrome.undo_mark = if open { mark } else { UndoMark::default() };
|
||||
if let Some(count) = picked {
|
||||
let _ = app.run("edit.undoTo", json!({"count": count}));
|
||||
// Picking a row closes the Undo History popover on its foreground layer; return keyboard
|
||||
// focus to the document both now and after the pass's overlay-close focus hook (#3040).
|
||||
app.canvas.focus_page(ui.ctx());
|
||||
app.canvas.focus_page_after_pass();
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
out.response.rect
|
||||
}
|
||||
@@ -232,6 +240,19 @@ fn qat_menu(app: &mut WordApp, ui: &mut Ui) -> egui::Rect {
|
||||
out.response.rect
|
||||
}
|
||||
|
||||
/// Solid accent pill look for the full title bar Discord button (#656, #7311).
|
||||
fn discord_pill_look(tokens: &Tokens) -> VariantLook {
|
||||
VariantLook::of(Emphasis::Solid, Tone::Accent, tokens).radius(RadiusStep::Pill)
|
||||
}
|
||||
|
||||
/// Solid accent look for the compact icon-only Discord button when the title bar narrows (#5886, #7311).
|
||||
fn discord_icon_look(tokens: &Tokens) -> VariantLook {
|
||||
VariantLook::of(Emphasis::Solid, Tone::Accent, tokens)
|
||||
}
|
||||
|
||||
const DISCORD_PILL: CustomVariant = CustomVariant::new::<ButtonStyleKey>("wordcraft.discord-pill", discord_pill_look);
|
||||
const DISCORD_ICON: CustomVariant = CustomVariant::new::<IconButtonStyleKey>("wordcraft.discord-icon", discord_icon_look);
|
||||
|
||||
/// Search, the community button and the account, at the end of the bar; returns the rect they took. In a narrow
|
||||
/// window they give way by `step` (#5886, as the old bar's fit): at 1 the Discord button drops its label, at 2 the
|
||||
/// search shows its magnifier alone as well.
|
||||
@@ -240,11 +261,17 @@ fn trailing(app: &mut WordApp, ui: &mut Ui, step: usize) -> Option<egui::Rect> {
|
||||
if app.ui.show_discord {
|
||||
let tip = TooltipSpec::new(tl!("Join the ArtCraft community on Discord").to_string());
|
||||
let clicked = if step >= 1 {
|
||||
let out = IconButton::new(IconId::new("discord")).label(tl!("Discord").to_string()).tooltip(tip).show(ui);
|
||||
let out = IconButton::new(IconId::new("discordPill"))
|
||||
.label(tl!("Discord").to_string())
|
||||
.variant(Variant::Custom(DISCORD_ICON))
|
||||
.glyphs(GlyphRole::Tool)
|
||||
.tooltip(tip)
|
||||
.show(ui);
|
||||
rects.push(out.response.rect);
|
||||
out.response.clicked()
|
||||
} else {
|
||||
let out = Button::new(tl!("Discord").to_string()).icon(IconId::new("discord")).tooltip(tip).show(ui);
|
||||
let out =
|
||||
Button::new(tl!("Discord").to_string()).icon(IconId::new("discordPill")).variant(Variant::Custom(DISCORD_PILL)).tooltip(tip).show(ui);
|
||||
rects.push(out.response.rect);
|
||||
out.clicked()
|
||||
};
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
//! control library
|
||||
//! - `ui.clickText {page, x, y}`: click at a page position (points from the page's top-left)
|
||||
//! - `ui.dialog.set`, `ui.dialog.confirm`, `ui.dialog.cancel`: the open dialogs' fields and answers
|
||||
//! - `ui.screenshot {path?}`: PNG of the window; `ui.render {path?, page?, scale?}`: page PNG
|
||||
//! - `ui.screenshot {path?, region?}`: PNG of the window (or of `region` `[x0, y0, x1, y1]` in points); `ui.render {path?, page?, scale?}`: page PNG
|
||||
//! (without `path`, both reply with the PNG as base64 `png`)
|
||||
//! - `ui.resize`, `ui.focus`, `ui.closeWindow`, `ui.clipboard`, `ui.replayAt`, `ui.accessTree`
|
||||
//! - `ui.parity`: feature catalog parity
|
||||
|
||||
@@ -376,10 +376,13 @@ fn handle_request(app: &mut WordApp, ctx: &egui::Context, req: &ControlRequest)
|
||||
"ui.inspect" => ok(inspect(app, ctx)),
|
||||
"ui.parity" => ok(wordcraft_engine::catalog::parity(&app.session.registry)),
|
||||
"ui.clickText" => click_text(app, ctx, p),
|
||||
"ui.screenshot" => {
|
||||
let token = app.next_capture_token();
|
||||
Reply::screenshot(token, s("path").map(str::to_string), app.active_viewport())
|
||||
}
|
||||
"ui.screenshot" => match craft::automation::screenshot::ScreenshotParams::from_params(p) {
|
||||
Ok(params) => {
|
||||
let token = app.next_capture_token();
|
||||
Reply::screenshot(token, params, app.active_viewport())
|
||||
}
|
||||
Err(e) => err(e),
|
||||
},
|
||||
"ui.render" => {
|
||||
let page = p.get("page").and_then(Value::as_u64).unwrap_or(1);
|
||||
let scale = p.get("scale").and_then(Value::as_f64).map_or(2.0, |v| v as f32);
|
||||
|
||||
@@ -307,7 +307,8 @@ fn control_keyboard_reaches_the_background_document_once() {
|
||||
assert_eq!(body_text(h.state()), "Seed", "one Undo reverses the one text input");
|
||||
}
|
||||
|
||||
/// Control text and keys target the focused widget of a dialog, not the document, and Escape closes it.
|
||||
/// Control text and keys target the focused widget of a dialog, not the document. The Find dialog is modeless, so the
|
||||
/// first Escape reverts the field's typing and the second closes the dialog.
|
||||
#[test]
|
||||
fn control_keyboard_keeps_the_background_widget_target() {
|
||||
let mut a = app();
|
||||
@@ -325,7 +326,10 @@ fn control_keyboard_keeps_the_background_widget_target() {
|
||||
assert_eq!(body_text(h.state()), "Seed", "the Find field, not the document, owns the input");
|
||||
send(&mut h, "ui.key", json!({"key": "Escape"}));
|
||||
frames(&mut h, 6);
|
||||
assert_eq!(open(&mut h), 0, "Escape closes the dialog");
|
||||
assert!(open(&mut h) > 0, "the first Escape reverts the field and leaves the dialog open");
|
||||
send(&mut h, "ui.key", json!({"key": "Escape"}));
|
||||
frames(&mut h, 6);
|
||||
assert_eq!(open(&mut h), 0, "the second Escape closes the dialog");
|
||||
assert_eq!(body_text(h.state()), "Seed");
|
||||
}
|
||||
|
||||
|
||||
+143
-15
@@ -66,22 +66,59 @@ pub fn credits() -> Credits {
|
||||
}
|
||||
|
||||
/// The About tab's contents: name, blurb, version and build, and the project links in the old About's order (site,
|
||||
/// Discord, source), one to a line.
|
||||
/// Discord, source), one to a line. A Nightly window names its channel, its exact feed version
|
||||
/// and commit, and offers a link to report a problem.
|
||||
pub fn about_info() -> AboutInfo {
|
||||
let build = option_env!("WORDCRAFT_BUILD_SHA").map(|s| s.get(..8).unwrap_or(s)).unwrap_or(tl!("development build"));
|
||||
// The dialog's own "Version {version}" words the line, so this is the number and the build only.
|
||||
let version = crate::i18n::fmt(tl!("{version} ({build})"), &[("version", env!("CARGO_PKG_VERSION")), ("build", build)]);
|
||||
AboutInfo::new(
|
||||
tl!("WordCraft").to_string(),
|
||||
tl!("A free, open-source word processor written from scratch in Rust.\nPart of the Crafting Apps from the ArtCraft team.").to_string(),
|
||||
version.to_string(),
|
||||
)
|
||||
.links([
|
||||
AboutLink::new(tl!("getartcraft.com/apps/wordcraft").to_string(), "https://getartcraft.com/apps/wordcraft"),
|
||||
AboutLink::new(tl!("Join us on Discord: discord.gg/artcraft").to_string(), "https://discord.gg/artcraft"),
|
||||
AboutLink::new(tl!("Source code: github.com/storytold/wordcraft").to_string(), "https://github.com/storytold/wordcraft"),
|
||||
])
|
||||
.built_with(tl!("MIT OR Apache-2.0. Copyright (c) 2026 ArtCraft Team and the WordCraft contributors.").to_string())
|
||||
about_info_for(crate::os_window::identity(), option_env!("WORDCRAFT_BUILD_SHA"))
|
||||
}
|
||||
|
||||
/// The About tab's three lines for `identity`: (name, blurb, version line). A Nightly window's
|
||||
/// are English only: they are not one of the stable catalogs' strings.
|
||||
fn about_text(identity: crate::os_window::LaunchIdentity, commit: Option<&str>) -> (String, String, String) {
|
||||
match identity {
|
||||
crate::os_window::LaunchIdentity::NightlyV1 => {
|
||||
let version = option_env!("WORDCRAFT_VERSION").unwrap_or(env!("CARGO_PKG_VERSION"));
|
||||
let commit = commit.filter(|value| !value.is_empty()).unwrap_or("unavailable");
|
||||
(
|
||||
crate::os_window::name_for(identity).to_string(),
|
||||
"A free, open-source word processor written from scratch in Rust.\nPart of the Crafting Apps from the ArtCraft team.".to_string(),
|
||||
format!("{version}\nCommit: {commit}"),
|
||||
)
|
||||
}
|
||||
crate::os_window::LaunchIdentity::Stable => {
|
||||
let build = commit.map(|s| s.get(..8).unwrap_or(s)).unwrap_or(tl!("development build"));
|
||||
// The dialog's own "Version {version}" words the line, so this is the number and the build only.
|
||||
let version = crate::i18n::fmt(tl!("{version} ({build})"), &[("version", env!("CARGO_PKG_VERSION")), ("build", build)]);
|
||||
(
|
||||
tl!("WordCraft").to_string(),
|
||||
tl!("A free, open-source word processor written from scratch in Rust.\nPart of the Crafting Apps from the ArtCraft team.")
|
||||
.to_string(),
|
||||
version.to_string(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn about_info_for(identity: crate::os_window::LaunchIdentity, commit: Option<&str>) -> AboutInfo {
|
||||
let (name, blurb, version) = about_text(identity, commit);
|
||||
if identity == crate::os_window::LaunchIdentity::NightlyV1 {
|
||||
return AboutInfo::new(name, blurb, version)
|
||||
.links([
|
||||
AboutLink::new("getartcraft.com/apps/wordcraft".to_string(), "https://getartcraft.com/apps/wordcraft"),
|
||||
AboutLink::new("Join us on Discord: discord.gg/artcraft".to_string(), "https://discord.gg/artcraft"),
|
||||
AboutLink::new("Source code: github.com/storytold/wordcraft".to_string(), "https://github.com/storytold/wordcraft"),
|
||||
// Opens only after a click; nothing is collected or sent automatically.
|
||||
AboutLink::new("Report a problem".to_string(), "https://github.com/storytold/wordcraft/issues"),
|
||||
])
|
||||
.built_with("MIT OR Apache-2.0. Copyright (c) 2026 ArtCraft Team and the WordCraft contributors.".to_string());
|
||||
}
|
||||
AboutInfo::new(name, blurb, version)
|
||||
.links([
|
||||
AboutLink::new(tl!("getartcraft.com/apps/wordcraft").to_string(), "https://getartcraft.com/apps/wordcraft"),
|
||||
AboutLink::new(tl!("Join us on Discord: discord.gg/artcraft").to_string(), "https://discord.gg/artcraft"),
|
||||
AboutLink::new(tl!("Source code: github.com/storytold/wordcraft").to_string(), "https://github.com/storytold/wordcraft"),
|
||||
])
|
||||
.built_with(tl!("MIT OR Apache-2.0. Copyright (c) 2026 ArtCraft Team and the WordCraft contributors.").to_string())
|
||||
}
|
||||
|
||||
/// The About dialog opened on `tab`, with the Language data tab after Models (`AboutTab::App(0)`). The name
|
||||
@@ -90,3 +127,94 @@ pub(crate) fn about(tab: AboutTab) -> HostedAbout {
|
||||
// PLAN: assumed `HostedAbout::layout(self, AboutLayout) -> Self` (look-dialogs-b framework fix)
|
||||
HostedAbout::new(about_info(), credits()).app_tab(language_data_tab()).tab(tab).layout(AboutLayout::Listed)
|
||||
}
|
||||
|
||||
/// A Nightly window's About names its channel, keeps the full feed version and commit, invents
|
||||
/// nothing when the commit is missing, and adds the report link the stable About does not have.
|
||||
#[cfg(test)]
|
||||
mod nightly_about_tests {
|
||||
use crate::os_window::LaunchIdentity;
|
||||
|
||||
const COMMIT: &str = "0123456789abcdef0123456789abcdef01234567";
|
||||
|
||||
#[test]
|
||||
fn nightly_about_names_the_channel_and_keeps_the_full_version_and_commit() {
|
||||
let (name, blurb, version) = super::about_text(LaunchIdentity::NightlyV1, Some(COMMIT));
|
||||
assert_eq!(name, "WordCraft Nightly");
|
||||
assert!(blurb.contains("word processor"));
|
||||
let package = option_env!("WORDCRAFT_VERSION").unwrap_or(env!("CARGO_PKG_VERSION"));
|
||||
assert_eq!(version, format!("{package}\nCommit: {COMMIT}"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_about_invents_no_provenance_when_the_commit_is_missing() {
|
||||
for commit in [None, Some("")] {
|
||||
let (_, _, version) = super::about_text(LaunchIdentity::NightlyV1, commit);
|
||||
assert!(version.ends_with("\nCommit: unavailable"), "{version}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_nightly_about_offers_the_report_link_and_the_stable_name_is_unchanged() {
|
||||
let nightly = super::about_info_for(LaunchIdentity::NightlyV1, Some(COMMIT));
|
||||
assert!(nightly.links.iter().any(|link| link.url == "https://github.com/storytold/wordcraft/issues"));
|
||||
let stable = super::about_info_for(LaunchIdentity::Stable, Some(COMMIT));
|
||||
assert!(!stable.links.iter().any(|link| link.url == "https://github.com/storytold/wordcraft/issues"));
|
||||
let (name, _, _) = super::about_text(LaunchIdentity::Stable, Some(COMMIT));
|
||||
assert_eq!(name, "WordCraft");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use craft::ui::contract::Role;
|
||||
use craft::ui::dialog::DialogHost;
|
||||
use craft::ui::testing::Fixture;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn column_header(fixture: &Fixture, label: &str) -> egui::Rect {
|
||||
fixture
|
||||
.by_role(Role::COLUMN_HEADER)
|
||||
.into_iter()
|
||||
.find(|cell| fixture.tree().name_of(cell.node) == Some(label))
|
||||
.unwrap_or_else(|| panic!("missing column header {label:?}"))
|
||||
.rect
|
||||
}
|
||||
|
||||
fn table_rect(fixture: &Fixture) -> egui::Rect {
|
||||
fixture.by_role(Role::TABLE).first().expect("the credits table shows").rect
|
||||
}
|
||||
|
||||
/// Verifies that WordCraft's `about(AboutTab::Models)` (`AboutLayout::Listed` with the baked
|
||||
/// `MODELS` table) fits within the dialog and refits its `Company` column when narrowed.
|
||||
/// The original drag-then-content-change refit check (#5588) belongs in `craft-libs` and is
|
||||
/// tracked in `storytold/craft-libs#3372`.
|
||||
#[test]
|
||||
fn models_table_refits_to_narrower_window() {
|
||||
let wide = egui::vec2(1400.0, 800.0);
|
||||
let narrow = egui::vec2(660.0, 800.0);
|
||||
|
||||
let host = Rc::new(RefCell::new(DialogHost::new()));
|
||||
let shown_host = Rc::clone(&host);
|
||||
let mut fixture = Fixture::new(move |ui| shown_host.borrow_mut().run(ui));
|
||||
fixture.room(wide);
|
||||
host.borrow_mut().open(about(AboutTab::Models));
|
||||
fixture.settle();
|
||||
|
||||
let wide_table = table_rect(&fixture);
|
||||
let wide_company = column_header(&fixture, "Company");
|
||||
let wide_last = column_header(&fixture, "Lines +/\u{2212}");
|
||||
assert!(wide_last.right() <= wide_table.right() + 1.0, "the table opens fitted to the dialog: {wide_last:?} in {wide_table:?}");
|
||||
|
||||
fixture.room(narrow).settle();
|
||||
let slim_table = table_rect(&fixture);
|
||||
let slim_company = column_header(&fixture, "Company");
|
||||
let slim_last = column_header(&fixture, "Lines +/\u{2212}");
|
||||
assert!(slim_table.width() < wide_table.width() - 1.0, "hosted About shrinks with window: {slim_table:?} vs {wide_table:?}");
|
||||
assert!(slim_company.width() < wide_company.width() - 1.0, "hosted About refits its Company column: {slim_company:?} vs {wide_company:?}");
|
||||
assert!(slim_last.right() <= slim_table.right() + 1.0, "the narrower table still fits its last column: {slim_last:?} in {slim_table:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -287,7 +287,7 @@ pub(crate) fn show(app: &mut WordApp, ui: &mut Ui, layout: &DocLayout, body: &Pa
|
||||
);
|
||||
}
|
||||
}
|
||||
if out.apply || out.discard {
|
||||
if out.apply.is_some() || out.discard {
|
||||
leave(app);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ use serde_json::Value;
|
||||
use crate::WordApp;
|
||||
|
||||
mod bookmarks;
|
||||
pub(crate) mod chrome;
|
||||
mod customize_keyboard;
|
||||
mod enclose;
|
||||
mod find;
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
//! Modal dialog chrome: modal nudge/shake animations and decorations (#3859, #4076, #7321).
|
||||
|
||||
use craft::ui::runtime::env::Env;
|
||||
use craft::ui::style::rgba_color;
|
||||
use egui::emath::TSTransform;
|
||||
use egui::{Context, CornerRadius, Id, LayerId, Order, Stroke, StrokeKind, Ui, vec2};
|
||||
|
||||
use crate::WordApp;
|
||||
|
||||
/// How long a modal window shakes or flashes after a press beside it, in seconds.
|
||||
pub(crate) const NUDGE_SECS: f64 = 0.4;
|
||||
|
||||
/// The `ctx.data` key for when the window `id` was last nudged, in this document window: the data
|
||||
/// is shared by all of them.
|
||||
pub(crate) fn nudge_id(ctx: &Context, id: Id) -> Id {
|
||||
id.with(("nudge", ctx.viewport_id()))
|
||||
}
|
||||
|
||||
/// Forgets a nudge of the window `id` as it closes, so it doesn't go on when the window reopens.
|
||||
pub(crate) fn forget_nudge(ctx: &Context, id: Id) {
|
||||
let key = nudge_id(ctx, id);
|
||||
ctx.data_mut(|d| {
|
||||
d.remove::<f64>(key);
|
||||
});
|
||||
}
|
||||
|
||||
/// The shake's sideways offset at `t` (0 to 1) through it: three swings either way of up to 6
|
||||
/// points, dying away.
|
||||
pub(crate) fn shake_offset(t: f32) -> f32 {
|
||||
6.0 * (t * 3.0 * std::f32::consts::TAU).sin() * (1.0 - t)
|
||||
}
|
||||
|
||||
/// Triggers a shake/nudge animation on dialog `id` if not already running.
|
||||
pub(crate) fn trigger_prompt_nudge(ctx: &Context, id: Id) {
|
||||
let key = nudge_id(ctx, id);
|
||||
let now = ctx.input(|i| i.time);
|
||||
let running = ctx.data(|d| d.get_temp::<f64>(key)).is_some_and(|s| (0.0..NUDGE_SECS).contains(&(now - s)));
|
||||
if !running {
|
||||
ctx.data_mut(|d| d.insert_temp(key, now));
|
||||
}
|
||||
ctx.request_repaint();
|
||||
}
|
||||
|
||||
/// Applies modal shake / nudge animation (or accent border flashes under reduced motion) to the
|
||||
/// active modal dialog. Also detects presses beside the dialog (on the backdrop or outside) to
|
||||
/// trigger the nudge.
|
||||
pub(crate) fn apply_modal_nudge(app: &mut WordApp, ui: &mut Ui) {
|
||||
let ctx = ui.ctx().clone();
|
||||
if craft::ui::runtime::measure::active(&ctx) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Forget nudge on every dialog close, so reopening within NUDGE_SECS opens still.
|
||||
// Tracking the host-provided open_serial distinguishes successive opens sharing the same ID.
|
||||
let prev_open_key = Id::NULL.with("modal_dialogs_open_last_pass").with(ctx.viewport_id());
|
||||
let prev_open: Vec<(Id, u64)> = ctx.data(|d| d.get_temp(prev_open_key)).unwrap_or_default();
|
||||
let current_open: Vec<(Id, u64)> =
|
||||
app.dialog_host.open_dialogs().into_iter().filter_map(|d| app.dialog_host.open_serial(d.id).map(|s| (d.id, s))).collect();
|
||||
for (closed_id, prev_serial) in &prev_open {
|
||||
if !current_open.iter().any(|(id, serial)| id == closed_id && serial == prev_serial) {
|
||||
forget_nudge(&ctx, *closed_id);
|
||||
}
|
||||
}
|
||||
ctx.data_mut(|d| d.insert_temp(prev_open_key, current_open));
|
||||
|
||||
let prompt_id = app.closing.as_ref().and_then(|c| c.prompt).filter(|&id| app.dialog_host.get_dyn(id).is_some());
|
||||
let target_id =
|
||||
prompt_id.or_else(|| app.dialog_host.shows_modal().then(|| app.dialog_host.open_dialogs().into_iter().next_back().map(|d| d.id)).flatten());
|
||||
let Some(id) = target_id else {
|
||||
return;
|
||||
};
|
||||
|
||||
let hosted = app.dialog_host.get_dyn(id).is_some();
|
||||
if !hosted {
|
||||
return;
|
||||
}
|
||||
|
||||
// When popups/menus are open inside a modal dialog, overlay::top points to the popup.
|
||||
// Walk up .parent to locate the target modal dialog's own overlay entry so clicking
|
||||
// inside the dialog (outside the popup) does not falsely trigger a shake.
|
||||
let top_id = craft::ui::runtime::overlay::top(&ctx);
|
||||
let mut modal_entry = top_id.and_then(|tid| craft::ui::runtime::overlay::entry(&ctx, tid));
|
||||
while let Some(entry) = modal_entry.as_ref() {
|
||||
if entry.rank.is_modal() {
|
||||
break;
|
||||
}
|
||||
modal_entry = entry.parent.and_then(|pid| craft::ui::runtime::overlay::entry(&ctx, pid));
|
||||
}
|
||||
let modal_entry = modal_entry.filter(|e| e.rank.is_modal());
|
||||
let modal_layer_id = ctx.memory(|m| m.top_modal_layer());
|
||||
|
||||
let (dialog_rect, area_layer_id) = if let Some(ref entry) = modal_entry {
|
||||
(Some(entry.rect), Some(LayerId::new(Order::Foreground, craft::ui::runtime::memory::sub(entry.id, "area"))))
|
||||
} else if let Some(layer) = modal_layer_id {
|
||||
(ctx.memory(|m| m.area_rect(layer.id)), Some(layer))
|
||||
} else {
|
||||
(None, None)
|
||||
};
|
||||
|
||||
let Some(rect) = dialog_rect else {
|
||||
return;
|
||||
};
|
||||
|
||||
// Include the modal dialog's rectangle and all open overlays in its family
|
||||
// (such as dropdown popups or submenus) so presses on popup extensions are inside.
|
||||
let mut inside_rects = vec![rect];
|
||||
if let Some(ref entry) = modal_entry {
|
||||
for family_id in craft::ui::runtime::overlay::family(&ctx, entry.id) {
|
||||
if let Some(e) = craft::ui::runtime::overlay::entry(&ctx, family_id) {
|
||||
inside_rects.push(e.rect);
|
||||
if let Some(anchor) = e.anchor {
|
||||
inside_rects.push(anchor);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let is_inside = |pos: egui::Pos2| inside_rects.iter().any(|r| r.contains(pos));
|
||||
|
||||
let beside = ctx.input(|i| {
|
||||
let event_pressed = i.events.iter().any(|e| match e {
|
||||
egui::Event::PointerButton { pos, pressed: true, button: egui::PointerButton::Primary, .. } => !is_inside(*pos),
|
||||
_ => false,
|
||||
});
|
||||
let held_pressed = i.pointer.any_pressed() && i.pointer.press_origin().is_some_and(|p| !is_inside(p));
|
||||
event_pressed || held_pressed
|
||||
});
|
||||
if beside {
|
||||
trigger_prompt_nudge(&ctx, id);
|
||||
}
|
||||
|
||||
let key = nudge_id(&ctx, id);
|
||||
let now = ctx.input(|i| i.time);
|
||||
let start = match ctx.data(|d| d.get_temp::<f64>(key)).filter(|s| (0.0..NUDGE_SECS).contains(&(now - s))) {
|
||||
Some(s) => s,
|
||||
None => return,
|
||||
};
|
||||
|
||||
ctx.request_repaint();
|
||||
let t = ((now - start) / NUDGE_SECS).clamp(0.0, 1.0) as f32;
|
||||
let animate = app.animations_on() && app.system_animations();
|
||||
|
||||
if animate {
|
||||
let offset = shake_offset(t);
|
||||
let transform = TSTransform::from_translation(vec2(offset, 0.0));
|
||||
if let Some(area_layer) = area_layer_id {
|
||||
ctx.transform_layer_shapes(area_layer, transform);
|
||||
}
|
||||
if let Some(modal_layer) = modal_layer_id
|
||||
&& Some(modal_layer) != area_layer_id
|
||||
{
|
||||
ctx.transform_layer_shapes(modal_layer, transform);
|
||||
}
|
||||
} else if ((t * 4.0) as u32).is_multiple_of(2) {
|
||||
let env = Env::of(ui);
|
||||
let radius = CornerRadius::from(env.tokens.shape.radius.window);
|
||||
let stroke = Stroke::new(2.0, rgba_color(env.tokens.color.accent.solid));
|
||||
if let Some(area_layer) = area_layer_id {
|
||||
ctx.layer_painter(area_layer).rect_stroke(rect, radius, stroke, StrokeKind::Inside);
|
||||
}
|
||||
if let Some(modal_layer) = modal_layer_id
|
||||
&& Some(modal_layer) != area_layer_id
|
||||
{
|
||||
ctx.layer_painter(modal_layer).rect_stroke(rect, radius, stroke, StrokeKind::Inside);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -147,10 +147,14 @@ pub(crate) fn open(app: &mut WordApp, _name: &str, _params: &Value, parent: Opti
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use craft::keymap::Binding;
|
||||
use craft::keymap::{Binding, CommandRef};
|
||||
use craft::ui::dialog::dialog_id;
|
||||
use egui::accesskit::Role;
|
||||
use egui_kittest::kittest::{By, NodeT, Queryable};
|
||||
use serde_json::json;
|
||||
use wordcraft_engine::Session;
|
||||
|
||||
use super::KEY;
|
||||
use crate::{Services, WordApp};
|
||||
|
||||
fn app() -> WordApp {
|
||||
@@ -181,4 +185,66 @@ mod tests {
|
||||
assert_eq!(chords(&b, "format.bold"), Some(Vec::new()));
|
||||
assert_eq!(chords(&b, "format.italic"), Some(italic));
|
||||
}
|
||||
|
||||
/// #1905: a command with no shortcuts shows `None` in the Current shortcuts list, whereas a
|
||||
/// command with a built-in shortcut shows its binding instead of `None`.
|
||||
#[test]
|
||||
fn keys_list_without_shortcuts_says_none() {
|
||||
let mut a = app();
|
||||
super::open(&mut a, KEY, &json!({}), None).expect("dialog opens");
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_eframe(|_| a);
|
||||
h.run_steps(2);
|
||||
|
||||
let keymap = craft::ui::runtime::commands::keymap(&h.ctx).expect("command board installs a keymap");
|
||||
let unbound_id = h
|
||||
.state()
|
||||
.session
|
||||
.registry
|
||||
.all()
|
||||
.iter()
|
||||
.find(|spec| {
|
||||
let cmd = CommandRef::new(spec.id);
|
||||
keymap.bindable(&cmd).is_some() && keymap.bindings(&cmd).is_empty()
|
||||
})
|
||||
.map(|spec| spec.id.to_string())
|
||||
.expect("a bindable command with no built-in shortcut");
|
||||
assert!(!keymap.bindings(&CommandRef::new("format.bold")).is_empty(), "format.bold has a built-in shortcut");
|
||||
|
||||
let dlg_id = dialog_id(KEY);
|
||||
let ctx = h.ctx.clone();
|
||||
let select = |h: &mut egui_kittest::Harness<'_, WordApp>, id: &str| {
|
||||
h.state_mut().dialog_host.set_json_field(&ctx, dlg_id, "command", json!(id)).expect("command field accepts id");
|
||||
h.run_steps(3);
|
||||
let selected = h
|
||||
.state()
|
||||
.dialog_host
|
||||
.open_dialogs()
|
||||
.into_iter()
|
||||
.find(|d| d.id == dlg_id)
|
||||
.and_then(|d| d.fields)
|
||||
.and_then(|fields| fields.get("command").and_then(|v| v.as_str()).map(str::to_owned));
|
||||
assert_eq!(selected.as_deref(), Some(id), "dialog selected {id}");
|
||||
};
|
||||
let keys_list_labels = |h: &egui_kittest::Harness<'_, WordApp>| -> Vec<String> {
|
||||
let list = h.get_by_role_and_label(Role::List, "Current shortcuts:");
|
||||
let list_id = list.accesskit_node().id();
|
||||
let rect = list.rect();
|
||||
h.query_all(By::new())
|
||||
.filter(|n| n.accesskit_node().id() != list_id && !n.accesskit_node().is_hidden() && n.accesskit_node().bounding_box().is_some())
|
||||
.filter(|n| rect.contains_rect(n.rect()))
|
||||
.filter_map(|n| n.accesskit_node().label())
|
||||
.collect()
|
||||
};
|
||||
|
||||
// Positive contrast: a bound command lists its shortcut and does not show the empty `None` placeholder.
|
||||
select(&mut h, "format.bold");
|
||||
let bound_labels = keys_list_labels(&h);
|
||||
assert!(!bound_labels.is_empty(), "bound command lists its shortcut");
|
||||
assert!(!bound_labels.iter().any(|t| t == "None"), "bound command keys list does not say None: {bound_labels:?}");
|
||||
|
||||
// Target behavior: an unbound command shows `None` inside the Current shortcuts list.
|
||||
select(&mut h, &unbound_id);
|
||||
let unbound_labels = keys_list_labels(&h);
|
||||
assert!(unbound_labels.iter().any(|t| t == "None"), "empty keys list says None: {unbound_labels:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ use craft::ui::contract::{
|
||||
use craft::ui::dialog::DialogId;
|
||||
use craft::ui::display::Text;
|
||||
use craft::ui::layout_components::Row;
|
||||
use craft::ui::list::{ListRow, ThumbAspect};
|
||||
use craft::ui::list::{ListRow, ThumbAspect, ThumbSize};
|
||||
// PLAN: assumed `FormCx::accept` (dialogs-w5, S-L285)
|
||||
use craft::ui::patterns::form_dialogs::FormCx;
|
||||
use craft::ui::primitives::DataWidth;
|
||||
@@ -22,7 +22,7 @@ use craft::ui::runtime::env::Label;
|
||||
use craft::ui::style::DataColor;
|
||||
use craft::ui::table::Table;
|
||||
use craft::ui::text::TextField;
|
||||
use craft::ui::tile_grid::{Tile, TileGrid};
|
||||
use craft::ui::tile_grid::{GridZoom, Tile, TileGrid};
|
||||
use egui::{Color32, Ui, Vec2};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
@@ -272,6 +272,9 @@ fn chart_grid(ui: &mut Ui, colors: [Color32; 3], form: &mut ChartTypeForm) -> bo
|
||||
let current = kinds.iter().position(|k| *k == form.kind).unwrap_or(0);
|
||||
let source = keyed(&positions, |i| *i);
|
||||
let out = TileGrid::<usize>::new(tl!("Chart types").to_string())
|
||||
.thumb_size(ThumbSize::Large)
|
||||
.zoom(GridZoom::Fixed(1.6))
|
||||
.aspect(19.0 / 15.0)
|
||||
.select(SelectMode::Single)
|
||||
.card_columns(3)
|
||||
// Every type shows, as in production, so the dialog's body is the one scroll.
|
||||
|
||||
@@ -26,7 +26,7 @@ pub(crate) mod symbol;
|
||||
pub use columns::DropCapForm;
|
||||
pub use date_time::DateTimeForm;
|
||||
#[cfg(test)]
|
||||
pub(crate) use date_time::date_time_preview_matches;
|
||||
pub(crate) use date_time::date_time_previews_at;
|
||||
pub use field::{DATE_FORMATS, FIELD_CATEGORIES, FIELDS, FieldForm, FieldKind, NUMBER_FORMATS, STYLEREF_SWITCHES, field_kind};
|
||||
pub(crate) use symbol::SymbolDialog;
|
||||
pub use symbol::{RECENT_SYMBOLS, RecentSymbol, SPECIAL, SUBSETS, SymbolForm, remember_symbol, subset_of};
|
||||
|
||||
@@ -35,14 +35,16 @@ const PT_DATE_FORMATS: &[&str] = &[
|
||||
"HH:mm:ss",
|
||||
];
|
||||
|
||||
/// The date preview list consists of document values (not interface strings).
|
||||
/// The i18n audit recognizes these dynamic values instead of treating month names as UI labels.
|
||||
/// What the Date and Time preview list shows at the instant `unix`: document values, not
|
||||
/// interface strings. The i18n audit recognizes these instead of treating month names, dates and
|
||||
/// times as labels.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn date_time_preview_matches(value: &str) -> bool {
|
||||
PT_DATE_FORMATS.iter().chain(DATE_FORMATS.iter()).any(|picture| {
|
||||
wordcraft_engine::cmd::insert::format_date_in(picture, Some("pt-BR")) == value
|
||||
|| wordcraft_engine::cmd::insert::format_date_in(picture, Some("en-US")) == value
|
||||
})
|
||||
pub(crate) fn date_time_previews_at(unix: u64) -> impl Iterator<Item = String> {
|
||||
let offset = wordcraft_engine::cmd::local_offset_secs(unix);
|
||||
PT_DATE_FORMATS
|
||||
.iter()
|
||||
.chain(DATE_FORMATS.iter())
|
||||
.flat_map(move |picture| ["pt-BR", "en-US"].map(|lang| wordcraft_engine::cmd::insert::format_date_at_in(picture, Some(lang), unix, offset)))
|
||||
}
|
||||
|
||||
/// State of the Word-like Insert > Date & Time dialog.
|
||||
|
||||
@@ -8,7 +8,7 @@ use craft::ui::dialog::{DialogId, DialogResult, DialogStack, HeldAnswer, HeldOk,
|
||||
use craft::ui::display::{Kbd, Text};
|
||||
use craft::ui::form::Field;
|
||||
use craft::ui::layout_components::Stack;
|
||||
use craft::ui::list::{ListRow, ThumbAspect};
|
||||
use craft::ui::list::{ListRow, ThumbAspect, ThumbSize};
|
||||
use craft::ui::patterns::form_dialogs::{FormCx, FormDialog};
|
||||
use craft::ui::primitives::ContentPainterCx;
|
||||
use craft::ui::runtime::env::Label;
|
||||
@@ -639,6 +639,7 @@ fn recent_row(ui: &mut Ui, form: &mut SymbolForm, dark: bool) {
|
||||
let events = {
|
||||
let recent = &form.recent;
|
||||
TileGrid::new(word("Recently used symbols:"))
|
||||
.thumb_size(ThumbSize::Medium)
|
||||
.select(SelectMode::Single)
|
||||
.caption(CaptionPlace::None)
|
||||
.card_columns(RECENT_SYMBOLS)
|
||||
@@ -681,8 +682,12 @@ fn glyph_grid(ui: &mut Ui, form: &mut SymbolForm, dark: bool) -> bool {
|
||||
let font = form.shown_font().to_string();
|
||||
let events = {
|
||||
let chars = &form.chars;
|
||||
let mut grid =
|
||||
TileGrid::new(word("Symbols")).select(SelectMode::Single).max_rows(8).caption(CaptionPlace::None).selection(Bind::bound(&mut selection));
|
||||
let mut grid = TileGrid::new(word("Symbols"))
|
||||
.thumb_size(ThumbSize::Medium)
|
||||
.select(SelectMode::Single)
|
||||
.max_rows(8)
|
||||
.caption(CaptionPlace::None)
|
||||
.selection(Bind::bound(&mut selection));
|
||||
if let Some(at) = reveal {
|
||||
grid = grid.reveal(at);
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use egui_kittest::kittest::Queryable;
|
||||
use serde_json::json;
|
||||
|
||||
use super::*;
|
||||
@@ -118,6 +119,25 @@ fn symbol_dialog_inserts_with_its_font() {
|
||||
assert_eq!(f.params().unwrap(), json!({"char": "\u{2665}"}));
|
||||
}
|
||||
|
||||
/// #7326: Recently used symbols and Symbols map use compact tile sizing so the dialog
|
||||
/// fits comfortably within default window bounds without vertical overflow.
|
||||
#[test]
|
||||
fn symbol_dialog_uses_compact_tile_grids() {
|
||||
let mut a = app();
|
||||
remember_symbol(&mut a, "©", "DejaVu Sans");
|
||||
let mut h = testing::harness(a);
|
||||
let id = crate::dialogs::open(h.state_mut(), "symbol", &json!({})).expect("symbol dialog opens");
|
||||
h.run_steps(3);
|
||||
assert!(h.state().dialog_host.get_dyn(id).is_some(), "the symbol dialog is open");
|
||||
let dialog = h.get_by_role_and_label(egui::accesskit::Role::Dialog, "Symbol").rect();
|
||||
assert!(dialog.height() <= 900.0, "complete dialog should fit within default desktop viewport: {}", dialog.height());
|
||||
assert!(dialog.max.y <= 900.0, "complete dialog should not overflow viewport bottom: {}", dialog.max.y);
|
||||
let symbols = h.get_by_role_and_label(egui::accesskit::Role::ListBox, "Symbols").rect();
|
||||
assert!(symbols.height() < 500.0, "symbols grid should be compact: {}", symbols.height());
|
||||
let recent = h.get_by_role_and_label(egui::accesskit::Role::ListBox, "Recently used symbols:").rect();
|
||||
assert!(recent.height() < 80.0, "recently used symbols row should be compact: {}", recent.height());
|
||||
}
|
||||
|
||||
/// The Field dialog builds the field code from its options.
|
||||
#[test]
|
||||
fn field_dialog_builds_the_instruction() {
|
||||
@@ -355,3 +375,21 @@ fn date_time_dialog_keeps_open_and_displays_invalid_picture_error() {
|
||||
assert!(a.dialog_host.get_dyn(id).is_some(), "the dialog stays open");
|
||||
assert_eq!(a.session.doc.plain_text(wordcraft_doc::StoryRef::Body), "");
|
||||
}
|
||||
|
||||
/// #4832: Document Information fields are offered and format instructions match the chosen
|
||||
/// format.
|
||||
#[test]
|
||||
fn field_dialog_lists_the_document_information_fields() {
|
||||
let listed: Vec<&str> = FIELDS.iter().filter(|(_, cat, _)| *cat == "Document Information").map(|(n, _, _)| *n).collect();
|
||||
for name in ["COMMENTS", "KEYWORDS", "LASTSAVEDBY", "NUMCHARS", "REVNUM", "SUBJECT"] {
|
||||
assert!(listed.contains(&name), "{name} in {listed:?}");
|
||||
}
|
||||
let a = app();
|
||||
let mut f = FieldForm::new(&a);
|
||||
f.select("REVNUM");
|
||||
f.number_format = "ROMAN".into();
|
||||
f.preserve = false;
|
||||
assert_eq!(f.instruction(), r"REVNUM \* ROMAN");
|
||||
f.select("SUBJECT");
|
||||
assert_eq!(f.instruction(), "SUBJECT");
|
||||
}
|
||||
|
||||
@@ -14,9 +14,9 @@ use craft::ui::patterns::form_dialogs::FormCx;
|
||||
use craft::ui::primitives::{ContentPainterCx, TextRun};
|
||||
use craft::ui::runtime::env::{Label, LengthUnits, UnitKind};
|
||||
use craft::ui::sections::Section;
|
||||
use craft::ui::style::{Corners, SurfaceKind, TypeRole};
|
||||
use craft::ui::style::TypeRole;
|
||||
use craft::ui::text::{NumberField, TextField};
|
||||
use egui::{Rect, Ui, pos2, vec2};
|
||||
use egui::{Color32, Rect, Ui, pos2};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use wordcraft_doc::section::NumFormat;
|
||||
@@ -293,7 +293,10 @@ impl ListForm {
|
||||
/// being edited at full strength and the others faded.
|
||||
fn preview(rows: Vec<PreviewRow>, edited: usize) -> impl Fn(&ContentPainterCx, Rect) {
|
||||
move |cx: &ContentPainterCx, rect: Rect| {
|
||||
cx.surface(rect, SurfaceKind::Sunken, Corners::All);
|
||||
cx.data_shapes([
|
||||
egui::Shape::rect_filled(rect, 2.0, Color32::WHITE),
|
||||
egui::Shape::rect_stroke(rect, 2.0, egui::Stroke::new(1.0, Color32::from_gray(160)), egui::StrokeKind::Inside),
|
||||
]);
|
||||
let row = rect.height() / LEVELS as f32;
|
||||
// Positions are points, scaled so 4.5 inches fit.
|
||||
let scale = (rect.width() - 16.0).max(1.0) / 324.0;
|
||||
@@ -302,14 +305,20 @@ fn preview(rows: Vec<PreviewRow>, edited: usize) -> impl Fn(&ContentPainterCx, R
|
||||
let top = rect.top() + row * i as f32;
|
||||
let paint = |cx: &ContentPainterCx| {
|
||||
let run = TextRun::new(r.sample.clone()).role(TypeRole::Caption);
|
||||
let width = cx.with_draw(|draw| draw.layout(&run, f32::INFINITY).size().x);
|
||||
let layout = cx.with_draw(|draw| draw.layout(&run, f32::INFINITY));
|
||||
let width = layout.size().x;
|
||||
let x = x_of(r.aligned_at);
|
||||
let number_x = match r.align.as_str() {
|
||||
"center" => x - width / 2.0,
|
||||
"right" => x - width,
|
||||
_ => x,
|
||||
};
|
||||
cx.with_draw(|draw| draw.text(Rect::from_min_size(pos2(number_x, top), vec2(width + 1.0, row)), &run));
|
||||
let spare = if layout.galley.rows.len() <= 1 { (row - layout.size().y).max(0.0) } else { 0.0 };
|
||||
cx.data_shapes([egui::Shape::galley_with_override_text_color(
|
||||
pos2(number_x, top + spare / 2.0),
|
||||
layout.galley.clone(),
|
||||
Color32::BLACK,
|
||||
)]);
|
||||
let text_x = match r.follow.as_str() {
|
||||
"space" => number_x + width + 3.0,
|
||||
"nothing" => number_x + width,
|
||||
@@ -317,7 +326,7 @@ fn preview(rows: Vec<PreviewRow>, edited: usize) -> impl Fn(&ContentPainterCx, R
|
||||
};
|
||||
let bar = Rect::from_min_max(pos2(text_x, top + row / 2.0 - 2.0), pos2(rect.right() - 8.0, top + row / 2.0 + 2.0));
|
||||
if bar.width() > 0.0 {
|
||||
let draw_bar = |cx: &ContentPainterCx| cx.data_shapes([egui::Shape::rect_filled(bar, 1.0, cx.ink())]);
|
||||
let draw_bar = |cx: &ContentPainterCx| cx.data_shapes([egui::Shape::rect_filled(bar, 1.0, Color32::BLACK)]);
|
||||
cx.faded(0.45, draw_bar);
|
||||
}
|
||||
};
|
||||
@@ -789,4 +798,79 @@ mod tests {
|
||||
a.run("review.trackingOptions", json!({"moveToMark": v})).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
/// #7325: the Define New Multilevel List dialog preview renders an opaque white paper sheet
|
||||
/// with a crisp stroke outline across both Light and Dark themes, and renders level samples
|
||||
/// and text bars in fixed dark ink.
|
||||
#[test]
|
||||
fn define_new_multilevel_list_preview_opaque_paper_in_both_themes() {
|
||||
use egui::epaint::ClippedShape;
|
||||
|
||||
fn collect_shapes<'a>(shapes: &'a [ClippedShape], out: &mut Vec<&'a egui::Shape>) {
|
||||
for clipped in shapes {
|
||||
fn walk<'a>(shape: &'a egui::Shape, out: &mut Vec<&'a egui::Shape>) {
|
||||
match shape {
|
||||
egui::Shape::Vec(children) => {
|
||||
for child in children {
|
||||
walk(child, out);
|
||||
}
|
||||
}
|
||||
other => out.push(other),
|
||||
}
|
||||
}
|
||||
walk(&clipped.shape, out);
|
||||
}
|
||||
}
|
||||
|
||||
for theme in ["light", "dark"] {
|
||||
let mut a = app();
|
||||
a.run("ui.theme", json!({"value": theme})).unwrap();
|
||||
let mut h = harness(a);
|
||||
assert_eq!(h.state_mut().run("list.define", json!({})).unwrap(), json!({"pending": "defineList"}));
|
||||
h.run_steps(2);
|
||||
|
||||
let mut shapes = Vec::new();
|
||||
collect_shapes(&h.output().shapes, &mut shapes);
|
||||
|
||||
// Verify the preview paper sheet is painted as an opaque white rect
|
||||
let white_rects: Vec<_> = shapes
|
||||
.iter()
|
||||
.filter_map(|s| match s {
|
||||
egui::Shape::Rect(r)
|
||||
if r.fill == egui::Color32::WHITE && (r.rect.width() - 80.0).abs() <= 5.0 && (r.rect.height() - 48.0).abs() <= 5.0 =>
|
||||
{
|
||||
Some(r)
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert!(!white_rects.is_empty(), "{theme}: preview sheet must have an opaque white paper background");
|
||||
|
||||
// Verify crisp stroke border (StrokeKind::Inside with gray 160)
|
||||
let stroke_rects: Vec<_> = shapes
|
||||
.iter()
|
||||
.filter_map(|s| match s {
|
||||
egui::Shape::Rect(r)
|
||||
if r.stroke.color == egui::Color32::from_gray(160)
|
||||
&& (r.rect.width() - 80.0).abs() <= 5.0
|
||||
&& (r.rect.height() - 48.0).abs() <= 5.0 =>
|
||||
{
|
||||
Some(r)
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert!(!stroke_rects.is_empty(), "{theme}: preview sheet must have a crisp stroke border");
|
||||
|
||||
// Verify sample text has black override text color in both themes
|
||||
let black_text_samples: Vec<_> = shapes
|
||||
.iter()
|
||||
.filter_map(|s| match s {
|
||||
egui::Shape::Text(t) if t.override_text_color == Some(egui::Color32::BLACK) => Some(t),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert!(!black_text_samples.is_empty(), "{theme}: preview text samples must override text color with black");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -632,7 +632,7 @@ mod tests {
|
||||
use egui_kittest::kittest::Queryable;
|
||||
let mut app = app("");
|
||||
app.run("tools.autocorrect", json!({})).unwrap();
|
||||
let mut h = crate::test_harness::builder().with_size(vec2(1440.0, 900.0)).build_ui_state(
|
||||
let mut h = crate::test_harness::builder().allow_missing_glyphs().with_size(vec2(1440.0, 900.0)).build_ui_state(
|
||||
|ui, app: &mut WordApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
@@ -665,4 +665,85 @@ mod tests {
|
||||
}
|
||||
assert_eq!(h.state().session.doc.plain_text(wordcraft_doc::StoryRef::Body), "Hello. world");
|
||||
}
|
||||
|
||||
/// #3036: the Replace list says so when the filter matches nothing instead of going blank.
|
||||
#[test]
|
||||
fn the_autocorrect_list_says_when_the_filter_matches_nothing() {
|
||||
let mut app = app("");
|
||||
app.session.prefs.autocorrect.entries.push(("brb".to_string(), "be right back".to_string()));
|
||||
app.run("tools.autocorrect", json!({})).unwrap();
|
||||
fn texts(h: &egui_kittest::Harness<'_, WordApp>) -> Vec<String> {
|
||||
fn extract(shape: &egui::Shape, out: &mut Vec<String>) {
|
||||
match shape {
|
||||
egui::Shape::Text(t) => out.push(t.galley.text().to_string()),
|
||||
egui::Shape::Vec(v) => v.iter().for_each(|s| extract(s, out)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for clipped in &h.output().shapes {
|
||||
extract(&clipped.shape, &mut out);
|
||||
}
|
||||
out
|
||||
}
|
||||
let mut h = crate::test_harness::builder().allow_missing_glyphs().with_size(vec2(1440.0, 900.0)).build_ui_state(
|
||||
|ui, app: &mut WordApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
app,
|
||||
);
|
||||
for _ in 0..4 {
|
||||
h.step();
|
||||
}
|
||||
assert!(!texts(&h).iter().any(|t| t.contains("(none)")), "entries show, no hint");
|
||||
if let Some(host) = h.state_mut().dialog_host.get_mut::<FormHost<AutoCorrectForm>>() {
|
||||
host.form_mut().from = "zzz".to_string();
|
||||
} else {
|
||||
panic!("the AutoCorrect form is open");
|
||||
}
|
||||
for _ in 0..2 {
|
||||
h.step();
|
||||
}
|
||||
assert!(texts(&h).iter().any(|t| t.contains("(none)")), "no matches: the hint shows");
|
||||
}
|
||||
|
||||
/// #6046: Compare › More shows "Show changes at:" and its two choices each on one line. The
|
||||
/// column is not the grid's last, so it first gets the grid's minimum cell width; wrapped to
|
||||
/// that, its text broke after every few letters and the column stayed that narrow.
|
||||
#[test]
|
||||
fn compare_more_keeps_the_show_changes_at_column_on_one_line() {
|
||||
use egui_kittest::kittest::Queryable;
|
||||
let mut app = app("Original text.");
|
||||
app.run("review.compare", json!({})).unwrap();
|
||||
let mut h = crate::test_harness::builder().allow_missing_glyphs().with_size(vec2(1440.0, 900.0)).build_ui_state(
|
||||
|ui, app: &mut WordApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
app,
|
||||
);
|
||||
h.run_steps(4);
|
||||
h.get_by_label("More >>").click();
|
||||
h.run_steps(4);
|
||||
let one_line = h.get_by_label("New document").rect().height();
|
||||
for label in ["Word level", "Character level"] {
|
||||
let r = h.get_by_label(label).rect();
|
||||
assert!(r.height() <= one_line + 1.0, "{label} wraps: {r:?}, one line is {one_line}");
|
||||
}
|
||||
fn find_galley<'a>(shape: &'a egui::Shape, text: &str) -> Option<&'a std::sync::Arc<egui::Galley>> {
|
||||
match shape {
|
||||
egui::Shape::Text(t) if t.galley.text() == text => Some(&t.galley),
|
||||
egui::Shape::Vec(v) => v.iter().find_map(|s| find_galley(s, text)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
let galley = h.output().shapes.iter().find_map(|s| find_galley(&s.shape, "Show changes at:")).expect("Show changes at: text galley");
|
||||
assert_eq!(galley.rows.len(), 1, "Show changes at: must be on one line, but has {} rows", galley.rows.len());
|
||||
// The next column starts after the widest of them.
|
||||
let (left, right) = (h.get_by_label("Character level").rect(), h.get_by_label("Show changes in:").rect());
|
||||
assert!(right.left() >= left.right(), "the columns overlap: {left:?} {right:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -788,6 +788,7 @@ pub(crate) fn open(app: &mut WordApp, name: &str, _params: &Value, parent: Optio
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use egui_kittest::kittest::Queryable;
|
||||
use serde_json::json;
|
||||
use wordcraft_engine::Session;
|
||||
@@ -859,4 +860,42 @@ mod tests {
|
||||
crate::test_harness::frames(&mut h, 3);
|
||||
assert_ne!(h.state().session.view.ruler, ruler, "the custom group's button runs its command");
|
||||
}
|
||||
|
||||
/// #1845: typing in the command filter searches across all commands regardless of category,
|
||||
/// and Add >> places the selected command on the Quick Access Toolbar.
|
||||
#[test]
|
||||
fn command_filter_narrows_the_picker_and_add_works() {
|
||||
let mut a = app();
|
||||
a.run("tools.customizeRibbon", json!({})).unwrap();
|
||||
let id = craft::ui::dialog::dialog_id("customizeRibbon");
|
||||
assert!(a.dialog_host.open_dialogs().iter().any(|d| d.id == id), "the dialog is open");
|
||||
|
||||
let (category, current) = {
|
||||
let d = a.dialog_host.get_by_id::<RibbonDialog>(id).expect("dialog exists");
|
||||
(d.category.clone(), d.command.clone())
|
||||
};
|
||||
|
||||
// Empty filter keeps the category scope.
|
||||
let unfiltered = matching_commands(&a, &category, "");
|
||||
assert!(!unfiltered.is_empty());
|
||||
|
||||
// Typing searches every command, ignoring the category.
|
||||
let filter = "bold";
|
||||
let cmds = matching_commands(&a, &category, filter);
|
||||
assert!(cmds.iter().any(|(cmd_id, _)| cmd_id == "format.bold"));
|
||||
assert!(cmds.len() < a.session.registry.all().len());
|
||||
|
||||
let ctx = egui::Context::default();
|
||||
a.dialog_host.set_json_field(&ctx, id, "filter", json!(filter)).unwrap();
|
||||
prepare(&mut a, id);
|
||||
|
||||
let picked = select_in(&cmds, ¤t);
|
||||
assert!(!picked.is_empty());
|
||||
a.dialog_host.set_json_field(&ctx, id, "command", json!(picked)).unwrap();
|
||||
|
||||
// The dialog's Add >> adds the filtered pick to the Quick Access Toolbar.
|
||||
a.run("tools.customizeRibbon", json!({"qatAdd": picked})).unwrap();
|
||||
assert!(a.session.ribbon.qat().contains(&picked.as_str()));
|
||||
assert!(a.session.ribbon.qat().contains(&"format.bold"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,7 +29,7 @@ use craft::ui::runtime::focus::{self, FocusTarget};
|
||||
// PLAN: assumed `RuleKind` re-exported from `craft::ui::style`
|
||||
use craft::ui::style::{DataColor, RuleKind};
|
||||
use craft::ui::text::TextField;
|
||||
use craft::ui::tile_grid::{Tile, TileGrid};
|
||||
use craft::ui::tile_grid::{GridZoom, Tile, TileGrid};
|
||||
use egui::{Color32, CornerRadius, Pos2, Rect, Ui, pos2, vec2};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
@@ -315,6 +315,8 @@ fn layout_tiles(ui: &mut Ui, theme: &[Rgb], form: &mut SmartArtForm) -> bool {
|
||||
let positions: Vec<usize> = (0..shown.len()).collect();
|
||||
let current = shown.iter().position(|l| *l == form.layout).unwrap_or(0);
|
||||
let out = TileGrid::<usize>::new(tl!("Layouts").to_string())
|
||||
.thumb_size(ThumbSize::Large)
|
||||
.zoom(GridZoom::Fixed(1.4))
|
||||
.select(SelectMode::Single)
|
||||
.card_columns(3)
|
||||
// Production's picker is three tile rows high and scrolls the rest; the cap also makes the grid the one owner
|
||||
|
||||
@@ -6,15 +6,18 @@
|
||||
use craft::behavior::Anchor9;
|
||||
use craft::color_ui::ui::ColorPickerTab;
|
||||
use craft::font_manager::picker::FontPickerSettings;
|
||||
use craft::ui::buttons::{Button, ToggleButton};
|
||||
use craft::ui::contract::{Bind, Entry, Show as _, ShowContainer as _, Trigger};
|
||||
use craft::ui::buttons::{Button, ControlPlace, GroupLevel, ToggleButton};
|
||||
use craft::ui::contract::{Bind, Entry, Gap, Props as _, Show as _, ShowContainer as _, Sizing, Trigger};
|
||||
use craft::ui::controls::disclosure::DisclosureGlyph;
|
||||
use craft::ui::dialog::DialogId;
|
||||
use craft::ui::display::Picture;
|
||||
use craft::ui::display::{Picture, PictureSize, Text};
|
||||
use craft::ui::form::{Field, FieldGroup};
|
||||
use craft::ui::list::ThumbAspect;
|
||||
use craft::ui::layout_components::Row;
|
||||
use craft::ui::list::{ThumbAspect, ThumbSize};
|
||||
use craft::ui::menu::Menu;
|
||||
use craft::ui::patterns::form_dialogs::FormCx;
|
||||
use craft::ui::pickers::{ReferencePoint, ReferencePointKind, Select};
|
||||
use craft::ui::pickers::{ComboBox, ReferencePoint, ReferencePointKind, Select};
|
||||
use craft::ui::popover::Popover;
|
||||
use craft::ui::primitives::{ContentPainterCx, Glyph, IconSpec};
|
||||
use craft::ui::runtime::env::Label;
|
||||
use craft::ui::sections::Section;
|
||||
@@ -122,6 +125,15 @@ const ANCHORS: [Anchor9; 9] = [
|
||||
Anchor9::BottomRight,
|
||||
];
|
||||
|
||||
/// The alignment labels shown on the closed Alignment button, in [`CELL_ALIGNS`] order.
|
||||
const ALIGN_LABELS: [&str; 9] = ["Top left", "Top", "Top right", "Left", "Center", "Right", "Bottom left", "Bottom", "Bottom right"];
|
||||
|
||||
/// The closed Alignment button's visible label for `align` (`"Auto"` when inherited).
|
||||
fn align_label(align: &str) -> Label {
|
||||
let text = CELL_ALIGNS.iter().position(|(n, _, _)| *n == align).and_then(|i| ALIGN_LABELS.get(i).copied()).unwrap_or("Auto");
|
||||
lab(text)
|
||||
}
|
||||
|
||||
/// The `cellAlign` name for a part's alignments, empty when it sets neither.
|
||||
fn align_name(h: Option<Align>, v: Option<VAlign>) -> String {
|
||||
if h.is_none() && v.is_none() {
|
||||
@@ -167,7 +179,10 @@ fn region_of(st: &TableStyleProps, part: TablePart) -> TableRegion {
|
||||
/// The params `table.newStyle` / `table.modifyStyle` take for the dialog's state: only what
|
||||
/// changed from `basis`, part by part, so the rest stays inherited.
|
||||
pub fn table_style_params(id: Option<&str>, name: &str, based_on: &str, regions: &[TableRegion; 13], basis: &[TableRegion; 13]) -> Value {
|
||||
let mut v = json!({"name": name.trim(), "basedOn": based_on});
|
||||
let mut v = json!({"name": name.trim()});
|
||||
if !based_on.trim().is_empty() {
|
||||
v["basedOn"] = json!(based_on.trim());
|
||||
}
|
||||
for (((part, _), r), b) in PARTS.iter().zip(regions.iter()).zip(basis.iter()) {
|
||||
let ch = region_changes(r, b);
|
||||
if ch.as_object().is_some_and(|o| !o.is_empty()) {
|
||||
@@ -272,6 +287,7 @@ fn edges_on(b: &Borders, edges: &str) -> bool {
|
||||
|
||||
/// A square showing which edges a border choice draws: the drawn edges in the icon colour, the
|
||||
/// others as faint dotted guides.
|
||||
#[derive(craft::ui::contract::MemoProps)]
|
||||
struct EdgeGlyph {
|
||||
edges: &'static str,
|
||||
}
|
||||
@@ -358,7 +374,9 @@ fn paint_preview(cx: &ContentPainterCx<'_>, rect: Rect, style: Option<&TableStyl
|
||||
let Some(st) = style else { return };
|
||||
let mut shapes: Vec<Shape> = Vec::new();
|
||||
let formats: Vec<PartFormat> = TablePart::ALL.iter().map(|p| st.part(*p)).collect();
|
||||
let table = rect.shrink2(vec2(14.0, 10.0));
|
||||
let pad_x = (rect.width() * 0.035).clamp(6.0, 14.0);
|
||||
let pad_y = (rect.height() * 0.06).clamp(4.0, 10.0);
|
||||
let table = rect.shrink2(vec2(pad_x, pad_y));
|
||||
let (cw, rh) = (table.width() / COLS as f32, table.height() / ROWS as f32);
|
||||
let rgb = |c: Rgb| Color32::from_rgb(c.0, c.1, c.2);
|
||||
let tb = st.parts.borders.unwrap_or_default();
|
||||
@@ -425,16 +443,18 @@ fn paint_preview(cx: &ContentPainterCx<'_>, rect: Rect, style: Option<&TableStyl
|
||||
Some(TextColor::Rgb(c)) => rgb(c),
|
||||
_ => Color32::BLACK,
|
||||
};
|
||||
let font = egui::FontId::proportional(11.0);
|
||||
let font = egui::FontId::proportional((rh * 0.65).clamp(8.5, 11.0));
|
||||
let inset_x = (cw * 0.06).clamp(2.0, 4.0);
|
||||
let inset_y = (rh * 0.1).clamp(1.0, 2.0);
|
||||
let (ax, x) = match h {
|
||||
Some(Align::Center) => (egui::Align::Center, cell.center().x),
|
||||
Some(Align::Right) => (egui::Align::Max, cell.right() - 4.0),
|
||||
_ => (egui::Align::Min, cell.left() + 4.0),
|
||||
Some(Align::Right) => (egui::Align::Max, cell.right() - inset_x),
|
||||
_ => (egui::Align::Min, cell.left() + inset_x),
|
||||
};
|
||||
let (ay, y) = match v {
|
||||
Some(VAlign::Center) => (egui::Align::Center, cell.center().y),
|
||||
Some(VAlign::Bottom) => (egui::Align::Max, cell.bottom() - 2.0),
|
||||
_ => (egui::Align::Min, cell.top() + 2.0),
|
||||
Some(VAlign::Bottom) => (egui::Align::Max, cell.bottom() - inset_y),
|
||||
_ => (egui::Align::Min, cell.top() + inset_y),
|
||||
};
|
||||
let galley = cx.painter.layout_no_wrap(txt.to_string(), font, color);
|
||||
let r = egui::Align2([ax, ay]).anchor_size(pos2(x, y), galley.size());
|
||||
@@ -518,7 +538,7 @@ impl TableStyleForm {
|
||||
FieldGroup::new(lab("Table style")).show(ui, |ui, _| {
|
||||
let name_label = lab("Name:");
|
||||
Field::new(name_label.clone()).show(ui, |ui, _| {
|
||||
TextField::new(name_label.clone(), Bind::bound(&mut self.name)).show(ui);
|
||||
TextField::new(name_label.clone(), Bind::bound(&mut self.name)).width_chars(30).show(ui);
|
||||
});
|
||||
let entries: Vec<Entry<usize>> = self.bases.iter().enumerate().map(|(i, b)| Entry::new(i, b.name.clone())).collect();
|
||||
let current = self.bases.iter().position(|b| b.id == self.based_on).unwrap_or(usize::MAX);
|
||||
@@ -544,72 +564,172 @@ impl TableStyleForm {
|
||||
let Self { region, regions, pen, palette, catalog, font_settings, .. } = self;
|
||||
let Some(r) = regions.get_mut(*region) else { return };
|
||||
Section::fixed(lab("Formatting")).show(ui, |ui, _| {
|
||||
FieldGroup::new(lab("Formatting")).show(ui, |ui, _| {
|
||||
// Row 1: Font, size, and B / I / U toggles.
|
||||
Row::new().gap(Gap::Inline).wrap(true).show(ui, |ui, _| {
|
||||
let sizes: Vec<Entry<String>> = wordcraft_engine::cmd::format::SIZES
|
||||
.iter()
|
||||
.map(|s| {
|
||||
let s = size_text(*s);
|
||||
Entry::new(s.clone(), s)
|
||||
})
|
||||
.collect();
|
||||
if let Some(catalog) = catalog.get() {
|
||||
let font_label = lab("Font:");
|
||||
Field::new(font_label.clone()).show(ui, |ui, _| {
|
||||
font_picker(font_label.clone(), Bind::bound(&mut r.font), catalog, Bind::bound(&mut *font_settings), &[], None).show(ui);
|
||||
Row::new().gap(Gap::Inline).show(ui, |ui, _| {
|
||||
let font_label = lab("Font:");
|
||||
Text::new(font_label.clone()).show(ui);
|
||||
craft::ui::runtime::env::with_env(
|
||||
ui,
|
||||
|overrides| {
|
||||
overrides.values.set(ControlPlace::Ribbon);
|
||||
},
|
||||
|ui| {
|
||||
font_picker(font_label, Bind::bound(&mut r.font), catalog, Bind::bound(&mut *font_settings), &[], None).show(ui);
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
// Text, so an empty box means the size is inherited.
|
||||
let size_label = lab("Size:");
|
||||
Field::new(size_label.clone()).show(ui, |ui, _| {
|
||||
TextField::new(size_label.clone(), Bind::bound(&mut r.size)).show(ui);
|
||||
Row::new().gap(Gap::Inline).show(ui, |ui, _| {
|
||||
let size_label = lab("Size:");
|
||||
Text::new(size_label.clone()).show(ui);
|
||||
craft::ui::runtime::env::with_env(
|
||||
ui,
|
||||
|overrides| {
|
||||
overrides.values.set(ControlPlace::Ribbon);
|
||||
},
|
||||
|ui| {
|
||||
ComboBox::new(size_label, Bind::bound(&mut r.size), &sizes).show(ui);
|
||||
},
|
||||
);
|
||||
});
|
||||
Field::new(lab("Font style:")).show(ui, |ui, _| {
|
||||
ui.horizontal(|ui| {
|
||||
ToggleButton::new(lab("Bold"), Bind::bound(&mut r.bold)).show(ui);
|
||||
ToggleButton::new(lab("Italic"), Bind::bound(&mut r.italic)).show(ui);
|
||||
ToggleButton::new(lab("Underline"), Bind::bound(&mut r.underline)).show(ui);
|
||||
});
|
||||
|
||||
// Compact icon-only labels inside standard secondary (framed) toggle buttons so B / I / U
|
||||
// keep full icon size and visible button outlines.
|
||||
craft::ui::runtime::env::with_env(
|
||||
ui,
|
||||
|overrides| {
|
||||
overrides.values.set(GroupLevel::Compact);
|
||||
},
|
||||
|ui| {
|
||||
Row::new().gap(Gap::Tight).show(ui, |ui, _| {
|
||||
ToggleButton::new(lab("Bold"), Bind::bound(&mut r.bold)).icon(crate::icons::id("bold")).tooltip(lab("Bold")).show(ui);
|
||||
ToggleButton::new(lab("Italic"), Bind::bound(&mut r.italic))
|
||||
.icon(crate::icons::id("italic"))
|
||||
.tooltip(lab("Italic"))
|
||||
.show(ui);
|
||||
ToggleButton::new(lab("Underline"), Bind::bound(&mut r.underline))
|
||||
.icon(crate::icons::id("underline"))
|
||||
.tooltip(lab("Underline"))
|
||||
.show(ui);
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
// Row 2: Font color and Fill color.
|
||||
Row::new().gap(Gap::Section).wrap(true).show(ui, |ui, _| {
|
||||
Row::new().gap(Gap::Inline).show(ui, |ui, _| {
|
||||
Text::new(lab("Font color:")).show(ui);
|
||||
if color_field(ui, &lab("Font color:"), &mut r.color, &ColorFieldEmpty::NoColor, palette).more_colors {
|
||||
asks.push(Asks::Color { field: "color", current: Rgb::parse(&r.color), tab: ColorPickerTab::Standard });
|
||||
}
|
||||
});
|
||||
if color_field(ui, &lab("Font color:"), &mut r.color, &ColorFieldEmpty::NoColor, palette).more_colors {
|
||||
asks.push(Asks::Color { field: "color", current: Rgb::parse(&r.color), tab: ColorPickerTab::Standard });
|
||||
}
|
||||
Row::new().gap(Gap::Inline).show(ui, |ui, _| {
|
||||
Text::new(lab("Fill color:")).show(ui);
|
||||
if color_field(ui, &lab("Fill color:"), &mut r.fill, &ColorFieldEmpty::NoColor, palette).more_colors {
|
||||
asks.push(Asks::Color { field: "fill", current: Rgb::parse(&r.fill), tab: ColorPickerTab::Standard });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Row 3: Border pen style, width, and color.
|
||||
Row::new().gap(Gap::Inline).wrap(true).show(ui, |ui, _| {
|
||||
let styles: Vec<Entry<usize>> = LINE_STYLES.iter().enumerate().map(|(i, (_, n))| Entry::new(i, lab(n))).collect();
|
||||
let current = LINE_STYLES.iter().position(|(s, _)| *s == pen.style).unwrap_or(0);
|
||||
if let Some((s, _)) = pick_index(ui, "Style:", &styles, current).and_then(|i| LINE_STYLES.get(i)) {
|
||||
pen.style = *s;
|
||||
}
|
||||
Row::new().gap(Gap::Inline).show(ui, |ui, _| {
|
||||
Text::new(lab("Style:")).show(ui);
|
||||
if let Some((s, _)) = Select::new(lab("Style:"), Bind::given(current), &styles)
|
||||
.sizing(Sizing::Content)
|
||||
.show(ui)
|
||||
.value()
|
||||
.copied()
|
||||
.and_then(|i| LINE_STYLES.get(i))
|
||||
{
|
||||
pen.style = *s;
|
||||
}
|
||||
});
|
||||
|
||||
let widths: Vec<Entry<usize>> =
|
||||
WIDTHS.iter().enumerate().map(|(i, w)| Entry::new(i, crate::i18n::fmt(tl!("{n} pt"), &[("n", &w.to_string())]))).collect();
|
||||
let current = WIDTHS.iter().position(|w| *w == pen.width).unwrap_or(usize::MAX);
|
||||
if let Some(w) = pick_index(ui, "Width:", &widths, current).and_then(|i| WIDTHS.get(i)) {
|
||||
pen.width = *w;
|
||||
}
|
||||
if color_field(ui, &lab("Color:"), &mut pen.color, &ColorFieldEmpty::NoColor, palette).more_colors {
|
||||
asks.push(Asks::Color { field: "pen", current: Rgb::parse(&pen.color), tab: ColorPickerTab::Standard });
|
||||
}
|
||||
Field::new(lab("Borders:")).show(ui, |ui, _| {
|
||||
let button = Button::new(lab("Borders")).show(ui);
|
||||
let entries: Vec<Entry<usize>> = EDGES
|
||||
.iter()
|
||||
.zip(EDGE_GLYPHS.iter())
|
||||
.enumerate()
|
||||
.map(|(i, ((label, edges), glyph))| {
|
||||
Entry::new(i, lab(label)).icon(IconSpec::glyph(glyph)).checked(edges_on(&r.borders, edges))
|
||||
})
|
||||
.collect();
|
||||
let picked = Menu::new(lab("Borders")).opened_by(&button, Trigger::Press).pick(ui, &entries).picked;
|
||||
if let Some((_, edges)) = picked.and_then(|i| EDGES.get(i)) {
|
||||
pick_edges(&mut r.borders, edges, pen);
|
||||
Row::new().gap(Gap::Inline).show(ui, |ui, _| {
|
||||
Text::new(lab("Width:")).show(ui);
|
||||
if let Some(w) = Select::new(lab("Width:"), Bind::given(current), &widths)
|
||||
.sizing(Sizing::Content)
|
||||
.show(ui)
|
||||
.value()
|
||||
.copied()
|
||||
.and_then(|i| WIDTHS.get(i))
|
||||
{
|
||||
pen.width = *w;
|
||||
}
|
||||
});
|
||||
if color_field(ui, &lab("Fill color:"), &mut r.fill, &ColorFieldEmpty::NoColor, palette).more_colors {
|
||||
asks.push(Asks::Color { field: "fill", current: Rgb::parse(&r.fill), tab: ColorPickerTab::Standard });
|
||||
}
|
||||
// The grid is row by row from the top left, as `CELL_ALIGNS` is.
|
||||
let current = CELL_ALIGNS.iter().position(|(n, _, _)| *n == r.align).and_then(|i| ANCHORS.get(i)).copied();
|
||||
let picked =
|
||||
ReferencePoint::new(lab("Alignment:"), Bind::given(current)).kind(ReferencePointKind::Alignment).show(ui).value().copied();
|
||||
if let Some(anchor) = picked {
|
||||
// Picking the selected cell again clears the alignment.
|
||||
r.align = anchor
|
||||
.and_then(|a| ANCHORS.iter().position(|x| *x == a))
|
||||
.and_then(|i| CELL_ALIGNS.get(i))
|
||||
.map(|(n, _, _)| n.to_string())
|
||||
.unwrap_or_default();
|
||||
|
||||
Row::new().gap(Gap::Inline).show(ui, |ui, _| {
|
||||
Text::new(lab("Color:")).show(ui);
|
||||
if color_field(ui, &lab("Color:"), &mut pen.color, &ColorFieldEmpty::NoColor, palette).more_colors {
|
||||
asks.push(Asks::Color { field: "pen", current: Rgb::parse(&pen.color), tab: ColorPickerTab::Standard });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Row 4: Borders menu and compact Alignment dropdown opening the 3×3 alignment grid.
|
||||
Row::new().gap(Gap::Section).wrap(true).show(ui, |ui, _| {
|
||||
let button = Button::new(lab("Borders:")).painted(lab("Borders")).trailing_icon(DisclosureGlyph::menu_button()).show(ui);
|
||||
let entries: Vec<Entry<usize>> = EDGES
|
||||
.iter()
|
||||
.zip(EDGE_GLYPHS.iter())
|
||||
.enumerate()
|
||||
.map(|(i, ((label, edges), glyph))| Entry::new(i, lab(label)).icon(IconSpec::glyph(glyph)).checked(edges_on(&r.borders, edges)))
|
||||
.collect();
|
||||
let picked = Menu::new(lab("Borders")).opened_by(&button, Trigger::Press).pick(ui, &entries).picked;
|
||||
if let Some((_, edges)) = picked.and_then(|i| EDGES.get(i)) {
|
||||
pick_edges(&mut r.borders, edges, pen);
|
||||
}
|
||||
|
||||
Row::new().gap(Gap::Inline).show(ui, |ui, _| {
|
||||
Text::new(lab("Alignment:")).show(ui);
|
||||
let open_id = ui.make_persistent_id("tstyle_align_open");
|
||||
let mut open = ui.ctx().data(|d| d.get_temp::<bool>(open_id)).unwrap_or(false);
|
||||
let align_text = align_label(&r.align);
|
||||
let align_spoken = Label::from(format!("{} {}", tl!("Alignment:"), align_text.as_str()));
|
||||
let button = Button::new(align_spoken)
|
||||
.painted(align_text)
|
||||
.icon(crate::icons::id("cellAlign"))
|
||||
.trailing_icon(DisclosureGlyph::menu_button())
|
||||
.show(ui);
|
||||
if button.clicked() {
|
||||
open = !open;
|
||||
}
|
||||
Popover::new(lab("Alignment"), Bind::bound(&mut open)).opened_by(&button).show(ui, |ui, cx| {
|
||||
// The grid is row by row from the top left, as `CELL_ALIGNS` is.
|
||||
let current = CELL_ALIGNS.iter().position(|(n, _, _)| *n == r.align).and_then(|i| ANCHORS.get(i)).copied();
|
||||
let picked = ReferencePoint::new(lab("Alignment:"), Bind::given(current))
|
||||
.kind(ReferencePointKind::Alignment)
|
||||
.show(ui)
|
||||
.value()
|
||||
.copied();
|
||||
if let Some(anchor) = picked {
|
||||
// Picking the selected cell again clears the alignment.
|
||||
r.align = anchor
|
||||
.and_then(|a| ANCHORS.iter().position(|x| *x == a))
|
||||
.and_then(|i| CELL_ALIGNS.get(i))
|
||||
.map(|(n, _, _)| n.to_string())
|
||||
.unwrap_or_default();
|
||||
cx.request_close();
|
||||
}
|
||||
});
|
||||
ui.ctx().data_mut(|d| d.insert_temp(open_id, open));
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -651,7 +771,9 @@ impl WordForm for TableStyleForm {
|
||||
let look = look_for(self.look, self.part());
|
||||
let preview = self.preview.as_ref();
|
||||
Section::fixed(lab("Preview")).show(ui, |ui, _| {
|
||||
Picture::painter(lab("Table style preview"), ThumbAspect::new(36, 13), |cx, rect| paint_preview(cx, rect, preview, &look)).show(ui);
|
||||
Picture::painter(lab("Table style preview"), ThumbAspect::new(36, 13), |cx, rect| paint_preview(cx, rect, preview, &look))
|
||||
.extent(PictureSize::Sample(ThumbSize::Large))
|
||||
.show(ui);
|
||||
});
|
||||
true
|
||||
}
|
||||
@@ -776,6 +898,191 @@ mod tests {
|
||||
)
|
||||
}
|
||||
|
||||
/// Alignment choices expose their names and current selection, and can be toggled through the dialog.
|
||||
#[test]
|
||||
fn alignment_buttons_expose_names_selection_and_clicks() {
|
||||
use crate::dialogs::host::FormHost;
|
||||
use egui::accesskit::{Role, Toggled};
|
||||
use egui_kittest::kittest::NodeT;
|
||||
|
||||
let mut app = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default());
|
||||
app.run("insert.table", json!({"rows": 4, "cols": 3})).unwrap();
|
||||
app.run("table.newStyle", json!({"name": "AlignTest"})).unwrap();
|
||||
let dialog_id = crate::dialogs::open(&mut app, "modifyTableStyle", &json!({})).expect("dialog opened");
|
||||
// Keep the background ribbon's character controls out of the dialog's label queries.
|
||||
app.ui.tab = "Insert".into();
|
||||
let mut h = harness(app);
|
||||
steps(&mut h);
|
||||
|
||||
// Open the Alignment popover, verify labels and unchecked state, then pick "Bottom right".
|
||||
h.get_by_role_and_label(Role::Button, "Alignment: Auto").click();
|
||||
steps(&mut h);
|
||||
assert_eq!(h.get_by_role_and_label(Role::RadioButton, "Bottom right").accesskit_node().toggled(), Some(Toggled::False));
|
||||
assert!(!h.get_by_role_and_label(Role::RadioButton, "Center").accesskit_node().is_disabled());
|
||||
|
||||
// Click "Bottom right", check align == "bottomRight" and button exposes the value.
|
||||
h.get_by_role_and_label(Role::RadioButton, "Bottom right").click();
|
||||
steps(&mut h);
|
||||
{
|
||||
let host = h.state().dialog_host.get_by_id::<FormHost<TableStyleForm>>(dialog_id).expect("form is hosted");
|
||||
let r = &host.form().regions[host.form().region];
|
||||
assert_eq!(r.align, "bottomRight");
|
||||
}
|
||||
|
||||
// Reopen Alignment via its updated accessible name, verify "Bottom right" is checked, click again to clear it.
|
||||
h.get_by_role_and_label(Role::Button, "Alignment: Bottom right").click();
|
||||
steps(&mut h);
|
||||
assert_eq!(h.get_by_role_and_label(Role::RadioButton, "Bottom right").accesskit_node().toggled(), Some(Toggled::True));
|
||||
h.get_by_role_and_label(Role::RadioButton, "Bottom right").click();
|
||||
steps(&mut h);
|
||||
{
|
||||
let host = h.state().dialog_host.get_by_id::<FormHost<TableStyleForm>>(dialog_id).expect("form is hosted");
|
||||
let r = &host.form().regions[host.form().region];
|
||||
assert_eq!(r.align, "");
|
||||
}
|
||||
assert!(h.query_by_role_and_label(Role::Button, "Alignment: Auto").is_some());
|
||||
}
|
||||
|
||||
/// #7692: empty or whitespace basedOn must be omitted so build_modified does not reject unbased styles.
|
||||
#[test]
|
||||
fn table_style_params_omits_empty_based_on() {
|
||||
let regions: [TableRegion; 13] = std::array::from_fn(|_| TableRegion::default());
|
||||
let basis: [TableRegion; 13] = std::array::from_fn(|_| TableRegion::default());
|
||||
let params = table_style_params(Some("tableGrid"), "Table Grid", "", ®ions, &basis);
|
||||
assert!(!params.as_object().unwrap().contains_key("basedOn"));
|
||||
|
||||
let params_whitespace = table_style_params(Some("tableGrid"), "Table Grid", " ", ®ions, &basis);
|
||||
assert!(!params_whitespace.as_object().unwrap().contains_key("basedOn"));
|
||||
|
||||
let params_with_base = table_style_params(None, "New Style", "tableGrid", ®ions, &basis);
|
||||
assert_eq!(params_with_base.get("basedOn").and_then(|v| v.as_str()), Some("tableGrid"));
|
||||
}
|
||||
|
||||
/// Choosing the document default font or size on a sub-part after changing Whole Table must
|
||||
/// still emit that part's explicit override instead of treating the default as unchanged.
|
||||
#[test]
|
||||
fn choosing_default_font_and_size_on_sub_part_overrides_whole_table() {
|
||||
use crate::dialogs::host::FormHost;
|
||||
use egui::accesskit::Role;
|
||||
use wordcraft_doc::CharProps;
|
||||
|
||||
let mut app = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default());
|
||||
app.run("insert.table", json!({"rows": 2, "cols": 2})).unwrap();
|
||||
let default_chr = app.session.doc.styles.resolve_char(None, &CharProps::default());
|
||||
let default_size = size_text(default_chr.size);
|
||||
let other_size = if (default_chr.size - 9.0).abs() < 0.1 { "14".to_string() } else { "9".to_string() };
|
||||
let other_font = "Georgia".to_string();
|
||||
|
||||
let dialog_id = crate::dialogs::open(&mut app, "modifyTableStyle", &json!({})).expect("dialog opened");
|
||||
app.ui.tab = "Insert".into();
|
||||
let mut h = harness(app);
|
||||
steps(&mut h);
|
||||
|
||||
// Set Whole Table font and size to non-default values, then switch to Header Row and pick
|
||||
// the document's own default font and size explicitly.
|
||||
{
|
||||
let host = h.state_mut().dialog_host.get_mut_by_id::<FormHost<TableStyleForm>>(dialog_id).expect("form is hosted");
|
||||
host.form_mut().regions[part_index(TablePart::WholeTable)].font = other_font.clone();
|
||||
host.form_mut().regions[part_index(TablePart::WholeTable)].size = other_size.clone();
|
||||
}
|
||||
steps(&mut h);
|
||||
h.get_by_label("Apply formatting to:").click();
|
||||
steps(&mut h);
|
||||
h.get_by_label("Header Row").click();
|
||||
steps(&mut h);
|
||||
h.get_by_role_and_label(Role::ComboBox, "Size:").click();
|
||||
steps(&mut h);
|
||||
for _ in 0..default_size.len().max(4) {
|
||||
h.key_press(egui::Key::Backspace);
|
||||
}
|
||||
h.event(egui::Event::Text(default_size));
|
||||
h.key_press(egui::Key::Enter);
|
||||
steps(&mut h);
|
||||
{
|
||||
let host = h.state_mut().dialog_host.get_mut_by_id::<FormHost<TableStyleForm>>(dialog_id).expect("form is hosted");
|
||||
host.form_mut().regions[part_index(TablePart::FirstRow)].font = default_chr.font.clone();
|
||||
}
|
||||
steps(&mut h);
|
||||
|
||||
h.get_by_label("OK").click();
|
||||
steps(&mut h);
|
||||
assert!(h.state().dialog_host.open_dialogs().is_empty(), "OK closes the dialog");
|
||||
|
||||
let st = h.state().session.doc.styles.get("TableGrid").cloned().unwrap();
|
||||
assert_eq!(st.table_part(TablePart::WholeTable).chr.font.as_deref(), Some(other_font.as_str()));
|
||||
assert_eq!(st.table_part(TablePart::FirstRow).chr.font.as_deref(), Some(default_chr.font.as_str()));
|
||||
assert_eq!(st.table_part(TablePart::FirstRow).chr.size, Some(default_chr.size));
|
||||
}
|
||||
|
||||
/// #7692: modifying the default Table Grid style (which has no base style) sends no empty basedOn
|
||||
/// and OK closes successfully without a blank preview or command rejection.
|
||||
#[test]
|
||||
fn modify_table_grid_style_omits_empty_based_on_and_does_not_fail() {
|
||||
use crate::dialogs::host::FormHost;
|
||||
|
||||
let mut app = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default());
|
||||
app.run("insert.table", json!({"rows": 2, "cols": 2})).unwrap();
|
||||
let dialog_id = crate::dialogs::open(&mut app, "modifyTableStyle", &json!({})).expect("dialog opened");
|
||||
app.ui.tab = "Insert".into();
|
||||
let mut h = harness(app);
|
||||
steps(&mut h);
|
||||
{
|
||||
let host = h.state().dialog_host.get_by_id::<FormHost<TableStyleForm>>(dialog_id).expect("form is hosted");
|
||||
assert!(host.form().based_on.is_empty(), "Table Grid has no base style");
|
||||
assert!(host.form().preview.is_some(), "Table Grid preview must build without a base style");
|
||||
let r = &host.form().regions[host.form().region];
|
||||
assert!(r.font.is_empty(), "unset font stays empty (inherited) until edited");
|
||||
assert!(r.size.is_empty(), "unset size stays empty (inherited) until edited");
|
||||
let params = host.form().params();
|
||||
let obj = params.as_object().unwrap();
|
||||
assert!(!obj.contains_key("basedOn"), "empty basedOn must be omitted");
|
||||
assert!(!obj.contains_key("wholeTable"), "untouched style sends no region changes");
|
||||
}
|
||||
{
|
||||
use egui::accesskit::Role;
|
||||
|
||||
let dialog = h.get_by_role_and_label(Role::Dialog, "Modify Table Style").rect();
|
||||
assert!(h.query_by_role_and_label(Role::Heading, "Formatting").is_some(), "Formatting section heading is exposed");
|
||||
assert!(h.query_by_role_and_label(Role::Label, "Font:").is_some(), "Font visible label is exposed");
|
||||
assert!(h.query_by_role_and_label(Role::Label, "Size:").is_some(), "Size visible label is exposed");
|
||||
let font = h.get_by_role_and_label(Role::ComboBox, "Font:").rect();
|
||||
let size = h.get_by_role_and_label(Role::ComboBox, "Size:").rect();
|
||||
let underline = h.get_by_role_and_label(Role::Button, "Underline").rect();
|
||||
let font_color = h.query_all_by_label("Font color: No Color").next().expect("font color field").rect();
|
||||
let fill = h.query_all_by_label("Fill color: No Color").next().expect("fill color field").rect();
|
||||
let borders = h.get_by_role_and_label(Role::Button, "Borders:").rect();
|
||||
let align = h.get_by_role_and_label(Role::Button, "Alignment: Auto").rect();
|
||||
assert!(size.width() < font.width(), "Size box should be narrower than Font box: size={size:?} font={font:?}");
|
||||
for (name, rect) in
|
||||
[("Underline", underline), ("Font color", font_color), ("Fill color", fill), ("Borders", borders), ("Alignment", align)]
|
||||
{
|
||||
assert!(rect.right() <= dialog.right(), "{name} must fit inside the dialog without overflowing: rect={rect:?} dialog={dialog:?}");
|
||||
}
|
||||
assert!(
|
||||
(borders.center().y - align.center().y).abs() < (borders.height() + align.height()) * 0.25
|
||||
&& (borders.height() - align.height()).abs() < borders.height() * 0.25,
|
||||
"Borders and Alignment should line up compactly on one row: borders={borders:?} align={align:?}"
|
||||
);
|
||||
assert!(
|
||||
(font_color.center().y - fill.center().y).abs() < (font_color.height() + fill.height()) * 0.25,
|
||||
"Font color and Fill color should share one row: font_color={font_color:?} fill={fill:?}"
|
||||
);
|
||||
let preview = h.get_by_role_and_label(Role::Image, "Table style preview").rect();
|
||||
let controls_height = align.bottom() - font.top();
|
||||
assert!(
|
||||
preview.height() > font.height() * 2.0 && preview.height() < controls_height && preview.width() > preview.height() * 2.0,
|
||||
"preview should be a landscape compact sample taller than a control row and shorter than the formatting controls: preview={preview:?} font={font:?} controls_height={controls_height}"
|
||||
);
|
||||
assert!(
|
||||
preview.right() <= dialog.right() && preview.bottom() <= dialog.bottom(),
|
||||
"preview must stay inside the dialog: preview={preview:?} dialog={dialog:?}"
|
||||
);
|
||||
}
|
||||
h.get_by_label("OK").click();
|
||||
steps(&mut h);
|
||||
assert!(h.state().dialog_host.open_dialogs().is_empty(), "OK closes the dialog");
|
||||
}
|
||||
|
||||
/// #714: picking a part under "Apply formatting to" and changing it edits that part (here the
|
||||
/// even banded rows) and no other.
|
||||
#[test]
|
||||
@@ -796,10 +1103,14 @@ mod tests {
|
||||
steps(&mut h);
|
||||
for label in ["Bold", "Italic", "Underline"] {
|
||||
// An off toggle button reports no toggled state; only an on one says `True`.
|
||||
assert_ne!(h.get_by_label(label).accesskit_node().toggled(), Some(Toggled::True), "{label} starts off");
|
||||
h.get_by_label(label).click();
|
||||
assert_ne!(
|
||||
h.get_by_role_and_label(egui::accesskit::Role::Button, label).accesskit_node().toggled(),
|
||||
Some(Toggled::True),
|
||||
"{label} starts off"
|
||||
);
|
||||
h.get_by_role_and_label(egui::accesskit::Role::Button, label).click();
|
||||
steps(&mut h);
|
||||
assert_eq!(h.get_by_label(label).accesskit_node().toggled(), Some(Toggled::True));
|
||||
assert_eq!(h.get_by_role_and_label(egui::accesskit::Role::Button, label).accesskit_node().toggled(), Some(Toggled::True));
|
||||
}
|
||||
h.get_by_label("OK").click();
|
||||
steps(&mut h);
|
||||
|
||||
@@ -108,12 +108,19 @@ pub(crate) fn settle(app: &mut WordApp, ctx: &Context) {
|
||||
/// More Colors targets, so none outlives its dialog.
|
||||
pub(crate) fn close_all(app: &mut WordApp, ctx: &Context) {
|
||||
let ids: Vec<DialogId> = app.dialog_host.open_dialogs().into_iter().rev().map(|dialog| dialog.id).collect();
|
||||
let had_dialogs = !ids.is_empty();
|
||||
for id in ids {
|
||||
app.dialog_host.cancel_by_id(ctx, id);
|
||||
}
|
||||
settle(app, ctx);
|
||||
// PLAN: assumed `WordApp::more_colors` with `clear()` (ribbon-w11, rb.A4's target map)
|
||||
app.more_colors.clear();
|
||||
if had_dialogs && !app.file_dialog_open() && !app.ui.backstage {
|
||||
app.canvas.focus_page(ctx);
|
||||
app.canvas.focus_pending = true;
|
||||
app.canvas.focus_page_after_pass();
|
||||
ctx.request_repaint();
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens the About dialog on `tab`. A second About while one is open opens nothing: the first keeps the input.
|
||||
@@ -699,14 +706,7 @@ pub(crate) mod testing {
|
||||
|
||||
/// A harness that runs the app's logic and UI each frame in a 1440×900 window.
|
||||
pub(crate) fn harness(app: WordApp) -> Harness<'static, WordApp> {
|
||||
crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|
||||
|ui, app: &mut WordApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
crate::test_harness::driver_logic(&ctx, app);
|
||||
app.ui(ui);
|
||||
},
|
||||
app,
|
||||
)
|
||||
crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_eframe(|_| app)
|
||||
}
|
||||
|
||||
/// Confirms the dialog `id` as OK does and runs the passes it takes to file the held OK and finish: the held OK
|
||||
|
||||
@@ -950,6 +950,83 @@ fn opened_paper(h: &mut egui_kittest::Harness<'_, WordApp>) -> (f32, f32) {
|
||||
paper
|
||||
}
|
||||
|
||||
/// #1433: in a right-to-left interface, typing a number wider than the field's column into a
|
||||
/// margin spin button keeps the dialog the same width; clicking the visible end of the blurred
|
||||
/// field enters editing again, and entering a normal value restores the field.
|
||||
#[test]
|
||||
fn page_setup_rtl_large_margin_can_be_edited_again_after_blur() {
|
||||
use egui::accesskit::Role;
|
||||
let mut app = app_with("Page");
|
||||
app.run("ui.dialog", json!({"name": "pageSetup"})).unwrap();
|
||||
let ar = crate::i18n::fixture_lang("ar", "\tMargins\tMargins\n");
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|
||||
move |ui, app: &mut WordApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
// Draw the actual dialog in a fixture language even without embedded catalogs.
|
||||
crate::i18n::apply_language(ar);
|
||||
ctx.global_style_mut(|s| s.right_to_left = true);
|
||||
assert!(crate::i18n::current().rtl() && ctx.global_style().right_to_left);
|
||||
craft::ui::runtime::env::with_env(ui, |o| o.direction = Some(craft::i18n::Direction::Rtl), |ui| app.ui(ui));
|
||||
ctx.global_style_mut(|s| s.right_to_left = false);
|
||||
crate::i18n::apply_language(crate::i18n::Lang::EN);
|
||||
},
|
||||
app,
|
||||
);
|
||||
h.run_steps(4);
|
||||
let initial = h.get_by_role_and_label(Role::SpinButton, "Bottom").rect();
|
||||
assert!(h.get_by_role_and_label(Role::SpinButton, "Top").rect().center().x > initial.center().x, "the form is mirrored");
|
||||
let window = |h: &egui_kittest::Harness<'_, WordApp>| h.get_by_role_and_label(Role::Dialog, "Page Setup").rect();
|
||||
let before = window(&h).width();
|
||||
let id = id_of(h.state(), "pageSetup");
|
||||
let initial_bottom = h.state().dialog_host.get_by_id::<PageSetupHost>(id).unwrap().setup.margins.bottom;
|
||||
assert!(initial_bottom < craft::pages::setup::MAX_PAGE_SIDE, "initial margin starts below the upper bound: {initial_bottom}");
|
||||
h.get_by_role_and_label(Role::SpinButton, "Bottom").click();
|
||||
h.run_steps(2);
|
||||
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
|
||||
h.event(egui::Event::Paste(format!("1{}", "0".repeat(36))));
|
||||
h.run_steps(3);
|
||||
let id = id_of(h.state(), "pageSetup");
|
||||
let value = h.state().dialog_host.get_by_id::<PageSetupHost>(id).unwrap().setup.margins.bottom;
|
||||
assert!(
|
||||
value > initial_bottom && (value - craft::pages::setup::MAX_PAGE_SIDE).abs() < 1e-3,
|
||||
"oversized margin paste should be accepted and clamped to MAX_PAGE_SIDE: got {value}"
|
||||
);
|
||||
// While the 37-digit text is in the field, the dialog does not blow up to the typed text width.
|
||||
assert!(window(&h).width() <= before + 15.0);
|
||||
h.key_press(egui::Key::Tab);
|
||||
h.run_steps(3);
|
||||
let id = id_of(h.state(), "pageSetup");
|
||||
assert_eq!(h.state().dialog_host.get_by_id::<PageSetupHost>(id).unwrap().setup.margins.bottom, value);
|
||||
let field = h.get_by_role_and_label(Role::SpinButton, "Bottom");
|
||||
assert!(!field.is_focused());
|
||||
let wide = field.rect();
|
||||
let visible = wide.intersect(initial).intersect(window(&h));
|
||||
assert!(visible.is_positive());
|
||||
// The inline notice "Margins do not fit" may add a few points, but the dialog does not blow up to the typed text width.
|
||||
assert!(window(&h).width() <= before + 15.0);
|
||||
// The AccessKit bounds include clipped text: click the visible part, not their centre.
|
||||
let pos = visible.center();
|
||||
h.event(egui::Event::PointerMoved(pos));
|
||||
for pressed in [true, false] {
|
||||
h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE });
|
||||
}
|
||||
h.run_steps(3);
|
||||
assert!(h.get_by_role_and_label(Role::SpinButton, "Bottom").is_focused(), "the visible field enters editing");
|
||||
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
|
||||
h.event(egui::Event::Paste("2".into()));
|
||||
h.run_steps(3);
|
||||
h.key_press(egui::Key::Tab);
|
||||
h.run_steps(3);
|
||||
let id = id_of(h.state(), "pageSetup");
|
||||
let bottom = h.state().dialog_host.get_by_id::<PageSetupHost>(id).unwrap().setup.margins.bottom;
|
||||
let unit = crate::options::unit_kind(h.state().session.units());
|
||||
let expected =
|
||||
unit.to_pixels(2.0, 0.0, craft::ui::runtime::env::UnitKind::POINTS_PER_INCH, craft::ui::runtime::env::UnitKind::POINTS_PER_INCH).unwrap();
|
||||
assert!((bottom - expected).abs() < 1e-3, "the field accepts a normal value again: got {bottom}, expected {expected}");
|
||||
assert!(window(&h).width() <= before + 2.0);
|
||||
}
|
||||
|
||||
/// #1433: Page Setup's Paper size shows the named size the section has, in either
|
||||
/// orientation, and Custom size (None) for anything else.
|
||||
#[test]
|
||||
@@ -1500,6 +1577,56 @@ fn modal_dialogs_block_the_window_behind_them() {
|
||||
assert!(h.state().ui.backstage, "File opens beside Find");
|
||||
}
|
||||
|
||||
/// Dismissing a dialog opened from a non-canvas command or control returns keyboard focus to the page (#7458).
|
||||
#[test]
|
||||
fn dismissing_a_dialog_from_non_canvas_control_returns_keyboard_focus_to_page() {
|
||||
let mut h = app_harness(WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default()));
|
||||
h.run_steps(6);
|
||||
|
||||
// 1. Move focus to a control outside the canvas (Navigation pane search box)
|
||||
h.state_mut().run("view.navigationPane", json!({"value": true})).unwrap();
|
||||
h.run_steps(3);
|
||||
h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Search document").click();
|
||||
h.run_steps(2);
|
||||
assert!(h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Search document").is_focused());
|
||||
assert!(!h.state().canvas.focused(&h.ctx), "canvas does not have focus");
|
||||
|
||||
// Open a dialog via command while Navigation pane has focus
|
||||
h.state_mut().run("ui.dialog", json!({"name": "font"})).unwrap();
|
||||
h.run_steps(3);
|
||||
assert!(is_open(h.state(), "font"), "font dialog is open");
|
||||
|
||||
// Dismiss with Escape
|
||||
h.key_press(egui::Key::Escape);
|
||||
h.run_steps(3);
|
||||
assert!(!is_open(h.state(), "font"), "font dialog closed");
|
||||
|
||||
// Canvas must have regained keyboard focus
|
||||
assert!(h.state().canvas.focused(&h.ctx), "the document canvas took keyboard focus back");
|
||||
h.event(egui::Event::Text("!".into()));
|
||||
h.run_steps(2);
|
||||
assert_eq!(body_of(h.state()), "!", "typing reached the document canvas");
|
||||
|
||||
// 2. Focus Navigation pane search box again, open dialog, and dismiss via Cancel button
|
||||
h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Search document").click();
|
||||
h.run_steps(2);
|
||||
assert!(h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Search document").is_focused());
|
||||
assert!(!h.state().canvas.focused(&h.ctx), "canvas does not have focus");
|
||||
|
||||
h.state_mut().run("ui.dialog", json!({"name": "font"})).unwrap();
|
||||
h.run_steps(3);
|
||||
assert!(is_open(h.state(), "font"), "font dialog is open");
|
||||
|
||||
press(&mut h, "Cancel");
|
||||
h.run_steps(3);
|
||||
assert!(!is_open(h.state(), "font"), "font dialog closed");
|
||||
|
||||
assert!(h.state().canvas.focused(&h.ctx), "the document canvas took keyboard focus back after Cancel");
|
||||
h.event(egui::Event::Text("?".into()));
|
||||
h.run_steps(2);
|
||||
assert_eq!(body_of(h.state()), "!?", "typing reached the document canvas after Cancel");
|
||||
}
|
||||
|
||||
/// Which dialogs leave the window working (#3859, Word for Mac 16.114.1): `shows_modal` and
|
||||
/// `modal_open` agree with it for each.
|
||||
#[test]
|
||||
@@ -1536,6 +1663,71 @@ fn find_symbol_mark_entry_cross_reference_and_merge_fields_are_modeless() {
|
||||
}
|
||||
}
|
||||
|
||||
/// #3859: Escape in the fallback file chooser over a modal dialog (`templates`) cancels only the
|
||||
/// chooser; the dialog under it, drawn first on `dialog_host`, stays open and regains the top
|
||||
/// of the stack.
|
||||
#[test]
|
||||
fn escape_in_the_browser_leaves_the_dialog_under_it_open() {
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft::browse::places::{FakeDirectories, FolderCache};
|
||||
use craft::dialogs::ui::FileChooser;
|
||||
use craft::host::{ManualJobs, PickRequest, Wake};
|
||||
use craft::ui::dialog::DialogResult;
|
||||
|
||||
let mut h = app_harness(app_with(""));
|
||||
h.run_steps(6);
|
||||
// A new window's page takes the keyboard from the first click or command; establish focus so
|
||||
// the later blocked-input check actually tests modal blocking.
|
||||
let ctx = h.ctx.clone();
|
||||
h.state_mut().canvas.focus_page(&ctx);
|
||||
h.run_steps(2);
|
||||
h.event(egui::Event::Text("a".into()));
|
||||
h.run_steps(2);
|
||||
assert_eq!(body_of(h.state()), "a", "the page takes typing while no modal is open");
|
||||
|
||||
open_named(&mut h, "templates", json!({}));
|
||||
assert_eq!(open_keys(h.state()), ["templates"]);
|
||||
|
||||
let jobs = Arc::new(ManualJobs::new());
|
||||
let folders = FolderCache::new(Arc::new(FakeDirectories::new().folder("/d/drafts").file("/d/House.dotx")), jobs.clone(), Wake::none());
|
||||
let req = PickRequest::open("template").directory("/d").fallback(true);
|
||||
h.state_mut().dialog_host.open(FileChooser::new(req, None, folders));
|
||||
for _ in 0..4 {
|
||||
jobs.run_all();
|
||||
h.step();
|
||||
}
|
||||
|
||||
assert!(h.state().dialog_host.is_open::<FileChooser>(), "browser is open");
|
||||
let open = h.state().dialog_host.open_dialogs();
|
||||
assert_eq!(open.len(), 2, "browser is stacked over templates");
|
||||
let ids: Vec<_> = open.iter().map(|d| d.id).collect();
|
||||
assert_eq!(
|
||||
ids,
|
||||
[craft::ui::dialog::dialog_id("templates"), craft::ui::dialog::dialog_id("fileChooser")],
|
||||
"browser is stacked on top of templates"
|
||||
);
|
||||
let listed = open.into_iter().find_map(|d| d.fields.and_then(|f| f.get("listed").cloned()));
|
||||
assert_eq!(listed, Some(json!(true)), "the chooser finished listing its folder");
|
||||
|
||||
h.key_press(egui::Key::Escape);
|
||||
h.run_steps(3);
|
||||
|
||||
assert!(!h.state().dialog_host.is_open::<FileChooser>(), "Escape closes the browser");
|
||||
assert_eq!(h.state_mut().dialog_host.take::<FileChooser>(), Some(DialogResult::Cancel), "Escape cancels the browser");
|
||||
assert_eq!(open_keys(h.state()), ["templates"], "and leaves the dialog under it open");
|
||||
|
||||
h.event(egui::Event::Text("x".into()));
|
||||
h.run_steps(2);
|
||||
assert_eq!(body_of(h.state()), "a", "the document behind templates stays blocked");
|
||||
assert!(is_open(h.state(), "templates"), "templates stays open");
|
||||
|
||||
h.key_press(egui::Key::Escape);
|
||||
h.run_steps(3);
|
||||
assert!(!is_open(h.state(), "templates"), "a second Escape closes templates once it is back on top");
|
||||
assert!(h.state().dialog_host.is_empty(), "all dialogs are closed");
|
||||
}
|
||||
|
||||
/// Every dialog name the name table knows opens its dialog under the key the host reports, or
|
||||
/// nothing where its condition isn't met; scripts and every command use this table (dg.A2).
|
||||
#[test]
|
||||
@@ -1674,6 +1866,54 @@ fn word_count_shows_label_and_count_on_a_line_over_close_and_cancel() {
|
||||
assert!(!is_open(h.state(), "wordCount"), "Cancel closes Word Count");
|
||||
}
|
||||
|
||||
/// #1885: the close control is at the title bar's right end; a click in the close box
|
||||
/// closes the dialog; one just under the title bar leaves it open; a drag that starts on the box
|
||||
/// doesn't move the dialog.
|
||||
#[test]
|
||||
fn the_title_bar_close_box_is_the_whole_corner() {
|
||||
use egui::accesskit::Role;
|
||||
fn press(h: &mut egui_kittest::Harness<'_, WordApp>, from: egui::Pos2, to: egui::Pos2) {
|
||||
let button =
|
||||
|pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE };
|
||||
h.event(egui::Event::PointerMoved(from));
|
||||
h.step();
|
||||
h.event(button(from, true));
|
||||
h.step();
|
||||
if to != from {
|
||||
h.event(egui::Event::PointerMoved(to));
|
||||
h.step();
|
||||
}
|
||||
h.event(button(to, false));
|
||||
for _ in 0..4 {
|
||||
h.step();
|
||||
}
|
||||
}
|
||||
let mut app = app_with("Some text");
|
||||
super::open(&mut app, "wordCount", &json!({})).expect("word count opens");
|
||||
let mut h = app_harness(app);
|
||||
h.run_steps(4);
|
||||
assert!(is_open(h.state(), "wordCount"), "dialog is open");
|
||||
let before = h.get_by_role_and_label(Role::Dialog, "Word Count").rect();
|
||||
let closes: Vec<_> = h.query_all_by_role_and_label(Role::Button, "Close").filter(|n| !n.accesskit_node().is_hidden()).collect();
|
||||
let close_box = closes.into_iter().min_by(|a, b| a.rect().min.y.total_cmp(&b.rect().min.y)).expect("title bar close");
|
||||
let bx = close_box.rect();
|
||||
assert!((bx.top() - before.top()).abs() <= 10.0, "box {bx:?} is in the title bar area of {before:?}");
|
||||
assert!(
|
||||
bx.right() <= before.right() && before.right() - bx.right() <= 10.0 && bx.left() > before.center().x,
|
||||
"close button sits at the right: {bx:?} in {before:?}"
|
||||
);
|
||||
let under = egui::pos2(bx.center().x, bx.bottom() + 4.0);
|
||||
press(&mut h, under, under);
|
||||
assert!(is_open(h.state(), "wordCount"), "a click under the title bar keeps the dialog");
|
||||
let at = bx.center();
|
||||
press(&mut h, at, at + egui::vec2(-150.0, 90.0));
|
||||
assert!(is_open(h.state(), "wordCount"), "a drag from the box isn't a click");
|
||||
let after = h.get_by_role_and_label(Role::Dialog, "Word Count").rect();
|
||||
assert!((after.min - before.min).length() <= 1.0, "the box isn't a drag handle: {before:?} -> {after:?}");
|
||||
press(&mut h, at, at);
|
||||
assert!(!is_open(h.state(), "wordCount"), "a click in the box closes the dialog");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Font layout
|
||||
|
||||
/// The Font dialog stands as the old one did: the Effects check boxes two to a line (Bold beside Italic, Underline
|
||||
@@ -1785,3 +2025,235 @@ fn colour_fields_say_their_label_and_colour_in_the_interface_language() {
|
||||
assert!(present, "the translated field is {name}");
|
||||
}
|
||||
}
|
||||
|
||||
/// #7446: the SmartArt picker renders compact layout tiles capped at three rows (PICKER_HEIGHT = 304),
|
||||
/// instead of expanding each thumbnail to default card dimensions (~132×132 pt) and overflowing.
|
||||
#[test]
|
||||
fn smartart_layout_cells_keep_productions_size() {
|
||||
use egui::accesskit::Role;
|
||||
|
||||
let mut h = app_harness(app_with("Text"));
|
||||
open_named(&mut h, "insertSmartArt", json!({}));
|
||||
crate::test_harness::frames(&mut h, 4);
|
||||
let cell = h.get_by_role_and_label(Role::ListItem, "Basic List").rect();
|
||||
assert!(cell.width() <= 80.0 && cell.height() <= 102.0, "a layout cell is 75×93, got {:?}", cell.size());
|
||||
let grid = h.get_by_role_and_label(Role::ListBox, "Layouts").rect();
|
||||
assert!(grid.height() <= 304.0, "the picker is three 96 pt rows, got {:?}", grid.size());
|
||||
}
|
||||
|
||||
/// #7456: the Insert Chart dialog renders compact chart type tiles in its 3-column gallery,
|
||||
/// instead of expanding each thumbnail to default card dimensions (~132×104 pt) and ballooning the grid.
|
||||
#[test]
|
||||
fn insert_chart_tiles_render_within_compact_bounds() {
|
||||
use egui::accesskit::Role;
|
||||
|
||||
let mut h = app_harness(app_with("Text"));
|
||||
open_named(&mut h, "insertChart", json!({}));
|
||||
crate::test_harness::frames(&mut h, 4);
|
||||
let cell = h.get_by_role_and_label(Role::ListItem, "Clustered Column").rect();
|
||||
assert!(cell.width() <= 90.0 && cell.height() <= 92.0, "chart tile should be compact (~85×87 pt), got {:?}", cell.size());
|
||||
let grid = h.get_by_role_and_label(Role::ListBox, "Chart types").rect();
|
||||
assert!(grid.width() <= 380.0, "3-column chart types grid should not exceed comfortable dialog proportions (~360 pt), got {:?}", grid.size());
|
||||
}
|
||||
|
||||
/// The shake starts and ends where the dialog is and swings at most 6 points either way (#3859, #4076, #7321).
|
||||
#[test]
|
||||
fn the_shake_comes_back_to_rest() {
|
||||
assert_eq!(chrome::shake_offset(0.0), 0.0);
|
||||
assert!(chrome::shake_offset(1.0).abs() < 1e-4);
|
||||
assert!((0..=100).map(|i| chrome::shake_offset(i as f32 / 100.0).abs()).all(|x| x <= 6.0));
|
||||
assert!((0..=100).any(|i| chrome::shake_offset(i as f32 / 100.0).abs() > 3.0), "it does move");
|
||||
}
|
||||
|
||||
/// #7321: clicking beside the Save Changes modal dialog nudges it (or flashes its edge under reduced motion),
|
||||
/// repeat clicks mid-nudge leave the animation running without restarting, and closing clears the nudge state.
|
||||
#[test]
|
||||
fn unsaved_changes_dialog_shakes_on_outside_click_and_clears_on_close() {
|
||||
for animations in ["on", "off"] {
|
||||
let mut app = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default());
|
||||
app.run("text.insert", json!({"text": "Unsaved"})).unwrap();
|
||||
app.run("ui.animations", json!({"value": animations})).unwrap();
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).with_step_dt(1.0 / 60.0).build_eframe(|_| app);
|
||||
h.run_steps(6);
|
||||
|
||||
// Attempt window close while dirty. Prompt opens peacefully without shaking.
|
||||
h.input_mut().viewports.entry(egui::ViewportId::ROOT).or_default().events.push(egui::ViewportEvent::Close);
|
||||
h.step();
|
||||
h.step();
|
||||
|
||||
let prompt_id = h.state().closing.as_ref().and_then(|c| c.prompt).expect("Save Changes prompt is open");
|
||||
let key = chrome::nudge_id(&h.ctx, prompt_id);
|
||||
let started = |h: &egui_kittest::Harness<'_, WordApp>| h.ctx.data(|d| d.get_temp::<f64>(key));
|
||||
|
||||
assert_eq!(started(&h), None, "{animations:?}: prompt opens peacefully without shaking");
|
||||
|
||||
let look = |h: &egui_kittest::Harness<'_, WordApp>| {
|
||||
let shapes = &h.output().shapes;
|
||||
let mut flat = Vec::new();
|
||||
fn walk<'a>(s: &'a egui::Shape, out: &mut Vec<&'a egui::Shape>) {
|
||||
match s {
|
||||
egui::Shape::Vec(children) => {
|
||||
for c in children {
|
||||
walk(c, out);
|
||||
}
|
||||
}
|
||||
other => out.push(other),
|
||||
}
|
||||
}
|
||||
for c in shapes {
|
||||
walk(&c.shape, &mut flat);
|
||||
}
|
||||
let save_x = flat.iter().find_map(|s| match s {
|
||||
egui::Shape::Text(t) if t.galley.text() == "Save" || t.galley.text() == "Don't Save" || t.galley.text() == "Cancel" => Some(t.pos.x),
|
||||
_ => None,
|
||||
});
|
||||
let border_flashes =
|
||||
flat.iter().filter(|s| matches!(s, egui::Shape::Rect(r) if r.stroke.width > 0.0 && r.fill == egui::Color32::TRANSPARENT)).count();
|
||||
(save_x, border_flashes)
|
||||
};
|
||||
|
||||
let rest_pos = look(&h).0;
|
||||
let baseline_flashes = look(&h).1;
|
||||
|
||||
// Clicking beside the dialog triggers the nudge
|
||||
let rect = craft::ui::runtime::overlay::top(&h.ctx)
|
||||
.and_then(|id| craft::ui::runtime::overlay::entry(&h.ctx, id))
|
||||
.map(|e| e.rect)
|
||||
.or_else(|| h.ctx.memory(|m| m.top_modal_layer().and_then(|l| m.area_rect(l.id))))
|
||||
.expect("dialog rect exists");
|
||||
let beside = egui::pos2(rect.min.x - 20.0, rect.min.y - 20.0);
|
||||
assert!(!rect.contains(beside));
|
||||
|
||||
h.event(egui::Event::PointerMoved(beside));
|
||||
h.event(egui::Event::PointerButton { pos: beside, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE });
|
||||
h.step();
|
||||
h.event(egui::Event::PointerButton { pos: beside, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE });
|
||||
h.step();
|
||||
|
||||
let first = started(&h).expect("clicking outside nudges the dialog");
|
||||
let mut looks = vec![look(&h)];
|
||||
|
||||
// Repeat outside click while it runs does not restart it
|
||||
h.event(egui::Event::PointerMoved(beside));
|
||||
h.event(egui::Event::PointerButton { pos: beside, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE });
|
||||
h.step();
|
||||
h.event(egui::Event::PointerButton { pos: beside, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE });
|
||||
h.step();
|
||||
assert_eq!(started(&h), Some(first), "{animations:?}: repeat click does not reset start time mid-nudge");
|
||||
|
||||
for _ in 0..6 {
|
||||
h.step();
|
||||
looks.push(look(&h));
|
||||
}
|
||||
|
||||
if animations == "on" {
|
||||
assert!(looks.iter().any(|l| l.0 != rest_pos), "it shakes horizontally under full animations");
|
||||
} else {
|
||||
assert!(looks.iter().any(|l| l.1 > baseline_flashes), "it flashes accent border under reduced motion");
|
||||
assert!(looks.iter().all(|l| l.0 == rest_pos), "it does not translate horizontally under reduced motion");
|
||||
}
|
||||
|
||||
// Run until shake completes
|
||||
h.run_steps(30);
|
||||
let final_look = look(&h);
|
||||
assert_eq!(final_look.0, rest_pos, "it comes back to rest");
|
||||
assert_eq!(final_look.1, baseline_flashes, "border flash ends at rest");
|
||||
|
||||
// Cancel closes the dialog and forgets nudge
|
||||
h.state_mut().run("ui.saveChanges", json!({"answer": "cancel"})).unwrap();
|
||||
h.step();
|
||||
assert_eq!(started(&h), None, "{animations:?}: closing the dialog clears nudge state");
|
||||
}
|
||||
}
|
||||
|
||||
/// #7321: ordinary click inside a dialog with a popup open does not shake it;
|
||||
/// clicking outside the dialog shakes it; closing clears nudge so reopening within 0.4s opens still.
|
||||
#[test]
|
||||
fn modal_dialog_with_open_popup_does_not_shake_on_inside_click_but_shakes_on_outside_click() {
|
||||
let app = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default());
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).with_step_dt(1.0 / 60.0).build_eframe(|_| app);
|
||||
h.run_steps(6);
|
||||
let id = super::open(h.state_mut(), "font", &json!({})).expect("font dialog opens");
|
||||
h.run_steps(4);
|
||||
|
||||
// Open a dropdown popup inside the Font dialog
|
||||
let buttons: Vec<_> =
|
||||
h.query_all_by_role_and_label(egui::accesskit::Role::Button, "Font color: Automatic").filter(|n| !n.accesskit_node().is_hidden()).collect();
|
||||
assert!(!buttons.is_empty(), "Font color button exists");
|
||||
buttons.last().unwrap().click();
|
||||
h.run_steps(3);
|
||||
|
||||
// Verify a popup is open on top of the overlay stack
|
||||
let top = craft::ui::runtime::overlay::top(&h.ctx).expect("top overlay entry exists");
|
||||
let top_entry = craft::ui::runtime::overlay::entry(&h.ctx, top).expect("top entry exists");
|
||||
assert_eq!(top_entry.rank, craft::ui::runtime::overlay::Rank::Popup, "top entry is popup");
|
||||
|
||||
// Resolve the target modal dialog's own overlay entry by traversing parents
|
||||
let mut cur = top_entry.clone();
|
||||
while let Some(parent) = cur.parent.and_then(|p| craft::ui::runtime::overlay::entry(&h.ctx, p)) {
|
||||
if cur.rank.is_modal() {
|
||||
break;
|
||||
}
|
||||
cur = parent;
|
||||
}
|
||||
assert!(cur.rank.is_modal(), "found modal dialog overlay entry");
|
||||
let modal_rect = cur.rect;
|
||||
let popup_rect = top_entry.rect;
|
||||
|
||||
// A click inside the modal dialog (on body padding, outside the popup) must NOT nudge
|
||||
let inside_point = egui::pos2(modal_rect.min.x + 40.0, modal_rect.min.y + 40.0);
|
||||
assert!(modal_rect.contains(inside_point), "point is inside dialog");
|
||||
assert!(!popup_rect.contains(inside_point), "point is outside popup");
|
||||
|
||||
h.event(egui::Event::PointerMoved(inside_point));
|
||||
h.event(egui::Event::PointerButton { pos: inside_point, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE });
|
||||
h.step();
|
||||
h.event(egui::Event::PointerButton { pos: inside_point, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE });
|
||||
h.step();
|
||||
|
||||
let key = chrome::nudge_id(&h.ctx, id);
|
||||
assert!(h.ctx.data(|d| d.get_temp::<f64>(key)).is_none(), "click inside dialog with popup open does not nudge");
|
||||
assert!(h.state().dialog_host.get_dyn(id).is_some(), "dialog remains open after inside click");
|
||||
|
||||
// A click inside the popup itself (or an extension of the popup) must also NOT nudge
|
||||
let popup_point = popup_rect.center();
|
||||
h.event(egui::Event::PointerMoved(popup_point));
|
||||
h.event(egui::Event::PointerButton { pos: popup_point, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE });
|
||||
h.step();
|
||||
h.event(egui::Event::PointerButton { pos: popup_point, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE });
|
||||
h.step();
|
||||
assert!(h.ctx.data(|d| d.get_temp::<f64>(key)).is_none(), "click inside popup does not nudge");
|
||||
|
||||
// Dismiss the open dropdown popup
|
||||
h.event(egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE });
|
||||
h.step();
|
||||
h.event(egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: false, repeat: false, modifiers: egui::Modifiers::NONE });
|
||||
h.step();
|
||||
|
||||
// A click outside the modal dialog (even completed within a single frame) MUST nudge it
|
||||
let beside_point = egui::pos2(modal_rect.min.x - 20.0, modal_rect.min.y - 20.0);
|
||||
assert!(!modal_rect.contains(beside_point), "point is outside dialog");
|
||||
|
||||
h.event(egui::Event::PointerMoved(beside_point));
|
||||
h.event(egui::Event::PointerButton { pos: beside_point, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE });
|
||||
h.event(egui::Event::PointerButton { pos: beside_point, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE });
|
||||
h.step();
|
||||
|
||||
assert!(h.ctx.data(|d| d.get_temp::<f64>(key)).is_some(), "click outside dialog nudges it");
|
||||
|
||||
let serial1 = h.state().dialog_host.open_serial(id).expect("dialog has open serial");
|
||||
|
||||
// Closing the dialog clears the nudge
|
||||
let ctx = h.ctx.clone();
|
||||
h.state_mut().dialog_host.cancel_by_id(&ctx, id);
|
||||
h.run_steps(3);
|
||||
assert!(h.ctx.data(|d| d.get_temp::<f64>(key)).is_none(), "closing dialog clears nudge");
|
||||
|
||||
// Reopening the dialog gets a new open serial and starts still
|
||||
let id2 = super::open(h.state_mut(), "font", &json!({})).expect("font dialog reopens");
|
||||
let serial2 = h.state().dialog_host.open_serial(id2).expect("reopened dialog has open serial");
|
||||
assert_ne!(serial1, serial2, "successive opens have distinct open serials");
|
||||
h.run_steps(2);
|
||||
let key2 = chrome::nudge_id(&h.ctx, id2);
|
||||
assert!(h.ctx.data(|d| d.get_temp::<f64>(key2)).is_none(), "reopened dialog starts still");
|
||||
}
|
||||
|
||||
@@ -237,10 +237,15 @@ pub fn is_word_template(path: &str) -> bool {
|
||||
/// The name an open document goes by in the window: the engine's title, with an untitled
|
||||
/// document's `Document2` in the interface language.
|
||||
pub fn display_title(d: &DocInfo) -> String {
|
||||
if d.path.is_none() {
|
||||
return untitled_title(&d.title).unwrap_or_else(|| d.title.clone());
|
||||
// NUL cannot go into an X11 window title (C string); a title of only NUL reads as untitled (#3634).
|
||||
let title: String = d.title.chars().filter(|&c| c != '\0').collect();
|
||||
if title.is_empty() && !d.title.is_empty() {
|
||||
return tl!("Document1").into();
|
||||
}
|
||||
d.title.clone()
|
||||
if d.path.is_none() {
|
||||
return untitled_title(&title).unwrap_or(title);
|
||||
}
|
||||
title
|
||||
}
|
||||
|
||||
/// `Document2` (the engine's English name for an untitled document) in the interface language,
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
//! In-app file browser trials and interaction regressions (#576, #3037, #3859).
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests;
|
||||
@@ -0,0 +1,47 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft::browse::places::{FakeDirectories, FolderCache};
|
||||
use craft::dialogs::ui::FileChooser;
|
||||
use craft::host::{ManualJobs, PickRequest, Wake};
|
||||
use egui::vec2;
|
||||
use serde_json::json;
|
||||
use wordcraft_engine::Session;
|
||||
|
||||
use crate::{Services, WordApp};
|
||||
|
||||
/// #3859: a modal dialog that closes as it opens the browser (Save in "Save changes?" as a new
|
||||
/// document closes, with no system dialog) leaves the keyboard in the browser's name box: the
|
||||
/// document doesn't take it back on the next frame.
|
||||
#[test]
|
||||
fn a_dialog_closing_into_the_browser_leaves_it_the_keyboard() {
|
||||
let mut a = WordApp::new(Session::new(wordcraft_doc::Document::new()), Services::default());
|
||||
a.run("text.insert", json!({"text": "Unsaved"})).unwrap();
|
||||
let _ = a.run("file.close", json!({}));
|
||||
assert!(a.dialog_host.shows_modal(), "Save Changes prompt opens");
|
||||
|
||||
let mut h = crate::test_harness::builder().with_size(vec2(1440.0, 900.0)).build_ui_state(
|
||||
|ui, app: &mut WordApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
crate::test_harness::logic(&ctx, app);
|
||||
app.ui(ui);
|
||||
},
|
||||
a,
|
||||
);
|
||||
crate::test_harness::frames(&mut h, 4);
|
||||
|
||||
let _ = h.state_mut().run("ui.saveChanges", json!({"answer": "save"}));
|
||||
let folders = FolderCache::new(Arc::new(FakeDirectories::new().folder("/d/drafts")), Arc::new(ManualJobs::new()), Wake::none());
|
||||
let req = PickRequest::save("document").file_name("Unsaved.docx").fallback(true);
|
||||
h.state_mut().dialog_host.open(FileChooser::new(req, None, folders));
|
||||
crate::test_harness::frames(&mut h, 4);
|
||||
|
||||
assert!(h.state().dialog_host.is_open::<FileChooser>(), "Save As goes on in the browser");
|
||||
assert!(!h.state().canvas.focused(&h.ctx), "document does not take the keyboard back");
|
||||
|
||||
let before_doc = h.state().session.doc.plain_text(wordcraft_doc::StoryRef::Body);
|
||||
h.event(egui::Event::Text("x".into()));
|
||||
crate::test_harness::frames(&mut h, 2);
|
||||
|
||||
let after_doc = h.state().session.doc.plain_text(wordcraft_doc::StoryRef::Body);
|
||||
assert_eq!(after_doc, before_doc, "typing does not leak into the document behind the browser");
|
||||
}
|
||||
@@ -923,3 +923,73 @@ fn many_failed_fonts_end_with_a_count() {
|
||||
a.add_fonts(fonts).unwrap();
|
||||
assert_eq!(status_text(&a), "Added 0 fonts; 5 couldn't be read: f0.ttf, f1.ttf, f2.ttf and 2 more");
|
||||
}
|
||||
|
||||
/// Drawn entries have names and selection state, and choosing one still picks its path (#576, #6790).
|
||||
#[test]
|
||||
fn entries_expose_names_selection_and_picking() {
|
||||
use craft::browse::places::{FakeDirectories, FolderCache};
|
||||
use craft::dialogs::Answer;
|
||||
use craft::dialogs::ui::FileChooser;
|
||||
use craft::host::{ManualJobs, Wake};
|
||||
use craft::ui::dialog::DialogResult;
|
||||
use egui::accesskit::Role;
|
||||
use egui::vec2;
|
||||
use egui_kittest::kittest::{NodeT, Queryable};
|
||||
|
||||
let fake = Arc::new(FakeDirectories::new().folder("/d/Drafts").file("/d/chapter.docx"));
|
||||
let jobs = Arc::new(ManualJobs::new());
|
||||
let folders = FolderCache::new(fake, jobs.clone(), Wake::none());
|
||||
|
||||
let a = WordApp::new(Session::new(wordcraft_doc::Document::new()), Services::default());
|
||||
let mut h = crate::test_harness::builder().with_size(vec2(760.0, 520.0)).build_eframe(|_| a);
|
||||
|
||||
let req = PickRequest::open("document").directory("/d").fallback(true);
|
||||
h.state_mut().dialog_host.open(FileChooser::new(req, None, folders));
|
||||
|
||||
let step = |h: &mut egui_kittest::Harness<'_, WordApp>, count: usize| {
|
||||
for _ in 0..count {
|
||||
jobs.run_all();
|
||||
h.step();
|
||||
}
|
||||
};
|
||||
let chooser_fields = |h: &egui_kittest::Harness<'_, WordApp>| {
|
||||
h.state()
|
||||
.dialog_host
|
||||
.open_dialogs()
|
||||
.into_iter()
|
||||
.find_map(|d| d.fields.filter(|f| f.get("listed").is_some()))
|
||||
.expect("FileChooser fields are exposed")
|
||||
};
|
||||
|
||||
step(&mut h, 6);
|
||||
assert_eq!(chooser_fields(&h)["listed"], json!(true), "folder finished listing");
|
||||
|
||||
// Both entries are exposed with ListItem role and start unselected.
|
||||
for name in ["Drafts", "chapter.docx"] {
|
||||
assert_eq!(h.get_by_role_and_label(Role::ListItem, name).accesskit_node().is_selected(), Some(false), "{name} starts unselected");
|
||||
}
|
||||
|
||||
// Selecting the folder marks Drafts selected, leaves chapter.docx unselected, and leaves the name box empty.
|
||||
h.get_by_role_and_label(Role::ListItem, "Drafts").click();
|
||||
step(&mut h, 3);
|
||||
assert_eq!(h.get_by_role_and_label(Role::ListItem, "Drafts").accesskit_node().is_selected(), Some(true));
|
||||
assert_eq!(h.get_by_role_and_label(Role::ListItem, "chapter.docx").accesskit_node().is_selected(), Some(false));
|
||||
assert_eq!(chooser_fields(&h)["selection"], json!(["Drafts"]));
|
||||
assert_eq!(chooser_fields(&h)["name"], json!(""));
|
||||
|
||||
// Selecting chapter.docx moves selection from Drafts to chapter.docx and fills the File name box.
|
||||
h.get_by_role_and_label(Role::ListItem, "chapter.docx").click();
|
||||
step(&mut h, 3);
|
||||
assert_eq!(h.get_by_role_and_label(Role::ListItem, "Drafts").accesskit_node().is_selected(), Some(false));
|
||||
assert_eq!(h.get_by_role_and_label(Role::ListItem, "chapter.docx").accesskit_node().is_selected(), Some(true));
|
||||
assert_eq!(chooser_fields(&h)["selection"], json!(["chapter.docx"]));
|
||||
assert_eq!(chooser_fields(&h)["name"], json!("chapter.docx"));
|
||||
assert_eq!(h.get_by_role_and_label(Role::TextInput, "File name").accesskit_node().value().as_deref(), Some("chapter.docx"));
|
||||
|
||||
// Open button confirms the pick.
|
||||
h.get_by_role_and_label(Role::Button, "Open").click();
|
||||
step(&mut h, 3);
|
||||
|
||||
let answer = h.state_mut().dialog_host.take::<FileChooser>();
|
||||
assert_eq!(answer, Some(DialogResult::Ok(Answer::Paths(vec![PathBuf::from("/d/chapter.docx")]))));
|
||||
}
|
||||
|
||||
@@ -14,12 +14,14 @@ use craft::behavior::IconId;
|
||||
use craft::theme::Variant;
|
||||
use craft::ui::buttons::Button;
|
||||
use craft::ui::choice::Checkbox;
|
||||
use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _, clicked};
|
||||
use craft::ui::contract::{Bind, Pad, Props as _, Show as _, ShowContainer as _, clicked};
|
||||
use craft::ui::dialog::{Dialog, DialogId, DialogResult, DialogStack, StackDialog, dialog_id};
|
||||
use craft::ui::display::{Badge, Icon, Shade, Text};
|
||||
use craft::ui::layout_components::Row as Line;
|
||||
use craft::ui::display::{Badge, Elide, Icon, Shade, Text};
|
||||
use craft::ui::layout::RowAlign;
|
||||
use craft::ui::layout_components::{Row as Line, Stack};
|
||||
use craft::ui::primitives::IconSpec;
|
||||
use craft::ui::sections::{DialogRole, FooterButton, GroupBox};
|
||||
use craft::ui::sections::{DialogRole, FooterButton};
|
||||
use craft::ui::style::{SurfaceKind, TypeRole};
|
||||
use egui::Ui;
|
||||
use serde::Serialize;
|
||||
|
||||
@@ -272,15 +274,22 @@ impl StackDialog for FontBox {
|
||||
.shade(Shade::Faint)
|
||||
.show(ui);
|
||||
for (at, g) in groups(fonts).into_iter().enumerate() {
|
||||
// The names are the document's own words, not interface text.
|
||||
GroupBox::new(g.fonts.join(", "), None).id_salt(("download", at)).show(ui, |ui, _| {
|
||||
let shown_as =
|
||||
crate::i18n::fmt(tl!("Shown as {fonts} · {publisher}"), &[("fonts", &g.shown_as.join(", ")), ("publisher", g.publisher)]);
|
||||
Text::new(shown_as).shade(Shade::Faint).show(ui);
|
||||
if g.restricted {
|
||||
Text::new(tl!("Its licence limits who may use it: read the terms first.")).shade(Shade::Faint).show(ui);
|
||||
}
|
||||
Line::new().show(ui, |ui, _| {
|
||||
// One row per download, as before the craft port: the names, what they are shown as and the licence
|
||||
// note stacked at the start edge, the button at the end. The names are the document's own words.
|
||||
Stack::new().surface(SurfaceKind::Frame).pad(Pad::Regular).fill_width().id_salt(("download_group", at)).show(ui, |ui, _| {
|
||||
Line::new().fill_width().align(RowAlign::SpaceBetween).id_salt(("download", at)).show(ui, |ui, _| {
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
// One line cut at the end, whole in a tooltip: one unbroken name must not push the button out.
|
||||
Text::new(g.fonts.join(", ")).role(TypeRole::BodyStrong).elide(Elide::End).show(ui);
|
||||
let shown_as = crate::i18n::fmt(
|
||||
tl!("Shown as {fonts} · {publisher}"),
|
||||
&[("fonts", &g.shown_as.join(", ")), ("publisher", g.publisher)],
|
||||
);
|
||||
Text::new(shown_as).shade(Shade::Faint).show(ui);
|
||||
if g.restricted {
|
||||
Text::new(tl!("Its licence limits who may use it: read the terms first.")).shade(Shade::Faint).show(ui);
|
||||
}
|
||||
});
|
||||
if clicked(&Button::new(tl!("Download")).variant(Variant::PRIMARY).id_salt(("download_button", at)).show(ui)) {
|
||||
asks.push(Ask::Download(g.url.to_string()));
|
||||
}
|
||||
|
||||
@@ -207,6 +207,37 @@ fn fonts_of_one_download_are_listed_together() {
|
||||
assert_eq!((g[1].fonts.as_slice(), g[1].url), (["Cascadia Code"].as_slice(), "https://c"));
|
||||
}
|
||||
|
||||
/// As many downloads as the box lists, in a short window and a very short one: what is above
|
||||
/// the row with Close scrolls, so the opt-out and Close stay on screen and the box in the window.
|
||||
#[test]
|
||||
fn many_downloads_in_a_short_window_leave_the_opt_out_and_close_on_screen() {
|
||||
for height in [600.0, 400.0] {
|
||||
let mut a = WordApp::new(Session::new(wordcraft_doc::Document::from_text("Lanterns")), crate::Services::default());
|
||||
let fonts: Vec<Row> = (0..LISTED)
|
||||
.map(|i| Row {
|
||||
font: format!("Harbour Face {i}"),
|
||||
shown_as: vec!["Carlito".into()],
|
||||
download: format!("Harbour Face {i}"),
|
||||
publisher: "Lantern Works".into(),
|
||||
url: format!("https://example.org/{i}"),
|
||||
restricted: false,
|
||||
})
|
||||
.collect();
|
||||
open_with(&mut a, None, FontBox::new(fonts, false), DialogHooks { prepare: None, settle });
|
||||
let h = harness_sized(a, egui::vec2(1000.0, height));
|
||||
// The steps are still there, to scroll to.
|
||||
assert!(h.query_by_label("Add Font…").is_some());
|
||||
for label in ["Don't show this again", "Close"] {
|
||||
// Close is also the window's close box: every match is on screen.
|
||||
let rects: Vec<egui::Rect> = h.query_all_by_label(label).map(|n| n.rect()).collect();
|
||||
assert!(!rects.is_empty(), "no {label}");
|
||||
for r in rects {
|
||||
assert!(r.min.y >= 0.0 && r.max.y <= height, "{label} is at {r:?}, outside the {height} pt window");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A font whose publisher limits its use says so on its card, and has a card of its own.
|
||||
#[test]
|
||||
fn a_font_with_a_limited_licence_says_so() {
|
||||
@@ -233,3 +264,60 @@ fn only_so_many_documents_are_remembered() {
|
||||
assert_eq!(a.font_notice_seen.len(), REMEMBERED);
|
||||
assert_eq!(a.font_notice_seen.last(), Some(&(REMEMBERED as u64 + 49)));
|
||||
}
|
||||
|
||||
/// Each missing font's names, substitute and Download button sit in one compact row, not one under another, and a
|
||||
/// narrow window keeps them inside the box.
|
||||
#[test]
|
||||
fn each_download_is_one_row() {
|
||||
let row = |font: &str, shown: &str, url: &str| Row {
|
||||
font: font.into(),
|
||||
shown_as: vec![shown.into()],
|
||||
download: font.into(),
|
||||
publisher: "Microsoft".into(),
|
||||
url: url.into(),
|
||||
restricted: false,
|
||||
};
|
||||
for width in [1440.0, 520.0] {
|
||||
let mut a = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default());
|
||||
let fonts = vec![row("Aptos", "Carlito", "https://a"), row("Cascadia Code", "Liberation Mono", "https://c")];
|
||||
open_with(&mut a, None, FontBox::new(fonts, false), DialogHooks { prepare: None, settle });
|
||||
let h = harness_sized(a, egui::vec2(width, 900.0));
|
||||
let buttons: Vec<_> = h.query_all_by_role_and_label(egui::accesskit::Role::Button, "Download").collect();
|
||||
assert_eq!(buttons.len(), 2);
|
||||
for (button, shown) in buttons.iter().zip(["Shown as Carlito · Microsoft", "Shown as Liberation Mono · Microsoft"]) {
|
||||
let shown = h.get_by_label(shown).rect();
|
||||
let button = button.rect();
|
||||
// The button is beside the text block, level with it, not under it.
|
||||
assert!(button.min.x >= shown.max.x, "{width}: {button:?} {shown:?}");
|
||||
assert!(button.center().y < shown.max.y, "{width}: button under the text: {button:?} {shown:?}");
|
||||
assert!(button.max.x <= width, "{width}: clipped {button:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One very long unbroken family name is cut inside its card and leaves the Download button inside the card too.
|
||||
#[test]
|
||||
fn a_long_unbroken_name_stays_inside_its_card() {
|
||||
let long = format!("Aptos {}", "W".repeat(200));
|
||||
let row = Row {
|
||||
font: long.clone(),
|
||||
shown_as: vec!["Carlito".into()],
|
||||
download: "Aptos".into(),
|
||||
publisher: "Microsoft".into(),
|
||||
url: "https://a".into(),
|
||||
restricted: false,
|
||||
};
|
||||
let mut a = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default());
|
||||
open_with(&mut a, None, FontBox::new(vec![row], false), DialogHooks { prepare: None, settle });
|
||||
let h = harness_sized(a, egui::vec2(700.0, 900.0));
|
||||
let button = h.query_all_by_role_and_label(egui::accesskit::Role::Button, "Download").next().expect("button").rect();
|
||||
let name = h.get_by_label(&long).rect();
|
||||
let shown = h.get_by_label("Shown as Carlito · Microsoft").rect();
|
||||
// The card has no node of its own; the dialog it fills is the tightest box to hold both to.
|
||||
let dialog = h.query_all(egui_kittest::kittest::By::new().role(egui::accesskit::Role::Dialog)).next().expect("the dialog").rect();
|
||||
assert!(name.max.x <= button.min.x, "name runs under the button: {name:?} {button:?}");
|
||||
assert!(dialog.contains_rect(name) && dialog.contains_rect(button), "outside the dialog: {name:?} {button:?} {dialog:?}");
|
||||
// The card's padding stands between the button and the dialog's edge.
|
||||
assert!(button.max.x < dialog.max.x, "button reaches the dialog's edge: {button:?} {dialog:?}");
|
||||
assert!(name.min.x >= shown.min.x - 1.0 && name.width() > 0.0, "{name:?} {shown:?}");
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user