mirror of
https://github.com/storytold/wordcraft.git
synced 2026-12-01 02:03:33 -06:00
Compare commits
64
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
695d358ed1 | ||
|
|
4daed0b5ad | ||
|
|
d22500664d | ||
|
|
effb736735 | ||
|
|
d7aac19341 | ||
|
|
055a9065f5 | ||
|
|
5265924f29 | ||
|
|
0f241aef67 | ||
|
|
6478152244 | ||
|
|
aaaeff2b94 | ||
|
|
e1f261501c | ||
|
|
837999196a | ||
|
|
13f5e9702c | ||
|
|
0eace8de49 | ||
|
|
63863ec62d | ||
|
|
b4f0a3abad | ||
|
|
ff98927ea6 | ||
|
|
fff580d8f0 | ||
|
|
4b3e5d52df | ||
|
|
53bbaa8978 | ||
|
|
813f069712 | ||
|
|
43c38dfb56 | ||
|
|
6d6ab5f4dc | ||
|
|
54f6709a97 | ||
|
|
c6d71b829a | ||
|
|
af26131063 | ||
|
|
9b13180006 | ||
|
|
2ca5bf5dfa | ||
|
|
1f6cf16029 | ||
|
|
18bbf00090 | ||
|
|
a3b0f9835f | ||
|
|
5f06b28447 | ||
|
|
4c913ffd28 | ||
|
|
e3f1356360 | ||
|
|
303c80a253 | ||
|
|
9e899aaae9 | ||
|
|
8e52baaf18 | ||
|
|
1b75d8dfd4 | ||
|
|
dedd658cb0 | ||
|
|
f28896acc1 | ||
|
|
f3b51422b0 | ||
|
|
11b1b69457 | ||
|
|
2b3b9c8460 | ||
|
|
ff0d327056 | ||
|
|
194ca941bf | ||
|
|
f0dfe49348 | ||
|
|
df3279f87e | ||
|
|
45a851dee2 | ||
|
|
1857c7e41b | ||
|
|
106622972b | ||
|
|
b6a402597f | ||
|
|
18368bae46 | ||
|
|
4767a33981 | ||
|
|
4699c8d7c7 | ||
|
|
7abfe7d86a | ||
|
|
08a4392b18 | ||
|
|
d1bb1ff547 | ||
|
|
56512dbc1d | ||
|
|
4deb338b44 | ||
|
|
0c6c377681 | ||
|
|
17c163c425 | ||
|
|
6fbf780789 | ||
|
|
57fb4544f2 | ||
|
|
eeeb31d85f |
@@ -4,10 +4,10 @@
|
||||
"repository_id": 1408489772,
|
||||
"producer_workflow_id": 429734489,
|
||||
"producer_workflow_path": ".github/workflows/nightly.yml",
|
||||
"producer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
|
||||
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
|
||||
"producer_tooling_revision": "main",
|
||||
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main",
|
||||
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
|
||||
"signer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
|
||||
"signer_tooling_revision": "main",
|
||||
"release_branch": "nightly-signer",
|
||||
"manual_actors": [
|
||||
"bflatastic",
|
||||
@@ -83,7 +83,9 @@
|
||||
}
|
||||
},
|
||||
"max_artifact_bytes": 2147483648,
|
||||
"automatic_signer_actors": [],
|
||||
"automatic_signer_actors": [
|
||||
"github-actions[bot]"
|
||||
],
|
||||
"platforms": {
|
||||
"windows-x86_64": {
|
||||
"unsigned_artifact_name": "nightly-unsigned-windows-x86_64",
|
||||
@@ -95,7 +97,15 @@
|
||||
"unsigned_artifact_name": "nightly-unsigned-linux-x86_64",
|
||||
"trust": {
|
||||
"fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"
|
||||
}
|
||||
},
|
||||
"package_formats": [
|
||||
"appimage",
|
||||
"arch",
|
||||
"deb",
|
||||
"flatpak",
|
||||
"oci",
|
||||
"rpm"
|
||||
]
|
||||
},
|
||||
"macos-aarch64": {
|
||||
"unsigned_artifact_name": "nightly-unsigned-macos-aarch64",
|
||||
|
||||
@@ -44,10 +44,10 @@ jobs:
|
||||
- name: Install the system libraries the GUI links
|
||||
run: sudo apt-get update && sudo apt-get install -y pkg-config libxkbcommon-dev libwayland-dev libx11-dev libxcursor-dev libxrandr-dev libxi-dev libgtk-3-dev libfontconfig1-dev libfreetype-dev
|
||||
- name: Check out craft-fonts
|
||||
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@f5141455aac7b2eb4708aa259d8ffcdf10fde939
|
||||
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@main
|
||||
with:
|
||||
ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@f5141455aac7b2eb4708aa259d8ffcdf10fde939
|
||||
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@main
|
||||
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
|
||||
with:
|
||||
toolchain: stable
|
||||
@@ -128,10 +128,10 @@ jobs:
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Check out craft-fonts
|
||||
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@f5141455aac7b2eb4708aa259d8ffcdf10fde939
|
||||
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@main
|
||||
with:
|
||||
ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@f5141455aac7b2eb4708aa259d8ffcdf10fde939
|
||||
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@main
|
||||
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
|
||||
with:
|
||||
toolchain: stable
|
||||
@@ -188,10 +188,10 @@ jobs:
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Check out craft-fonts
|
||||
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@f5141455aac7b2eb4708aa259d8ffcdf10fde939
|
||||
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@main
|
||||
with:
|
||||
ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@f5141455aac7b2eb4708aa259d8ffcdf10fde939
|
||||
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@main
|
||||
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
|
||||
with:
|
||||
toolchain: stable
|
||||
|
||||
@@ -11,9 +11,9 @@ permissions: {}
|
||||
|
||||
jobs:
|
||||
dispatch:
|
||||
# SOURCE PREPARATION: literal off until immutable shared tooling and policy qualification.
|
||||
# Automatic Stage 2 signer dispatch for completed scheduled nightly producer runs.
|
||||
if: >-
|
||||
false && github.repository == 'storytold/wordcraft' &&
|
||||
github.repository == 'storytold/wordcraft' &&
|
||||
github.event_name == 'workflow_run'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
|
||||
@@ -34,12 +34,26 @@ jobs:
|
||||
checks: read
|
||||
attestations: write
|
||||
id-token: write
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@main
|
||||
with:
|
||||
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
|
||||
tooling-revision: main
|
||||
app-name: wordcraft
|
||||
producer_run_id: ${{ inputs.producer_run_id }}
|
||||
producer_run_attempt: ${{ inputs.producer_run_attempt }}
|
||||
secrets:
|
||||
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
|
||||
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
|
||||
KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
|
||||
APPLE_ID: ${{ secrets.APPLE_ID }}
|
||||
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
|
||||
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
|
||||
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
|
||||
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
|
||||
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
|
||||
AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }}
|
||||
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
|
||||
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
|
||||
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
|
||||
# No secrets: inherit or raw platform values in this caller. Only the isolated native
|
||||
# callee job may bind the existing release environment (which trusts release and
|
||||
# nightly-signer) and export keys in its signing step.
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
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).
|
||||
# Automated daily unsigned nightly build at 07:00 UTC plus supervised manual runs.
|
||||
on:
|
||||
schedule:
|
||||
- cron: '0 7 * * *'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
@@ -22,9 +23,9 @@ jobs:
|
||||
actions: read
|
||||
attestations: write
|
||||
id-token: write
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main
|
||||
with:
|
||||
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
|
||||
tooling-revision: main
|
||||
app-name: wordcraft
|
||||
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
@@ -32,3 +33,4 @@ jobs:
|
||||
# craft-common-actions main commit that merged the exact-analysis admission (#371, after #370,
|
||||
# #369 and #364).
|
||||
platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'
|
||||
linux-package-formats: '["deb","rpm","appimage","flatpak","oci","arch"]'
|
||||
|
||||
@@ -10,7 +10,7 @@ permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: sonarcloud-${{ github.ref }}
|
||||
group: ${{ github.ref == 'refs/heads/main' && format('sonarcloud-main-{0}', github.sha) || format('sonarcloud-{0}', github.ref) }}
|
||||
# A push to main is the run that publishes coverage; superseded runs there would never finish.
|
||||
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
|
||||
|
||||
|
||||
@@ -258,6 +258,7 @@ The UI icons are SVG files in `crates/ui-egui/icons/`, one row each below. Gener
|
||||
| `crates/ui-egui/icons/pageNumber.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
|
||||
| `crates/ui-egui/icons/pageWidth.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
|
||||
| `crates/ui-egui/icons/painter.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
|
||||
| `crates/ui-egui/icons/painter-fill.svg` | WordCraft contributors | original: the Format Painter's yellow bar, split out as the fill drawn under `painter.svg` | MIT OR Apache-2.0 | UI icon |
|
||||
| `crates/ui-egui/icons/paraSpacing.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
|
||||
| `crates/ui-egui/icons/pastCitation.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
|
||||
| `crates/ui-egui/icons/paste.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
|
||||
|
||||
Generated
+225
-130
File diff suppressed because it is too large
Load Diff
+53
-52
@@ -37,21 +37,22 @@ wordcraft-pdf = { path = "crates/pdf" }
|
||||
# reads the ca-valencia pack), #589 (French elision suggestions first), #497 (flag-based
|
||||
# compounding), #496 (review follow-ups, en-AU) and the merged #482–#490/#495 stack; the font
|
||||
# store's `language-pack` kind is #486 (CP4.1).
|
||||
wordcraft-proof = { package = "craft-proof", git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-ssip = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
wordcraft-proof = { package = "craft-proof", git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-ssip = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
wordcraft-engine = { path = "crates/engine" }
|
||||
wordcraft-mcp = { path = "crates/mcp" }
|
||||
wordcraft-zotero = { path = "crates/zotero" }
|
||||
wordcraft-control-key = { path = "crates/control-key" }
|
||||
wordcraft-ui-egui = { path = "crates/ui-egui" }
|
||||
wordcraft-validate = { path = "crates/validate" }
|
||||
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0", default-features = false }
|
||||
craft-ui-test-kit = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0", default-features = false }
|
||||
craft-ui-test-kit = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24" }
|
||||
|
||||
# foundation
|
||||
kurbo = { version = "0.13", features = ["serde"] }
|
||||
@@ -84,28 +85,28 @@ wuff = "0.2.9"
|
||||
brotli-decompressor = "5"
|
||||
vello_cpu = "0.2"
|
||||
image = { version = "0.25", default-features = false }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0", default-features = false, features = ["write"] }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0", default-features = false, features = ["write"] }
|
||||
|
||||
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0", features = ["doc"] }
|
||||
craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-flow = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-odf = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0", features = ["text"] }
|
||||
craft-markdown = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-html = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0", features = ["flow"] }
|
||||
craft-latex = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0", features = ["detect"] }
|
||||
craft-sheet = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0", features = ["doc"] }
|
||||
craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-flow = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-odf = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0", features = ["text"] }
|
||||
craft-markdown = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-html = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0", features = ["flow"] }
|
||||
craft-latex = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0", features = ["detect"] }
|
||||
craft-sheet = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", version = "=0.1.0" }
|
||||
# zlib streams (compressed metafile pictures in `.doc` drawings); already in the lock as a dependency of other crates.
|
||||
miniz_oxide = "0.9"
|
||||
cfb = "0.15"
|
||||
@@ -173,27 +174,27 @@ debug = 0
|
||||
# The framework's patches, which Cargo does not carry over to dependents: its vendored crates from craft-libs,
|
||||
# and the egui and winit forks it builds with.
|
||||
[patch.crates-io]
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541" }
|
||||
hayro = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21" }
|
||||
hayro = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
|
||||
|
||||
|
||||
@@ -282,7 +282,8 @@ into `%LOCALAPPDATA%\Programs\ArtCraft\WordCraft`, and needs no administrator ri
|
||||
and asks for an administrator. Install only one copy: a copy for another scope is refused, so
|
||||
uninstall first to change who WordCraft is installed for. Installers and executables are code-signed.
|
||||
|
||||
**If the app doesn't open on Windows:** the desktop app initializes only DirectX 12 by default.
|
||||
**If the app doesn't open on Windows:** on 64-bit builds with a usable DirectX 12 GPU, the
|
||||
desktop app initializes only DirectX 12 by default.
|
||||
Letting wgpu also create an OpenGL instance can crash some graphics drivers (AMD's
|
||||
`atio6axx.dll`) before the window appears, so the app would flash in Task Manager and quit.
|
||||
`WGPU_BACKEND` overrides the default for troubleshooting (for example `dx12` or `vulkan`). In
|
||||
|
||||
@@ -153,6 +153,8 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm
|
||||
|
||||
## Progress log
|
||||
|
||||
- 2026-11-28: Layout indexes numbering definitions for each list and STYLEREF walk. List labels still follow the document's literal labels, start overrides and nested restart rules (#3615).
|
||||
|
||||
- 2026-11-24: Pasting a plain table over selected cells overwrites from the selection's top-left, even when the copy is wider than the selection (#6742).
|
||||
- 2026-11-21: Layout: strict column balancing measures a kept paragraph again in each candidate column, so a float in one column does not make the paragraph skip another where it fits (#6821). Readiness estimates unchanged.
|
||||
|
||||
@@ -170,6 +172,7 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm
|
||||
- 2026-11-15: Native, built-in and web Insert/Change Picture choosers offer both TIFF extensions (`.tif`, `.tiff`) alongside other supported pictures; native drops, picked-file inbox dispatch and pasted picture paths recognize the same suffixes (#6704). TIFF decoding remains limited to supported compression.
|
||||
|
||||
|
||||
- 2026-11-27: Replace with curls a quote typed there when smart quotes are on, as typing does: finding `^034` and replacing with a typed `"` curls stray straight quotes in bulk; `^034` and `^039` stay straight, and a curly quote a typed `'` also finds is left and not counted (#7307).
|
||||
- 2026-11-15: Get the Missing Fonts. A document opened from a file that is missing fonts their publisher gives away (Microsoft's Aptos family, the default in recent Word documents; Cascadia Code and Mono) brings up a box naming each font, the font drawn instead, the publisher's download page and how to install the download, with Don't show this again. `font.missing` reports the same page, so agents get it without the box. WordCraft links to the page only; it downloads and bundles nothing.
|
||||
- 2026-10-30: Track Changes: a list item deleted whole, text and paragraph mark, shows its number as deleted text, in the deletion's colour and with its mark (struck through by default, or caret, #, bold, italic, underline), and hides it with No Markup or when Track Changes Options hide deletions (#4828). Readiness unchanged.
|
||||
- 2026-11-03: A picture inserted or pasted in a table cell fits the cell, as in Word, instead of running out of it; in text columns it fits the column, in a section with other margins that section's width (#5428).
|
||||
@@ -981,6 +984,7 @@ MATH glyphs that reference the same construction now share its immutable variant
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-27 | trivial | Progress log: a quote typed in Replace with goes in curly when smart quotes are on (#7307) |
|
||||
| 2026-11-18 | trivial | DOCX validation reports undeclared binary tombstones in coverage notes when relationship discovery establishes that no relationship targets the part. |
|
||||
| 2026-11-18 | trivial | DOCX validation excludes the content-type manifest from main-part cardinality and reports untargeted ordinary document parts in coverage when one ordinary main is established. |
|
||||
| 2026-11-18 | trivial | DOCX validation warns on an image signature mismatch when the image is unused or can be decoded in another raster format. Used, unusable images retain their error. |
|
||||
|
||||
@@ -43,6 +43,7 @@ craft = { workspace = true, features = [
|
||||
"platform-appearance",
|
||||
"platform-clipboard-system",
|
||||
] }
|
||||
craft-nightly = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
# Temporary settings folders for the `prefs` tests.
|
||||
|
||||
@@ -1,23 +1,11 @@
|
||||
//! 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 use craft_nightly::BuildFlavor;
|
||||
|
||||
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
|
||||
}
|
||||
@@ -37,7 +25,10 @@ pub fn version_query(args: &[OsString]) -> bool {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use super::{BuildFlavor, needs_native_error, version, version_query};
|
||||
use craft_nightly::{Profile, ProfileError, StartupOptions, canonical_profile_root, parse_startup};
|
||||
use std::ffi::OsString;
|
||||
|
||||
#[test]
|
||||
fn only_a_nightly_desktop_refusal_requests_a_native_dialog() {
|
||||
assert!(needs_native_error(BuildFlavor::NightlyV1, true));
|
||||
@@ -47,19 +38,22 @@ mod tests {
|
||||
}
|
||||
|
||||
#[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());
|
||||
fn direct_nightly_launch_self_isolates_into_canonical_profile_root() {
|
||||
let spec = crate::profile_root::spec();
|
||||
let expected_root = canonical_profile_root(spec.app_id).unwrap();
|
||||
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, [OsString::from("letter.docx")], &StartupOptions::new()).unwrap();
|
||||
assert_eq!(launch.profile, Profile::NightlyV1(expected_root));
|
||||
assert_eq!(launch.passthrough_args, vec![OsString::from("letter.docx")]);
|
||||
}
|
||||
|
||||
#[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());
|
||||
fn stable_build_refuses_nightly_launch_flags() {
|
||||
let spec = crate::profile_root::spec();
|
||||
let args = craft_nightly::launch_arguments(std::path::Path::new(crate::launch_profile::launcher_root()), &[]);
|
||||
let err = parse_startup(BuildFlavor::Stable, &spec, args, &StartupOptions::new()).unwrap_err();
|
||||
assert!(matches!(err, ProfileError::NightlyFlagsInStableBuild));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_version_query_is_unambiguous_and_never_reinterprets_file_arguments() {
|
||||
assert_eq!(version(BuildFlavor::Stable, "0.18.1"), "0.18.1");
|
||||
|
||||
@@ -1,174 +1,132 @@
|
||||
//! 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.
|
||||
//! Nightly-v1 bootstrap backed by `craft-nightly`. Selected before logging, preferences, fonts or
|
||||
//! saved state. Stable launches retain their original arguments and directory policy.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::sync::OnceLock;
|
||||
use std::ffi::{OsStr, OsString};
|
||||
|
||||
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 use craft_nightly::Profile;
|
||||
|
||||
/// Returns the active launch profile for this process, defaulting to [`Profile::Stable`] before
|
||||
/// `craft_nightly::prepare_launch` installs one.
|
||||
pub fn current() -> &'static Profile {
|
||||
PROFILE.get().unwrap_or(&Profile::Stable)
|
||||
static STABLE: Profile = Profile::Stable;
|
||||
craft_nightly::current().unwrap_or(&STABLE)
|
||||
}
|
||||
|
||||
pub fn install(profile: Profile) -> Result<(), String> {
|
||||
PROFILE.set(profile).map_err(|_| "the launch profile was already selected".into())
|
||||
fn is_nightly_flag_token(arg: &OsStr) -> bool {
|
||||
arg.to_str().is_some_and(|s| {
|
||||
s == craft_nightly::LAUNCH_PROFILE_FLAG
|
||||
|| s == craft_nightly::PROFILE_ROOT_FLAG
|
||||
|| s.starts_with("--launch-profile=")
|
||||
|| s.starts_with("--profile-root=")
|
||||
})
|
||||
}
|
||||
|
||||
/// 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" {
|
||||
/// Returns `true` when `args` starts with nightly launch protocol flags followed by `--`.
|
||||
/// `craft_nightly::parse_startup` consumes that `--`; preserving it lets `main.rs`'s
|
||||
/// `split_at_delimiter` treat every argument after `--` as a document path.
|
||||
pub fn had_launcher_separator(args: &[OsString]) -> bool {
|
||||
if !args.first().is_some_and(|arg| is_nightly_flag_token(arg)) {
|
||||
return false;
|
||||
}
|
||||
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)
|
||||
let mut idx = 0;
|
||||
while let Some(arg) = args.get(idx) {
|
||||
if arg == "--" {
|
||||
return true;
|
||||
}
|
||||
if arg == craft_nightly::LAUNCH_PROFILE_FLAG || arg == craft_nightly::PROFILE_ROOT_FLAG {
|
||||
idx += 2;
|
||||
} else if arg.to_str().is_some_and(|s| s.starts_with("--launch-profile=") || s.starts_with("--profile-root=")) {
|
||||
idx += 1;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// 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)
|
||||
/// Re-attaches the `--` separator when `craft_nightly` stripped one from an explicit launcher
|
||||
/// header, leaving direct-launch arguments untouched.
|
||||
pub fn passthrough_args(args: Vec<OsString>, had_separator: bool) -> Vec<OsString> {
|
||||
if had_separator { std::iter::once(OsString::from("--")).chain(args).collect() } else { args }
|
||||
}
|
||||
|
||||
/// The root the Launcher hands a nightly on this platform, in that platform's own spelling: `C:\NightlyData\profiles\wordcraft`
|
||||
/// on Windows, `/nightly-data/profiles/wordcraft` elsewhere. A test that fixtures the hand-off uses this rather than a
|
||||
/// literal, because a root literal in the other platform's spelling is not absolute here and `parse` refuses it (#7849).
|
||||
/// literal, because a root literal in the other platform's spelling is not absolute here and validation refuses it (#7849).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn launcher_root() -> &'static str {
|
||||
if cfg!(windows) { r"C:\NightlyData\profiles\wordcraft" } else { "/nightly-data/profiles/wordcraft" }
|
||||
}
|
||||
|
||||
/// Resolve the selected private root before the caller's first startup effect.
|
||||
pub fn validate_root(root: &Path) -> Result<PathBuf, String> {
|
||||
crate::profile_root::validate(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref(), crate::profile_root::probe_writable)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::cell::Cell;
|
||||
use super::{had_launcher_separator, launcher_root, passthrough_args};
|
||||
use craft_nightly::{
|
||||
BuildFlavor, NIGHTLY_V1_CONTRACT, Profile, ProfileError, StartupOptions, canonical_profile_root, parse_startup, validate_and_prepare_root,
|
||||
};
|
||||
use std::ffi::OsString;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn args(values: &[&str]) -> Vec<OsString> {
|
||||
values.iter().map(OsString::from).collect()
|
||||
}
|
||||
|
||||
fn absolute() -> &'static str {
|
||||
super::launcher_root()
|
||||
launcher_root()
|
||||
}
|
||||
|
||||
fn nightly() -> Vec<OsString> {
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"])
|
||||
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--"])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stable_arguments_and_directory_policy_are_unchanged() {
|
||||
let spec = crate::profile_root::spec();
|
||||
for argv in [args(&[]), args(&["--control", "7981", "a.docx"]), args(&["--", "--launch-profile", "file.docx"])] {
|
||||
let launch = prepare(parse(argv.clone()).unwrap(), |_| panic!("stable must never validate a nightly root")).unwrap();
|
||||
assert_eq!(launch, Launch { profile: Profile::Stable, args: argv });
|
||||
let had_sep = had_launcher_separator(&argv);
|
||||
assert!(!had_sep);
|
||||
let launch = parse_startup(BuildFlavor::Stable, &spec, argv.clone(), &StartupOptions::new()).unwrap();
|
||||
assert_eq!(launch.profile, Profile::Stable);
|
||||
assert_eq!(passthrough_args(launch.passthrough_args, had_sep), argv);
|
||||
}
|
||||
}
|
||||
|
||||
#[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"]));
|
||||
fn direct_nightly_launch_resolves_canonical_root_and_preserves_user_arguments() {
|
||||
let spec = crate::profile_root::spec();
|
||||
let expected_root = canonical_profile_root(spec.app_id).unwrap();
|
||||
let argv = args(&["--sample", "letter.docx"]);
|
||||
let had_sep = had_launcher_separator(&argv);
|
||||
assert!(!had_sep);
|
||||
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::new()).unwrap();
|
||||
assert_eq!(launch.profile, Profile::NightlyV1(expected_root));
|
||||
assert_eq!(passthrough_args(launch.passthrough_args, had_sep), argv);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() {
|
||||
fn exact_version_and_root_are_parsed_without_reinterpreting_file_names() {
|
||||
let spec = crate::profile_root::spec();
|
||||
let mut argv = nightly();
|
||||
argv.extend(args(&["--profile-root", "letter with spaces.docx"]));
|
||||
let had_sep = had_launcher_separator(&argv);
|
||||
assert!(had_sep);
|
||||
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv, &StartupOptions::new()).unwrap();
|
||||
assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute())));
|
||||
assert_eq!(passthrough_args(launch.passthrough_args, had_sep), args(&["--", "--profile-root", "letter with spaces.docx"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_duplicate_and_unknown_profile_arguments_are_refused() {
|
||||
let spec = crate::profile_root::spec();
|
||||
for argv in [
|
||||
args(&["--launch-profile", VERSION]),
|
||||
args(&["--launch-profile", NIGHTLY_V1_CONTRACT]),
|
||||
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()]),
|
||||
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", "", "--"]),
|
||||
] {
|
||||
assert!(parse(argv).is_err());
|
||||
assert!(parse_startup(BuildFlavor::NightlyV1, &spec, argv, &StartupOptions::new()).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -177,53 +135,36 @@ mod tests {
|
||||
/// instead of run against a directory this platform never meant.
|
||||
#[test]
|
||||
fn a_root_absolute_only_in_the_other_platforms_spelling_is_refused() {
|
||||
let spec = crate::profile_root::spec();
|
||||
let foreign = if cfg!(windows) { "/nightly-data/profiles/wordcraft" } else { r"C:\NightlyData\profiles\wordcraft" };
|
||||
let argv = args(&["--launch-profile", VERSION, "--profile-root", foreign, "--"]);
|
||||
assert!(parse(argv).is_err(), "the other platform's root spelling must not stand in: {foreign}");
|
||||
let err = validate_and_prepare_root(std::path::Path::new(foreign), &spec).unwrap_err();
|
||||
assert!(matches!(err, ProfileError::RelativeProfileRoot(_)), "the other platform's root spelling must not stand in: {foreign}");
|
||||
}
|
||||
|
||||
#[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];
|
||||
fn launcher_and_plain_version_queries_are_recognized() {
|
||||
let spec = crate::profile_root::spec();
|
||||
let pair = &["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute()];
|
||||
let reversed = &["--profile-root", absolute(), "--launch-profile", NIGHTLY_V1_CONTRACT];
|
||||
for flag in ["--version", "-V"] {
|
||||
let plain = parse_startup(BuildFlavor::NightlyV1, &spec, args(&[flag]), &StartupOptions::new()).unwrap();
|
||||
assert!(plain.is_version_query());
|
||||
for form in [pair, reversed] {
|
||||
let mut argv = args(form);
|
||||
argv.push(flag.into());
|
||||
assert!(version_query(&argv), "{argv:?}");
|
||||
let direct = parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::new()).unwrap();
|
||||
assert!(direct.is_version_query());
|
||||
argv.push("letter with spaces.docx".into());
|
||||
let with_document = parse_startup(BuildFlavor::NightlyV1, &spec, argv, &StartupOptions::new()).unwrap();
|
||||
assert!(!with_document.is_version_query());
|
||||
assert_eq!(with_document.passthrough_args, args(&[flag, "letter with spaces.docx"]));
|
||||
|
||||
let mut with_sep = args(form);
|
||||
with_sep.push("--".into());
|
||||
with_sep.push(flag.into());
|
||||
let separated = parse_startup(BuildFlavor::NightlyV1, &spec, with_sep, &StartupOptions::new()).unwrap();
|
||||
assert!(separated.is_version_query());
|
||||
}
|
||||
}
|
||||
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());
|
||||
}
|
||||
}
|
||||
|
||||
+31
-17
@@ -415,34 +415,40 @@ fn report_launch_profile_error(error: &str) {
|
||||
|
||||
/// Select the immutable launch profile before any startup service or side effect.
|
||||
fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
|
||||
// The trusted Launcher protocol is decided before logging, crash handling, the update helper,
|
||||
// The launch profile 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))
|
||||
{
|
||||
// Plain `--version` / `-V` on nightly: answered before root resolution, validation,
|
||||
// process identity, IPC or any window.
|
||||
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && build_flavor::version_query(&argv) {
|
||||
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))
|
||||
let had_separator = launch_profile::had_launcher_separator(&argv);
|
||||
let early = craft_nightly::prepare_launch(build_flavor::COMPILED, &profile_root::spec(), argv, &craft_nightly::StartupOptions::new())
|
||||
.unwrap_or_else(|error| {
|
||||
report_launch_profile_error(&error);
|
||||
report_launch_profile_error(&error.to_string());
|
||||
std::process::exit(2)
|
||||
});
|
||||
// Launcher `--launch-profile nightly-v1 --profile-root <dir> [--] --version` / `-V`:
|
||||
// `craft_nightly::prepare_launch` skips root validation and profile installation for
|
||||
// version queries, so answer and exit before any startup side effect.
|
||||
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && early.is_version_query() {
|
||||
let line = build_flavor::version(build_flavor::COMPILED, env!("WORDCRAFT_BUILT_VERSION"));
|
||||
let _ = std::io::Write::write_all(&mut std::io::stdout(), format!("{line}\n").as_bytes());
|
||||
return None;
|
||||
}
|
||||
if let Err(error) = initialize_nightly_process_identity() {
|
||||
report_launch_profile_error(&error.to_string());
|
||||
std::process::exit(2);
|
||||
}
|
||||
let identity = if early.profile.is_nightly() {
|
||||
wordcraft_ui_egui::os_window::LaunchIdentity::NightlyV1
|
||||
} else {
|
||||
wordcraft_ui_egui::os_window::LaunchIdentity::Stable
|
||||
};
|
||||
if let Err(error) = launch_profile::install(early.profile).and_then(|()| wordcraft_ui_egui::os_window::select_identity(identity)) {
|
||||
if let Err(error) = wordcraft_ui_egui::os_window::select_identity(identity) {
|
||||
report_launch_profile_error(&error);
|
||||
std::process::exit(2);
|
||||
}
|
||||
@@ -454,7 +460,7 @@ fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
|
||||
report_launch_profile_error(&error);
|
||||
std::process::exit(2);
|
||||
}
|
||||
Some(early.args)
|
||||
Some(launch_profile::passthrough_args(early.passthrough_args, had_separator))
|
||||
}
|
||||
|
||||
/// Parses the command line, installs logging and the panic hook, restores preferences and window
|
||||
@@ -1199,14 +1205,22 @@ mod command_line_tests {
|
||||
use super::{documents_to_open, split_at_delimiter};
|
||||
|
||||
/// The argv the Launcher starts a nightly with, as `prepare_launch` hands it on. The root is the one this
|
||||
/// platform would pass: `/nightly-data/...` has no drive prefix, so on Windows `parse` rightly refuses it.
|
||||
/// platform would pass: `/nightly-data/...` has no drive prefix, so on Windows validation rightly refuses it.
|
||||
fn launcher_argv(tail: &[&str]) -> Vec<String> {
|
||||
let mut argv: Vec<std::ffi::OsString> = ["--launch-profile", "nightly-v1", "--profile-root", super::launch_profile::launcher_root(), "--"]
|
||||
.iter()
|
||||
.map(std::ffi::OsString::from)
|
||||
.collect();
|
||||
argv.extend(tail.iter().map(std::ffi::OsString::from));
|
||||
super::launch_profile::parse(argv).unwrap().args.iter().map(|a| a.to_string_lossy().into_owned()).collect()
|
||||
let had_separator = super::launch_profile::had_launcher_separator(&argv);
|
||||
let launch = craft_nightly::parse_startup(
|
||||
crate::build_flavor::BuildFlavor::NightlyV1,
|
||||
&crate::profile_root::spec(),
|
||||
argv,
|
||||
&craft_nightly::StartupOptions::new(),
|
||||
)
|
||||
.unwrap();
|
||||
super::launch_profile::passthrough_args(launch.passthrough_args, had_separator).iter().map(|a| a.to_string_lossy().into_owned()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+161
-479
@@ -1,4 +1,5 @@
|
||||
//! App-owned nightly profile fences; no stable fallback, migration or process environment changes.
|
||||
//! App-owned nightly profile specification for `craft-nightly`; 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/`,
|
||||
@@ -8,528 +9,209 @@
|
||||
//! (`wordcraft_engine::packs::use_font_store_in`). Every stable location of either is fenced here.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use craft_nightly::AppProfileSpec;
|
||||
|
||||
/// 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";
|
||||
pub const APP_ID: &str = "wordcraft";
|
||||
pub const DISPLAY_NAME: &str = "WordCraft";
|
||||
pub const STABLE_PACKAGE_ID: &str = "ai.storyteller.wordcraft";
|
||||
pub const NIGHTLY_PACKAGE_ID: &str = "ai.storyteller.wordcraft.nightly";
|
||||
pub const STABLE_DIR_NAMES: &[&str] = &["wordcraft", "WordCraft", "craft-fonts", "Craft Fonts"];
|
||||
pub const FORBIDDEN_ENV_VARS: &[&str] = &["WORDCRAFT_PROFILE_DIR"];
|
||||
pub const FOLDER_ONLY_ENTRIES: &[&str] = &["recovery", "logs", "fonts", "Templates", "FontStore"];
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Platform {
|
||||
Windows,
|
||||
Linux,
|
||||
Mac,
|
||||
/// Returns WordCraft's `craft-nightly` isolation specification, including OS-specific installation
|
||||
/// and sandbox roots that must never overlap a nightly profile.
|
||||
pub fn spec() -> AppProfileSpec {
|
||||
spec_with(|key| std::env::var_os(key))
|
||||
}
|
||||
|
||||
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 spec_with(env: impl Fn(&str) -> Option<OsString>) -> AppProfileSpec {
|
||||
AppProfileSpec {
|
||||
app_id: APP_ID,
|
||||
display_name: DISPLAY_NAME,
|
||||
stable_dir_names: STABLE_DIR_NAMES,
|
||||
stable_package_id: STABLE_PACKAGE_ID,
|
||||
nightly_package_id: NIGHTLY_PACKAGE_ID,
|
||||
profile_root_env: None,
|
||||
forbidden_env_vars: FORBIDDEN_ENV_VARS,
|
||||
portable_markers: &[],
|
||||
folder_only_entries: FOLDER_ONLY_ENTRIES,
|
||||
extra_forbidden_roots: extra_forbidden_roots_with(env),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(unix, target_os = "windows"))]
|
||||
fn non_empty_abs(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Option<PathBuf> {
|
||||
let value = env(key)?;
|
||||
if value.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let path = PathBuf::from(value);
|
||||
if path.is_absolute() { Some(path) } else { None }
|
||||
}
|
||||
|
||||
fn extra_forbidden_roots_with(env: impl Fn(&str) -> Option<OsString>) -> Vec<PathBuf> {
|
||||
let mut roots = Vec::new();
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
// Per-user and per-machine MSI install locations.
|
||||
if let Some(local) =
|
||||
non_empty_abs(&env, "LOCALAPPDATA").or_else(|| non_empty_abs(&env, "USERPROFILE").map(|p| p.join("AppData").join("Local")))
|
||||
{
|
||||
roots.push(local.join("Programs").join("ArtCraft").join("WordCraft"));
|
||||
}
|
||||
}
|
||||
|
||||
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")?;
|
||||
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
|
||||
if let Some(base) = non_empty_abs(&env, key) {
|
||||
roots.push(base.join("ArtCraft").join("WordCraft"));
|
||||
}
|
||||
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());
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
{
|
||||
// Native packages' locations and the stable Flatpak's per-app data folder.
|
||||
roots.extend(["/usr/bin/wordcraft", "/usr/local/bin/wordcraft", "/opt/wordcraft"].map(PathBuf::from));
|
||||
if let Some(home) = non_empty_abs(&env, "HOME") {
|
||||
roots.push(home.join(".var/app/ai.storyteller.wordcraft"));
|
||||
}
|
||||
}
|
||||
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")?;
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
roots.push(PathBuf::from("/Applications/WordCraft.app"));
|
||||
if let Some(home) = non_empty_abs(&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(library.join("Preferences/ai.storyteller.wordcraft.plist"));
|
||||
roots.push(library.join("Saved Application State/ai.storyteller.wordcraft.savedState"));
|
||||
roots.push(home.join("Applications/WordCraft.app"));
|
||||
}
|
||||
};
|
||||
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(not(any(unix, target_os = "windows")))]
|
||||
let _ = env;
|
||||
roots
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use super::{
|
||||
APP_ID, DISPLAY_NAME, FOLDER_ONLY_ENTRIES, FORBIDDEN_ENV_VARS, NIGHTLY_PACKAGE_ID, STABLE_DIR_NAMES, STABLE_PACKAGE_ID,
|
||||
extra_forbidden_roots_with, spec_with,
|
||||
};
|
||||
use craft_nightly::{ProfileError, validate_and_prepare_root};
|
||||
use std::collections::BTreeMap;
|
||||
use std::ffi::OsString;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
struct Fixture {
|
||||
root: PathBuf,
|
||||
env: BTreeMap<String, OsString>,
|
||||
exe: PathBuf,
|
||||
}
|
||||
struct TempRoot(PathBuf);
|
||||
|
||||
impl Fixture {
|
||||
fn new() -> Self {
|
||||
impl TempRoot {
|
||||
fn new(label: &str) -> 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)));
|
||||
let candidate = std::env::temp_dir().join(format!(
|
||||
"wordcraft-profile-spec-{label}-{}-{}",
|
||||
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())
|
||||
Self(root)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Fixture {
|
||||
impl Drop for TempRoot {
|
||||
fn drop(&mut self) {
|
||||
// Only the directory successfully created by this fixture is owned for removal.
|
||||
std::fs::remove_dir_all(&self.root).unwrap();
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[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);
|
||||
fn spec_preserves_wordcraft_isolation_contract() {
|
||||
let spec = spec_with(|_| None);
|
||||
assert_eq!(spec.app_id, APP_ID);
|
||||
assert_eq!(spec.display_name, DISPLAY_NAME);
|
||||
assert_eq!(spec.stable_dir_names, STABLE_DIR_NAMES);
|
||||
assert_eq!(spec.stable_package_id, STABLE_PACKAGE_ID);
|
||||
assert_eq!(spec.nightly_package_id, NIGHTLY_PACKAGE_ID);
|
||||
assert_eq!(spec.profile_root_env, None);
|
||||
assert_eq!(spec.forbidden_env_vars, FORBIDDEN_ENV_VARS);
|
||||
assert!(spec.portable_markers.is_empty());
|
||||
assert_eq!(spec.folder_only_entries, FOLDER_ONLY_ENTRIES);
|
||||
}
|
||||
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
#[test]
|
||||
fn linux_extra_forbidden_roots_cover_native_packages_and_stable_flatpak() {
|
||||
let env = BTreeMap::from([(String::from("HOME"), OsString::from("/home/tester"))]);
|
||||
let roots = extra_forbidden_roots_with(|k| env.get(k).cloned());
|
||||
assert!(roots.contains(&PathBuf::from("/usr/bin/wordcraft")));
|
||||
assert!(roots.contains(&PathBuf::from("/usr/local/bin/wordcraft")));
|
||||
assert!(roots.contains(&PathBuf::from("/opt/wordcraft")));
|
||||
assert!(roots.contains(&PathBuf::from("/home/tester/.var/app/ai.storyteller.wordcraft")));
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
#[test]
|
||||
fn macos_extra_forbidden_roots_cover_bundles_plist_and_saved_state() {
|
||||
let env = BTreeMap::from([(String::from("HOME"), OsString::from("/Users/tester"))]);
|
||||
let roots = extra_forbidden_roots_with(|k| env.get(k).cloned());
|
||||
assert!(roots.contains(&PathBuf::from("/Applications/WordCraft.app")));
|
||||
assert!(roots.contains(&PathBuf::from("/Users/tester/Applications/WordCraft.app")));
|
||||
assert!(roots.contains(&PathBuf::from("/Users/tester/Library/Preferences/ai.storyteller.wordcraft.plist")));
|
||||
assert!(roots.contains(&PathBuf::from("/Users/tester/Library/Saved Application State/ai.storyteller.wordcraft.savedState")));
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
#[test]
|
||||
fn windows_extra_forbidden_roots_cover_per_user_and_machine_installs() {
|
||||
let env = BTreeMap::from([
|
||||
(String::from("LOCALAPPDATA"), OsString::from(r"C:\Users\tester\AppData\Local")),
|
||||
(String::from("ProgramFiles"), OsString::from(r"C:\Program Files")),
|
||||
(String::from("ProgramFiles(x86)"), OsString::from(r"C:\Program Files (x86)")),
|
||||
]);
|
||||
let roots = extra_forbidden_roots_with(|k| env.get(k).cloned());
|
||||
assert!(roots.contains(&PathBuf::from(r"C:\Users\tester\AppData\Local\Programs\ArtCraft\WordCraft")));
|
||||
assert!(roots.contains(&PathBuf::from(r"C:\Program Files\ArtCraft\WordCraft")));
|
||||
assert!(roots.contains(&PathBuf::from(r"C:\Program Files (x86)\ArtCraft\WordCraft")));
|
||||
}
|
||||
|
||||
#[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"));
|
||||
fn nightly_profile_reopens_and_enforces_folder_only_entries_and_extra_fences() {
|
||||
let temp = TempRoot::new("reopen");
|
||||
let fenced = temp.0.join("fenced-stable");
|
||||
let mut spec = spec_with(|_| None);
|
||||
spec.extra_forbidden_roots.push(fenced.clone());
|
||||
|
||||
let overlap = validate_and_prepare_root(&fenced.join("nightly"), &spec).unwrap_err();
|
||||
assert!(matches!(overlap, ProfileError::ForbiddenRootOverlap { .. }));
|
||||
assert!(!fenced.exists());
|
||||
|
||||
let private = temp.0.join("nightly-private");
|
||||
assert_eq!(validate_and_prepare_root(&private, &spec).unwrap(), private);
|
||||
for name in ["config.toml", "window.json", "nightly-session.lock", "nightly-session.json"] {
|
||||
std::fs::write(private.join(name), b"saved profile data").unwrap();
|
||||
}
|
||||
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());
|
||||
for name in FOLDER_ONLY_ENTRIES {
|
||||
std::fs::create_dir(private.join(name)).unwrap();
|
||||
}
|
||||
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());
|
||||
assert_eq!(validate_and_prepare_root(&private, &spec).unwrap(), private);
|
||||
for name in ["config.toml", "window.json", "nightly-session.lock", "nightly-session.json"] {
|
||||
assert_eq!(std::fs::read(private.join(name)).unwrap(), b"saved profile data", "{name} remains intact after reopen");
|
||||
}
|
||||
let fonts = PathBuf::from(fixture.get("LOCALAPPDATA").unwrap()).join("Craft Fonts");
|
||||
assert!(fixture.check(Platform::Windows, &fonts.join("nightly")).unwrap_err().contains("overlap"));
|
||||
assert!(fixture.check(Platform::Windows, &fixture.exe.parent().unwrap().join("profile")).is_err());
|
||||
let local = PathBuf::from(fixture.get("LOCALAPPDATA").unwrap());
|
||||
let per_user = local.join("Programs").join("ArtCraft").join("WordCraft");
|
||||
assert!(fixture.check(Platform::Windows, &per_user.join("nightly")).unwrap_err().contains("overlap"));
|
||||
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
|
||||
let base = fixture.root.join(format!("machine {key}"));
|
||||
fixture.env.insert(key.into(), base.clone().into_os_string());
|
||||
let machine = base.join("ArtCraft").join("WordCraft");
|
||||
assert!(fixture.check(Platform::Windows, &machine.join("nightly")).unwrap_err().contains("overlap"));
|
||||
assert!(!machine.exists());
|
||||
|
||||
for name in FOLDER_ONLY_ENTRIES {
|
||||
let path = private.join(name);
|
||||
std::fs::remove_dir(&path).unwrap();
|
||||
std::fs::write(&path, b"not a directory").unwrap();
|
||||
let err = validate_and_prepare_root(&private, &spec).unwrap_err();
|
||||
assert!(matches!(err, ProfileError::ExpectedDirectoryEntry(_)), "{name} must stay a directory");
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
std::fs::create_dir(&path).unwrap();
|
||||
}
|
||||
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");
|
||||
}
|
||||
}
|
||||
|
||||
+145
-9
@@ -109,6 +109,55 @@ pub struct Numbering {
|
||||
pub nums: Vec<Num>,
|
||||
}
|
||||
|
||||
/// Borrowed definition lookups for a walk over immutable numbering. The first occurrence of
|
||||
/// each id wins, as in the linear methods; the public vectors and saved data are unchanged.
|
||||
pub struct NumberingIndex<'a> {
|
||||
nums: HashMap<u32, &'a Num>,
|
||||
abstracts: HashMap<u32, &'a AbstractNum>,
|
||||
}
|
||||
|
||||
impl<'a> NumberingIndex<'a> {
|
||||
pub fn new(numbering: &'a Numbering) -> Self {
|
||||
let mut nums = HashMap::new();
|
||||
let mut abstracts = HashMap::new();
|
||||
for n in &numbering.nums {
|
||||
nums.entry(n.id).or_insert(n);
|
||||
}
|
||||
for a in &numbering.abstracts {
|
||||
abstracts.entry(a.id).or_insert(a);
|
||||
}
|
||||
Self { nums, abstracts }
|
||||
}
|
||||
|
||||
pub fn num(&self, id: u32) -> Option<&'a Num> {
|
||||
self.nums.get(&id).copied()
|
||||
}
|
||||
|
||||
pub fn abstract_of(&self, num: u32) -> Option<&'a AbstractNum> {
|
||||
self.abstract_for(self.num(num)?)
|
||||
}
|
||||
|
||||
fn abstract_for(&self, num: &Num) -> Option<&'a AbstractNum> {
|
||||
self.abstracts.get(&num.abstract_id).copied()
|
||||
}
|
||||
|
||||
pub fn level(&self, num: u32, level: u8) -> Option<&'a Level> {
|
||||
let n = self.num(num)?;
|
||||
n.level(self.abstract_for(n), level)
|
||||
}
|
||||
|
||||
/// Whether a paragraph has a defined label, without advancing the counters.
|
||||
pub fn shows_label(&self, num: u32, level: u8) -> bool {
|
||||
self.num(num).is_some_and(|n| self.abstract_for(n).is_some_and(|a| n.level(Some(a), level.min(8)).is_some()))
|
||||
}
|
||||
}
|
||||
|
||||
impl Num {
|
||||
fn level<'a>(&'a self, abstract_num: Option<&'a AbstractNum>, level: u8) -> Option<&'a Level> {
|
||||
self.level_overrides.iter().find(|(i, _)| *i == level).map(|(_, l)| l).or_else(|| abstract_num?.levels.get(level as usize))
|
||||
}
|
||||
}
|
||||
|
||||
/// Built-in list kinds for the Bullets / Numbering / Multilevel galleries.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -321,10 +370,28 @@ impl Counters {
|
||||
/// Advance the counter for `num`/`level` and return the label (`"1."`, `"a)"`, `"•"`).
|
||||
pub fn next_label(&mut self, numbering: &Numbering, num: u32, level: u8) -> Option<(String, Level)> {
|
||||
let n = numbering.num(num)?;
|
||||
let abs = numbering.abstracts.iter().find(|a| a.id == n.abstract_id)?;
|
||||
self.next_label_from(n, abs, level)
|
||||
}
|
||||
|
||||
/// Like [`Self::next_label`], using one walk's borrowed definition index.
|
||||
pub fn next_label_indexed(&mut self, numbering: &NumberingIndex<'_>, num: u32, level: u8) -> Option<(String, Level)> {
|
||||
let n = numbering.num(num)?;
|
||||
let abs = numbering.abstract_for(n)?;
|
||||
self.next_label_from(n, abs, level)
|
||||
}
|
||||
|
||||
/// Like [`Self::values`], using one walk's borrowed definition index.
|
||||
pub fn values_indexed(&self, numbering: &NumberingIndex<'_>, num: u32) -> Option<[u32; 9]> {
|
||||
let abs = numbering.abstract_of(num)?;
|
||||
Some(self.state.get(&abs.id).copied().unwrap_or([0; 9]))
|
||||
}
|
||||
|
||||
fn next_label_from(&mut self, n: &Num, abs: &AbstractNum, level: u8) -> Option<(String, Level)> {
|
||||
let num = n.id;
|
||||
let lv = (level as usize).min(8);
|
||||
// This list's own definition of a level wins over its abstract list's.
|
||||
let level_def = |k: usize| numbering.level(num, k as u8);
|
||||
let level_def = |k: usize| n.level(Some(abs), k as u8);
|
||||
// A "none" level (Word's numFmt none) still counts and restarts the levels below it; only
|
||||
// its number reads as nothing, so its literal text ("RESPONSE:") shows (#4985).
|
||||
let def = level_def(lv)?.clone();
|
||||
@@ -378,7 +445,7 @@ impl Counters {
|
||||
let vals = *st;
|
||||
let started = *fl;
|
||||
let numeric = def.format != NumFormat::Bullet;
|
||||
let label = if numeric { render_label(numbering, num, &def, &vals, &started) } else { def.text.clone() };
|
||||
let label = if numeric { render_label(level_def, &def, &vals, &started) } else { def.text.clone() };
|
||||
// A "none" level shows its literal text, but has no number of its own for a reference to
|
||||
// show (#4985): it is kept as one that shows none.
|
||||
let counted = if def.format == NumFormat::None {
|
||||
@@ -400,18 +467,19 @@ impl Counters {
|
||||
/// the last paragraph at that level showed (`"14."` while walking clause 14's sub-clauses).
|
||||
/// `None` for a bullet or "none" level, or a level the list doesn't define.
|
||||
pub fn current_label(&self, numbering: &Numbering, num: u32, level: u8) -> Option<String> {
|
||||
let abs = numbering.abstract_of(num)?;
|
||||
let n = numbering.num(num)?;
|
||||
let abs = numbering.abstracts.iter().find(|a| a.id == n.abstract_id)?;
|
||||
if let Some(last) = self.labels.get(&(abs.id, level.min(8))) {
|
||||
return last.label.clone();
|
||||
}
|
||||
// A deeper item can count a level implicitly without rendering a paragraph there.
|
||||
let def = numbering.level(num, level.min(8))?;
|
||||
let def = n.level(Some(abs), level.min(8))?;
|
||||
if matches!(def.format, NumFormat::None | NumFormat::Bullet) {
|
||||
return None;
|
||||
}
|
||||
let vals = self.state.get(&abs.id).copied().unwrap_or([0; 9]);
|
||||
let started = self.flags.get(&abs.id).copied().unwrap_or_default();
|
||||
Some(render_label(numbering, num, def, &vals, &started))
|
||||
Some(render_label(|k| n.level(Some(abs), k as u8), def, &vals, &started))
|
||||
}
|
||||
|
||||
/// Levels shown by the last rendered label, or the current definition for an implicit level.
|
||||
@@ -444,8 +512,7 @@ pub fn template_levels(text: &str) -> Vec<usize> {
|
||||
}
|
||||
|
||||
/// Render a list label without advancing counters, retaining the existing hostile-input caps.
|
||||
fn render_label(numbering: &Numbering, num: u32, def: &Level, vals: &[u32; 9], started: &[LevelFlags; 9]) -> String {
|
||||
let level_def = |k: usize| numbering.level(num, k as u8);
|
||||
fn render_label<'a>(level_def: impl Fn(usize) -> Option<&'a Level>, def: &Level, vals: &[u32; 9], started: &[LevelFlags; 9]) -> String {
|
||||
let mut label = String::new();
|
||||
// Word's level text is short; .docx and the lists command already cap it at 64.
|
||||
let mut chars = def.text.chars().take(MAX_LEVEL_TEXT).peekable();
|
||||
@@ -457,10 +524,11 @@ fn render_label(numbering: &Numbering, num: u32, def: &Level, vals: &[u32; 9], s
|
||||
let k = (d as usize).saturating_sub(1).min(8);
|
||||
let val = vals.get(k).copied().unwrap_or(0);
|
||||
let counted = started.get(k).is_some_and(|f| f.started);
|
||||
let val = if counted { val } else { level_def(k).map(|l| l.start).unwrap_or(1) };
|
||||
let level = level_def(k);
|
||||
let val = if counted { val } else { level.map_or(1, |l| l.start) };
|
||||
// Legal numbering (w:isLgl) shows every level in Arabic digits, whatever its own
|
||||
// format (二 of a Chinese outline becomes 2 in "2.1"); a "none" level stays empty.
|
||||
let fmt = match level_def(k).map(|l| l.format).unwrap_or(NumFormat::Decimal) {
|
||||
let fmt = match level.map_or(NumFormat::Decimal, |l| l.format) {
|
||||
f @ (NumFormat::DecimalZero | NumFormat::None) => f,
|
||||
_ if def.legal => NumFormat::Decimal,
|
||||
f => f,
|
||||
@@ -773,4 +841,72 @@ mod tests {
|
||||
let mut c = Counters::default();
|
||||
assert_eq!(c.next_label(&n, r, 0).unwrap().0, "Part V");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn definition_index_keeps_first_ids_overrides_and_missing_definitions() {
|
||||
let override_level = Level { start: 0, text: "own %1".into(), ..Default::default() };
|
||||
let n = Numbering {
|
||||
abstracts: vec![
|
||||
AbstractNum { id: 7, levels: levels_for(ListKind::Numbered), ..Default::default() },
|
||||
AbstractNum { id: 7, levels: levels_for(ListKind::Bullet), ..Default::default() },
|
||||
AbstractNum { id: 8, levels: Vec::new(), ..Default::default() },
|
||||
],
|
||||
nums: vec![
|
||||
Num { id: 0, abstract_id: 7, ..Default::default() },
|
||||
Num { id: 1, abstract_id: 7, ..Default::default() },
|
||||
Num { id: 1, abstract_id: 8, ..Default::default() },
|
||||
Num { id: 2, abstract_id: 99, level_overrides: vec![(0, override_level.clone())], ..Default::default() },
|
||||
Num { id: 3, abstract_id: 8, level_overrides: vec![(0, override_level), (0, Level::default())], ..Default::default() },
|
||||
],
|
||||
};
|
||||
let index = NumberingIndex::new(&n);
|
||||
for id in [0, 1, 2, 3, 7, 99, u32::MAX] {
|
||||
assert_eq!(index.num(id), n.num(id));
|
||||
assert_eq!(index.abstract_of(id), n.abstract_of(id));
|
||||
for level in [0, 1, 2, 8, 9, u8::MAX] {
|
||||
assert_eq!(index.level(id, level), n.level(id, level));
|
||||
assert_eq!(index.shows_label(id, level), n.shows_label(id, level));
|
||||
}
|
||||
}
|
||||
assert_eq!(index.level(3, 0).unwrap().start, 0);
|
||||
assert!(index.level(2, 0).is_some(), "a local override exists even without its abstract");
|
||||
assert!(!index.shows_label(2, 0), "counting still requires the abstract list");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn indexed_counters_preserve_shared_state_starts_and_restarts() {
|
||||
let mut n = Numbering::default();
|
||||
let a = n.add_list(ListKind::Legal);
|
||||
let b = n.restart(a).unwrap();
|
||||
let bullet = n.add_list(ListKind::Bullet);
|
||||
let none = n.add_list(ListKind::Numbered);
|
||||
n.abstracts[0].levels[0].start = 0;
|
||||
n.abstracts[0].levels[1].restart_after = Some(1);
|
||||
n.abstracts[0].levels[2].restart = false;
|
||||
n.abstracts[0].levels[3].format = NumFormat::DecimalZero;
|
||||
n.nums[0].start_overrides = vec![(1, 5), (1, 99)];
|
||||
n.nums[1].start_overrides = vec![(0, 9), (2, 0)];
|
||||
n.nums[1].level_overrides = vec![
|
||||
(2, Level { format: NumFormat::UpperRoman, text: "%1.%2.%3.".into(), legal: true, ..Default::default() }),
|
||||
(2, Level { format: NumFormat::None, ..Default::default() }),
|
||||
];
|
||||
let literal = &mut n.abstracts.last_mut().unwrap().levels[0];
|
||||
literal.format = NumFormat::None;
|
||||
literal.text = "RESPONSE: %1".into();
|
||||
literal.legal = true;
|
||||
let index = NumberingIndex::new(&n);
|
||||
let (mut linear, mut indexed) = (Counters::default(), Counters::default());
|
||||
let sequence = [(a, 2), (a, 0), (a, 1), (a, 2), (a, 1), (b, 2), (b, 0), (a, 2), (a, 3), (bullet, 0), (none, 0), (a, 255), (999, 0)];
|
||||
for (num, level) in sequence.into_iter().cycle().take(120) {
|
||||
assert_eq!(indexed.next_label_indexed(&index, num, level), linear.next_label(&n, num, level), "{num}/{level}");
|
||||
for id in [a, b, bullet, none, 999] {
|
||||
assert_eq!(indexed.values_indexed(&index, id), linear.values(&n, id));
|
||||
}
|
||||
}
|
||||
assert!(index.shows_label(none, 0));
|
||||
assert_eq!(indexed.next_label_indexed(&index, none, 0).unwrap().0, "RESPONSE: ");
|
||||
assert_eq!(indexed.next_label_indexed(&index, none, 0), linear.next_label(&n, none, 0));
|
||||
assert_eq!(indexed.current_label(&n, none, 0), None);
|
||||
assert_eq!(indexed.current_label(&n, a, 0), linear.current_label(&n, a, 0));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -506,6 +506,11 @@ pub struct ParaProps {
|
||||
/// file (not laid out yet); Word sizes a line by it, so dropping it changes Word's pages.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub text_alignment: Option<TextAlignment>,
|
||||
/// A list item's paragraph after its first (or a list header's), with no number of its own,
|
||||
/// at this list level (0..=8): formats with list items (ODT, HTML, Markdown) keep it in the
|
||||
/// item. Set only directly, never by a style.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub list_item: Option<u8>,
|
||||
}
|
||||
|
||||
impl ParaProps {
|
||||
|
||||
@@ -183,6 +183,13 @@ pub struct Settings {
|
||||
/// comments and tracked changes are saved without `w:date`.
|
||||
#[serde(skip_serializing_if = "std::ops::Not::not")]
|
||||
pub remove_date_time: bool,
|
||||
/// Hide spelling errors in this document only (`w:hideSpellingErrors`): no squiggles under
|
||||
/// misspelled words.
|
||||
#[serde(skip_serializing_if = "std::ops::Not::not")]
|
||||
pub hide_spelling_errors: bool,
|
||||
/// Hide grammar errors in this document only (`w:hideGrammaticalErrors`).
|
||||
#[serde(skip_serializing_if = "std::ops::Not::not")]
|
||||
pub hide_grammar_errors: bool,
|
||||
/// The document was opened from ODF: the standard's rules that differ from Word's apply as
|
||||
/// it is laid out.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
@@ -349,6 +356,8 @@ impl Default for Settings {
|
||||
zoom: None,
|
||||
remove_personal_info: false,
|
||||
remove_date_time: false,
|
||||
hide_spelling_errors: false,
|
||||
hide_grammar_errors: false,
|
||||
odf: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -221,6 +221,17 @@ impl Table {
|
||||
}
|
||||
row.cells.push(nc);
|
||||
}
|
||||
// #6326: text typed into a new cell gets the font formatting of the cell it was copied
|
||||
// from, as in Word: that of the first character of the source cell's first paragraph (its
|
||||
// mark when it's empty), never a link, revision mark or symbol's own font.
|
||||
for (nc, c) in row.cells.iter_mut().zip(&src.cells) {
|
||||
let mark = c.blocks.iter().find_map(|b| b.as_para()).map(|p| p.props_at(0).formatting().without_symbol());
|
||||
if let Some(mark) = mark
|
||||
&& let Some(crate::Block::Para(p)) = nc.blocks.first_mut().map(std::sync::Arc::make_mut)
|
||||
{
|
||||
p.mark = mark;
|
||||
}
|
||||
}
|
||||
self.rows.insert(at.min(self.rows.len()), row);
|
||||
}
|
||||
|
||||
@@ -744,6 +755,38 @@ mod tests {
|
||||
t.delete_col(99);
|
||||
}
|
||||
|
||||
/// #6326: a new row's empty cells type in the font formatting of the cells it was copied
|
||||
/// from, as in Word: that of the first character of the source cell's first paragraph (not
|
||||
/// its mark), or the mark of an empty one; never its link or revision marks.
|
||||
#[test]
|
||||
fn insert_row_types_in_the_source_cells_font() {
|
||||
let courier = crate::CharProps {
|
||||
font: Some("Courier New".into()),
|
||||
size: Some(16.0),
|
||||
bold: Some(true),
|
||||
link: Some("https://example.com".into()),
|
||||
ins: Some(0),
|
||||
..Default::default()
|
||||
};
|
||||
let mut p = Paragraph::with_text("A", courier.clone());
|
||||
p.insert_text(1, "B", &crate::CharProps { font: Some("Georgia".into()), ..Default::default() }).unwrap();
|
||||
p.mark = crate::CharProps { font: Some("Arial".into()), ..Default::default() };
|
||||
let mut empty = Paragraph::new();
|
||||
empty.mark = crate::CharProps { italic: Some(true), size: Some(20.0), ..Default::default() };
|
||||
let mut t = Table::new(2, 2, 200.0);
|
||||
t.rows[0].cells[0].blocks = vec![para_block(p)];
|
||||
t.rows[0].cells[1].blocks = vec![para_block(empty)];
|
||||
t.insert_row(1, 0);
|
||||
t.insert_row(0, 0);
|
||||
let want = crate::CharProps { link: None, ins: None, ..courier };
|
||||
let italic = crate::CharProps { italic: Some(true), size: Some(20.0), ..Default::default() };
|
||||
for r in [0, 2] {
|
||||
let mark = |c: usize| t.rows[r].cells[c].blocks[0].as_para().map(|p| (p.text.clone(), p.mark.clone()));
|
||||
assert_eq!(mark(0), Some((String::new(), want.clone())), "row {r}");
|
||||
assert_eq!(mark(1), Some((String::new(), italic.clone())), "row {r}");
|
||||
}
|
||||
}
|
||||
|
||||
/// #3637: a `.json` file can give a cell any span; inserting a column through it, merging it
|
||||
/// or deleting a column under it doesn't overflow, and the span it gets is in 1..=MAX_COLS.
|
||||
#[test]
|
||||
|
||||
@@ -175,6 +175,7 @@ mod tests {
|
||||
ch_w: 64.0,
|
||||
ch_h: 48.0,
|
||||
children: vec![craft_wordmodel::para::GroupChild {
|
||||
link: None,
|
||||
x: 4.0,
|
||||
y: 6.0,
|
||||
obj: craft_wordmodel::para::InlineObject::Field {
|
||||
@@ -202,7 +203,7 @@ mod tests {
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
source.settings.compat_mode = 11;
|
||||
source.settings.compat_mode = Some(11);
|
||||
let image = Arc::new(vec![0x5a; 1 << 20]);
|
||||
source.media.insert("image1.png".into(), image.clone());
|
||||
|
||||
|
||||
@@ -100,18 +100,35 @@ fn object_value_from_shared(
|
||||
float: convert(float)?,
|
||||
ch_w,
|
||||
ch_h,
|
||||
children: children.into_iter().map(|c| group_child_value_from_shared(c, graphics)).collect::<Result<_, _>>()?,
|
||||
children: group_children_from_shared(children, graphics)?,
|
||||
canvas: canvas.map(convert).transpose()?,
|
||||
}),
|
||||
other => convert(other),
|
||||
}
|
||||
}
|
||||
|
||||
fn group_child_value_from_shared(
|
||||
source: craft_wordmodel::para::GroupChild,
|
||||
/// A group's members. The shared reader keeps a hyperlinked nested group whole; WordCraft's
|
||||
/// text box, layout and edit code looks one level deep, so lift its members into this group
|
||||
/// (their offsets composed, scaled from the nested group's child space), as the reader does for
|
||||
/// an unlinked one. The nested group's own link is dropped.
|
||||
// lean: nested groups are flattened until WordCraft supports them (follow-up issue).
|
||||
fn group_children_from_shared(
|
||||
children: Vec<craft_wordmodel::para::GroupChild>,
|
||||
graphics: &mut GraphicCache,
|
||||
) -> Result<wordcraft_doc::para::GroupChild, DocxError> {
|
||||
Ok(wordcraft_doc::para::GroupChild { x: source.x, y: source.y, obj: object_value_from_shared(source.obj, graphics)? })
|
||||
) -> Result<Vec<wordcraft_doc::para::GroupChild>, DocxError> {
|
||||
let mut out = Vec::with_capacity(children.len());
|
||||
for c in children {
|
||||
let (x, y) = (c.x, c.y);
|
||||
match object_value_from_shared(c.obj, graphics)? {
|
||||
wordcraft_doc::para::InlineObject::Group { w, h, ch_w, ch_h, children, .. } => {
|
||||
let (kx, ky) = (if ch_w > 0.0 { w / ch_w } else { 1.0 }, if ch_h > 0.0 { h / ch_h } else { 1.0 });
|
||||
// `children` is already flat: the recursion converted the nested group first.
|
||||
out.extend(children.into_iter().map(|m| wordcraft_doc::para::GroupChild { x: x + m.x * kx, y: y + m.y * ky, obj: m.obj }));
|
||||
}
|
||||
obj => out.push(wordcraft_doc::para::GroupChild { x, y, obj }),
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn table_value_from_shared(source: craft_wordmodel::table::Table, graphics: &mut GraphicCache) -> Result<wordcraft_doc::table::Table, DocxError> {
|
||||
@@ -215,7 +232,10 @@ pub fn from_shared_model(mut source: craft_wordmodel::Document) -> Result<wordcr
|
||||
document.numbering = Arc::new(convert((*numbering).clone())?);
|
||||
document.comments = convert(comments)?;
|
||||
document.revisions = convert(revisions)?;
|
||||
// The shared model keeps an omitted `compatibilityMode` as `None` (Word 2007 rules); the app model has no `None`.
|
||||
let compat_mode = settings.effective_compat_mode();
|
||||
document.settings = convert(settings)?;
|
||||
document.settings.compat_mode = compat_mode;
|
||||
document.core = convert(core)?;
|
||||
document.sources = convert(sources)?;
|
||||
document.custom_props = convert(custom_props)?;
|
||||
@@ -321,7 +341,7 @@ fn object_value_to_shared(source: &wordcraft_doc::para::InlineObject) -> Result<
|
||||
}
|
||||
|
||||
fn group_child_value_to_shared(source: &wordcraft_doc::para::GroupChild) -> Result<craft_wordmodel::para::GroupChild, DocxError> {
|
||||
Ok(craft_wordmodel::para::GroupChild { x: source.x, y: source.y, obj: object_value_to_shared(&source.obj)? })
|
||||
Ok(craft_wordmodel::para::GroupChild { link: None, x: source.x, y: source.y, obj: object_value_to_shared(&source.obj)? })
|
||||
}
|
||||
|
||||
fn table_value_to_shared(source: &wordcraft_doc::table::Table) -> Result<craft_wordmodel::table::Table, DocxError> {
|
||||
@@ -558,6 +578,7 @@ mod tests {
|
||||
ch_w: 64.0,
|
||||
ch_h: 48.0,
|
||||
children: vec![craft_wordmodel::para::GroupChild {
|
||||
link: None,
|
||||
x: 4.0,
|
||||
y: 6.0,
|
||||
obj: craft_wordmodel::para::InlineObject::Field {
|
||||
@@ -585,7 +606,7 @@ mod tests {
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
source.settings.compat_mode = 11;
|
||||
source.settings.compat_mode = Some(11);
|
||||
let image = Arc::new(vec![0x5a; 1 << 16]);
|
||||
source.media.insert("image1.png".into(), image.clone());
|
||||
|
||||
|
||||
@@ -4781,3 +4781,20 @@ fn vml_horizontal_rules_are_read_and_kept() {
|
||||
let d = read_body(&body);
|
||||
assert_eq!(rules(&d).iter().map(|r| r.0).collect::<Vec<_>>(), [None, None]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hide_spelling_and_grammar_errors_survive_a_save() {
|
||||
let settings_xml = |d: &Document| {
|
||||
let bytes = wordcraft_docx::write(d).unwrap();
|
||||
let mut z = craft_zip::Archive::open(&bytes, craft_zip::Limits { max_entries: 10_000, max_total_bytes: 64 << 20 }).unwrap();
|
||||
String::from_utf8(z.read("word/settings.xml", 16 << 20).unwrap().unwrap()).unwrap()
|
||||
};
|
||||
let d = with_settings(Some("<w:hideSpellingErrors/><w:hideGrammaticalErrors/>"));
|
||||
let saved = settings_xml(&d);
|
||||
assert!(saved.contains("<w:hideSpellingErrors") && saved.contains("<w:hideGrammaticalErrors"), "{saved}");
|
||||
let again = wordcraft_docx::read(&wordcraft_docx::write(&d).unwrap()).unwrap();
|
||||
let saved = settings_xml(&again);
|
||||
assert!(saved.contains("<w:hideSpellingErrors") && saved.contains("<w:hideGrammaticalErrors"), "second save: {saved}");
|
||||
let plain = settings_xml(&with_settings(Some("")));
|
||||
assert!(!plain.contains("hideSpellingErrors") && !plain.contains("hideGrammaticalErrors"), "not invented: {plain}");
|
||||
}
|
||||
|
||||
@@ -229,6 +229,7 @@ fn every_para_prop_round_trips() {
|
||||
fmt_change: None,
|
||||
snap_to_grid: Some(false),
|
||||
text_alignment: Some(TextAlignment::Top),
|
||||
list_item: None, // not a DOCX property
|
||||
};
|
||||
let variants = [
|
||||
ParaProps { line_spacing: Some(LineSpacing::AtLeast(14.0)), indent_first: Some(24.0), align: Some(Align::Center), ..Default::default() },
|
||||
|
||||
@@ -37,7 +37,7 @@ fn section_metadata_survives_native_json_and_two_docx_save_reopen_cycles() {
|
||||
assert!(xml.contains(r#"<w15:footnoteColumns w:val="3"/>"#), "cycle {cycle}: {xml}");
|
||||
assert!(xml.contains(r#"w:chapStyle="1" w:chapSep="hyphen""#), "cycle {cycle}: {xml}");
|
||||
assert!(xml.contains(r#"w:chapStyle="10" w:chapSep="colon""#), "cycle {cycle}: {xml}");
|
||||
assert!(xml.contains("xmlns:w15=") && xml.contains("mc:Ignorable=\"w14 w15 wp14\""), "cycle {cycle}: {xml}");
|
||||
assert!(xml.contains("xmlns:w15=") && xml.contains("mc:Ignorable=\"w14 w15 wp14 w16du\""), "cycle {cycle}: {xml}");
|
||||
document = wordcraft_docx::read(&bytes).unwrap();
|
||||
let json = serde_json::to_vec(&document).unwrap();
|
||||
document = serde_json::from_slice(&json).unwrap();
|
||||
|
||||
@@ -265,3 +265,23 @@ fn story_shared_by_many_shapes_is_written_once() {
|
||||
// fallback. The other shapes do not repeat it.
|
||||
assert_eq!(xml.matches(text.as_str()).count(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_box_in_a_linked_nested_group_survives_pruning() {
|
||||
// The shared reader keeps a hyperlinked nested group whole; the box inside must still be
|
||||
// reachable (`text_boxes` looks one level deep), or the first edit's prune deletes its story.
|
||||
let inner = r#"<wpg:grpSp><wpg:cNvPr id="3" name="Inner"><a:hlinkClick r:id="rId9"/></wpg:cNvPr><wpg:cNvGrpSpPr/><wpg:grpSpPr><a:xfrm><a:off x="635000" y="0"/><a:ext cx="635000" cy="635000"/><a:chOff x="0" y="0"/><a:chExt cx="635000" cy="635000"/></a:xfrm></wpg:grpSpPr><wps:wsp><wps:cNvPr id="4" name="Box"/><wps:cNvSpPr txBox="1"/><wps:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="635000" cy="635000"/></a:xfrm><a:prstGeom prst="rect"/></wps:spPr><wps:txbx><w:txbxContent><w:p><w:r><w:t>Inside</w:t></w:r></w:p></w:txbxContent></wps:txbx><wps:bodyPr/></wps:wsp></wpg:grpSp>"#;
|
||||
let doc = format!(
|
||||
r#"<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape" xmlns:wpg="http://schemas.microsoft.com/office/word/2010/wordprocessingGroup"><w:body><w:p><w:r><w:drawing><wp:inline><wp:extent cx="1270000" cy="635000"/><wp:docPr id="1" name="Outer"/><a:graphic><a:graphicData uri="http://schemas.microsoft.com/office/word/2010/wordprocessingGroup"><wpg:wgp><wpg:cNvGrpSpPr/><wpg:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="1270000" cy="635000"/><a:chOff x="0" y="0"/><a:chExt cx="1270000" cy="635000"/></a:xfrm></wpg:grpSpPr>{inner}</wpg:wgp></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p></w:body></w:document>"#
|
||||
);
|
||||
let rels = br#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
|
||||
let doc_rels = br#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId9" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="https://example.com/" TargetMode="External"/></Relationships>"#;
|
||||
let bytes = zip(&[("_rels/.rels", rels), ("word/document.xml", doc.as_bytes()), ("word/_rels/document.xml.rels", doc_rels)]);
|
||||
let mut d = wordcraft_docx::read(&bytes).unwrap();
|
||||
assert_eq!(boxes(&d).len(), 1);
|
||||
// What every mutating command does after it runs.
|
||||
d.prune_text_boxes();
|
||||
assert_eq!(boxes(&d).len(), 1, "the nested box lost its story");
|
||||
let xml = document_xml(&wordcraft_docx::write(&d).unwrap());
|
||||
assert!(xml.contains("Inside"), "{xml}");
|
||||
}
|
||||
|
||||
@@ -477,7 +477,7 @@ fn drag_unit(s: &mut Session, v: &Value) -> CmdResult {
|
||||
/// Select the n-th occurrence of `text` in the body (agents: "select the word X").
|
||||
fn select_text(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let needle = p::req_str(v, "text")?;
|
||||
let n = p::u64(v, "occurrence").unwrap_or(1).max(1) as usize;
|
||||
let n = p::u64(v, "occurrence").unwrap_or(1).max(1);
|
||||
if needle.is_empty() {
|
||||
return Err(CmdError::Params("`text` is empty".into()));
|
||||
}
|
||||
|
||||
@@ -161,7 +161,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.params(r#"{"tab"?: "find|replace|goto" (default replace)}"#)
|
||||
.pure(),
|
||||
CommandSpec::new("edit.replaceAll", "Replace All", "Home › Editing › Replace", replace_all)
|
||||
.params(r#"{"text": string, "with": string (^p ^t ^& ^c …; \\1 with wildcards; with regex also $1 ${n} ${name} $0 $$ \\1 \\n (paragraph mark) \\t), …options of edit.find}"#),
|
||||
.params(r#"{"text": string, "with": string (^p ^t ^& ^c …; \\1 with wildcards; with regex also $1 ${n} ${name} $0 $$ \\1 \\n (paragraph mark) \\t), …options of edit.find} (with AutoFormat's smart quotes on, a " or ' typed in `with` goes in curly by the character before it, as typing does, except with regex or special: false (taken as written); ^034 and ^039 stay straight; a match that already reads so, curled the same kind, is left and not counted)"#),
|
||||
CommandSpec::new("edit.goto", "Go To", "Home › Editing › Find", goto)
|
||||
.key("Mod+Alt+G / F5")
|
||||
.params(r#"{"page"?: n, "pageBy"?: int (pages forward, negative back, from the caret's page), "bookmark"?: string (selects its text), "paragraph"?: n}; none opens Find and Replace on its Go To tab"#)
|
||||
@@ -496,6 +496,9 @@ pub(crate) struct Found {
|
||||
pub a: Pos,
|
||||
pub b: Pos,
|
||||
pub rep: Option<String>,
|
||||
/// With smart quotes on, the match already is its replacement with the quotes curled the
|
||||
/// same kind (a curly apostrophe a typed `'` found): Replace leaves it and doesn't count it.
|
||||
pub keep: bool,
|
||||
}
|
||||
|
||||
/// A stretch of searched text: `len` bytes from `hay` are paragraph `para`'s bytes from `raw`.
|
||||
@@ -535,6 +538,13 @@ fn find_opts(f: &crate::session::FindState) -> find_pattern::Opts {
|
||||
/// wildcard groups). A pattern that can match a paragraph mark (`^p`) reads runs of sibling
|
||||
/// paragraphs as one text with a mark between them; otherwise each paragraph is read alone.
|
||||
pub(crate) fn search_full(s: &Session, story: StoryRef, with_rep: bool) -> Result<Vec<Found>, CmdError> {
|
||||
search_matches(s, story, with_rep, false)
|
||||
}
|
||||
|
||||
/// [`search_full`]. With `chain` (Replace All, which replaces every match), a quote typed in
|
||||
/// Replace with curls by the previous match's replacement when the two touch; without it, by the
|
||||
/// text as it is, since Replace changes only the selected match (#7307).
|
||||
fn search_matches(s: &Session, story: StoryRef, with_rep: bool, chain: bool) -> Result<Vec<Found>, CmdError> {
|
||||
use regex_automata::{Input, meta, util::syntax};
|
||||
let f = &s.find;
|
||||
if f.query.is_empty() {
|
||||
@@ -551,6 +561,9 @@ pub(crate) fn search_full(s: &Session, story: StoryRef, with_rep: bool) -> Resul
|
||||
let index = |name: &str| re.group_info().to_index(regex_automata::PatternID::ZERO, name);
|
||||
find_pattern::resolve_names(find_pattern::parse_replace(&f.replace, &opts), &index)
|
||||
});
|
||||
// "Straight quotes with smart quotes" curls a quote typed in Replace with (#7307).
|
||||
let ac = &s.prefs.autocorrect;
|
||||
let smart = ac.enabled && ac.smart_quotes && pieces.as_deref().is_some_and(find_pattern::has_typed_quote);
|
||||
let paths = s.doc.para_paths(story);
|
||||
// Paragraphs read as one text: consecutive siblings when the pattern spans paragraphs.
|
||||
let mut chunks: Vec<std::ops::Range<usize>> = Vec::new();
|
||||
@@ -613,6 +626,8 @@ pub(crate) fn search_full(s: &Session, story: StoryRef, with_rep: bool) -> Resul
|
||||
};
|
||||
cuts.push(hay.len());
|
||||
let mut from = 0;
|
||||
// Where the last match ends and the character that stands there once it is replaced.
|
||||
let mut last: Option<(usize, Option<char>)> = None;
|
||||
for cut in cuts {
|
||||
if cut <= from {
|
||||
continue;
|
||||
@@ -636,11 +651,24 @@ pub(crate) fn search_full(s: &Session, story: StoryRef, with_rep: bool) -> Resul
|
||||
continue;
|
||||
}
|
||||
let (Some(a), Some(b)) = (pos_of(m.start(), false), pos_of(m.end(), true)) else { continue };
|
||||
let found = hay.get(m.range()).unwrap_or("");
|
||||
// A quote curls by the character in front of the match as it will read: with
|
||||
// `chain`, the previous match's replacement when the two touch. A section mark
|
||||
// starts a paragraph.
|
||||
let before = match last {
|
||||
Some((end, c)) if chain && end == m.start() => c,
|
||||
_ => hay.get(..m.start()).and_then(|t| t.chars().next_back()),
|
||||
}
|
||||
.filter(|c| *c != find_pattern::SECT_MARK);
|
||||
let quotes = if smart { find_pattern::Quotes::Smart { before } } else { find_pattern::Quotes::Straight };
|
||||
let rep = pieces.as_ref().map(|pc| {
|
||||
let group = |n: usize| caps.get_group(n).and_then(|g| hay.get(g.range())).map(str::to_string);
|
||||
find_pattern::expand(pc, hay.get(m.range()).unwrap_or(""), &group, &s.clipboard_text)
|
||||
find_pattern::expand(pc, found, &group, &s.clipboard_text, quotes)
|
||||
});
|
||||
out.push(Found { a, b, rep });
|
||||
let keep = smart && rep.as_deref().is_some_and(|r| find_pattern::already_curled(found, r));
|
||||
let stays = if keep { found } else { rep.as_deref().unwrap_or(found) };
|
||||
last = Some((m.end(), stays.chars().next_back().or(before)));
|
||||
out.push(Found { a, b, rep, keep });
|
||||
if out.len() >= 100_000 {
|
||||
return Ok(out);
|
||||
}
|
||||
@@ -779,7 +807,8 @@ fn replace(s: &mut Session, v: &Value) -> CmdResult {
|
||||
// Replace the current match if selected, then move to the next. The result says which
|
||||
// happened (#6877): a first call that only selects a match reads as `replaced: 0`.
|
||||
let mut replaced = 0;
|
||||
if let Some(f) = results.into_iter().find(|f| f.a == a && f.b == b) {
|
||||
// A match already curled as the replacement would curl it is left as it is (#7307).
|
||||
if let Some(f) = results.into_iter().find(|f| f.a == a && f.b == b && !f.keep) {
|
||||
super::paste_text(s, &f.rep.unwrap_or_default())?;
|
||||
replaced = 1;
|
||||
}
|
||||
@@ -799,10 +828,11 @@ fn replace_all(s: &mut Session, v: &Value) -> CmdResult {
|
||||
need_query(s, v)?;
|
||||
read_opts(s, v);
|
||||
let story = s.sel.focus.story;
|
||||
let results = search_full(s, story, true)?;
|
||||
// Matches already curled as the replacement would curl them are left and not counted (#7307).
|
||||
let results: Vec<Found> = search_matches(s, story, true, true)?.into_iter().filter(|f| !f.keep).collect();
|
||||
let n = results.len();
|
||||
super::controls::check_deletions(s, story, results.iter().map(|f| (&f.a, &f.b)))?;
|
||||
for Found { a, b, rep } in results.into_iter().rev() {
|
||||
for Found { a, b, rep, .. } in results.into_iter().rev() {
|
||||
let with = rep.unwrap_or_default();
|
||||
if s.doc.settings.track_changes {
|
||||
// Same path as a single replace, so the change is a reviewable revision.
|
||||
|
||||
@@ -20,7 +20,7 @@ pub const MAX_AUTHOR_CHARS: usize = 255;
|
||||
/// carry an author.
|
||||
pub fn normalize_author(name: &str) -> Result<String, CmdError> {
|
||||
let name: String = name.trim().chars().filter(|c| !c.is_control()).take(MAX_AUTHOR_CHARS).collect();
|
||||
let name = name.trim_end();
|
||||
let name = name.trim();
|
||||
if name.is_empty() {
|
||||
return Err(CmdError::Params("`name` must not be blank".into()));
|
||||
}
|
||||
|
||||
@@ -359,6 +359,20 @@ pub enum Piece {
|
||||
Named(String),
|
||||
/// `^c`: the clipboard.
|
||||
Clip,
|
||||
/// A straight `"` or `'` typed as itself (not a regex, not with special characters off, which
|
||||
/// takes the text as written, and not given by its code such as `^034`): curled with smart
|
||||
/// quotes on, as typing curls it ([`Quotes`]).
|
||||
Quote(char),
|
||||
}
|
||||
|
||||
/// How a quote typed in Replace with goes in (#7307).
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub enum Quotes {
|
||||
/// As typed.
|
||||
Straight,
|
||||
/// Curled by the typing rule ("straight quotes with smart quotes"): `before` is the character
|
||||
/// in front of the match, `None` at a paragraph's start.
|
||||
Smart { before: Option<char> },
|
||||
}
|
||||
|
||||
/// Read Replace with text: `^` codes (unless `literal`), `\1`–`\9` with wildcards, and with a
|
||||
@@ -438,6 +452,11 @@ pub fn parse_replace(with: &str, o: &Opts) -> Vec<Piece> {
|
||||
i += used;
|
||||
continue;
|
||||
}
|
||||
if matches!(c, '"' | '\'') && !o.regex {
|
||||
flush_literal(&mut cur, &mut out);
|
||||
out.push(Piece::Quote(c));
|
||||
continue;
|
||||
}
|
||||
cur.push(c);
|
||||
}
|
||||
flush_literal(&mut cur, &mut out);
|
||||
@@ -511,7 +530,8 @@ fn as_inserted(s: &str) -> String {
|
||||
}
|
||||
|
||||
/// Fill in Replace with text for one match: `found` is the matched text, `group(n)` a group's.
|
||||
pub fn expand(pieces: &[Piece], found: &str, group: &dyn Fn(usize) -> Option<String>, clip: &str) -> String {
|
||||
/// A typed quote is curled by what goes in before it: the replacement so far, else `before`.
|
||||
pub fn expand(pieces: &[Piece], found: &str, group: &dyn Fn(usize) -> Option<String>, clip: &str, quotes: Quotes) -> String {
|
||||
let mut out = String::new();
|
||||
for p in pieces {
|
||||
match p {
|
||||
@@ -520,11 +540,39 @@ pub fn expand(pieces: &[Piece], found: &str, group: &dyn Fn(usize) -> Option<Str
|
||||
Piece::Group(n) => out.push_str(&as_inserted(&group(*n).unwrap_or_default())),
|
||||
Piece::Clip => out.push_str(&clip.replace("\r\n", "\r").replace('\n', "\r")),
|
||||
Piece::Named(_) => {}
|
||||
Piece::Quote(q) => {
|
||||
let curly = match quotes {
|
||||
Quotes::Smart { before } => super::text::smart_quote(out.chars().next_back().or(before), *q),
|
||||
Quotes::Straight => None,
|
||||
};
|
||||
match curly {
|
||||
Some(c) => out.push_str(c),
|
||||
None => out.push(*q),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether Replace with has a quote typed as itself, which smart quotes curl.
|
||||
pub fn has_typed_quote(pieces: &[Piece]) -> bool {
|
||||
pieces.iter().any(|p| matches!(p, Piece::Quote(_)))
|
||||
}
|
||||
|
||||
/// The match already reads as its replacement: the same text, with a curly quote of the same
|
||||
/// kind (single or double) wherever the replacement has a curly one. Replace leaves such a match
|
||||
/// alone and doesn't count it (#7307), so a typed `'` that also finds curly apostrophes keeps one
|
||||
/// set the other way on purpose (’90s).
|
||||
pub fn already_curled(found: &str, rep: &str) -> bool {
|
||||
let kind = |c: char| match c {
|
||||
'\u{2018}' | '\u{2019}' => Some('\''),
|
||||
'\u{201C}' | '\u{201D}' => Some('"'),
|
||||
_ => None,
|
||||
};
|
||||
found.chars().count() == rep.chars().count() && found.chars().zip(rep.chars()).all(|(f, r)| f == r || (kind(f).is_some() && kind(f) == kind(r)))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -535,7 +583,45 @@ mod tests {
|
||||
}
|
||||
|
||||
fn replaced(with: &str) -> String {
|
||||
expand(&parse_replace(with, &Opts::default()), "", &|_| None, "")
|
||||
expand(&parse_replace(with, &Opts::default()), "", &|_| None, "", Quotes::Straight)
|
||||
}
|
||||
|
||||
fn curled(with: &str, o: &Opts, before: Option<char>) -> String {
|
||||
expand(&parse_replace(with, o), "", &|_| None, "", Quotes::Smart { before })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_typed_quote_curls_by_what_goes_before_it_and_a_coded_one_stays_straight() {
|
||||
let o = Opts::default();
|
||||
// Opening at a paragraph's start or after a space, closing after a letter.
|
||||
assert_eq!(curled("\"", &o, None), "\u{201C}");
|
||||
assert_eq!(curled("\"", &o, Some(' ')), "\u{201C}");
|
||||
assert_eq!(curled("\"", &o, Some('d')), "\u{201D}");
|
||||
assert_eq!(curled("'", &o, Some('n')), "\u{2019}");
|
||||
// Inside the replacement, the text before it decides.
|
||||
assert_eq!(curled("\"quoted\"", &o, Some(' ')), "\u{201C}quoted\u{201D}");
|
||||
assert_eq!(curled(" 'a'", &o, Some('x')), " \u{2018}a\u{2019}");
|
||||
assert_eq!(curled("^p\"", &o, Some('x')), "\r\u{201C}");
|
||||
// Given by its code, a quote stays straight; with smart quotes off, typed ones do too.
|
||||
for code in ["^034", "^039", "^u34", "^0039"] {
|
||||
let straight = if code.ends_with("34") { "\"" } else { "'" };
|
||||
assert_eq!(curled(code, &o, Some('x')), straight, "{code}");
|
||||
}
|
||||
assert_eq!(replaced("\"a'"), "\"a'");
|
||||
// A regex replacement and an escaped wildcard one are taken as written.
|
||||
assert_eq!(curled("\"", &Opts { regex: true, ..o }, None), "\"");
|
||||
assert_eq!(curled("\\\"", &Opts { wildcards: true, ..o }, None), "\"");
|
||||
assert_eq!(curled("\"", &Opts { wildcards: true, ..o }, None), "\u{201C}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_match_already_curled_the_same_kind_reads_as_its_replacement() {
|
||||
assert!(already_curled("\u{2019}", "\u{2018}"));
|
||||
assert!(already_curled("don\u{2019}t", "don\u{2019}t"));
|
||||
assert!(already_curled("\u{201C}", "\u{201D}"));
|
||||
assert!(!already_curled("'", "\u{2019}"), "a straight quote is curled");
|
||||
assert!(!already_curled("\u{2019}", "\u{201D}"), "a single quote isn't a double one");
|
||||
assert!(!already_curled("dont", "don\u{2019}t"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
//! Character formatting (Home › Font).
|
||||
|
||||
use std::sync::{Arc, PoisonError};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use wordcraft_doc::eq::{EncloseShape, EncloseStyle, Enclosure};
|
||||
use wordcraft_doc::props::{Border, CharProps, Highlight, Rgb, TextColor, Underline, VertAlign};
|
||||
@@ -8,8 +10,44 @@ use wordcraft_doc::{InlineObject, PartKind, Pos, RevisionKind, StoryRef};
|
||||
|
||||
use super::sel_result;
|
||||
use super::tools::{is_turkic, lower_char, upper_char};
|
||||
use crate::doc_state::{ColumnBlock, Selection};
|
||||
use crate::{CmdError, CmdResult, CommandSpec, Session, p};
|
||||
|
||||
#[derive(Clone, PartialEq)]
|
||||
struct StateKey {
|
||||
document_id: u64,
|
||||
rev: u64,
|
||||
sel: Selection,
|
||||
pending: Option<CharProps>,
|
||||
pending_at: Option<Pos>,
|
||||
column: Option<ColumnBlock>,
|
||||
font_gen: u64,
|
||||
}
|
||||
|
||||
/// Cached result of [`cached_state`] and the session inputs it depends on.
|
||||
pub(crate) struct StateCache {
|
||||
key: StateKey,
|
||||
value: Arc<Value>,
|
||||
}
|
||||
|
||||
impl StateCache {
|
||||
pub(crate) fn rev(&self) -> u64 {
|
||||
self.key.rev
|
||||
}
|
||||
}
|
||||
|
||||
fn state_key(s: &Session) -> StateKey {
|
||||
StateKey {
|
||||
document_id: s.document_id(),
|
||||
rev: s.rev(),
|
||||
sel: s.sel.clone(),
|
||||
pending: s.pending.clone(),
|
||||
pending_at: s.pending_at.clone(),
|
||||
column: s.column.clone(),
|
||||
font_gen: wordcraft_fonts::FontDb::global().generation(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Word's font size list.
|
||||
pub const SIZES: [f32; 17] = [8.0, 9.0, 10.0, 10.5, 11.0, 12.0, 14.0, 16.0, 18.0, 20.0, 22.0, 24.0, 26.0, 28.0, 36.0, 48.0, 72.0];
|
||||
|
||||
@@ -879,8 +917,30 @@ fn set(s: &mut Session, v: &Value) -> CmdResult {
|
||||
apply(s, &|c| c.overlay(&props))
|
||||
}
|
||||
|
||||
/// What the ribbon shows: the formatting at the selection (mixed values are null), cached per
|
||||
/// document revision, selection, pending caret state, column selection, and font generation.
|
||||
pub fn cached_state(s: &Session) -> Arc<Value> {
|
||||
let key = state_key(s);
|
||||
{
|
||||
let cache = s.format_state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if let Some(cached) = cache.as_ref()
|
||||
&& cached.key == key
|
||||
{
|
||||
return Arc::clone(&cached.value);
|
||||
}
|
||||
}
|
||||
let value = Arc::new(compute_state(s));
|
||||
let mut cache = s.format_state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
*cache = Some(StateCache { key, value: Arc::clone(&value) });
|
||||
value
|
||||
}
|
||||
|
||||
/// What the ribbon shows: the formatting at the selection (mixed values are null).
|
||||
pub fn state(s: &Session) -> Value {
|
||||
(*cached_state(s)).clone()
|
||||
}
|
||||
|
||||
fn compute_state(s: &Session) -> Value {
|
||||
let all = resolved(s);
|
||||
let first = all.first().cloned();
|
||||
let same = |f: &dyn Fn(&ResolvedChar) -> Value| -> Value {
|
||||
@@ -906,6 +966,7 @@ pub fn state(s: &Session) -> Value {
|
||||
"italic": all.iter().all(shown_italic),
|
||||
"underline": all.iter().all(|r| r.underline != Underline::None),
|
||||
"underlineColor": same(&|r| json!(r.underline_color.map_or_else(|| "auto".to_string(), |c| c.hex()))),
|
||||
"shading": same(&|r| json!(r.shading.map(|c| c.hex()))),
|
||||
"strike": all.iter().all(|r| r.strike),
|
||||
"border": all.iter().all(|r| r.border.is_some()),
|
||||
"subscript": all.iter().all(|r| r.vert_align == VertAlign::Subscript),
|
||||
@@ -927,6 +988,14 @@ pub fn state(s: &Session) -> Value {
|
||||
})
|
||||
}
|
||||
|
||||
/// The selection's uniform highlight colour (`Some(None)` when uniformly unhighlighted), or `None`
|
||||
/// when the selection is mixed or empty.
|
||||
pub fn uniform_highlight(s: &Session) -> Option<Option<Rgb>> {
|
||||
let all = resolved(s);
|
||||
let first = all.first()?.highlight;
|
||||
all.iter().all(|r| r.highlight == first).then_some(first)
|
||||
}
|
||||
|
||||
/// What Enclose Characters works on: the selected text (one full-width or up to two half-width
|
||||
/// characters), or enclosed characters already there (selected, or beside the caret).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
@@ -1054,4 +1123,30 @@ mod tests {
|
||||
assert_eq!(convert("one 3.14 apples and two 2.5 pears.", "sentence", true), "One 3.14 apples and two 2.5 pears.");
|
||||
assert_eq!(convert("pi is 3.14. next sentence.", "sentence", true), "Pi is 3.14. Next sentence.");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cached_state_hits_until_selection_format_or_pending_changes() {
|
||||
use serde_json::json;
|
||||
use std::sync::Arc;
|
||||
|
||||
let mut s = crate::Session::new(wordcraft_doc::Document::new());
|
||||
let a = super::cached_state(&s);
|
||||
let b = super::cached_state(&s);
|
||||
assert!(Arc::ptr_eq(&a, &b), "unchanged session should reuse cached format state Arc");
|
||||
|
||||
s.run("text.insert", &json!({"text": "hello world"})).unwrap();
|
||||
let c = super::cached_state(&s);
|
||||
assert!(!Arc::ptr_eq(&b, &c), "text edit bumps rev and invalidates cache");
|
||||
|
||||
s.run("format.bold", &json!({})).unwrap();
|
||||
let d = super::cached_state(&s);
|
||||
assert!(!Arc::ptr_eq(&c, &d), "pending bold changes caret formatting");
|
||||
assert_eq!(d["bold"], json!(true));
|
||||
assert!(Arc::ptr_eq(&d, &super::cached_state(&s)));
|
||||
|
||||
s.run("select.text", &json!({"text": "hello"})).unwrap();
|
||||
let e = super::cached_state(&s);
|
||||
assert!(!Arc::ptr_eq(&d, &e), "selection change updates format state");
|
||||
assert_eq!(e["bold"], json!(false));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,6 +37,7 @@ pub(super) fn table(s: &mut Session, v: &Value) -> CmdResult {
|
||||
if s.doc.para_at(&s.sel.focus).is_some_and(|p| s.doc.styles.resolve_para(&p.props).bidi) {
|
||||
t.props.bidi_visual = true;
|
||||
}
|
||||
cells_in_language(&mut t, &s.typing_props());
|
||||
let story = s.sel.focus.story;
|
||||
let path = insert_block_at_caret(s, Block::Table(t))?;
|
||||
let mut first = path.0.clone();
|
||||
@@ -45,6 +46,27 @@ pub(super) fn table(s: &mut Session, v: &Value) -> CmdResult {
|
||||
Ok(json!({"table": path.0}))
|
||||
}
|
||||
|
||||
/// Like Word, a new table is in the language of the text it is inserted in (#6013): each cell's
|
||||
/// paragraph mark takes `at`'s languages and Do not check spelling, so what is typed in the cells
|
||||
/// is proofed in that language rather than the document's default. Unset ones stay unset.
|
||||
fn cells_in_language(t: &mut Table, at: &CharProps) {
|
||||
for cell in t.rows.iter_mut().flat_map(|r| r.cells.iter_mut()) {
|
||||
for b in &mut cell.blocks {
|
||||
if let Block::Para(p) = std::sync::Arc::make_mut(b) {
|
||||
let mark = &mut p.mark;
|
||||
for (to, from) in [(&mut mark.lang, &at.lang), (&mut mark.lang_ea, &at.lang_ea), (&mut mark.lang_bidi, &at.lang_bidi)] {
|
||||
if from.is_some() {
|
||||
to.clone_from(from);
|
||||
}
|
||||
}
|
||||
if at.no_proof.is_some() {
|
||||
mark.no_proof = at.no_proof;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Minimal base64 (standard alphabet, padding optional, whitespace ignored).
|
||||
pub fn base64_decode(s: &str) -> Option<Vec<u8>> {
|
||||
let mut out = Vec::with_capacity(s.len() * 3 / 4);
|
||||
|
||||
@@ -176,7 +176,7 @@ pub(super) fn recipients(s: &mut Session, v: &Value) -> CmdResult {
|
||||
}
|
||||
Pick::Index(0)
|
||||
}
|
||||
Some(_) => return Err(CmdError::Params("`sheet` must be a sheet name or number".into())),
|
||||
Some(_) => return Err(CmdError::Params("`sheet` must be a sheet name or positive integer (1 = the first sheet)".into())),
|
||||
};
|
||||
let (names, rows) = read_rows(&bytes, pick).map_err(CmdError::Failed)?;
|
||||
let chosen = match pick {
|
||||
|
||||
@@ -242,7 +242,10 @@ fn recipients_from_a_workbook_ask_for_the_sheet_when_there_are_several() {
|
||||
assert_eq!(r["fields"], json!(["Column 1", "Column 2", "Column 3"]));
|
||||
assert_eq!(r["records"], 3);
|
||||
assert!(s.run("mailings.recipients", &json!({"data": data, "sheet": 3})).is_err());
|
||||
assert!(s.run("mailings.recipients", &json!({"data": data, "sheet": 0})).is_err());
|
||||
assert!(matches!(
|
||||
s.run("mailings.recipients", &json!({"data": data, "sheet": 0})),
|
||||
Err(CmdError::Params(message)) if message == "`sheet` must be a sheet name or positive integer (1 = the first sheet)"
|
||||
));
|
||||
assert!(s.run("mailings.recipients", &json!({"data": "%%%"})).is_err());
|
||||
}
|
||||
|
||||
|
||||
@@ -304,7 +304,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
/// start, so all of a paragraph's text is still text, except in the last paragraph of its story,
|
||||
/// cell or box, where it stands for the paragraph with its mark. A selected picture, shape or text
|
||||
/// box is its object character, not text (a field's object character is).
|
||||
fn shades_text(s: &Session) -> bool {
|
||||
pub fn shades_text(s: &Session) -> bool {
|
||||
let (a, b) = s.sel.ordered();
|
||||
if a == b || a.story != b.story || a.path != b.path {
|
||||
return false;
|
||||
|
||||
@@ -144,6 +144,21 @@ pub(super) fn set_props(s: &mut Session, v: &Value) -> CmdResult {
|
||||
para.props.indent_right = Some(x);
|
||||
}
|
||||
para.touch();
|
||||
// An indent given in points wins over one in characters, the paragraph's own or its
|
||||
// style's, unless `props` gives the characters too: Word's dialog writes
|
||||
// `w:firstLineChars="0"` (and the like) for it. Paragraphs without one stay as they are.
|
||||
let points = |pt: bool, chars: Option<f32>| pt && chars.is_none();
|
||||
let set = [
|
||||
points(props.indent_left.is_some() || start.is_some(), props.indent_left_chars),
|
||||
points(props.indent_right.is_some() || end.is_some(), props.indent_right_chars),
|
||||
points(props.indent_first.is_some(), props.indent_first_chars),
|
||||
];
|
||||
let Some(para) = s.doc.para(story, &path) else { continue };
|
||||
let chars = s.doc.styles.resolve_para(¶.props).indent_chars;
|
||||
let [l, r, f] = [0, 1, 2].map(|i| set[i] && chars[i] != 0.0);
|
||||
if l || r || f {
|
||||
s.doc.para_mut(story, &path)?.props.cancel_char_indents(l, r, f);
|
||||
}
|
||||
}
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
@@ -29,7 +29,6 @@ pub(super) fn apply_style(s: &mut Session, v: &Value) -> CmdResult {
|
||||
if kind == StyleKind::Character {
|
||||
return crate::cmd::format::apply(s, &|c| c.style = Some(id.clone()));
|
||||
}
|
||||
let (a, b) = s.sel.ordered();
|
||||
// A style linked to a list level (a heading in a numbered-headings list) brings its number.
|
||||
let numbered = s.doc.styles.resolve_para(&ParaProps { style: Some(id.clone()), ..Default::default() }).numbering.is_some();
|
||||
fmt(s, &|p| {
|
||||
@@ -40,33 +39,108 @@ pub(super) fn apply_style(s: &mut Session, v: &Value) -> CmdResult {
|
||||
p.numbering = None;
|
||||
}
|
||||
})?;
|
||||
// A paragraph style resets direct character formatting that matches nothing (Word keeps
|
||||
// direct formatting unless it covers most of the paragraph; we clear font/size/colour).
|
||||
if a.path == b.path || a == b {
|
||||
let paths = s.doc.paths_between(&a, &b);
|
||||
for path in paths {
|
||||
let para = s.doc.para_mut(a.story, &path)?;
|
||||
let len = para.len();
|
||||
para.format(0, len, &|c| {
|
||||
c.font = None;
|
||||
c.font_cs = None;
|
||||
c.font_ea = None;
|
||||
c.size = None;
|
||||
c.size_cs = None;
|
||||
c.color = None;
|
||||
})?;
|
||||
para.mark.font = None;
|
||||
para.mark.font_cs = None;
|
||||
para.mark.font_ea = None;
|
||||
para.mark.size = None;
|
||||
para.mark.size_cs = None;
|
||||
para.mark.color = None;
|
||||
}
|
||||
}
|
||||
reset_direct_formatting(s)?;
|
||||
s.pending = None;
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
/// A character property a paragraph style can reset: whether a run sets it directly, and how to
|
||||
/// clear it.
|
||||
type Reset = (fn(&CharProps) -> bool, fn(&mut CharProps));
|
||||
|
||||
/// The direct character formatting applying a paragraph style can reset, as observed in Word.
|
||||
/// Word keeps highlight, superscript and subscript, scale, shading, borders, the underline's
|
||||
/// colour, language, no-proof and the character style whatever they cover, so they are not here.
|
||||
const RESETS: [Reset; 24] = [
|
||||
(|c| c.font.is_some(), |c| c.font = None),
|
||||
(|c| c.font_cs.is_some(), |c| c.font_cs = None),
|
||||
(|c| c.font_ea.is_some(), |c| c.font_ea = None),
|
||||
(|c| c.size.is_some(), |c| c.size = None),
|
||||
(|c| c.size_cs.is_some(), |c| c.size_cs = None),
|
||||
(|c| c.color.is_some(), |c| c.color = None),
|
||||
(|c| c.bold.is_some(), |c| c.bold = None),
|
||||
(|c| c.bold_cs.is_some(), |c| c.bold_cs = None),
|
||||
(|c| c.italic.is_some(), |c| c.italic = None),
|
||||
(|c| c.italic_cs.is_some(), |c| c.italic_cs = None),
|
||||
(|c| c.underline.is_some(), |c| c.underline = None),
|
||||
(|c| c.strike.is_some(), |c| c.strike = None),
|
||||
(|c| c.double_strike.is_some(), |c| c.double_strike = None),
|
||||
(|c| c.caps.is_some(), |c| c.caps = None),
|
||||
(|c| c.small_caps.is_some(), |c| c.small_caps = None),
|
||||
(|c| c.spacing.is_some(), |c| c.spacing = None),
|
||||
(|c| c.position.is_some(), |c| c.position = None),
|
||||
(|c| c.kern.is_some(), |c| c.kern = None),
|
||||
(|c| c.hidden.is_some(), |c| c.hidden = None),
|
||||
(|c| c.emboss.is_some(), |c| c.emboss = None),
|
||||
(|c| c.engrave.is_some(), |c| c.engrave = None),
|
||||
(|c| c.outline.is_some(), |c| c.outline = None),
|
||||
(|c| c.shadow.is_some(), |c| c.shadow = None),
|
||||
(|c| c.emphasis.is_some(), |c| c.emphasis = None),
|
||||
];
|
||||
|
||||
/// Clear `resets` in `a..b` of `para` (bytes), and in its mark when `mark`.
|
||||
fn clear_resets(para: &mut wordcraft_doc::Paragraph, a: usize, b: usize, mark: bool, resets: &[fn(&mut CharProps)]) -> Result<(), CmdError> {
|
||||
if resets.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let reset = |c: &mut CharProps| {
|
||||
for f in resets {
|
||||
f(c);
|
||||
}
|
||||
};
|
||||
para.format(a, b, &reset)?;
|
||||
if mark {
|
||||
reset(&mut para.mark);
|
||||
}
|
||||
para.touch();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// What applying a paragraph style does to direct character formatting, as observed in Word:
|
||||
/// - A caret, or a selection of a whole paragraph or of several paragraphs: the selection from its
|
||||
/// start to the end of its first paragraph decides, the paragraph mark counted as one character
|
||||
/// (the whole paragraph for a caret). Each property in [`RESETS`] set directly on at least half
|
||||
/// of those characters is reset in every selected paragraph, text and mark. One set on less
|
||||
/// stays everywhere, even where it covers a whole later paragraph.
|
||||
/// - A selection inside one paragraph: only the selection loses that formatting. Outside it,
|
||||
/// nothing changes, however much of the paragraph it covers.
|
||||
fn reset_direct_formatting(s: &mut Session) -> Result<(), CmdError> {
|
||||
let story = s.sel.focus.story;
|
||||
let (a, b) = s.sel.ordered();
|
||||
let paths = crate::cmd::selected_paths(s);
|
||||
let Some(first) = paths.first() else { return Ok(()) };
|
||||
let all: Vec<fn(&mut CharProps)> = RESETS.iter().map(|(_, clear)| *clear).collect();
|
||||
if a != b && a.path == b.path && paths.len() == 1 {
|
||||
let para = s.doc.para_mut(story, first)?;
|
||||
let (from, to) = (para.clamp(a.off), para.clamp(b.off));
|
||||
if from > 0 || to < para.len() {
|
||||
return clear_resets(para, from, to, false, &all);
|
||||
}
|
||||
}
|
||||
// Characters of the first paragraph from `start`, the mark included, and how many of them set
|
||||
// each property.
|
||||
let para = s.doc.para(story, first).ok_or_else(|| CmdError::Failed("the selected paragraph is gone".into()))?;
|
||||
let start = if a != b && a.path == *first { para.clamp(a.off) } else { 0 };
|
||||
let total = para.text.get(start..).map_or(0, |t| t.chars().count()).saturating_add(1);
|
||||
let mut set = [0usize; RESETS.len()];
|
||||
let runs = para.run_ranges().map(|(r, c)| (para.text.get(r.start.max(start)..r.end.max(start)).map_or(0, |t| t.chars().count()), c));
|
||||
for (n, c) in runs.chain(std::iter::once((1, ¶.mark))) {
|
||||
for (count, (has, _)) in set.iter_mut().zip(RESETS.iter()) {
|
||||
if has(c) {
|
||||
*count = count.saturating_add(n);
|
||||
}
|
||||
}
|
||||
}
|
||||
let reset: Vec<fn(&mut CharProps)> =
|
||||
set.iter().zip(RESETS.iter()).filter(|(count, _)| count.saturating_mul(2) >= total).map(|(_, (_, clear))| *clear).collect();
|
||||
for path in &paths {
|
||||
let para = s.doc.para_mut(story, path)?;
|
||||
let len = para.len();
|
||||
clear_resets(para, 0, len, true, &reset)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn create_style(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let name = p::req_str(v, "name")?.trim().to_string();
|
||||
if name.is_empty() {
|
||||
|
||||
@@ -65,7 +65,11 @@ pub(super) fn to_text(s: &mut Session, v: &Value) -> CmdResult {
|
||||
Some("other") => match p::str(v, "char").and_then(|c| c.chars().next()) {
|
||||
// U+FFFC marks an object in the text, so it cannot set the cells apart.
|
||||
Some(c) if c != '\n' && c != '\r' && c != wordcraft_doc::para::OBJ => Some(c),
|
||||
_ => return Err(CmdError::Params("`char` (the separating character) is required with `other`".into())),
|
||||
_ => {
|
||||
return Err(CmdError::Params(
|
||||
"`char` with `other` must start with a character other than CR, LF or U+FFFC (the object marker); only the first character is used".into(),
|
||||
));
|
||||
}
|
||||
},
|
||||
Some(x) => return Err(CmdError::Params(format!("unknown separator `{x}`"))),
|
||||
};
|
||||
@@ -364,7 +368,11 @@ pub(super) fn from_text(s: &mut Session, v: &Value) -> CmdResult {
|
||||
Some("paragraph") => None,
|
||||
Some("other") => match p::str(v, "char").and_then(|c| c.chars().next()) {
|
||||
Some(c) if c != '\n' && c != '\r' => Some(c),
|
||||
_ => return Err(CmdError::Params("`char` (the separating character) is required with `other`".into())),
|
||||
_ => {
|
||||
return Err(CmdError::Params(
|
||||
"`char` with `other` must start with a character other than CR or LF; only the first character is used".into(),
|
||||
));
|
||||
}
|
||||
},
|
||||
Some(x) => return Err(CmdError::Params(format!("unknown separator `{x}`"))),
|
||||
};
|
||||
|
||||
@@ -14,6 +14,7 @@ mod enter_tab;
|
||||
mod unicode;
|
||||
|
||||
use autoformat::insert;
|
||||
pub(crate) use autoformat::smart_quote;
|
||||
use delete::{backspace, delete, delete_sentence_back, delete_word_back, delete_word_fwd};
|
||||
pub use enter_tab::MAX_TYPED_PARAGRAPHS;
|
||||
use enter_tab::{back_tab, new_paragraph, tab};
|
||||
|
||||
@@ -17,7 +17,13 @@ fn autoformat(s: &mut Session, text: &str) -> Option<String> {
|
||||
let f = &s.sel.focus;
|
||||
let para = s.doc.para_at(f)?;
|
||||
let before = para.text.get(..f.off)?;
|
||||
let prev = before.chars().next_back();
|
||||
smart_quote(before.chars().next_back(), c).map(String::from)
|
||||
}
|
||||
|
||||
/// The curly form of a straight quote `c` that follows `prev` (`None` at a paragraph's start):
|
||||
/// opening after a space, an opening bracket, a dash or the other opening quote, else closing.
|
||||
/// A quote typed in Replace with goes in by the same rule (#7307).
|
||||
pub(crate) fn smart_quote(prev: Option<char>, c: char) -> Option<&'static str> {
|
||||
let opening = prev.is_none_or(|p| {
|
||||
p.is_whitespace()
|
||||
|| "([{<\u{2014}\u{2013}\u{00AB}\u{2039}\u{201E}\u{201A}".contains(p)
|
||||
@@ -25,8 +31,8 @@ fn autoformat(s: &mut Session, text: &str) -> Option<String> {
|
||||
|| (c == '\'' && p == '\u{201C}')
|
||||
});
|
||||
match c {
|
||||
'"' => Some(if opening { "\u{201C}" } else { "\u{201D}" }.into()),
|
||||
'\'' => Some(if opening { "\u{2018}" } else { "\u{2019}" }.into()),
|
||||
'"' => Some(if opening { "\u{201C}" } else { "\u{201D}" }),
|
||||
'\'' => Some(if opening { "\u{2018}" } else { "\u{2019}" }),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -485,7 +485,7 @@ pub(super) fn spreadsheet_rows(v: &Value) -> Result<Vec<Vec<String>>, CmdError>
|
||||
Value::Number(x) => x.to_string(),
|
||||
Value::Bool(x) => x.to_string(),
|
||||
Value::Null => String::new(),
|
||||
_ => return Err(CmdError::Params(format!("`values` row {} holds a cell that is not text, a number or a boolean", r + 1))),
|
||||
_ => return Err(CmdError::Params(format!("`values` row {} holds a cell that is not text, a number, a boolean or null", r + 1))),
|
||||
});
|
||||
}
|
||||
rows.push(out);
|
||||
|
||||
@@ -1607,11 +1607,17 @@ fn proofing_language_options() {
|
||||
#[test]
|
||||
fn spreadsheet_takes_values_header_and_style() {
|
||||
let mut s = Session::new(Document::from_text(""));
|
||||
s.run("insert.spreadsheet", &json!({"values": [["Month", "Cases"], ["Jan", 12], ["Feb", null]], "header": true, "style": "TableGrid"})).unwrap();
|
||||
s.run(
|
||||
"insert.spreadsheet",
|
||||
&json!({"values": [["Month", "Cases"], ["Jan", 12], ["Feb", null], ["Mar", true]], "header": true, "style": "TableGrid"}),
|
||||
)
|
||||
.unwrap();
|
||||
let Some(Block::Table(t)) = s.doc.body.iter().map(|b| &**b).find(|b| matches!(b, Block::Table(_))) else { panic!("no table") };
|
||||
assert_eq!((t.rows.len(), t.rows[0].cells.len()), (3, 2));
|
||||
assert_eq!((t.rows.len(), t.rows[0].cells.len()), (4, 2));
|
||||
assert!(t.rows[0].props.header && !t.rows[1].props.header);
|
||||
assert_eq!(t.rows[1].cells[1].blocks[0].as_para().unwrap().text, "12");
|
||||
assert_eq!(t.rows[2].cells[1].blocks[0].as_para().unwrap().text, "");
|
||||
assert_eq!(t.rows[3].cells[1].blocks[0].as_para().unwrap().text, "true");
|
||||
assert_eq!(t.props.style.as_deref(), Some("TableGrid"));
|
||||
}
|
||||
|
||||
@@ -1637,23 +1643,22 @@ fn spreadsheet_rejects_an_explicit_null_values_without_changing_anything() {
|
||||
fn spreadsheet_rejects_hostile_values() {
|
||||
let wide: Vec<Value> = (0..64).map(|i| json!(i)).collect();
|
||||
let many: Vec<Value> = (0..1001).map(|_| json!(["x"])).collect();
|
||||
for bad in [
|
||||
json!("x"),
|
||||
json!(5),
|
||||
json!([]),
|
||||
json!(["a"]),
|
||||
json!([["a", "b"], ["c"]]),
|
||||
json!([wide]),
|
||||
json!(many),
|
||||
json!([[{"a": 1}]]),
|
||||
json!([[[1]]]),
|
||||
json!([[]]),
|
||||
] {
|
||||
for bad in [json!("x"), json!(5), json!([]), json!(["a"]), json!([["a", "b"], ["c"]]), json!([wide]), json!(many), json!([[]])] {
|
||||
let mut s = Session::new(Document::from_text("keep"));
|
||||
assert!(s.run("insert.spreadsheet", &json!({"values": bad})).is_err(), "{bad}");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "keep");
|
||||
assert!(!s.doc.body.iter().any(|b| matches!(&**b, Block::Table(_))));
|
||||
}
|
||||
for cell in [json!({"a": 1}), json!([1])] {
|
||||
let mut s = Session::new(Document::from_text("keep"));
|
||||
let err = s.run("insert.spreadsheet", &json!({"values": [["keep"], [cell]]})).unwrap_err();
|
||||
assert!(
|
||||
matches!(err, CmdError::Params(ref message) if message == "`values` row 2 holds a cell that is not text, a number, a boolean or null"),
|
||||
"{err}"
|
||||
);
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "keep");
|
||||
assert!(!s.doc.body.iter().any(|b| matches!(&**b, Block::Table(_))));
|
||||
}
|
||||
}
|
||||
|
||||
/// The inspector's removals delete straight from the document, so they aren't tracked: on a
|
||||
|
||||
@@ -149,6 +149,8 @@ pub struct Session {
|
||||
/// ([`Session::why_disabled`]): computed once per document, revision and author instead of
|
||||
/// for every button on every frame.
|
||||
protect_facts: std::sync::Mutex<Option<((u64, u64, String), crate::cmd::protect::Facts)>>,
|
||||
/// Cached result of [`crate::cmd::format::cached_state`] and the state key it was made for.
|
||||
pub(crate) format_state: std::sync::Mutex<Option<crate::cmd::format::StateCache>>,
|
||||
/// How many times the document's body was replaced under the same [`Self::document_id`]
|
||||
/// (`document.setText`, version restore, compare, Undo/Redo). It is the body's IME
|
||||
/// replacement epoch: a composition must not survive the swap, even when the new body has
|
||||
|
||||
@@ -285,6 +285,7 @@ impl Session {
|
||||
last_highlight: _,
|
||||
// Keyed by document id and revision, so one cache serves every document.
|
||||
protect_facts: _,
|
||||
format_state: _,
|
||||
// The input method talks to the window, whichever document it shows; the IME
|
||||
// context is keyed by `document_id`.
|
||||
ime_state_revision: _,
|
||||
|
||||
@@ -131,6 +131,7 @@ impl Session {
|
||||
untitled,
|
||||
made_rev,
|
||||
protect_facts: std::sync::Mutex::new(None),
|
||||
format_state: std::sync::Mutex::new(None),
|
||||
ime_body_epoch,
|
||||
ime_state_revision: None,
|
||||
ime_state_seen: None,
|
||||
|
||||
@@ -113,6 +113,7 @@ impl Session {
|
||||
autocap: _,
|
||||
rev: _,
|
||||
protect_facts: _,
|
||||
format_state: _,
|
||||
cache: _,
|
||||
layout: _,
|
||||
// The word being typed, like `column`: valid only while `sel` is where typing left it.
|
||||
@@ -296,6 +297,10 @@ impl Session {
|
||||
if facts.as_ref().is_some_and(|((_, r, _), _)| *r != rev) {
|
||||
*facts = None;
|
||||
}
|
||||
let format_state = self.format_state.get_mut().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if format_state.as_ref().is_some_and(|c| c.rev() != rev) {
|
||||
*format_state = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// [`crate::cmd::protect::Facts`] for the document as it is now, cached per revision.
|
||||
|
||||
+316
-3
@@ -1124,6 +1124,164 @@ fn applying_a_heading_clears_list_numbering() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Make the first `upto` bytes of body paragraph `block` 20 pt, red and bold.
|
||||
fn formatted_words(s: &mut Session, block: usize, upto: usize) {
|
||||
select(s, (block, 0), (block, upto));
|
||||
run(s, "format.size", json!({"size": 20}));
|
||||
run(s, "format.color", json!({"color": "FF0000"}));
|
||||
run(s, "format.bold", json!({"value": true}));
|
||||
}
|
||||
|
||||
/// 39 characters, 40 with the paragraph mark.
|
||||
const WORDS: &str = "keep this text and some more words here";
|
||||
|
||||
fn select(s: &mut Session, from: (usize, usize), to: (usize, usize)) {
|
||||
run(s, "select.range", json!({"anchor": {"block": from.0, "off": from.1}, "focus": {"block": to.0, "off": to.1}}));
|
||||
}
|
||||
|
||||
/// Size, colour and bold set directly on the character at `off` of body paragraph `block`.
|
||||
fn direct(s: &Session, block: usize, off: usize) -> (Option<f32>, bool, Option<bool>) {
|
||||
let c = s.doc.para_at(&Pos::body(block, 0)).unwrap().props_of_char(off);
|
||||
(c.size, c.color.is_some(), c.bold)
|
||||
}
|
||||
|
||||
const KEPT: (Option<f32>, bool, Option<bool>) = (Some(20.0), true, Some(true));
|
||||
const RESET: (Option<f32>, bool, Option<bool>) = (None, false, None);
|
||||
|
||||
#[test]
|
||||
fn a_paragraph_style_keeps_direct_formatting_on_less_than_half_the_paragraph() {
|
||||
// #5947, as in Word: "keep" is 4 of 40 characters (the paragraph mark counts), so Heading 1
|
||||
// keeps its size, colour and bold with the caret or the whole paragraph selected. Its size and
|
||||
// colour used to go.
|
||||
for (case, from, to) in [("caret", 37, 37), ("whole paragraph", 0, 39)] {
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": WORDS}));
|
||||
formatted_words(&mut s, 0, 4);
|
||||
select(&mut s, (0, from), (0, to));
|
||||
run(&mut s, "para.heading1", json!({}));
|
||||
assert_eq!(para_style(&s, 0).as_deref(), Some("Heading1"), "{case}");
|
||||
assert_eq!(direct(&s, 0, 0), KEPT, "{case}");
|
||||
let doc = crate::io::open_bytes("k.docx", &crate::io::save_bytes("k.docx", &s.doc).unwrap()).unwrap();
|
||||
let back = doc.para_at(&Pos::body(0, 0)).unwrap().props_of_char(0);
|
||||
assert_eq!((back.size, back.bold), (Some(20.0), Some(true)), "{case}: saved and reopened");
|
||||
}
|
||||
// Characters, not bytes: 6 of 16 characters, but 12 of 22 bytes.
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "\u{e9}\u{e9}\u{e9}\u{e9}\u{e9}\u{e9} abcdefgh"}));
|
||||
formatted_words(&mut s, 0, 12);
|
||||
run(&mut s, "caret.set", json!({"pos": {"story": "body", "path": [0], "off": 20}}));
|
||||
run(&mut s, "para.heading1", json!({}));
|
||||
assert_eq!(direct(&s, 0, 0), KEPT);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_paragraph_style_resets_direct_formatting_on_half_the_paragraph_or_more() {
|
||||
// As in Word: "keep this text and some more" is 28 of 40 characters, so Heading 1 resets its
|
||||
// size, colour and bold everywhere in the paragraph, wherever the caret is. Each property
|
||||
// counts on its own: italic on "keep" alone stays, and highlight always stays.
|
||||
{
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": WORDS}));
|
||||
formatted_words(&mut s, 0, 28);
|
||||
run(&mut s, "format.highlight", json!({"color": "yellow"}));
|
||||
select(&mut s, (0, 0), (0, 4));
|
||||
run(&mut s, "format.italic", json!({"value": true}));
|
||||
run(&mut s, "caret.set", json!({"pos": {"story": "body", "path": [0], "off": 37}}));
|
||||
run(&mut s, "para.heading1", json!({}));
|
||||
for off in [0, 10, 27] {
|
||||
assert_eq!(direct(&s, 0, off), RESET, "offset {off}");
|
||||
}
|
||||
let p = s.doc.para_at(&Pos::body(0, 0)).unwrap();
|
||||
assert_eq!(p.props_of_char(0).italic, Some(true), "italic on 4 characters stays");
|
||||
assert!(p.props_of_char(10).highlight.is_some(), "highlight stays");
|
||||
}
|
||||
// Exactly half resets: 11 of 22. 10 of 21 doesn't, but a formatted paragraph mark makes the
|
||||
// size 11 of 21.
|
||||
for (text, upto, mark, want) in [
|
||||
("aaaa bbbb cccc ddddd.", 11, false, RESET),
|
||||
("aaaa bbbb cccc dddd.", 10, false, KEPT),
|
||||
("aaaa bbbb cccc dddd.", 10, true, (None, true, Some(true))),
|
||||
] {
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": text}));
|
||||
formatted_words(&mut s, 0, upto);
|
||||
if mark {
|
||||
s.doc.para_mut(StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap().mark.size = Some(20.0);
|
||||
}
|
||||
run(&mut s, "caret.set", json!({"pos": {"story": "body", "path": [0], "off": 18}}));
|
||||
run(&mut s, "para.heading1", json!({}));
|
||||
assert_eq!(direct(&s, 0, 0), want, "{upto} of {}, mark formatted: {mark}", text.len() + 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_paragraph_style_on_part_of_a_paragraph_resets_only_the_selection() {
|
||||
// As in Word: with part of one paragraph selected, the selection loses its direct formatting
|
||||
// and nothing outside it changes, however much of the paragraph it covers. First the #5947
|
||||
// case: "keep" formatted, "this" selected. Then 28 of 40 formatted: "words" selected keeps it
|
||||
// all, "this" selected loses only its own. Checked at "keep", "this" and "more".
|
||||
for (upto, from, to, want) in [(4, 5, 9, (KEPT, RESET, RESET)), (28, 29, 34, (KEPT, KEPT, KEPT)), (28, 5, 9, (KEPT, RESET, KEPT))] {
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": WORDS}));
|
||||
formatted_words(&mut s, 0, upto);
|
||||
select(&mut s, (0, from), (0, to));
|
||||
run(&mut s, "para.heading1", json!({}));
|
||||
assert_eq!(para_style(&s, 0).as_deref(), Some("Heading1"));
|
||||
assert_eq!((direct(&s, 0, 0), direct(&s, 0, 6), direct(&s, 0, 24)), want, "{upto} formatted, {from}..{to} selected");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_paragraph_style_on_several_paragraphs_follows_the_first() {
|
||||
// As in Word: the selection from its start to the end of its first paragraph decides, and
|
||||
// what it resets goes from every selected paragraph. Nothing was reset across paragraphs
|
||||
// before. One undo takes it all back.
|
||||
let two = |first: usize, second: usize| {
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": format!("{WORDS}\n{WORDS}")}));
|
||||
formatted_words(&mut s, 0, first);
|
||||
formatted_words(&mut s, 1, second);
|
||||
s
|
||||
};
|
||||
// 4 of 40 in the first: both keep theirs, the second's 28 of 40 too.
|
||||
let mut s = two(4, 28);
|
||||
select(&mut s, (0, 0), (1, 2));
|
||||
run(&mut s, "para.heading1", json!({}));
|
||||
assert_eq!((para_style(&s, 0).as_deref(), para_style(&s, 1).as_deref()), (Some("Heading1"), Some("Heading1")));
|
||||
assert_eq!((direct(&s, 0, 0), direct(&s, 1, 0), direct(&s, 1, 10)), (KEPT, KEPT, KEPT));
|
||||
// 28 of 40 in the first: both lose it, the second's 4 of 40 too.
|
||||
let mut s = two(28, 4);
|
||||
let before = s.doc.body.clone();
|
||||
select(&mut s, (0, 0), (1, 2));
|
||||
run(&mut s, "para.heading1", json!({}));
|
||||
assert_eq!((direct(&s, 0, 0), direct(&s, 0, 10), direct(&s, 1, 0)), (RESET, RESET, RESET));
|
||||
let after = s.doc.body.clone();
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(s.doc.body, before, "one undo");
|
||||
run(&mut s, "edit.redo", json!({}));
|
||||
assert_eq!(s.doc.body, after, "redo");
|
||||
// From "here" (unformatted, 5 characters with the mark) in the first: nothing is reset.
|
||||
let mut s = two(28, 28);
|
||||
select(&mut s, (0, 35), (1, 2));
|
||||
run(&mut s, "para.heading1", json!({}));
|
||||
assert_eq!((direct(&s, 0, 0), direct(&s, 1, 0)), (KEPT, KEPT));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_style_created_from_formatted_text_carries_its_formatting() {
|
||||
// New Style from the selection: the style takes the paragraph's look, so its direct
|
||||
// formatting (all of the paragraph) goes and the text looks the same.
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": WORDS}));
|
||||
formatted_words(&mut s, 0, 39);
|
||||
run(&mut s, "caret.set", json!({"pos": {"story": "body", "path": [0], "off": 6}}));
|
||||
let id = run(&mut s, "styles.create", json!({"name": "Loud"}))["id"].as_str().unwrap().to_string();
|
||||
let st = s.doc.styles.get(&id).unwrap();
|
||||
assert_eq!((st.chr.size, st.chr.color.is_some(), st.chr.bold), KEPT);
|
||||
assert_eq!(para_style(&s, 0).as_deref(), Some(id.as_str()));
|
||||
assert_eq!(direct(&s, 0, 6), RESET, "the style carries it now");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_replace() {
|
||||
let mut s = s();
|
||||
@@ -2535,6 +2693,40 @@ fn table_doc() -> Session {
|
||||
s
|
||||
}
|
||||
|
||||
/// #6326: text typed into a row added by Insert Above, Insert Below or Tab in the last cell gets
|
||||
/// the font of the cells it was copied from, as in Word, not the default font.
|
||||
#[test]
|
||||
fn new_table_rows_type_in_the_rows_font() {
|
||||
let mut s = table_doc();
|
||||
for (text, font) in [("A1", "Courier New"), ("A2", "Courier New"), ("B1", "Georgia"), ("B2", "Georgia")] {
|
||||
run(&mut s, "select.text", json!({"text": text}));
|
||||
run(&mut s, "format.font", json!({"name": font}));
|
||||
run(&mut s, "format.size", json!({"size": 16}));
|
||||
run(&mut s, "format.bold", json!({}));
|
||||
}
|
||||
let typed = |s: &Session, r: usize, c: usize| {
|
||||
let t = s.doc.body.iter().find_map(|b| b.as_table()).unwrap();
|
||||
let p = t.rows[r].cells[c].blocks[0].as_para().unwrap();
|
||||
(p.plain_text(), p.props_at(0).font.clone(), p.props_at(0).size, p.props_at(0).bold)
|
||||
};
|
||||
let courier = |t: &str| (t.to_string(), Some("Courier New".to_string()), Some(16.0), Some(true));
|
||||
let georgia = |t: &str| (t.to_string(), Some("Georgia".to_string()), Some(16.0), Some(true));
|
||||
// (command, the caret's row, the new row)
|
||||
for (cmd, src, r) in [("table.insertRowBelow", 0, 1), ("table.insertRowAbove", 2, 2)] {
|
||||
run(&mut s, "caret.set", json!({"pos": {"story": "body", "path": [1, src, 0, 0], "off": 1}}));
|
||||
run(&mut s, cmd, json!({}));
|
||||
run(&mut s, "text.insert", json!({"text": "new"}));
|
||||
run(&mut s, "text.tab", json!({}));
|
||||
run(&mut s, "text.insert", json!({"text": "cell"}));
|
||||
assert_eq!((typed(&s, r, 0), typed(&s, r, 1)), (courier("new"), georgia("cell")), "{cmd}");
|
||||
}
|
||||
// Tab in the last cell adds a row like the last one.
|
||||
run(&mut s, "caret.set", json!({"pos": {"story": "body", "path": [1, 3, 1, 0], "off": 2}}));
|
||||
run(&mut s, "text.tab", json!({}));
|
||||
run(&mut s, "text.insert", json!({"text": "tab"}));
|
||||
assert_eq!(typed(&s, 4, 0), courier("tab"));
|
||||
}
|
||||
|
||||
fn body_table_cells(s: &Session) -> Vec<Vec<String>> {
|
||||
s.doc
|
||||
.body
|
||||
@@ -4560,6 +4752,10 @@ fn set_author_refuses_blank_names_and_clamps_long_ones() {
|
||||
}
|
||||
run(&mut s, "file.setAuthor", json!({"name": "Ada\u{0}\u{1b} Lovelace"}));
|
||||
assert_eq!(s.author, "Ada Lovelace", "control characters can't reach the saved XML");
|
||||
for name in ["\u{0} Ada Lovelace", "\u{1b}\t Ada Lovelace \u{0}"] {
|
||||
run(&mut s, "file.setAuthor", json!({"name": name}));
|
||||
assert_eq!(s.author, "Ada Lovelace", "whitespace exposed by removing controls is trimmed; internal spaces stay");
|
||||
}
|
||||
run(&mut s, "file.setAuthor", json!({"name": "é".repeat(100_000)}));
|
||||
assert_eq!(s.author.chars().count(), cmd::file::MAX_AUTHOR_CHARS);
|
||||
}
|
||||
@@ -5963,6 +6159,22 @@ fn caret_navigation() {
|
||||
assert_eq!(s.sel.focus.off, 10);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn select_text_does_not_wrap_large_occurrence_numbers() {
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "match match"}));
|
||||
run(&mut s, "select.text", json!({"text": "match", "occurrence": 2}));
|
||||
let selected = s.sel.clone();
|
||||
let depth = s.undo_depth();
|
||||
// On a 32-bit target, narrowing either number to usize would select the first match.
|
||||
for occurrence in [4_294_967_297u64, 8_589_934_593] {
|
||||
let result = s.run("select.text", &json!({"text": "match", "occurrence": occurrence}));
|
||||
assert!(matches!(result, Err(crate::CmdError::Failed(_))), "{occurrence}: no such match");
|
||||
assert_eq!(s.sel, selected, "{occurrence}: a failed search keeps the selection");
|
||||
assert_eq!(s.undo_depth(), depth, "{occurrence}: a failed search adds no undo step");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_box_insert_puts_the_caret_inside() {
|
||||
let mut s = s();
|
||||
@@ -7755,6 +7967,46 @@ fn props_colours_take_hex_strings() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The Paragraph dialog's indents in points win over indents in characters, as in Word: a
|
||||
/// document from WPS with `w:firstLineChars="400" w:firstLine="1417"` set to a first line of
|
||||
/// 2.5 cm keeps 2.5 cm, not four characters. The paragraph's own characters and its style's are
|
||||
/// cancelled; a paragraph without any is left without, and characters given with it stay.
|
||||
#[test]
|
||||
fn para_set_indents_in_points_win_over_indents_in_characters() {
|
||||
use wordcraft_doc::{Path, Pos};
|
||||
let mut s = s();
|
||||
run(&mut s, "text.insert", json!({"text": "One"}));
|
||||
run(&mut s, "text.newParagraph", json!({}));
|
||||
run(&mut s, "text.insert", json!({"text": "Two"}));
|
||||
let own = |s: &Session, i: usize| s.doc.para_at(&Pos::body(i, 0)).unwrap().props.clone();
|
||||
let shown = |s: &Session, i: usize| s.doc.styles.resolve_para(&own(s, i));
|
||||
{
|
||||
let p = &mut s.doc.para_mut(StoryRef::Body, &Path::top(0)).unwrap().props;
|
||||
(p.indent_first_chars, p.indent_first) = (Some(4.0), Some(70.85));
|
||||
}
|
||||
assert!((shown(&s, 0).indent_first - 70.85).abs() > 1.0, "four characters, not the points beside them");
|
||||
let cm = 2.5 * 72.0 / 2.54;
|
||||
|
||||
s.sel = crate::Selection::caret(Pos::body(0, 0));
|
||||
run(&mut s, "para.set", json!({"props": {"indentFirst": cm}}));
|
||||
assert_eq!((own(&s, 0).indent_first, own(&s, 0).indent_first_chars), (Some(cm), Some(0.0)));
|
||||
assert!((shown(&s, 0).indent_first - cm).abs() < 0.01, "2.5 cm on the page");
|
||||
|
||||
s.sel = crate::Selection::caret(Pos::body(1, 0));
|
||||
run(&mut s, "para.set", json!({"props": {"indentFirst": cm}}));
|
||||
assert_eq!(own(&s, 1).indent_first_chars, None, "no characters to cancel, none written");
|
||||
|
||||
// The style's characters, on the start edge through `onPage`, give way too.
|
||||
run(&mut s, "styles.modify", json!({"style": "Normal", "para": {"indentLeftChars": 2.0}}));
|
||||
run(&mut s, "para.set", json!({"props": {}, "onPage": {"left": 36.0}}));
|
||||
assert_eq!((own(&s, 1).indent_left, own(&s, 1).indent_left_chars), (Some(36.0), Some(0.0)));
|
||||
assert!((shown(&s, 1).indent_left - 36.0).abs() < 0.01);
|
||||
|
||||
// Characters given along with the points are kept.
|
||||
run(&mut s, "para.set", json!({"props": {"indentFirst": 24.0, "indentFirstChars": 2.0}}));
|
||||
assert_eq!(own(&s, 1).indent_first_chars, Some(2.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn para_set_frame_geometry_keeps_anchor_lock_unless_replaced() {
|
||||
use wordcraft_doc::props::TextFrame;
|
||||
@@ -10352,13 +10604,21 @@ fn convert_to_text_takes_each_separator() {
|
||||
let obj = wordcraft_doc::para::OBJ.to_string();
|
||||
for bad in [
|
||||
json!({"separator": "other"}),
|
||||
json!({"separator": "other", "char": ""}),
|
||||
json!({"separator": "other", "char": "\n"}),
|
||||
json!({"separator": "other", "char": "\r"}),
|
||||
json!({"separator": "other", "char": obj}),
|
||||
json!({"separator": "pipe"}),
|
||||
] {
|
||||
let mut s = typed_table(2, &["a", "b", "c", "d"]);
|
||||
let depth = s.undo_depth();
|
||||
assert!(s.run("table.toText", &bad).is_err(), "{bad}");
|
||||
let err = s.run("table.toText", &bad).unwrap_err();
|
||||
if bad["separator"] == "other" {
|
||||
assert!(
|
||||
matches!(err, crate::CmdError::Params(ref message) if message == "`char` with `other` must start with a character other than CR, LF or U+FFFC (the object marker); only the first character is used"),
|
||||
"{bad}: {err}"
|
||||
);
|
||||
}
|
||||
assert!(s.doc.body.iter().any(|b| b.as_table().is_some()), "{bad}: the table stays");
|
||||
assert_eq!(s.undo_depth(), depth);
|
||||
}
|
||||
@@ -10716,8 +10976,18 @@ fn convert_text_to_table_dialog_options() {
|
||||
let mut s1 = s();
|
||||
run(&mut s1, "document.setText", json!({"text": "a-b"}));
|
||||
run(&mut s1, "select.all", json!({}));
|
||||
assert!(s1.run("table.fromText", &json!({"separator": "other"})).is_err(), "no character");
|
||||
assert!(s1.run("table.fromText", &json!({"separator": "other", "char": ""})).is_err());
|
||||
for bad in [
|
||||
json!({"separator": "other"}),
|
||||
json!({"separator": "other", "char": ""}),
|
||||
json!({"separator": "other", "char": "\n"}),
|
||||
json!({"separator": "other", "char": "\r"}),
|
||||
] {
|
||||
let err = s1.run("table.fromText", &bad).unwrap_err();
|
||||
assert!(
|
||||
matches!(err, crate::CmdError::Params(ref message) if message == "`char` with `other` must start with a character other than CR or LF; only the first character is used"),
|
||||
"{bad}: {err}"
|
||||
);
|
||||
}
|
||||
assert!(s1.run("table.fromText", &json!({"separator": "nonsense"})).is_err());
|
||||
assert!(s1.run("table.fromText", &json!({"autofit": "nonsense"})).is_err());
|
||||
assert_eq!(body_texts(&s1), ["a-b"]);
|
||||
@@ -11529,6 +11799,49 @@ fn review_language_validates_tags_and_marks_text_unchecked() {
|
||||
assert_eq!(run(&mut s, "review.issues", json!({})), json!([]));
|
||||
}
|
||||
|
||||
/// #6013: as in Word, a table inserted in French text is French. Its cells take the language at
|
||||
/// the caret, not the document's default, so what is typed in them is proofed in that language.
|
||||
#[test]
|
||||
fn a_new_table_is_in_the_language_at_the_caret() {
|
||||
polish_test_dictionary();
|
||||
let cell_langs = |s: &Session| -> Vec<Option<String>> {
|
||||
let t = s.doc.body.iter().find_map(|b| b.as_table()).unwrap();
|
||||
t.rows.iter().flat_map(|r| &r.cells).flat_map(|c| &c.blocks).filter_map(|b| b.as_para()).map(|p| p.mark.lang.clone()).collect()
|
||||
};
|
||||
let mut fr = s();
|
||||
assert_eq!(fr.doc.styles.default_chr.lang.as_deref(), Some("en-US"));
|
||||
run(&mut fr, "review.language", json!({"lang": "fr-FR"}));
|
||||
run(&mut fr, "text.insert", json!({"text": "Bonjour"}));
|
||||
run(&mut fr, "text.newParagraph", json!({}));
|
||||
let at = run(&mut fr, "insert.table", json!({"rows": 2, "cols": 2}))["table"][0].clone();
|
||||
assert_eq!(cell_langs(&fr), vec![Some("fr-FR".to_string()); 4]);
|
||||
// Click in a cell, then type.
|
||||
for (cell, word) in [(1, "Vin"), (2, "Fromage")] {
|
||||
run(&mut fr, "caret.set", json!({"pos": {"story": "body", "path": [at, cell / 2, cell % 2, 0], "off": 0}}));
|
||||
assert_eq!(run(&mut fr, "format.state", json!({}))["lang"], "fr-FR", "cell {cell}");
|
||||
run(&mut fr, "text.insert", json!({"text": word}));
|
||||
}
|
||||
let t = fr.doc.body.iter().find_map(|b| b.as_table()).unwrap();
|
||||
for (cell, word) in [(1, "Vin"), (2, "Fromage")] {
|
||||
let p = t.rows[cell / 2].cells[cell % 2].blocks[0].as_para().unwrap();
|
||||
assert_eq!((p.plain_text().as_str(), p.props_of_char(0).lang.as_deref()), (word, Some("fr-FR")));
|
||||
}
|
||||
|
||||
// At the end of a Polish paragraph: Polish words typed in the cell aren't misspelt.
|
||||
let mut pl = Session::new(wordcraft_doc::Document::from_text("Płynie rzeka."));
|
||||
run(&mut pl, "select.all", json!({}));
|
||||
run(&mut pl, "review.language", json!({"lang": "pl-PL"}));
|
||||
run(&mut pl, "caret.docEnd", json!({}));
|
||||
run(&mut pl, "insert.table", json!({"rows": 1, "cols": 1}));
|
||||
run(&mut pl, "text.insert", json!({"text": "Zażółć gęślą jaźń."}));
|
||||
assert_eq!(run(&mut pl, "review.issues", json!({})), json!([]));
|
||||
|
||||
// Text with no language of its own: the cells follow the document's default.
|
||||
let mut plain = s();
|
||||
run(&mut plain, "insert.table", json!({"rows": 1, "cols": 2}));
|
||||
assert_eq!(cell_langs(&plain), vec![None, None]);
|
||||
}
|
||||
|
||||
/// The editing language (set by the front end from the interface language): new blank
|
||||
/// documents and opened plain text are written in it; the untouched first document switches,
|
||||
/// a document with changes never does, and templates stay English.
|
||||
|
||||
@@ -92,3 +92,91 @@ fn normal_double_quote_search_keeps_exact_modes_and_original_byte_ranges() {
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(text(&s), original);
|
||||
}
|
||||
|
||||
/// #7307: with smart quotes on, a quote typed in Replace with goes in curly by the character
|
||||
/// before the match, as typing curls it, so finding a straight quote and replacing it with a
|
||||
/// typed one curls a manuscript's stray quotes in bulk.
|
||||
#[test]
|
||||
fn a_quote_typed_in_replace_with_is_curled_by_smart_quotes() {
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "He said \"hi\" (\"no\") and 'bye' -- don't"}));
|
||||
assert_eq!(run(&mut s, "edit.replaceAll", json!({"text": "^034", "with": "\""}))["replaced"], 4);
|
||||
assert_eq!(text(&s), "He said “hi” (“no”) and 'bye' -- don't");
|
||||
assert_eq!(run(&mut s, "edit.replaceAll", json!({"text": "^039", "with": "'"}))["replaced"], 3);
|
||||
assert_eq!(text(&s), "He said “hi” (“no”) and ‘bye’ -- don’t");
|
||||
// One undo step each.
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(text(&s), "He said “hi” (“no”) and 'bye' -- don't");
|
||||
|
||||
// A match touching the one before it curls by that one's replacement: after an opening
|
||||
// double quote a single quote opens too.
|
||||
let mut s = super::s();
|
||||
run(&mut s, "document.setText", json!({"text": "xx"}));
|
||||
assert_eq!(run(&mut s, "edit.replaceAll", json!({"text": "x", "with": "'\""}))["replaced"], 2);
|
||||
assert_eq!(text(&s), "‘“‘“");
|
||||
|
||||
// Replace (one at a time) changes only the selected match, so the text before it as it is
|
||||
// decides: the second `x` follows an unreplaced `x` and closes.
|
||||
let mut s = super::s();
|
||||
run(&mut s, "document.setText", json!({"text": "xx"}));
|
||||
run(&mut s, "select.range", json!({"anchor": wordcraft_doc::Pos::body(0, 1), "focus": wordcraft_doc::Pos::body(0, 2)}));
|
||||
assert_eq!(run(&mut s, "edit.replace", json!({"text": "x", "with": "'\""}))["replaced"], 1);
|
||||
assert_eq!(text(&s), "x’”");
|
||||
}
|
||||
|
||||
/// #7307: a typed `'` in Find what also finds curly apostrophes. A match that already is a curly
|
||||
/// quote of that kind is left as it is and not counted, so an apostrophe set on purpose (’90s)
|
||||
/// isn't turned into an opening quote.
|
||||
#[test]
|
||||
fn replace_with_a_typed_quote_leaves_curly_ones_and_does_not_count_them() {
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "the ’90s, it’s 'x' and “y”"}));
|
||||
assert_eq!(run(&mut s, "edit.replaceAll", json!({"text": "'", "with": "'"}))["replaced"], 2);
|
||||
assert_eq!(text(&s), "the ’90s, it’s ‘x’ and “y”");
|
||||
assert_eq!(run(&mut s, "edit.replaceAll", json!({"text": "\"", "with": "\""}))["replaced"], 0);
|
||||
assert_eq!(text(&s), "the ’90s, it’s ‘x’ and “y”");
|
||||
// A whole word with its apostrophe: already curled, left alone; straight, curled.
|
||||
run(&mut s, "document.setText", json!({"text": "don’t don't"}));
|
||||
assert_eq!(run(&mut s, "edit.replaceAll", json!({"text": "don't", "with": "don't"}))["replaced"], 1);
|
||||
assert_eq!(text(&s), "don’t don’t");
|
||||
|
||||
// Replace (one at a time) skips such a match too, and moves on to the next.
|
||||
let mut s = super::s();
|
||||
run(&mut s, "document.setText", json!({"text": "it’s 'x"}));
|
||||
let first = run(&mut s, "edit.replace", json!({"text": "'", "with": "'"}));
|
||||
assert_eq!(first["replaced"], 0, "the first call selects the first match");
|
||||
let kept = run(&mut s, "edit.replace", json!({}));
|
||||
assert_eq!((kept["replaced"].clone(), text(&s)), (json!(0), "it’s 'x".to_string()), "the curly apostrophe stays");
|
||||
assert_eq!(run(&mut s, "edit.replace", json!({}))["replaced"], 1);
|
||||
assert_eq!(text(&s), "it’s ‘x");
|
||||
}
|
||||
|
||||
/// #7307: a quote given by its code stays straight, so curly quotes can still be made straight on
|
||||
/// purpose; with smart quotes off, or with a regular expression, a typed quote stays straight too.
|
||||
#[test]
|
||||
fn coded_quotes_and_smart_quotes_off_replace_with_straight_quotes() {
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "“hi” it’s"}));
|
||||
assert_eq!(run(&mut s, "edit.replaceAll", json!({"text": "\"", "with": "^034"}))["replaced"], 2);
|
||||
assert_eq!(run(&mut s, "edit.replaceAll", json!({"text": "'", "with": "^039"}))["replaced"], 1);
|
||||
assert_eq!(text(&s), "\"hi\" it's");
|
||||
|
||||
let mut s = super::s();
|
||||
run(&mut s, "document.setText", json!({"text": "“hi”"}));
|
||||
assert_eq!(run(&mut s, "edit.replaceAll", json!({"text": "\"", "with": "\"", "regex": false, "wildcards": false}))["replaced"], 0);
|
||||
assert_eq!(run(&mut s, "edit.replaceAll", json!({"text": "[“”]", "with": "\"", "regex": true}))["replaced"], 2);
|
||||
assert_eq!(text(&s), "\"hi\"");
|
||||
|
||||
// Special characters off takes Replace with as written: with codes off it is the way, besides
|
||||
// turning smart quotes off, to put a straight quote in.
|
||||
let mut s = super::s();
|
||||
run(&mut s, "document.setText", json!({"text": "“hi”"}));
|
||||
assert_eq!(run(&mut s, "edit.replaceAll", json!({"text": "“", "with": "\"", "special": false}))["replaced"], 1);
|
||||
assert_eq!(text(&s), "\"hi”");
|
||||
|
||||
let mut s = super::s();
|
||||
s.prefs.autocorrect.smart_quotes = false;
|
||||
run(&mut s, "document.setText", json!({"text": "“hi”"}));
|
||||
assert_eq!(run(&mut s, "edit.replaceAll", json!({"text": "\"", "with": "\"", "regex": false}))["replaced"], 2);
|
||||
assert_eq!(text(&s), "\"hi\"");
|
||||
}
|
||||
|
||||
@@ -1258,3 +1258,16 @@ fn html_container_shading_is_paragraph_shading_while_inline_highlight_stays_on_r
|
||||
assert_eq!(p2.runs.first().and_then(|r| r.props.shading), Some(wordcraft_doc::Rgb(0xff, 0xff, 0x00)), "{exported}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn odt_list_item_later_paragraphs_stay_in_the_item() {
|
||||
// "One" has two paragraphs. The second must stay inside item 1, so HTML's "Two" is item 2.
|
||||
let fodt = r#"<?xml version="1.0" encoding="UTF-8"?>
|
||||
<office:document xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" office:version="1.3" office:mimetype="application/vnd.oasis.opendocument.text"><office:automatic-styles><text:list-style style:name="L1"><text:list-level-style-number text:level="1" style:num-format="1"/></text:list-style></office:automatic-styles><office:body><office:text><text:list text:style-name="L1"><text:list-item><text:p>One</text:p><text:p>Still one</text:p></text:list-item><text:list-item><text:p>Two</text:p></text:list-item></text:list></office:text></office:body></office:document>"#;
|
||||
let doc = crate::odt::import_flat(fodt.as_bytes()).unwrap();
|
||||
let html = crate::html::export(&doc);
|
||||
assert_eq!(html.matches("<ol").count(), 1, "one list, not restarted: {html}");
|
||||
let (one, still, two) = (html.find("One").unwrap(), html.find("Still one").unwrap(), html.find("Two").unwrap());
|
||||
assert!(one < still && still < two, "{html}");
|
||||
assert!(html[one..still].matches("</li>").count() == 0, "later paragraph left item 1: {html}");
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@ pub(crate) enum Pass {
|
||||
/// Walk state while paginating.
|
||||
pub(crate) struct Ctx<'a> {
|
||||
pub(crate) doc: &'a Document,
|
||||
pub(crate) numbering: wordcraft_doc::numbering::NumberingIndex<'a>,
|
||||
pub(crate) cache: &'a mut LayoutCache,
|
||||
pub(crate) opts: &'a LayoutOptions,
|
||||
pub(crate) counters: Counters,
|
||||
@@ -289,11 +290,11 @@ impl Ctx<'_> {
|
||||
.numbering
|
||||
.or_else(|| self.doc.styles.resolve_para(&p.props).numbering)
|
||||
.filter(|n| n.num != 0)
|
||||
.is_some_and(|n| self.doc.numbering.shows_label(n.num, n.level))
|
||||
.is_some_and(|n| self.numbering.shows_label(n.num, n.level))
|
||||
}
|
||||
pub(crate) fn next_label(&mut self, p: &Paragraph) -> Option<(String, Level)> {
|
||||
let n = p.props.numbering.or_else(|| self.doc.styles.resolve_para(&p.props).numbering).filter(|n| n.num != 0)?;
|
||||
self.counters.next_label(&self.doc.numbering, n.num, n.level)
|
||||
self.counters.next_label_indexed(&self.numbering, n.num, n.level)
|
||||
}
|
||||
|
||||
/// Lay out `p` with its already counted `label`, so laying a paragraph out again (around
|
||||
@@ -587,6 +588,7 @@ mod tests {
|
||||
let mut cache = LayoutCache::new();
|
||||
let mut ctx = Ctx {
|
||||
doc: &doc,
|
||||
numbering: wordcraft_doc::numbering::NumberingIndex::new(&doc.numbering),
|
||||
cache: &mut cache,
|
||||
opts: &opts,
|
||||
counters: Default::default(),
|
||||
|
||||
@@ -750,11 +750,14 @@ fn inline_objects(ctx: &LineContext<'_, '_, '_>, out: &mut Vec<Draw>) {
|
||||
}
|
||||
|
||||
fn proofing_marks(ctx: &LineContext<'_, '_, '_>, out: &mut Vec<Draw>) {
|
||||
// Spaces hanging past the right margin are marked only up to where the caret stops (#6434).
|
||||
let limit = ctx.pl.caret_limit(ctx.li);
|
||||
for (start, end, grammar) in &ctx.pl.issues {
|
||||
if *end <= ctx.line.start || *start >= ctx.line.stop {
|
||||
continue;
|
||||
}
|
||||
for (x0, x1) in ctx.pl.x_spans(ctx.li, (*start).max(ctx.line.start), (*end).min(ctx.line.stop)) {
|
||||
let (x0, x1) = limit.map_or((x0, x1), |m| (x0.min(m), x1.min(m)));
|
||||
if x1 - x0 < 1.0 {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -712,9 +712,10 @@ impl<'a> Flow<'a> {
|
||||
},
|
||||
);
|
||||
self.late.drew();
|
||||
let raised = items.len()..items.len() + front.len();
|
||||
items.extend(front);
|
||||
items.extend(line_numbers(ctx, pb, &self.pl, (l0, l1), y));
|
||||
add_items(pb, behind, items);
|
||||
add_items(pb, behind, items, raised);
|
||||
if let (Some(f), Some(l)) = (self.pl.lines.get(l0), self.pl.lines.get(l1 - 1)) {
|
||||
pb.y = y + (l.top + l.height - f.top);
|
||||
pb.content_bottom = pb.content_bottom.max(pb.y);
|
||||
@@ -957,10 +958,17 @@ fn line_numbers(ctx: &mut Ctx, pb: &mut PageBuilder, pl: &ParaLayout, (l0, l1):
|
||||
items
|
||||
}
|
||||
|
||||
/// Add a piece's items to the last page: those `behind` the text at the front, the rest at the end.
|
||||
fn add_items(pb: &mut PageBuilder, behind: Vec<Placed>, items: Vec<Placed>) {
|
||||
/// Add a piece's items to the last page: those `behind` the text at the front, the rest at the end,
|
||||
/// the `raised` ones among them (its floating objects) to be drawn over the page's text.
|
||||
fn add_items(pb: &mut PageBuilder, behind: Vec<Placed>, items: Vec<Placed>, raised: std::ops::Range<usize>) {
|
||||
let n_behind = behind.len();
|
||||
if let Some(pg) = pb.pages.last_mut() {
|
||||
let at = pg.items.len().saturating_sub(pb.behind.last().copied().unwrap_or(0));
|
||||
if !raised.is_empty()
|
||||
&& let Some(f) = pb.front.last_mut()
|
||||
{
|
||||
f.push(at.saturating_add(raised.start)..at.saturating_add(raised.end));
|
||||
}
|
||||
for (i, it) in behind.into_iter().enumerate() {
|
||||
pg.items.insert(i.min(pg.items.len()), it);
|
||||
}
|
||||
@@ -1166,7 +1174,7 @@ fn next_first_line(ctx: &mut Ctx, block: usize, width: f32, depth: usize, new_pa
|
||||
// Keep list indents and label metrics without consuming the document counters.
|
||||
let rp = ctx.doc.styles.resolve_para(&p.props);
|
||||
let label =
|
||||
p.props.numbering.or(rp.numbering).filter(|n| n.num != 0).and_then(|n| counters.next_label(&ctx.doc.numbering, n.num, n.level));
|
||||
p.props.numbering.or(rp.numbering).filter(|n| n.num != 0).and_then(|n| counters.next_label_indexed(&ctx.numbering, n.num, n.level));
|
||||
let pl = match ctx.para_ahead(p, width, label.clone()) {
|
||||
Some(pl) => pl,
|
||||
None => {
|
||||
|
||||
@@ -988,15 +988,19 @@ impl DocLayout {
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let x0 = para.x_of(li, from).unwrap_or(l.left);
|
||||
let mut x1 = para.x_of(li, to).unwrap_or(x0);
|
||||
// Spaces hanging past the right margin are highlighted only up to where the
|
||||
// caret stops (#6434).
|
||||
let limit = para.caret_limit(li);
|
||||
let clamp = |x: f32| limit.map_or(x, |m| x.min(m));
|
||||
let x0 = clamp(para.x_of(li, from).unwrap_or(l.left));
|
||||
let mut x1 = clamp(para.x_of(li, to).unwrap_or(x0));
|
||||
// Selection continuing past the paragraph end shows the paragraph mark.
|
||||
let last_line = li + 1 == para.lines.len();
|
||||
if last_line && path != b.path {
|
||||
x1 += PARA_MARK_WIDTH;
|
||||
}
|
||||
if path == b.path && to >= l.stop && li + 1 < para.lines.len() && b.off > l.stop {
|
||||
x1 = para.x_of(li, l.stop).unwrap_or(x1);
|
||||
x1 = clamp(para.x_of(li, l.stop).unwrap_or(x1));
|
||||
}
|
||||
if x1 <= x0 && !(last_line && path != b.path) {
|
||||
continue;
|
||||
|
||||
@@ -303,7 +303,12 @@ pub struct Page {
|
||||
pub section: usize,
|
||||
/// Page number as displayed (after section restarts).
|
||||
pub number: u32,
|
||||
/// The body's items in drawing order: floating objects in front of the text after all of it.
|
||||
pub items: Vec<Placed>,
|
||||
/// Where each of `items` comes in reading order (its anchor's), when that isn't its place in
|
||||
/// `items`: floating objects in front of the text are drawn after it (#5534) but read after
|
||||
/// their anchor. Empty when the two orders are the same; items past its end are read in place.
|
||||
pub reading: Vec<usize>,
|
||||
/// Header / footer items (drawn dimmed while editing the body).
|
||||
pub header: Vec<Placed>,
|
||||
pub footer: Vec<Placed>,
|
||||
|
||||
@@ -65,6 +65,10 @@ pub(crate) struct PageBuilder<'a> {
|
||||
/// Per page: how many items were inserted at the front of its list (behind the text), so a
|
||||
/// [`Snap`] can take them out again.
|
||||
pub(crate) behind: Vec<usize>,
|
||||
/// Per page: the items of its floating objects that are not behind the text (indices counted
|
||||
/// after the items behind it), drawn over all of its text once it is laid out
|
||||
/// ([`PageBuilder::raise_front`]).
|
||||
pub(crate) front: Vec<Vec<std::ops::Range<usize>>>,
|
||||
/// The bottom of the tallest column on the current page before the current one.
|
||||
pub(crate) max_y: f32,
|
||||
/// The bottom of the lowest line or table row placed on the current page (without the space
|
||||
@@ -303,12 +307,32 @@ impl PageBuilder<'_> {
|
||||
}
|
||||
self.pages.pop();
|
||||
self.behind.pop();
|
||||
self.front.pop();
|
||||
self.number = self.number.saturating_sub(1);
|
||||
self.after_break_mark = false;
|
||||
// The page before was aligned when it was left: nothing on it moves again.
|
||||
self.page_items_start = self.pages.last().map_or(0, |p| p.items.len());
|
||||
true
|
||||
}
|
||||
/// Draw each page's floating objects that are not behind the text over all of its text, in
|
||||
/// their own order: Word draws them on top, and the shading, borders and lines of the
|
||||
/// paragraphs and tables after their anchor would otherwise cover them (#5534). Once all
|
||||
/// pages are laid out, so going back to a [`Snap`] still finds the items where they went.
|
||||
/// Their place in reading order stays in [`Page::reading`].
|
||||
pub(crate) fn raise_front(&mut self) {
|
||||
for ((pg, ranges), behind) in self.pages.iter_mut().zip(&mut self.front).zip(&self.behind) {
|
||||
if ranges.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let mut raised = vec![false; pg.items.len()];
|
||||
for r in ranges.drain(..) {
|
||||
let (start, end) = (r.start.saturating_add(*behind), r.end.saturating_add(*behind));
|
||||
raised.get_mut(start..end.min(pg.items.len())).into_iter().flatten().for_each(|f| *f = true);
|
||||
}
|
||||
let (top, under): (Vec<_>, Vec<_>) = std::mem::take(&mut pg.items).into_iter().zip(raised).enumerate().partition(|(_, (_, up))| *up);
|
||||
(pg.reading, pg.items) = under.into_iter().chain(top).map(|(at, (it, _))| (at, it)).unzip();
|
||||
}
|
||||
}
|
||||
/// Finish the current page: the lines between its columns, its vertical alignment and its
|
||||
/// footnotes, placed with the section state in effect (margins, gutter, separators).
|
||||
/// `new_page` starts with this; after it has run, `new_page` finds nothing left to finish.
|
||||
@@ -345,6 +369,7 @@ impl PageBuilder<'_> {
|
||||
self.page_valign = s.valign;
|
||||
self.pages.push(Page { w, h, section: self.sect_idx, number: self.number, body, first_block, items: decor, ..Default::default() });
|
||||
self.behind.push(0);
|
||||
self.front.push(Vec::new());
|
||||
self.col = 0;
|
||||
self.cols = s.column_boxes();
|
||||
self.top = body_top;
|
||||
|
||||
@@ -214,13 +214,15 @@ impl ParaLayout {
|
||||
}
|
||||
/// The farthest right a caret goes on left-to-right line `li`: spaces at the end of a line
|
||||
/// hang past its right edge, but the caret after them stays at the edge, as in Word (#2146);
|
||||
/// text that overflows the line still carries it. `None` on bidirectional lines.
|
||||
/// text that overflows the line still carries it. Markers and breaks after the spaces hang
|
||||
/// with them, as where the line's content ends (#6434). `None` on bidirectional lines.
|
||||
pub fn caret_limit(&self, li: usize) -> Option<f32> {
|
||||
let l = self.lines.get(li)?;
|
||||
if !l.vis.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let ink = (l.c0..l.c1).rev().find(|&k| self.clusters.get(k).is_some_and(|c| c.kind != ClKind::Space));
|
||||
let hangs = |c: &Cluster| matches!(c.kind, ClKind::Space | ClKind::Marker | ClKind::LineBreak | ClKind::PageBreak | ClKind::ColumnBreak);
|
||||
let ink = (l.c0..l.c1).rev().find(|&k| self.clusters.get(k).is_some_and(|c| !hangs(c)));
|
||||
let end = match ink {
|
||||
Some(k) => l.xs.get(k + 1 - l.c0).copied(),
|
||||
None => l.xs.first().copied(),
|
||||
|
||||
@@ -79,6 +79,7 @@ fn new_ctx<'a>(
|
||||
});
|
||||
Ctx {
|
||||
doc,
|
||||
numbering: wordcraft_doc::numbering::NumberingIndex::new(&doc.numbering),
|
||||
cache,
|
||||
opts,
|
||||
hide_deleted: opts.hides_deleted(StoryRef::Body),
|
||||
@@ -224,6 +225,7 @@ fn new_page_builder<'p>(
|
||||
seps: NoteSeps::default(),
|
||||
para_end: None,
|
||||
behind: Vec::new(),
|
||||
front: Vec::new(),
|
||||
max_y: 0.0,
|
||||
content_bottom: 0.0,
|
||||
balance: None,
|
||||
@@ -456,6 +458,7 @@ fn finish_pages(pb: PageBuilder, doc: &Document, sections: &[(usize, &SectionPro
|
||||
pb.flush_notes();
|
||||
}
|
||||
pb.carry.clear();
|
||||
pb.raise_front();
|
||||
let mut pages = pb.pages;
|
||||
if !web {
|
||||
for p in &mut pages {
|
||||
@@ -660,9 +663,9 @@ struct Snap<'a> {
|
||||
impl<'a> Snap<'a> {
|
||||
fn take(pb: &mut PageBuilder<'a>, ctx: &Ctx) -> Self {
|
||||
// The pages stay out of the copy: it would cost the whole document per block.
|
||||
let (pages, behind) = (std::mem::take(&mut pb.pages), std::mem::take(&mut pb.behind));
|
||||
let (pages, behind, front) = (std::mem::take(&mut pb.pages), std::mem::take(&mut pb.behind), std::mem::take(&mut pb.front));
|
||||
let copy = pb.clone();
|
||||
(pb.pages, pb.behind) = (pages, behind);
|
||||
(pb.pages, pb.behind, pb.front) = (pages, behind, front);
|
||||
Snap {
|
||||
pb: copy,
|
||||
pages: pb.pages.len(),
|
||||
@@ -679,9 +682,15 @@ impl<'a> Snap<'a> {
|
||||
/// Go back to this state: drop the pages added since and what was added to the last one
|
||||
/// (appended, or inserted at the front behind the text).
|
||||
fn restore(&self, pb: &mut PageBuilder<'a>, ctx: &mut Ctx) {
|
||||
let (mut pages, mut behind) = (std::mem::take(&mut pb.pages), std::mem::take(&mut pb.behind));
|
||||
let (mut pages, mut behind, mut front) = (std::mem::take(&mut pb.pages), std::mem::take(&mut pb.behind), std::mem::take(&mut pb.front));
|
||||
pages.truncate(self.pages);
|
||||
behind.truncate(self.pages);
|
||||
front.truncate(self.pages);
|
||||
// The objects in front of the text that were added to the last page since go with them.
|
||||
let kept = self.items.saturating_sub(self.behind);
|
||||
if let Some(f) = front.last_mut() {
|
||||
f.retain(|r| r.end <= kept);
|
||||
}
|
||||
if let Some(pg) = pages.last_mut() {
|
||||
let k = behind.last().copied().unwrap_or(0).saturating_sub(self.behind).min(pg.items.len());
|
||||
pg.items.drain(..k);
|
||||
@@ -691,7 +700,7 @@ impl<'a> Snap<'a> {
|
||||
*b = self.behind;
|
||||
}
|
||||
*pb = self.pb.clone();
|
||||
(pb.pages, pb.behind) = (pages, behind);
|
||||
(pb.pages, pb.behind, pb.front) = (pages, behind, front);
|
||||
ctx.counters = self.counters.clone();
|
||||
ctx.eq_count = self.eq_count;
|
||||
ctx.fields.page = self.page_field;
|
||||
|
||||
@@ -169,6 +169,7 @@ impl StyleIndex {
|
||||
styles.entry(st.name.to_lowercase()).or_insert_with(|| v.clone());
|
||||
styles.insert(st.id.to_lowercase(), v);
|
||||
}
|
||||
let numbering = wordcraft_doc::numbering::NumberingIndex::new(&doc.numbering);
|
||||
let mut counters = Counters::default();
|
||||
let mut ordinals: HashMap<String, u32> = HashMap::new();
|
||||
let mut entries = Vec::new();
|
||||
@@ -184,12 +185,12 @@ impl StyleIndex {
|
||||
let num = p.props.numbering.or_else(|| doc.styles.resolve_para(&p.props).numbering).filter(|n| n.num != 0);
|
||||
let (mut label, mut levels, mut level) = (None, Vec::new(), 0u8);
|
||||
if let Some(n) = num
|
||||
&& let Some((l, def)) = counters.next_label(&doc.numbering, n.num, n.level)
|
||||
&& let Some((l, def)) = counters.next_label_indexed(&numbering, n.num, n.level)
|
||||
&& def.format != NumFormat::Bullet
|
||||
{
|
||||
let vals = counters.values(&doc.numbering, n.num).unwrap_or_default();
|
||||
let vals = counters.values_indexed(&numbering, n.num).unwrap_or_default();
|
||||
for (k, v) in vals.iter().enumerate().take(usize::from(n.level.min(8)) + 1) {
|
||||
let Some(lv) = doc.numbering.level(n.num, k as u8) else { continue };
|
||||
let Some(lv) = numbering.level(n.num, k as u8) else { continue };
|
||||
if matches!(lv.format, NumFormat::None | NumFormat::Bullet) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ use wordcraft_geom::Rect;
|
||||
|
||||
use crate::boxes::BoxContext;
|
||||
use crate::para::{CellText, ClKind, ParaLayout};
|
||||
use crate::{BoxInput, BoxLayout, Ctx, Placed, layout_box};
|
||||
use crate::{BoxInput, BoxLayout, Ctx, Placed, ViewMode, layout_box};
|
||||
|
||||
/// Largest preferred table width, as a share of the text column, that a file can ask for.
|
||||
const MAX_WIDTH_SHARE: f32 = 10.0;
|
||||
@@ -431,6 +431,12 @@ fn table_frame(ctx: &mut Ctx, t: &Table, avail: f32, depth: usize, style: Option
|
||||
grid.iter_mut().for_each(|w| *w *= k);
|
||||
total = avail;
|
||||
}
|
||||
// The reading view reflows to its column, so even a table with its own width fits it (#7988).
|
||||
if ctx.opts.view == ViewMode::Read && total > avail && avail > 0.0 {
|
||||
let k = avail / total;
|
||||
grid.iter_mut().for_each(|w| *w *= k);
|
||||
total = avail;
|
||||
}
|
||||
if !t.props.fixed {
|
||||
// Measuring lays paragraphs out once more; it mustn't count their equations twice.
|
||||
let eq_count = ctx.eq_count;
|
||||
@@ -477,6 +483,14 @@ fn table_frame(ctx: &mut Ctx, t: &Table, avail: f32, depth: usize, style: Option
|
||||
} else {
|
||||
indent - first_cell_left_margin_in(t, margins_def)
|
||||
};
|
||||
// The reading view fits the table into what the start offset leaves of the column, mirrored or not (#7988).
|
||||
let room = (avail - start_offset.max(0.0)).max(1.0);
|
||||
if ctx.opts.view == ViewMode::Read && acc > room && !matches!(t.props.align, Some(Align::Center | Align::Right)) {
|
||||
let k = room / acc;
|
||||
colx.iter_mut().for_each(|c| *c *= k);
|
||||
acc = room;
|
||||
total = room;
|
||||
}
|
||||
let x = match (t.props.align, rtl) {
|
||||
(Some(Align::Center), _) => (avail - total) / 2.0,
|
||||
// End alignment: the right margin, or the left one in a right-to-left table.
|
||||
@@ -485,6 +499,13 @@ fn table_frame(ctx: &mut Ctx, t: &Table, avail: f32, depth: usize, style: Option
|
||||
(_, true) => avail - total - start_offset,
|
||||
(_, false) => start_offset,
|
||||
};
|
||||
// The reading view has no margin to hang a negative indent into: keep the table inside the column (#8020).
|
||||
// The clamp also pulls in an over-large positive indent. A table wider than the column keeps its start edge.
|
||||
let x = if ctx.opts.view == crate::ViewMode::Read {
|
||||
if total > avail { if rtl { avail - total } else { 0.0 } } else { x.clamp(0.0, avail - total) }
|
||||
} else {
|
||||
x
|
||||
};
|
||||
TableFrame { ncols, colx, acc, total, margins_def, tborders, rtl, x }
|
||||
}
|
||||
|
||||
@@ -1506,7 +1527,7 @@ fn blocks_content(ctx: &mut Ctx, blocks: &Blocks, text: Option<&CellText>, depth
|
||||
/// The list level `p` is in, for its indents (without counting it: measuring isn't laying out).
|
||||
fn list_level(ctx: &Ctx, p: &Paragraph) -> Option<wordcraft_doc::numbering::Level> {
|
||||
let n = p.props.numbering.or_else(|| ctx.doc.styles.resolve_para(&p.props).numbering).filter(|n| n.num != 0)?;
|
||||
ctx.doc.numbering.level(n.num, n.level).cloned()
|
||||
ctx.numbering.level(n.num, n.level).cloned()
|
||||
}
|
||||
|
||||
/// A width to lay a paragraph out in so that only its own line breaks end lines.
|
||||
|
||||
@@ -660,6 +660,31 @@ fn reading_layout_reflows_into_viewport_height_pages_without_changing_print_layo
|
||||
assert!(invalid.pages.iter().all(|p| p.w.is_finite() && p.h.is_finite()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reading_layout_fits_a_wide_table_to_the_column() {
|
||||
crate::test_fonts();
|
||||
// #7988: a 468 pt table is wider than a reading column but must not run past its edge, however it is indented or mirrored.
|
||||
let cases = [(0.0, false, None), (36.0, false, None), (36.0, true, None)];
|
||||
let aligned = [None, Some(Align::Left), Some(Align::Center), Some(Align::Right)].map(|a| (36.0, false, a));
|
||||
let aligned_rtl = [Some(Align::Left), Some(Align::Right)].map(|a| (36.0, true, a));
|
||||
for (indent, rtl, align) in cases.into_iter().chain(aligned).chain(aligned_rtl) {
|
||||
let mut d = Document::from_text("Before.");
|
||||
let mut t = Table::new(2, 4, 468.0);
|
||||
t.props.indent = Some(indent);
|
||||
t.props.bidi_visual = rtl;
|
||||
t.props.align = align;
|
||||
d.insert_block(StoryRef::Body, &Path::top(1), wordcraft_doc::Block::Table(t)).unwrap();
|
||||
let opts = LayoutOptions { view: ViewMode::Read, web_width: 360.0, read_height: 600.0, ..Default::default() };
|
||||
let l = layout(&d, &mut LayoutCache::new(), &opts);
|
||||
let p = &l.pages[0];
|
||||
let cells: Vec<_> = p.items.iter().filter_map(|i| if let Placed::Cell { rect, .. } = i { Some(*rect) } else { None }).collect();
|
||||
let (left, right) = cells.iter().fold((f32::MAX, 0.0f32), |(l, r), c| (l.min(c.x), r.max(c.x + c.w)));
|
||||
assert!(right > left, "cells placed");
|
||||
assert!(right <= p.body.x + p.body.w + 0.5, "indent {indent} rtl {rtl} {align:?}: right {right} vs column {}", p.body.x + p.body.w);
|
||||
assert!(left >= p.body.x - 0.5, "indent {indent} rtl {rtl} {align:?}: left {left} vs column {}", p.body.x);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hit_and_caret_agree() {
|
||||
crate::test_fonts();
|
||||
@@ -3737,6 +3762,70 @@ fn caret_after_hanging_spaces_stays_at_the_margin() {
|
||||
}
|
||||
}
|
||||
|
||||
/// "a" and 200 spaces hanging past the right margin: at the paragraph's end, before a letter that
|
||||
/// wraps, before a bookmark (a zero-width marker) and before a line break.
|
||||
fn hanging_space_paragraphs() -> Vec<(&'static str, wordcraft_doc::Paragraph)> {
|
||||
let spaces = format!("a{}", " ".repeat(200));
|
||||
let mut marked = wordcraft_doc::Paragraph::with_text(&spaces, Default::default());
|
||||
marked.insert_object(spaces.len(), InlineObject::BookmarkStart { name: "end".into() }, &Default::default()).unwrap();
|
||||
let text = |t: &str| wordcraft_doc::Paragraph::with_text(t, Default::default());
|
||||
vec![
|
||||
("at the end", text(&spaces)),
|
||||
("before a wrap", text(&format!("{spaces}b"))),
|
||||
("before a bookmark", marked),
|
||||
("before a line break", text(&format!("{spaces}{}b", wordcraft_doc::para::LINE_BREAK))),
|
||||
]
|
||||
}
|
||||
|
||||
/// The selection highlight over spaces hanging past the right margin stops at the margin with the
|
||||
/// caret (#6434), whatever follows the spaces. Selected through the paragraph's end, its mark
|
||||
/// shows just past the margin.
|
||||
#[test]
|
||||
fn selection_over_hanging_spaces_stops_at_the_margin() {
|
||||
crate::test_fonts();
|
||||
for (case, p) in hanging_space_paragraphs() {
|
||||
let len = p.text.len();
|
||||
let mut d = Document::new();
|
||||
d.body = vec![wordcraft_doc::para_block(p), wordcraft_doc::para_block(wordcraft_doc::Paragraph::new())];
|
||||
let right = d.last_section.page_w - d.last_section.margin_right;
|
||||
let l = lay(&d);
|
||||
let c = l.caret(&Pos::body(0, 201)).unwrap();
|
||||
assert!(c.x <= right + 0.5, "{case}: caret after the spaces at {} past the margin at {right}", c.x);
|
||||
for (end, mark) in [(Pos::body(0, len), 0.0), (Pos::body(1, 0), crate::para::PARA_MARK_WIDTH)] {
|
||||
let rects = l.selection_rects(&d, &Pos::body(0, 0), &end, 0);
|
||||
assert!(rects.iter().any(|(_, r)| r.right() >= right - 0.5), "{case} to {end:?}: the highlight reaches the margin: {rects:?}");
|
||||
for (_, r) in &rects {
|
||||
assert!(r.right() <= right + mark + 0.5, "{case} to {end:?}: highlight {r:?} past the margin at {right}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The grammar underline over a run of spaces hanging past the right margin ("Extra space") stops
|
||||
/// at the margin with the caret (#6434), whatever follows the spaces.
|
||||
#[test]
|
||||
fn proofing_marks_over_hanging_spaces_stop_at_the_margin() {
|
||||
crate::test_fonts();
|
||||
for (case, p) in hanging_space_paragraphs() {
|
||||
let mut d = Document::new();
|
||||
d.body = vec![wordcraft_doc::para_block(p)];
|
||||
let right = d.last_section.page_w - d.last_section.margin_right;
|
||||
let l = layout(&d, &mut LayoutCache::new(), &LayoutOptions { proofing: true, ..Default::default() });
|
||||
let issues = l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para.issues.clone()) } else { None });
|
||||
assert!(issues.as_ref().is_some_and(|v| v.contains(&(1, 201, true))), "{case}: the spaces are a grammar issue: {issues:?}");
|
||||
let items = display::page_display(&d, &l.pages[0], &display::DisplayOptions::default());
|
||||
let underlines: Vec<(f32, f32)> = items
|
||||
.iter()
|
||||
.filter_map(|i| match i {
|
||||
display::Draw::Line { x0, x1, stroke: display::Stroke::Double, .. } => Some((*x0, *x1)),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert!(underlines.iter().any(|&(_, x1)| x1 >= right - 0.5), "{case}: the underline reaches the margin: {underlines:?}");
|
||||
assert!(underlines.iter().all(|&(_, x1)| x1 <= right + 0.5), "{case}: {underlines:?} past the margin at {right}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tall_first_page_header_pushes_body_down() {
|
||||
crate::test_fonts();
|
||||
@@ -14632,6 +14721,35 @@ fn a_paragraph_left_out_whole_takes_no_room() {
|
||||
assert!((three_top(&d, &plain, 2) - without).abs() < 0.01);
|
||||
}
|
||||
|
||||
/// #5534: a picture floating beside or in front of the text is drawn over the paragraphs after its
|
||||
/// anchor, their shading included, as Word draws it. It was drawn with its anchor, and each shaded
|
||||
/// paragraph below painted a white band across it: the picture showed in strips. One behind the
|
||||
/// text stays under the shading.
|
||||
#[test]
|
||||
fn a_floating_object_is_drawn_over_the_shading_of_the_paragraphs_below_it() {
|
||||
use wordcraft_doc::para::{Anchor, Float, Wrap};
|
||||
crate::test_fonts();
|
||||
for (wrap, over) in [(Wrap::Square, true), (Wrap::InFrontOfText, true), (Wrap::BehindText, false)] {
|
||||
let mut d = Document::from_text("Anchor\n\n\n\n\n\nAfter");
|
||||
d.format_paragraphs(&Pos::body(0, 0), &Pos::body(6, 0), &|p| p.shading = Some(wordcraft_doc::Rgb(0xFF, 0xFF, 0xFF))).unwrap();
|
||||
let f = Float { wrap, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, x: 100.0, y: 4.0, ..Default::default() };
|
||||
d.insert_object(&Pos::body(0, 0), rect_shape(144.0, 100.0, f), &Default::default()).unwrap();
|
||||
let l = lay(&d);
|
||||
let items = &l.pages[0].items;
|
||||
let (shape, rect) =
|
||||
items.iter().enumerate().find_map(|(k, i)| if let Placed::Shape { rect, .. } = i { Some((k, *rect)) } else { None }).unwrap();
|
||||
let fills: Vec<(usize, Rect)> =
|
||||
items.iter().enumerate().filter_map(|(k, i)| if let Placed::Fill { rect, .. } = i { Some((k, *rect)) } else { None }).collect();
|
||||
let covering: Vec<usize> = fills.iter().filter(|(_, r)| r.y > rect.y && r.y < rect.bottom()).map(|(k, _)| *k).collect();
|
||||
assert!(covering.len() >= 3, "{wrap:?}: the shaded paragraphs below reach across the picture: {fills:?} {rect:?}");
|
||||
if over {
|
||||
assert!(covering.iter().all(|k| *k < shape), "{wrap:?}: shading drawn over the picture: fills {covering:?}, picture {shape}");
|
||||
} else {
|
||||
assert!(covering.iter().all(|k| *k > shape), "{wrap:?}: the picture behind the text is under the shading");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Gap #5 review: a paragraph left out whole draws no shading and no borders (they would be
|
||||
/// lines across the page at its zero height).
|
||||
#[test]
|
||||
@@ -17799,3 +17917,66 @@ fn header_text_covers_the_whole_band_of_centred_and_right_lines() {
|
||||
assert!(hit(x + left - 60.0), "{align:?}: beyond 40pt left of the band the picture is hit");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reading_layout_keeps_a_negatively_indented_table_in_the_column() {
|
||||
crate::test_fonts();
|
||||
// #8020: a table indented left of the margin ran out of the column's start edge (right edge when mirrored).
|
||||
for (rtl, width, indent, align) in [
|
||||
(false, 300.0, -36.0, None),
|
||||
(true, 300.0, -36.0, None),
|
||||
(true, 400.0, -36.0, None),
|
||||
(false, 400.0, -36.0, None),
|
||||
(false, 300.0, -36.0, Some(Align::Center)),
|
||||
] {
|
||||
let mut d = Document::from_text("Before.");
|
||||
let mut t = Table::new(2, 4, width);
|
||||
t.props.indent = Some(indent);
|
||||
t.props.bidi_visual = rtl;
|
||||
t.props.align = align;
|
||||
d.insert_block(StoryRef::Body, &Path::top(1), wordcraft_doc::Block::Table(t)).unwrap();
|
||||
let opts = LayoutOptions { view: ViewMode::Read, web_width: 360.0, read_height: 600.0, ..Default::default() };
|
||||
let l = layout(&d, &mut LayoutCache::new(), &opts);
|
||||
let p = &l.pages[0];
|
||||
let cells: Vec<_> = p.items.iter().filter_map(|i| if let Placed::Cell { rect, .. } = i { Some(*rect) } else { None }).collect();
|
||||
let (left, right) = cells.iter().fold((f32::MAX, 0.0f32), |(l, r), c| (l.min(c.x), r.max(c.x + c.w)));
|
||||
assert!(right > left, "cells placed");
|
||||
// A table wider than the column keeps its start edge there; one that fits is inside at both edges.
|
||||
if !rtl || width <= 300.0 {
|
||||
assert!(left >= p.body.x - 0.5, "rtl {rtl} width {width}: left {left} vs column {}", p.body.x);
|
||||
}
|
||||
if rtl || width <= 300.0 {
|
||||
assert!(right <= p.body.x + p.body.w + 0.5, "rtl {rtl} width {width}: right {right} vs column {}", p.body.x + p.body.w);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn many_list_definitions_keep_the_list_numbering_in_order() {
|
||||
use wordcraft_doc::numbering::{AbstractNum, Level, Num};
|
||||
use wordcraft_doc::props::NumRef;
|
||||
|
||||
let mut doc = Document::from_text(&(0..512).map(|i| format!("Item {i}")).collect::<Vec<_>>().join("\n"));
|
||||
let numbering = Arc::make_mut(&mut doc.numbering);
|
||||
numbering.abstracts = (0..12_000).map(|id| AbstractNum { id, levels: vec![Level::default()], ..Default::default() }).collect();
|
||||
numbering.nums = (1..=12_000).map(|id| Num { id, abstract_id: id - 1, ..Default::default() }).collect();
|
||||
for block in &mut doc.body {
|
||||
let Block::Para(p) = Arc::make_mut(block) else { panic!("paragraph fixture") };
|
||||
p.props.numbering = Some(NumRef { num: 12_000, level: 0 });
|
||||
p.props.space_before = Some(0.0);
|
||||
p.props.space_after = Some(0.0);
|
||||
}
|
||||
let layout = lay(&doc);
|
||||
let labels: Vec<_> = layout
|
||||
.pages
|
||||
.iter()
|
||||
.flat_map(|page| &page.items)
|
||||
.filter_map(|item| match item {
|
||||
Placed::Lines { story: StoryRef::Body, para, .. } => para.label.as_ref().map(|label| label.text.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(labels.len(), 512);
|
||||
assert_eq!(labels.first().copied(), Some("1."));
|
||||
assert_eq!(labels.last().copied(), Some("512."));
|
||||
}
|
||||
|
||||
@@ -104,6 +104,7 @@ fn write_attempt(doc: &Document, lay: &DocLayout, opts: &PdfOptions, pages: &[us
|
||||
vectors: HashMap::new(),
|
||||
tags: Vec::new(),
|
||||
tag_index: HashMap::new(),
|
||||
at: (0, 0),
|
||||
links: Vec::new(),
|
||||
bookmarks: std::cell::OnceCell::new(),
|
||||
};
|
||||
|
||||
@@ -35,6 +35,8 @@ pub(crate) struct Exporter<'a> {
|
||||
pub(crate) vectors: HashMap<String, Option<Arc<Vector>>>,
|
||||
pub(crate) tags: Vec<TagEntry>,
|
||||
pub(crate) tag_index: HashMap<(StoryRef, DocPath), usize>,
|
||||
/// Where the item being drawn is read ([`TagEntry::at`]).
|
||||
pub(crate) at: (usize, usize),
|
||||
/// Link rectangles on the current page: (x0, y0, x1, y1, target).
|
||||
pub(crate) links: Vec<(f32, f32, f32, f32, String)>,
|
||||
/// Bookmark positions by name (the first of a name wins), gathered once: looking each internal
|
||||
@@ -145,7 +147,7 @@ impl Exporter<'_> {
|
||||
s.end_tagged();
|
||||
let alt = alt.map(str::to_string).filter(|a| !a.is_empty()).or_else(|| Some("picture".to_string()));
|
||||
let g = TagGroup::with_children(Tag::Figure(alt), vec![Node::Leaf(id)]);
|
||||
self.tags.push(TagEntry { kind: Tag::Div.into(), children: vec![Node::Group(g)] });
|
||||
self.tags.push(TagEntry { kind: Tag::Div.into(), children: vec![Node::Group(g)], at: self.at });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -222,6 +224,7 @@ impl Exporter<'_> {
|
||||
|
||||
/// Draws the content of a single page (background, watermark, headers, footers, body items, and comments) onto the surface.
|
||||
pub(crate) fn page(&mut self, s: &mut Surface, page: &Page, w: f32, h: f32) {
|
||||
self.at = (self.at.0.saturating_add(1), 0);
|
||||
if let Some(c) = self.doc.settings.page_color
|
||||
&& let Some(p) = rect_path(&Rect::new(0.0, 0.0, w, h))
|
||||
{
|
||||
@@ -252,7 +255,8 @@ impl Exporter<'_> {
|
||||
}
|
||||
});
|
||||
}
|
||||
for it in &page.items {
|
||||
for (i, it) in page.items.iter().enumerate() {
|
||||
self.at.1 = page.reading.get(i).copied().unwrap_or(i);
|
||||
let draws = shown.draws(it, &dopts);
|
||||
match it {
|
||||
Placed::Lines { story, path, para, .. } => {
|
||||
@@ -328,7 +332,7 @@ impl Exporter<'_> {
|
||||
}
|
||||
_ => Tag::P.into(),
|
||||
};
|
||||
self.tags.push(TagEntry { kind, children: Vec::new() });
|
||||
self.tags.push(TagEntry { kind, children: Vec::new(), at: self.at });
|
||||
let i = self.tags.len() - 1;
|
||||
self.tag_index.insert((story, path.clone()), i);
|
||||
i
|
||||
@@ -336,7 +340,12 @@ impl Exporter<'_> {
|
||||
|
||||
pub(crate) fn tag_tree(&mut self) -> TagTree {
|
||||
let mut tree = TagTree::new().with_lang(self.doc.styles.default_chr.lang.clone());
|
||||
for e in std::mem::take(&mut self.tags) {
|
||||
// In reading order: a floating object drawn over the text after it is read after its
|
||||
// anchor (#5534). The sort is stable, so what is read at one place keeps its order.
|
||||
let mut tags = std::mem::take(&mut self.tags);
|
||||
tags.sort_by_key(|e| e.at);
|
||||
self.tag_index.clear();
|
||||
for e in tags {
|
||||
if e.children.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -32,10 +32,13 @@ pub(crate) fn figure_alt(alt: &str, kind: Option<GraphicKind>) -> &str {
|
||||
}
|
||||
}
|
||||
|
||||
/// A structure element being collected (one per paragraph, in reading order).
|
||||
/// A structure element being collected (one per paragraph or figure).
|
||||
pub(crate) struct TagEntry {
|
||||
pub(crate) kind: TagKind,
|
||||
pub(crate) children: Vec<Node>,
|
||||
/// Where it is first read: the page (in the order pages are drawn) and the place there of
|
||||
/// the item it came from (`Page::reading`). The tree is in this order, not the drawing order.
|
||||
pub(crate) at: (usize, usize),
|
||||
}
|
||||
|
||||
/// What the content being drawn is, for tagging.
|
||||
|
||||
@@ -1350,6 +1350,104 @@ fn decorative_pictures_are_artifacts_not_figures() {
|
||||
}
|
||||
}
|
||||
|
||||
/// #5534 review: a floating picture or text box in front of the text is drawn after the shaded
|
||||
/// paragraph below its anchor, so the shading doesn't cover it, but a tagged PDF still reads it
|
||||
/// (the picture's Figure, the box's paragraph) right after its anchor paragraph, not after the
|
||||
/// rest of the page.
|
||||
#[test]
|
||||
fn a_floating_object_is_read_after_its_anchor_though_drawn_over_the_text_below() {
|
||||
use hayro_syntax::object::{Dict, Name, Object};
|
||||
use wordcraft_doc::para::{Anchor, Float, ShapeKind, Wrap};
|
||||
// The marked content in a structure element: its ids number the content in drawing order.
|
||||
fn marked(o: Object<'_>, out: &mut Vec<i64>) {
|
||||
match o {
|
||||
Object::Number(n) => out.push(n.as_i64()),
|
||||
Object::Array(a) => a.iter::<Object>().for_each(|o| marked(o, out)),
|
||||
Object::Dict(d) => match (d.get::<Object>(b"MCID"), d.get::<Object>(b"K")) {
|
||||
(Some(id), _) | (None, Some(id)) => marked(id, out),
|
||||
(None, None) => {}
|
||||
},
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let shaded = |text: &str| {
|
||||
let mut p = Paragraph::with_text(text, CharProps::default());
|
||||
p.props.shading = Some(wordcraft_doc::Rgb(0xEE, 0xEE, 0xEE));
|
||||
p
|
||||
};
|
||||
let float = Float { wrap: Wrap::InFrontOfText, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, x: 100.0, y: 4.0, ..Default::default() };
|
||||
for (name, text_box, expected) in [("picture", false, ["P", "Div", "P"]), ("text box", true, ["P", "P", "P"])] {
|
||||
let mut d = Document::new();
|
||||
let object = if text_box {
|
||||
let story = d.add_part(wordcraft_doc::PartKind::TextBox, vec![para_block(Paragraph::with_text("Inside the box", CharProps::default()))]);
|
||||
InlineObject::Shape {
|
||||
kind: ShapeKind::TextBox,
|
||||
w: 120.0,
|
||||
h: 60.0,
|
||||
fill: None,
|
||||
stroke: None,
|
||||
stroke_width: 0.0,
|
||||
float: float.clone(),
|
||||
story: Some(story),
|
||||
freeform: None,
|
||||
effects: Default::default(),
|
||||
extra: Default::default(),
|
||||
}
|
||||
} else {
|
||||
let media = d.add_media(red_right_half_emf(), "emf");
|
||||
InlineObject::Image {
|
||||
media,
|
||||
w: 70.0,
|
||||
h: 70.0,
|
||||
alt: "A red square".into(),
|
||||
float: float.clone(),
|
||||
crop: [0.0; 4],
|
||||
fx: Default::default(),
|
||||
ole: None,
|
||||
}
|
||||
};
|
||||
let mut first = shaded("Anchor");
|
||||
first.insert_object(0, object, &CharProps::default()).unwrap();
|
||||
d.body = vec![para_block(first), para_block(shaded("After"))];
|
||||
let bytes = export(&d, &PdfOptions { compress: false, tagged: true, ..Default::default() }).unwrap();
|
||||
let pdf = hayro_syntax::Pdf::new(bytes).unwrap();
|
||||
let root = pdf.xref().get::<Dict>(pdf.xref().root_id()).unwrap().get::<Dict>(b"StructTreeRoot").unwrap();
|
||||
let mut tops: Vec<Dict> = match root.get::<Object>(b"K") {
|
||||
Some(Object::Array(a)) => a.iter::<Dict>().collect(),
|
||||
Some(Object::Dict(d)) => vec![d],
|
||||
_ => Vec::new(),
|
||||
};
|
||||
// A document element holding them all is looked through.
|
||||
while let [only] = tops.as_slice()
|
||||
&& only.get::<Name>(b"S").is_some_and(|s| s.as_str() == "Document")
|
||||
{
|
||||
tops = match only.get::<Object>(b"K") {
|
||||
Some(Object::Array(a)) => a.iter::<Dict>().collect(),
|
||||
Some(Object::Dict(d)) => vec![d],
|
||||
_ => Vec::new(),
|
||||
};
|
||||
}
|
||||
let read: Vec<(String, Vec<i64>)> = tops
|
||||
.iter()
|
||||
.map(|e| {
|
||||
let mut ids = Vec::new();
|
||||
if let Some(k) = e.get::<Object>(b"K") {
|
||||
marked(k, &mut ids);
|
||||
}
|
||||
(e.get::<Name>(b"S").map(|s| s.as_str().to_string()).unwrap_or_default(), ids)
|
||||
})
|
||||
.collect();
|
||||
let names: Vec<&str> = read.iter().map(|(s, _)| s.as_str()).collect();
|
||||
assert_eq!(names, expected, "{name}: three elements: {read:?}");
|
||||
// The second element read is the object's: it is drawn after the third, the paragraph below.
|
||||
let (object, after) = (&read[1].1, &read[2].1);
|
||||
assert!(
|
||||
!object.is_empty() && !after.is_empty() && object.iter().min() > after.iter().max(),
|
||||
"{name}: read after its anchor paragraph, drawn after the paragraph below it: {read:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A row of exact height cuts its cell's lines (one clip around them): text and a picture in
|
||||
/// it are tagged as they are in a row that fits, the text as the paragraph's, the picture as a
|
||||
/// Figure with its alt text.
|
||||
@@ -1845,6 +1943,7 @@ fn bookmark_destination_is_the_page_of_its_start() {
|
||||
vectors: HashMap::new(),
|
||||
tags: Vec::new(),
|
||||
tag_index: HashMap::new(),
|
||||
at: (0, 0),
|
||||
links: Vec::new(),
|
||||
bookmarks: std::cell::OnceCell::new(),
|
||||
};
|
||||
|
||||
@@ -16,7 +16,7 @@ craft = { workspace = true, features = [
|
||||
"color", "color-ui", "control", "draw", "font-manager", "gpu", "menu", "pages", "print", "review", "table", "text",
|
||||
"text-find", "web-api", "web-host", "window",
|
||||
] }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541" }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21" }
|
||||
wordcraft-geom = { workspace = true, features = ["image"] }
|
||||
wordcraft-doc = { workspace = true }
|
||||
wordcraft-fonts = { workspace = true }
|
||||
@@ -76,7 +76,7 @@ craft-ui-test-kit = { workspace = true }
|
||||
craft = { workspace = true, features = ["ui-testing"] }
|
||||
|
||||
[build-dependencies]
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", features = ["subset"] }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "7097741460d683b4ddf1ba78026e7759f2d5ee21", 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">
|
||||
<rect x="4" y="3" width="12" height="5" rx="1" fill="#F2C811"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 157 B |
@@ -1,5 +1,4 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" width="20" height="20">
|
||||
<rect x="4" y="3" width="12" height="5" rx="1" fill="#F2C811" class="fixed"/>
|
||||
<rect x="4" y="3" width="12" height="5" rx="1" fill="none" stroke="currentColor" stroke-width="1.25"/>
|
||||
<path d="M16 5.5 L17.5 5.5 L17.5 10 L10 10 L10 12" fill="none" stroke="currentColor" stroke-width="1.25"/>
|
||||
<rect x="8.8" y="12" width="2.4" height="6" rx="1" fill="currentColor"/>
|
||||
|
||||
|
Before Width: | Height: | Size: 460 B After Width: | Height: | Size: 380 B |
@@ -107,6 +107,7 @@ impl WordApp {
|
||||
command_states: Default::default(),
|
||||
command_states_cache: None,
|
||||
keytip_cache: None,
|
||||
search_cache: None,
|
||||
fonts_frames: 0,
|
||||
clipboard_published: false,
|
||||
printing: Default::default(),
|
||||
|
||||
@@ -147,6 +147,12 @@ const LINKED_EDIT: [craft::ui::runtime::commands::EditCommands; 5] = {
|
||||
[Cut, Copy, Paste, Undo, Redo]
|
||||
};
|
||||
|
||||
/// The English parts of a registry `location` (`Home › Font`, split as `i18n::location` does); `None` for no place.
|
||||
pub(crate) fn location_path(location: &str) -> Option<Vec<&str>> {
|
||||
let path: Vec<&str> = location.split(" › ").filter(|part| !part.is_empty()).collect();
|
||||
(!path.is_empty()).then_some(path)
|
||||
}
|
||||
|
||||
impl WordApp {
|
||||
/// The app's commands as the keymap knows them: every engine command with its default
|
||||
/// chords, then the interface commands. The interface commands come last because a tie in the
|
||||
@@ -183,6 +189,11 @@ impl WordApp {
|
||||
// warned about), so their chords go in as the set's replaced defaults (the `LINKED_EDIT` fold below).
|
||||
for spec in registry.all().iter().filter(|spec| seen.insert(spec.id) && !LINKED_EDIT.iter().any(|c| c.id() == spec.id)) {
|
||||
let mut def = CommandDef::new(CommandRef::new(spec.id), tl!(spec.label), Scope::app());
|
||||
// Its ribbon place is its menu path, in English: Customize Keyboard files it under the tab by name,
|
||||
// and the framework translates each segment where it shows it.
|
||||
if let Some(path) = location_path(spec.location) {
|
||||
def = def.with_path(path.into_iter().map(str::to_owned).collect());
|
||||
}
|
||||
for binding in default_bindings(spec.shortcut) {
|
||||
def = def.with_default(binding);
|
||||
}
|
||||
|
||||
@@ -684,7 +684,7 @@ impl WordApp {
|
||||
}
|
||||
None => {
|
||||
return Some(Err(format!(
|
||||
"`percent` must be \"auto\" or a number from {} to {}",
|
||||
"`percent` must be \"auto\" or a finite number (clamped between {} and {})",
|
||||
theme::InterfaceSize::MIN,
|
||||
theme::InterfaceSize::MAX
|
||||
)));
|
||||
|
||||
@@ -87,26 +87,34 @@ impl WordApp {
|
||||
.screen_mode(Bind::given(mode))
|
||||
.dropped(Bind::given(dropped))
|
||||
.window_title(self.window_title())
|
||||
.page(self.ui.backstage, crate::backstage::scope(), crate::backstage::show)
|
||||
.title_bar(chrome::title_bar::show)
|
||||
.top(Slot::new("screenBar").screen_bar(), chrome::screen_bar::show)
|
||||
.page(self.ui.backstage, crate::backstage::scope(), |_| None, crate::backstage::show)
|
||||
.title_bar(|_| None, chrome::title_bar::show)
|
||||
.top(Slot::new("screenBar").screen_bar(), |_| None, chrome::screen_bar::show)
|
||||
// The ribbon is a tab strip over a group row: its slots are as tall as it is and stack it. A slot of the
|
||||
// default size is one options bar high and lays its content in one line, which put the groups beside the
|
||||
// tabs and collapsed every one of them.
|
||||
.top(Slot::new("ribbonDrop").drops().size(SlotSize::Content), |ui, _cx, app: &mut WordApp| {
|
||||
if !stale(app) {
|
||||
*ribbon_out.borrow_mut() = Some(ribbon::show(app, ui));
|
||||
}
|
||||
})
|
||||
.top(Slot::new("ribbon").size(SlotSize::Content), |ui, _cx, app: &mut WordApp| {
|
||||
if !stale(app) {
|
||||
*ribbon_out.borrow_mut() = Some(ribbon::show(app, ui));
|
||||
}
|
||||
})
|
||||
.top(
|
||||
Slot::new("ribbonDrop").drops().size(SlotSize::Content),
|
||||
|_| None,
|
||||
|ui, _cx, app: &mut WordApp| {
|
||||
if !stale(app) {
|
||||
*ribbon_out.borrow_mut() = Some(ribbon::show(app, ui));
|
||||
}
|
||||
},
|
||||
)
|
||||
.top(
|
||||
Slot::new("ribbon").size(SlotSize::Content),
|
||||
|_| None,
|
||||
|ui, _cx, app: &mut WordApp| {
|
||||
if !stale(app) {
|
||||
*ribbon_out.borrow_mut() = Some(ribbon::show(app, ui));
|
||||
}
|
||||
},
|
||||
)
|
||||
// As tall as the bar: a failure's line under the message puts Install below the first line, and a slot of
|
||||
// the default size (one options bar high) clips it, so a press on it reached nothing.
|
||||
.top(Slot::new("languagePack").size(SlotSize::Content).visible(language_packs::bar_offer(self)), language_packs::pack_bar)
|
||||
.status(true, chrome::status_bar::show)
|
||||
.top(Slot::new("languagePack").size(SlotSize::Content).visible(language_packs::bar_offer(self)), |_| None, language_packs::pack_bar)
|
||||
.status(true, |_| None, chrome::status_bar::show)
|
||||
.body(|ui, _cx, app: &mut WordApp| {
|
||||
if !app.has_document() || stale(app) {
|
||||
return;
|
||||
|
||||
@@ -250,11 +250,21 @@ fn side_menu(ui: &mut Ui, band: f32, current: &str, has_document: bool, show_dis
|
||||
.least_width(LeastWidth::SideMenu)
|
||||
.surface(SurfaceKind::Brand)
|
||||
.label(label("File"))
|
||||
.gap(Gap::None)
|
||||
// v0.19.1's row pitch (~42 pt against the 38 pt rows): the theme's tight gap between the page rows.
|
||||
.gap(Gap::Tight)
|
||||
.scroll(Scroll::vertical())
|
||||
.header(move |ui, _| {
|
||||
ui.add_space(band);
|
||||
let _ = IconButton::command(IconSpec::svg(IconId::new("chevronLeft")), BackstagePageCommand::Back).show(ui);
|
||||
// The side menu place, so the arrow reads in the rail's white ink, not a panel button's dark ink (#7707).
|
||||
with_env(
|
||||
ui,
|
||||
|overrides| {
|
||||
overrides.values.set(ControlPlace::SideMenu);
|
||||
},
|
||||
|ui| {
|
||||
let _ = IconButton::command(IconSpec::svg(IconId::new("chevronLeft")), BackstagePageCommand::Back).show(ui);
|
||||
},
|
||||
);
|
||||
})
|
||||
// The community link above About, both at the reading start, as production's bottom links: rows of the side
|
||||
// menu place too, so they read in the rail's white ink over the brand colour, not a panel button's dark ink.
|
||||
|
||||
@@ -748,7 +748,7 @@ fn about_stays_at_the_bottom_of_a_side_menu_that_fits() {
|
||||
}
|
||||
|
||||
/// The side menu is production's rail: 200 pt wide (five rail columns, `LeastWidth::SideMenu`), its page rows about
|
||||
/// 38 pt tall one after another. The footer's links are rows of the same place, so they read in the rail's white ink;
|
||||
/// 38 pt tall a tight gap apart. The footer's links are rows of the same place, so they read in the rail's white ink;
|
||||
/// production's were a little shorter (32 pt), which the side menu place has no row for.
|
||||
#[test]
|
||||
fn the_side_menu_rows_are_production_s_rail_rows() {
|
||||
@@ -758,7 +758,9 @@ fn the_side_menu_rows_are_production_s_rail_rows() {
|
||||
// The least width holds in the row beside the page: before, the row gave the menu only its widest name (~123 pt).
|
||||
assert!((190.0..=260.0).contains(&info.width()), "the menu is production's 200 pt rail: {info:?}");
|
||||
assert!((34.0..=44.0).contains(&info.height()), "a page row is a rail row: {info:?}");
|
||||
assert!((recover.min.y - info.max.y).abs() < 1.0, "the rows follow each other without a gap: {info:?} {recover:?}");
|
||||
// v0.19.1's pitch was ~42 pt for 38 pt rows: the rows are a little apart, not touching and not far apart.
|
||||
let gap = recover.min.y - info.max.y;
|
||||
assert!((1.0..=8.0).contains(&gap), "the rows have a small gap between them: {info:?} {recover:?}");
|
||||
assert!(about.height() <= info.height() + 1.0, "the footer link is no taller than a page row: {info:?} {about:?}");
|
||||
}
|
||||
|
||||
|
||||
@@ -716,8 +716,17 @@ fn show_reading(app: &mut WordApp, ui: &mut Ui, layout: &Arc<DocLayout>, full: R
|
||||
let mut state = std::mem::take(&mut app.canvas.reading);
|
||||
let source = source::WordPages::new(app, layout, false, None);
|
||||
let out = ReadingView::new(tl!("Document"), &source, &mut state, paper).zoom(zoom).show_at(ui, columns);
|
||||
// The page-turn row sits at the bottom right, as in v0.19.1 (the far end, so the bottom left in a right-to-left UI),
|
||||
// the page view's side margin in from the edge.
|
||||
let margin = Env::of(ui).tokens.space.inset.page_side;
|
||||
let footer = footer.shrink2(egui::vec2(margin, 0.0));
|
||||
let far = if crate::i18n::current().rtl() {
|
||||
egui::Layout::left_to_right(egui::Align::Center)
|
||||
} else {
|
||||
egui::Layout::right_to_left(egui::Align::Center)
|
||||
};
|
||||
let nav = ui
|
||||
.scope_builder(egui::UiBuilder::new().max_rect(footer), |ui| {
|
||||
.scope_builder(egui::UiBuilder::new().max_rect(footer).layout(far), |ui| {
|
||||
ReadingNav::new(&mut state, layout.pages.len()).position(true).action(tl!("Edit Document")).show(ui)
|
||||
})
|
||||
.inner;
|
||||
|
||||
@@ -146,6 +146,9 @@ pub(crate) fn paint_caret(app: &mut WordApp, ui: &mut Ui, pass: &ToolPass, body:
|
||||
let ctx = ui.ctx().clone();
|
||||
let focused = app.canvas.focused(&ctx);
|
||||
crate::dialogs_smart_art::end_typing_run(app, focused);
|
||||
// The page keeps the keyboard focus while another window is active, but the caret shows and blinks only in the
|
||||
// active window: a window in the background asks for no frames to blink it (#7674).
|
||||
let active = focused && ctx.input(|input| input.focused);
|
||||
let doc = app.session.layout();
|
||||
let Some(pl) = place(app, &doc, body.pages) else { return };
|
||||
|
||||
@@ -184,7 +187,7 @@ pub(crate) fn paint_caret(app: &mut WordApp, ui: &mut Ui, pass: &ToolPass, body:
|
||||
};
|
||||
let ink = |app: &mut WordApp| caret_color_at(app, &doc, pl.page, pl.probe.0, pl.probe.1, zoom_key, dim_body);
|
||||
|
||||
let shown = pl.collapsed && focused;
|
||||
let shown = pl.collapsed && active;
|
||||
let mut bars: Vec<(Bar, Color32)> = Vec::new();
|
||||
let mut composition = None;
|
||||
if focused && !pl.in_equation && !app.canvas.ime_preedit.is_empty() {
|
||||
@@ -211,7 +214,7 @@ pub(crate) fn paint_caret(app: &mut WordApp, ui: &mut Ui, pass: &ToolPass, body:
|
||||
ctx.request_repaint();
|
||||
} else if shown && blink_fading(since_ms / 1000.0, app.canvas.glide.secs()) {
|
||||
ctx.request_repaint_after(std::time::Duration::from_millis(16));
|
||||
} else if focused {
|
||||
} else if active {
|
||||
ctx.request_repaint_after(std::time::Duration::from_millis(530 - (since_ms as u64 % 530)));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -56,7 +56,7 @@ impl Component for ReadingProbe {
|
||||
|
||||
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> egui::Vec2 {
|
||||
let measure = ReadingMeasure::of(TypeRole::Body, |run| cx.layout(run));
|
||||
self.measured = Some(ReadingMetrics::new(cx.style.column_gap, cx.style.nav_bar, measure));
|
||||
self.measured = Some(metrics(cx.style.column_gap, cx.style.nav_bar, measure));
|
||||
egui::Vec2::ZERO
|
||||
}
|
||||
|
||||
@@ -69,6 +69,19 @@ impl Component for ReadingProbe {
|
||||
}
|
||||
}
|
||||
|
||||
/// Column widths Read Mode has always used (about one column per 295 screen points, none under 192), as v0.19.1 laid out 4
|
||||
/// columns at 1440 screen points. craft's body-text measure (66 characters) gives 2 there, so only the gaps come from it.
|
||||
const COLUMN_TARGET: f32 = 295.0;
|
||||
const COLUMN_MIN: f32 = 192.0;
|
||||
|
||||
fn metrics(column_gap: f32, nav_bar: f32, measure: ReadingMeasure) -> ReadingMetrics {
|
||||
let mut m = ReadingMetrics::new(column_gap, nav_bar, measure);
|
||||
// lean: fixed px, not the text size; follow the body text again if Read Mode should scale with it.
|
||||
m.column_target = COLUMN_TARGET;
|
||||
m.column_min = COLUMN_MIN;
|
||||
m
|
||||
}
|
||||
|
||||
/// The reading metrics under the current theme, or `None` when the probe did not measure this pass.
|
||||
pub(super) fn read(ui: &mut Ui) -> Option<ReadingMetrics> {
|
||||
ReadingProbe { common: Common::new(), measured: None }.label("Reading metrics").show(ui).metrics
|
||||
|
||||
@@ -253,6 +253,48 @@ fn drawing_over_the_pages_follows_the_read_mode_page_color() {
|
||||
assert_eq!(blank(&a), Rgb::WHITE, "the paper under the raster, not the page color");
|
||||
}
|
||||
|
||||
/// #8019: at 1440 x 900 Read Mode lays out several narrow columns (v0.19.1: 4), not the two the body
|
||||
/// text's measure gave after the port.
|
||||
#[test]
|
||||
fn read_mode_lays_out_several_columns_at_1440() {
|
||||
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::from_text("Hello WordCraft")), Default::default());
|
||||
a.run("view.readMode", json!({})).unwrap();
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|
||||
|ui, app: &mut WordApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
a,
|
||||
);
|
||||
h.run_steps(4);
|
||||
let px = ReadingView::screen_scale(1.0) * h.state().session.view.read_width;
|
||||
assert!(px > 0.0 && 4.0 * px < 1440.0, "columns {px} px wide: four do not fit");
|
||||
}
|
||||
|
||||
/// #8019: the page-turn row (position and Edit Document) sits in the bottom-right quadrant, as in v0.19.1,
|
||||
/// not at the bottom left where craft's row starts.
|
||||
#[test]
|
||||
fn read_mode_pager_is_at_the_bottom_right() {
|
||||
use egui_kittest::kittest::Queryable;
|
||||
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::from_text("Hello WordCraft")), Default::default());
|
||||
a.run("view.readMode", json!({})).unwrap();
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|
||||
|ui, app: &mut WordApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
a,
|
||||
);
|
||||
h.run_steps(4);
|
||||
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440.0, 900.0));
|
||||
for label in ["Edit Document", "1 / 1"] {
|
||||
let r = h.get_all_by_label(label).last().unwrap().rect();
|
||||
assert!(r.center().x > screen.center().x && r.center().y > screen.center().y, "{label} at {r:?}: not bottom right");
|
||||
}
|
||||
}
|
||||
|
||||
/// #299: the caret's colour is worked out only when the caret is drawn: with text selected
|
||||
/// there is no caret, so the page's draw list isn't built for it.
|
||||
#[test]
|
||||
@@ -2442,3 +2484,63 @@ fn hostile_numbers_are_ignored() {
|
||||
assert!(h.state().canvas.view.zoom.is_finite() && h.state().canvas.view.zoom > 0.0);
|
||||
assert!(h.state().canvas.view.offset.0.is_finite() && h.state().canvas.view.offset.1.is_finite());
|
||||
}
|
||||
|
||||
/// A window in the background shows no caret and asks for no frames to blink one (#7674). The page keeps the keyboard
|
||||
/// focus, so the caret blinks again once the window is active again.
|
||||
#[test]
|
||||
fn the_caret_blinks_only_while_the_window_is_active() {
|
||||
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
|
||||
a.run("text.insert", json!({"text": "Some text"})).unwrap();
|
||||
// No glide or fade: the caret's frames are the blink's alone.
|
||||
a.ui.animations = crate::theme::Animations::Off;
|
||||
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,
|
||||
);
|
||||
let ctx = h.ctx.clone();
|
||||
h.state_mut().canvas.focus_page(&ctx);
|
||||
for _ in 0..6 {
|
||||
h.app_frame();
|
||||
}
|
||||
assert!(h.state().canvas.focused(&ctx), "the page has the keyboard focus");
|
||||
let blink = std::time::Duration::from_millis(530);
|
||||
let next_frame =
|
||||
|h: &H| h.output().viewport_output.get(&egui::ViewportId::ROOT).map_or(std::time::Duration::MAX, |viewport| viewport.repaint_delay);
|
||||
assert!(next_frame(&h) <= blink, "an active window asks for a frame within a blink");
|
||||
// The caret is a stroke from its top to its bottom where the layout puts it. The blink runs on the wall clock:
|
||||
// restarted, it is in its on half for the next 530 ms, so a caret the window draws at all is in the frame after.
|
||||
let (top, bottom) = {
|
||||
let app = h.state_mut();
|
||||
let focus = app.session.sel.focus.clone();
|
||||
let c = app.session.layout().caret(&focus).expect("the caret has a place");
|
||||
let mut at = |y| crate::canvas::page_to_screen(app, c.page, c.x, y).expect("the caret's page is on screen");
|
||||
(at(c.top), at(c.top + c.height))
|
||||
};
|
||||
let caret_drawn = |h: &mut H| {
|
||||
h.state_mut().canvas.glide.restart(craft::platform::clock::monotonic_ms());
|
||||
h.app_frame();
|
||||
h.output().shapes.iter().any(|clipped| match &clipped.shape {
|
||||
egui::Shape::Path(path) => path.points.len() == 2 && path.points[0].distance(top) < 1.5 && path.points[1].distance(bottom) < 1.5,
|
||||
_ => false,
|
||||
})
|
||||
};
|
||||
assert!(caret_drawn(&mut h), "an active window draws the caret");
|
||||
|
||||
h.input_mut().focused = false;
|
||||
h.event(egui::Event::WindowFocused(false));
|
||||
for _ in 0..3 {
|
||||
h.app_frame();
|
||||
}
|
||||
assert!(h.state().canvas.focused(&ctx), "the page keeps the keyboard focus");
|
||||
assert!(next_frame(&h) > blink, "a window in the background asks for no frame to blink the caret");
|
||||
assert!(!caret_drawn(&mut h), "a window in the background draws no caret");
|
||||
|
||||
h.input_mut().focused = true;
|
||||
h.event(egui::Event::WindowFocused(true));
|
||||
h.app_frame();
|
||||
assert!(next_frame(&h) <= blink, "active again, the caret blinks again");
|
||||
}
|
||||
|
||||
@@ -9,7 +9,8 @@
|
||||
//! [`GLIDE_SECS`], fast at first and settling ([`ease`]). The time is the same for one
|
||||
//! character and for a whole line.
|
||||
//! - **Another move before it arrives:** it snaps to where it was heading and glides from there.
|
||||
//! - **A click moves the caret:** no glide; it is drawn at its new place.
|
||||
//! - **A click moves the caret:** it glides the same way, so the eye follows it to the new place
|
||||
//! (our choice; Word draws it at once).
|
||||
//! - **A command from a script or the control channel:** no glide, no fade.
|
||||
//! - **The blink is a fade:** each time the caret turns on or off it takes [`GLIDE_SECS`] to get
|
||||
//! there. A move by a key or a click turns it on the same way, from however visible it was, so
|
||||
@@ -214,8 +215,8 @@ impl CaretGlide {
|
||||
// A key or a click turns the caret on, from however visible it was.
|
||||
self.fade = Some(FadeIn { from: was_opacity, started: f.now });
|
||||
self.glide = match heading {
|
||||
// Keys glide, from where the caret was heading (not from where it has got to).
|
||||
Some(from) if by_keys && !by_pointer && same_view => {
|
||||
// Keys and clicks glide, from where the caret was heading (not from where it has got to).
|
||||
Some(from) if same_view => {
|
||||
let seen = f.viewport.expand(OFFSCREEN_SLACK);
|
||||
let on_screen = |b: Bar| seen.intersects(Rect::from_two_pos(b[0], b[1]));
|
||||
(on_screen(from) && on_screen(f.target)).then_some(Glide { from, to: f.target, started: f.now })
|
||||
|
||||
@@ -142,16 +142,18 @@ fn a_new_key_move_sets_off_from_where_the_caret_was_heading() {
|
||||
assert!(!r.glide.is_gliding());
|
||||
}
|
||||
|
||||
/// Word: a click puts the caret where it was clicked, a script's move likewise; only keys glide.
|
||||
/// A click glides like a key; a script's move does not.
|
||||
#[test]
|
||||
fn clicks_and_scripts_do_not_glide() {
|
||||
fn clicks_glide_and_scripts_do_not() {
|
||||
let mut r = Rig::new(bar(100.0, 100.0));
|
||||
r.click_to(bar(400.0, 300.0));
|
||||
let look = r.step(DT);
|
||||
assert_eq!(look.bar, bar(400.0, 300.0));
|
||||
assert!(!r.glide.is_gliding());
|
||||
assert!(r.glide.is_gliding(), "a click glides to its place");
|
||||
assert_ne!(look.bar, bar(400.0, 300.0));
|
||||
assert_eq!(look.opacity, 1.0, "a lit caret stays lit");
|
||||
r.rest(0.2);
|
||||
assert!(!r.glide.is_gliding());
|
||||
assert_eq!(r.step(DT).bar, bar(400.0, 300.0));
|
||||
r.script_to(bar(50.0, 50.0));
|
||||
assert_eq!(r.step(DT), Look { bar: bar(50.0, 50.0), opacity: 1.0, moving: false });
|
||||
// A script's move during a glide ends the glide.
|
||||
@@ -161,12 +163,12 @@ fn clicks_and_scripts_do_not_glide() {
|
||||
assert!(r.glide.is_gliding());
|
||||
r.script_to(bar(20.0, 20.0));
|
||||
assert_eq!(r.step(DT), Look { bar: bar(20.0, 20.0), opacity: 1.0, moving: false });
|
||||
// A click during a glide too.
|
||||
// A click during a glide starts a new glide.
|
||||
r.key_to(bar(250.0, 20.0));
|
||||
r.step(DT);
|
||||
r.click_to(bar(300.0, 300.0));
|
||||
assert_eq!(r.step(DT).bar, bar(300.0, 300.0));
|
||||
assert!(!r.glide.is_gliding());
|
||||
r.step(DT);
|
||||
assert!(r.glide.is_gliding());
|
||||
}
|
||||
|
||||
/// Word: the blink is a fade, and a move turns the caret on from however visible it was.
|
||||
@@ -200,15 +202,15 @@ fn the_blink_fades_and_a_move_turns_the_caret_on() {
|
||||
assert!(seen.windows(2).all(|w| w[1] >= w[0]) && seen[1] > 0.1 && seen[2] > seen[1], "{seen:?}");
|
||||
assert!((seen[3] - 0.5).abs() < 0.02, "half lit half-way: {seen:?}");
|
||||
assert_eq!(r.step(DT).opacity, 1.0);
|
||||
// A click while it is off fades in too, in place.
|
||||
// A click while it is off fades in too, as it glides.
|
||||
r.rest(0.8);
|
||||
assert_eq!(r.glide.opacity(), 0.0);
|
||||
r.click_to(bar(300.0, 200.0));
|
||||
let look = r.step(DT);
|
||||
assert_eq!((look.bar, look.opacity, look.moving), (bar(300.0, 200.0), 0.0, true));
|
||||
let look = r.rest(0.05);
|
||||
assert!(look.opacity > 0.3 && look.opacity < 0.7 && look.bar == bar(300.0, 200.0), "{look:?}");
|
||||
assert_eq!(r.rest(0.1).opacity, 1.0);
|
||||
assert!(look.opacity < 0.2 && look.moving, "{look:?}");
|
||||
r.rest(0.05);
|
||||
assert!(r.glide.opacity() > 0.2, "fading in");
|
||||
assert_eq!(r.rest(0.2).opacity, 1.0);
|
||||
// A script's move while it is off: lit at once.
|
||||
r.rest(0.7);
|
||||
assert_eq!(r.glide.opacity(), 0.0);
|
||||
|
||||
@@ -18,12 +18,18 @@ pub(crate) struct ChromeOpen {
|
||||
pub(crate) undo: bool,
|
||||
/// The actions marked in the open Undo drop-down; back to none whenever the drop-down is closed.
|
||||
pub(crate) undo_mark: craft::ui::list::UndoMark,
|
||||
/// The rows and mark the Undo drop-down had when it closed, drawn through its exit fade: a pick has already
|
||||
/// undone those steps, so the live history would empty the list as it fades (#8141).
|
||||
pub(crate) undo_closing: Option<(Vec<String>, craft::ui::list::UndoMark)>,
|
||||
/// The command search.
|
||||
pub(crate) search: bool,
|
||||
/// How the title bar's controls at the end fit the room the leading controls leave them.
|
||||
pub(crate) title_fit: Fit,
|
||||
/// How the status bar's controls fit the room the page leaves them.
|
||||
pub(crate) status_fit: Fit,
|
||||
/// Cached word count `(document_id, count_key, words)` for [`StatusCount::Words`] so typing
|
||||
/// avoids full-document text extraction and character scans.
|
||||
pub(crate) status_words: Option<(u64, u64, usize)>,
|
||||
}
|
||||
|
||||
/// The steps a bar's group of controls takes in a narrow window, from the fullest to the most compact.
|
||||
@@ -244,6 +250,28 @@ impl WordApp {
|
||||
wordcraft_engine::cmd::font::warns(font, &shown).then_some(shown)
|
||||
}
|
||||
|
||||
/// The count in `unit` for the status bar, computing only word count when `unit` is
|
||||
/// [`StatusCount::Words`] and the full [`StatusCounts`] has not already been cached.
|
||||
pub fn cached_status_count(&mut self, unit: StatusCount) -> usize {
|
||||
let key = self.session.rev().wrapping_mul(2) | u64::from(self.session.prefs.count_notes);
|
||||
if self.status_counts.0 == key {
|
||||
return self.status_counts.1.in_unit(unit);
|
||||
}
|
||||
if unit == StatusCount::Words {
|
||||
let doc_id = self.session.document_id();
|
||||
if let Some((cached_doc, cached_key, words)) = self.chrome.status_words
|
||||
&& cached_doc == doc_id
|
||||
&& cached_key == key
|
||||
{
|
||||
return words;
|
||||
}
|
||||
let words = self.session.word_count();
|
||||
self.chrome.status_words = Some((doc_id, key, words));
|
||||
return words;
|
||||
}
|
||||
self.cached_status_counts().in_unit(unit)
|
||||
}
|
||||
|
||||
/// The document's counts, recomputed only when the document (or the count option) changes:
|
||||
/// words as the status bar and the Word Count dialog count them, and characters with and
|
||||
/// without spaces as the dialog does (#2797).
|
||||
@@ -252,14 +280,10 @@ impl WordApp {
|
||||
let key = self.session.rev().wrapping_mul(2) | u64::from(self.session.prefs.count_notes);
|
||||
if self.status_counts.0 != key {
|
||||
let text = self.session.counted_text();
|
||||
self.status_counts = (
|
||||
key,
|
||||
StatusCounts {
|
||||
words: self.session.word_count(),
|
||||
chars: wordcraft_doc::count_chars(&text),
|
||||
chars_no_spaces: wordcraft_doc::count_chars_no_spaces(&text),
|
||||
},
|
||||
);
|
||||
let words = self.session.word_count();
|
||||
self.chrome.status_words = Some((self.session.document_id(), key, words));
|
||||
self.status_counts =
|
||||
(key, StatusCounts { words, chars: wordcraft_doc::count_chars(&text), chars_no_spaces: wordcraft_doc::count_chars_no_spaces(&text) });
|
||||
}
|
||||
self.status_counts.1
|
||||
}
|
||||
|
||||
@@ -1,18 +1,45 @@
|
||||
//! Command search: a `CommandPalette` in its in-place face, over the registry's commands.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft::behavior::IconId;
|
||||
use craft::keymap::CommandRef;
|
||||
use craft::ui::buttons::IconButton;
|
||||
use craft::ui::contract::{Bind, Props as _, Show as _, TooltipSpec};
|
||||
use craft::ui::menu::search::{HelpEntry, SearchIndex, SearchWords, Synonyms};
|
||||
use craft::ui::patterns::panels::{CommandPalette, PaletteFace};
|
||||
use craft::ui::runtime::env::{Env, Label, WordTemplate};
|
||||
use craft::ui::runtime::env::{Env, EnvView, Label, WordTemplate};
|
||||
use craft::ui::runtime::inspect;
|
||||
use egui::Ui;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::WordApp;
|
||||
|
||||
/// The search's entries and their index, kept between passes. Building the index folds every command's labels, so it
|
||||
/// is built again only when the commands or the interface language change, not in every pass the field shows.
|
||||
pub(crate) struct SearchCache {
|
||||
registry: Arc<wordcraft_engine::Registry>,
|
||||
lang: &'static str,
|
||||
entries: Vec<HelpEntry>,
|
||||
pub(crate) index: Arc<SearchIndex>,
|
||||
}
|
||||
|
||||
impl SearchCache {
|
||||
/// `kept` while it was built from `app`'s registry in the current language, else the entries and index built
|
||||
/// again, their labels resolved and folded as `view` reads them.
|
||||
fn for_pass(kept: Option<SearchCache>, app: &WordApp, view: &EnvView<'_>) -> SearchCache {
|
||||
let lang = crate::i18n::current().code();
|
||||
match kept {
|
||||
Some(cache) if cache.lang == lang && Arc::ptr_eq(&cache.registry, &app.session.registry) => cache,
|
||||
_ => {
|
||||
let entries = help_entries(app);
|
||||
let index = Arc::new(SearchIndex::new(view, &entries, &Synonyms::of(&view.words::<SearchWords>())));
|
||||
SearchCache { registry: Arc::clone(&app.session.registry), lang, entries, index }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One help entry for each registry command Search offers: its label, with the English label so a search in
|
||||
/// English finds it in any language. Paper Color opens the selector in Options instead of running with no
|
||||
/// value, since Search is an interactive entry point.
|
||||
@@ -25,7 +52,11 @@ pub(crate) fn help_entries(app: &WordApp) -> Vec<HelpEntry> {
|
||||
.map(|c| {
|
||||
let command =
|
||||
if c.id == "view.paperColor" { CommandRef::with_params("file.options", json!({"pane": "general"})) } else { CommandRef::new(c.id) };
|
||||
HelpEntry::new(command, tl!(c.label).to_string()).with_english(c.label.to_string())
|
||||
let entry = HelpEntry::new(command, tl!(c.label).to_string()).with_english(c.label.to_string());
|
||||
match crate::app::command_board::location_path(c.location) {
|
||||
Some(path) => entry.with_path(path.into_iter().map(|part| tl!(part).to_string())),
|
||||
None => entry,
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -49,13 +80,14 @@ pub(crate) fn is_open(app: &WordApp) -> bool {
|
||||
/// rect it took. `compact` (a narrow window, #5886) shows the magnifier alone, and the search opens as a box over
|
||||
/// the window, since the bar has no room for the field.
|
||||
pub(super) fn show(app: &mut WordApp, ui: &mut Ui, compact: bool) -> egui::Rect {
|
||||
// Built in every pass the field runs: the palette opens inside its own `show`, so the entries are there before
|
||||
// it knows. The list lives for the pass only.
|
||||
let entries = help_entries(app);
|
||||
// There in every pass the field runs: the palette opens inside its own `show`, so the entries are there before
|
||||
// it knows. They and their index are kept between passes ([`SearchCache`]).
|
||||
let kept = app.search_cache.take();
|
||||
let suggested: Vec<CommandRef> = crate::dialogs::SEARCH_SUGGESTIONS.iter().map(|id| CommandRef::new(*id)).collect();
|
||||
let mut open = app.chrome.search;
|
||||
let name = tl!("Search commands and help").to_string();
|
||||
let ((rect, out), _) = inspect::record(ui, crate::keytips::search_region(), |ui| {
|
||||
let commands: &WordApp = app;
|
||||
let ((rect, out, cache), _) = inspect::record(ui, crate::keytips::search_region(), |ui| {
|
||||
let mut rect = None;
|
||||
if compact {
|
||||
let button = IconButton::new(IconId::new("wordcraft.search")).label(name.clone()).tooltip(TooltipSpec::new(name.clone())).show(ui);
|
||||
@@ -66,18 +98,33 @@ pub(super) fn show(app: &mut WordApp, ui: &mut Ui, compact: bool) -> egui::Rect
|
||||
}
|
||||
let env = Env::of(ui);
|
||||
let view = env.view();
|
||||
let index = SearchIndex::new(&view, &entries, &Synonyms::of(&view.words::<SearchWords>()));
|
||||
let out = CommandPalette::new(name.clone(), &entries, &index, Bind::bound(&mut open))
|
||||
let cache = SearchCache::for_pass(kept, commands, &view);
|
||||
let out = CommandPalette::new(name.clone(), &cache.entries, &cache.index, Bind::bound(&mut open))
|
||||
.face(if compact { PaletteFace::Dialog } else { PaletteFace::InPlace })
|
||||
.placeholder(Label::from(name.clone()))
|
||||
.suggested((Label::from(tl!("Suggested").to_string()), suggested))
|
||||
.fallback(WordTemplate::new(tl!("Find “{text}” in the document")))
|
||||
.show(ui);
|
||||
(rect.unwrap_or(out.response.rect), out)
|
||||
(rect.unwrap_or(out.response.rect), out, cache)
|
||||
});
|
||||
app.search_cache = Some(cache);
|
||||
app.chrome.search = open;
|
||||
if let Some(text) = out.fallback {
|
||||
crate::dialogs::find_in_navigation_pane(app, ui.ctx(), &text);
|
||||
}
|
||||
rect
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::{Services, WordApp};
|
||||
|
||||
/// #7983: a search result names the ribbon place of its command.
|
||||
#[test]
|
||||
fn search_entries_show_the_ribbon_location() {
|
||||
let app = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Services::default());
|
||||
let entries = super::help_entries(&app);
|
||||
let bold = entries.iter().find(|e| e.command().id == "format.bold").expect("format.bold is searchable");
|
||||
assert!(!bold.path().is_empty(), "the entry has a path");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -121,13 +121,13 @@ fn readouts(app: &mut WordApp, ui: &mut Ui) -> egui::Rect {
|
||||
/// without spaces, whichever was chosen (#2797). A click opens Word Count; a right click the choice.
|
||||
fn count(app: &mut WordApp, ui: &mut Ui) {
|
||||
let unit = app.ui.status_count;
|
||||
let counts = app.cached_status_counts();
|
||||
let total = app.cached_status_count(unit);
|
||||
// A selected picture/shape/text box isn't a text selection: show the total.
|
||||
let text = if app.session.sel.is_collapsed() || crate::objects::selected(app).is_some() {
|
||||
status_count_text(unit, counts.in_unit(unit), None)
|
||||
status_count_text(unit, total, None)
|
||||
} else {
|
||||
let selected = crate::count_in_unit(&app.session.selected_text(), unit);
|
||||
status_count_text(unit, counts.in_unit(unit), Some(selected))
|
||||
status_count_text(unit, total, Some(selected))
|
||||
};
|
||||
let out = item(ui, text, None);
|
||||
if out.clicked() {
|
||||
|
||||
@@ -249,6 +249,37 @@ fn the_status_bar_totals_are_the_word_count_dialogs_numbers() {
|
||||
assert_eq!(line(StatusCount::CharactersNoSpaces), "6 of 21 characters (no spaces)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cached_status_count_words_matches_full_counts_across_edits() {
|
||||
let mut a = new_app();
|
||||
a.run("text.insert", json!({"text": "one two"})).unwrap();
|
||||
assert_eq!(a.cached_status_count(StatusCount::Words), 2);
|
||||
|
||||
a.run("text.insert", json!({"text": " three four"})).unwrap();
|
||||
assert_eq!(a.cached_status_count(StatusCount::Words), 4);
|
||||
assert_eq!(a.cached_status_count(StatusCount::Words), a.cached_status_counts().words);
|
||||
assert_eq!(a.cached_status_count(StatusCount::Characters), a.cached_status_counts().chars);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn previews_style_gallery_reuses_arc_until_styles_change() {
|
||||
let mut a = new_app();
|
||||
let rev = a.session.rev();
|
||||
let first = a.previews.style_gallery(&a.session.doc, rev);
|
||||
let second = a.previews.style_gallery(&a.session.doc, rev);
|
||||
assert!(std::sync::Arc::ptr_eq(&first, &second), "same rev should reuse cached style gallery Arc");
|
||||
assert!(!first.is_empty());
|
||||
|
||||
a.run("text.insert", json!({"text": "changed"})).unwrap();
|
||||
let typed = a.previews.style_gallery(&a.session.doc, a.session.rev());
|
||||
assert!(std::sync::Arc::ptr_eq(&second, &typed), "text edit with identical style sheet reuses gallery Arc");
|
||||
|
||||
a.run("styles.create", json!({"name": "Stage7TestStyle", "fromSelection": false})).unwrap();
|
||||
let updated = a.previews.style_gallery(&a.session.doc, a.session.rev());
|
||||
assert!(!std::sync::Arc::ptr_eq(&typed, &updated), "changing styles refreshes style gallery");
|
||||
assert!(updated.iter().any(|(_, name)| name == "Stage7TestStyle"));
|
||||
}
|
||||
|
||||
/// The status bar's actions, through its menus by name: the count row sets the unit and is kept between
|
||||
/// runs, Overtype switches back to inserting.
|
||||
#[test]
|
||||
@@ -1126,3 +1157,38 @@ fn status_bar_view_mode_toggles_and_zoom_slider_proportions() {
|
||||
});
|
||||
assert!(has_14pt_knob, "Zoom slider should paint a {glyph_md} pt thumb (ControlSize::Md) matching 14 pt IconButton icons inside {slider:?}");
|
||||
}
|
||||
|
||||
/// The title bar's command search keeps its entries and their index between passes: building the index folds every
|
||||
/// command's labels, and an idle window repaints for its caret (#7674). New commands, or another interface language,
|
||||
/// build it again.
|
||||
#[test]
|
||||
fn the_title_bar_search_keeps_its_index_until_the_commands_or_the_language_change() {
|
||||
struct ResetLang;
|
||||
impl Drop for ResetLang {
|
||||
fn drop(&mut self) {
|
||||
crate::i18n::apply_language(crate::i18n::Lang::EN);
|
||||
}
|
||||
}
|
||||
let _reset = ResetLang;
|
||||
let index = |h: &egui_kittest::Harness<'static, WordApp>| {
|
||||
h.state().search_cache.as_ref().map(|cache| std::sync::Arc::clone(&cache.index)).expect("the title bar's search has its index")
|
||||
};
|
||||
|
||||
let mut h = harness(new_app());
|
||||
let built = index(&h);
|
||||
crate::test_harness::frames(&mut h, 4);
|
||||
assert!(std::sync::Arc::ptr_eq(&built, &index(&h)), "idle passes keep the index");
|
||||
|
||||
let same_commands = wordcraft_engine::Registry::new(h.state().session.registry.all().to_vec());
|
||||
h.state_mut().session.registry = std::sync::Arc::new(same_commands);
|
||||
crate::test_harness::frames(&mut h, 1);
|
||||
let rebuilt = index(&h);
|
||||
assert!(!std::sync::Arc::ptr_eq(&built, &rebuilt), "a new command registry builds it again");
|
||||
|
||||
if crate::i18n::catalogs_embedded() {
|
||||
h.state_mut().run("ui.language", json!({"value": "de"})).unwrap();
|
||||
crate::test_harness::frames(&mut h, 2);
|
||||
assert_eq!(crate::i18n::current().code(), "de");
|
||||
assert!(!std::sync::Arc::ptr_eq(&rebuilt, &index(&h)), "another interface language builds it again");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -163,14 +163,19 @@ const UNDO_ROWS_SHOWN: u16 = 8;
|
||||
fn undo_arrow(app: &mut WordApp, ui: &mut Ui, enabled: bool) -> egui::Rect {
|
||||
// The small filled triangle of the old toolbar.
|
||||
let out = IconButton::new(IconSpec::glyph(&crate::ribbon::common::MENU_ARROW)).label(tl!("Undo History").to_string()).enabled(enabled).show(ui);
|
||||
let labels = undo_list_rows(app);
|
||||
let mut open = app.chrome.undo;
|
||||
if out.response.clicked() {
|
||||
open = !open;
|
||||
}
|
||||
let mut mark = app.chrome.undo_mark;
|
||||
let was_open = app.chrome.undo;
|
||||
// Through the exit fade the list draws what it had when it closed.
|
||||
let closing = if open { None } else { app.chrome.undo_closing.take() };
|
||||
let mut mark = closing.as_ref().map_or(app.chrome.undo_mark, |(_, m)| *m);
|
||||
let mut picked = None;
|
||||
let mut drawn = None;
|
||||
Popover::new(tl!("Undo History").to_string(), Bind::bound(&mut open)).opened_by(&out.response).show(ui, |ui, cx| {
|
||||
// Built inside the body, which runs only while the popover shows or fades.
|
||||
let labels = closing.as_ref().map_or_else(|| undo_list_rows(app), |(l, _)| l.clone());
|
||||
let rows = UndoRows::new(&labels);
|
||||
// A collection owns its scroll: the popover's body scrolls, so the list caps its rows and scrolls the rest.
|
||||
let events = UndoList::new(tl!("Undo History").to_string())
|
||||
@@ -178,6 +183,7 @@ fn undo_arrow(app: &mut WordApp, ui: &mut Ui, enabled: bool) -> egui::Rect {
|
||||
.selection(Bind::bound(&mut mark))
|
||||
.show_items(ui, &rows, &mut |key, _| rows.row(*key))
|
||||
.events;
|
||||
drawn = Some(labels.clone());
|
||||
if let Some(count) = undo_count(&events) {
|
||||
picked = Some(count);
|
||||
cx.request_close();
|
||||
@@ -198,6 +204,11 @@ fn undo_arrow(app: &mut WordApp, ui: &mut Ui, enabled: bool) -> egui::Rect {
|
||||
});
|
||||
app.chrome.undo = open;
|
||||
app.chrome.undo_mark = if open { mark } else { UndoMark::default() };
|
||||
app.chrome.undo_closing = match (open, was_open) {
|
||||
(true, _) => None,
|
||||
(false, true) => drawn.map(|l| (l, mark)),
|
||||
(false, false) => closing,
|
||||
};
|
||||
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
|
||||
@@ -213,19 +224,17 @@ fn undo_arrow(app: &mut WordApp, ui: &mut Ui, enabled: bool) -> egui::Rect {
|
||||
fn qat_menu(app: &mut WordApp, ui: &mut Ui) -> egui::Rect {
|
||||
let out =
|
||||
IconButton::new(IconId::new("wordcraft.more")).label(tl!("Customize Quick Access Toolbar").to_string()).glyphs(GlyphRole::Tool).show(ui);
|
||||
let shown: Vec<(&'static str, String, bool)> = QAT_MENU
|
||||
.iter()
|
||||
.filter_map(|id| {
|
||||
let label = app.session.registry.get(id).map(|s| tl!(s.label).to_string())?;
|
||||
Some((*id, label, app.session.ribbon.qat().contains(id)))
|
||||
})
|
||||
.collect();
|
||||
// No `open` binding: with one the framework leaves the opening to the app, without it the opener opens the menu.
|
||||
Menu::new(tl!("Customize Quick Access Toolbar").to_string()).opened_by(&out.response, Trigger::Click).show(ui, |ui, _| {
|
||||
MenuItem::heading(tl!("Customize Quick Access Toolbar").to_string()).show(ui);
|
||||
for (id, label, on) in &shown {
|
||||
let key = if *on { "qatRemove" } else { "qatAdd" };
|
||||
MenuItem::command(CommandRef::with_params("tools.customizeRibbon", json!({ key: *id }))).label(label.clone()).check(*on).show(ui);
|
||||
for &id in &QAT_MENU {
|
||||
let Some(spec) = app.session.registry.get(id) else { continue };
|
||||
let on = app.session.ribbon.qat().contains(&id);
|
||||
let key = if on { "qatRemove" } else { "qatAdd" };
|
||||
MenuItem::command(CommandRef::with_params("tools.customizeRibbon", json!({ key: id })))
|
||||
.label(tl!(spec.label).to_string())
|
||||
.check(on)
|
||||
.show(ui);
|
||||
}
|
||||
Divider::horizontal().show(ui);
|
||||
MenuItem::command(CommandRef::with_params("ui.dialog", json!({"name": "customizeQuickAccess"})))
|
||||
|
||||
+207
-36
@@ -17,10 +17,10 @@ use craft::ui::choice::{CellMarks, SwatchTable};
|
||||
use craft::ui::contract::{BodyCx, Hover, NoValue, Props as _, Show as _, clicked};
|
||||
use craft::ui::dialog::{DialogId, DialogResult};
|
||||
use craft::ui::menu::{MenuItem, MenuItemOutput};
|
||||
use craft::ui::primitives::{IconMark, IconSpec};
|
||||
use craft::ui::primitives::{Glyph, IconMark, IconSpec, StrokeWidth};
|
||||
use craft::ui::runtime::env::Label;
|
||||
use craft::ui::style::DataColor;
|
||||
use egui::{Color32, Ui};
|
||||
use craft::ui::style::{DataColor, UiTokens};
|
||||
use egui::{Color32, Painter, Rect, Stroke, StrokeKind, Ui, vec2};
|
||||
use serde_json::{Value, json};
|
||||
use wordcraft_doc::Rgb;
|
||||
|
||||
@@ -241,18 +241,76 @@ pub fn apply(app: &mut WordApp, target: &Target, hex: &str) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The colour a target has now (the dialog's Current swatch).
|
||||
/// The colour every item has, `None` for no items, no colour, or items that differ.
|
||||
fn agree(mut colors: impl Iterator<Item = Option<Rgb>>) -> Option<Rgb> {
|
||||
let first = colors.next()??;
|
||||
colors.all(|c| c == Some(first)).then_some(first)
|
||||
}
|
||||
|
||||
/// The shading the given cells share; cells a ragged table lacks are skipped, not read as unshaded.
|
||||
fn cell_shading(table: &wordcraft_doc::Table, cells: impl IntoIterator<Item = (usize, usize)>) -> Option<Rgb> {
|
||||
agree(cells.into_iter().filter_map(|(r, c)| table.rows.get(r)?.cells.get(c).map(|cell| cell.props.shading)))
|
||||
}
|
||||
|
||||
/// The colour a target has now (the dialog's Current swatch), read from what its command changes:
|
||||
/// `para.shading` reads the selected text's shading when the selection is text within one paragraph,
|
||||
/// else the paragraphs'; `shape.effects` reads shapes only. `None` when it has none, is Automatic,
|
||||
/// differs across the selection, or cannot be read (a picture's icon colour is not stored).
|
||||
fn current_of(app: &mut WordApp, target: &Target) -> Option<Rgb> {
|
||||
use wordcraft_doc::InlineObject;
|
||||
let Target::Run { cmd, .. } = target else { return None };
|
||||
let s = &app.session;
|
||||
let shapes = |o: &InlineObject| matches!(o, InlineObject::Shape { .. }) || o.is_canvas();
|
||||
let objects = || wordcraft_engine::cmd::objects::target_objects(s, shapes).into_iter().map(|(_, o)| o);
|
||||
match cmd.as_str() {
|
||||
"format.color" => {
|
||||
let st = wordcraft_engine::cmd::format::state(&app.session);
|
||||
st.get("color").and_then(Value::as_str).and_then(parse)
|
||||
"format.color" | "format.underlineColor" => {
|
||||
let st = wordcraft_engine::cmd::format::cached_state(s);
|
||||
let key = if cmd == "format.color" { "color" } else { "underlineColor" };
|
||||
st.get(key).and_then(Value::as_str).and_then(parse)
|
||||
}
|
||||
// The command shades the selected text, not its paragraph, when the selection is text within one.
|
||||
"para.shading" if wordcraft_engine::cmd::para::shades_text(s) => {
|
||||
wordcraft_engine::cmd::format::cached_state(s).get("shading").and_then(Value::as_str).and_then(parse)
|
||||
}
|
||||
"para.shading" => agree(
|
||||
wordcraft_engine::cmd::selected_paths(s)
|
||||
.iter()
|
||||
.map(|path| s.doc.para(s.sel.focus.story, path).and_then(|p| s.doc.styles.resolve_para(&p.props).shading)),
|
||||
),
|
||||
"table.shading" => {
|
||||
let (tp, _, _) = s.sel.focus.path.cell()?;
|
||||
let table = s.doc.table(s.sel.focus.story, &tp)?;
|
||||
cell_shading(table, wordcraft_engine::cmd::table::selected_cells(s))
|
||||
}
|
||||
"design.pageColor" => s.doc.settings.page_color,
|
||||
"shape.fill" => agree(objects().map(|o| {
|
||||
let fill = match &o {
|
||||
InlineObject::Shape { fill, .. } => fill.as_ref(),
|
||||
o => o.canvas_style().and_then(|c| c.fill.as_ref()),
|
||||
};
|
||||
match fill {
|
||||
Some(wordcraft_doc::fill::Fill::Solid { color, .. }) => Some(*color),
|
||||
_ => None,
|
||||
}
|
||||
})),
|
||||
"shape.outline" => agree(objects().map(|o| match &o {
|
||||
InlineObject::Shape { stroke, .. } => *stroke,
|
||||
o => o.canvas_style().and_then(|c| c.stroke),
|
||||
})),
|
||||
// Glow is applied to shapes only, so a canvas in the selection is not read.
|
||||
"shape.effects" => agree(objects().filter(|o| matches!(o, InlineObject::Shape { .. })).map(|o| match &o {
|
||||
InlineObject::Shape { effects, .. } => effects.glow.as_ref().map(|g| g.color),
|
||||
_ => None,
|
||||
})),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the selection's font colour is uniformly Automatic.
|
||||
fn current_is_auto(app: &WordApp) -> bool {
|
||||
wordcraft_engine::cmd::format::state(&app.session).get("color").and_then(Value::as_str) == Some("auto")
|
||||
}
|
||||
|
||||
/// The colour a split button's main part applies: what its target remembers, else what is in effect.
|
||||
fn remembered(app: &mut WordApp, target: &Target) -> Option<Rgb> {
|
||||
match target {
|
||||
@@ -287,9 +345,9 @@ pub struct ColorPick {
|
||||
pub response: egui::Response,
|
||||
/// The colour picked in this pass.
|
||||
pub picked: Option<Rgb>,
|
||||
/// What the pointer over a swatch did to the live preview: it shows while the pointer is over a
|
||||
/// swatch and ends when it leaves.
|
||||
pub preview: craft::behavior::Preview<Rgb>,
|
||||
/// What the pointer over a swatch or menu choice did to the live preview: `Some(c)` for a
|
||||
/// palette colour, `None` for Automatic / No Color, and `Ended` when the pointer leaves.
|
||||
pub preview: craft::behavior::Preview<Option<Rgb>>,
|
||||
/// The main part's stay of a split button; `Hover::default()` for a body without one.
|
||||
pub hover: Hover,
|
||||
}
|
||||
@@ -318,9 +376,9 @@ fn swatch_table(
|
||||
(picked, preview, out.response)
|
||||
}
|
||||
|
||||
/// Two previews of one pass: a start wins over an end, as the pointer moving from one table to
|
||||
/// Two previews of one pass: a start wins over an end, as the pointer moving from one control to
|
||||
/// the next ends one and starts the other.
|
||||
fn merge_preview(a: craft::behavior::Preview<Rgb>, b: craft::behavior::Preview<Rgb>) -> craft::behavior::Preview<Rgb> {
|
||||
fn merge_preview<T>(a: craft::behavior::Preview<T>, b: craft::behavior::Preview<T>) -> craft::behavior::Preview<T> {
|
||||
use craft::behavior::Preview;
|
||||
match (a, b) {
|
||||
(Preview::Shows(c), _) | (_, Preview::Shows(c)) => Preview::Shows(c),
|
||||
@@ -329,6 +387,26 @@ fn merge_preview(a: craft::behavior::Preview<Rgb>, b: craft::behavior::Preview<R
|
||||
}
|
||||
}
|
||||
|
||||
/// Tracks hover preview transitions for a single `MenuItem` inside a colour drop-down so hovering
|
||||
/// it previews `None` and leaving or closing the drop-down ends the preview.
|
||||
fn item_preview(ctx: &egui::Context, key: egui::Id, hovered: bool, open: bool) -> craft::behavior::Preview<Option<Rgb>> {
|
||||
use craft::behavior::Preview;
|
||||
let was = ctx.data(|d| d.get_temp::<bool>(key)).unwrap_or(false);
|
||||
if !open {
|
||||
if was {
|
||||
ctx.data_mut(|d| d.remove::<bool>(key));
|
||||
return Preview::Ended;
|
||||
}
|
||||
return Preview::Unchanged;
|
||||
}
|
||||
if hovered != was {
|
||||
ctx.data_mut(|d| d.insert_temp(key, hovered));
|
||||
if hovered { Preview::Shows(None) } else { Preview::Ended }
|
||||
} else {
|
||||
Preview::Unchanged
|
||||
}
|
||||
}
|
||||
|
||||
/// The theme and recent swatches of `palette`; the colour in effect carries the selection mark.
|
||||
fn swatches(ui: &mut Ui, palette: &Palette, current: Option<Rgb>) -> (Option<Rgb>, craft::behavior::Preview<Rgb>) {
|
||||
let (mut picked, mut preview, _) = swatch_table(ui, "Theme Colors", &palette.theme, THEME_PER_ROW, current);
|
||||
@@ -360,7 +438,7 @@ pub fn palette(ui: &mut Ui, app: &mut WordApp, target: Target) -> ColorPick {
|
||||
if more.ran {
|
||||
open_for(app, &target, current, ColorPickerTab::Standard);
|
||||
}
|
||||
ColorPick { response: more.response, picked, preview, hover: Hover::default() }
|
||||
ColorPick { response: more.response, picked, preview: preview.map(Some), hover: Hover::default() }
|
||||
}
|
||||
|
||||
/// A command colour drop-down's body: [`palette`]; the caller closes the drop-down.
|
||||
@@ -390,30 +468,33 @@ enum Above {
|
||||
}
|
||||
|
||||
/// A split button whose main part runs `main` and whose arrow opens `body`.
|
||||
/// `body` returns its `ColorPick` and whether its `Automatic` / `No Color` item is hovered.
|
||||
fn split_with(
|
||||
ui: &mut Ui,
|
||||
app: &mut WordApp,
|
||||
label: Label,
|
||||
icon: IconSpec<'static>,
|
||||
main: CommandRef,
|
||||
mut body: impl FnMut(&mut Ui, &mut WordApp, &mut BodyCx<'_>) -> ColorPick,
|
||||
mut body: impl FnMut(&mut Ui, &mut WordApp, &mut BodyCx<'_>) -> (ColorPick, bool),
|
||||
) -> ColorPick {
|
||||
let mut inner: Option<(Option<Rgb>, craft::behavior::Preview<Rgb>)> = None;
|
||||
let mut inner: Option<(Option<Rgb>, craft::behavior::Preview<Option<Rgb>>, bool)> = None;
|
||||
// The arrow is its own button, named "<label> options" so it is told from the main part (#3172).
|
||||
let arrow_name = crate::i18n::fmt(tl!("{name} options"), &[("name", label.as_str())]);
|
||||
let out = SplitButton::<NoValue>::command(
|
||||
main,
|
||||
SplitMenu::Body(Box::new(|ui: &mut Ui, cx: &mut BodyCx<'_>| {
|
||||
let pick = body(ui, app, cx);
|
||||
inner = Some((pick.picked, pick.preview));
|
||||
let (pick, empty_hovered) = body(ui, app, cx);
|
||||
inner = Some((pick.picked, pick.preview, empty_hovered));
|
||||
})),
|
||||
)
|
||||
.label(label)
|
||||
.arrow_label(arrow_name)
|
||||
.icon(icon)
|
||||
.show(ui);
|
||||
let (picked, preview) = inner.unwrap_or((None, craft::behavior::Preview::Unchanged));
|
||||
ColorPick { response: out.response, picked, preview, hover: out.hover }
|
||||
let open = inner.is_some();
|
||||
let (picked, swatch_preview, empty_hovered) = inner.unwrap_or((None, craft::behavior::Preview::Unchanged, false));
|
||||
let empty_preview = item_preview(ui.ctx(), out.response.id.with("empty_hover"), empty_hovered, open);
|
||||
ColorPick { response: out.response, picked, preview: merge_preview(swatch_preview, empty_preview), hover: out.hover }
|
||||
}
|
||||
|
||||
/// The split button of a colour `target`: the icon of its command with a bar of the remembered
|
||||
@@ -433,24 +514,29 @@ fn color_split(ui: &mut Ui, app: &mut WordApp, label: Label, target: Target, abo
|
||||
_ => CommandRef::new(cmd.clone()),
|
||||
};
|
||||
split_with(ui, app, label, icon, main, |ui, app, cx| {
|
||||
let mut empty_hovered = false;
|
||||
match above {
|
||||
Above::Nothing => {}
|
||||
Above::Automatic => {
|
||||
let auto = CommandRef::with_params("format.color", json!({"color": "auto"}));
|
||||
if MenuItem::new(tl!("Automatic").to_string()).command(auto).show(ui).ran {
|
||||
let item = MenuItem::new(tl!("Automatic").to_string()).command(auto).check(current_is_auto(app)).show(ui);
|
||||
if item.ran {
|
||||
cx.request_close();
|
||||
}
|
||||
empty_hovered = item.response.hovered() && !item.ran;
|
||||
}
|
||||
Above::NoColor => {
|
||||
let none = CommandRef::with_params(cmd.clone(), json!({"color": null}));
|
||||
if MenuItem::new(tl!("No Color").to_string()).command(none).show(ui).ran {
|
||||
let item = MenuItem::new(tl!("No Color").to_string()).command(none).show(ui);
|
||||
if item.ran {
|
||||
cx.request_close();
|
||||
}
|
||||
empty_hovered = item.response.hovered() && !item.ran;
|
||||
}
|
||||
}
|
||||
let pick = menu(ui, app, target.clone());
|
||||
close_after(&pick, cx);
|
||||
pick
|
||||
(pick, empty_hovered)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -480,17 +566,15 @@ pub(crate) fn highlight_button_appearance(name: &str) -> (&'static str, Option<C
|
||||
/// The highlight drop-down: the highlight colours five to a row, then No Color. A pick, No Color
|
||||
/// too, becomes the split button's colour, as in Word: after No Color a click on the button
|
||||
/// removes highlighting (#2105).
|
||||
fn highlight_body(ui: &mut Ui, app: &mut WordApp, cx: &mut BodyCx<'_>) -> ColorPick {
|
||||
fn highlight_body(ui: &mut Ui, app: &mut WordApp, cx: &mut BodyCx<'_>) -> (ColorPick, bool) {
|
||||
use wordcraft_doc::props::Highlight;
|
||||
let in_effect = Some(wordcraft_engine::cmd::format::state(&app.session))
|
||||
.and_then(|st| st.get("highlight").and_then(Value::as_str).map(str::to_string))
|
||||
.unwrap_or_else(|| "none".into());
|
||||
let in_effect = wordcraft_engine::cmd::format::uniform_highlight(&app.session);
|
||||
let shown: Vec<(&Highlight, Rgb)> = Highlight::ALL.iter().skip(1).filter_map(|h| h.rgb().map(|c| (h, c))).collect();
|
||||
let swatches: Vec<(Label, Srgba)> = shown.iter().map(|(h, c)| (Label::from(tl!(h.name()).to_string()), srgba(*c))).collect();
|
||||
let out = SwatchTable::new("Highlight Colors".to_string(), &swatches)
|
||||
.per_row(5)
|
||||
.tips(true)
|
||||
.marks(|i: &usize| CellMarks::default().edge(shown.get(*i).is_some_and(|(h, _)| h.ooxml() == in_effect)))
|
||||
.marks(|i: &usize| CellMarks::default().edge(shown.get(*i).is_some_and(|(_, c)| in_effect == Some(Some(*c)))))
|
||||
.show_all(ui);
|
||||
let mut picked = None;
|
||||
if let Some((h, c)) = out.selected.and_then(|i| shown.get(i)) {
|
||||
@@ -500,16 +584,20 @@ fn highlight_body(ui: &mut Ui, app: &mut WordApp, cx: &mut BodyCx<'_>) -> ColorP
|
||||
cx.request_close();
|
||||
}
|
||||
let preview = match out.preview {
|
||||
craft::behavior::Preview::Shows(i) => shown.get(i).map_or(craft::behavior::Preview::Unchanged, |(_, c)| craft::behavior::Preview::Shows(*c)),
|
||||
craft::behavior::Preview::Shows(i) => {
|
||||
shown.get(i).map_or(craft::behavior::Preview::Unchanged, |(_, c)| craft::behavior::Preview::Shows(Some(*c)))
|
||||
}
|
||||
craft::behavior::Preview::Ended => craft::behavior::Preview::Ended,
|
||||
_ => craft::behavior::Preview::Unchanged,
|
||||
};
|
||||
let none = CommandRef::with_params("format.highlight", json!({"color": "none"}));
|
||||
if MenuItem::new(tl!("No Color").to_string()).command(none).show(ui).ran {
|
||||
let no_color = MenuItem::new(tl!("No Color").to_string()).command(none).check(in_effect == Some(None)).show(ui);
|
||||
if no_color.ran {
|
||||
app.canvas.last_highlight = "none".into();
|
||||
cx.request_close();
|
||||
}
|
||||
ColorPick { response: out.response, picked, preview, hover: Hover::default() }
|
||||
let empty_hovered = no_color.response.hovered() && !no_color.ran;
|
||||
(ColorPick { response: out.response, picked, preview, hover: Hover::default() }, empty_hovered)
|
||||
}
|
||||
|
||||
/// Text Highlight Color: the highlight grid under the arrow; the main part applies the remembered
|
||||
@@ -529,14 +617,15 @@ pub fn highlight_split(ui: &mut Ui, app: &mut WordApp, label: impl Into<Label>)
|
||||
// More Colors…
|
||||
|
||||
/// The Colors dialog: Standard honeycomb and greys, Custom compact picker. `current` is the colour
|
||||
/// the target has now; `key` comes back in the result.
|
||||
/// the target has now, `None` when it has none: Current then shows no colour (as in v0.19.1) and
|
||||
/// Restore does nothing, while New starts on black. `key` comes back in the result.
|
||||
pub fn more_colors(current: Option<Rgb>, key: String, tab: ColorPickerTab) -> ColorPickerDialog {
|
||||
let (cells, greys) = standard_cells();
|
||||
ColorPickerDialog::new(key, tl!("Colors").to_string(), current.map_or(Srgba::rgb(0.0, 0.0, 0.0), srgba))
|
||||
let dialog = ColorPickerDialog::new(key, tl!("Colors").to_string(), current.map_or(Srgba::rgb(0.0, 0.0, 0.0), srgba))
|
||||
.layout(ColorPickerDialogLayout::Tabbed)
|
||||
.standard(cells, greys)
|
||||
.compare(current.is_some())
|
||||
.tab(tab)
|
||||
.tab(tab);
|
||||
if current.is_some() { dialog } else { dialog.no_current() }
|
||||
}
|
||||
|
||||
/// Opens the Colors dialog for `target`, remembering where its answer goes.
|
||||
@@ -613,6 +702,23 @@ pub enum AutoFace {
|
||||
Several(Vec<Srgba>),
|
||||
}
|
||||
|
||||
/// The swatch of a choice of several colours (By author): the colours side by side in equal shares, framed as a one-colour
|
||||
/// swatch is.
|
||||
#[derive(craft::ui::contract::MemoProps)]
|
||||
struct SwatchShares(Vec<Srgba>);
|
||||
|
||||
impl Glyph for SwatchShares {
|
||||
fn paint(&self, painter: &Painter, tokens: &UiTokens, rect: Rect, color: Color32, _mirrored: bool) {
|
||||
let width = rect.width() / self.0.len().max(1) as f32;
|
||||
for (at, share) in self.0.iter().enumerate() {
|
||||
let part = Rect::from_min_size(rect.min + vec2(width * at as f32, 0.0), vec2(width, rect.height()));
|
||||
painter.rect_filled(part, 0.0, color32(rgb_of(*share)));
|
||||
}
|
||||
let stroke = Stroke::new(StrokeWidth::Thin.points(tokens, painter.pixels_per_point()), color);
|
||||
painter.rect_stroke(rect, 0.0, stroke, StrokeKind::Inside);
|
||||
}
|
||||
}
|
||||
|
||||
/// What a colour field did in a pass.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct ColorFieldResponse {
|
||||
@@ -630,7 +736,7 @@ pub fn color_field(ui: &mut Ui, label: &Label, value: &mut String, empty: &Color
|
||||
let (shown, text) = match (current, empty) {
|
||||
(Some(c), _) => (Some(srgba(c)), Label::from(c.hex())),
|
||||
(None, ColorFieldEmpty::NoColor) => (None, Label::from(tl!("No Color").to_string())),
|
||||
// PLAN: framework gap: `IconSpec` has no multi-share swatch face, so `AutoFace::Several` shows its first colour until `IconSource` can paint `SwatchFace` shares (ribbon-w2).
|
||||
// Two or more `AutoFace::Several` colours paint as `SwatchShares` (below); a single one paints as itself.
|
||||
(None, ColorFieldEmpty::Automatic { label, face, .. }) => (
|
||||
match face {
|
||||
AutoFace::One(c) => Some(*c),
|
||||
@@ -639,7 +745,14 @@ pub fn color_field(ui: &mut Ui, label: &Label, value: &mut String, empty: &Color
|
||||
label.clone(),
|
||||
),
|
||||
};
|
||||
let icon = shown.map_or_else(IconSpec::empty_swatch, IconSpec::swatch);
|
||||
let shares = match (current, empty) {
|
||||
(None, ColorFieldEmpty::Automatic { face: AutoFace::Several(colors), .. }) if colors.len() > 1 => Some(SwatchShares(colors.clone())),
|
||||
_ => None,
|
||||
};
|
||||
let icon = match &shares {
|
||||
Some(shares) => IconSpec::glyph(shares),
|
||||
None => shown.map_or_else(IconSpec::empty_swatch, IconSpec::swatch),
|
||||
};
|
||||
let spoken_value = current.map_or_else(|| text.as_str().to_string(), |c| format!("#{}", c.hex()));
|
||||
let spoken = format!("{} {spoken_value}", label.as_str());
|
||||
let field = SplitButton::<NoValue>::body(text, |ui: &mut Ui, cx: &mut BodyCx<'_>| {
|
||||
@@ -766,4 +879,62 @@ mod tests {
|
||||
assert_eq!(app.ui.recent_colors.first().map(String::as_str), Some("7A3EC8"));
|
||||
assert!(app.more_colors.is_empty(), "no entry outlives its dialog");
|
||||
}
|
||||
|
||||
/// The Current swatch reads what the selection has, and says "no colour" where there is none or it
|
||||
/// differs (#7984).
|
||||
#[test]
|
||||
fn current_reads_the_selection_and_is_none_when_unset_or_mixed() {
|
||||
let c = |hex: u8| Rgb(hex, hex, hex);
|
||||
assert_eq!(agree([Some(c(1)), Some(c(1))].into_iter()), Some(c(1)), "all alike");
|
||||
assert_eq!(agree([Some(c(1)), Some(c(2))].into_iter()), None, "mixed");
|
||||
assert_eq!(agree([Some(c(1)), None].into_iter()), None, "one has none");
|
||||
assert_eq!(agree(std::iter::empty()), None, "nothing selected");
|
||||
|
||||
// Set on the caret's paragraph directly: the commands lay the page out, which costs ~0.7 s.
|
||||
let mut app = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default());
|
||||
let shading = Target::cmd("para.shading");
|
||||
assert_eq!(current_of(&mut app, &shading), None, "no shading yet");
|
||||
assert_eq!(current_of(&mut app, &Target::cmd("table.shading")), None, "no table, no colour");
|
||||
assert_eq!(current_of(&mut app, &Target::cmd("shape.fill")), None, "no shape selected");
|
||||
let at = app.session.sel.focus.clone();
|
||||
app.session.doc.para_mut(at.story, &at.path).unwrap().props.shading = Some(c(0xAA));
|
||||
assert_eq!(current_of(&mut app, &shading), Some(c(0xAA)), "a collapsed caret reads its paragraph");
|
||||
}
|
||||
|
||||
/// Text selected inside a paragraph is what Shading changes, so Current must not report the
|
||||
/// paragraph's shading for it (#7984).
|
||||
#[test]
|
||||
fn partial_selection_reads_the_text_shading_not_the_paragraph() {
|
||||
let mut app = WordApp::new(Session::new(wordcraft_doc::Document::from_text("hello world")), crate::Services::default());
|
||||
let at = app.session.sel.focus.clone();
|
||||
app.session.doc.para_mut(at.story, &at.path).unwrap().props.shading = Some(Rgb(0xAA, 0xAA, 0xAA));
|
||||
let mut end = at.clone();
|
||||
end.off = 5;
|
||||
app.session.sel = wordcraft_engine::Selection { anchor: at, focus: end };
|
||||
let shading = Target::cmd("para.shading");
|
||||
assert_eq!(current_of(&mut app, &shading), None, "the text has no shading, whatever its paragraph has");
|
||||
let _ = app.session.run("format.shading", &json!({"color": "112233"}));
|
||||
assert_eq!(current_of(&mut app, &shading), Some(Rgb(0x11, 0x22, 0x33)), "the selected run's shading");
|
||||
}
|
||||
|
||||
/// A ragged table's missing cells do not blank Current when the real cells agree (#7984).
|
||||
#[test]
|
||||
fn table_shading_skips_missing_cells() {
|
||||
let mut t = wordcraft_doc::Table::new(2, 2, 100.0);
|
||||
t.rows[1].cells.pop();
|
||||
for cell in t.rows.iter_mut().flat_map(|r| r.cells.iter_mut()) {
|
||||
cell.props.shading = Some(Rgb(1, 2, 3));
|
||||
}
|
||||
let all = [(0, 0), (0, 1), (1, 0), (1, 1)];
|
||||
assert_eq!(cell_shading(&t, all), Some(Rgb(1, 2, 3)), "the missing (1,1) is skipped");
|
||||
t.rows[0].cells[1].props.shading = None;
|
||||
assert_eq!(cell_shading(&t, all), None, "a real unshaded cell still blanks it");
|
||||
}
|
||||
|
||||
/// A target with no colour opens with no Current colour, not black (#7984).
|
||||
#[test]
|
||||
fn no_current_colour_is_not_black() {
|
||||
assert!(more_colors(None, "k".into(), ColorPickerTab::Standard).has_no_current());
|
||||
assert!(!more_colors(Some(Rgb(0, 0, 0)), "k".into(), ColorPickerTab::Standard).has_no_current(), "a real black stays a current colour");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,6 +39,13 @@ pub(crate) use host::close_all;
|
||||
pub(crate) use mailings::{FilterRow, RecipientDraft, RecipientFilter, RecipientListDialog, hold_rows, merge_order, visible_recipients};
|
||||
pub(crate) use page_setup::PAPER_LABELS;
|
||||
|
||||
/// `max_rows` for a `TileGrid` that shows `rows` rows of `columns` tiles. The collection counts the cap in
|
||||
/// items (the tile `rows` in, not the grid row it is in), so a cap of `rows` shows one row; a cap past the item
|
||||
/// count adds blank rows, so it stops at `len`. lean: upstream fix in craft-libs `rows_height`, then drop this.
|
||||
pub(crate) fn tile_rows_cap(len: usize, columns: usize, rows: usize) -> u16 {
|
||||
u16::try_from(len.min(columns * rows)).unwrap_or(u16::MAX)
|
||||
}
|
||||
|
||||
/// Opens the dialog `name` for a script, a button or a command, with `params`; the module of the name reads what it
|
||||
/// needs of them. Returns the dialog's id, or `None` when no dialog opened (an unknown name, nothing to show, or a
|
||||
/// pane such as Restrict Editing).
|
||||
|
||||
@@ -5,10 +5,11 @@
|
||||
//! through `tools.customizeKeyboard`, so agents get the same result without the dialog.
|
||||
|
||||
use craft::keymap::{Binding, CommandDef, Keymap, Overrides};
|
||||
use craft::menu::shortcuts::{DialogState, Layout, Options, Outcome, ShortcutsDialog};
|
||||
use craft::menu::shortcuts::{Area, DialogState, Layout, Options, Outcome, ShortcutsDialog};
|
||||
use craft::ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id};
|
||||
use egui::{Context, Ui};
|
||||
use serde_json::{Value, json};
|
||||
use wordcraft_engine::ribbon::{CONTEXTUAL_TABS, TABS};
|
||||
|
||||
use super::host::{DialogHooks, Settle, open_with};
|
||||
use crate::WordApp;
|
||||
@@ -49,11 +50,61 @@ fn assignable(binding: &Binding) -> bool {
|
||||
chord.mods.cmd || chord.mods.ctrl || chord.mods.alt || chord.is_function_key()
|
||||
}
|
||||
|
||||
/// The ribbon tab a command lives on, in English (the first part of its path).
|
||||
fn tab(def: &CommandDef) -> &str {
|
||||
def.paths.first().and_then(|path| path.first()).map_or("", String::as_str)
|
||||
}
|
||||
|
||||
/// Tabs that come up with the selection or a view, besides the engine's contextual ones; they share one Categories entry.
|
||||
const EXTRA_CONTEXT_TABS: [&str; 3] = ["Header & Footer", "Outlining", "Reading"];
|
||||
|
||||
fn in_tab<const N: usize>(def: &CommandDef) -> bool {
|
||||
tab(def) == TABS[N]
|
||||
}
|
||||
|
||||
fn in_context_tab(def: &CommandDef) -> bool {
|
||||
CONTEXTUAL_TABS.contains(&tab(def)) || EXTRA_CONTEXT_TABS.contains(&tab(def))
|
||||
}
|
||||
|
||||
fn in_no_tab(def: &CommandDef) -> bool {
|
||||
!TABS.contains(&tab(def)) && !in_context_tab(def)
|
||||
}
|
||||
|
||||
/// One filter per entry of `TABS` (the array's length makes the compiler check it).
|
||||
const TAB_FILTERS: [fn(&CommandDef) -> bool; TABS.len()] = [
|
||||
in_tab::<0>,
|
||||
in_tab::<1>,
|
||||
in_tab::<2>,
|
||||
in_tab::<3>,
|
||||
in_tab::<4>,
|
||||
in_tab::<5>,
|
||||
in_tab::<6>,
|
||||
in_tab::<7>,
|
||||
in_tab::<8>,
|
||||
in_tab::<9>,
|
||||
in_tab::<10>,
|
||||
in_tab::<11>,
|
||||
in_tab::<12>,
|
||||
];
|
||||
|
||||
/// Categories as Word lists them: the ribbon tabs (not the framework's menu and panel ids), the contextual tabs, the
|
||||
/// rest, then All Commands.
|
||||
fn areas() -> Vec<Area> {
|
||||
let mut areas: Vec<Area> = TABS.iter().copied().zip(TAB_FILTERS).map(|(name, rows)| Area::new(name, tl!(name), rows)).collect();
|
||||
areas.push(Area::new("Contextual Tabs", tl!("Contextual Tabs"), in_context_tab));
|
||||
areas.push(Area::new("Other", tl!("Other"), in_no_tab));
|
||||
areas.push(Area::new("All Commands", tl!("All Commands"), |_| true));
|
||||
areas
|
||||
}
|
||||
|
||||
/// The framework dialog's options: the command-list layout, sorted by label, with the assign rule above.
|
||||
fn options() -> Options {
|
||||
Options::default().with(|o| {
|
||||
o.layout = Layout::CommandLists;
|
||||
o.sort_by_label = true;
|
||||
o.own_areas = true;
|
||||
o.size = Some(egui::vec2(720.0, 700.0));
|
||||
o.areas = areas();
|
||||
o.title = Some(tl!("Customize Keyboard").to_string());
|
||||
o.accept = Some(Box::new(|_: &CommandDef, binding: &Binding| {
|
||||
if assignable(binding) { Ok(()) } else { Err(tl!("Use a key combination with Ctrl, Alt or a function key.").to_string()) }
|
||||
@@ -247,4 +298,53 @@ mod tests {
|
||||
let unbound_labels = keys_list_labels(&h);
|
||||
assert!(unbound_labels.iter().any(|t| t == "None"), "empty keys list says None: {unbound_labels:?}");
|
||||
}
|
||||
|
||||
/// #7971: Categories are the ribbon tabs a command is on, not menu or panel ids; a command with no tab is under Other,
|
||||
/// and every command is under All Commands.
|
||||
#[test]
|
||||
fn categories_are_ribbon_tabs() {
|
||||
use craft::keymap::{CommandDef, Scope};
|
||||
let on = |path: &[&str]| {
|
||||
let mut def = CommandDef::new(CommandRef::new("x"), "X", Scope::app());
|
||||
if !path.is_empty() {
|
||||
def = def.with_path(path.iter().map(|part| part.to_string()).collect());
|
||||
}
|
||||
def
|
||||
};
|
||||
let areas = super::areas();
|
||||
let listing = |def: &CommandDef| areas.iter().filter(|a| (a.rows)(def)).map(|a| a.id).collect::<Vec<_>>();
|
||||
assert_eq!(listing(&on(&["Home", "Font"])), ["Home", "All Commands"]);
|
||||
assert_eq!(listing(&on(&["Help", "Support"])), ["Help", "All Commands"], "every ribbon tab has its entry");
|
||||
assert_eq!(listing(&on(&["Table Design", "Styles"])), ["Contextual Tabs", "All Commands"]);
|
||||
assert_eq!(listing(&on(&[])), ["Other", "All Commands"]);
|
||||
assert_eq!(areas.last().map(|a| a.id), Some("All Commands"), "All Commands comes last");
|
||||
}
|
||||
|
||||
/// #7971: under another language, and for the SmartArt tab that shows as "Diagram Design", commands still land
|
||||
/// under their tab (the catalog keeps English paths; only the display is translated).
|
||||
#[test]
|
||||
fn commands_stay_under_their_tab_in_another_language() {
|
||||
let ctx = egui::Context::default();
|
||||
crate::i18n::fixture_host(&ctx, "x-fixture", "\tHome\tHome-FX\n\tFont\tFont-FX\n\tDiagram Design\tDiagram-FX\n");
|
||||
let mut a = app();
|
||||
let catalog = a.catalog().expect("catalog");
|
||||
let areas = super::areas();
|
||||
let under = |id: &str, area: &str| {
|
||||
let def = catalog.defs().iter().find(|def| def.command == CommandRef::new(id)).unwrap_or_else(|| panic!("{id} in catalog"));
|
||||
areas.iter().any(|a| a.id == area && (a.rows)(def))
|
||||
};
|
||||
assert!(under("format.bold", "Home"), "Bold is under Home in a translated interface");
|
||||
assert!(!under("format.bold", "Other"));
|
||||
let smart = a.session.registry.all().iter().find(|spec| spec.location.starts_with("SmartArt Design")).expect("a SmartArt command");
|
||||
assert!(under(smart.id, "Contextual Tabs") && !under(smart.id, "Other"), "{} is under the contextual tabs", smart.id);
|
||||
}
|
||||
|
||||
/// #7971: the board's catalog files each engine command under its ribbon tab.
|
||||
#[test]
|
||||
fn catalog_paths_follow_the_ribbon_location() {
|
||||
let mut a = app();
|
||||
let catalog = a.catalog().expect("catalog");
|
||||
let bold = catalog.defs().iter().find(|def| def.command == CommandRef::new("format.bold")).expect("format.bold");
|
||||
assert_eq!(bold.paths.first().and_then(|p| p.first()).map(String::as_str), Some("Home"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,10 +6,9 @@ use craft::ui::buttons::Button;
|
||||
use craft::ui::choice::{Radio, RadioGroup};
|
||||
use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _, clicked};
|
||||
use craft::ui::dialog::DialogId;
|
||||
use craft::ui::display::{Picture, Text};
|
||||
use craft::ui::form::FieldGroup;
|
||||
use craft::ui::display::{Picture, PictureSize, Text};
|
||||
use craft::ui::layout_components::Row;
|
||||
use craft::ui::list::ThumbAspect;
|
||||
use craft::ui::list::{ThumbAspect, ThumbSize};
|
||||
use craft::ui::patterns::form_dialogs::FormCx;
|
||||
use craft::ui::primitives::{ContentPainterCx, TextureCache};
|
||||
use craft::ui::runtime::env::Label;
|
||||
@@ -20,7 +19,7 @@ use wordcraft_doc::props::Align;
|
||||
|
||||
use super::dialogs_insert::symbol::SymbolRequest;
|
||||
use super::font::FontRequest;
|
||||
use super::host::{Asks, ChildAnswer, WordForm, open_form};
|
||||
use super::host::{Asks, ChildAnswer, WordForm, captioned, open_form};
|
||||
use crate::WordApp;
|
||||
|
||||
/// The alignments the dialog offers: `para.defineBullet`'s `align` and their names.
|
||||
@@ -183,6 +182,7 @@ impl DefineBulletForm {
|
||||
}
|
||||
},
|
||||
)
|
||||
.extent(PictureSize::Sample(ThumbSize::Large))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -210,8 +210,8 @@ impl WordForm for DefineBulletForm {
|
||||
});
|
||||
let entries: Vec<Entry<String>> = ALIGNMENTS.iter().map(|(k, n)| Entry::new((*k).to_string(), Label::from(tl!(n)))).collect();
|
||||
let current = if self.align.is_empty() { "left".to_string() } else { self.align.clone() };
|
||||
FieldGroup::new(Label::from(tl!("Alignment:"))).show(ui, |ui, _| {
|
||||
let group = RadioGroup::new(Label::from(tl!("Alignment:")), Bind::given(current.clone())).show(ui, |ui, _| {
|
||||
let group = captioned(ui, Label::from(tl!("Alignment:")), |name, ui| {
|
||||
RadioGroup::new(name, Bind::given(current.clone())).show(ui, |ui, _| {
|
||||
Row::new().show(ui, |ui, _| {
|
||||
for e in &entries {
|
||||
if let (Some(id), label) = (e.value(), e.label()) {
|
||||
@@ -219,12 +219,12 @@ impl WordForm for DefineBulletForm {
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
if let Some(a) = group.output.value().cloned() {
|
||||
self.align = a;
|
||||
}
|
||||
})
|
||||
});
|
||||
FieldGroup::new(Label::from(tl!("Preview"))).show(ui, |ui, _| {
|
||||
if let Some(a) = group.and_then(|g| g.output.value().cloned()) {
|
||||
self.align = a;
|
||||
}
|
||||
captioned(ui, Label::from(tl!("Preview")), |_, ui| {
|
||||
self.preview().show(ui);
|
||||
});
|
||||
self.ch.chars().count() == 1
|
||||
|
||||
@@ -4,10 +4,11 @@ use craft::text::ui::columns::{ColumnsApply, TextColumns, TextColumnsDialog};
|
||||
use craft::ui::choice::{Radio, RadioGroup};
|
||||
use craft::ui::contract::{Bind, FieldLayout, Props as _, Show as _, ShowContainer as _, SideLabel};
|
||||
use craft::ui::dialog::DialogId;
|
||||
use craft::ui::form::{Field, FieldGroup};
|
||||
use craft::ui::form::Field;
|
||||
use craft::ui::layout_components::Stack;
|
||||
use craft::ui::patterns::form_dialogs::FormCx;
|
||||
use craft::ui::runtime::env::Label;
|
||||
use craft::ui::sections::GroupBox;
|
||||
use craft::ui::text::NumberField;
|
||||
use egui::Ui;
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -15,7 +16,7 @@ use serde_json::{Map, Value, json};
|
||||
|
||||
use super::{settled, word};
|
||||
use crate::WordApp;
|
||||
use crate::dialogs::host::{Asks, DialogHooks, Keyed, Settle, WordForm, open_with};
|
||||
use crate::dialogs::host::{Asks, DialogHooks, Keyed, Settle, WordForm, captioned, open_with};
|
||||
use crate::options::lengths;
|
||||
use crate::widgets::font_box::{CatalogRef, font_picker};
|
||||
|
||||
@@ -104,14 +105,16 @@ impl WordForm for DropCapForm {
|
||||
fn body(&mut self, ui: &mut Ui, _cx: &mut FormCx<'_, '_>, _asks: &mut Vec<Asks>) -> bool {
|
||||
let enabled = self.position != "none";
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
RadioGroup::new(word("Position"), Bind::bound(&mut self.position)).show(ui, |ui, _| {
|
||||
Stack::new().show(ui, |ui, cx| {
|
||||
for (at, (v, l)) in [("none", "None"), ("dropped", "Dropped"), ("margin", "In margin")].into_iter().enumerate() {
|
||||
cx.labelled(ui, at, word(l), SideLabel::new().layout(FieldLayout::After), Radio::new(v.to_string()));
|
||||
}
|
||||
});
|
||||
captioned(ui, word("Position"), |name, ui| {
|
||||
RadioGroup::new(name, Bind::bound(&mut self.position)).show(ui, |ui, _| {
|
||||
Stack::new().show(ui, |ui, cx| {
|
||||
for (at, (v, l)) in [("none", "None"), ("dropped", "Dropped"), ("margin", "In margin")].into_iter().enumerate() {
|
||||
cx.labelled(ui, at, word(l), SideLabel::new().layout(FieldLayout::After), Radio::new(v.to_string()));
|
||||
}
|
||||
});
|
||||
})
|
||||
});
|
||||
FieldGroup::new(word("Options")).show(ui, |ui, _| {
|
||||
GroupBox::new(word("Options"), None).show(ui, |ui, _| {
|
||||
if let Some(catalog) = self.catalog.get() {
|
||||
Field::new(word("Font:")).show(ui, |ui, _| {
|
||||
font_picker(word("Font:"), Bind::bound(&mut self.font), catalog, Bind::bound(&mut self.settings), &[], None)
|
||||
|
||||
@@ -3,23 +3,25 @@ use std::sync::Arc;
|
||||
use craft::behavior::{ColumnWidth, Selection, SelectionChange, keyed};
|
||||
use craft::font_manager::Catalog;
|
||||
use craft::font_manager::picker::FontPickerSettings;
|
||||
use craft::ui::contract::{Bind, CollectionEvent, ColumnKey, ColumnSpec, SelectMode, Show as _, ShowCollection as _, ShowContainer as _};
|
||||
use craft::theme::Mode;
|
||||
use craft::ui::contract::{Bind, CollectionEvent, ColumnKey, ColumnSpec, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _};
|
||||
use craft::ui::dialog::{DialogId, DialogResult, DialogStack, HeldAnswer, HeldOk, StackDialog, dialog_id};
|
||||
use craft::ui::display::{Kbd, Text};
|
||||
use craft::ui::form::Field;
|
||||
use craft::ui::layout_components::Stack;
|
||||
use craft::ui::layout_components::{Row, Stack};
|
||||
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;
|
||||
use craft::ui::runtime::env::{Env, Label};
|
||||
use craft::ui::table::Table;
|
||||
use craft::ui::tabs::{Tab, TabKind, TabStrip};
|
||||
use craft::ui::text::TextField;
|
||||
use craft::ui::tile_grid::{CaptionPlace, Tile, TileGrid};
|
||||
use egui::Ui;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{select_index, settled, text_field, word};
|
||||
use super::{select_index, settled, word};
|
||||
use crate::WordApp;
|
||||
use crate::dialogs::host::{DialogHooks, Settle, open_with};
|
||||
use crate::widgets::font_box::font_picker;
|
||||
@@ -36,6 +38,12 @@ pub struct RecentSymbol {
|
||||
pub font: String,
|
||||
}
|
||||
|
||||
/// Characters per row of the Symbols map (Word's grid is 16 wide).
|
||||
// lean: the cap assumes this many columns; read the laid-out count if the map becomes resizable.
|
||||
const GRID_COLUMNS: usize = 16;
|
||||
/// Rows of the Symbols map shown before it scrolls.
|
||||
const GRID_ROWS: usize = 8;
|
||||
|
||||
/// How many recent symbols are kept.
|
||||
pub const RECENT_SYMBOLS: usize = 20;
|
||||
|
||||
@@ -546,7 +554,7 @@ fn special_table(ui: &mut Ui, form: &mut SymbolForm) -> bool {
|
||||
let columns = vec![
|
||||
ColumnSpec::new(glyph.clone(), Label::Empty, ColumnWidth::fill(0.5)),
|
||||
ColumnSpec::new(name.clone(), word("Special Characters"), ColumnWidth::fill(2.0)),
|
||||
ColumnSpec::new(keys.clone(), word("Shortcut key:"), ColumnWidth::fill(1.0)),
|
||||
ColumnSpec::new(keys.clone(), word("Shortcut key:"), ColumnWidth::Controls(5.5)),
|
||||
];
|
||||
let positions: Vec<usize> = (0..SPECIAL.len()).collect();
|
||||
let source = keyed(&positions, |at: &usize| *at);
|
||||
@@ -614,14 +622,21 @@ fn symbol_page(ui: &mut Ui, form: &mut SymbolForm, catalog: Option<&Arc<Catalog>
|
||||
{
|
||||
form.jump_to(name);
|
||||
}
|
||||
let dark = ui.visuals().dark_mode;
|
||||
// The theme's mode, not egui's `dark_mode`, which the craft theme does not drive (light tiles in the light theme, #8021).
|
||||
let dark = Env::of(ui).view().mode() == Mode::Dark;
|
||||
let activated = glyph_grid(ui, form, dark);
|
||||
recent_row(ui, form, dark);
|
||||
if let Some(c) = form.selected {
|
||||
Text::new(Label::from(format!("U+{:04X}", c as u32))).show(ui);
|
||||
}
|
||||
let before = form.code.clone();
|
||||
text_field(ui, "symbol_code", &word("Character code:"), &mut form.code);
|
||||
let label = word("Character code:");
|
||||
Field::new(label.clone()).id_salt("symbol_code").show(ui, |ui, _| {
|
||||
Row::new().show(ui, |ui, _| {
|
||||
TextField::new(label.clone(), Bind::bound(&mut form.code)).show(ui);
|
||||
Text::new(word("from Unicode (hex)")).show(ui);
|
||||
});
|
||||
});
|
||||
if form.code != before {
|
||||
let code = form.code.clone();
|
||||
form.select_code(&code);
|
||||
@@ -631,14 +646,17 @@ fn symbol_page(ui: &mut Ui, form: &mut SymbolForm, catalog: Option<&Arc<Catalog>
|
||||
|
||||
/// The recently inserted symbols as one row of glyphs, each in its own font; a click picks one.
|
||||
fn recent_row(ui: &mut Ui, form: &mut SymbolForm, dark: bool) {
|
||||
// The heading shows while the row is empty too, as Word does; with symbols it labels the row.
|
||||
if form.recent.is_empty() {
|
||||
Text::new(word("Recently used symbols:")).show(ui);
|
||||
return;
|
||||
}
|
||||
let positions: Vec<usize> = (0..form.recent.len()).collect();
|
||||
let source = keyed(&positions, |at: &usize| *at);
|
||||
let events = {
|
||||
let mut events = Vec::new();
|
||||
Field::new(word("Recently used symbols:")).show(ui, |ui, _| {
|
||||
let recent = &form.recent;
|
||||
TileGrid::new(word("Recently used symbols:"))
|
||||
events = TileGrid::new(word("Recently used symbols:"))
|
||||
.thumb_size(ThumbSize::Medium)
|
||||
.select(SelectMode::Single)
|
||||
.caption(CaptionPlace::None)
|
||||
@@ -652,8 +670,8 @@ fn recent_row(ui: &mut Ui, form: &mut SymbolForm, dark: bool) {
|
||||
Tile::new(r.ch).thumb(ThumbAspect::SQUARE, move |cx, rect| paint_glyph(cx, rect, ch, &font, dark))
|
||||
})
|
||||
.response
|
||||
.events
|
||||
};
|
||||
.events;
|
||||
});
|
||||
for event in events {
|
||||
if let CollectionEvent::Selection { change: SelectionChange::Set(rows), .. } = event
|
||||
&& let Some(r) = rows.last().and_then(|i| form.recent.get(*i)).cloned()
|
||||
@@ -685,7 +703,8 @@ fn glyph_grid(ui: &mut Ui, form: &mut SymbolForm, dark: bool) -> bool {
|
||||
let mut grid = TileGrid::new(word("Symbols"))
|
||||
.thumb_size(ThumbSize::Medium)
|
||||
.select(SelectMode::Single)
|
||||
.max_rows(8)
|
||||
.max_rows(crate::dialogs::tile_rows_cap(form.chars.len(), GRID_COLUMNS, GRID_ROWS))
|
||||
.card_columns(GRID_COLUMNS)
|
||||
.caption(CaptionPlace::None)
|
||||
.selection(Bind::bound(&mut selection));
|
||||
if let Some(at) = reveal {
|
||||
|
||||
@@ -138,6 +138,43 @@ fn symbol_dialog_uses_compact_tile_grids() {
|
||||
assert!(recent.height() < 80.0, "recently used symbols row should be compact: {}", recent.height());
|
||||
}
|
||||
|
||||
fn h_recent(a: &mut WordApp) {
|
||||
remember_symbol(a, "©", "DejaVu Sans");
|
||||
}
|
||||
|
||||
/// #7972: the Symbols map shows rows of characters (not one strip), with the Recently used heading
|
||||
/// and the note that the code is Unicode hex.
|
||||
#[test]
|
||||
fn symbol_dialog_shows_the_map_in_rows() {
|
||||
use egui::accesskit::Role;
|
||||
let mut a = app();
|
||||
h_recent(&mut a);
|
||||
let mut h = testing::harness(a);
|
||||
crate::dialogs::open(h.state_mut(), "symbol", &json!({})).expect("symbol dialog opens");
|
||||
h.run_steps(3);
|
||||
assert_eq!(h.query_all_by_label("Recently used symbols:").count(), 1, "the heading is the row's one name");
|
||||
h.get_by_role_and_label(Role::ListBox, "Recently used symbols:");
|
||||
let map = h.get_by_role_and_label(Role::ListBox, "Symbols").rect();
|
||||
let tile = h.query_all_by_label("A").map(|n| n.rect()).find(|r| map.contains_rect(*r)).expect("a tile in the map");
|
||||
assert!(map.height() > 3.0 * tile.height(), "the map is several rows tall: {} vs a tile {}", map.height(), tile.height());
|
||||
h.get_by_label("from Unicode (hex)");
|
||||
}
|
||||
|
||||
/// #7973: Insert Diagram offers every layout in its grid, not the first row of three.
|
||||
#[test]
|
||||
fn insert_diagram_dialog_shows_every_layout() {
|
||||
use egui::accesskit::Role;
|
||||
let mut h = testing::harness(app());
|
||||
crate::dialogs::open(h.state_mut(), "insertSmartArt", &json!({})).expect("the dialog opens");
|
||||
// The tiles' heights settle over a few passes.
|
||||
h.run_steps(10);
|
||||
let grid = h.get_by_role_and_label(Role::ListBox, "Layouts").rect();
|
||||
for layout in wordcraft_doc::smart_art::SmartArtLayout::ALL {
|
||||
let shown = h.query_all_by_label(layout.label()).any(|n| grid.contains(n.rect().center()));
|
||||
assert!(shown, "{} is shown in the grid", layout.label());
|
||||
}
|
||||
}
|
||||
|
||||
/// The Field dialog builds the field code from its options.
|
||||
#[test]
|
||||
fn field_dialog_builds_the_instruction() {
|
||||
|
||||
@@ -15,7 +15,7 @@ use egui::Ui;
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::WordApp;
|
||||
use crate::dialogs::host::{DialogHooks, open_form, open_form_with};
|
||||
use crate::dialogs::host::{DialogHooks, labelled, open_form, open_form_with};
|
||||
|
||||
mod page;
|
||||
pub(crate) mod print;
|
||||
@@ -92,11 +92,23 @@ pub(crate) fn points() -> LengthUnits {
|
||||
LengthUnits::new(UnitKind::Points, UnitKind::Points, 96.0)
|
||||
}
|
||||
|
||||
/// A whole-number field over `value` within `range`; true when the user changed it.
|
||||
/// A whole-number field over `value` within `range`, with its caption; true when the user changed it.
|
||||
pub(crate) fn count_field(ui: &mut Ui, label: &str, value: &mut u32, range: RangeInclusive<u32>, enabled: bool) -> bool {
|
||||
labelled(ui, label.to_string(), |name, ui| count_box(ui, name, value, range.clone(), enabled)).unwrap_or(false)
|
||||
}
|
||||
|
||||
/// `count_field` with no caption, named `label` for assistive technology: for a box that follows a radio carrying the
|
||||
/// same words ("Start at:").
|
||||
pub(crate) fn count_box(
|
||||
ui: &mut Ui,
|
||||
label: impl Into<craft::ui::runtime::env::Label>,
|
||||
value: &mut u32,
|
||||
range: RangeInclusive<u32>,
|
||||
enabled: bool,
|
||||
) -> bool {
|
||||
let was = f64::from(*value);
|
||||
let mut shown = Some(was);
|
||||
NumberField::new(label.to_string(), Bind::bound(&mut shown)).range(f64::from(*range.start())..=f64::from(*range.end())).enabled(enabled).show(ui);
|
||||
NumberField::new(label, Bind::bound(&mut shown)).range(f64::from(*range.start())..=f64::from(*range.end())).enabled(enabled).show(ui);
|
||||
match shown {
|
||||
Some(n) if n != was => {
|
||||
*value = (n.round().max(0.0) as u32).clamp(*range.start(), *range.end());
|
||||
@@ -116,8 +128,10 @@ pub(crate) fn length_field(ui: &mut Ui, label: &str, value: &mut f32, lengths: L
|
||||
let was = f64::from(*value);
|
||||
// The form takes the field's edit events, not a write into a copy that lives one pass: an edit that commits as the
|
||||
// dialog files its OK (Enter, or a click on OK) reaches the form in the pass that files it.
|
||||
let out = NumberField::length(label.to_string(), Bind::given(Some(was)), lengths).range(range).enabled(enabled).show(ui);
|
||||
match edited(&out.edit.events) {
|
||||
let out = labelled(ui, label.to_string(), |name, ui| {
|
||||
NumberField::length(name, Bind::given(Some(was)), lengths).range(range.clone()).enabled(enabled).show(ui)
|
||||
});
|
||||
match out.as_ref().and_then(|out| edited(&out.edit.events)) {
|
||||
Some(n) if n != was => {
|
||||
*value = n as f32;
|
||||
true
|
||||
@@ -129,8 +143,8 @@ pub(crate) fn length_field(ui: &mut Ui, label: &str, value: &mut f32, lengths: L
|
||||
/// A percentage field over `value`; true when the user changed it.
|
||||
pub(crate) fn percent_field(ui: &mut Ui, label: &str, value: &mut f32, range: RangeInclusive<f64>) -> bool {
|
||||
let was = f64::from(*value);
|
||||
let out = NumberField::new(label.to_string(), Bind::given(Some(was))).range(range).unit("%").show(ui);
|
||||
match edited(&out.edit.events) {
|
||||
let out = labelled(ui, label.to_string(), |name, ui| NumberField::new(name, Bind::given(Some(was))).range(range.clone()).unit("%").show(ui));
|
||||
match out.as_ref().and_then(|out| edited(&out.edit.events)) {
|
||||
Some(n) if n != was => {
|
||||
*value = n as f32;
|
||||
true
|
||||
@@ -151,11 +165,16 @@ pub(crate) fn named_field<K: NumberName + 'static>(
|
||||
enabled: bool,
|
||||
) {
|
||||
let presets = vec![Entry::new(NumberPick::Choice(name.0.id()), name.1.to_string()).checked(matches!(*value, NamedOr::Named(_)))];
|
||||
let mut field = NumberField::named(label.to_string(), Bind::bound(value)).range(range).presets(&presets).enabled(enabled);
|
||||
if let Some(lengths) = lengths {
|
||||
field = field.lengths(lengths);
|
||||
}
|
||||
field.show(ui);
|
||||
labelled(ui, label.to_string(), |name, ui| {
|
||||
{
|
||||
let field = NumberField::named(name, Bind::bound(&mut *value)).range(range.clone()).presets(&presets).enabled(enabled);
|
||||
match lengths {
|
||||
Some(lengths) => field.lengths(lengths),
|
||||
None => field,
|
||||
}
|
||||
}
|
||||
.show(ui)
|
||||
});
|
||||
}
|
||||
|
||||
/// The number a named field holds, 0 while it holds its name.
|
||||
|
||||
@@ -14,7 +14,7 @@ use serde_json::{Value, json};
|
||||
use wordcraft_engine::cmd::objects::fit_size;
|
||||
|
||||
use super::{DialogId, WordApp, length_field, percent_field, points};
|
||||
use crate::dialogs::host::{Asks, FormHost, WordForm};
|
||||
use crate::dialogs::host::{Asks, FormHost, WordForm, captioned, labelled};
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Size
|
||||
@@ -300,14 +300,22 @@ impl WordForm for PageNumbersForm {
|
||||
fn body(&mut self, ui: &mut Ui, _cx: &mut FormCx<'_, '_>, _asks: &mut Vec<Asks>) -> bool {
|
||||
let formats: Vec<Entry<String>> =
|
||||
crate::dialogs_notes::FORMATS.iter().map(|(v, l)| Entry::new((*v).to_string(), tl!(l).to_string())).collect();
|
||||
Select::new(tl!("Number format").to_string(), Bind::bound(&mut self.format), &formats).show(ui);
|
||||
RadioGroup::new(tl!("Page numbering").to_string(), Bind::bound(&mut self.cont)).show(ui, |ui, _| {
|
||||
Stack::new().show(ui, |ui, cx| {
|
||||
cx.labelled(ui, 0, Label::from(tl!("Continue from previous section")), SideLabel::new().layout(FieldLayout::After), Radio::new(true));
|
||||
cx.labelled(ui, 1, Label::from(tl!("Start at:")), SideLabel::new().layout(FieldLayout::After), Radio::new(false));
|
||||
});
|
||||
labelled(ui, tl!("Number format").to_string(), |name, ui| Select::new(name, Bind::bound(&mut self.format), &formats).show(ui));
|
||||
captioned(ui, tl!("Page numbering").to_string(), |name, ui| {
|
||||
RadioGroup::new(name, Bind::bound(&mut self.cont)).show(ui, |ui, _| {
|
||||
Stack::new().show(ui, |ui, cx| {
|
||||
cx.labelled(
|
||||
ui,
|
||||
0,
|
||||
Label::from(tl!("Continue from previous section")),
|
||||
SideLabel::new().layout(FieldLayout::After),
|
||||
Radio::new(true),
|
||||
);
|
||||
cx.labelled(ui, 1, Label::from(tl!("Start at:")), SideLabel::new().layout(FieldLayout::After), Radio::new(false));
|
||||
});
|
||||
})
|
||||
});
|
||||
super::count_field(ui, tl!("Start at:"), &mut self.start, 0..=100_000, !self.cont);
|
||||
super::count_box(ui, tl!("Start at:"), &mut self.start, 0..=100_000, !self.cont);
|
||||
true
|
||||
}
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ use wordcraft_engine::cmd::mailings::{ENVELOPE_SIZES, LABEL_PRODUCTS};
|
||||
use wordcraft_geom::Region;
|
||||
|
||||
use crate::WordApp;
|
||||
use crate::dialogs::host::{Asks, WordForm, open_form};
|
||||
use crate::dialogs::host::{Asks, WordForm, labelled, open_form};
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Envelopes
|
||||
@@ -72,10 +72,12 @@ impl WordForm for EnvelopeForm {
|
||||
fn body(&mut self, ui: &mut egui::Ui, _cx: &mut FormCx<'_, '_>, _asks: &mut Vec<Asks>) -> bool {
|
||||
let sizes: Vec<Entry<usize>> =
|
||||
ENVELOPE_SIZES.iter().enumerate().map(|(i, (n, w, h))| Entry::new(i, envelope_label(n, *w, *h, &self.region))).collect();
|
||||
TextField::new(tl!("Delivery address:"), Bind::bound(&mut self.delivery)).lines(4).show(ui);
|
||||
labelled(ui, tl!("Delivery address:"), |name, ui| TextField::new(name, Bind::bound(&mut self.delivery)).lines(4).show(ui));
|
||||
Checkbox::new(Bind::bound(&mut self.omit_return)).label(tl!("Omit")).show(ui);
|
||||
TextField::new(tl!("Return address:"), Bind::bound(&mut self.ret)).lines(3).enabled(!self.omit_return).show(ui);
|
||||
Select::new(tl!("Envelope size:"), Bind::bound(&mut self.size), &sizes).show(ui);
|
||||
labelled(ui, tl!("Return address:"), |name, ui| {
|
||||
TextField::new(name, Bind::bound(&mut self.ret)).lines(3).enabled(!self.omit_return).show(ui)
|
||||
});
|
||||
labelled(ui, tl!("Envelope size:"), |name, ui| Select::new(name, Bind::bound(&mut self.size), &sizes).show(ui));
|
||||
self.ready()
|
||||
}
|
||||
fn commands(&self) -> Vec<(String, Value)> {
|
||||
@@ -202,9 +204,9 @@ impl WordForm for LabelsForm {
|
||||
Checkbox::new(Bind::bound(&mut self.recipients)).label(tl!("One label per recipient")).show(ui);
|
||||
}
|
||||
let per_recipient = self.has_recipients && self.recipients && !self.single;
|
||||
TextField::new(tl!("Address:"), Bind::bound(&mut self.text)).lines(4).enabled(!per_recipient).show(ui);
|
||||
labelled(ui, tl!("Address:"), |name, ui| TextField::new(name, Bind::bound(&mut self.text)).lines(4).enabled(!per_recipient).show(ui));
|
||||
let products: Vec<Entry<usize>> = (0..LABEL_PRODUCTS.len()).map(|i| Entry::new(i, product_label(i, &self.region))).collect();
|
||||
Select::new(tl!("Label:"), Bind::bound(&mut self.product), &products).show(ui);
|
||||
labelled(ui, tl!("Label:"), |name, ui| Select::new(name, Bind::bound(&mut self.product), &products).show(ui));
|
||||
let (rows, cols) = LABEL_PRODUCTS.get(self.product).map_or((1, 1), |p| (p.rows, p.cols));
|
||||
let mut single = self.single;
|
||||
let (mut row, mut col) = (self.row, self.col);
|
||||
@@ -216,21 +218,17 @@ impl WordForm for LabelsForm {
|
||||
Radio::new(1u8).label(tl!("Single label")).show(ui);
|
||||
});
|
||||
single = mode == 1;
|
||||
if let Some(Some(v)) = NumberField::new(tl!("Row:"), Bind::given(Some(row as f64)))
|
||||
.range(1.0..=rows.max(1) as f64)
|
||||
.enabled(single_on)
|
||||
.show(ui)
|
||||
.value()
|
||||
.copied()
|
||||
if let Some(Some(v)) = labelled(ui, tl!("Row:"), |name, ui| {
|
||||
NumberField::new(name, Bind::given(Some(row as f64))).range(1.0..=rows.max(1) as f64).enabled(single_on).show(ui)
|
||||
})
|
||||
.and_then(|out| out.value().copied())
|
||||
{
|
||||
row = v as usize;
|
||||
}
|
||||
if let Some(Some(v)) = NumberField::new(tl!("Column:"), Bind::given(Some(col as f64)))
|
||||
.range(1.0..=cols.max(1) as f64)
|
||||
.enabled(single_on)
|
||||
.show(ui)
|
||||
.value()
|
||||
.copied()
|
||||
if let Some(Some(v)) = labelled(ui, tl!("Column:"), |name, ui| {
|
||||
NumberField::new(name, Bind::given(Some(col as f64))).range(1.0..=cols.max(1) as f64).enabled(single_on).show(ui)
|
||||
})
|
||||
.and_then(|out| out.value().copied())
|
||||
{
|
||||
col = v as usize;
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{WordApp, count_field, named_field, number_or_zero, points};
|
||||
use crate::dialogs::host::{Asks, WordForm};
|
||||
use crate::dialogs::host::{Asks, WordForm, labelled};
|
||||
|
||||
/// The field's one name: a width that shares the text width out.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
@@ -96,7 +96,7 @@ impl WordForm for FormulaForm {
|
||||
});
|
||||
let functions: Vec<Entry<String>> = FORMULA_FUNCTIONS.iter().map(|n| Entry::new((*n).to_string(), (*n).to_string())).collect();
|
||||
let mut picked = String::new();
|
||||
Select::new(tl!("Paste function:").to_string(), Bind::bound(&mut picked), &functions).show(ui);
|
||||
labelled(ui, tl!("Paste function:").to_string(), |name, ui| Select::new(name, Bind::bound(&mut picked), &functions).show(ui));
|
||||
if !picked.is_empty() {
|
||||
self.paste(&picked);
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ use serde_json::{Value, json};
|
||||
use wordcraft_doc::section::LineNumberRestart;
|
||||
|
||||
use super::{WordApp, count_field, length_field, named_field, number_or_zero, points};
|
||||
use crate::dialogs::host::{Asks, Filed, WordForm};
|
||||
use crate::dialogs::host::{Asks, Filed, WordForm, captioned};
|
||||
|
||||
/// The field's one name: no limit on consecutive hyphens.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
@@ -105,12 +105,14 @@ impl WordForm for LineNumbersForm {
|
||||
length_field(ui, tl!("From text:"), &mut self.distance, lengths, 0.0..=22.0 * 72.0, on && !self.auto_distance);
|
||||
count_field(ui, tl!("Count by:"), &mut self.count_by, 1..=100, on);
|
||||
let opts = [("restartPage", tl!("Restart Each Page")), ("restartSection", tl!("Restart Each Section")), ("continuous", tl!("Continuous"))];
|
||||
RadioGroup::new(tl!("Numbering:").to_string(), Bind::bound(&mut self.restart)).show(ui, |ui, _| {
|
||||
Stack::new().show(ui, |ui, cx| {
|
||||
for (at, (v, l)) in opts.iter().enumerate() {
|
||||
cx.labelled(ui, at, Label::from(*l), SideLabel::new().layout(FieldLayout::After), Radio::new((*v).to_string()));
|
||||
}
|
||||
});
|
||||
captioned(ui, tl!("Numbering:").to_string(), |name, ui| {
|
||||
RadioGroup::new(name, Bind::bound(&mut self.restart)).show(ui, |ui, _| {
|
||||
Stack::new().show(ui, |ui, cx| {
|
||||
for (at, (v, l)) in opts.iter().enumerate() {
|
||||
cx.labelled(ui, at, Label::from(*l), SideLabel::new().layout(FieldLayout::After), Radio::new((*v).to_string()));
|
||||
}
|
||||
});
|
||||
})
|
||||
});
|
||||
true
|
||||
}
|
||||
@@ -444,6 +446,8 @@ impl WordForm for LanguageForm {
|
||||
let which: Vec<usize> = (0..list.len()).collect();
|
||||
let source = keyed(which.as_slice(), |i: &usize| *i);
|
||||
let selection = at.map_or_else(|| Selection::new(Vec::new(), None, None), Selection::single);
|
||||
// A plain caption, not a `Field`: the list keeps its own accessible name (#7976).
|
||||
Text::new(Label::from(heading.to_string())).show(ui);
|
||||
let shown = List::<usize>::new(Label::from(heading.to_string()))
|
||||
.select(SelectMode::Single)
|
||||
.selection(Bind::given(selection))
|
||||
|
||||
@@ -22,7 +22,7 @@ use serde_json::{Value, json};
|
||||
use wordcraft_doc::section::NumFormat;
|
||||
use wordcraft_engine::cmd::lists::{LEVELS, caret_list, level_json, levels_of};
|
||||
|
||||
use super::dialogs_para::{color_row, pick, radios, srgba, word};
|
||||
use super::dialogs_para::{color_row, pick, radios, radios_in_section, srgba, word};
|
||||
use super::host::{Asks, ChildAnswer, WordForm, open_form};
|
||||
use crate::WordApp;
|
||||
use crate::colors::{AutoFace, ColorFieldEmpty, Palette};
|
||||
@@ -282,7 +282,7 @@ impl ListForm {
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
Text::new(word(tl!("Preview"))).show(ui);
|
||||
Picture::painter(word(tl!("Preview")), ThumbAspect::new(5, 3), preview(rows.clone(), level))
|
||||
.extent(PictureSize::Thumb(ThumbSize::Large))
|
||||
.extent(PictureSize::Sample(ThumbSize::Large))
|
||||
.show(ui);
|
||||
});
|
||||
});
|
||||
@@ -599,7 +599,7 @@ fn choose(ui: &mut Ui, salt: &'static str, label: Label, options: &[(&str, &str)
|
||||
/// A radio group over `options` setting `value`.
|
||||
fn choose_radio(ui: &mut Ui, label: Label, options: &[(&str, &str)], value: &mut String) {
|
||||
let current = index_of(options, value).unwrap_or(0);
|
||||
if let Some((v, _)) = radios(ui, label, &labels(options), current).and_then(|at| options.get(at)) {
|
||||
if let Some((v, _)) = radios_in_section(ui, label, &labels(options), current).and_then(|at| options.get(at)) {
|
||||
*value = v.to_string();
|
||||
}
|
||||
}
|
||||
@@ -829,6 +829,12 @@ mod tests {
|
||||
assert_eq!(h.state_mut().run("list.define", json!({})).unwrap(), json!({"pending": "defineList"}));
|
||||
h.run_steps(2);
|
||||
|
||||
// The sheet fills the Preview image's rect, which is larger than the 80 × 48 icon-side thumbnail it once
|
||||
// shrank to (#7977).
|
||||
let preview = egui_kittest::kittest::Queryable::get_by_role_and_label(&h, egui::accesskit::Role::Image, "Preview").rect();
|
||||
assert!(preview.width() > 80.0 && preview.height() > 48.0, "{theme}: the preview is {preview:?}");
|
||||
let is_sheet = |r: egui::Rect| (r.width() - preview.width()).abs() <= 2.0 && (r.height() - preview.height()).abs() <= 2.0;
|
||||
|
||||
let mut shapes = Vec::new();
|
||||
collect_shapes(&h.output().shapes, &mut shapes);
|
||||
|
||||
@@ -836,11 +842,7 @@ mod tests {
|
||||
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)
|
||||
}
|
||||
egui::Shape::Rect(r) if r.fill == egui::Color32::WHITE && is_sheet(r.rect) => Some(r),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
@@ -850,13 +852,7 @@ mod tests {
|
||||
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)
|
||||
}
|
||||
egui::Shape::Rect(r) if r.stroke.color == egui::Color32::from_gray(160) && is_sheet(r.rect) => Some(r),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
@@ -873,4 +869,39 @@ mod tests {
|
||||
assert!(!black_text_samples.is_empty(), "{theme}: preview text samples must override text color with black");
|
||||
}
|
||||
}
|
||||
|
||||
/// The By author colour choice's swatch shows the first three author colours side by side, as it did before the
|
||||
/// port, not the first author's colour alone.
|
||||
#[test]
|
||||
fn track_changes_options_by_author_swatch_shows_three_author_colours() {
|
||||
use egui_kittest::kittest::Queryable as _;
|
||||
fn fills_in(shape: &egui::Shape, area: egui::Rect, out: &mut Vec<egui::Color32>) {
|
||||
match shape {
|
||||
egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| fills_in(shape, area, out)),
|
||||
egui::Shape::Rect(rect) if area.contains_rect(rect.rect) => out.push(rect.fill),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut h = harness(app());
|
||||
h.state_mut().run("review.trackingOptions", json!({})).unwrap();
|
||||
h.run_steps(3);
|
||||
// The Insertions row's colour field, at By author.
|
||||
// The first node named "Color: By author" is the field's body, or its arrow once the row's `Field` names the body
|
||||
// "Color:" (#7525); the field is every part of either name in that row.
|
||||
let first = h.query_all_by_label("Color: By author").next().expect("a By author colour field").rect();
|
||||
let field = h
|
||||
.query_all_by_label("Color: By author")
|
||||
.chain(h.query_all_by_label("Color:"))
|
||||
.map(|node| node.rect())
|
||||
.filter(|rect| (rect.center().y - first.center().y).abs() < 1.0)
|
||||
.fold(first, |all, rect| all.union(rect));
|
||||
let mut fills = Vec::new();
|
||||
for clipped in &h.output().shapes {
|
||||
fills_in(&clipped.shape, field, &mut fills);
|
||||
}
|
||||
for k in 0..3 {
|
||||
let c = wordcraft_layout::display::revision_color(k);
|
||||
assert!(fills.contains(&egui::Color32::from_rgb(c.0, c.1, c.2)), "author {k}'s colour is in the swatch: {fills:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ use std::borrow::Cow;
|
||||
|
||||
use craft::behavior::{Mixed, SelectionChange, keyed};
|
||||
use craft::color_ui::ui::ColorPickerTab;
|
||||
use craft::pages::ui::table::{BorderEdges, EdgeKey, EdgeLook, EdgePicker, SampleArea};
|
||||
use craft::pages::ui::table::{BorderEdges, EdgeKey, EdgeLook, EdgePicker, EdgeSize, SampleArea};
|
||||
use craft::text::ui::DocUnit;
|
||||
use craft::text::ui::ruler::{TabAlign as UiAlign, TabLeader as UiLeader, TabStop as UiStop};
|
||||
use craft::text::ui::tabs_dialog::{MAX_STOPS, TabStopsDialog, TabStopsResult};
|
||||
@@ -14,6 +14,7 @@ use craft::theme::Srgba;
|
||||
use craft::ui::choice::{Checkbox, Radio, RadioGroup};
|
||||
use craft::ui::contract::{Bind, CollectionEvent, Entry, FieldLayout, Props as _, Show as _, ShowCollection as _, ShowContainer as _, SideLabel};
|
||||
use craft::ui::dialog::DialogId;
|
||||
use craft::ui::display::Text;
|
||||
use craft::ui::form::Field;
|
||||
use craft::ui::layout_components::{Row, Stack};
|
||||
use craft::ui::patterns::form_dialogs::FormCx;
|
||||
@@ -25,7 +26,7 @@ use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Map, Value, json};
|
||||
use wordcraft_doc::props::{Border, BorderStyle, Borders, Rgb, TabAlign, TabLeader, TabStop};
|
||||
|
||||
use super::host::{Asks, ChildAnswer, DialogHooks, Keyed, Settle, WordForm, open_form, open_with};
|
||||
use super::host::{Asks, ChildAnswer, DialogHooks, Keyed, Settle, WordForm, captioned, open_form, open_with};
|
||||
use crate::WordApp;
|
||||
use crate::colors::{AutoFace, ColorFieldEmpty, Palette, color_field};
|
||||
use crate::options::unit_kind;
|
||||
@@ -60,6 +61,23 @@ pub(super) fn color_row(
|
||||
}
|
||||
}
|
||||
|
||||
/// `color_row` with `label` drawn beside it as plain text. Not a `Field`: its label scope would rename the split button
|
||||
/// "Color:" and drop the colour it speaks ("Color: Automatic").
|
||||
fn captioned_color_row(
|
||||
ui: &mut Ui,
|
||||
key: &'static str,
|
||||
label: Label,
|
||||
value: &mut String,
|
||||
empty: &ColorFieldEmpty,
|
||||
palette: &Palette,
|
||||
asks: &mut Vec<Asks>,
|
||||
) {
|
||||
Row::new().show(ui, |ui, _| {
|
||||
Text::new(label.clone()).show(ui);
|
||||
color_row(ui, key, &label, value, empty, palette, asks);
|
||||
});
|
||||
}
|
||||
|
||||
/// A drop-down over `labels` under `label`, showing entry `current` (empty while it is `None`). The index of the entry
|
||||
/// picked in this pass.
|
||||
pub(super) fn pick(ui: &mut Ui, salt: &'static str, label: Label, labels: &[Label], current: Option<usize>, enabled: bool) -> Option<usize> {
|
||||
@@ -72,9 +90,18 @@ pub(super) fn pick(ui: &mut Ui, salt: &'static str, label: Label, labels: &[Labe
|
||||
.flatten()
|
||||
}
|
||||
|
||||
/// A radio group over `labels` under `label`, entry `current` chosen. The index chosen in this pass, when it is
|
||||
/// another one.
|
||||
/// A radio group over `labels` under a caption `label`, entry `current` chosen. The index chosen in this pass, when it
|
||||
/// is another one.
|
||||
pub(super) fn radios(ui: &mut Ui, label: Label, labels: &[Label], current: usize) -> Option<usize> {
|
||||
captioned(ui, label.clone(), |_, ui| radio_set(ui, label.clone(), labels, current)).flatten()
|
||||
}
|
||||
|
||||
/// `radios` with no caption: for a group inside a section that already carries its title.
|
||||
pub(super) fn radios_in_section(ui: &mut Ui, label: Label, labels: &[Label], current: usize) -> Option<usize> {
|
||||
radio_set(ui, label, labels, current)
|
||||
}
|
||||
|
||||
fn radio_set(ui: &mut Ui, label: Label, labels: &[Label], current: usize) -> Option<usize> {
|
||||
let mut at = current;
|
||||
RadioGroup::new(label, Bind::bound(&mut at)).show(ui, |ui, cx| {
|
||||
for (i, text) in labels.iter().enumerate() {
|
||||
@@ -481,7 +508,7 @@ fn lines(ui: &mut Ui, key: &'static str, l: &mut LineForm, area: SampleArea, fil
|
||||
l.style = *style;
|
||||
}
|
||||
let automatic = ColorFieldEmpty::Automatic { label: word(tl!("Automatic")), value: "", face: AutoFace::One(srgba(Rgb(0, 0, 0))) };
|
||||
color_row(ui, key, &word(tl!("Color:")), &mut l.color, &automatic, palette, asks);
|
||||
captioned_color_row(ui, key, word(tl!("Color:")), &mut l.color, &automatic, palette, asks);
|
||||
let names: Vec<Label> = WIDTHS.iter().map(|w| word(crate::i18n::fmt(tl!("{n} pt"), &[("n", &w.to_string())]))).collect();
|
||||
let current = WIDTHS.iter().position(|w| *w == l.width);
|
||||
if let Some(width) = pick(ui, "width", word(tl!("Width:")), &names, current, true).and_then(|at| WIDTHS.get(at)) {
|
||||
@@ -491,7 +518,7 @@ fn lines(ui: &mut Ui, key: &'static str, l: &mut LineForm, area: SampleArea, fil
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
let mut edges = l.edges(between);
|
||||
let sample = EdgeLook::sample(area, fill.map(srgba));
|
||||
let picker = EdgePicker::new(word(tl!("Preview")), Bind::bound(&mut edges)).look(sample);
|
||||
let picker = EdgePicker::new(word(tl!("Preview")), Bind::bound(&mut edges)).look(sample).preview(EdgeSize::Sample);
|
||||
let picker = if between { picker.paragraph() } else { picker };
|
||||
picker.show(ui);
|
||||
l.take_edges(edges, between);
|
||||
@@ -540,12 +567,12 @@ impl WordForm for BordersForm {
|
||||
Self::apply_to(ui, &mut self.whole_doc, word(tl!("This section")), word(tl!("Whole document")));
|
||||
}
|
||||
_ => {
|
||||
color_row(ui, "fill", &word(tl!("Fill")), &mut self.fill, &ColorFieldEmpty::NoColor, &palette, asks);
|
||||
captioned_color_row(ui, "fill", word(tl!("Fill")), &mut self.fill, &ColorFieldEmpty::NoColor, &palette, asks);
|
||||
// The same sample as the Borders tab shows, without the lines and not editable.
|
||||
let mut none = BorderEdges::default();
|
||||
let area = if self.fill_to_text { SampleArea::Text } else { SampleArea::Paragraph };
|
||||
let sample = EdgeLook::sample(area, Rgb::parse(&self.fill).map(srgba));
|
||||
EdgePicker::new(word(tl!("Preview")), Bind::bound(&mut none)).look(sample).enabled(false).show(ui);
|
||||
EdgePicker::new(word(tl!("Preview")), Bind::bound(&mut none)).look(sample).preview(EdgeSize::Sample).enabled(false).show(ui);
|
||||
Self::apply_to(ui, &mut self.fill_to_text, word(tl!("Paragraph")), word(tl!("Text")));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -116,12 +116,15 @@ impl WordForm for CaptionForm {
|
||||
let caption = Label::from(tl!("Caption:").to_string());
|
||||
if let Some(text) = Field::new(caption.clone())
|
||||
.show(ui, |ui, _| {
|
||||
TextField::new(caption.clone(), Bind::given(self.text.clone()))
|
||||
.prefix(Label::from(self.preview()))
|
||||
.placeholder(Label::from(tl!("Caption text").to_string()))
|
||||
.show(ui)
|
||||
.value()
|
||||
.cloned()
|
||||
ui.horizontal(|ui| {
|
||||
Text::new(Label::from(self.preview())).show(ui);
|
||||
TextField::new(caption.clone(), Bind::given(self.text.clone()))
|
||||
.placeholder(Label::from(tl!("Caption text").to_string()))
|
||||
.show(ui)
|
||||
.value()
|
||||
.cloned()
|
||||
})
|
||||
.inner
|
||||
})
|
||||
.inner
|
||||
.flatten()
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use craft::behavior::{Mixed, Selection, keyed};
|
||||
use craft::ui::contract::{Bind, Entry, SelectMode, Show as _, ShowCollection as _, ShowContainer as _};
|
||||
use craft::ui::dialog::DialogId;
|
||||
use craft::ui::display::Text;
|
||||
use craft::ui::form::Field;
|
||||
use craft::ui::list::{List, ListRow};
|
||||
use craft::ui::patterns::form_dialogs::FormCx;
|
||||
@@ -156,6 +157,7 @@ impl WordForm for CrossRefForm {
|
||||
let source = keyed(&which, |i: &usize| *i);
|
||||
let mut selection = self.selected.map_or_else(|| Selection::new(Vec::new(), None, None), Selection::single);
|
||||
let targets = &self.targets;
|
||||
Text::new(Label::from(tl!("For which item:").to_string())).show(ui);
|
||||
let _ = List::new(Label::from(tl!("For which item:").to_string()))
|
||||
.max_rows(8)
|
||||
.select(SelectMode::Single)
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user