Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fbe5c3017a | ||
|
|
4deb338b44 | ||
|
|
0c6c377681 | ||
|
|
17c163c425 | ||
|
|
3b77539db2 | ||
|
|
98e71c1478 | ||
|
|
0483b212b7 | ||
|
|
06642d07c7 | ||
|
|
6fbf780789 | ||
|
|
57fb4544f2 | ||
|
|
eeeb31d85f | ||
|
|
5796c665b9 | ||
|
|
e74e627a38 | ||
|
|
e9286c9487 | ||
|
|
b7057e56f6 | ||
|
|
784e4c3c35 | ||
|
|
188be727b7 | ||
|
|
05dc3214ea | ||
|
|
72ca96a27c | ||
|
|
f83d554322 | ||
|
|
0f4e80aedd | ||
|
|
bab08b77e1 | ||
|
|
2b407facd0 | ||
|
|
b7819874c8 | ||
|
|
9cf6a33374 | ||
|
|
29bb5a4f44 | ||
|
|
aae46e1274 | ||
|
|
b322c3d816 | ||
|
|
64e297ca57 | ||
|
|
ca8feb71aa | ||
|
|
73f42fd607 | ||
|
|
ff11882e9d | ||
|
|
5687172000 | ||
|
|
0b5d4df261 | ||
|
|
6cbd8114d7 | ||
|
|
760cb852a2 | ||
|
|
59803ced07 | ||
|
|
fddd892b2d | ||
|
|
c98954d755 | ||
|
|
5d2153c15d | ||
|
|
257b81ec8f | ||
|
|
7883de796d | ||
|
|
59269a4e0e | ||
|
|
f9aaa12da7 | ||
|
|
cc9ad91d2a | ||
|
|
f1810cb01d | ||
|
|
0151061ccd | ||
|
|
992937e5dd | ||
|
|
e51fbe2e4b | ||
|
|
3a3523f172 | ||
|
|
bfc6fbc46b | ||
|
|
bdbb15e197 | ||
|
|
b7b978b05c | ||
|
|
66f603931f | ||
|
|
e7647ca261 | ||
|
|
c3e38cef0b | ||
|
|
5de0344173 | ||
|
|
b67d4723cf | ||
|
|
c7009c675f | ||
|
|
274cf67ac2 | ||
|
|
0c6a8ea18d | ||
|
|
a0f82451e3 | ||
|
|
5e129ac951 | ||
|
|
62391d8aa3 | ||
|
|
44719ece99 | ||
|
|
9d78c95517 | ||
|
|
6ea92c6b93 | ||
|
|
7905692c1f | ||
|
|
7416d36aeb | ||
|
|
6c6ac698ca | ||
|
|
68c024a624 | ||
|
|
104556e47d | ||
|
|
765abcc790 | ||
|
|
a44dc74fc0 | ||
|
|
77a530b179 | ||
|
|
4e00d00779 | ||
|
|
26b1d89ad2 | ||
|
|
a272715194 | ||
|
|
ff90488655 | ||
|
|
bc629b7a4f | ||
|
|
954750790b | ||
|
|
f587bcb95a | ||
|
|
b068e1a538 | ||
|
|
9ab9f2f874 | ||
|
|
231a09761c | ||
|
|
dc12b22371 | ||
|
|
b77c55c028 | ||
|
|
09465c9fc4 | ||
|
|
c8ecea24cf | ||
|
|
2a09d78972 | ||
|
|
b163c0568d | ||
|
|
8ed5ddd47b | ||
|
|
ea8f665f20 | ||
|
|
c30777bf2a | ||
|
|
34b79b33db | ||
|
|
f89c52c428 | ||
|
|
4da5534eb8 | ||
|
|
afe332b225 | ||
|
|
3ebf69481a | ||
|
|
ab014b8fe5 | ||
|
|
7951466b8b | ||
|
|
d26c7375ff | ||
|
|
e3b742f75a | ||
|
|
f847159a29 | ||
|
|
9409b2fd79 | ||
|
|
e2f001b946 | ||
|
|
dc5d27cded | ||
|
|
c56825487f | ||
|
|
4343683da8 | ||
|
|
1f65a8e588 | ||
|
|
bfc160809c | ||
|
|
3639389be3 | ||
|
|
37d03a1eb4 | ||
|
|
7fa77df595 | ||
|
|
9e68fdb76a | ||
|
|
d63de66920 | ||
|
|
c179a31619 | ||
|
|
6e92d33e07 | ||
|
|
bee50afd8f | ||
|
|
a1a3b53f74 | ||
|
|
8ff9bdb1a1 | ||
|
|
694ac7810d | ||
|
|
1441c64970 | ||
|
|
3b94750945 | ||
|
|
376411a22b | ||
|
|
932f5b4748 | ||
|
|
011a46c677 | ||
|
|
4239458948 | ||
|
|
b4219f9745 | ||
|
|
37e5849e58 |
@@ -2,4 +2,15 @@
|
||||
# (#6537) and `cargo fmt --check` still passed, so the gate could not see it. Normalise on add.
|
||||
* text=auto
|
||||
|
||||
craft-i18n.rev text eol=lf
|
||||
craft-i18n.rev text eol=lf
|
||||
|
||||
# These model sources and generated tables have byte hashes recorded in model/README.md.
|
||||
# Keep checkout bytes stable even when core.autocrlf=true.
|
||||
crates/validate/model/extract_content_model.py text eol=lf
|
||||
crates/validate/model/generate_model.py text eol=lf
|
||||
crates/validate/model/content_model_v2.json text eol=lf
|
||||
crates/validate/model/content_model_v2_transitional.json text eol=lf
|
||||
crates/validate/model/content_model_dml_v2.json text eol=lf
|
||||
crates/validate/model/content_model_dml_v2_transitional.json text eol=lf
|
||||
crates/validate/src/model.rs text eol=lf
|
||||
crates/validate/model/extract_model_lf.py text eol=lf
|
||||
|
||||
@@ -2,13 +2,13 @@
|
||||
"schema": "craft-nightly-release-policy/v3",
|
||||
"repository": "storytold/wordcraft",
|
||||
"repository_id": 1408489772,
|
||||
"producer_workflow_id": null,
|
||||
"producer_workflow_id": 429734489,
|
||||
"producer_workflow_path": ".github/workflows/nightly.yml",
|
||||
"producer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea",
|
||||
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@605d58766e8f536564da8fc81d3676ac86816dea",
|
||||
"producer_tooling_revision": "bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3",
|
||||
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3",
|
||||
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
|
||||
"signer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea",
|
||||
"release_branch": "release",
|
||||
"signer_tooling_revision": "bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3",
|
||||
"release_branch": "nightly-signer",
|
||||
"manual_actors": [
|
||||
"bflatastic",
|
||||
"dylanmtaylor",
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
name: Dispatch release-ref nightly
|
||||
|
||||
# Transport only, never authorization. No checkout, payload parsing or release environment.
|
||||
on:
|
||||
workflow_run:
|
||||
workflows: [WordCraft unsigned nightly]
|
||||
types: [completed]
|
||||
branches: [main]
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
dispatch:
|
||||
# SOURCE PREPARATION: literal off until immutable shared tooling and policy qualification.
|
||||
if: >-
|
||||
false && github.repository == 'storytold/wordcraft' &&
|
||||
github.event_name == 'workflow_run'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
permissions:
|
||||
actions: write
|
||||
steps:
|
||||
- name: Dispatch only the exact completed producer run and attempt
|
||||
shell: python
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
import json
|
||||
import os
|
||||
import urllib.request
|
||||
|
||||
def require(value, message):
|
||||
if not value:
|
||||
raise RuntimeError(message)
|
||||
|
||||
# These filters reduce noise; the protected signer-branch validator repeats admission
|
||||
# against authenticated API metadata and required attestation/quality evidence.
|
||||
require(os.environ.get('GITHUB_REPOSITORY') == 'storytold/wordcraft', 'wrong repository')
|
||||
require(os.environ.get('GITHUB_EVENT_NAME') == 'workflow_run', 'wrong event')
|
||||
with open(os.environ['GITHUB_EVENT_PATH'], encoding='utf-8') as stream:
|
||||
event = json.load(stream)
|
||||
require(event.get('action') == 'completed', 'producer is not complete')
|
||||
require(event.get('repository', {}).get('full_name') == 'storytold/wordcraft', 'wrong event repository')
|
||||
producer = event.get('workflow_run', {})
|
||||
require(producer.get('head_repository', {}).get('full_name') == 'storytold/wordcraft', 'foreign producer')
|
||||
require(producer.get('path') == '.github/workflows/nightly.yml', 'wrong producer path')
|
||||
require(producer.get('head_branch') == 'main', 'wrong producer branch')
|
||||
require(producer.get('status') == 'completed' and producer.get('conclusion') == 'success', 'producer did not succeed')
|
||||
# First scheduled attempt only; reviewed manual/re-run authority belongs to release policy.
|
||||
require(producer.get('event') == 'schedule', 'not an automatic scheduled producer')
|
||||
run_id, attempt = producer.get('id'), producer.get('run_attempt')
|
||||
require(type(run_id) is int and run_id > 0, 'invalid producer run id')
|
||||
require(type(attempt) is int and attempt == 1, 'invalid automatic producer attempt')
|
||||
body = json.dumps({'ref': 'refs/heads/nightly-signer', 'inputs': {
|
||||
'producer_run_id': str(run_id), 'producer_run_attempt': str(attempt)
|
||||
}}).encode('utf-8')
|
||||
request = urllib.request.Request(
|
||||
'https://api.github.com/repos/storytold/wordcraft/actions/workflows/nightly-sign.yml/dispatches',
|
||||
data=body, method='POST', headers={
|
||||
'Authorization': 'Bearer ' + os.environ['GH_TOKEN'],
|
||||
'Accept': 'application/vnd.github+json',
|
||||
'Content-Type': 'application/json',
|
||||
'X-GitHub-Api-Version': '2022-11-28',
|
||||
'User-Agent': 'wordcraft-nightly-dispatch'
|
||||
})
|
||||
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
raise RuntimeError('dispatch redirects are forbidden')
|
||||
# One bounded request, no retry: duplicate transport is not publication authority.
|
||||
with urllib.request.build_opener(NoRedirect()).open(request, timeout=20) as response:
|
||||
require(response.status == 204, 'dispatch was not accepted')
|
||||
print('Dispatched producer run/attempt to the release-ref validator; not a signing result.')
|
||||
@@ -1,7 +1,8 @@
|
||||
name: WordCraft release-ref nightly signer
|
||||
|
||||
# Enabled for supervised manual dispatch on release. Main/release contents must match.
|
||||
# A reusable callee does not change context; this must be a real top-level release dispatch.
|
||||
# Enabled for supervised manual dispatch on the dedicated nightly-signer branch, which only ever
|
||||
# fast-forwards to reviewed main commits (never the stable release branch).
|
||||
# A reusable callee does not change context; this must be a real top-level signer-branch dispatch.
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
@@ -22,21 +23,37 @@ concurrency:
|
||||
|
||||
jobs:
|
||||
release:
|
||||
# Actual context guards: official repository, manual dispatch, real release branch.
|
||||
# Actual context guards: official repository, manual dispatch, real nightly-signer branch.
|
||||
if: >-
|
||||
github.repository == 'storytold/wordcraft' &&
|
||||
github.event_name == 'workflow_dispatch' &&
|
||||
github.ref == 'refs/heads/release' && github.ref_type == 'branch'
|
||||
github.ref == 'refs/heads/nightly-signer' && github.ref_type == 'branch'
|
||||
permissions:
|
||||
contents: write
|
||||
actions: read
|
||||
checks: read
|
||||
attestations: write
|
||||
id-token: write
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@605d58766e8f536564da8fc81d3676ac86816dea
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
|
||||
with:
|
||||
tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea
|
||||
tooling-revision: bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
|
||||
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 and export keys in its signing step.
|
||||
# callee job may bind the existing release environment (which trusts release and
|
||||
# nightly-signer) and export keys in its signing step.
|
||||
|
||||
@@ -22,13 +22,13 @@ jobs:
|
||||
actions: read
|
||||
attestations: write
|
||||
id-token: write
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@605d58766e8f536564da8fc81d3676ac86816dea
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
|
||||
with:
|
||||
tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea
|
||||
tooling-revision: bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
|
||||
app-name: wordcraft
|
||||
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
# One producer run builds every listed platform for one all-or-nothing release. The pin is the
|
||||
# craft-common-actions main commit that merged #339 (bounded lineage compares), on top of the
|
||||
# Linux/macOS signer (#342).
|
||||
# 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"]'
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
name: Notify Services on Release Change
|
||||
|
||||
on:
|
||||
release:
|
||||
types:
|
||||
- published
|
||||
- unpublished
|
||||
- created
|
||||
- edited
|
||||
- deleted
|
||||
- prereleased
|
||||
- released
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
notify:
|
||||
uses: storytold/craft-common-actions/.github/workflows/notify-services.yml@main
|
||||
secrets:
|
||||
ARTCRAFT_SERVICES_DISPATCH_TOKEN: ${{ secrets.ARTCRAFT_SERVICES_DISPATCH_TOKEN }}
|
||||
@@ -70,3 +70,5 @@ jobs:
|
||||
run: bash packaging/linux/nightly-arch-tar-test.sh
|
||||
- name: Render and run the Nightly tar launcher (no build)
|
||||
run: bash packaging/linux/nightly-package-test.sh
|
||||
- name: Check the flat Nightly tar's shared template launcher (no build)
|
||||
run: bash packaging/linux/nightly-tar-launch-test.sh
|
||||
|
||||
@@ -74,5 +74,6 @@ WordCraft is a Rust word processor targeting Microsoft Word parity, for macOS, W
|
||||
- Attribution: `ATTRIBUTION.md`, a row per asset file, checked by `cargo xtask assets`. Icons are our own SVG set in `crates/ui-egui/icons/` (draw new icons there); sample content is in `crates/engine/src/sample.rs` and `cmd/design.rs`.
|
||||
- Fonts and language data come from other repositories as optional build inputs: craft-fonts through `CRAFT_FONTS_DIR`, and craft-i18n's `language-data/` through `CRAFT_I18N_DIR` (pinned by `craft-i18n.rev`; CI checks it out). Without craft-i18n the app builds with fallback spelling and no pattern hyphenation, so proofing tests need it. Proprietary font requests use installed fonts or the open substitutes in `crates/fonts/src/word.rs`. Layout tests use the fixed fonts in `assets/fonts/` ([docs/testing.md](docs/testing.md)).
|
||||
- Run: `cargo run --release -p wordcraft -- --sample --control 7981` starts the app with a sample document and the control channel. It takes JSON lines on `127.0.0.1:7981`: authenticate once per connection with the token from `~/.config/wordcraft/control-key.local-7981` (macOS: `~/Library/Application Support/WordCraft/`), `{"id":1,"method":"auth","params":{"token":"…"}}`, then send requests without a token; methods are in `crates/ui-egui/src/control.rs`, docs in `docs/control-protocol.md` (Token). Headless screenshots: `cargo run --release -p wordcraft-ui-egui --example ui_shot -- script.jsonl`. CLI: `wordcraft-cli convert|run|commands|parity`. MCP: `wordcraft-cli mcp --automation-read-root DIR --automation-write-root DIR` (both required; `--connect` is refused until the app confines its control channel, #3695), see `docs/mcp.md`.
|
||||
- Headless column ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): `cargo xtask parity` marks a catalog feature `headless: yes` only when its command is in the engine registry that `wordcraft-cli` and the MCP server load (never a `ui.*` id). A missing feature takes its `no`/`partial` value and `reach:` (`window`, `os` or `engine-gap`) from `HEADLESS` in `crates/engine/src/catalog.rs`, or reads `unknown`. When a command lands, delete its mark; `headless_marks_are_current` fails on a stale one.
|
||||
- Notes and progress: `plan/` is an optional gitignored notebook. Committed: `ROADMAP.md` (progress log), `docs/gaps.md`, `docs/roadmap.md`, `docs/target-app-parity.md`, `docs/architecture.md` and the parity checklists.
|
||||
- Contributor credits: `docs/contributors.md`.
|
||||
|
||||
@@ -202,7 +202,7 @@ The UI icons are SVG files in `crates/ui-egui/icons/`, one row each below. Gener
|
||||
| `crates/ui-egui/icons/insertLeft.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
|
||||
| `crates/ui-egui/icons/insertRight.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
|
||||
| `crates/ui-egui/icons/interfaceTheme.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
|
||||
| `crates/ui-egui/icons/italic.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
|
||||
| `crates/ui-egui/icons/italic.svg` | WordCraft contributors | original: redrawn for #7694 | MIT OR Apache-2.0 | UI icon |
|
||||
| `crates/ui-egui/icons/justify.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
|
||||
| `crates/ui-egui/icons/labels.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
|
||||
| `crates/ui-egui/icons/language.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
|
||||
@@ -339,6 +339,7 @@ The UI icons are SVG files in `crates/ui-egui/icons/`, one row each below. Gener
|
||||
| `crates/ui-egui/icons/size.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
|
||||
| `crates/ui-egui/icons/smartArt.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
|
||||
| `crates/ui-egui/icons/smartArtColors.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
|
||||
| `crates/ui-egui/icons/smartArtLayouts.svg` | WordCraft contributors | original: drawn for WordCraft in the style of the code-drawn icon set (#7149) | MIT OR Apache-2.0 | UI icon |
|
||||
| `crates/ui-egui/icons/sort.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
|
||||
| `crates/ui-egui/icons/sources.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
|
||||
| `crates/ui-egui/icons/spaceAfter.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
|
||||
@@ -358,6 +359,8 @@ The UI icons are SVG files in `crates/ui-egui/icons/`, one row each below. Gener
|
||||
| `crates/ui-egui/icons/table.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
|
||||
| `crates/ui-egui/icons/tableOfAuthorities.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
|
||||
| `crates/ui-egui/icons/tableOfFigures.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
|
||||
| `crates/ui-egui/icons/tableStyleOptions.svg` | WordCraft contributors | original: drawn for WordCraft in the style of the code-drawn icon set (#7149) | MIT OR Apache-2.0 | UI icon |
|
||||
| `crates/ui-egui/icons/tableStyles.svg` | WordCraft contributors | original: drawn for WordCraft in the style of the code-drawn icon set (#7149) | MIT OR Apache-2.0 | UI icon |
|
||||
| `crates/ui-egui/icons/textBox.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
|
||||
| `crates/ui-egui/icons/textBoxLink.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
|
||||
| `crates/ui-egui/icons/textBoxUnlink.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
|
||||
@@ -375,7 +378,7 @@ The UI icons are SVG files in `crates/ui-egui/icons/`, one row each below. Gener
|
||||
| `crates/ui-egui/icons/trackChanges.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
|
||||
| `crates/ui-egui/icons/transform.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
|
||||
| `crates/ui-egui/icons/translate.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
|
||||
| `crates/ui-egui/icons/underline.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
|
||||
| `crates/ui-egui/icons/underline.svg` | WordCraft contributors | original: redrawn for #7694 | MIT OR Apache-2.0 | UI icon |
|
||||
| `crates/ui-egui/icons/undo.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
|
||||
| `crates/ui-egui/icons/unlinkCitations.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
|
||||
| `crates/ui-egui/icons/update.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
|
||||
@@ -395,3 +398,35 @@ The UI icons are SVG files in `crates/ui-egui/icons/`, one row each below. Gener
|
||||
| craft-fonts (optional build input, not files in this repo): BIZ UDPGothic, BIZ UDMincho, Shippori Mincho, Noto Sans CJK SC, Noto Sans Arabic | see https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md | embedded only when built with `CRAFT_FONTS_DIR` (all official releases) | OFL-1.1 | Japanese and Chinese UI, Japanese document fallback |
|
||||
| craft-i18n (optional build input, not files in this repo): the interface translations | see https://github.com/storytold/craft-i18n/blob/main/ATTRIBUTION.md, which credits every translator of WordCraft's former in-repo catalogs (`crates/ui-egui/src/i18n/*.tsv`, migrated at `wordcraft@806a945`) | embedded only when built with `CRAFT_I18N_DIR`, at the commit in `craft-i18n.rev` (all official releases) | MIT OR Apache-2.0 | Interface languages other than English; clean-room translations from the English interface labels |
|
||||
| craft-i18n Language data (optional build input, not files in this repo): the spelling word lists and hyphenation patterns (`language-data/`: the Moby Hyphenator II list and our patterns for English, `en-extra.txt`, `en-variants.txt`, `ru-extra.txt`, and the hyph-utf8 German, Polish, Portuguese and Italian patterns) | see the Language data section of https://github.com/storytold/craft-i18n/blob/main/ATTRIBUTION.md (authors, upstream sources with SHA-256, licences); moved there from `assets/hyphenation/` and `assets/spelling/` byte for byte | embedded by craft-proof (storytold/craft-libs) only when built with `CRAFT_I18N_DIR`, at the commit in `craft-i18n.rev` (all official releases) | Public Domain / CC0-1.0, MIT, BSD-3-Clause, MIT OR Apache-2.0 (per file; see NOTICE) | Spelling and hyphenation; without it English spelling falls back to an installed Hunspell English or craft-proof's built-in Moby list, and pattern hyphenation is off |
|
||||
| `crates/validate/corpus/calibration/00-control.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: valid control |
|
||||
| `crates/validate/corpus/calibration/01-not-zip.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; contains no picture; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: PKG-NOT-ZIP defect fixture |
|
||||
| `crates/validate/corpus/calibration/02-dup-entry.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: PKG-DUP-ENTRY defect fixture |
|
||||
| `crates/validate/corpus/calibration/03-case-collision.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: PKG-CASE-COLLISION defect fixture |
|
||||
| `crates/validate/corpus/calibration/04-no-content-types.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: PKG-NO-CONTENT-TYPES defect fixture |
|
||||
| `crates/validate/corpus/calibration/05-no-main.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: PKG-NO-MAIN defect fixture |
|
||||
| `crates/validate/corpus/calibration/06-ct-undeclared.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: CT-UNDECLARED defect fixture |
|
||||
| `crates/validate/corpus/calibration/07-ct-main-type.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: CT-MAIN-TYPE defect fixture |
|
||||
| `crates/validate/corpus/calibration/08-xml-malformed-main.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: XML-MALFORMED (main part) defect fixture |
|
||||
| `crates/validate/corpus/calibration/09-xml-malformed-unused.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: XML-MALFORMED (unreferenced part) defect fixture |
|
||||
| `crates/validate/corpus/calibration/10-xml-undeclared-prefix.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: XML-UNDECLARED-PREFIX defect fixture |
|
||||
| `crates/validate/corpus/calibration/11-rel-dup-id.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: REL-DUP-ID defect fixture |
|
||||
| `crates/validate/corpus/calibration/12-rel-dangling.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: REL-DANGLING defect fixture |
|
||||
| `crates/validate/corpus/calibration/13-rel-typed.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: REL-TYPED defect fixture |
|
||||
| `crates/validate/corpus/calibration/14-comment-dup.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: ID-COMMENT-DUP defect fixture |
|
||||
| `crates/validate/corpus/calibration/15-comment-ref.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: REF-COMMENT defect fixture |
|
||||
| `crates/validate/corpus/calibration/16-docpr-dup.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: ID-DOCPR-DUP defect fixture |
|
||||
| `crates/validate/corpus/calibration/17-bookmark-dup.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: ID-BOOKMARK-DUP defect fixture |
|
||||
| `crates/validate/corpus/calibration/18-revision-dup.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: ID-REVISION-DUP defect fixture |
|
||||
| `crates/validate/corpus/calibration/19-note-ref.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: REF-NOTE defect fixture |
|
||||
| `crates/validate/corpus/calibration/20-header-ref.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: REF-HEADER defect fixture |
|
||||
| `crates/validate/corpus/calibration/21-style-ref.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: REF-STYLE defect fixture |
|
||||
| `crates/validate/corpus/calibration/22-fld-unbalanced.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: FLD-UNBALANCED defect fixture |
|
||||
| `crates/validate/corpus/calibration/23-tc-no-p.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: STRUCT-TC-NO-P defect fixture |
|
||||
| `crates/validate/corpus/calibration/24-deltext.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: STRUCT-DELTEXT defect fixture |
|
||||
| `crates/validate/corpus/calibration/25-move-unpaired.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is the fixed 1×1 PNG constant defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: STRUCT-MOVE-UNPAIRED defect fixture |
|
||||
| `crates/validate/corpus/calibration/26-media-magic.docx` | WordCraft contributors | generated by `crates/validate/corpus/make_calibration.py` (original synthetic document; embedded picture is a fixed JPEG-header stub defined in the script; no third-party content) | MIT OR Apache-2.0, like the code | wordcraft-validate calibration corpus: MEDIA-MAGIC defect fixture |
|
||||
| `crates/validate/model/content_model_v2.json` | WordCraft contributors | generated by `crates/validate/model/extract_content_model.py` from the ECMA-376 Part 1 (5th ed.) Strict schemas (public specification; archive URL and SHA-256 in `crates/validate/model/README.md`); the schemas themselves are not copied | MIT OR Apache-2.0, like the code (element/type content models extracted from a public specification) | wordcraft-validate grammar tables: WML, Strict |
|
||||
| `crates/validate/model/content_model_v2_transitional.json` | WordCraft contributors | generated by `crates/validate/model/extract_content_model.py` from the ECMA-376 Part 4 (5th ed.) Transitional schemas (public specification; archive URL and SHA-256 in `crates/validate/model/README.md`); the schemas themselves are not copied | MIT OR Apache-2.0, like the code (element/type content models extracted from a public specification) | wordcraft-validate grammar tables: WML, Transitional |
|
||||
| `crates/validate/model/content_model_dml_v2.json` | WordCraft contributors | generated by `crates/validate/model/extract_content_model.py --profile dml` from the ECMA-376 Part 1 (5th ed.) Strict schemas (public specification; archive URL and SHA-256 in `crates/validate/model/README.md`); the schemas themselves are not copied | MIT OR Apache-2.0, like the code (element/type content models extracted from a public specification) | wordcraft-validate grammar tables: DrawingML, Strict |
|
||||
| `crates/validate/model/content_model_dml_v2_transitional.json` | WordCraft contributors | generated by `crates/validate/model/extract_content_model.py --profile dml` from the ECMA-376 Part 4 (5th ed.) Transitional schemas (public specification; archive URL and SHA-256 in `crates/validate/model/README.md`); the schemas themselves are not copied | MIT OR Apache-2.0, like the code (element/type content models extracted from a public specification) | wordcraft-validate grammar tables: DrawingML, Transitional |
|
||||
| `crates/validate/src/model.rs` | WordCraft contributors | generated by `crates/validate/model/generate_model.py` from the four `crates/validate/model/content_model_*.json` tables above and the `ST_NumberFormat` enumeration of the ECMA-376 Part 1 Strict `wml.xsd` | MIT OR Apache-2.0, like the code (data extracted from a public specification) | wordcraft-validate grammar tables compiled into the crate |
|
||||
|
||||
@@ -247,6 +247,15 @@ version = "1.0.104"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
|
||||
|
||||
[[package]]
|
||||
name = "arbitrary"
|
||||
version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed"
|
||||
dependencies = [
|
||||
"derive_arbitrary",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "arboard"
|
||||
version = "3.7.0"
|
||||
@@ -1183,7 +1192,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"craft-automation",
|
||||
"craft-behavior",
|
||||
@@ -1221,10 +1230,20 @@ dependencies = [
|
||||
"toml",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-appkit"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"block2 0.6.2",
|
||||
"objc2-app-kit 0.3.2",
|
||||
"objc2-foundation 0.3.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-atomic"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"rustix 1.1.6",
|
||||
]
|
||||
@@ -1232,7 +1251,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-automation"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"craft-behavior",
|
||||
@@ -1257,7 +1276,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-behavior"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"accesskit",
|
||||
"bitflags 2.13.2",
|
||||
@@ -1275,7 +1294,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-browse"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-docpath",
|
||||
@@ -1293,12 +1312,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-cfb"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
|
||||
[[package]]
|
||||
name = "craft-cloud-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"egui",
|
||||
]
|
||||
@@ -1306,7 +1325,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-cms"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"md-5",
|
||||
"rayon",
|
||||
@@ -1315,12 +1334,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-codepage"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
|
||||
[[package]]
|
||||
name = "craft-color"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
@@ -1328,7 +1347,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-color-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-cms",
|
||||
@@ -1348,7 +1367,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-control"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"getrandom 0.3.4",
|
||||
"serde",
|
||||
@@ -1358,7 +1377,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-dds"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"rayon",
|
||||
]
|
||||
@@ -1366,7 +1385,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-dialogs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"block2 0.6.2",
|
||||
"craft-atomic",
|
||||
@@ -1391,7 +1410,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-doc-binary"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"craft-cfb",
|
||||
@@ -1408,7 +1427,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-docpath"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
@@ -1416,7 +1435,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-docx"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"chrono",
|
||||
@@ -1436,7 +1455,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-draw"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-color-ui",
|
||||
@@ -1455,7 +1474,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-drawingml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"craft-xml",
|
||||
@@ -1467,7 +1486,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-flow"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"craft-wordmodel",
|
||||
"image",
|
||||
@@ -1477,7 +1496,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-font-catalog"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"fontique",
|
||||
"harfrust 0.13.3",
|
||||
@@ -1492,7 +1511,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-font-manager"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-font-catalog",
|
||||
@@ -1505,17 +1524,27 @@ dependencies = [
|
||||
"egui",
|
||||
"log",
|
||||
"serde",
|
||||
"skrifa 0.44.0",
|
||||
"skrifa 0.47.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-font-os-windows"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"windows-registry",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-font-store"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"cap-primitives",
|
||||
"craft-atomic",
|
||||
"craft-font-catalog",
|
||||
"craft-font-os-windows",
|
||||
"flate2",
|
||||
"log",
|
||||
"ruzstd",
|
||||
@@ -1527,12 +1556,13 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
"toml",
|
||||
"ureq",
|
||||
"wuff",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-font-subset"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"brotli 9.1.3",
|
||||
"harfbuzz-subset-sys",
|
||||
@@ -1545,7 +1575,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-fonts-build"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"craft-font-subset",
|
||||
]
|
||||
@@ -1553,7 +1583,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-gpu"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"egui-wgpu",
|
||||
"log",
|
||||
@@ -1565,7 +1595,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-host"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"craft-i18n",
|
||||
@@ -1578,7 +1608,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-html"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"craft-codepage",
|
||||
"craft-flow",
|
||||
@@ -1591,7 +1621,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-i18n"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"fixed_decimal",
|
||||
@@ -1619,7 +1649,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-image-codecs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"craft-dds",
|
||||
"craft-jpeg",
|
||||
@@ -1646,7 +1676,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-imaging"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-color-ui",
|
||||
@@ -1664,7 +1694,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-jpeg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
@@ -1672,7 +1702,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-keymap"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"craft-host",
|
||||
"craft-i18n",
|
||||
@@ -1687,7 +1717,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-latex"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"craft-flow",
|
||||
"craft-math",
|
||||
@@ -1698,7 +1728,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-markdown"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"craft-flow",
|
||||
"craft-html",
|
||||
@@ -1708,7 +1738,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-math"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"craft-xml",
|
||||
"roxmltree",
|
||||
@@ -1718,7 +1748,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-mcp-server"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
@@ -1726,7 +1756,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-menu"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -1744,7 +1774,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-metadata"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"brotli-decompressor 6.3.1",
|
||||
"chrono",
|
||||
@@ -1756,7 +1786,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-metafile"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"image",
|
||||
@@ -1767,7 +1797,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-mime"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"chardetng",
|
||||
"chrono",
|
||||
@@ -1778,7 +1808,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-odf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"base64 0.23.1",
|
||||
@@ -1804,7 +1834,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ods"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"craft-odf",
|
||||
"craft-sheet",
|
||||
@@ -1815,7 +1845,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-offcrypto"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"base64 0.23.1",
|
||||
@@ -1832,7 +1862,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-opc"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"craft-xml",
|
||||
"craft-zip",
|
||||
@@ -1843,7 +1873,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-pages"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-keymap",
|
||||
@@ -1859,7 +1889,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-pdf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"krilla",
|
||||
"serde",
|
||||
@@ -1869,7 +1899,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-platform"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"arboard",
|
||||
"async-channel",
|
||||
@@ -1905,7 +1935,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-print"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -1929,7 +1959,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-proof"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"log",
|
||||
"miniz_oxide 0.9.1",
|
||||
@@ -1940,7 +1970,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-quit"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"dispatch2",
|
||||
"egui",
|
||||
@@ -1953,7 +1983,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-review"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"craft-behavior",
|
||||
@@ -1972,7 +2002,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-rtf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"craft-codepage",
|
||||
"craft-flow",
|
||||
@@ -1985,7 +2015,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-settings"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"craft-atomic",
|
||||
"craft-host",
|
||||
@@ -2002,17 +2032,17 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-sheet"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
|
||||
[[package]]
|
||||
name = "craft-ssip"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
|
||||
[[package]]
|
||||
name = "craft-svg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"craft-xml",
|
||||
"flate2",
|
||||
@@ -2029,7 +2059,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-table"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-keymap",
|
||||
@@ -2041,7 +2071,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-text"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2065,7 +2095,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-theme"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"craft-tracked",
|
||||
@@ -2080,7 +2110,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-theme-store"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"craft-atomic",
|
||||
"craft-behavior",
|
||||
@@ -2095,7 +2125,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-tiff"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
@@ -2105,7 +2135,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-time"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
@@ -2114,7 +2144,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-timeline"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-keymap",
|
||||
@@ -2129,12 +2159,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-tracked"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
|
||||
[[package]]
|
||||
name = "craft-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"craft-cloud-ui",
|
||||
"craft-ui-canvas",
|
||||
@@ -2148,7 +2178,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-canvas"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-i18n",
|
||||
@@ -2164,7 +2194,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-contract"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"accesskit",
|
||||
"craft-behavior",
|
||||
@@ -2202,7 +2232,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-macros"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"proc-macro-crate",
|
||||
"proc-macro2",
|
||||
@@ -2213,7 +2243,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-panels"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2231,7 +2261,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-patterns"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2252,7 +2282,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-shell"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2273,7 +2303,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-test-kit"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2284,7 +2314,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-widgets"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2303,7 +2333,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-update"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"craft-host",
|
||||
@@ -2326,13 +2356,13 @@ dependencies = [
|
||||
"verifysign",
|
||||
"winreg",
|
||||
"winsafe",
|
||||
"zip",
|
||||
"zip 9.1.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-web-api"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"js-sys",
|
||||
"serde_json",
|
||||
@@ -2343,7 +2373,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-web-host"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"craft-host",
|
||||
"craft-platform",
|
||||
@@ -2355,7 +2385,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-win32"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"winsafe",
|
||||
]
|
||||
@@ -2363,8 +2393,9 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-window"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"craft-appkit",
|
||||
"craft-atomic",
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2380,6 +2411,7 @@ dependencies = [
|
||||
"serde_json",
|
||||
"wayland-client",
|
||||
"winsafe",
|
||||
"x11rb",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2393,7 +2425,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-wordmodel"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"craft-math",
|
||||
@@ -2407,7 +2439,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-xls"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"craft-cfb",
|
||||
"craft-sheet",
|
||||
@@ -2420,7 +2452,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-xlsx"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"craft-drawingml",
|
||||
"craft-opc",
|
||||
@@ -2432,7 +2464,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"quick-xml 0.41.0",
|
||||
"serde",
|
||||
@@ -2442,11 +2474,11 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-zip"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"thiserror 2.0.21",
|
||||
"zip",
|
||||
"zip 9.1.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2580,6 +2612,17 @@ version = "0.5.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e"
|
||||
|
||||
[[package]]
|
||||
name = "derive_arbitrary"
|
||||
version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1b034bd7d5f032402a2479444dcc6f74e36a03f31854d41680fb240ef682a1ac"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "dify"
|
||||
version = "0.8.0"
|
||||
@@ -2760,7 +2803,7 @@ checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813"
|
||||
[[package]]
|
||||
name = "ecolor"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"emath",
|
||||
@@ -2769,7 +2812,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "eframe"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytemuck",
|
||||
@@ -2804,7 +2847,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
|
||||
dependencies = [
|
||||
"accesskit",
|
||||
"ahash",
|
||||
@@ -2823,7 +2866,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui-wgpu"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytemuck",
|
||||
@@ -2842,7 +2885,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui-winit"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
|
||||
dependencies = [
|
||||
"accesskit_winit",
|
||||
"arboard",
|
||||
@@ -2868,7 +2911,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui_extras"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"egui",
|
||||
@@ -2881,7 +2924,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui_glow"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"egui",
|
||||
@@ -2894,7 +2937,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui_kittest"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
|
||||
dependencies = [
|
||||
"dify",
|
||||
"eframe",
|
||||
@@ -2920,7 +2963,7 @@ checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"
|
||||
[[package]]
|
||||
name = "emath"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
]
|
||||
@@ -3001,7 +3044,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "epaint"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytemuck",
|
||||
@@ -3027,7 +3070,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "epaint_default_fonts"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
|
||||
|
||||
[[package]]
|
||||
name = "equivalent"
|
||||
@@ -3750,7 +3793,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
|
||||
[[package]]
|
||||
name = "hayro-cmap"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"brotli 8.0.4",
|
||||
"hayro-postscript",
|
||||
@@ -3759,7 +3802,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-interpret"
|
||||
version = "0.7.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"hayro-cmap",
|
||||
@@ -3777,7 +3820,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-jbig2"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"fearless_simd",
|
||||
"hayro-ccitt",
|
||||
@@ -3795,12 +3838,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-postscript"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
|
||||
[[package]]
|
||||
name = "hayro-syntax"
|
||||
version = "0.7.2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hayro-ccitt",
|
||||
@@ -4474,9 +4517,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "jpeg-encoder"
|
||||
version = "0.6.1"
|
||||
version = "0.7.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b454d911ac55068f53495488d8ccd0646eaa540c033a28ee15b07838afafb01f"
|
||||
checksum = "a0370574b86f7eca156b9f298392b5e69a23f8c86f3f865add60bbc2e79467a6"
|
||||
|
||||
[[package]]
|
||||
name = "js-sys"
|
||||
@@ -4529,7 +4572,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "krilla"
|
||||
version = "0.8.2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bumpalo",
|
||||
@@ -4668,7 +4711,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4"
|
||||
[[package]]
|
||||
name = "linesweeper"
|
||||
version = "0.5.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
dependencies = [
|
||||
"arrayvec",
|
||||
"kurbo",
|
||||
@@ -9004,6 +9047,7 @@ dependencies = [
|
||||
"wordcraft-geom",
|
||||
"wordcraft-mcp",
|
||||
"wordcraft-render",
|
||||
"wordcraft-validate",
|
||||
"wordcraft-zotero",
|
||||
]
|
||||
|
||||
@@ -9253,6 +9297,21 @@ dependencies = [
|
||||
"zbus",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wordcraft-validate"
|
||||
version = "0.18.1"
|
||||
dependencies = [
|
||||
"craft-image-codecs",
|
||||
"craft-tiff",
|
||||
"craft-xml",
|
||||
"png 0.18.1",
|
||||
"quick-xml 0.41.0",
|
||||
"rayon",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"zip 3.0.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wordcraft-web"
|
||||
version = "0.18.1"
|
||||
@@ -9736,6 +9795,20 @@ dependencies = [
|
||||
"syn 3.0.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zip"
|
||||
version = "3.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "12598812502ed0105f607f941c386f43d441e00148fce9dec3ca5ffb0bde9308"
|
||||
dependencies = [
|
||||
"arbitrary",
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
"indexmap",
|
||||
"memchr",
|
||||
"zopfli",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zip"
|
||||
version = "9.1.0"
|
||||
@@ -9764,6 +9837,18 @@ version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
|
||||
|
||||
[[package]]
|
||||
name = "zopfli"
|
||||
version = "0.8.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "aaf7fc5d30c28483d93805c4a5e12b05bbb52407fa67c5f8bd552374cd01fb11"
|
||||
dependencies = [
|
||||
"bumpalo",
|
||||
"crc32fast",
|
||||
"log",
|
||||
"simd-adler32",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zune-core"
|
||||
version = "0.5.3"
|
||||
@@ -9841,19 +9926,19 @@ dependencies = [
|
||||
[[patch.unused]]
|
||||
name = "egui_demo_lib"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
|
||||
|
||||
[[patch.unused]]
|
||||
name = "egui_inspection"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
|
||||
|
||||
[[patch.unused]]
|
||||
name = "egui_system_font_provider"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
|
||||
|
||||
[[patch.unused]]
|
||||
name = "hayro"
|
||||
version = "0.7.1"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b436ae992591173ce53fdb1314421ba2d8897e49#b436ae992591173ce53fdb1314421ba2d8897e49"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0b8bbaf4c842da2d47de7b3fddd7170ba6115541#0b8bbaf4c842da2d47de7b3fddd7170ba6115541"
|
||||
|
||||
@@ -37,26 +37,29 @@ 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 = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-ssip = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
wordcraft-proof = { package = "craft-proof", git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-ssip = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
wordcraft-engine = { path = "crates/engine" }
|
||||
wordcraft-mcp = { path = "crates/mcp" }
|
||||
wordcraft-zotero = { path = "crates/zotero" }
|
||||
wordcraft-control-key = { path = "crates/control-key" }
|
||||
wordcraft-ui-egui = { path = "crates/ui-egui" }
|
||||
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0", default-features = false }
|
||||
craft-ui-test-kit = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
wordcraft-validate = { path = "crates/validate" }
|
||||
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0", default-features = false }
|
||||
craft-ui-test-kit = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
|
||||
# foundation
|
||||
kurbo = { version = "0.13", features = ["serde"] }
|
||||
thiserror = "2"
|
||||
serde = { version = "1", features = ["derive", "rc"] }
|
||||
serde_json = { version = "1", features = ["float_roundtrip"] }
|
||||
quick-xml = "0.41"
|
||||
zip = { version = "3", default-features = false, features = ["deflate"] }
|
||||
log = "0.4"
|
||||
# All date/time conversion goes through chrono (no hand-rolled calendar code beyond the 400-year range extension; AGENTS.md).
|
||||
chrono = { version = "0.4.45", default-features = false, features = ["std"] }
|
||||
@@ -81,28 +84,28 @@ wuff = "0.2.9"
|
||||
brotli-decompressor = "5"
|
||||
vello_cpu = "0.2"
|
||||
image = { version = "0.25", default-features = false }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0", default-features = false, features = ["write"] }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0", default-features = false, features = ["write"] }
|
||||
|
||||
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0", features = ["doc"] }
|
||||
craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-flow = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-odf = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0", features = ["text"] }
|
||||
craft-markdown = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-html = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0", features = ["flow"] }
|
||||
craft-latex = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0", features = ["detect"] }
|
||||
craft-sheet = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0", features = ["doc"] }
|
||||
craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-flow = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-odf = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0", features = ["text"] }
|
||||
craft-markdown = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-html = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0", features = ["flow"] }
|
||||
craft-latex = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0", features = ["detect"] }
|
||||
craft-sheet = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", version = "=0.1.0" }
|
||||
# zlib streams (compressed metafile pictures in `.doc` drawings); already in the lock as a dependency of other crates.
|
||||
miniz_oxide = "0.9"
|
||||
cfb = "0.15"
|
||||
@@ -170,27 +173,27 @@ debug = 0
|
||||
# The framework's patches, which Cargo does not carry over to dependents: its vendored crates from craft-libs,
|
||||
# and the egui and winit forks it builds with.
|
||||
[patch.crates-io]
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49" }
|
||||
hayro = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541" }
|
||||
hayro = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
|
||||
|
||||
|
||||
@@ -66,3 +66,16 @@ _Avoid_: Tofu, box, notdef character
|
||||
A picture the document refers to that the output cannot include: its part is absent, its data
|
||||
cannot be decoded, its format is unsupported, or it is linked from outside the file.
|
||||
_Avoid_: Broken image, dropped image
|
||||
|
||||
## Windows
|
||||
|
||||
**Document window**:
|
||||
A top-level window showing one open document. A document can be shown in several document windows
|
||||
at once (View › New Window); each window shows exactly one.
|
||||
_Avoid_: Viewport (that is the framework's surface), root window, tab
|
||||
|
||||
**Save prompt**:
|
||||
The question "Save changes?" asked when the last document window showing a document with unsaved
|
||||
changes is about to close. It belongs to that window and appears there; while it is up, the other
|
||||
windows wait.
|
||||
_Avoid_: Close guard, save dialog, unsaved-changes dialog
|
||||
|
||||
@@ -19,6 +19,7 @@ wordcraft-engine = { workspace = true }
|
||||
wordcraft-render = { workspace = true }
|
||||
wordcraft-mcp = { workspace = true }
|
||||
wordcraft-zotero = { workspace = true }
|
||||
wordcraft-validate = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
sys-locale = "0.3"
|
||||
|
||||
|
||||
@@ -51,6 +51,7 @@ USAGE:
|
||||
documents and with {\"id\": N} makes one active
|
||||
wordcraft-cli commands [--json] list every command
|
||||
wordcraft-cli parity [--markdown] feature-catalog parity
|
||||
wordcraft-cli validate <file> [--json] structural integrity check (exit 0 pass, 1 fail, 2 incomplete, 3 usage/IO)
|
||||
wordcraft-cli mcp --automation-read-root DIR --automation-write-root DIR [--author NAME]
|
||||
MCP server on stdio, with a headless session.
|
||||
Both roots are required: the agent's commands read
|
||||
@@ -81,7 +82,7 @@ same output on every machine.
|
||||
";
|
||||
|
||||
/// The subcommands, in `USAGE` order; `--help` or `-h` after any of them prints `USAGE` (#968).
|
||||
const SUBCOMMANDS: &[&str] = &["convert", "info", "text", "inspect", "render", "run", "commands", "parity", "mcp", "zotero"];
|
||||
const SUBCOMMANDS: &[&str] = &["convert", "info", "text", "inspect", "render", "run", "commands", "parity", "validate", "mcp", "zotero"];
|
||||
|
||||
fn wants_help(cmd: &str, rest: &[String]) -> bool {
|
||||
SUBCOMMANDS.contains(&cmd) && rest.iter().any(|a| a == "--help" || a == "-h")
|
||||
@@ -118,7 +119,7 @@ fn open(path: &Path, password: Option<&str>) -> Result<Session, Failure> {
|
||||
|
||||
/// The commands that open a file, and which positional argument it is, excluding option values.
|
||||
/// `run` opens the value of `--file`.
|
||||
const OPENS_FILE: &[(&str, usize)] = &[("convert", 0), ("info", 0), ("text", 0), ("inspect", 0), ("render", 0), ("zotero", 1)];
|
||||
const OPENS_FILE: &[(&str, usize)] = &[("convert", 0), ("info", 0), ("text", 0), ("inspect", 0), ("render", 0), ("validate", 0), ("zotero", 1)];
|
||||
|
||||
/// The arguments as text. Only the file the command opens may have a name that isn't valid Unicode,
|
||||
/// such as a Latin-1 one (#1440): it comes back as the path to open, and lossy among the arguments.
|
||||
@@ -367,6 +368,8 @@ const RUN_OPTIONS: &[OptionSpec] = &[
|
||||
];
|
||||
const COMMANDS_OPTIONS: &[OptionSpec] = &[OptionSpec { name: "--json", takes_value: false }];
|
||||
const PARITY_OPTIONS: &[OptionSpec] = &[OptionSpec { name: "--markdown", takes_value: false }];
|
||||
const VALIDATE_OPTIONS: &[OptionSpec] = &[OptionSpec { name: "--json", takes_value: false }];
|
||||
|
||||
/// Why `mcp` won't start unconfined (shared rule 18, #7124).
|
||||
const MCP_NEEDS_ROOTS: &str = "mcp: give both --automation-read-root DIR and --automation-write-root DIR: an agent's \
|
||||
commands may read only inside the read root and write only inside the write root (the same folder may be both)";
|
||||
@@ -391,8 +394,10 @@ enum Failure {
|
||||
/// A real error, reported on stderr with a failing exit status.
|
||||
Error(String),
|
||||
/// Whoever read stdout closed it (`wordcraft-cli commands --json | head`): there is nobody left
|
||||
/// to write to, so stop quietly and exit 0 like other command-line tools.
|
||||
/// to write to. Most commands exit 0; validation retains its verdict status.
|
||||
StdoutClosed,
|
||||
/// The subcommand has already written its output and decided its own exit status (`validate`).
|
||||
Status(u8),
|
||||
/// `convert --strict` refused: the text for stderr (the report's lines, then its JSON line).
|
||||
/// Exit status 3.
|
||||
Strict(String),
|
||||
@@ -403,6 +408,7 @@ impl fmt::Display for Failure {
|
||||
match self {
|
||||
Failure::Error(e) => f.write_str(e),
|
||||
Failure::StdoutClosed => f.write_str("stdout closed"),
|
||||
Failure::Status(code) => write!(f, "exit {code}"),
|
||||
Failure::Strict(report) => f.write_str(report),
|
||||
}
|
||||
}
|
||||
@@ -717,7 +723,7 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
|
||||
for c in s.registry.all() {
|
||||
writeln!(o, "{:<32} {:<36} {:<24} {}", c.id, c.label, c.shortcut, c.location)?;
|
||||
}
|
||||
Ok(())
|
||||
writeln!(o, "{:<32} Structural integrity check", "validate")
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -731,6 +737,7 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
|
||||
write_stdout(|o| writeln!(o, "{}", serde_json::to_string_pretty(&p).unwrap_or_default()))
|
||||
}
|
||||
}
|
||||
"validate" => run_validate(file.as_deref(), &rest),
|
||||
"mcp" => {
|
||||
let (roots, rest) = automation_roots("mcp", &rest)?;
|
||||
// Refused with or without a value, before the option check, so `--connect=…` gets this refusal rather than
|
||||
@@ -882,6 +889,17 @@ fn parity_markdown(p: &Value) -> String {
|
||||
for t in p["tabs"].as_array().cloned().unwrap_or_default() {
|
||||
s += &format!("| {} | {} | {} |\n", t["tab"].as_str().unwrap_or(""), t["live"], t["total"]);
|
||||
}
|
||||
let h = &p["headless"];
|
||||
s += &format!(
|
||||
"\n**Headless ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): {} yes, {} no (window {}, os {}, engine-gap {}), {} partial, {} unknown.** A feature is `headless: yes` when its command is in the engine registry that `wordcraft-cli` and the MCP server load, so every live feature above is `yes`; the missing ones carry the hand mark from `HEADLESS` in `crates/engine/src/catalog.rs`, or `unknown`.\n",
|
||||
h["yes"],
|
||||
h["no"]["window"].as_u64().unwrap_or(0) + h["no"]["os"].as_u64().unwrap_or(0) + h["no"]["engine-gap"].as_u64().unwrap_or(0),
|
||||
h["no"]["window"],
|
||||
h["no"]["os"],
|
||||
h["no"]["engine-gap"],
|
||||
h["partial"],
|
||||
h["unknown"]
|
||||
);
|
||||
s += "\n## Missing\n\n";
|
||||
for t in p["tabs"].as_array().cloned().unwrap_or_default() {
|
||||
let m = t["missing"].as_array().cloned().unwrap_or_default();
|
||||
@@ -897,6 +915,129 @@ fn parity_markdown(p: &Value) -> String {
|
||||
s
|
||||
}
|
||||
|
||||
/// `validate`: exactly one positional path (batch mode does not exist yet, so a surplus operand is
|
||||
/// a usage error rather than a silently ignored second file). `file` is the preserved operand, so a
|
||||
/// file name that is not valid Unicode still reaches the validator.
|
||||
fn run_validate(file: Option<&Path>, rest: &[String]) -> Result<(), Failure> {
|
||||
if let Err(e) = validate_options("validate", rest, VALIDATE_OPTIONS) {
|
||||
eprintln!("wordcraft-cli: {e}");
|
||||
return Err(Failure::Status(3));
|
||||
}
|
||||
let paths = positionals(rest, VALIDATE_OPTIONS);
|
||||
if paths.len() != 1 {
|
||||
eprintln!("wordcraft-cli: validate takes exactly one file\n\n{USAGE}");
|
||||
return Err(Failure::Status(3));
|
||||
}
|
||||
let path = file.unwrap_or_else(|| Path::new(paths[0]));
|
||||
let report = match wordcraft_validate::validate_path(path) {
|
||||
Ok(report) => report,
|
||||
Err(e) => {
|
||||
eprintln!("wordcraft-cli: {}: {e}", path.display());
|
||||
return Err(Failure::Status(3));
|
||||
}
|
||||
};
|
||||
let written = if rest.iter().any(|a| a == "--json") {
|
||||
let json = serde_json::to_string_pretty(&report).unwrap_or_default();
|
||||
write_stdout(|o| writeln!(o, "{json}"))
|
||||
} else {
|
||||
write_stdout(|o| write_validate_report(o, &report))
|
||||
};
|
||||
match written {
|
||||
// A reader closing early must not turn a FAIL or INCOMPLETE verdict into PASS.
|
||||
Ok(()) | Err(Failure::StdoutClosed) => {}
|
||||
Err(error) => {
|
||||
eprintln!("wordcraft-cli: {error}");
|
||||
return Err(Failure::Status(3));
|
||||
}
|
||||
}
|
||||
match report.verdict {
|
||||
wordcraft_validate::Verdict::Pass => Ok(()),
|
||||
wordcraft_validate::Verdict::Fail => Err(Failure::Status(1)),
|
||||
wordcraft_validate::Verdict::Incomplete => Err(Failure::Status(2)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Write a `validate` report for people: the verdict, then one line per finding
|
||||
/// (`SEVERITY RULE [part] message`), then the coverage notes.
|
||||
fn write_validate_report(o: &mut std::io::StdoutLock<'static>, report: &wordcraft_validate::Report) -> std::io::Result<()> {
|
||||
o.write_all(render_validate_report(report).as_bytes())
|
||||
}
|
||||
|
||||
/// Render a `validate` report for people. Document-controlled text — a ZIP entry name flowing into
|
||||
/// a finding part or coverage note — is escaped so a name cannot end its line or drive the
|
||||
/// terminal; printable text, including Unicode, is left as written.
|
||||
///
|
||||
/// The `--json` form is not escaped by hand; it is the validator's own `serde_json` serialization.
|
||||
/// `serde_json` escapes `U+0000`–`U+001F`, `"` and `\`; C1 controls such as `U+009B` and the bidi
|
||||
/// embeddings/overrides (`U+202A`–`U+202E`, `U+2066`–`U+2069`) are emitted raw. So a control or bidi
|
||||
/// run carried by a ZIP entry name survives into the JSON text; JSON is only safe because a
|
||||
/// *parser* takes the string value as data. If that text is printed directly to a terminal, the raw
|
||||
/// C1/bidi run reaches the terminal exactly as it would from any other text, so the JSON form is
|
||||
/// not a terminal-safe rendering. Only the human report below escapes those characters, and it does
|
||||
/// so to defend the terminal; keeping the JSON byte-for-byte the validator's own serialization is
|
||||
/// why its escaping is left to `serde_json`.
|
||||
fn render_validate_report(report: &wordcraft_validate::Report) -> String {
|
||||
let mut out = format!("{}\n", verdict_label(report.verdict));
|
||||
for f in &report.findings {
|
||||
let severity = severity_label(f.severity);
|
||||
match &f.part {
|
||||
Some(part) => out.push_str(&format!("{severity} {} [{}] {}\n", f.rule, escape_report_text(part), escape_report_text(&f.message))),
|
||||
None => out.push_str(&format!("{severity} {} {}\n", f.rule, escape_report_text(&f.message))),
|
||||
}
|
||||
}
|
||||
for note in &report.coverage_notes {
|
||||
out.push_str(&format!("note: {}\n", escape_report_text(note)));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Escape the control and invisible-formatting characters that could spoof a report line, in the
|
||||
/// same escape *form* `escape_debug` uses (`\u{1b}`, `\n`); printable characters (including Unicode)
|
||||
/// are left untouched. The *selection* is a hand-picked set ([`is_invisible_format`] plus
|
||||
/// `char::is_control`), not `escape_debug`'s full non-printable set: it omits, for example, the
|
||||
/// U+E0000 tag block, U+FFF9–U+FFFB and the Hangul fillers. None of those can end a line or drive a
|
||||
/// terminal, which is the threat this guards against. Backslash is not escaped, so a name that
|
||||
/// literally contains the text `\u{1b}` prints exactly like an escaped ESC and the output is not
|
||||
/// injective.
|
||||
fn escape_report_text(s: &str) -> String {
|
||||
let mut out = String::with_capacity(s.len());
|
||||
for c in s.chars() {
|
||||
if c.is_control() || is_invisible_format(c) {
|
||||
out.extend(c.escape_debug());
|
||||
} else {
|
||||
out.push(c);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Invisible Unicode formatting characters and line/paragraph separators: no glyph, but they can
|
||||
/// alter how a terminal renders the rest of the line (`char::is_control` covers C0/C1 controls).
|
||||
fn is_invisible_format(c: char) -> bool {
|
||||
matches!(
|
||||
c,
|
||||
'\u{00ad}' | '\u{061c}' | '\u{180e}' | '\u{200b}'..='\u{200f}' | '\u{2028}'..='\u{202e}' | '\u{2060}'..='\u{206f}' | '\u{feff}'
|
||||
)
|
||||
}
|
||||
|
||||
/// Map a validation verdict enum to its human-readable uppercase display label.
|
||||
fn verdict_label(v: wordcraft_validate::Verdict) -> &'static str {
|
||||
match v {
|
||||
wordcraft_validate::Verdict::Pass => "PASS",
|
||||
wordcraft_validate::Verdict::Fail => "FAIL",
|
||||
wordcraft_validate::Verdict::Incomplete => "INCOMPLETE",
|
||||
}
|
||||
}
|
||||
|
||||
/// Map a validation severity enum to its human-readable uppercase display label.
|
||||
fn severity_label(s: wordcraft_validate::Severity) -> &'static str {
|
||||
match s {
|
||||
wordcraft_validate::Severity::Corrupt => "CORRUPT",
|
||||
wordcraft_validate::Severity::Error => "ERROR",
|
||||
wordcraft_validate::Severity::Warning => "WARNING",
|
||||
}
|
||||
}
|
||||
|
||||
/// The Launcher's Nightly bootstrap belongs to the desktop app: a CLI must not accept it, in the
|
||||
/// separate-token or `=` form, so a mis-routed launch fails loudly instead of editing stable data.
|
||||
fn launcher_profile_flag(args: &[OsString]) -> bool {
|
||||
@@ -920,6 +1061,7 @@ fn main() -> ExitCode {
|
||||
}
|
||||
match run(&args) {
|
||||
Ok(()) | Err(Failure::StdoutClosed) => ExitCode::SUCCESS,
|
||||
Err(Failure::Status(code)) => ExitCode::from(code),
|
||||
Err(Failure::Error(e)) => {
|
||||
eprintln!("wordcraft-cli: {e}");
|
||||
ExitCode::FAILURE
|
||||
|
||||
@@ -230,10 +230,12 @@ fn only_the_opened_file_may_be_other_than_unicode() {
|
||||
assert_eq!(ok(vec!["run".into(), "--print".into(), "--file".into(), latin1()]), Some(PathBuf::from(latin1())));
|
||||
assert_eq!(ok(vec!["info".into(), "in.docx".into()]), None);
|
||||
// Every command that opens a file reaches the open with it (no such file here), so
|
||||
// `OPENS_FILE` and the commands' own arguments agree.
|
||||
// `OPENS_FILE` and the commands' own arguments agree. `validate` takes exactly one path, so it
|
||||
// is checked separately below, together with its exit-3 usage status.
|
||||
let missing = || OsString::from_vec(b"/definitely/not/caf\xe9.docx".to_vec());
|
||||
let mut opening: Vec<Vec<OsString>> = OPENS_FILE
|
||||
.iter()
|
||||
.filter(|(cmd, _)| *cmd != "validate")
|
||||
.map(|(cmd, n)| [vec![(*cmd).into()], vec![OsString::from("refresh"); *n], vec![missing(), "out.png".into()]].concat())
|
||||
.collect();
|
||||
opening.push(vec!["run".into(), "--file".into(), missing()]);
|
||||
@@ -241,6 +243,7 @@ fn only_the_opened_file_may_be_other_than_unicode() {
|
||||
let e = run(&raw).unwrap_err().to_string();
|
||||
assert!(e.contains("No such file"), "{raw:?}: {e}");
|
||||
}
|
||||
assert!(matches!(run(&["validate".into(), missing()]), Err(Failure::Status(3))));
|
||||
for (raw, n) in [
|
||||
(vec!["zotero".into(), latin1(), "in.docx".into()], 2),
|
||||
(vec!["render".into(), "in.docx".into(), latin1()], 3),
|
||||
@@ -298,6 +301,7 @@ fn every_agent_entry_point_refuses_to_start_without_both_roots() {
|
||||
("run", NotAgent("runs the commands and script named on its command line, then exits")),
|
||||
("commands", NotAgent("lists the commands; touches no file")),
|
||||
("parity", NotAgent("prints the feature catalog; touches no file")),
|
||||
("validate", NotAgent("validates the one file named on its command line, then exits")),
|
||||
("mcp", Agent),
|
||||
("zotero", NotAgent("runs one named Zotero command; Zotero's replies edit citations and name no file")),
|
||||
];
|
||||
@@ -700,6 +704,114 @@ fn script_parse_resolves_paths_against_the_base() {
|
||||
assert_eq!(s.commands.len(), 1);
|
||||
}
|
||||
|
||||
/// Finding 3: a surplus operand is a usage error (exit 3) rejected in the operand check, before any
|
||||
/// file is validated, so a valid first path can no longer make `validate a.docx b.docx` print PASS.
|
||||
/// The two paths are DIFFERENT files and validating either one would return `Ok`; the code path
|
||||
/// returns `Status(3)` from the `paths.len() != 1` check before `validate_path` runs, so no file was
|
||||
/// validated to produce it. (A `Status(3)` on its own does not prove that — `validate` also returns
|
||||
/// it for an I/O error after a single valid operand reaches the validator — which is why the
|
||||
/// operand check, not the status, is what establishes the rejection happened first.)
|
||||
#[test]
|
||||
fn validate_rejects_missing_or_surplus_operands_without_validating() {
|
||||
let dir = std::env::temp_dir().join(format!("wc-cli-validate-args-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let first = dir.join("first.docx");
|
||||
let second = dir.join("second.docx");
|
||||
run(&args(&["run", "--template", "sample", "--save", &first.to_string_lossy()])).unwrap();
|
||||
run(&args(&["run", "--template", "sample", "--save", &second.to_string_lossy()])).unwrap();
|
||||
let (first, second) = (first.to_string_lossy().into_owned(), second.to_string_lossy().into_owned());
|
||||
assert_ne!(first, second, "the two operands must be different files");
|
||||
assert_eq!(run(&args(&["validate", &first])), Ok(()), "one valid path reports PASS");
|
||||
assert_eq!(
|
||||
run(&args(&["validate", &first, &second])),
|
||||
Err(Failure::Status(3)),
|
||||
"two different paths are a usage error; validating either would return Ok, so it validated neither"
|
||||
);
|
||||
assert_eq!(run(&args(&["validate"])), Err(Failure::Status(3)), "no path is a usage error");
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// Finding 4: `validate` is in `OPENS_FILE`, so a file name that is not valid Unicode reaches the
|
||||
/// validator by its preserved path rather than being rejected as a bad argument.
|
||||
/// APFS refuses invalid UTF-8 file names, so macOS covers native path handling without creating one.
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
#[test]
|
||||
fn validate_accepts_a_file_name_that_is_not_unicode() {
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
let dir = std::env::temp_dir().join(format!("wc-cli-validate-nonutf8-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let doc = wordcraft_doc::Document::from_text("Bonjour");
|
||||
let bytes = wordcraft_engine::io::save_bytes("x.docx", &doc).unwrap();
|
||||
let mut name = dir.as_os_str().to_os_string().into_vec();
|
||||
name.extend_from_slice(b"/caf\xe9.docx");
|
||||
let path = PathBuf::from(OsString::from_vec(name));
|
||||
std::fs::write(&path, bytes).unwrap();
|
||||
let raw = vec![OsString::from("validate"), path.into_os_string()];
|
||||
assert_eq!(run(&raw), Ok(()), "a non-Unicode path validates and reports PASS");
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// A real `.docx` archive with `extra` parts added: content types, package relationships, the main
|
||||
/// document and an empty main relationships part. Used to drive `validate_bytes` from real bytes so
|
||||
/// a document-controlled entry name is shown to reach the report the way production does.
|
||||
fn validate_fixture_zip(extra: &[(&str, &[u8])]) -> Vec<u8> {
|
||||
let mut w = craft_zip::Writer::new();
|
||||
w.add(
|
||||
"[Content_Types].xml",
|
||||
br#"<?xml version="1.0"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/></Types>"#,
|
||||
craft_zip::Compression::Stored,
|
||||
)
|
||||
.unwrap();
|
||||
w.add(
|
||||
"_rels/.rels",
|
||||
br#"<?xml version="1.0"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#,
|
||||
craft_zip::Compression::Stored,
|
||||
)
|
||||
.unwrap();
|
||||
w.add(
|
||||
"word/document.xml",
|
||||
br#"<?xml version="1.0"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body/></w:document>"#,
|
||||
craft_zip::Compression::Stored,
|
||||
)
|
||||
.unwrap();
|
||||
for (name, bytes) in extra {
|
||||
w.add(name, bytes, craft_zip::Compression::Stored).unwrap();
|
||||
}
|
||||
w.finish().unwrap()
|
||||
}
|
||||
|
||||
/// Finding 5: document-controlled text (a ZIP entry name) is escaped in the human report, while the
|
||||
/// JSON form keeps serde's escaping. The input is a real archive whose entry name carries a control
|
||||
/// character, so the test shows the name actually reaches the escaped fields (part and message).
|
||||
#[test]
|
||||
fn human_report_escapes_document_controlled_text() {
|
||||
let evil = "word/evil\u{1b}[2J.bin";
|
||||
let printable = "word/café—naïve.bin";
|
||||
let zip = validate_fixture_zip(&[(evil, b"x"), (printable, b"x")]);
|
||||
let report = wordcraft_validate::validate_bytes(&zip);
|
||||
// The undeclared part carries the raw control character in its part field and its message.
|
||||
let finding = report
|
||||
.findings
|
||||
.iter()
|
||||
.find(|f| f.rule == "CT-UNDECLARED" && f.part.as_deref() == Some(evil))
|
||||
.unwrap_or_else(|| panic!("expected CT-UNDECLARED at the control-character name: {:#?}", report.findings));
|
||||
assert!(finding.message.contains(evil), "the name reaches the message too: {:?}", finding.message);
|
||||
|
||||
let human = render_validate_report(&report);
|
||||
assert!(!human.contains('\u{1b}'), "no raw escape survives the human report: {human:?}");
|
||||
assert!(human.contains("\\u{1b}"), "{human:?}");
|
||||
assert!(human.contains("[2J"), "the surrounding name text is kept as written: {human:?}");
|
||||
// Printable Unicode in a name is left as written.
|
||||
assert!(human.contains(printable), "printable Unicode must be untouched: {human:?}");
|
||||
|
||||
// JSON output is unchanged by the human escaping: serde still emits the control character as
|
||||
// its own JSON escape.
|
||||
let json = serde_json::to_string(&report).unwrap();
|
||||
assert!(json.contains("\\u001b"), "{json}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invisible_characters_are_escaped_and_json_lines_still_parse_back() {
|
||||
let hidden = "a\u{ad}b\u{200b}c\u{200d}d\u{2060}e\u{2064}f\u{feff}g\u{e0041}h\u{e007f}i\u{85}j\u{202e}k";
|
||||
@@ -715,3 +827,18 @@ fn invisible_characters_are_escaped_and_json_lines_still_parse_back() {
|
||||
assert!(line.contains("\\ud800") || line.contains("\\udb40"), "{line}");
|
||||
assert_eq!(serde_json::from_str::<Value>(&line).unwrap(), value);
|
||||
}
|
||||
|
||||
/// Native non-Unicode paths survive argument parsing and reach the validator's I/O error path.
|
||||
/// No file is created: APFS refuses invalid UTF-8 names. The original bytes, rather than their
|
||||
/// lossy display spelling, must be retained even when options precede the operand.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn validate_preserves_a_non_unicode_path_without_creating_a_file() {
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
let raw_path = OsString::from_vec(b"wordcraft-nonexistent-caf\xe9.docx".to_vec());
|
||||
let raw = vec![OsString::from("validate"), OsString::from("--json"), raw_path.clone()];
|
||||
let (_, parsed) = text_args(&raw).unwrap();
|
||||
assert_eq!(parsed.as_deref(), Some(Path::new(&raw_path)));
|
||||
assert!(parsed.as_deref().unwrap().to_str().is_none());
|
||||
assert_eq!(run(&raw), Err(Failure::Status(3)), "native path reaches I/O handling");
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! A reader that closes stdout early (`wordcraft-cli commands --json | head`) must end the CLI
|
||||
//! quietly with exit 0, never with a panic (#508).
|
||||
//! Readers closing stdout early must not panic (#508). Listing and MCP stop quietly;
|
||||
//! validation retains its verdict exit status.
|
||||
|
||||
use std::io::{Read, Write};
|
||||
use std::process::{Command, Stdio};
|
||||
@@ -47,3 +47,65 @@ fn mcp_server_ends_cleanly_when_its_client_closes_stdout() {
|
||||
assert!(out.status.success(), "status {:?}, stderr: {stderr}", out.status);
|
||||
assert!(!stderr.contains("panicked"), "stderr: {stderr}");
|
||||
}
|
||||
|
||||
/// A closed reader preserves validation's verdict for both report formats, including INCOMPLETE.
|
||||
#[test]
|
||||
fn validate_closed_stdout_preserves_verdict() {
|
||||
let corpus = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../crates/validate/corpus/calibration");
|
||||
let sparse = std::env::temp_dir().join(format!("wordcraft-validate-closed-stdout-{}.docx", std::process::id()));
|
||||
// The validator checks metadata before reading inputs over its 512 MiB limit.
|
||||
std::fs::File::create(&sparse).unwrap().set_len((512 << 20) + 1).unwrap();
|
||||
let pass = sparse.with_file_name(format!("wordcraft-validate-closed-stdout-pass-{}.docx", std::process::id()));
|
||||
let bytes = wordcraft_engine::io::save_bytes("pass.docx", &wordcraft_doc::Document::from_text("Control")).unwrap();
|
||||
std::fs::write(&pass, bytes).unwrap();
|
||||
let mut results = Vec::new();
|
||||
for (fixture, expected) in [(pass.clone(), 0), (corpus.join("14-comment-dup.docx"), 1), (sparse.clone(), 2)] {
|
||||
for json in [false, true] {
|
||||
let mut open = cli();
|
||||
open.arg("validate").arg(&fixture);
|
||||
if json {
|
||||
open.arg("--json");
|
||||
}
|
||||
let open = open.output().unwrap();
|
||||
// Close the only reader before spawning, so even a short report reliably gets BrokenPipe.
|
||||
let (reader, writer) = std::io::pipe().unwrap();
|
||||
drop(reader);
|
||||
let mut closed = cli();
|
||||
closed.arg("validate").arg(&fixture).stdout(writer);
|
||||
if json {
|
||||
closed.arg("--json");
|
||||
}
|
||||
results.push((fixture.clone(), json, expected, open, closed.output().unwrap()));
|
||||
}
|
||||
}
|
||||
std::fs::remove_file(sparse).unwrap();
|
||||
std::fs::remove_file(pass).unwrap();
|
||||
for (fixture, json, expected, open, closed) in results {
|
||||
assert_eq!(open.status.code(), Some(expected), "{}, json={json}: {open:?}", fixture.display());
|
||||
assert_eq!(closed.status.code(), Some(expected), "{}, json={json}: {closed:?}", fixture.display());
|
||||
assert!(!String::from_utf8_lossy(&closed.stderr).contains("panicked"), "{closed:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Other report-write failures are I/O status 3; a child-only file-size limit forces EFBIG on stdout.
|
||||
#[test]
|
||||
fn validate_stdout_write_error_is_io_status() {
|
||||
let fixture = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../crates/validate/corpus/calibration/14-comment-dup.docx");
|
||||
let stdout = std::env::temp_dir().join(format!("wordcraft-validate-stdout-error-{}", std::process::id()));
|
||||
let mut results = Vec::new();
|
||||
for json in [false, true] {
|
||||
// Ignore SIGXFSZ so the write returns an error rather than terminating the CLI.
|
||||
let mut command = Command::new("/bin/sh");
|
||||
command.args(["-c", "trap '' XFSZ; ulimit -f 0 || exit 99; exec \"$@\"", "sh", env!("CARGO_BIN_EXE_wordcraft-cli"), "validate"]);
|
||||
command.arg(&fixture).stdout(std::fs::File::create(&stdout).unwrap());
|
||||
if json {
|
||||
command.arg("--json");
|
||||
}
|
||||
results.push((json, command.output().unwrap()));
|
||||
}
|
||||
std::fs::remove_file(stdout).unwrap();
|
||||
for (json, output) in results {
|
||||
assert_eq!(output.status.code(), Some(3), "json={json}: {output:?}");
|
||||
assert!(!String::from_utf8_lossy(&output.stderr).contains("panicked"), "{output:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,9 +37,9 @@ use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
|
||||
use craft::host::{FileError, Files, PickId, PickRequest, Picked, WriteIntent};
|
||||
use craft::host::{FileError, Files, PendingPick, PickId, PickRequest, Picked, WriteIntent};
|
||||
use craft::platform::browser_files::BrowserFiles;
|
||||
use craft::platform::open::{DropTarget, DroppedFile, IntakeSender};
|
||||
use craft::platform::open::{DroppedFile, IntakeSender};
|
||||
use craft::web_host::web::{FileData, Host, Message};
|
||||
use wordcraft_ui_egui::{Services, WordApp};
|
||||
|
||||
@@ -131,7 +131,7 @@ fn deliver_open(intake: &IntakeSender, name: &str, data: &FileData) {
|
||||
return;
|
||||
}
|
||||
let file = DroppedFile { path: None, name, bytes: Some(Arc::from(array.to_vec())) };
|
||||
intake.dropped(vec![file], DropTarget::Elsewhere);
|
||||
intake.dropped(vec![file]);
|
||||
}
|
||||
|
||||
/// The files of a hosted page: reads go to the browser's files, but a save goes to the host page,
|
||||
@@ -167,8 +167,8 @@ impl Files for HostedFiles {
|
||||
}
|
||||
}
|
||||
|
||||
fn pick_pending(&self) -> bool {
|
||||
self.inner.pick_pending()
|
||||
fn pending_pick(&self) -> Option<PendingPick> {
|
||||
self.inner.pending_pick()
|
||||
}
|
||||
|
||||
fn read(&self, path: &Path) -> Result<Vec<u8>, FileError> {
|
||||
@@ -192,7 +192,7 @@ impl Files for HostedFiles {
|
||||
let answer = match sent {
|
||||
// A Save As or first Save makes the page hold the document as this file: the answer
|
||||
// names it, and the next Save posts the name with `save_as` false.
|
||||
Ok(()) if request.save_as => Picked::Paths(vec![PathBuf::from(&name)]),
|
||||
Ok(()) if request.save_as => Picked::Saved { path: PathBuf::from(&name), file_type: None },
|
||||
// An overwrite of the opened file, or a copy: the document's file stays as it is.
|
||||
Ok(()) => Picked::Downloaded(name),
|
||||
Err(error) => Picked::Failed(error),
|
||||
|
||||
@@ -10,7 +10,7 @@ use craft::host::{Files, Host, Wake};
|
||||
use craft::platform::appearance::SystemReader;
|
||||
use craft::platform::browser_files::BrowserFiles;
|
||||
use craft::platform::clipboard::{Clipboard, ClipboardError, EventClipboard, Flavor, LateOffers, TEXT};
|
||||
use craft::platform::open::{DropTarget, DroppedFile, FileIntake, IntakeSender};
|
||||
use craft::platform::open::{DroppedFile, FileIntake, IntakeSender};
|
||||
use craft::print::spool::Spool;
|
||||
use craft::settings::SharedSettings;
|
||||
use craft::ui::InstallSpec;
|
||||
@@ -227,7 +227,7 @@ impl eframe::App for WebShell {
|
||||
match f.bytes_async().await {
|
||||
Ok(bytes) => {
|
||||
let file = DroppedFile { path: None, name, bytes: Some(Arc::from(bytes)) };
|
||||
sender.dropped(vec![file], DropTarget::Elsewhere);
|
||||
sender.dropped(vec![file]);
|
||||
}
|
||||
Err(e) => log::error!("couldn't read dropped file {name}: {e}"),
|
||||
}
|
||||
@@ -412,7 +412,7 @@ fn guard_unload(dirty: Rc<Cell<bool>>, files: Arc<BrowserFiles>) -> Result<(), S
|
||||
let window = web_sys::window().ok_or("no window")?;
|
||||
let on_unload = wasm_bindgen::closure::Closure::<dyn FnMut(web_sys::BeforeUnloadEvent)>::new(move |e: web_sys::BeforeUnloadEvent| {
|
||||
// A save still in the browser's picker hasn't written anything yet.
|
||||
if dirty.get() || files.pick_pending() {
|
||||
if dirty.get() || files.pending_pick().is_some() {
|
||||
e.prevent_default();
|
||||
// Older browsers ask only when `returnValue` is set.
|
||||
e.set_return_value("unsaved changes");
|
||||
|
||||
@@ -57,7 +57,7 @@ winresource = "0.1"
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
# Finder double-click, Open With, Dock drops and `open -a WordCraft letter.docx` arrive as a
|
||||
# kAEOpenDocuments Apple event, which winit doesn't handle (#27).
|
||||
craft = { workspace = true, features = ["platform-apple-events"] }
|
||||
craft = { workspace = true, features = ["platform-apple-events", "menu"] }
|
||||
|
||||
[target.'cfg(all(unix, not(target_os = "macos")))'.dependencies]
|
||||
winit = { version = "0.30", default-features = false, features = ["x11"] }
|
||||
|
||||
@@ -226,4 +226,64 @@ mod tests {
|
||||
|
||||
control.shut_down();
|
||||
}
|
||||
|
||||
/// Post-#7101 adaptation of `params_key_is_only_a_secret_for_auth` (#124, tracked under #7317 / #7729):
|
||||
/// `craft::automation::server` replaced legacy `"key"` / `params.key` secrets with one-time
|
||||
/// per-connection `auth` using `params.token` (`docs/control-protocol.md`, Token).
|
||||
#[test]
|
||||
fn params_token_is_only_a_secret_for_auth() {
|
||||
let (port, rx, control) = boot();
|
||||
|
||||
// Neither `params.token` on a non-`auth` method nor legacy `params.key` on
|
||||
// `document.inspect` or `auth` authenticates.
|
||||
for (id, line) in [
|
||||
(1, format!(r#"{{"id":1,"method":"document.inspect","params":{{"token":"{TOKEN}"}}}}"#)),
|
||||
(2, format!(r#"{{"id":2,"method":"document.inspect","params":{{"key":"{TOKEN}"}}}}"#)),
|
||||
(3, format!(r#"{{"id":3,"method":"auth","params":{{"key":"{TOKEN}"}}}}"#)),
|
||||
] {
|
||||
let mut c = Conn::open(port);
|
||||
assert_eq!(c.call(&line), serde_json::json!({"id": id, "ok": false, "error": "authentication required"}));
|
||||
assert!(c.closed());
|
||||
}
|
||||
assert!(rx.try_recv().is_err(), "refused requests must not reach the UI");
|
||||
|
||||
// Authenticate once with `params.token`; `params.key` and `params.token` on subsequent
|
||||
// non-`auth` methods are forwarded untouched as ordinary parameters.
|
||||
let mut c = Conn::open(port);
|
||||
let auth_resp = c.call(&format!(r#"{{"id":1,"method":"auth","params":{{"token":"{TOKEN}"}}}}"#));
|
||||
assert_eq!(auth_resp, serde_json::json!({"id": 1, "ok": true, "result": {"authenticated": true}}));
|
||||
|
||||
c.send(r#"{"id":2,"method":"ui.key","params":{"key":"Enter"}}"#);
|
||||
let req = answer(&rx);
|
||||
assert_eq!((req.method.as_str(), &req.params), ("ui.key", &serde_json::json!({"key": "Enter"})));
|
||||
let r = c.recv();
|
||||
assert_eq!((&r["ok"], &r["id"]), (&serde_json::json!(true), &serde_json::json!(2)));
|
||||
|
||||
c.send(r#"{"id":3,"method":"document.inspect","params":{"token":"ordinary"}}"#);
|
||||
let req = answer(&rx);
|
||||
assert_eq!((req.method.as_str(), &req.params), ("document.inspect", &serde_json::json!({"token": "ordinary"})));
|
||||
let r = c.recv();
|
||||
assert_eq!((&r["ok"], &r["id"]), (&serde_json::json!(true), &serde_json::json!(3)));
|
||||
drop(c);
|
||||
|
||||
control.shut_down();
|
||||
}
|
||||
|
||||
/// Post-#7101 adaptation of `a_wrong_key_is_refused_and_closed` (#124, tracked under #7317):
|
||||
/// wrong, short, and long `params.token` values are refused and close the connection without
|
||||
/// reaching the UI.
|
||||
#[test]
|
||||
fn a_wrong_token_is_refused_and_closed() {
|
||||
let (port, rx, control) = boot();
|
||||
let wrong = TOKEN.replace('0', "1");
|
||||
let long = format!("{TOKEN}0");
|
||||
for token in ["nope", wrong.as_str(), &TOKEN[..63], long.as_str()] {
|
||||
let mut c = Conn::open(port);
|
||||
let resp = c.call(&format!(r#"{{"id":1,"method":"auth","params":{{"token":"{token}"}}}}"#));
|
||||
assert_eq!(resp, serde_json::json!({"id": 1, "ok": false, "error": "authentication required"}), "{token}");
|
||||
assert!(c.closed(), "{token}");
|
||||
}
|
||||
assert!(rx.try_recv().is_err(), "refused auth attempts must not reach the UI");
|
||||
control.shut_down();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,6 +54,23 @@ pub fn identity() -> AppIdentity {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Every type the button claims is included in identity, and plain text/Markdown are never claimed.
|
||||
#[test]
|
||||
fn xdg_mime_sets_every_word_type_in_one_call() {
|
||||
let id = identity();
|
||||
assert_eq!(id.desktop_id, "ai.storyteller.wordcraft.desktop");
|
||||
assert_eq!(id.registered_name, "WordCraft");
|
||||
for t in [
|
||||
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||
"application/msword",
|
||||
"application/rtf",
|
||||
"application/vnd.oasis.opendocument.text",
|
||||
] {
|
||||
assert!(id.mime_types.iter().any(|a| a == t), "{t}");
|
||||
}
|
||||
assert!(!id.mime_types.iter().any(|a| a == "text/plain" || a == "text/markdown"), "plain text and Markdown are never claimed");
|
||||
}
|
||||
|
||||
/// Every type the button claims is one the desktop entry declares, or desktops ignore it.
|
||||
#[test]
|
||||
fn the_desktop_entry_declares_every_claimed_type() {
|
||||
|
||||
@@ -111,6 +111,14 @@ pub fn prepare(mut launch: Launch, validate: impl FnOnce(&Path) -> Result<PathBu
|
||||
Ok(launch)
|
||||
}
|
||||
|
||||
/// The root the Launcher hands a nightly on this platform, in that platform's own spelling: `C:\NightlyData\profiles\wordcraft`
|
||||
/// on Windows, `/nightly-data/profiles/wordcraft` elsewhere. A test that fixtures the hand-off uses this rather than a
|
||||
/// literal, because a root literal in the other platform's spelling is not absolute here and `parse` refuses it (#7849).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn launcher_root() -> &'static str {
|
||||
if cfg!(windows) { r"C:\NightlyData\profiles\wordcraft" } else { "/nightly-data/profiles/wordcraft" }
|
||||
}
|
||||
|
||||
/// Resolve the selected private root before the caller's first startup effect.
|
||||
pub fn validate_root(root: &Path) -> Result<PathBuf, String> {
|
||||
crate::profile_root::validate(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref(), crate::profile_root::probe_writable)
|
||||
@@ -124,7 +132,7 @@ mod tests {
|
||||
values.iter().map(OsString::from).collect()
|
||||
}
|
||||
fn absolute() -> &'static str {
|
||||
if cfg!(windows) { r"C:\NightlyData\profiles\wordcraft" } else { "/nightly-data/profiles/wordcraft" }
|
||||
super::launcher_root()
|
||||
}
|
||||
fn nightly() -> Vec<OsString> {
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"])
|
||||
@@ -164,6 +172,16 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// #7849: `/nightly-data/...` carries no drive prefix and so is not absolute on Windows, and `C:\...`
|
||||
/// is one relative name on Unix. A launch that carries the other platform's root spelling is refused
|
||||
/// instead of run against a directory this platform never meant.
|
||||
#[test]
|
||||
fn a_root_absolute_only_in_the_other_platforms_spelling_is_refused() {
|
||||
let foreign = if cfg!(windows) { "/nightly-data/profiles/wordcraft" } else { r"C:\NightlyData\profiles\wordcraft" };
|
||||
let argv = args(&["--launch-profile", VERSION, "--profile-root", foreign, "--"]);
|
||||
assert!(parse(argv).is_err(), "the other platform's root spelling must not stand in: {foreign}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_launcher_version_check_is_a_version_query_only_in_its_exact_form() {
|
||||
let pair = &["--launch-profile", VERSION, "--profile-root", absolute()];
|
||||
|
||||
@@ -20,6 +20,8 @@ mod build_flavor;
|
||||
mod control_server;
|
||||
mod default_apps;
|
||||
mod launch_profile;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod native_menu;
|
||||
mod nightly_session;
|
||||
mod prefs;
|
||||
mod process_identity;
|
||||
@@ -38,7 +40,7 @@ use craft::platform::appearance::SystemReader;
|
||||
use craft::platform::clipboard::{Clipboard, ClipboardImage, SystemClipboard};
|
||||
use craft::platform::default_app::{DefaultApp, DefaultAppError};
|
||||
use craft::platform::logs::{self, LogNames, crash};
|
||||
use craft::platform::open::{DropTarget, DroppedFile, FileIntake, IntakeSender};
|
||||
use craft::platform::open::{DroppedFile, FileIntake, IntakeSender};
|
||||
use craft::print::spool::Spool;
|
||||
use craft::settings::SharedSettings;
|
||||
use craft::ui::InstallSpec;
|
||||
@@ -54,6 +56,8 @@ use wordcraft_ui_egui::{Services, WordApp, prefs::Prefs};
|
||||
/// exit, the print spool it waits for at exit and the control server it stops at exit.
|
||||
struct App {
|
||||
app: WordApp,
|
||||
#[cfg(target_os = "macos")]
|
||||
native_menu: Option<craft::menu::NativeMenu>,
|
||||
/// The native panels behind the file service the app reaches through `Host::files`.
|
||||
panels: FilePanels,
|
||||
/// Feeds the files dropped on the window into the app's intake (`Services::intake`), the one
|
||||
@@ -71,10 +75,22 @@ struct App {
|
||||
}
|
||||
|
||||
impl App {
|
||||
fn before_input(&mut self, ctx: &egui::Context) {
|
||||
#[cfg(target_os = "macos")]
|
||||
if let Some(menu) = &mut self.native_menu {
|
||||
menu.poll(ctx);
|
||||
}
|
||||
embed::before_input(ctx, |out| self.app.frame_input(out));
|
||||
}
|
||||
|
||||
/// One frame's logic: what the OS asked, the app, its file dialogs, then the root window's close
|
||||
/// path. Without `frame` (a test over no window) the dialogs have no parent window.
|
||||
fn logic_pass(&mut self, ctx: &egui::Context, frame: Option<&eframe::Frame>) {
|
||||
self.app.logic(ctx);
|
||||
#[cfg(target_os = "macos")]
|
||||
if let Some(menu) = &mut self.native_menu {
|
||||
native_menu::update(menu, &mut self.app, ctx);
|
||||
}
|
||||
self.panels.pump_with(self.app.dialog_host_mut(), frame);
|
||||
// A quit that waits for nothing (the documents are answered for) closes the root window.
|
||||
if self.app.quit_requested && !self.app.printing.busy() {
|
||||
@@ -121,9 +137,9 @@ impl eframe::App for App {
|
||||
// Once per frame, before any pass; the files stay in `raw` for the runtime's own reading.
|
||||
let files = dropped_files(raw);
|
||||
if !files.is_empty() {
|
||||
self.drops.dropped(files, DropTarget::Elsewhere);
|
||||
self.drops.dropped(files);
|
||||
}
|
||||
embed::before_input(ctx, |out| self.app.frame_input(out));
|
||||
self.before_input(ctx);
|
||||
}
|
||||
fn logic(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) {
|
||||
self.logic_pass(ctx, Some(frame));
|
||||
@@ -273,6 +289,30 @@ fn build_sha() -> &'static str {
|
||||
option_env!("WORDCRAFT_BUILD_SHA").map(|s| s.get(..8).unwrap_or(s)).unwrap_or("dev")
|
||||
}
|
||||
|
||||
/// Split the command line at its first `--`: the options before it, the documents after it. The
|
||||
/// Launcher's nightly hand-off arrives as `--` followed by the file names (`launch_profile::parse`
|
||||
/// puts that separator first), so it is dropped here rather than opened as a document.
|
||||
fn split_at_delimiter(args: Vec<String>) -> (Vec<String>, Vec<String>) {
|
||||
match args.iter().position(|a| a == "--") {
|
||||
Some(i) => {
|
||||
let mut options = args;
|
||||
let files = options.split_off(i + 1);
|
||||
options.pop();
|
||||
(options, files)
|
||||
}
|
||||
None => (args, Vec::new()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The documents to open, in the order the command line gave them: the words before `--` that the flag
|
||||
/// loop kept, then the ones after it. The separator moves no document, and the Launcher, which sends
|
||||
/// none before it, opens just its own file names in order.
|
||||
fn documents_to_open(before: Vec<String>, after: Vec<String>) -> Vec<String> {
|
||||
let mut documents = before;
|
||||
documents.extend(after);
|
||||
documents
|
||||
}
|
||||
|
||||
/// The arguments as text, and apart the files whose names aren't valid Unicode, such as a Latin-1
|
||||
/// one (#1440). A `--control` port, a token or a token file that isn't is an error.
|
||||
fn text_args(arguments: Vec<std::ffi::OsString>) -> (Vec<String>, Vec<std::path::PathBuf>) {
|
||||
@@ -342,14 +382,24 @@ fn initialize_nightly_process_identity() -> Result<(), process_identity::Identit
|
||||
)
|
||||
}
|
||||
|
||||
/// Tell the person why a Launcher launch was refused, with a native message box on a desktop
|
||||
/// session (a Launcher start has no terminal to read standard error from).
|
||||
/// Whether a refusal may also open a native message box. Standard error always carries the reason;
|
||||
/// this only adds a box where one renders without the app's event loop. Never on macOS: rfd's alert
|
||||
/// there needs the AppKit run loop this start has not reached, so a refused nightly launch hung in
|
||||
/// an invisible modal instead of exiting (GridCraft Mac smoke, 2026-11-26).
|
||||
fn refusal_dialog(flavor: build_flavor::BuildFlavor, desktop_session: bool, macos: bool) -> bool {
|
||||
build_flavor::needs_native_error(flavor, desktop_session) && !macos
|
||||
}
|
||||
|
||||
/// Tell the person why a Launcher launch was refused: on standard error always, and with a native
|
||||
/// message box on a desktop session whose modal renders without the app's run loop (Windows,
|
||||
/// X11/Wayland) — a Launcher start has no terminal to read standard error from, and on macOS a modal
|
||||
/// before the event loop never appears.
|
||||
fn report_launch_profile_error(error: &str) {
|
||||
complain(format_args!("launch profile: {error}"));
|
||||
let desktop_session = cfg!(windows)
|
||||
|| cfg!(target_os = "macos")
|
||||
|| (cfg!(target_os = "linux") && ["DISPLAY", "WAYLAND_DISPLAY"].into_iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty())));
|
||||
if build_flavor::needs_native_error(build_flavor::COMPILED, desktop_session) {
|
||||
if refusal_dialog(build_flavor::COMPILED, desktop_session, cfg!(target_os = "macos")) {
|
||||
if let Err(identity) = initialize_nightly_process_identity() {
|
||||
complain(format_args!("launch profile: {identity}"));
|
||||
return;
|
||||
@@ -445,11 +495,16 @@ fn main() -> eframe::Result {
|
||||
log::error!("couldn't start again without another program's AppImage variables, so the self-update is off in this window: {e}");
|
||||
}
|
||||
let mut flags = ControlOptions::default();
|
||||
let mut files = Vec::new();
|
||||
let mut sample = false;
|
||||
let (args, other_files) = text_args(arguments);
|
||||
// Only macOS (Finder / LaunchServices) adds these; elsewhere `-NS…` could be a real file name.
|
||||
// The Launcher's own hand-off: `--` ends the options, so nothing after it is read as one and
|
||||
// the separator itself never becomes a document.
|
||||
let (args, after_separator) = split_at_delimiter(args);
|
||||
// Only macOS (Finder / LaunchServices) adds these, and only to the options: a Finder launch carries
|
||||
// no separator for them to sit after, and the Launcher starts the app itself, so a document whose
|
||||
// name merely looks like one of these (`-NSNotes.docx`) is still opened (#7849 review).
|
||||
let args = if cfg!(target_os = "macos") { without_launch_args(args) } else { args };
|
||||
let mut documents: Vec<String> = Vec::new();
|
||||
let mut bad_control: Option<Option<String>> = None;
|
||||
let mut missing_value: Option<&'static str> = None;
|
||||
let mut args = args.into_iter().peekable();
|
||||
@@ -492,9 +547,12 @@ fn main() -> eframe::Result {
|
||||
let _ = std::io::Write::write_all(&mut std::io::stdout(), USAGE.as_bytes());
|
||||
return Ok(());
|
||||
}
|
||||
_ => files.push(a),
|
||||
_ => documents.push(a),
|
||||
}
|
||||
}
|
||||
// After the loop, so a document before `--` opens before the ones after it (a stable launch's
|
||||
// `a.docx -- b.docx` used to be reversed when the Launcher's list was the one collected first).
|
||||
let files = documents_to_open(documents, after_separator);
|
||||
// After the loop, so `--version` later on the line still wins.
|
||||
if let Some(port) = bad_control {
|
||||
let got = port.map(|p| format!(", got {p:?}")).unwrap_or_default();
|
||||
@@ -756,6 +814,8 @@ fn main() -> eframe::Result {
|
||||
noticed_in_window.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
Ok(Box::new(App {
|
||||
#[cfg(target_os = "macos")]
|
||||
native_menu: native_menu::install(&ctx, &app),
|
||||
app,
|
||||
panels,
|
||||
drops,
|
||||
@@ -972,14 +1032,29 @@ mod smoke {
|
||||
let drops = intake.sender();
|
||||
let session = Session::new(wordcraft_doc::Document::new());
|
||||
let app = WordApp::new(session, services(spool.clone(), intake, false)).with_host(host).with_settings(settings.clone());
|
||||
Run { app: App { app, panels, drops, settings, spool, control: None, exit: None }, frames, ctx, sender }
|
||||
Run {
|
||||
app: App {
|
||||
#[cfg(target_os = "macos")]
|
||||
native_menu: None,
|
||||
app,
|
||||
panels,
|
||||
drops,
|
||||
settings,
|
||||
spool,
|
||||
control: None,
|
||||
exit: None,
|
||||
},
|
||||
frames,
|
||||
ctx,
|
||||
sender,
|
||||
}
|
||||
}
|
||||
|
||||
/// One frame as eframe runs it: the input hook once, the logic once, the UI per pass.
|
||||
/// Returns whether the frame sent a close command.
|
||||
fn step(&mut self, events: Vec<egui::Event>) -> bool {
|
||||
let Run { app, frames, ctx, .. } = self;
|
||||
embed::before_input(ctx, |out| app.app.frame_input(out));
|
||||
app.before_input(ctx);
|
||||
let mut first = true;
|
||||
frames.frame_without_input(events, |ui| {
|
||||
if std::mem::take(&mut first) {
|
||||
@@ -1002,7 +1077,7 @@ mod smoke {
|
||||
/// cancelling the close.
|
||||
fn close_request_is_let_through(&mut self) -> bool {
|
||||
let Run { app, ctx, .. } = self;
|
||||
embed::before_input(ctx, |out| app.app.frame_input(out));
|
||||
app.before_input(ctx);
|
||||
let mut input =
|
||||
egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440.0, 920.0))), ..Default::default() };
|
||||
input.viewports.insert(egui::ViewportId::ROOT, egui::ViewportInfo { events: vec![egui::ViewportEvent::Close], ..Default::default() });
|
||||
@@ -1036,7 +1111,7 @@ mod smoke {
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("dropped.txt");
|
||||
std::fs::write(&path, "Dropped words").unwrap();
|
||||
run.sender.dropped(vec![DroppedFile { path: Some(path), name: "dropped.txt".into(), bytes: None }], DropTarget::Elsewhere);
|
||||
run.sender.dropped(vec![DroppedFile { path: Some(path), name: "dropped.txt".into(), bytes: None }]);
|
||||
run.settle();
|
||||
assert!(run.app.app.session.doc.plain_text(wordcraft_doc::StoryRef::Body).contains("Dropped words"), "the dropped file opened");
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
@@ -1076,4 +1151,113 @@ mod smoke {
|
||||
assert!(closed, "Don't Save lets the close through");
|
||||
}
|
||||
}
|
||||
|
||||
/// A native menu selection reaches the hosted About dialog, including its credits, and Escape
|
||||
/// dismisses it without changing the document. The fake backend supplies the OS selection.
|
||||
#[cfg(target_os = "macos")]
|
||||
#[test]
|
||||
fn native_about_shows_credits_and_closes_with_escape() {
|
||||
use craft::menu::{Backend, Dispatch, Event, ItemRole, MenuBar, NativeMenu};
|
||||
|
||||
struct Selection(Vec<Event>);
|
||||
impl Backend for Selection {
|
||||
fn sync(&mut self, _: &MenuBar) {}
|
||||
fn attach(&mut self, _: Dispatch) {}
|
||||
fn drain(&mut self) -> Vec<Event> {
|
||||
std::mem::take(&mut self.0)
|
||||
}
|
||||
}
|
||||
|
||||
let mut run = Run::new();
|
||||
run.app.app.start_screen();
|
||||
run.settle();
|
||||
let before = run.app.app.session.doc.plain_text(wordcraft_doc::StoryRef::Body);
|
||||
let layout = native_menu::layout(&str::to_owned);
|
||||
let about = layout.bar.items().into_iter().find(|item| item.role == Some(ItemRole::About)).unwrap().command.clone();
|
||||
run.app.native_menu = Some(NativeMenu::new(Box::new(Selection(vec![Event::Click(about)]))));
|
||||
run.settle();
|
||||
assert!(run.app.app.dialog_host_mut().shows_modal());
|
||||
let tree = run.frames.tree();
|
||||
for label in ["WordCraft", "Contributors", "Models", "Language data"] {
|
||||
assert!(tree.keys().into_iter().any(|key| craft::ui::testing::access::name(&tree, key) == Some(label)), "About exposes {label}");
|
||||
}
|
||||
run.step(vec![egui::Event::Key {
|
||||
key: egui::Key::Escape,
|
||||
physical_key: None,
|
||||
pressed: true,
|
||||
repeat: false,
|
||||
modifiers: egui::Modifiers::NONE,
|
||||
}]);
|
||||
run.settle();
|
||||
assert!(run.app.app.dialog_host_mut().is_empty(), "Escape dismisses About");
|
||||
assert_eq!(run.app.app.session.doc.plain_text(wordcraft_doc::StoryRef::Body), before);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod command_line_tests {
|
||||
use super::{documents_to_open, split_at_delimiter};
|
||||
|
||||
/// The argv the Launcher starts a nightly with, as `prepare_launch` hands it on. The root is the one this
|
||||
/// platform would pass: `/nightly-data/...` has no drive prefix, so on Windows `parse` rightly refuses it.
|
||||
fn launcher_argv(tail: &[&str]) -> Vec<String> {
|
||||
let mut argv: Vec<std::ffi::OsString> = ["--launch-profile", "nightly-v1", "--profile-root", super::launch_profile::launcher_root(), "--"]
|
||||
.iter()
|
||||
.map(std::ffi::OsString::from)
|
||||
.collect();
|
||||
argv.extend(tail.iter().map(std::ffi::OsString::from));
|
||||
super::launch_profile::parse(argv).unwrap().args.iter().map(|a| a.to_string_lossy().into_owned()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_launchers_separator_is_never_a_document() {
|
||||
let (options, files) = split_at_delimiter(launcher_argv(&[]));
|
||||
assert!(options.is_empty(), "{options:?}");
|
||||
assert!(files.is_empty(), "the separator must not reach the documents: {files:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn documents_after_the_separator_are_kept_in_order() {
|
||||
let (options, files) = split_at_delimiter(launcher_argv(&["a.file"]));
|
||||
assert!(options.is_empty(), "{options:?}");
|
||||
assert_eq!(files, ["a.file"]);
|
||||
let (_, files) = split_at_delimiter(launcher_argv(&["a.file", "--version", "--sample"]));
|
||||
assert_eq!(files, ["a.file", "--version", "--sample"], "after -- every word is a document");
|
||||
// A real document path, as Windows hands one on: kept whole, in order, backslashes and spaces intact.
|
||||
let (_, files) = split_at_delimiter(launcher_argv(&[r"C:\Users\user\Holiday letter.docx", "a.file"]));
|
||||
assert_eq!(files, [r"C:\Users\user\Holiday letter.docx", "a.file"], "a real path after -- stays a document, in order");
|
||||
}
|
||||
|
||||
/// A document whose name looks like a LaunchServices option is one only after the separator: the strip
|
||||
/// for macOS runs on the options, after the split, so `-- -NSNotes.docx report.docx` opens both.
|
||||
#[test]
|
||||
fn a_document_named_like_a_launch_argument_survives_the_separator() {
|
||||
let (options, after) = split_at_delimiter(["-psn_0_12345", "--", "-NSNotes.docx", "report.docx"].map(String::from).to_vec());
|
||||
assert!(super::without_launch_args(options).is_empty(), "the option before the separator goes");
|
||||
let hazard: Vec<String> = ["-NSNotes.docx", "report.docx"].map(String::from).to_vec();
|
||||
assert!(super::without_launch_args(hazard).is_empty(), "before the split the strip takes the document and the one after it");
|
||||
assert_eq!(documents_to_open(Vec::new(), after), ["-NSNotes.docx", "report.docx"], "what follows the separator is opened, in order");
|
||||
}
|
||||
|
||||
/// A stable line that carries its own separator: `a.file` before `--` opens before `b.file` after it.
|
||||
/// The flag loop keeps `a.file` (its `_` arm, one push) and `documents_to_open` puts the two lists
|
||||
/// back in command-line order; the reverse, appending the loop's list to the separator's, opened them
|
||||
/// backwards (found in review of #7849).
|
||||
#[test]
|
||||
fn documents_before_the_separator_keep_their_place_before_the_ones_after_it() {
|
||||
let (options, after) = split_at_delimiter(["--sample", "a.file", "--", "b.file"].map(String::from).to_vec());
|
||||
assert_eq!(options, ["--sample", "a.file"], "--sample is a switch and a.file is left for the loop");
|
||||
assert_eq!(documents_to_open(vec!["a.file".into()], after), ["a.file", "b.file"]);
|
||||
let (_, after) = split_at_delimiter(launcher_argv(&["b.file"]));
|
||||
assert_eq!(documents_to_open(Vec::new(), after), ["b.file"], "the Launcher sends nothing before the separator");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_refusal_never_blocks_on_a_modal_before_the_event_loop_on_macos() {
|
||||
use crate::build_flavor::BuildFlavor;
|
||||
assert!(super::refusal_dialog(BuildFlavor::NightlyV1, true, false), "a desktop refusal still shows the box where one renders");
|
||||
assert!(!super::refusal_dialog(BuildFlavor::NightlyV1, true, true), "macOS has no run loop yet: the modal would hang");
|
||||
assert!(!super::refusal_dialog(BuildFlavor::NightlyV1, false, false), "a headless session has no box");
|
||||
assert!(!super::refusal_dialog(BuildFlavor::Stable, true, false), "only a nightly refusal explains itself in a box");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
//! The macOS application menu uses the same About dialog as File › About.
|
||||
|
||||
use craft::menu::{CommandRef, Gate, Item, ItemRole, Layout, LayoutOptions, Menu, MenuBar, MenuRole, NativeMenu, mac_layout};
|
||||
use serde_json::json;
|
||||
use wordcraft_ui_egui::{WordApp, i18n};
|
||||
|
||||
const APP_NAME: &str = "WordCraft";
|
||||
const ABOUT: &str = "About WordCraft";
|
||||
|
||||
/// The application menu, with `tr` the translation of an English string.
|
||||
pub(super) fn layout(tr: &dyn Fn(&'static str) -> String) -> Layout {
|
||||
let about = Item::new(CommandRef::with_params("ui.dialog", json!({"name": "about"})), tr(ABOUT)).role(ItemRole::About);
|
||||
let bar = MenuBar::new(vec![Menu::new(APP_NAME, vec![about.into()]).role(MenuRole::App)]);
|
||||
// `mac_layout` words About as the template; WordCraft's catalogs translate the whole label.
|
||||
let label = |s: &'static str| tr(if s == "About {app}" { ABOUT } else { s });
|
||||
let mut layout = mac_layout(&bar, &LayoutOptions::new(APP_NAME).label(&label));
|
||||
// WordCraft's document menus live in its ribbon; keep only the application menu.
|
||||
layout.bar.menus.retain(|menu| menu.role == MenuRole::App);
|
||||
layout
|
||||
}
|
||||
|
||||
fn lang(app: &WordApp) -> i18n::Lang {
|
||||
i18n::Lang::from_pref(&app.ui.language)
|
||||
}
|
||||
|
||||
fn layout_in(lang: i18n::Lang) -> Layout {
|
||||
layout(&|s| i18n::tr(lang, s).to_owned())
|
||||
}
|
||||
|
||||
pub(super) fn install(ctx: &egui::Context, app: &WordApp) -> Option<NativeMenu> {
|
||||
let menu = craft::menu::mac::install(ctx, &layout_in(lang(app)).bar);
|
||||
if menu.is_none() {
|
||||
log::warn!("the WordCraft application menu could not be installed");
|
||||
}
|
||||
menu
|
||||
}
|
||||
|
||||
pub(super) fn update(menu: &mut NativeMenu, app: &mut WordApp, ctx: &egui::Context) {
|
||||
menu.set_gate(Gate::default().modal(app.dialog_host_mut().shows_modal()));
|
||||
for command in menu.take_clicks(ctx) {
|
||||
if let Err(error) = app.run(&command.id, command.params) {
|
||||
log::warn!("application menu: {error}");
|
||||
}
|
||||
}
|
||||
menu.set_gate(Gate::default().modal(app.dialog_host_mut().shows_modal()));
|
||||
let lang = lang(app);
|
||||
for clash in menu.sync_with(lang.code(), || layout_in(lang)) {
|
||||
log::warn!("application menu: {clash:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The catalogs translate "About WordCraft" and have no "About {app}" row.
|
||||
#[test]
|
||||
fn about_shows_the_catalogs_translation() {
|
||||
let translate = |s: &'static str| if s == "About WordCraft" { "Über WordCraft".to_owned() } else { s.to_owned() };
|
||||
let layout = layout(&translate);
|
||||
let about = layout.bar.items().into_iter().find(|item| item.role == Some(ItemRole::About)).unwrap();
|
||||
assert_eq!(about.label, "Über WordCraft");
|
||||
}
|
||||
}
|
||||
@@ -157,6 +157,9 @@ fn private_subdirectory(root: &Path, name: impl AsRef<Path>, label: &str) -> Res
|
||||
if child == chosen || !child.starts_with(&chosen) {
|
||||
return Err(format!("the nightly {label} must stay inside its selected profile"));
|
||||
}
|
||||
if std::fs::metadata(&child).is_ok_and(|meta| !meta.is_dir()) {
|
||||
return Err(format!("the nightly {label} must be a directory"));
|
||||
}
|
||||
Ok(child)
|
||||
}
|
||||
|
||||
@@ -171,11 +174,56 @@ fn entries_stay_inside(root: &Path) -> Result<(), String> {
|
||||
};
|
||||
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")?;
|
||||
let path = entry.path();
|
||||
let metadata = std::fs::symlink_metadata(&path).map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
|
||||
// Settings and session state are ordinary files, not directories. Keep the existing
|
||||
// directory-boundary check for folders (including the known folder-only entries).
|
||||
let folder_only = PROFILE_FOLDERS.iter().any(|name| entry.file_name().eq_ignore_ascii_case(name));
|
||||
if metadata.is_file() && !folder_only {
|
||||
private_regular_file(&path, &metadata)?;
|
||||
} else {
|
||||
private_subdirectory(root, entry.file_name(), "profile entry")?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Persisted files must have their own ordinary file identity, not an alias to other data.
|
||||
fn private_regular_file(path: &Path, metadata: &std::fs::Metadata) -> Result<(), String> {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::MetadataExt as _;
|
||||
if metadata.nlink() != 1 {
|
||||
return Err("the nightly profile file must not be shared".into());
|
||||
}
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use winsafe::{HFILE, co};
|
||||
let (file, _) = HFILE::CreateFile(
|
||||
path.to_str().ok_or("the nightly profile file path is not textual")?,
|
||||
co::GENERIC::default(),
|
||||
Some(co::FILE_SHARE::READ | co::FILE_SHARE::WRITE | co::FILE_SHARE::DELETE),
|
||||
None,
|
||||
co::DISPOSITION::OPEN_EXISTING,
|
||||
co::FILE_ATTRIBUTE::NORMAL,
|
||||
Some(co::FILE_FLAG::OPEN_REPARSE_POINT),
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let info = file.GetFileInformationByHandle().map_err(|e| e.to_string())?;
|
||||
if info.dwFileAttributes.has(co::FILE_ATTRIBUTE::REPARSE_POINT | co::FILE_ATTRIBUTE::DIRECTORY) {
|
||||
return Err("the nightly profile file must not be an alias or directory".into());
|
||||
}
|
||||
if info.nNumberOfLinks != 1 {
|
||||
return Err("the nightly profile file must not be shared".into());
|
||||
}
|
||||
}
|
||||
let _ = (path, metadata);
|
||||
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);
|
||||
@@ -245,6 +293,8 @@ fn validate_for(
|
||||
Ok(confirmed)
|
||||
}
|
||||
|
||||
const PROFILE_FOLDERS: [&str; 5] = ["recovery", "logs", "fonts", "Templates", "FontStore"];
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -341,6 +391,31 @@ mod tests {
|
||||
assert_eq!(std::fs::read_dir(nightly).unwrap().count(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_profile_reopens_after_saving_settings_and_session_state() {
|
||||
let fixture = Fixture::new();
|
||||
for platform in [Platform::Mac, Platform::Linux, Platform::Windows] {
|
||||
let private = fixture.root.join(format!("nightly-reopen-{platform:?}"));
|
||||
assert_eq!(fixture.check(platform, &private).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();
|
||||
}
|
||||
for name in PROFILE_FOLDERS {
|
||||
std::fs::create_dir(private.join(name)).unwrap();
|
||||
}
|
||||
assert_eq!(fixture.check(platform, &private).unwrap(), private);
|
||||
assert_eq!(std::fs::read(private.join("config.toml")).unwrap(), b"saved profile data");
|
||||
for name in PROFILE_FOLDERS {
|
||||
let path = private.join(name);
|
||||
std::fs::remove_dir(&path).unwrap();
|
||||
std::fs::write(&path, b"not a directory").unwrap();
|
||||
assert!(fixture.check(platform, &private).is_err(), "{name} must stay a directory");
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
std::fs::create_dir(&path).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linux_fences_the_stable_flatpak_data_folder() {
|
||||
let fixture = Fixture::new();
|
||||
|
||||
@@ -209,5 +209,7 @@ real_name = "Helen Kwok"
|
||||
[people.ashokram-si]
|
||||
real_name = "Ashok Ram"
|
||||
|
||||
[people.reubgr]
|
||||
real_name = "Reuben Grinberg"
|
||||
[people.benandez]
|
||||
sync_github_name = true
|
||||
|
||||
@@ -7,7 +7,7 @@ use std::sync::Arc;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::para::{InlineObject, Run};
|
||||
use crate::para::{InlineObject, OBJ, Run};
|
||||
use crate::props::{CharProps, ParaProps};
|
||||
use crate::{Block, Blocks, DocError, Document, Paragraph, Part, PartKind, Path, Pos, Result, para_block};
|
||||
use crate::{Table, table::MAX_TABLE_DEPTH};
|
||||
@@ -26,8 +26,41 @@ pub struct Fragment {
|
||||
}
|
||||
|
||||
impl Fragment {
|
||||
/// Text box story IDs referenced by the fragment's objects in document order, falling
|
||||
/// back to the parts map's keys if no inline objects reference them.
|
||||
fn text_box_ids(&self) -> Vec<u32> {
|
||||
let mut ids = Vec::new();
|
||||
for b in &self.blocks {
|
||||
each_para(b, 0, &mut |p| {
|
||||
for o in &p.objects {
|
||||
for id in o.text_boxes() {
|
||||
if self.parts.get(&id).is_some_and(|part| part.kind == crate::PartKind::TextBox) {
|
||||
ids.push(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
if ids.is_empty() {
|
||||
ids.extend(self.parts.iter().filter(|(_, p)| p.kind == crate::PartKind::TextBox).map(|(id, _)| *id));
|
||||
}
|
||||
ids
|
||||
}
|
||||
|
||||
/// The plain text representation of the fragment's body, falling back to text box part stories
|
||||
/// when the body text has no real text (empty or only whitespace/object markers).
|
||||
pub fn plain_text(&self) -> String {
|
||||
self.to_document().plain_text(crate::StoryRef::Body)
|
||||
let d = self.to_document();
|
||||
let text = d.plain_text(crate::StoryRef::Body);
|
||||
let has_body_text = text.chars().any(|c| !c.is_whitespace() && c != OBJ);
|
||||
if !has_body_text && !self.parts.is_empty() {
|
||||
let parts: Vec<String> =
|
||||
self.text_box_ids().into_iter().map(|id| d.plain_text(crate::StoryRef::Part(id))).filter(|s| !s.is_empty()).collect();
|
||||
if !parts.is_empty() {
|
||||
return parts.join("\n");
|
||||
}
|
||||
}
|
||||
text
|
||||
}
|
||||
/// The fragment as the body of a new document (default styles).
|
||||
pub fn to_document(&self) -> Document {
|
||||
@@ -67,9 +100,20 @@ impl Fragment {
|
||||
found
|
||||
}
|
||||
/// The text a copy puts on the clipboard: [`Self::plain_text`] with symbol-font characters
|
||||
/// (Wingdings…) as their Unicode equivalents.
|
||||
/// (Wingdings…) as their Unicode equivalents. Falls back to text box part stories when body
|
||||
/// text has no real text (empty or only whitespace/object markers).
|
||||
pub fn clipboard_text(&self) -> String {
|
||||
self.to_document().shown_text(crate::StoryRef::Body)
|
||||
let d = self.to_document();
|
||||
let text = d.shown_text(crate::StoryRef::Body);
|
||||
let has_body_text = text.chars().any(|c| !c.is_whitespace() && c != OBJ);
|
||||
if !has_body_text && !self.parts.is_empty() {
|
||||
let parts: Vec<String> =
|
||||
self.text_box_ids().into_iter().map(|id| d.shown_text(crate::StoryRef::Part(id))).filter(|s| !s.is_empty()).collect();
|
||||
if !parts.is_empty() {
|
||||
return parts.join("\n");
|
||||
}
|
||||
}
|
||||
text
|
||||
}
|
||||
/// Add `piece` at the end, followed by a paragraph mark unless it already ends with one: how
|
||||
/// Word's Spike collects what it cuts. The piece's text box stories get ids after this
|
||||
@@ -603,6 +647,61 @@ fn remap_media_block(b: &mut Block, map: &BTreeMap<String, String>) {
|
||||
});
|
||||
}
|
||||
|
||||
/// Remaps media references across `blocks` and any text box stories in `parts`.
|
||||
fn remap_media_in(blocks: &mut [Block], parts: &mut BTreeMap<u32, Part>, map: &BTreeMap<String, String>) {
|
||||
if map.is_empty() {
|
||||
return;
|
||||
}
|
||||
for b in blocks {
|
||||
remap_media_block(b, map);
|
||||
}
|
||||
for part in parts.values_mut() {
|
||||
for b in &mut part.blocks {
|
||||
remap_media_block(Arc::make_mut(b), map);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Visit `(index, item)` in forward (`!last`) or reverse (`last`) order, returning the first `Some`.
|
||||
fn find_in_slice<T>(slice: &[T], last: bool, mut f: impl FnMut(usize, &T) -> Option<Path>) -> Option<Path> {
|
||||
if last { slice.iter().enumerate().rev().find_map(|(i, x)| f(i, x)) } else { slice.iter().enumerate().find_map(|(i, x)| f(i, x)) }
|
||||
}
|
||||
|
||||
/// First (`last == false`) or last (`last == true`) paragraph path inside `blk`,
|
||||
/// matching [`crate::text_walk::walk`] order and bounded by [`crate::PARA_WALK_DEPTH`].
|
||||
fn edge_para_in_block(blk: &Block, prefix: &mut Vec<u32>, depth: usize, last: bool) -> Option<Path> {
|
||||
if depth > crate::PARA_WALK_DEPTH {
|
||||
return None;
|
||||
}
|
||||
match blk {
|
||||
Block::Para(_) => Some(Path(prefix.clone())),
|
||||
Block::Table(t) => find_in_slice(&t.rows, last, |r, row| {
|
||||
find_in_slice(&row.cells, last, |c, cell| {
|
||||
prefix.push(r as u32);
|
||||
prefix.push(c as u32);
|
||||
let found = find_in_slice(&cell.blocks, last, |bi, b| {
|
||||
prefix.push(bi as u32);
|
||||
let res = edge_para_in_block(b, prefix, depth + 1, last);
|
||||
prefix.pop();
|
||||
res
|
||||
});
|
||||
prefix.pop();
|
||||
prefix.pop();
|
||||
found
|
||||
})
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Trim a paragraph to the offset range `from..to`, optionally clearing section breaks.
|
||||
fn trim_para(para: &Paragraph, from: usize, to: usize, clear_section: bool) -> Paragraph {
|
||||
let mut p = para.clone();
|
||||
let _ = p.delete(to.min(p.len()), p.len());
|
||||
let _ = p.delete(0, from.min(p.len()));
|
||||
if clear_section {
|
||||
p.section = None;
|
||||
}
|
||||
p
|
||||
}
|
||||
impl Document {
|
||||
/// Convert notes between footnotes and endnotes: footnotes (`foot`) become endnotes and
|
||||
/// endnotes (`end`) footnotes, both at once to swap them. Each note's kind changes, as do its
|
||||
@@ -1340,6 +1439,22 @@ impl Document {
|
||||
out
|
||||
}
|
||||
|
||||
/// Copy paragraphs in linear document order between `a` and `b` inclusive (#5906).
|
||||
fn copy_para_range(&self, a: &Pos, b: &Pos) -> Vec<Block> {
|
||||
let (a, b) = order(a, b);
|
||||
let mut out = Vec::new();
|
||||
for p in self.paths_between(&a, &b) {
|
||||
if let Some(para) = self.para(a.story, &p) {
|
||||
let from = if p == a.path { a.off } else { 0 };
|
||||
let to = if p == b.path { b.off } else { para.len() };
|
||||
let clear = p == b.path && b.off < para.len();
|
||||
out.push(Block::Para(trim_para(para, from, to, clear)));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Copy blocks spanning `a..b`, preserving whole tables when covered across containers (#5906).
|
||||
fn copy_blocks(&self, a: &Pos, b: &Pos) -> Vec<Block> {
|
||||
let (a, b) = order(a, b);
|
||||
let mut out = Vec::new();
|
||||
@@ -1352,21 +1467,17 @@ impl Document {
|
||||
let Some(blk) = bl.get(i) else { break };
|
||||
match &**blk {
|
||||
Block::Para(p) => {
|
||||
let mut p = p.clone();
|
||||
let to = if i == b.path.last() { b.off } else { p.len() };
|
||||
let from = if i == a.path.last() { a.off } else { 0 };
|
||||
let _ = p.delete(to.min(p.len()), p.len());
|
||||
let _ = p.delete(0, from.min(p.len()));
|
||||
if i == b.path.last() && to < self.para(a.story, &b.path).map(Paragraph::len).unwrap_or(0) {
|
||||
p.section = None;
|
||||
}
|
||||
out.push(Block::Para(p));
|
||||
let clear = i == b.path.last() && to < p.len();
|
||||
out.push(Block::Para(trim_para(p, from, to, clear)));
|
||||
}
|
||||
Block::Table(t) => out.push(Block::Table(t.clone())),
|
||||
Block::Table(_) => out.push((**blk).clone()),
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// Across the cells of a whole table: the table itself, not its cells' paragraphs (#1744).
|
||||
if let Some(tp) = self.whole_table(&a, &b)
|
||||
&& let Some(blk) = self.block(a.story, &tp)
|
||||
@@ -1374,17 +1485,92 @@ impl Document {
|
||||
out.push(blk.clone());
|
||||
return out;
|
||||
}
|
||||
for p in self.paths_between(&a, &b) {
|
||||
if let Some(para) = self.para(a.story, &p) {
|
||||
let mut q = para.clone();
|
||||
let to = if p == b.path { b.off } else { q.len() };
|
||||
let from = if p == a.path { a.off } else { 0 };
|
||||
let _ = q.delete(to.min(q.len()), q.len());
|
||||
let _ = q.delete(0, from.min(q.len()));
|
||||
q.section = None;
|
||||
out.push(Block::Para(q));
|
||||
|
||||
// Find the lowest common ancestor container.
|
||||
let common = a.path.0.iter().zip(&b.path.0).take_while(|(x, y)| x == y).count();
|
||||
let level = common.saturating_sub(common % 3);
|
||||
let prefix = a.path.0.get(..level).unwrap_or_default().to_vec();
|
||||
let block_path = |i: usize| {
|
||||
let mut v = prefix.clone();
|
||||
v.push(i as u32);
|
||||
Path(v)
|
||||
};
|
||||
|
||||
let (Some(&ia), Some(&ib)) = (a.path.0.get(level), b.path.0.get(level)) else {
|
||||
return self.copy_para_range(&a, &b);
|
||||
};
|
||||
let (ia, ib) = (ia as usize, ib as usize);
|
||||
if ia >= ib {
|
||||
return self.copy_para_range(&a, &b);
|
||||
}
|
||||
|
||||
let Some(bl) = self.container(a.story, &block_path(ia)) else {
|
||||
return self.copy_para_range(&a, &b);
|
||||
};
|
||||
|
||||
let edge_para = |i: usize, last: bool| -> Option<Path> {
|
||||
let blk = bl.get(i)?;
|
||||
if matches!(&**blk, Block::Para(_)) {
|
||||
return None;
|
||||
}
|
||||
let mut pre = block_path(i).0;
|
||||
edge_para_in_block(blk, &mut pre, level / 3, last)
|
||||
};
|
||||
let walked = |i: usize| bl.get(i).is_some_and(|b| !deeper_than_walk(b, level / 3));
|
||||
|
||||
let a_covers = if a.path.0.len() == level + 1 {
|
||||
a.off == 0
|
||||
} else {
|
||||
a.path.0.len() > level + 1 && a.off == 0 && walked(ia) && edge_para(ia, false).as_ref() == Some(&a.path)
|
||||
};
|
||||
|
||||
let b_at_end = self.para(b.story, &b.path).is_some_and(|p| p.len() == b.off);
|
||||
let b_covers = if b.path.0.len() == level + 1 {
|
||||
b_at_end
|
||||
} else {
|
||||
b.path.0.len() > level + 1 && walked(ib) && edge_para(ib, true).as_ref() == Some(&b.path) && b_at_end
|
||||
};
|
||||
|
||||
// Start block ia:
|
||||
if a_covers {
|
||||
if let Some(blk) = bl.get(ia) {
|
||||
out.push((**blk).clone());
|
||||
}
|
||||
} else if a.path.0.len() == level + 1 {
|
||||
if let Some(blk) = bl.get(ia)
|
||||
&& let Block::Para(p) = &**blk
|
||||
{
|
||||
out.push(Block::Para(trim_para(p, a.off, p.len(), false)));
|
||||
}
|
||||
} else if let Some(last_in_a) = edge_para(ia, true) {
|
||||
let end_pos = Pos { story: a.story, path: last_in_a.clone(), off: self.para(a.story, &last_in_a).map_or(0, Paragraph::len) };
|
||||
out.extend(self.copy_para_range(&a, &end_pos));
|
||||
}
|
||||
|
||||
// Blocks strictly between ia and ib: whole blocks
|
||||
for i in ia + 1..ib {
|
||||
if let Some(blk) = bl.get(i) {
|
||||
out.push((**blk).clone());
|
||||
}
|
||||
}
|
||||
|
||||
// End block ib:
|
||||
if b_covers {
|
||||
if let Some(blk) = bl.get(ib) {
|
||||
out.push((**blk).clone());
|
||||
}
|
||||
} else if b.path.0.len() == level + 1 {
|
||||
if let Some(blk) = bl.get(ib)
|
||||
&& let Block::Para(p) = &**blk
|
||||
{
|
||||
let clear = b.off < p.len();
|
||||
out.push(Block::Para(trim_para(p, 0, b.off, clear)));
|
||||
}
|
||||
} else if let Some(first_in_b) = edge_para(ib, false) {
|
||||
let start_pos = Pos { story: b.story, path: first_in_b, off: 0 };
|
||||
out.extend(self.copy_para_range(&start_pos, &b));
|
||||
}
|
||||
|
||||
out
|
||||
}
|
||||
|
||||
@@ -1470,13 +1656,41 @@ impl Document {
|
||||
Some(id)
|
||||
}
|
||||
|
||||
/// The blocks of `frag`, a fragment of another document, with every text box given a new
|
||||
/// story of its own here copied from the fragment's parts (as a paste does), to place them
|
||||
/// in this document; a box the fragment has no story for keeps none.
|
||||
/// Copies `media` into `self.media`, returning a remap for keys whose bytes differ from an
|
||||
/// existing entry under the same key.
|
||||
fn adopt_media(&mut self, media: &BTreeMap<String, Arc<Vec<u8>>>) -> BTreeMap<String, String> {
|
||||
let mut media_remap = BTreeMap::new();
|
||||
for (k, v) in media {
|
||||
if let Some(existing) = self.media.get(k) {
|
||||
if existing.as_slice() != v.as_slice() {
|
||||
let ext = k.rsplit_once('.').map_or("png", |(_, ext)| ext);
|
||||
let new_key = self.add_media((**v).clone(), ext);
|
||||
media_remap.insert(k.clone(), new_key);
|
||||
}
|
||||
} else {
|
||||
self.media.insert(k.clone(), v.clone());
|
||||
}
|
||||
}
|
||||
media_remap
|
||||
}
|
||||
|
||||
/// The blocks of `frag`, a fragment of another document, with its media copied (remapping
|
||||
/// conflicting keys) and every text box given a new story of its own here copied from the
|
||||
/// fragment's parts (as a paste does), to place them in this document; a box the fragment
|
||||
/// has no story for keeps none.
|
||||
pub fn adopt_fragment(&mut self, frag: &Fragment) -> Vec<Block> {
|
||||
let media_remap = self.adopt_media(&frag.media);
|
||||
let mut blocks = frag.blocks.clone();
|
||||
let mut remapped_parts;
|
||||
let parts = if media_remap.is_empty() {
|
||||
&frag.parts
|
||||
} else {
|
||||
remapped_parts = frag.parts.clone();
|
||||
remap_media_in(&mut blocks, &mut remapped_parts, &media_remap);
|
||||
&remapped_parts
|
||||
};
|
||||
let mut budget = BoxBudget { local: false, ..BoxBudget::new() };
|
||||
self.adopt_text_boxes(&mut blocks, &frag.parts, 0, &mut budget);
|
||||
self.adopt_text_boxes(&mut blocks, parts, 0, &mut budget);
|
||||
if budget.skipped > 0 {
|
||||
log::warn!(
|
||||
"{} text boxes are left empty; their stories are past what one copy brings ({MAX_PASTED_BOXES} stories, {MAX_PASTED_BOX_BYTES} bytes)",
|
||||
@@ -1488,18 +1702,7 @@ impl Document {
|
||||
|
||||
/// Insert a fragment at `pos`; returns the position after the pasted content.
|
||||
pub fn insert_fragment(&mut self, pos: &Pos, frag: &Fragment) -> Result<Pos> {
|
||||
let mut media_remap = BTreeMap::new();
|
||||
for (k, v) in &frag.media {
|
||||
if let Some(existing) = self.media.get(k) {
|
||||
if existing.as_slice() != v.as_slice() {
|
||||
let ext = k.rsplit_once('.').map_or("png", |(_, ext)| ext);
|
||||
let new_key = self.add_media((**v).clone(), ext);
|
||||
media_remap.insert(k.clone(), new_key);
|
||||
}
|
||||
} else {
|
||||
self.media.insert(k.clone(), v.clone());
|
||||
}
|
||||
}
|
||||
let media_remap = self.adopt_media(&frag.media);
|
||||
// Tables that would nest deeper than the limit here become their paragraphs (#1596).
|
||||
let room = MAX_TABLE_DEPTH.saturating_sub(pos.path.depth());
|
||||
let mut blocks = Vec::with_capacity(frag.blocks.len());
|
||||
@@ -1509,20 +1712,14 @@ impl Document {
|
||||
if blocks.is_empty() {
|
||||
return Ok(pos.clone());
|
||||
}
|
||||
if self.para_at(pos).is_none() {
|
||||
let Some(dest_para) = self.para_at(pos) else {
|
||||
return Err(DocError::BadPath(pos.path.to_string()));
|
||||
}
|
||||
};
|
||||
let is_dest_empty = dest_para.is_empty();
|
||||
let table_para = table_style_para(self, pos);
|
||||
let destination_shading = self.styles.resolve_para_in(&dest_para.props, table_para.as_ref()).shading;
|
||||
let mut parts = frag.parts.clone();
|
||||
if !media_remap.is_empty() {
|
||||
for b in &mut blocks {
|
||||
remap_media_block(b, &media_remap);
|
||||
}
|
||||
for part in parts.values_mut() {
|
||||
for b in &mut part.blocks {
|
||||
remap_media_block(Arc::make_mut(b), &media_remap);
|
||||
}
|
||||
}
|
||||
}
|
||||
remap_media_in(&mut blocks, &mut parts, &media_remap);
|
||||
// Pasted text boxes get stories of their own (never shared with the copy's source).
|
||||
let mut budget = BoxBudget::new();
|
||||
self.adopt_text_boxes(&mut blocks, &parts, 0, &mut budget);
|
||||
@@ -1538,6 +1735,7 @@ impl Document {
|
||||
&& let Some(Block::Para(src)) = blocks.first()
|
||||
{
|
||||
let src = src.clone();
|
||||
let src_shading = self.styles.resolve_para(&src.props).shading;
|
||||
let target = self.para_mut(pos.story, &pos.path)?;
|
||||
let tail = target.split_off(pos.off)?;
|
||||
let added = src.len();
|
||||
@@ -1548,6 +1746,13 @@ impl Document {
|
||||
target.append(src);
|
||||
target.append(tail);
|
||||
target.props = keep;
|
||||
// Paragraph shading is the pasted text's background (HTML container backgrounds
|
||||
// become paragraph shading), so an empty unshaded destination takes the source's.
|
||||
// A paste without a paragraph mark into an existing paragraph leaves the
|
||||
// destination paragraph's formatting unchanged (#6157).
|
||||
if is_dest_empty && destination_shading.is_none() {
|
||||
target.props.shading = src_shading;
|
||||
}
|
||||
target.section = sect;
|
||||
return Ok(Pos { off: pos.off + added, ..pos.clone() });
|
||||
}
|
||||
@@ -1559,13 +1764,28 @@ impl Document {
|
||||
let mut idx = left.last() + 1;
|
||||
match first {
|
||||
Block::Para(p) => {
|
||||
let src_shading = self.styles.resolve_para(&p.props).shading;
|
||||
let l = self.para_mut(pos.story, &left)?;
|
||||
let keep = l.props.clone();
|
||||
let keep_empty = keep.is_empty();
|
||||
let keep_shading = keep.shading;
|
||||
let mut p2 = p;
|
||||
let pprops = p2.props.clone();
|
||||
p2.section = None;
|
||||
l.append(p2);
|
||||
l.props = if keep.is_empty() { pprops } else { keep };
|
||||
l.props = if keep_empty { pprops } else { keep };
|
||||
if destination_shading.is_some() {
|
||||
// When adopting a source paragraph style into an empty destination,
|
||||
// preserve the destination background as a direct override so the
|
||||
// source style's shading does not win over it (#6157).
|
||||
if keep_empty && l.props.style.is_some() {
|
||||
l.props.shading = destination_shading;
|
||||
} else {
|
||||
l.props.shading = keep_shading;
|
||||
}
|
||||
} else if is_dest_empty && !keep_empty && l.props.shading.is_none() {
|
||||
l.props.shading = src_shading;
|
||||
}
|
||||
}
|
||||
t @ Block::Table(_) => {
|
||||
self.insert_block(pos.story, &left.with_last(idx), t)?;
|
||||
@@ -1606,6 +1826,13 @@ impl Document {
|
||||
}
|
||||
}
|
||||
|
||||
/// Paragraph formatting of the table style enclosing `pos`, if any.
|
||||
fn table_style_para(doc: &Document, pos: &Pos) -> Option<ParaProps> {
|
||||
let (tp, _, _) = pos.path.cell()?;
|
||||
let id = doc.table(pos.story, &tp)?.props.style.as_deref()?;
|
||||
Some(doc.styles.table_style(id)?.para.clone())
|
||||
}
|
||||
|
||||
/// Take the drop cap (and its options) off a paragraph's properties.
|
||||
fn clear_drop_cap(props: &mut crate::props::ParaProps) {
|
||||
props.drop_cap = None;
|
||||
|
||||
@@ -118,6 +118,182 @@ fn copy_paste_round_trip() {
|
||||
assert!(d.plain_text(StoryRef::Body).starts_with("XYalpha"));
|
||||
}
|
||||
|
||||
/// Shading a pasted paragraph gets from its style is kept as direct shading on an empty unshaded destination (#6157).
|
||||
#[test]
|
||||
fn paste_keeps_source_style_shading() {
|
||||
let mut d = doc(&[""]);
|
||||
Arc::make_mut(&mut d.styles).upsert(crate::Style {
|
||||
id: "SourceShaded".into(),
|
||||
name: "Source Shaded".into(),
|
||||
kind: crate::StyleKind::Paragraph,
|
||||
based_on: Some("Normal".into()),
|
||||
para: ParaProps { shading: Some(crate::Rgb(0x33, 0x33, 0x33)), ..Default::default() },
|
||||
..Default::default()
|
||||
});
|
||||
let mut src = Paragraph::with_text("X", CharProps::default());
|
||||
src.props.style = Some("SourceShaded".into());
|
||||
let one = Fragment { blocks: vec![Block::Para(src)], ..Default::default() };
|
||||
d.insert_fragment(&Pos::body(0, 0), &one).unwrap();
|
||||
let p = d.para(StoryRef::Body, &Path::top(0)).unwrap();
|
||||
assert_eq!(p.props.shading, Some(crate::Rgb(0x33, 0x33, 0x33)), "source style shading is kept on empty destination");
|
||||
}
|
||||
|
||||
/// A one-line paste without a paragraph mark into a non-empty paragraph leaves destination shading unshaded (#6157).
|
||||
#[test]
|
||||
fn single_block_paste_into_non_empty_paragraph_leaves_destination_unshaded() {
|
||||
let mut d = doc(&["plain"]);
|
||||
Arc::make_mut(&mut d.styles).upsert(crate::Style {
|
||||
id: "SourceShaded".into(),
|
||||
name: "Source Shaded".into(),
|
||||
kind: crate::StyleKind::Paragraph,
|
||||
based_on: Some("Normal".into()),
|
||||
para: ParaProps { shading: Some(crate::Rgb(0x33, 0x33, 0x33)), ..Default::default() },
|
||||
..Default::default()
|
||||
});
|
||||
let mut src = Paragraph::with_text("X", CharProps::default());
|
||||
src.props.style = Some("SourceShaded".into());
|
||||
let one = Fragment { blocks: vec![Block::Para(src)], ..Default::default() };
|
||||
d.insert_fragment(&Pos::body(0, 5), &one).unwrap();
|
||||
let p = d.para(StoryRef::Body, &Path::top(0)).unwrap();
|
||||
assert_eq!(p.props.shading, None, "one-line paste without a paragraph mark must not shade destination paragraph");
|
||||
}
|
||||
|
||||
/// An empty destination with direct properties keeps the first pasted paragraph's style shading (#6157).
|
||||
#[test]
|
||||
fn multi_block_paste_keeps_source_style_shading() {
|
||||
let mut d = doc(&[""]);
|
||||
Arc::make_mut(&mut d.styles).upsert(crate::Style {
|
||||
id: "SourceShaded".into(),
|
||||
name: "Source Shaded".into(),
|
||||
kind: crate::StyleKind::Paragraph,
|
||||
based_on: Some("Normal".into()),
|
||||
para: ParaProps { shading: Some(crate::Rgb(0x33, 0x33, 0x33)), ..Default::default() },
|
||||
..Default::default()
|
||||
});
|
||||
let mut a = Paragraph::with_text("A", CharProps::default());
|
||||
a.props.style = Some("SourceShaded".into());
|
||||
let b = Paragraph::with_text("B", CharProps::default());
|
||||
let frag = Fragment { blocks: vec![Block::Para(a), Block::Para(b)], ..Default::default() };
|
||||
d.para_mut(StoryRef::Body, &Path::top(0)).unwrap().props.align = Some(crate::props::Align::Center);
|
||||
d.insert_fragment(&Pos::body(0, 0), &frag).unwrap();
|
||||
let p = d.para(StoryRef::Body, &Path::top(0)).unwrap();
|
||||
assert_eq!(p.props.shading, Some(crate::Rgb(0x33, 0x33, 0x33)), "first pasted paragraph keeps its style shading");
|
||||
}
|
||||
|
||||
/// The destination's resolved (default) shading is not replaced by the source's direct shading (#6157).
|
||||
#[test]
|
||||
fn multi_block_paste_keeps_destination_default_shading() {
|
||||
let mut d = doc(&["plain"]);
|
||||
Arc::make_mut(&mut d.styles).default_para.shading = Some(crate::Rgb(0x22, 0x22, 0x22));
|
||||
let mut a = Paragraph::with_text("A", CharProps::default());
|
||||
a.props.shading = Some(crate::Rgb(0x11, 0x11, 0x11));
|
||||
let b = Paragraph::with_text("B", CharProps::default());
|
||||
let frag = Fragment { blocks: vec![Block::Para(a), Block::Para(b)], ..Default::default() };
|
||||
d.insert_fragment(&Pos::body(0, 5), &frag).unwrap();
|
||||
let p = d.para(StoryRef::Body, &Path::top(0)).unwrap();
|
||||
assert_eq!(p.props.shading, None, "source direct shading must not override the destination default");
|
||||
assert_eq!(d.styles.resolve_para(&p.props).shading, Some(crate::Rgb(0x22, 0x22, 0x22)));
|
||||
}
|
||||
|
||||
/// An empty destination with inherited shading keeps its shading when pasting a differently shaded source style (#6157).
|
||||
#[test]
|
||||
fn multi_block_paste_keeps_destination_inherited_shading_over_source_style() {
|
||||
let mut d = doc(&["plain"]);
|
||||
Arc::make_mut(&mut d.styles).default_para.shading = Some(crate::Rgb(0x22, 0x22, 0x22));
|
||||
Arc::make_mut(&mut d.styles).upsert(crate::Style {
|
||||
id: "SourceShaded".into(),
|
||||
name: "Source Shaded".into(),
|
||||
kind: crate::StyleKind::Paragraph,
|
||||
based_on: Some("Normal".into()),
|
||||
para: ParaProps { shading: Some(crate::Rgb(0x33, 0x33, 0x33)), ..Default::default() },
|
||||
..Default::default()
|
||||
});
|
||||
let mut a = Paragraph::with_text("A", CharProps::default());
|
||||
a.props.style = Some("SourceShaded".into());
|
||||
let b = Paragraph::with_text("B", CharProps::default());
|
||||
let frag = Fragment { blocks: vec![Block::Para(a), Block::Para(b)], ..Default::default() };
|
||||
d.insert_fragment(&Pos::body(0, 5), &frag).unwrap();
|
||||
let p = d.para(StoryRef::Body, &Path::top(0)).unwrap();
|
||||
assert_eq!(p.props.shading, Some(crate::Rgb(0x22, 0x22, 0x22)), "destination inherited shading is preserved as a direct override");
|
||||
assert_eq!(
|
||||
d.styles.resolve_para(&p.props).shading,
|
||||
Some(crate::Rgb(0x22, 0x22, 0x22)),
|
||||
"resolved shading must match the destination background, not the source style"
|
||||
);
|
||||
}
|
||||
|
||||
/// Multi-block paste into an empty unshaded destination keeps a shaded source style without
|
||||
/// duplicating its color into direct paragraph shading (#6157).
|
||||
#[test]
|
||||
fn multi_block_paste_into_empty_destination_keeps_source_style_without_direct_shading() {
|
||||
let mut d = doc(&[""]);
|
||||
Arc::make_mut(&mut d.styles).upsert(crate::Style {
|
||||
id: "SourceShaded".into(),
|
||||
name: "Source Shaded".into(),
|
||||
kind: crate::StyleKind::Paragraph,
|
||||
based_on: Some("Normal".into()),
|
||||
para: ParaProps { shading: Some(crate::Rgb(0x33, 0x33, 0x33)), ..Default::default() },
|
||||
..Default::default()
|
||||
});
|
||||
let mut a = Paragraph::with_text("A", CharProps::default());
|
||||
a.props.style = Some("SourceShaded".into());
|
||||
let mut b = Paragraph::with_text("B", CharProps::default());
|
||||
b.props.style = Some("SourceShaded".into());
|
||||
let frag = Fragment { blocks: vec![Block::Para(a), Block::Para(b)], ..Default::default() };
|
||||
d.insert_fragment(&Pos::body(0, 0), &frag).unwrap();
|
||||
for idx in [0, 1] {
|
||||
let p = d.para(StoryRef::Body, &Path::top(idx)).unwrap();
|
||||
assert_eq!(p.props.style.as_deref(), Some("SourceShaded"));
|
||||
assert_eq!(p.props.shading, None, "paragraph {idx} inherits from its style without redundant direct shading");
|
||||
assert_eq!(d.styles.resolve_para(&p.props).shading, Some(crate::Rgb(0x33, 0x33, 0x33)));
|
||||
}
|
||||
}
|
||||
|
||||
/// Paragraph shading inherited from an enclosing table's style is preserved as destination shading (#6157).
|
||||
#[test]
|
||||
fn paste_keeps_destination_table_style_shading() {
|
||||
let mut d = doc(&["outside"]);
|
||||
Arc::make_mut(&mut d.styles).upsert(crate::Style {
|
||||
id: "ShadedGrid".into(),
|
||||
name: "Shaded Grid".into(),
|
||||
kind: crate::StyleKind::Table,
|
||||
para: ParaProps { shading: Some(crate::Rgb(0x22, 0x22, 0x22)), ..Default::default() },
|
||||
..Default::default()
|
||||
});
|
||||
Arc::make_mut(&mut d.styles).upsert(crate::Style {
|
||||
id: "SourceShaded".into(),
|
||||
name: "Source Shaded".into(),
|
||||
kind: crate::StyleKind::Paragraph,
|
||||
based_on: Some("Normal".into()),
|
||||
para: ParaProps { shading: Some(crate::Rgb(0x44, 0x44, 0x44)), ..Default::default() },
|
||||
..Default::default()
|
||||
});
|
||||
let mut t = Table::new(1, 2, 200.0);
|
||||
t.props.style = Some("ShadedGrid".into());
|
||||
d.insert_block(StoryRef::Body, &Path::top(0), Block::Table(t)).unwrap();
|
||||
|
||||
// Single-block paste into cell (0, 0): table-style paragraph shading is not overridden.
|
||||
let mut src = Paragraph::with_text("cell1", CharProps::default());
|
||||
src.props.shading = Some(crate::Rgb(0x1e, 0x1e, 0x1e));
|
||||
let one = Fragment { blocks: vec![Block::Para(src)], ..Default::default() };
|
||||
let cell0 = Pos { story: StoryRef::Body, path: Path(vec![0, 0, 0, 0]), off: 0 };
|
||||
d.insert_fragment(&cell0, &one).unwrap();
|
||||
let p0 = d.para(StoryRef::Body, &cell0.path).unwrap();
|
||||
assert_eq!(p0.props.shading, None);
|
||||
let tp = &d.styles.table_style("ShadedGrid").unwrap().para;
|
||||
assert_eq!(d.styles.resolve_para_in(&p0.props, Some(tp)).shading, Some(crate::Rgb(0x22, 0x22, 0x22)));
|
||||
|
||||
// Multi-block paste with a differently shaded source style into empty cell (0, 1).
|
||||
let mut a = Paragraph::with_text("A", CharProps::default());
|
||||
a.props.style = Some("SourceShaded".into());
|
||||
let b = Paragraph::with_text("B", CharProps::default());
|
||||
let multi = Fragment { blocks: vec![Block::Para(a), Block::Para(b)], ..Default::default() };
|
||||
let cell1 = Pos { story: StoryRef::Body, path: Path(vec![0, 0, 1, 0]), off: 0 };
|
||||
d.insert_fragment(&cell1, &multi).unwrap();
|
||||
let p1 = d.para(StoryRef::Body, &cell1.path).unwrap();
|
||||
assert_eq!(d.styles.resolve_para_in(&p1.props, Some(tp)).shading, Some(crate::Rgb(0x22, 0x22, 0x22)));
|
||||
}
|
||||
|
||||
/// The first paragraph of the deepest cell, following the first table at each level.
|
||||
fn deepest(d: &Document) -> Path {
|
||||
let (mut path, mut blocks) = (Vec::new(), &d.body);
|
||||
@@ -304,6 +480,33 @@ fn fragment_without_parts_never_shows_an_unrelated_story() {
|
||||
assert_eq!(got[2], None, "a header isn't a text box");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fragment_extracts_text_box_stories_in_object_order() {
|
||||
let mut p = Paragraph::new();
|
||||
p.insert_object(0, box_shape(Some(20)), &CharProps::default()).unwrap();
|
||||
p.insert_object(p.text.len(), box_shape(Some(10)), &CharProps::default()).unwrap();
|
||||
let mut parts = BTreeMap::new();
|
||||
parts.insert(
|
||||
10,
|
||||
crate::Part {
|
||||
kind: PartKind::TextBox,
|
||||
blocks: vec![para_block(Paragraph::with_text("Second", CharProps::default()))],
|
||||
body: Default::default(),
|
||||
},
|
||||
);
|
||||
parts.insert(
|
||||
20,
|
||||
crate::Part {
|
||||
kind: PartKind::TextBox,
|
||||
blocks: vec![para_block(Paragraph::with_text("First", CharProps::default()))],
|
||||
body: Default::default(),
|
||||
},
|
||||
);
|
||||
let f = Fragment { blocks: vec![Block::Para(p)], parts, ..Default::default() };
|
||||
assert_eq!(f.plain_text(), "First\nSecond");
|
||||
assert_eq!(f.clipboard_text(), "First\nSecond");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn self_nested_text_box_paste_is_bounded() {
|
||||
let mut d = doc(&["x"]);
|
||||
@@ -989,6 +1192,61 @@ fn insert_fragment_remaps_conflicting_media_keys() {
|
||||
assert_eq!(remapped, other_key);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adopt_fragment_copies_and_remaps_conflicting_media_in_blocks_and_text_boxes() {
|
||||
let mut d = doc(&["destination"]);
|
||||
d.media.insert("image1.png".into(), Arc::new(vec![1, 1, 1]));
|
||||
|
||||
let mut frag_media = std::collections::BTreeMap::new();
|
||||
frag_media.insert("image1.png".into(), Arc::new(vec![2, 2, 2]));
|
||||
frag_media.insert("missing.png".into(), Arc::new(vec![3, 3, 3]));
|
||||
|
||||
let img = |key: &str| InlineObject::Image {
|
||||
media: key.into(),
|
||||
w: 10.0,
|
||||
h: 10.0,
|
||||
alt: String::new(),
|
||||
float: Default::default(),
|
||||
crop: [0.0; 4],
|
||||
fx: Default::default(),
|
||||
ole: None,
|
||||
};
|
||||
|
||||
let mut tb_para = Paragraph::with_text(&crate::para::OBJ.to_string(), CharProps::default());
|
||||
tb_para.objects.push(img("image1.png"));
|
||||
let mut parts = std::collections::BTreeMap::new();
|
||||
parts.insert(7, Part { kind: PartKind::TextBox, blocks: vec![para_block(tb_para)], body: Default::default() });
|
||||
|
||||
let mut top_para = Paragraph::with_text(&format!("{}{}", crate::para::OBJ, crate::para::OBJ), CharProps::default());
|
||||
top_para.objects.push(img("missing.png"));
|
||||
top_para.objects.push(InlineObject::Shape {
|
||||
kind: crate::para::ShapeKind::TextBox,
|
||||
w: 40.0,
|
||||
h: 40.0,
|
||||
fill: None,
|
||||
stroke: None,
|
||||
stroke_width: 1.0,
|
||||
float: Default::default(),
|
||||
story: Some(7),
|
||||
freeform: None,
|
||||
effects: Default::default(),
|
||||
extra: Default::default(),
|
||||
});
|
||||
let frag = Fragment { blocks: vec![Block::Para(top_para)], parts, media: frag_media };
|
||||
|
||||
let adopted = d.adopt_fragment(&frag);
|
||||
assert_eq!(d.media["image1.png"].as_slice(), &[1, 1, 1]);
|
||||
assert_eq!(d.media["missing.png"].as_slice(), &[3, 3, 3]);
|
||||
let remapped_key = d.media.keys().find(|k| k.as_str() != "image1.png" && k.as_str() != "missing.png").unwrap();
|
||||
assert_eq!(d.media[remapped_key].as_slice(), &[2, 2, 2]);
|
||||
|
||||
let adopted_para = adopted[0].as_para().unwrap();
|
||||
assert!(matches!(&adopted_para.objects[0], InlineObject::Image { media, .. } if media == "missing.png"));
|
||||
let adopted_tb_id = adopted_para.objects[1].text_box().unwrap();
|
||||
let adopted_tb_para = d.parts[&adopted_tb_id].blocks[0].as_para().unwrap();
|
||||
assert!(matches!(&adopted_tb_para.objects[0], InlineObject::Image { media, .. } if media == remapped_key));
|
||||
}
|
||||
|
||||
/// #6788: splitting a paragraph after its first letters leaves the drop cap on the first
|
||||
/// paragraph only; the new one (also when it is empty) is plain. A split at offset 0 is unchanged.
|
||||
#[test]
|
||||
@@ -1023,3 +1281,130 @@ fn split_paragraph_keeps_the_drop_cap_on_the_first_paragraph_only() {
|
||||
d.split_paragraph(&Pos::body(0, 0)).unwrap();
|
||||
assert_eq!((drop_cap(&d, 0), drop_cap(&d, 1)), (cap.clone(), cap));
|
||||
}
|
||||
|
||||
/// #5906: Copying a range spanning from inside a table to an outside paragraph preserves the table.
|
||||
#[test]
|
||||
fn copy_range_preserves_table_structure_across_blocks() {
|
||||
let mut d = Document::new();
|
||||
let mut t = Table::new(2, 2, 200.0);
|
||||
t.rows[0].cells[0].blocks = vec![para_block(Paragraph::with_text("A1", CharProps::default()))];
|
||||
t.rows[0].cells[1].blocks = vec![para_block(Paragraph::with_text("B1", CharProps::default()))];
|
||||
t.rows[1].cells[0].blocks = vec![para_block(Paragraph::with_text("A2", CharProps::default()))];
|
||||
t.rows[1].cells[1].blocks = vec![para_block(Paragraph::with_text("B2", CharProps::default()))];
|
||||
d.body = vec![Arc::new(Block::Table(t)), Arc::new(Block::Para(Paragraph::with_text("Trailing", CharProps::default())))];
|
||||
let start = d.start_of(StoryRef::Body);
|
||||
let end = d.end_of(StoryRef::Body);
|
||||
let frag = d.copy_range(&start, &end);
|
||||
assert_eq!(frag.blocks.len(), 2, "expected table and trailing paragraph, got {:?}", frag.blocks);
|
||||
let Block::Table(tbl) = &frag.blocks[0] else { panic!("first block should be Table") };
|
||||
assert_eq!(tbl.rows.len(), 2, "copied table row count");
|
||||
assert_eq!(tbl.cols(), 2, "copied table col count");
|
||||
let c00 = tbl.rows[0].cells[0].blocks.first().and_then(|b| match &**b {
|
||||
Block::Para(p) => Some(p.text.as_str()),
|
||||
_ => None,
|
||||
});
|
||||
assert_eq!(c00, Some("A1"), "cell (0, 0) text");
|
||||
let Block::Para(trail) = &frag.blocks[1] else { panic!("second block should be Para") };
|
||||
assert_eq!(trail.text.as_str(), "Trailing");
|
||||
}
|
||||
|
||||
/// #5906: Copying a range enclosing a table between paragraphs preserves the table block.
|
||||
#[test]
|
||||
fn copy_range_preserves_table_between_paragraphs() {
|
||||
let mut d = Document::new();
|
||||
let mut t = Table::new(2, 2, 200.0);
|
||||
t.rows[0].cells[0].blocks = vec![para_block(Paragraph::with_text("A1", CharProps::default()))];
|
||||
t.rows[0].cells[1].blocks = vec![para_block(Paragraph::with_text("B1", CharProps::default()))];
|
||||
t.rows[1].cells[0].blocks = vec![para_block(Paragraph::with_text("A2", CharProps::default()))];
|
||||
t.rows[1].cells[1].blocks = vec![para_block(Paragraph::with_text("B2", CharProps::default()))];
|
||||
d.body = vec![
|
||||
Arc::new(Block::Para(Paragraph::with_text("Intro", CharProps::default()))),
|
||||
Arc::new(Block::Table(t)),
|
||||
Arc::new(Block::Para(Paragraph::with_text("Outro", CharProps::default()))),
|
||||
];
|
||||
let start = Pos { story: StoryRef::Body, path: Path(vec![0]), off: 0 };
|
||||
let end = d.end_of(StoryRef::Body);
|
||||
let frag = d.copy_range(&start, &end);
|
||||
assert_eq!(frag.blocks.len(), 3, "expected intro, table, and outro, got {:?}", frag.blocks);
|
||||
assert!(matches!(&frag.blocks[0], Block::Para(p) if p.text == "Intro"));
|
||||
let Block::Table(tbl) = &frag.blocks[1] else { panic!("second block should be Table") };
|
||||
assert_eq!(tbl.rows.len(), 2, "copied table row count");
|
||||
assert_eq!(tbl.cols(), 2, "copied table col count");
|
||||
assert!(matches!(&frag.blocks[2], Block::Para(p) if p.text == "Outro"));
|
||||
}
|
||||
|
||||
/// #5906: Copy range across cells inside a table preserves all traversed paragraphs in linear order.
|
||||
#[test]
|
||||
fn copy_range_linear_cross_cells_preserves_all_traversed_paragraphs() {
|
||||
let mut d = Document::new();
|
||||
let mut t = Table::new(3, 3, 300.0);
|
||||
for (r, row) in t.rows.iter_mut().enumerate() {
|
||||
for (c, cell) in row.cells.iter_mut().enumerate() {
|
||||
cell.blocks = vec![para_block(Paragraph::with_text(&format!("R{r}C{c}"), CharProps::default()))];
|
||||
}
|
||||
}
|
||||
d.body = vec![Arc::new(Block::Table(t))];
|
||||
// Start at (0, 1) offset 1 ("0C1"), end at (1, 1) offset 3 ("R1C")
|
||||
let a = Pos { story: StoryRef::Body, path: Path(vec![0, 0, 1, 0]), off: 1 };
|
||||
let b = Pos { story: StoryRef::Body, path: Path(vec![0, 1, 1, 0]), off: 3 };
|
||||
let frag = d.copy_range(&a, &b);
|
||||
assert_eq!(frag.blocks.len(), 4, "all 4 traversed cells in linear order");
|
||||
let texts: Vec<&str> = frag
|
||||
.blocks
|
||||
.iter()
|
||||
.filter_map(|b| match b {
|
||||
Block::Para(p) => Some(p.text.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(texts, vec!["0C1", "R0C2", "R1C0", "R1C"]);
|
||||
}
|
||||
|
||||
/// #5906: Copy range from paragraph before table into non-corner cell preserves all traversed text in linear order.
|
||||
#[test]
|
||||
fn copy_range_from_para_before_table_to_non_corner_cell() {
|
||||
let mut d = Document::new();
|
||||
let mut t = Table::new(3, 3, 300.0);
|
||||
for (r, row) in t.rows.iter_mut().enumerate() {
|
||||
for (c, cell) in row.cells.iter_mut().enumerate() {
|
||||
cell.blocks = vec![para_block(Paragraph::with_text(&format!("R{r}C{c}"), CharProps::default()))];
|
||||
}
|
||||
}
|
||||
d.body = vec![Arc::new(Block::Para(Paragraph::with_text("LeadingText", CharProps::default()))), Arc::new(Block::Table(t))];
|
||||
let a = Pos { story: StoryRef::Body, path: Path(vec![0]), off: 7 };
|
||||
let b = Pos { story: StoryRef::Body, path: Path(vec![1, 1, 1, 0]), off: 3 };
|
||||
let frag = d.copy_range(&a, &b);
|
||||
let texts: Vec<&str> = frag
|
||||
.blocks
|
||||
.iter()
|
||||
.filter_map(|b| match b {
|
||||
Block::Para(p) => Some(p.text.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(texts, vec!["Text", "R0C0", "R0C1", "R0C2", "R1C0", "R1C"]);
|
||||
}
|
||||
|
||||
/// #5906: Copy range from non-corner cell into following paragraph preserves all traversed text in linear order.
|
||||
#[test]
|
||||
fn copy_range_from_cell_into_para_after_table() {
|
||||
let mut d = Document::new();
|
||||
let mut t = Table::new(2, 2, 200.0);
|
||||
t.rows[0].cells[0].blocks = vec![para_block(Paragraph::with_text("Hello", CharProps::default()))];
|
||||
t.rows[0].cells[1].blocks = vec![para_block(Paragraph::with_text("World", CharProps::default()))];
|
||||
t.rows[1].cells[0].blocks = vec![para_block(Paragraph::with_text("Foo", CharProps::default()))];
|
||||
t.rows[1].cells[1].blocks = vec![para_block(Paragraph::with_text("Bar", CharProps::default()))];
|
||||
d.body = vec![Arc::new(Block::Table(t)), Arc::new(Block::Para(Paragraph::with_text("Trailing", CharProps::default())))];
|
||||
let a = Pos { story: StoryRef::Body, path: Path(vec![0, 0, 1, 0]), off: 1 };
|
||||
let b = Pos { story: StoryRef::Body, path: Path(vec![1]), off: 5 };
|
||||
let frag = d.copy_range(&a, &b);
|
||||
let texts: Vec<&str> = frag
|
||||
.blocks
|
||||
.iter()
|
||||
.filter_map(|b| match b {
|
||||
Block::Para(p) => Some(p.text.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(texts, vec!["orld", "Foo", "Bar", "Trail"]);
|
||||
}
|
||||
|
||||
@@ -110,7 +110,17 @@ fn unmodelled_settings_survive_a_save_and_owned_ones_follow_the_model() {
|
||||
assert!(!s.contains("trackRevisions"), "{s}");
|
||||
assert_eq!(s.matches("compatibilityMode").count(), 1, "{s}");
|
||||
assert!(s.contains("mailMerge"), "{s}");
|
||||
assert!(text(&files, "word/_rels/settings.xml.rels").contains("file:///__wordcraft_missing_source__/letters.xlsx"));
|
||||
let rel_id = s
|
||||
.split("<w:dataSource")
|
||||
.nth(1)
|
||||
.and_then(|after| after.split("r:id=\"").nth(1))
|
||||
.and_then(|after| after.split('"').next())
|
||||
.expect("dataSource r:id");
|
||||
let rels = text(&files, "word/_rels/settings.xml.rels");
|
||||
let expected_rel = format!(
|
||||
r#"<Relationship Id="{rel_id}" Type="{REL}/mailMergeSource" Target="file:///__wordcraft_missing_source__/letters.xlsx" TargetMode="External"/>"#
|
||||
);
|
||||
assert!(rels.contains(&expected_rel), "missing matching relationship for {rel_id}: {rels}");
|
||||
// The privacy options are the model's (#1062): written once each, and gone when turned off.
|
||||
assert_eq!(s.matches("removePersonalInformation").count(), 1, "{s}");
|
||||
assert_eq!(s.matches("removeDateAndTime").count(), 1, "{s}");
|
||||
@@ -132,6 +142,37 @@ fn unmodelled_settings_survive_a_save_and_owned_ones_follow_the_model() {
|
||||
assert_eq!(text(&save(&again), "word/settings.xml"), s);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changed_zoom_survives_merged_settings_and_reads_back_as_page_width() {
|
||||
let old_zoom = r#"<w:zoom w:percent="120"/>"#;
|
||||
let updated_zoom = r#"<w:zoom w:val="bestFit" w:percent="145"/>"#;
|
||||
for original in [SETTINGS.to_string(), SETTINGS.replace(old_zoom, "")] {
|
||||
let mut doc = wordcraft_docx::read(&with_settings(&original)).unwrap();
|
||||
assert!(doc.passthrough.contains_key("wordcraft:settings.orig"));
|
||||
doc.settings.zoom = Some(wordcraft_doc::Zoom { percent: 145, fit: Some(wordcraft_doc::ZoomFit::PageWidth) });
|
||||
let bytes = wordcraft_docx::write(&doc).unwrap();
|
||||
let settings = text(&unzip(&bytes), "word/settings.xml");
|
||||
assert_eq!(settings.matches("<w:zoom ").count(), 1, "{settings}");
|
||||
assert!(settings.contains(updated_zoom), "{settings}");
|
||||
// The retained root and unrelated child bytes still belong to the original file.
|
||||
let root_end = original.find("><w:").unwrap() + 1;
|
||||
assert!(settings.starts_with(&original[..root_end]), "{settings}");
|
||||
for kept in [
|
||||
r#"<w:proofState w:spelling="clean" w:grammar="clean"/>"#,
|
||||
r#"<w:docVars><w:docVar w:name="ClauseSet" w:val="B"/></w:docVars>"#,
|
||||
r#"<w:rsids><w:rsidRoot w:val="00A1B2C3"/><w:rsid w:val="00A1B2C3"/></w:rsids>"#,
|
||||
] {
|
||||
assert!(settings.contains(kept), "{kept} lost: {settings}");
|
||||
}
|
||||
assert!(pos(&settings, "<w:zoom ") < pos(&settings, "<w:proofState"));
|
||||
let again = wordcraft_docx::read(&bytes).unwrap();
|
||||
let zoom = again.settings.zoom.unwrap();
|
||||
assert_eq!(zoom.percent, 145);
|
||||
assert!(matches!(zoom.fit, Some(wordcraft_doc::ZoomFit::PageWidth)));
|
||||
assert_eq!(text(&save(&again), "word/settings.xml"), settings);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_written_by_wordcraft_keep_no_original() {
|
||||
let doc = wordcraft_doc::Document::new();
|
||||
|
||||
@@ -532,6 +532,98 @@ Tools|Templates|Templates and Add-ins|tools.templates
|
||||
Tools|Views|Full Screen View|view.fullScreenView
|
||||
";
|
||||
|
||||
/// RFC-0052 hand marks for catalog features with no engine command: `id|headless|reach|why`.
|
||||
///
|
||||
/// `headless` is `no` or `partial`, `reach` is `window` (needs a desktop window, dialog or
|
||||
/// pointer), `os` (needs an OS or online service the engine doesn't wrap) or `engine-gap` (could
|
||||
/// be an engine command, isn't one yet). `yes` is never written here: a feature is `yes` only when
|
||||
/// its id is in the engine registry that `wordcraft-cli` and the MCP server load, and a mark on such
|
||||
/// an id is stale (`headless_errors`). A missing feature with no mark is `unknown`.
|
||||
pub const HEADLESS: &str = "\
|
||||
tools.dictate|no|os|speech recognition service
|
||||
insert.onlinePicture|no|os|online image search service
|
||||
insert.model3d|no|engine-gap|3-D model files could be inserted by a command
|
||||
insert.screenshot|no|os|screen capture of other windows
|
||||
addins.get|no|os|add-in store service
|
||||
insert.video|no|os|online video service
|
||||
insert.inkEquation|no|window|drawn with a pen or pointer
|
||||
draw.inkToMath|no|os|handwriting recognition service
|
||||
review.translate|no|os|online translation service
|
||||
review.blockAuthors|no|os|co-authoring service
|
||||
view.readLayout|no|window|Read Mode window layout
|
||||
";
|
||||
|
||||
/// One feature's RFC-0052 `headless:` value and, for `no`/`partial`, its `reach:` and reason.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Headless {
|
||||
pub value: &'static str,
|
||||
pub reach: Option<&'static str>,
|
||||
pub why: &'static str,
|
||||
}
|
||||
|
||||
const REACHES: [&str; 3] = ["window", "os", "engine-gap"];
|
||||
|
||||
/// Parsed `HEADLESS`-format marks: (id, value, reach, why). A malformed line is an error.
|
||||
pub fn headless_marks(src: &'static str) -> Result<Vec<(&'static str, Headless)>, String> {
|
||||
let mut out = Vec::new();
|
||||
for line in src.lines().filter(|l| !l.trim().is_empty()) {
|
||||
let f: Vec<&'static str> = line.splitn(4, '|').collect();
|
||||
let [id, value, reach, why] = f[..] else {
|
||||
return Err(format!("headless mark `{line}`: want `id|headless|reach|why`"));
|
||||
};
|
||||
if !matches!(value, "no" | "partial") {
|
||||
return Err(format!("headless mark `{id}`: `{value}` is not `no` or `partial` (`yes` comes from the registry)"));
|
||||
}
|
||||
if !REACHES.contains(&reach) {
|
||||
return Err(format!("headless mark `{id}`: reach `{reach}` is not window, os or engine-gap"));
|
||||
}
|
||||
if out.iter().any(|(m, _)| *m == id) {
|
||||
return Err(format!("headless mark `{id}` is written twice"));
|
||||
}
|
||||
out.push((id, Headless { value, reach: Some(reach), why }));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The `headless:` value of a catalog feature: `yes` when the engine registry has its id, else its
|
||||
/// hand mark, else `unknown`.
|
||||
pub fn headless_of(id: &str, live: bool, marks: &[(&'static str, Headless)]) -> Headless {
|
||||
if live {
|
||||
return Headless { value: "yes", reach: None, why: "" };
|
||||
}
|
||||
marks.iter().find(|(m, _)| *m == id).map(|(_, h)| *h).unwrap_or(Headless { value: "unknown", reach: None, why: "" })
|
||||
}
|
||||
|
||||
/// Problems with the marks against the catalog and the registry's ids: unknown ids, and marks on
|
||||
/// ids the engine registry has (they would hide a `yes`).
|
||||
pub fn headless_errors(src: &'static str, catalog: &[(&str, &str, &str, &str)], live: impl Fn(&str) -> bool) -> Vec<String> {
|
||||
let marks = match headless_marks(src) {
|
||||
Ok(m) => m,
|
||||
Err(e) => return vec![e],
|
||||
};
|
||||
let mut errs = Vec::new();
|
||||
for (id, _) in &marks {
|
||||
if !catalog.iter().any(|e| e.3 == *id) {
|
||||
errs.push(format!("headless mark `{id}` is not a catalog id"));
|
||||
} else if live(id) {
|
||||
errs.push(format!("headless mark `{id}` is stale: the engine registry has it, so it is `yes`"));
|
||||
}
|
||||
}
|
||||
errs
|
||||
}
|
||||
|
||||
/// Headless counts in the RFC-0052 summary shape.
|
||||
fn headless_summary(values: &[Headless]) -> Value {
|
||||
let count = |v: &str| values.iter().filter(|h| h.value == v).count();
|
||||
let no = |r: &str| values.iter().filter(|h| h.value == "no" && h.reach == Some(r)).count();
|
||||
json!({
|
||||
"yes": count("yes"),
|
||||
"no": {"window": no("window"), "os": no("os"), "engine-gap": no("engine-gap")},
|
||||
"partial": count("partial"),
|
||||
"unknown": count("unknown"),
|
||||
})
|
||||
}
|
||||
|
||||
/// Catalog entries: (tab, group, feature, id).
|
||||
pub fn entries() -> Vec<(&'static str, &'static str, &'static str, &'static str)> {
|
||||
CATALOG
|
||||
@@ -546,9 +638,13 @@ pub fn entries() -> Vec<(&'static str, &'static str, &'static str, &'static str)
|
||||
/// Parity summary: per tab and overall, with the missing features.
|
||||
pub fn parity(reg: &Registry) -> Value {
|
||||
let e = entries();
|
||||
let marks = headless_marks(HEADLESS).unwrap_or_default();
|
||||
let mut values = Vec::with_capacity(e.len());
|
||||
let mut tabs: Vec<(&str, usize, usize, Vec<String>)> = Vec::new();
|
||||
for (tab, group, label, id) in &e {
|
||||
let have = reg.get(id).is_some();
|
||||
let h = headless_of(id, have, &marks);
|
||||
values.push(h);
|
||||
let t = match tabs.iter_mut().find(|t| t.0 == *tab) {
|
||||
Some(t) => t,
|
||||
None => {
|
||||
@@ -564,7 +660,8 @@ pub fn parity(reg: &Registry) -> Value {
|
||||
if have {
|
||||
t.1 += 1;
|
||||
} else {
|
||||
t.3.push(format!("{group} › {label} (`{id}`)"));
|
||||
let reach = h.reach.map(|r| format!(", reach: {r} ({})", h.why)).unwrap_or_default();
|
||||
t.3.push(format!("{group} › {label} (`{id}`): headless: {}{reach}", h.value));
|
||||
}
|
||||
}
|
||||
let live = tabs.iter().map(|t| t.1).sum::<usize>();
|
||||
@@ -573,6 +670,7 @@ pub fn parity(reg: &Registry) -> Value {
|
||||
"live": live,
|
||||
"total": total,
|
||||
"percent": if total == 0 { 0.0 } else { (live as f64 * 1000.0 / total as f64).round() / 10.0 },
|
||||
"headless": headless_summary(&values),
|
||||
"tabs": tabs.iter().map(|t| json!({"tab": t.0, "live": t.1, "total": t.2, "missing": t.3})).collect::<Vec<_>>(),
|
||||
})
|
||||
}
|
||||
@@ -597,6 +695,44 @@ mod tests {
|
||||
assert!(pct >= 90.4, "parity {pct}%");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn headless_marks_are_current() {
|
||||
let reg = crate::cmd::registry();
|
||||
let errs = headless_errors(HEADLESS, &entries(), |id| reg.get(id).is_some());
|
||||
assert!(errs.is_empty(), "{errs:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn headless_yes_comes_only_from_the_registry() {
|
||||
let marks = headless_marks("a.b|no|window|pointer\n").unwrap();
|
||||
assert_eq!(headless_of("a.b", true, &marks).value, "yes", "a live id is yes whatever the mark says");
|
||||
assert_eq!(headless_of("a.b", false, &marks).reach, Some("window"));
|
||||
assert_eq!(headless_of("c.d", false, &marks).value, "unknown");
|
||||
assert!(headless_marks("a.b|yes|window|x\n").is_err(), "a hand-written yes is refused");
|
||||
assert!(headless_marks("a.b|no|desk|x\n").is_err(), "reach must be window, os or engine-gap");
|
||||
assert!(headless_marks("a.b|no\n").is_err());
|
||||
assert!(headless_marks("a.b|no|os|x\na.b|partial|os|y\n").is_err(), "one mark per id");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn headless_errors_flag_stale_and_unknown_marks() {
|
||||
let cat = [("T", "G", "F", "a.b"), ("T", "G", "H", "c.d")];
|
||||
let errs = headless_errors("a.b|no|os|x\nz.z|no|os|y\n", &cat, |id| id == "a.b");
|
||||
assert!(errs.iter().any(|e| e.contains("`a.b` is stale")), "{errs:?}");
|
||||
assert!(errs.iter().any(|e| e.contains("`z.z` is not a catalog id")), "{errs:?}");
|
||||
assert!(headless_errors("bad\n", &cat, |_| false).len() == 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parity_counts_every_feature_once_in_the_headless_summary() {
|
||||
let p = parity(&crate::cmd::registry());
|
||||
let h = &p["headless"];
|
||||
let n = |v: &Value| v.as_u64().unwrap_or(0);
|
||||
let no = n(&h["no"]["window"]) + n(&h["no"]["os"]) + n(&h["no"]["engine-gap"]);
|
||||
assert_eq!(n(&h["yes"]) + no + n(&h["partial"]) + n(&h["unknown"]), n(&p["total"]));
|
||||
assert_eq!(n(&h["yes"]), n(&p["live"]), "every live feature is an engine command here");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_mode_view_menu_is_catalogued() {
|
||||
let e = entries();
|
||||
|
||||
@@ -33,6 +33,7 @@ pub mod packs;
|
||||
pub mod page;
|
||||
pub mod para;
|
||||
pub mod paste;
|
||||
pub mod paste_cells;
|
||||
pub mod phonetic;
|
||||
pub mod protect;
|
||||
pub mod references;
|
||||
|
||||
@@ -35,6 +35,32 @@ pub fn selected_member(s: &Session) -> Option<(Pos, usize, &InlineObject)> {
|
||||
Some((pos, m.index, &c.obj))
|
||||
}
|
||||
|
||||
/// The canvas member whose text box story the caret is in (when no inner object is selected):
|
||||
/// the canvas's position, the member's index and the member.
|
||||
pub fn text_box_member(s: &Session) -> Option<(Pos, usize, &InlineObject)> {
|
||||
if super::objects::selected(s).is_some() {
|
||||
return None;
|
||||
}
|
||||
let StoryRef::Part(id) = s.sel.focus.story else { return None };
|
||||
if !s.doc.parts.get(&id).is_some_and(|p| p.kind == PartKind::TextBox) {
|
||||
return None;
|
||||
}
|
||||
let after = s.doc.text_box_anchor(id)?;
|
||||
let pos = Pos { off: after.off.checked_sub(wordcraft_doc::para::OBJ.len_utf8())?, ..after };
|
||||
let InlineObject::Group { children, canvas: Some(_), .. } = s.doc.para_at(&pos)?.object_at(pos.off)? else {
|
||||
return None;
|
||||
};
|
||||
let (index, c) =
|
||||
children.iter().enumerate().find(|(_, c)| pickable(c) && matches!(&c.obj, InlineObject::Shape { story: Some(sid), .. } if *sid == id))?;
|
||||
Some((pos, index, &c.obj))
|
||||
}
|
||||
|
||||
/// The canvas member object commands act on: one picked with `select.member`, or the text box
|
||||
/// member whose text the caret is in.
|
||||
pub(crate) fn active_member(s: &Session) -> Option<(Pos, usize, &InlineObject)> {
|
||||
selected_member(s).or_else(|| text_box_member(s))
|
||||
}
|
||||
|
||||
/// Whether a member can be picked on its own: a picture, shape or text box that is drawn (a
|
||||
/// group inside a canvas isn't, nor a hidden member).
|
||||
pub fn pickable(c: &GroupChild) -> bool {
|
||||
@@ -295,7 +321,13 @@ pub(crate) fn member_command(s: &mut Session, id: &str, _: &Value) -> Option<Cmd
|
||||
let replaces = (id.starts_with("text.") && id != "text.overtype")
|
||||
|| matches!(
|
||||
id,
|
||||
"edit.paste" | "edit.pasteText" | "edit.pasteMerge" | "edit.pasteSpecial" | "edit.pasteClipboardItem" | "edit.pasteAllClipboard"
|
||||
"edit.paste"
|
||||
| "edit.pasteText"
|
||||
| "edit.pasteMerge"
|
||||
| "edit.pasteNestedTable"
|
||||
| "edit.pasteSpecial"
|
||||
| "edit.pasteClipboardItem"
|
||||
| "edit.pasteAllClipboard"
|
||||
);
|
||||
if !replaces && !matches!(id, "edit.cut" | "edit.copy") {
|
||||
return None;
|
||||
@@ -350,7 +382,7 @@ fn remove_member(s: &mut Session, pos: &Pos, index: usize) -> Result<(), CmdErro
|
||||
/// Move or Resize with a member picked: `x`/`y` (the page point of its top-left, as dragging its
|
||||
/// frame gives it) and the size become its place and size in the canvas. `None`: no member.
|
||||
pub(crate) fn member_bounds(s: &mut Session, v: &Value) -> Option<CmdResult> {
|
||||
let (pos, index, obj) = selected_member(s)?;
|
||||
let (pos, index, obj) = active_member(s)?;
|
||||
let (w0, h0, _) = obj.frame()?;
|
||||
let min = super::objects::min_size(obj);
|
||||
let to = match (p::f32(v, "x"), p::f32(v, "y")) {
|
||||
@@ -381,7 +413,7 @@ pub(crate) fn member_bounds(s: &mut Session, v: &Value) -> Option<CmdResult> {
|
||||
|
||||
/// Nudge with a member picked: it moves inside the canvas. `None`: no member.
|
||||
pub(crate) fn member_nudge(s: &mut Session, dx: f32, dy: f32) -> Option<CmdResult> {
|
||||
let (pos, index, _) = selected_member(s)?;
|
||||
let (pos, index, _) = active_member(s)?;
|
||||
Some(edit_member(s, &pos, index, |_, (sx, sy), c| {
|
||||
c.x = (c.x + dx / sx).clamp(-MAX_SIDE, MAX_SIDE);
|
||||
c.y = (c.y + dy / sy).clamp(-MAX_SIDE, MAX_SIDE);
|
||||
@@ -406,10 +438,10 @@ fn edit_member(s: &mut Session, pos: &Pos, index: usize, f: impl FnOnce(wordcraf
|
||||
Ok(json!({"object": member, "pos": super::pos_json(pos), "member": index}))
|
||||
}
|
||||
|
||||
/// Change the picked member's own object (Shape Format, Size, Rotate, Alt Text) when `pos` is its
|
||||
/// canvas. `None`: no member picked there.
|
||||
/// Change the active member's own object (Shape Format, Size, Rotate, Alt Text) when `pos` is its
|
||||
/// canvas. `None`: no active member there.
|
||||
pub(crate) fn edit_member_object(s: &mut Session, pos: &Pos, f: impl Fn(&mut InlineObject)) -> Option<Result<InlineObject, CmdError>> {
|
||||
let (at, index, _) = selected_member(s).filter(|(at, ..)| at == pos)?;
|
||||
let (at, index, _) = active_member(s).filter(|(at, ..)| at == pos)?;
|
||||
let mut out = None;
|
||||
let r = edit_canvas(s, &at, |_, _, children| {
|
||||
if let Some(c) = children.get_mut(index) {
|
||||
|
||||
@@ -182,6 +182,9 @@ pub(crate) fn dispatch(s: &mut Session, id: &str, mutates: bool, run: fn(&mut Se
|
||||
_ if cells && (id.starts_with("table.") || matches!(id, "text.tab" | "text.backTab")) => run(s, v),
|
||||
// Copy and Cut of whole cells take a table of them (#1744).
|
||||
"edit.copy" | "edit.cut" if cells => run(s, v),
|
||||
// Paste can lay a copied table over the selected cells. Let it inspect the selection
|
||||
// before the ordinary column replacement deletes it.
|
||||
"edit.paste" if cells => run(s, v),
|
||||
"edit.copy" => copy(s, &segs),
|
||||
"edit.cut" => {
|
||||
let r = copy(s, &segs)?;
|
||||
@@ -209,6 +212,16 @@ pub(crate) fn dispatch(s: &mut Session, id: &str, mutates: bool, run: fn(&mut Se
|
||||
}
|
||||
}
|
||||
|
||||
/// Delete the pieces of a selected cell rectangle for an ordinary Paste replacement.
|
||||
pub(super) fn delete_cell_segments(s: &mut Session) -> Result<(), CmdError> {
|
||||
if s.cell_range().is_some()
|
||||
&& let Some(segments) = s.column_segments().map(<[(Pos, Pos)]>::to_vec)
|
||||
{
|
||||
delete(s, &segments)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Copy: one paragraph per block row (formatting kept); the plain text joins rows with newlines.
|
||||
fn copy(s: &mut Session, segs: &[(Pos, Pos)]) -> CmdResult {
|
||||
let mut blocks = Vec::new();
|
||||
|
||||
@@ -39,7 +39,7 @@ fn has_text_sel(s: &Session) -> Option<&'static str> {
|
||||
if s.sel.is_collapsed() { Some("nothing is selected") } else { None }
|
||||
}
|
||||
|
||||
/// Something to cut: text, or whole table cells (an empty cell's selection has no length, #1744).
|
||||
/// Something to cut: text, an object, or whole table cells (an empty cell's selection has no length, #1744).
|
||||
fn has_sel(s: &Session) -> Option<&'static str> {
|
||||
if s.sel.is_collapsed() && s.cell_range().is_none() { Some("nothing is selected") } else { None }
|
||||
}
|
||||
@@ -73,7 +73,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.key("Mod+Y / Mod+Shift+Z")
|
||||
.pure(),
|
||||
CommandSpec::new("edit.cut", "Cut", "Home › Clipboard", cut).key("Mod+X").when(has_sel),
|
||||
CommandSpec::new("edit.copy", "Copy", "Home › Clipboard", copy).key("Mod+C / Mod+Insert").pure(),
|
||||
CommandSpec::new("edit.copy", "Copy", "Home › Clipboard", copy).key("Mod+C / Mod+Insert").pure().when(has_sel),
|
||||
// Word's Spike (Ctrl+F3, Ctrl+Shift+F3; ⌘ on the Mac): the AutoText entry "Spike", so Quick
|
||||
// Parts and AutoText insert it without emptying it, as in Word.
|
||||
CommandSpec::new("edit.spike", "Spike", "Editing", spike).key("Mod+F3").when(has_text_sel),
|
||||
@@ -89,6 +89,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
CommandSpec::new("edit.paste", "Paste", "Home › Clipboard", paste)
|
||||
.key("Mod+V / Shift+Insert")
|
||||
.params(r#"{"text"?: string, "html"?: string, "rtf"?: string, "privateClipboard"?: bool}"#),
|
||||
CommandSpec::new("edit.pasteNestedTable", "Paste as Nested Table", "Home › Clipboard › Paste", paste_nested)
|
||||
.params(r#"{"text"?: string, "html"?: string, "rtf"?: string, "privateClipboard"?: bool} (a copied table with the caret in a table cell nests in that cell; Paste instead inserts its rows or overwrites the cells from the caret's)"#),
|
||||
CommandSpec::new("edit.pasteText", "Paste: Keep Text Only", "Home › Clipboard › Paste", paste_text)
|
||||
.params(r#"{"text"?: string}"#)
|
||||
.key("Mod+Shift+Alt+V"),
|
||||
@@ -185,6 +187,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
]
|
||||
}
|
||||
|
||||
/// Copy the selected text, object, or table cells to the clipboard.
|
||||
fn copy(s: &mut Session, _: &Value) -> CmdResult {
|
||||
let whole = super::table::selected_table(s);
|
||||
copy_with(s, whole.as_ref())
|
||||
@@ -218,6 +221,7 @@ pub(crate) fn copy_result(s: &mut Session) -> Value {
|
||||
(s.clipboard_html, s.clipboard_rtf) = match &s.clipboard {
|
||||
Some(f) => {
|
||||
let mut d = f.to_document();
|
||||
d.styles = s.doc.styles.clone();
|
||||
if d.media.is_empty() {
|
||||
d.media = s.doc.media.clone();
|
||||
}
|
||||
@@ -241,6 +245,7 @@ pub(crate) fn copy_result(s: &mut Session) -> Value {
|
||||
r
|
||||
}
|
||||
|
||||
/// Cut the selection, selected object, or whole table cells to the clipboard and remove it from the document.
|
||||
fn cut(s: &mut Session, _: &Value) -> CmdResult {
|
||||
let whole = super::table::selected_table(s);
|
||||
let r = copy_with(s, whole.as_ref())?;
|
||||
@@ -301,13 +306,30 @@ fn insert_spike(s: &mut Session, _: &Value) -> CmdResult {
|
||||
/// else another program's HTML or RTF (#687). The system clipboard's text has none, so it pastes
|
||||
/// as Keep Text Only does.
|
||||
fn paste(s: &mut Session, v: &Value) -> CmdResult {
|
||||
match super::paste::paste_content(s, v)? {
|
||||
let pasted = super::paste::paste_content(s, v)?;
|
||||
if let super::paste::Pasted::Fragment(frag) = &pasted
|
||||
&& super::paste_cells::paste_over_selection(s, frag)?
|
||||
{
|
||||
return sel_result(s);
|
||||
}
|
||||
super::column::delete_cell_segments(s)?;
|
||||
match pasted {
|
||||
super::paste::Pasted::Fragment(frag) => super::paste::insert(s, frag)?,
|
||||
super::paste::Pasted::Text(text) => super::paste::insert_text(s, &text)?,
|
||||
}
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
/// Paste as Nested Table: like Paste, but a copied table goes inside the cell the caret is in
|
||||
/// instead of laying its rows or cells over the table (#6739).
|
||||
fn paste_nested(s: &mut Session, v: &Value) -> CmdResult {
|
||||
match super::paste::paste_content(s, v)? {
|
||||
super::paste::Pasted::Fragment(frag) => super::paste::insert_as_is(s, frag)?,
|
||||
super::paste::Pasted::Text(text) => super::paste::insert_text(s, &text)?,
|
||||
}
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
/// Merge Formatting: the pasted text takes the destination's formatting, keeping its emphasis.
|
||||
fn paste_merge(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let mut frag = super::paste::paste_fragment(s, v)?;
|
||||
@@ -444,11 +466,17 @@ fn paste_clip_item(s: &mut Session, v: &Value) -> CmdResult {
|
||||
/// Every collected item, in the order they were copied (one undo step).
|
||||
fn paste_all_clips(s: &mut Session, _: &Value) -> CmdResult {
|
||||
let all: Vec<Fragment> = s.clip_history.items.iter().rev().map(|x| x.fragment.clone()).collect();
|
||||
let mut r = sel_result(s)?;
|
||||
let multiple = all.len() > 1;
|
||||
for f in all {
|
||||
r = paste_clip(s, f)?;
|
||||
if multiple {
|
||||
// Insert each item at the end of the last one. Cell paste can overwrite a
|
||||
// previous item or insert rows ahead of it.
|
||||
super::paste::insert_as_is(s, f)?;
|
||||
} else {
|
||||
return paste_clip(s, f);
|
||||
}
|
||||
}
|
||||
Ok(r)
|
||||
sel_result(s)
|
||||
}
|
||||
|
||||
fn paste_text(s: &mut Session, v: &Value) -> CmdResult {
|
||||
@@ -927,4 +955,32 @@ mod shortcut_tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copy_format_web_alias_respects_user_removal_and_reassignment() {
|
||||
use craft_keymap::{Binding, Chord, CommandRef, Overrides, Policy};
|
||||
|
||||
let mut commands = super::super::registry().all().to_vec();
|
||||
commands.iter_mut().find(|c| c.id == "edit.copyFormat").unwrap().shortcut = copy_format_shortcut(true);
|
||||
let registry = Registry::new(commands);
|
||||
|
||||
let mut keymap = crate::keymap::registry_keymap(®istry, &Overrides::default());
|
||||
let copy_cmd = CommandRef::new("edit.copyFormat");
|
||||
let bold_cmd = CommandRef::new("format.bold");
|
||||
let chord = Chord::parse("Mod+Alt+Shift+C").unwrap();
|
||||
let binding = Binding::parse("Mod+Alt+Shift+C").unwrap();
|
||||
|
||||
assert!(keymap.bindings(©_cmd).iter().any(|b| b.trigger.chord == chord));
|
||||
assert!(keymap.remove(©_cmd, &binding));
|
||||
assert_eq!(keymap.holder(&chord), None);
|
||||
|
||||
keymap.assign(&bold_cmd, binding, Policy::Steal).unwrap();
|
||||
assert_eq!(keymap.holder(&chord).as_ref().map(|c| c.id.as_str()), Some("format.bold"));
|
||||
assert_eq!(keymap.holder(&Chord::parse("Mod+Shift+C").unwrap()).as_ref().map(|c| c.id.as_str()), Some("edit.copyFormat"));
|
||||
|
||||
let overrides = keymap.overrides().clone();
|
||||
let restored = crate::keymap::registry_keymap(®istry, &overrides);
|
||||
assert_eq!(restored.holder(&chord).as_ref().map(|c| c.id.as_str()), Some("format.bold"));
|
||||
assert_eq!(restored.holder(&Chord::parse("Mod+Shift+C").unwrap()).as_ref().map(|c| c.id.as_str()), Some("edit.copyFormat"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -398,6 +398,28 @@ mod tests {
|
||||
assert!(!page_text(&mut s).contains("{ AUTHOR }"));
|
||||
}
|
||||
|
||||
/// #980: F11 is full screen, as people expect of a desktop app; the field walk keeps Word's
|
||||
/// other keys, Alt+F1 and Alt+Shift+F1 (and Shift+F11).
|
||||
#[test]
|
||||
fn f11_is_full_screen_and_alt_f1_walks_fields() {
|
||||
let s = Session::new(wordcraft_doc::Document::new());
|
||||
let keymap = crate::keymap::registry_keymap(&s.registry, s.keymap());
|
||||
let chord = |c: &str| craft_keymap::Chord::parse(c).unwrap();
|
||||
let key = |k: &str| keymap.holder(&chord(k)).map(|c| c.id);
|
||||
assert_eq!(key("F11").as_deref(), Some("view.fullScreen"));
|
||||
assert_eq!(key("Alt+F1").as_deref(), Some("fields.next"));
|
||||
assert_eq!(key("Alt+Shift+F1").as_deref(), Some("fields.previous"));
|
||||
assert_eq!(key("Shift+F11").as_deref(), Some("fields.previous"));
|
||||
assert_eq!(key("Mod+F11").as_deref(), Some("fields.lock"));
|
||||
let shortcut = s.registry.get("view.fullScreen").map(|c| c.shortcut);
|
||||
if cfg!(target_os = "macos") {
|
||||
assert_eq!(shortcut, Some("Mod+Ctrl+F / F11"));
|
||||
assert_eq!(key("Mod+Ctrl+F").as_deref(), Some("view.fullScreen"));
|
||||
} else {
|
||||
assert_eq!(shortcut, Some("F11"));
|
||||
}
|
||||
}
|
||||
|
||||
/// Editing a code changes the instruction and the result; lock keeps a result through updates;
|
||||
/// unlink turns the field into its text in one undo step; Alt+F1/Shift+F11 walk the fields.
|
||||
#[test]
|
||||
|
||||
@@ -117,9 +117,9 @@ fn place_picture(s: &mut Session, bytes: Vec<u8>, width: Option<f32>, alt: &str)
|
||||
None => return Err(CmdError::Failed("not a supported image (PNG, JPEG, GIF, WebP, BMP, TIFF, WMF, EMF)".into())),
|
||||
},
|
||||
};
|
||||
// Fitted to the room where it goes: the table cell, the column, its own section (#5428).
|
||||
let max_w = s.room_at(&s.sel.ordered().0);
|
||||
let key = s.doc.add_media(bytes, ext);
|
||||
// Fitted to the text width.
|
||||
let max_w = s.doc.sections().first().map(|(_, sp)| sp.text_width()).unwrap_or(468.0);
|
||||
let (mut w, mut h) = (natural_w, natural_h);
|
||||
if let Some(want) = width {
|
||||
// At most 22 inches, as for icons: a huge width made the height of a tall picture infinite.
|
||||
|
||||
@@ -32,11 +32,11 @@ pub(crate) use select::all_objects;
|
||||
pub(crate) use select::{edit_obj, has_shape_or_canvas};
|
||||
#[cfg(test)]
|
||||
use select::{has_group, holds_ink, obj_size, with_obj};
|
||||
pub use select::{min_size, object_selection, picked_objects, selected, selected_all};
|
||||
pub use select::{min_size, object_selection, picked_objects, selected, selected_all, selected_or_text_box, target_objects};
|
||||
#[cfg(test)]
|
||||
use shape::can_link;
|
||||
pub(crate) use shape::set_text_body;
|
||||
pub use shape::text_box_target;
|
||||
pub use shape::{text_box_target, text_box_targets};
|
||||
pub use specs::specs;
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::select::{edit_float, min_size, movable_story, obj_size, select_object, selected, with_obj};
|
||||
use super::select::{edit_float, min_size, movable_story, obj_size, select_object, selected_or_text_box, with_obj};
|
||||
use super::{CmdError, CmdResult, Float, InlineObject, Pos, Selection, Session, StoryRef, Value, Wrap, json, p};
|
||||
|
||||
/// Largest object offset or move, points.
|
||||
@@ -9,7 +9,7 @@ pub(super) fn bounds(s: &mut Session, v: &Value) -> CmdResult {
|
||||
if let Some(r) = crate::cmd::canvas::member_bounds(s, v) {
|
||||
return r;
|
||||
}
|
||||
let (pos, obj) = selected(s).ok_or_else(|| CmdError::Disabled("no picture or shape selected".into()))?;
|
||||
let (pos, obj) = selected_or_text_box(s).ok_or_else(|| CmdError::Disabled("no picture or shape selected".into()))?;
|
||||
let to = match (p::f32(v, "x"), p::f32(v, "y")) {
|
||||
(Some(x), Some(y)) => Some((x, y)),
|
||||
(None, None) => None,
|
||||
@@ -88,7 +88,7 @@ fn move_in_text(s: &mut Session, pos: Pos, to: &Pos) -> Result<Pos, CmdError> {
|
||||
/// (x, y), or for an In Line with Text object put it at the text position `to`, leaving the
|
||||
/// original in place and the clipboard alone. The copy is selected.
|
||||
pub(super) fn copy_to(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let (pos, obj) = selected(s).ok_or_else(|| CmdError::Disabled("no picture or shape selected".into()))?;
|
||||
let (pos, obj) = selected_or_text_box(s).ok_or_else(|| CmdError::Disabled("no picture or shape selected".into()))?;
|
||||
let len = wordcraft_doc::para::OBJ.len_utf8();
|
||||
let end = Pos { off: pos.off + len, ..pos.clone() };
|
||||
if let Some(to) = text_target(v, &obj)? {
|
||||
@@ -219,7 +219,7 @@ fn move_object_once(s: &mut Session, pos: &Pos, page: usize, x: f32, y: f32, (w,
|
||||
/// column / paragraph that keeps it where it is, so it can be moved by an offset.
|
||||
pub(super) fn unalign(s: &mut Session) -> Result<(), CmdError> {
|
||||
use wordcraft_doc::para::Anchor;
|
||||
let (pos, obj) = selected(s).ok_or_else(|| CmdError::Disabled("no picture or shape selected".into()))?;
|
||||
let (pos, obj) = selected_or_text_box(s).ok_or_else(|| CmdError::Disabled("no picture or shape selected".into()))?;
|
||||
let Some((_, _, float)) = obj.frame() else { return Ok(()) };
|
||||
if float.h_align.is_none() && float.v_align.is_none() {
|
||||
return Ok(());
|
||||
@@ -260,7 +260,7 @@ pub fn moves_with_text(f: &Float) -> bool {
|
||||
/// object's vertical position to its paragraph or to the page, keeping it where it is now.
|
||||
pub(super) fn move_with_text(s: &mut Session, with_text: bool) -> CmdResult {
|
||||
use wordcraft_doc::para::Anchor;
|
||||
let (pos, obj) = selected(s).ok_or_else(|| CmdError::Disabled("no picture or shape selected".into()))?;
|
||||
let (pos, obj) = selected_or_text_box(s).ok_or_else(|| CmdError::Disabled("no picture or shape selected".into()))?;
|
||||
let Some((_, _, float)) = obj.frame() else { return Err(CmdError::Disabled("select a floating picture or shape first".into())) };
|
||||
if moves_with_text(float) == with_text {
|
||||
return Ok(json!({"object": serde_json::to_value(&obj).unwrap_or(Value::Null)}));
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::select::{obj_size, selected, with_obj};
|
||||
use super::{CmdError, CmdResult, InlineObject, Rgb, Session, Value, Wrap, p};
|
||||
use super::select::{edit_obj, is_shape_or_canvas, obj_size, selected, target_objects, with_obj};
|
||||
use super::{CmdError, CmdResult, InlineObject, Pos, Rgb, Session, Value, Wrap, json, p};
|
||||
use wordcraft_doc::picfx::PicFx;
|
||||
|
||||
/// `picture.crop`: the crop, and optionally the new display size, as one edit. With a size, a
|
||||
@@ -70,19 +70,15 @@ pub fn cropped_original_size(s: &Session, o: &InlineObject) -> Option<(f32, f32)
|
||||
Some((orig.w * part(crop[0], crop[2]), orig.h * part(crop[1], crop[3])))
|
||||
}
|
||||
|
||||
/// Size: `scale` is a percentage of the current size, or with `original` of what the crop leaves
|
||||
/// of the original size (`original` alone gives that back: the Size dialog's Reset); then `width`
|
||||
/// and `height`, where one alone keeps the proportions unless `lockAspect` is false.
|
||||
pub(super) fn size(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let (_, o) = selected(s).ok_or_else(|| CmdError::Disabled("no object".into()))?;
|
||||
fn planned_size(s: &Session, o: &InlineObject, v: &Value) -> Result<(f32, f32), CmdError> {
|
||||
let lock = p::bool(v, "lockAspect").unwrap_or(true);
|
||||
let (w0, h0) = obj_size(&o);
|
||||
let (w0, h0) = obj_size(o);
|
||||
let (mut w, mut h) = (w0, h0);
|
||||
let scale = p::f32(v, "scale");
|
||||
let original = p::bool(v, "original").unwrap_or(false);
|
||||
if original {
|
||||
let (ow, oh) =
|
||||
cropped_original_size(s, &o).ok_or_else(|| CmdError::Disabled("only a picture whose image can be read has an original size".into()))?;
|
||||
cropped_original_size(s, o).ok_or_else(|| CmdError::Disabled("only a picture whose image can be read has an original size".into()))?;
|
||||
let k = scale.unwrap_or(100.0) / 100.0;
|
||||
(w, h) = (ow * k, oh * k);
|
||||
} else if let Some(sc) = scale {
|
||||
@@ -118,21 +114,55 @@ pub(super) fn size(s: &mut Session, v: &Value) -> CmdResult {
|
||||
// Sides set in proportion (from the original, or from a size whose sides both have a length)
|
||||
// fit the limits together. Otherwise each side the call sets fits on its own, and a side it
|
||||
// leaves as it was keeps its size, a straight line's 0 too.
|
||||
let (w, h) = if keep && (original || (w0 > 0.0 && h0 > 0.0 && (w, h) != (w0, h0))) {
|
||||
fit_size(w, h, true)
|
||||
if keep && (original || (w0 > 0.0 && h0 > 0.0 && (w, h) != (w0, h0))) {
|
||||
Ok(fit_size(w, h, true))
|
||||
} else {
|
||||
let (fw, fh) = fit_size(w, h, false);
|
||||
let left = |new: f32, old: f32| !original && new == old;
|
||||
(if left(w, w0) { w } else { fw }, if left(h, h0) { h } else { fh })
|
||||
};
|
||||
Ok((if left(w, w0) { w } else { fw }, if left(h, h0) { h } else { fh }))
|
||||
}
|
||||
}
|
||||
|
||||
fn size_matching(s: &mut Session, v: &Value, pred: impl Fn(&InlineObject) -> bool, empty_msg: &str) -> CmdResult {
|
||||
let targets = target_objects(s, pred);
|
||||
if targets.is_empty() {
|
||||
return Err(CmdError::Disabled(empty_msg.into()));
|
||||
}
|
||||
let planned: Vec<(Pos, f32, f32)> =
|
||||
targets.into_iter().map(|(pos, o)| planned_size(s, &o, v).map(|(w, h)| (pos, w, h))).collect::<Result<Vec<_>, _>>()?;
|
||||
// Any drawing: a group's members scale with its frame (its child space is kept); a chart or
|
||||
// SmartArt graphic lays itself out again at the new size.
|
||||
let theme = s.doc.settings.theme_colors.clone();
|
||||
with_obj(s, |o| {
|
||||
o.set_size(w, h);
|
||||
crate::cmd::chart::redraw(o, &theme);
|
||||
crate::cmd::smart_art::redraw(o, &theme);
|
||||
})
|
||||
let mut last = Value::Null;
|
||||
for (pos, w, h) in &planned {
|
||||
let o = edit_obj(s, pos, |o| {
|
||||
o.set_size(*w, *h);
|
||||
crate::cmd::chart::redraw(o, &theme);
|
||||
crate::cmd::smart_art::redraw(o, &theme);
|
||||
})?;
|
||||
last = serde_json::to_value(o).unwrap_or(Value::Null);
|
||||
}
|
||||
Ok(json!({"object": last, "count": planned.len()}))
|
||||
}
|
||||
|
||||
/// Size: `scale` is a percentage of the current size, or with `original` of what the crop leaves
|
||||
/// of the original size (`original` alone gives that back: the Size dialog's Reset); then `width`
|
||||
/// and `height`, where one alone keeps the proportions unless `lockAspect` is false.
|
||||
pub(super) fn size(s: &mut Session, v: &Value) -> CmdResult {
|
||||
size_matching(
|
||||
s,
|
||||
v,
|
||||
|o| match o {
|
||||
InlineObject::Graphic { graphic, .. } => graphic.chart.is_some() || graphic.smart_art.is_some(),
|
||||
_ => o.is_drawing(),
|
||||
},
|
||||
"no object",
|
||||
)
|
||||
}
|
||||
|
||||
/// Shape Size: resizes only selected shapes, text boxes, and drawing canvases (or the active text box).
|
||||
pub(super) fn shape_size(s: &mut Session, v: &Value) -> CmdResult {
|
||||
size_matching(s, v, is_shape_or_canvas, "no shape selected")
|
||||
}
|
||||
|
||||
/// An object size within 1–4000 pt. With `keep`, both sides scale by one factor, the one nearest
|
||||
|
||||
@@ -7,16 +7,18 @@ pub(super) fn has_picture(s: &Session) -> Option<&'static str> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Guard returning `None` when a picture, shape, or active text box is selected.
|
||||
pub(super) fn has_object(s: &Session) -> Option<&'static str> {
|
||||
if selected(s).is_some() { None } else { Some("select a picture or shape first") }
|
||||
if selected_or_text_box(s).is_some() { None } else { Some("select a picture or shape first") }
|
||||
}
|
||||
|
||||
/// Guard returning `None` when a floating picture, shape, or active text box is selected.
|
||||
pub(super) fn has_floating(s: &Session) -> Option<&'static str> {
|
||||
// A canvas member moves inside its canvas.
|
||||
if crate::cmd::canvas::selected_member(s).is_some() {
|
||||
if crate::cmd::canvas::active_member(s).is_some() {
|
||||
return None;
|
||||
}
|
||||
match selected(s) {
|
||||
match selected_or_text_box(s) {
|
||||
Some((_, InlineObject::Graphic { .. })) => Some(FROZEN),
|
||||
Some((_, o)) if o.is_floating() => None,
|
||||
_ => Some("select a floating picture or shape first"),
|
||||
@@ -55,10 +57,18 @@ pub(super) fn has_movable(s: &Session) -> Option<&'static str> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Guard returning `None` when at least one selected target (or active text box) is movable.
|
||||
pub(super) fn has_any_movable(s: &Session) -> Option<&'static str> {
|
||||
if !target_objects(s, |o| !matches!(o, InlineObject::Graphic { .. }) && o.is_drawing()).is_empty() {
|
||||
return None;
|
||||
}
|
||||
has_movable(s)
|
||||
}
|
||||
|
||||
/// `has_movable` for what places an object in the text (wrapping, position, alignment, Move with
|
||||
/// Text): not for a member picked inside a drawing canvas, which the canvas places.
|
||||
/// Text): not for a member inside a drawing canvas, which the canvas places.
|
||||
pub(super) fn has_placeable(s: &Session) -> Option<&'static str> {
|
||||
if crate::cmd::canvas::selected_member(s).is_some() {
|
||||
if crate::cmd::canvas::active_member(s).is_some() {
|
||||
return Some("a shape inside a drawing canvas is placed by the canvas");
|
||||
}
|
||||
has_movable(s)
|
||||
@@ -82,25 +92,33 @@ pub(super) fn has_group(s: &Session) -> Option<&'static str> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Shape Fill and Shape Outline: a shape, or a Drawing Canvas's background and border.
|
||||
/// Whether `o` is a shape, text box, or drawing canvas.
|
||||
pub(crate) fn is_shape_or_canvas(o: &InlineObject) -> bool {
|
||||
matches!(o, InlineObject::Shape { .. }) || o.is_canvas()
|
||||
}
|
||||
|
||||
/// Shape Fill and Shape Outline: any selected shape or Drawing Canvas, or the active text box.
|
||||
pub(crate) fn has_shape_or_canvas(s: &Session) -> Option<&'static str> {
|
||||
match selected(s) {
|
||||
Some((_, o)) if o.is_canvas() => None,
|
||||
_ => has_shape(s),
|
||||
}
|
||||
if target_objects(s, is_shape_or_canvas).is_empty() { Some("select a shape first") } else { None }
|
||||
}
|
||||
|
||||
pub(super) fn can_group(s: &Session) -> Option<&'static str> {
|
||||
if picked_objects(s).len() >= 2 { None } else { Some("select two or more pictures or shapes first (Shift+click)") }
|
||||
}
|
||||
|
||||
/// Guard returning `None` when a shape or active text box is selected.
|
||||
pub(super) fn has_shape(s: &Session) -> Option<&'static str> {
|
||||
match selected(s) {
|
||||
match selected_or_text_box(s) {
|
||||
Some((_, InlineObject::Shape { .. })) => None,
|
||||
_ => Some("select a shape first"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Guard returning `None` when any selected object (or the active text box) is a shape.
|
||||
pub(super) fn has_any_shape(s: &Session) -> Option<&'static str> {
|
||||
if target_objects(s, |o| matches!(o, InlineObject::Shape { .. })).is_empty() { Some("select a shape first") } else { None }
|
||||
}
|
||||
|
||||
/// The selection when it is exactly one picture, shape or text box (its U+FFFC), rather than
|
||||
/// text: what clicking an object selects.
|
||||
pub fn object_selection(s: &Session) -> Option<(Pos, &InlineObject)> {
|
||||
@@ -187,8 +205,51 @@ pub(super) fn alt_text(s: &mut Session, v: &Value) -> CmdResult {
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns the selected inline object, or the active text box containing the caret (including
|
||||
/// a text box member inside a Drawing Canvas; never an enclosing group or canvas).
|
||||
pub fn selected_or_text_box(s: &Session) -> Option<(Pos, InlineObject)> {
|
||||
if let Some((pos, o)) = selected(s) {
|
||||
return Some((pos, o));
|
||||
}
|
||||
if let Some((pos, _, member)) = crate::cmd::canvas::text_box_member(s) {
|
||||
return Some((pos, member.clone()));
|
||||
}
|
||||
let (pos, id) = super::shape::text_box_target(s)?;
|
||||
let o = s.doc.para_at(&pos)?.object_at(pos.off)?;
|
||||
matches!(o, InlineObject::Shape { story: Some(sid), .. } if *sid == id).then(|| (pos, o.clone()))
|
||||
}
|
||||
|
||||
/// Most objects one multi-object command changes.
|
||||
pub(crate) const MAX_TARGET_OBJECTS: usize = 10_000;
|
||||
|
||||
/// Selected objects matching `pred` (in the selection range or added with `select.addObject`),
|
||||
/// or — when nothing is selected — the active text box containing the caret if it matches `pred`.
|
||||
pub fn target_objects(s: &Session, pred: impl Fn(&InlineObject) -> bool) -> Vec<(Pos, InlineObject)> {
|
||||
if let Some((pos, _, member)) = crate::cmd::canvas::active_member(s) {
|
||||
return if pred(member) { vec![(pos, member.clone())] } else { Vec::new() };
|
||||
}
|
||||
let mut out: Vec<(Pos, InlineObject)> = selected_all(s, MAX_TARGET_OBJECTS).into_iter().filter(|(_, o)| pred(o)).collect();
|
||||
for pos in picked_objects(s) {
|
||||
if !out.iter().any(|(p, _)| p == &pos)
|
||||
&& let Some(o) = s.doc.para_at(&pos).and_then(|q| q.object_at(pos.off))
|
||||
&& pred(o)
|
||||
{
|
||||
out.push((pos, o.clone()));
|
||||
}
|
||||
}
|
||||
if out.is_empty()
|
||||
&& selected(s).is_none()
|
||||
&& let Some((pos, o)) = selected_or_text_box(s)
|
||||
&& pred(&o)
|
||||
{
|
||||
out.push((pos, o));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Mutates the selected picture or shape, or the active text box containing the caret.
|
||||
pub(super) fn with_obj(s: &mut Session, f: impl Fn(&mut InlineObject)) -> CmdResult {
|
||||
let (pos, _) = selected(s).ok_or_else(|| CmdError::Disabled("no picture or shape selected".into()))?;
|
||||
let (pos, _) = selected_or_text_box(s).ok_or_else(|| CmdError::Disabled("no picture or shape selected".into()))?;
|
||||
let o = edit_obj(s, &pos, f)?;
|
||||
Ok(json!({"object": serde_json::to_value(o).unwrap_or(Value::Null)}))
|
||||
}
|
||||
@@ -215,17 +276,38 @@ pub(super) fn edit_float(s: &mut Session, pos: &Pos, f: impl Fn(&mut Float)) ->
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn with_float(s: &mut Session, f: impl Fn(&mut Float)) -> CmdResult {
|
||||
with_obj(s, |o| {
|
||||
if let Some(float) = o.float_mut() {
|
||||
let was_inline = float.wrap == Wrap::Inline;
|
||||
f(float);
|
||||
// Word's distance from text for a newly wrapped object: 0.125" at the sides.
|
||||
if was_inline && float.wrap != Wrap::Inline && float.dist == 0.0 {
|
||||
float.dist = 9.0;
|
||||
}
|
||||
fn apply_float(o: &mut InlineObject, f: impl Fn(&mut Float)) {
|
||||
if let Some(float) = o.float_mut() {
|
||||
let was_inline = float.wrap == Wrap::Inline;
|
||||
f(float);
|
||||
// Word's distance from text for a newly wrapped object: 0.125" at the sides.
|
||||
if was_inline && float.wrap != Wrap::Inline && float.dist == 0.0 {
|
||||
float.dist = 9.0;
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn with_float(s: &mut Session, f: impl Fn(&mut Float)) -> CmdResult {
|
||||
with_obj(s, |o| apply_float(o, &f))
|
||||
}
|
||||
|
||||
/// Mutates `Float` on all selected targets matching `pred` (or the active text box if it matches).
|
||||
pub(super) fn with_floats_matching(s: &mut Session, pred: impl Fn(&InlineObject) -> bool, f: impl Fn(&mut Float)) -> CmdResult {
|
||||
let targets = target_objects(s, pred);
|
||||
if targets.is_empty() {
|
||||
return Err(CmdError::Disabled("no picture or shape selected".into()));
|
||||
}
|
||||
let mut last = Value::Null;
|
||||
for (pos, _) in &targets {
|
||||
let o = edit_obj(s, pos, |o| apply_float(o, &f))?;
|
||||
last = serde_json::to_value(o).unwrap_or(Value::Null);
|
||||
}
|
||||
Ok(json!({"object": last, "count": targets.len()}))
|
||||
}
|
||||
|
||||
/// Mutates `Float` on all selected movable objects (or the active text box).
|
||||
pub(super) fn with_movable_floats(s: &mut Session, f: impl Fn(&mut Float)) -> CmdResult {
|
||||
with_floats_matching(s, |o| !matches!(o, InlineObject::Graphic { .. }) && o.is_drawing(), f)
|
||||
}
|
||||
|
||||
/// The selected pictures, shapes, text boxes and groups: the one the selection holds, then
|
||||
|
||||
@@ -1,16 +1,37 @@
|
||||
use super::select::{all_objects, edit_obj, picked_objects, selected, selected_all};
|
||||
use super::select::{all_objects, edit_obj, picked_objects, selected, target_objects};
|
||||
use super::{CmdError, CmdResult, InlineObject, Pos, Rgb, Session, StoryRef, TextBody, Value, json, p};
|
||||
|
||||
pub(super) const NO_TEXT_BOX: &str = "select a text box first";
|
||||
|
||||
pub(super) fn has_text_box(s: &Session) -> Option<&'static str> {
|
||||
if text_box_target(s).is_some() { None } else { Some(NO_TEXT_BOX) }
|
||||
if text_box_targets(s).is_empty() { Some(NO_TEXT_BOX) } else { None }
|
||||
}
|
||||
|
||||
fn is_text_box(s: &Session, id: u32) -> bool {
|
||||
s.doc.parts.get(&id).is_some_and(|p| p.kind == wordcraft_doc::PartKind::TextBox)
|
||||
}
|
||||
|
||||
/// Target text boxes for Shape Format › Text commands: all selected text boxes (including
|
||||
/// those added with `select.addObject` or the active canvas text box member), falling back
|
||||
/// to the text box containing the caret when no object is selected.
|
||||
pub fn text_box_targets(s: &Session) -> Vec<(Pos, u32)> {
|
||||
let mut targets: Vec<(Pos, u32)> = target_objects(s, |o| matches!(o, InlineObject::Shape { story: Some(id), .. } if is_text_box(s, *id)))
|
||||
.into_iter()
|
||||
.filter_map(|(pos, o)| match o {
|
||||
InlineObject::Shape { story: Some(id), .. } => Some((pos, id)),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
if targets.is_empty()
|
||||
&& selected(s).is_none()
|
||||
&& picked_objects(s).is_empty()
|
||||
&& let Some(t) = text_box_target(s)
|
||||
{
|
||||
targets.push(t);
|
||||
}
|
||||
targets
|
||||
}
|
||||
|
||||
/// The text box the Shape Format › Text commands work on: the selected one, or the one whose
|
||||
/// text the caret is in. Its U+FFFC's position and its story.
|
||||
pub fn text_box_target(s: &Session) -> Option<(Pos, u32)> {
|
||||
@@ -28,15 +49,22 @@ pub fn text_box_target(s: &Session) -> Option<(Pos, u32)> {
|
||||
Some((Pos { off, ..after }, id))
|
||||
}
|
||||
|
||||
/// Change the target text box's text direction, alignment or link.
|
||||
/// Change the target text boxes' text direction, alignment or link.
|
||||
pub(crate) fn set_text_body(s: &mut Session, f: impl Fn(&mut TextBody)) -> CmdResult {
|
||||
let (pos, id) = text_box_target(s).ok_or_else(|| CmdError::Disabled(NO_TEXT_BOX.into()))?;
|
||||
let part = s.doc.parts.get_mut(&id).ok_or_else(|| CmdError::Failed("text box vanished".into()))?;
|
||||
f(&mut part.body);
|
||||
let body = part.body;
|
||||
// Its paragraph is laid out again.
|
||||
edit_obj(s, &pos, |_| {})?;
|
||||
Ok(json!({"textBox": id, "body": body}))
|
||||
let targets = text_box_targets(s);
|
||||
if targets.is_empty() {
|
||||
return Err(CmdError::Disabled(NO_TEXT_BOX.into()));
|
||||
}
|
||||
let mut last_id = 0;
|
||||
let mut last_body = TextBody::default();
|
||||
for (pos, id) in targets {
|
||||
let part = s.doc.parts.get_mut(&id).ok_or_else(|| CmdError::Failed("text box vanished".into()))?;
|
||||
f(&mut part.body);
|
||||
(last_id, last_body) = (id, part.body);
|
||||
// Its paragraph is laid out again.
|
||||
edit_obj(s, &pos, |_| {})?;
|
||||
}
|
||||
Ok(json!({"textBox": last_id, "body": last_body}))
|
||||
}
|
||||
|
||||
pub(super) fn can_link(s: &Session) -> Option<&'static str> {
|
||||
@@ -81,9 +109,6 @@ pub(super) fn link_text_box(s: &mut Session, v: &Value) -> CmdResult {
|
||||
Ok(json!({"textBox": from, "next": to}))
|
||||
}
|
||||
|
||||
/// Most shapes one `shape.effects` changes.
|
||||
const MAX_EFFECT_SHAPES: usize = 10_000;
|
||||
|
||||
/// `shape.effects`: set or clear the shadow, glow and soft edges of the selected shapes.
|
||||
pub(super) fn shape_effects(s: &mut Session, v: &Value) -> CmdResult {
|
||||
use wordcraft_doc::effects::{Glow, Shadow, ShapeEffects};
|
||||
@@ -133,19 +158,13 @@ pub(super) fn shape_effects(s: &mut Session, v: &Value) -> CmdResult {
|
||||
Some(n @ Value::Number(_)) => Some(n.as_f64().map(|x| x as f32)),
|
||||
Some(_) => return Err(CmdError::Params("`softEdge`: a radius in points or null".into())),
|
||||
};
|
||||
// The shapes in the selection and those added to it (Shift+click).
|
||||
let mut targets: Vec<Pos> =
|
||||
selected_all(s, MAX_EFFECT_SHAPES).into_iter().filter(|(_, o)| matches!(o, InlineObject::Shape { .. })).map(|(pos, _)| pos).collect();
|
||||
for pos in picked_objects(s) {
|
||||
if !targets.contains(&pos) && matches!(s.doc.para_at(&pos).and_then(|q| q.object_at(pos.off)), Some(InlineObject::Shape { .. })) {
|
||||
targets.push(pos);
|
||||
}
|
||||
}
|
||||
// The shapes in the selection, those added with `select.addObject`, or the active text box.
|
||||
let targets = target_objects(s, |o| matches!(o, InlineObject::Shape { .. }));
|
||||
if targets.is_empty() {
|
||||
return Err(CmdError::Disabled("no shape selected".into()));
|
||||
}
|
||||
let mut last = ShapeEffects::default();
|
||||
for pos in &targets {
|
||||
for (pos, _) in &targets {
|
||||
let o = edit_obj(s, pos, |o| {
|
||||
if let InlineObject::Shape { effects, float, .. } = o {
|
||||
let mut e = *effects;
|
||||
|
||||
@@ -1,14 +1,40 @@
|
||||
use super::arrange::{MAX_OFFSET, bounds, copy_to, move_with_text, unalign};
|
||||
use super::group::{add_object, group, ungroup};
|
||||
use super::picture::{adjust, adjust_media, clear_lum, crop, original_media, recolor, relook, remove_background, reset, size};
|
||||
use super::picture::{adjust, adjust_media, clear_lum, crop, original_media, recolor, relook, remove_background, reset, shape_size, size};
|
||||
use super::select::{
|
||||
all_objects, alt_text, can_group, edit_obj, has_floating, has_group, has_movable, has_object, has_picture, has_placeable, has_shape,
|
||||
has_shape_or_canvas, has_sizable, obj_size, objects_list, selected, with_float, with_obj,
|
||||
all_objects, alt_text, can_group, edit_obj, has_any_movable, has_any_shape, has_floating, has_group, has_movable, has_object, has_picture,
|
||||
has_placeable, has_shape, has_shape_or_canvas, has_sizable, is_shape_or_canvas, obj_size, objects_list, selected_or_text_box, target_objects,
|
||||
with_float, with_floats_matching, with_movable_floats, with_obj,
|
||||
};
|
||||
use super::shape::{NO_TEXT_BOX, can_link, has_text_box, link_text_box, set_text_body, shape_effects, text_box_target};
|
||||
use super::{CmdError, CommandSpec, InlineObject, Pos, Rgb, Selection, Spin, TextVert, VAlign, Wrap, WrapText, json, p, sel_result};
|
||||
use wordcraft_doc::picfx::PicFx;
|
||||
|
||||
fn run_rotation(s: &mut crate::Session, v: &serde_json::Value, pred: impl Fn(&InlineObject) -> bool) -> crate::CmdResult {
|
||||
let deg = p::req_f32(v, "degrees")?;
|
||||
let (fh, fv) = (p::bool(v, "flipH"), p::bool(v, "flipV"));
|
||||
with_floats_matching(s, pred, |f| {
|
||||
let cur = f.spin();
|
||||
f.set_spin(Spin::new(deg, fh.unwrap_or(cur.flip_h), fv.unwrap_or(cur.flip_v)));
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns the section properties of the target object's anchor story (including text boxes anchored
|
||||
/// in a later body section or header/footer), falling back to `page::sect`.
|
||||
fn target_sect(s: &crate::Session) -> wordcraft_doc::SectionProps {
|
||||
if let Some((pos, _)) = selected_or_text_box(s) {
|
||||
let i = match pos.story {
|
||||
wordcraft_doc::StoryRef::Body => s.doc.section_index_of(pos.path.0.first().copied().unwrap_or(0) as usize),
|
||||
wordcraft_doc::StoryRef::Part(id) => crate::cmd::page::section_of_part(s, id),
|
||||
};
|
||||
if let Some((_, sp)) = s.doc.sections().get(i) {
|
||||
return (*sp).clone();
|
||||
}
|
||||
}
|
||||
crate::cmd::page::sect(s)
|
||||
}
|
||||
|
||||
/// Returns all command specifications for objects (pictures, shapes, text boxes, and drawing canvases).
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
CommandSpec::new("picture.size", "Size", "Picture Format › Size", size)
|
||||
@@ -186,20 +212,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"right" => Spin::new(90.0, false, false),
|
||||
other => return Err(CmdError::Params(format!("unknown direction `{other}`"))),
|
||||
};
|
||||
with_float(s, |f| f.set_spin(f.spin().within(by)))
|
||||
with_movable_floats(s, |f| f.set_spin(f.spin().within(by)))
|
||||
})
|
||||
.params(r#"{"direction": "right|left|flipVertical|flipHorizontal"} (turns 90° or mirrors the selected picture, shape or text box; its pixels are kept)"#)
|
||||
.when(has_movable),
|
||||
.when(has_any_movable),
|
||||
CommandSpec::new("arrange.rotation", "Rotation", "Layout › Arrange", |s, v| {
|
||||
let deg = p::req_f32(v, "degrees")?;
|
||||
let (fh, fv) = (p::bool(v, "flipH"), p::bool(v, "flipV"));
|
||||
with_float(s, |f| {
|
||||
let cur = f.spin();
|
||||
f.set_spin(Spin::new(deg, fh.unwrap_or(cur.flip_h), fv.unwrap_or(cur.flip_v)));
|
||||
})
|
||||
run_rotation(s, v, |o| !matches!(o, InlineObject::Graphic { .. }) && o.is_drawing())
|
||||
})
|
||||
.params(r#"{"degrees": number, "flipH"?: bool, "flipV"?: bool} (the exact angle, clockwise, of the selected picture, shape or text box; normalised to 0–360)"#)
|
||||
.when(has_movable),
|
||||
.when(has_any_movable),
|
||||
CommandSpec::new("arrange.wrap", "Wrap Text", "Layout › Arrange", |s, v| {
|
||||
let wrap: Wrap = serde_json::from_value(v.get("wrap").cloned().unwrap_or(json!("square"))).map_err(|e| CmdError::Params(e.to_string()))?;
|
||||
with_float(s, |f| f.wrap = wrap)
|
||||
@@ -219,8 +240,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
CommandSpec::new("arrange.position", "Position", "Layout › Arrange", |s, v| {
|
||||
let preset = p::str(v, "preset").unwrap_or("middleCenter").to_string();
|
||||
let (x, y) = (p::f32(v, "x"), p::f32(v, "y"));
|
||||
let sect = crate::cmd::page::sect(s);
|
||||
let size = selected(s).map(|(_, o)| obj_size(&o)).unwrap_or((72.0, 72.0));
|
||||
let sect = target_sect(s);
|
||||
let size = selected_or_text_box(s).map(|(_, o)| obj_size(&o)).unwrap_or((72.0, 72.0));
|
||||
with_float(s, |f| {
|
||||
if f.wrap == Wrap::Inline {
|
||||
f.wrap = Wrap::Square;
|
||||
@@ -241,8 +262,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
CommandSpec::new("arrange.sendBackward", "Send Backward", "Layout › Arrange", |s, _| with_float(s, |f| f.wrap = Wrap::BehindText)).when(has_placeable),
|
||||
CommandSpec::new("arrange.align", "Align", "Layout › Arrange", |s, v| {
|
||||
let h = p::str(v, "value").unwrap_or("center").to_string();
|
||||
let tw = crate::cmd::page::sect(s).text_width();
|
||||
let w = selected(s).map(|(_, o)| obj_size(&o).0).unwrap_or(72.0);
|
||||
let tw = target_sect(s).text_width();
|
||||
let w = selected_or_text_box(s).map(|(_, o)| obj_size(&o).0).unwrap_or(72.0);
|
||||
with_float(s, |f| {
|
||||
if f.wrap == Wrap::Inline {
|
||||
f.wrap = Wrap::Square;
|
||||
@@ -297,31 +318,91 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.params(r#"{"index"?: n}"#)
|
||||
.pure(),
|
||||
CommandSpec::new("shape.outline", "Shape Outline", "Shape Format › Shape Styles", |s, v| {
|
||||
let c = p::str(v, "color").and_then(Rgb::parse);
|
||||
let w = p::f32(v, "width").map(|w| w.clamp(0.0, 72.0));
|
||||
with_obj(s, |o| {
|
||||
if let InlineObject::Shape { stroke, stroke_width, extra, .. } = o {
|
||||
*stroke = c;
|
||||
// A colour chosen here replaces an outline gradient from a file.
|
||||
extra.outline_fill = None;
|
||||
if let Some(w) = w {
|
||||
*stroke_width = w;
|
||||
}
|
||||
} else if let Some(style) = crate::cmd::canvas::style_mut(o) {
|
||||
style.stroke = c;
|
||||
if let Some(w) = w {
|
||||
style.stroke_width = w;
|
||||
}
|
||||
let color = match v.get("color") {
|
||||
None => None,
|
||||
Some(serde_json::Value::Null) => Some(None),
|
||||
Some(_) => {
|
||||
let hex = p::str(v, "color")
|
||||
.and_then(Rgb::parse)
|
||||
.ok_or_else(|| CmdError::Params("`color`: \"RRGGBB\" or null".into()))?;
|
||||
Some(Some(hex))
|
||||
}
|
||||
})
|
||||
};
|
||||
let w = p::f32(v, "width").map(|w| w.clamp(0.0, 72.0));
|
||||
let dash = match v.get("dash") {
|
||||
None => None,
|
||||
Some(val) => {
|
||||
let d = val.as_str().ok_or_else(|| {
|
||||
CmdError::Params(
|
||||
"`dash`: \"solid|dot|dash|lgDash|dashDot|lgDashDot|lgDashDotDot|sysDash|sysDot|sysDashDot|sysDashDotDot\"".into(),
|
||||
)
|
||||
})?;
|
||||
let parsed = wordcraft_doc::line_dash::LineDash::from_ooxml(d);
|
||||
if d != "solid" && parsed.is_solid() {
|
||||
return Err(CmdError::Params(format!("unknown `dash` preset `{d}`")));
|
||||
}
|
||||
Some(parsed)
|
||||
}
|
||||
};
|
||||
let cap = match v.get("cap") {
|
||||
None => None,
|
||||
Some(val) => {
|
||||
let c = val.as_str().ok_or_else(|| CmdError::Params("`cap`: \"flat|rnd|sq\"".into()))?;
|
||||
let parsed = wordcraft_doc::connector::LineCap::from_ooxml(c);
|
||||
if c != "flat" && parsed.is_flat() {
|
||||
return Err(CmdError::Params(format!("unknown `cap` style `{c}`")));
|
||||
}
|
||||
Some(parsed)
|
||||
}
|
||||
};
|
||||
let targets = target_objects(s, is_shape_or_canvas);
|
||||
if targets.is_empty() {
|
||||
return Err(CmdError::Disabled("no shape selected".into()));
|
||||
}
|
||||
let mut last = serde_json::Value::Null;
|
||||
for (pos, _) in &targets {
|
||||
let o = edit_obj(s, pos, |o| {
|
||||
if let InlineObject::Shape { stroke, stroke_width, extra, .. } = o {
|
||||
if let Some(c) = color {
|
||||
*stroke = c;
|
||||
// A colour chosen here replaces an outline gradient from a file.
|
||||
extra.outline_fill = None;
|
||||
}
|
||||
if let Some(w) = w {
|
||||
*stroke_width = w;
|
||||
}
|
||||
if let Some(d) = dash.clone() {
|
||||
extra.dash = d;
|
||||
}
|
||||
if let Some(cp) = cap {
|
||||
extra.cap = cp;
|
||||
}
|
||||
} else if let Some(style) = crate::cmd::canvas::style_mut(o) {
|
||||
if let Some(c) = color {
|
||||
style.stroke = c;
|
||||
}
|
||||
if let Some(w) = w {
|
||||
style.stroke_width = w;
|
||||
}
|
||||
}
|
||||
})?;
|
||||
last = serde_json::to_value(o).unwrap_or(serde_json::Value::Null);
|
||||
}
|
||||
Ok(json!({"object": last, "count": targets.len()}))
|
||||
})
|
||||
.params(r#"{"color": "RRGGBB" | null, "width"?: pt} (a selected drawing canvas: its border)"#)
|
||||
.params(r#"{"color"?: "RRGGBB" | null, "width"?: pt, "dash"?: "solid|dot|dash|lgDash|dashDot|lgDashDot|lgDashDotDot|sysDash|sysDot|sysDashDot|sysDashDotDot", "cap"?: "flat|rnd|sq"} (a selected drawing canvas: its border)"#)
|
||||
.when(has_shape_or_canvas),
|
||||
CommandSpec::new("shape.size", "Size", "Shape Format › Size", shape_size)
|
||||
.params(r#"{"width"?: pt, "height"?: pt, "lockAspect"?: bool, "scale"?: percent} (resizes the selected shapes, text boxes, and drawing canvases, or the active text box)"#)
|
||||
.when(has_shape_or_canvas),
|
||||
CommandSpec::new("shape.rotation", "Rotation", "Shape Format › Arrange", |s, v| run_rotation(s, v, is_shape_or_canvas))
|
||||
.params(r#"{"degrees": number, "flipH"?: bool, "flipV"?: bool} (rotates the selected shapes, text boxes, and drawing canvases, or the active text box)"#)
|
||||
.when(has_shape_or_canvas),
|
||||
CommandSpec::new("shape.effects", "Shape Effects", "Shape Format › Shape Styles", shape_effects)
|
||||
.params(
|
||||
r#"{"shadow"?: preset|{"preset"?, "color"?: "RRGGBB", "transparency"?: %, "blur"?: pt, "distance"?: pt, "angle"?: deg}|null, "glow"?: pt|{"color"?: "RRGGBB", "size"?: pt, "transparency"?: %}|null, "softEdge"?: pt|null} (shadow presets: offsetBottomRight, offsetBottom, offsetBottomLeft, offsetRight, offsetCenter, offsetLeft, offsetTopRight, offsetTop, offsetTopLeft; an omitted key is left as it is; applies to every shape in the selection)"#,
|
||||
)
|
||||
.when(has_shape),
|
||||
.when(has_any_shape),
|
||||
CommandSpec::new("shape.change", "Change Shape", "Shape Format › Insert Shapes", |s, v| {
|
||||
let kind: wordcraft_doc::para::ShapeKind = serde_json::from_value(v.get("kind").cloned().unwrap_or(json!("rectangle"))).map_err(|e| CmdError::Params(e.to_string()))?;
|
||||
with_obj(s, |o| {
|
||||
|
||||
@@ -1797,3 +1797,451 @@ fn only_ink_members_pin_a_group() {
|
||||
}
|
||||
assert!(!holds_ink(&group), "a group of charts is not pinned");
|
||||
}
|
||||
|
||||
/// Issue #5896: shape.outline can remove the frame (color: null), change width without
|
||||
/// erasing stroke color, set dash and cap, and acts on a text box while typing inside it.
|
||||
#[test]
|
||||
fn shape_outline_and_fill_on_text_box() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.run("insert.textBox", &json!({"text": "A text box with a frame"})).unwrap();
|
||||
// While typing inside the text box:
|
||||
// 1. shape.outline with {"color": null} removes the frame (stroke is None).
|
||||
s.run("shape.outline", &json!({"color": null})).unwrap();
|
||||
let (pos, _id) = text_box_target(&s).unwrap();
|
||||
let o = s.doc.para_at(&pos).unwrap().object_at(pos.off).unwrap();
|
||||
let InlineObject::Shape { stroke, .. } = o else { panic!("{o:?}") };
|
||||
assert_eq!(*stroke, None, "frame removed");
|
||||
|
||||
// 2. shape.outline can restore the frame with color, width, dash and cap:
|
||||
s.run("shape.outline", &json!({"color": "156082", "width": 1.5, "dash": "dash", "cap": "rnd"})).unwrap();
|
||||
let o = s.doc.para_at(&pos).unwrap().object_at(pos.off).unwrap();
|
||||
let InlineObject::Shape { stroke, stroke_width, extra, .. } = o else { panic!("{o:?}") };
|
||||
assert_eq!(*stroke, Some(Rgb(0x15, 0x60, 0x82)));
|
||||
assert_eq!(*stroke_width, 1.5);
|
||||
assert_eq!(extra.dash, wordcraft_doc::line_dash::LineDash::Dash);
|
||||
assert_eq!(extra.cap, wordcraft_doc::connector::LineCap::Round);
|
||||
|
||||
// 3. Changing only the width preserves the stroke color:
|
||||
s.run("shape.outline", &json!({"width": 3.0})).unwrap();
|
||||
let o = s.doc.para_at(&pos).unwrap().object_at(pos.off).unwrap();
|
||||
let InlineObject::Shape { stroke, stroke_width, .. } = o else { panic!("{o:?}") };
|
||||
assert_eq!(*stroke, Some(Rgb(0x15, 0x60, 0x82)), "color kept when width changed");
|
||||
assert_eq!(*stroke_width, 3.0);
|
||||
|
||||
// 4. Malformed non-null colors are rejected before mutation:
|
||||
assert!(matches!(s.run("shape.outline", &json!({"color": 123})), Err(CmdError::Params(_))));
|
||||
assert!(matches!(s.run("shape.outline", &json!({"color": "not-a-hex"})), Err(CmdError::Params(_))));
|
||||
let o = s.doc.para_at(&pos).unwrap().object_at(pos.off).unwrap();
|
||||
let InlineObject::Shape { stroke, .. } = o else { panic!("{o:?}") };
|
||||
assert_eq!(*stroke, Some(Rgb(0x15, 0x60, 0x82)), "color preserved on error");
|
||||
|
||||
// 5. Unlocked size edits preserve the other dimension:
|
||||
s.run("picture.size", &json!({"width": 100.0, "height": 80.0, "lockAspect": false})).unwrap();
|
||||
s.run("picture.size", &json!({"width": 250.0, "lockAspect": false})).unwrap();
|
||||
let o = s.doc.para_at(&pos).unwrap().object_at(pos.off).unwrap();
|
||||
let (w, h) = obj_size(o);
|
||||
assert_eq!((w, h), (250.0, 80.0), "height preserved on width edit");
|
||||
|
||||
s.run("picture.size", &json!({"height": 150.0, "lockAspect": false})).unwrap();
|
||||
let o = s.doc.para_at(&pos).unwrap().object_at(pos.off).unwrap();
|
||||
let (w, h) = obj_size(o);
|
||||
assert_eq!((w, h), (250.0, 150.0), "width preserved on height edit");
|
||||
|
||||
// 6. shape.effects targets the active text box when typing inside it:
|
||||
s.run("shape.effects", &json!({"shadow": "offsetBottomRight"})).unwrap();
|
||||
let o = s.doc.para_at(&pos).unwrap().object_at(pos.off).unwrap();
|
||||
let InlineObject::Shape { effects, .. } = o else { panic!("{o:?}") };
|
||||
assert!(effects.shadow.is_some(), "shadow applied to text box");
|
||||
|
||||
// 7. arrange.bounds targets the active text box when typing inside it:
|
||||
let caret_sel = s.sel.clone();
|
||||
s.run("arrange.bounds", &json!({"width": 300.0, "height": 180.0})).unwrap();
|
||||
let o = s.doc.para_at(&pos).unwrap().object_at(pos.off).unwrap();
|
||||
let (w, h) = obj_size(o);
|
||||
assert_eq!((w, h), (300.0, 180.0), "bounds applied to active text box");
|
||||
|
||||
// Restore typing caret inside text box so selected(&s) is None:
|
||||
s.sel = caret_sel.clone();
|
||||
assert!(selected(&s).is_none(), "caret is inside text box, no outer object selected");
|
||||
|
||||
// arrange.moveWithText targets the active text box once it is floating:
|
||||
assert!(s.run("arrange.moveWithText", &json!({"value": true})).is_err(), "inline text box cannot move with text");
|
||||
s.run("arrange.wrap", &json!({"wrap": "square"})).unwrap();
|
||||
s.sel = caret_sel;
|
||||
assert!(selected(&s).is_none(), "caret restored inside text box");
|
||||
s.run("arrange.moveWithText", &json!({"value": false})).unwrap();
|
||||
let o = s.doc.para_at(&pos).unwrap().object_at(pos.off).unwrap();
|
||||
let (_, _, float) = o.frame().unwrap();
|
||||
assert_eq!(float.v_rel, wordcraft_doc::para::Anchor::Page, "moveWithText targets active floating text box");
|
||||
|
||||
// 8. When a picture is selected, shape.fill, shape.effects, and shape.outline do not target the text box:
|
||||
let data = super::super::insert::base64_encode(&png(10, 10));
|
||||
s.run("insert.picture", &json!({"data": data})).unwrap();
|
||||
assert!(matches!(s.run("shape.fill", &json!({"color": "FF0000"})), Err(CmdError::Disabled(_))));
|
||||
assert!(matches!(s.run("shape.effects", &json!({"shadow": "none"})), Err(CmdError::Disabled(_))));
|
||||
assert!(matches!(s.run("shape.outline", &json!({"color": "FF0000"})), Err(CmdError::Disabled(_))));
|
||||
|
||||
// 9. fit_size normalizes NaN and clamps below 1 pt to 1 pt:
|
||||
assert_eq!(super::picture::fit_size(f32::NAN, 0.0, false), (1.0, 1.0));
|
||||
assert_eq!(super::picture::fit_size(-50.0, 0.0, false), (1.0, 1.0));
|
||||
}
|
||||
|
||||
/// Issue #5896: `arrange.align` and `arrange.position` use the active text box's own
|
||||
/// dimensions when invoked from a typing caret inside it, matching explicit object selection.
|
||||
#[test]
|
||||
fn arrange_align_and_position_on_active_text_box() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.run("insert.textBox", &json!({"text": "Sized text box"})).unwrap();
|
||||
let caret_sel = s.sel.clone();
|
||||
let (pos, _) = text_box_target(&s).unwrap();
|
||||
s.run("picture.size", &json!({"width": 250.0, "height": 140.0, "lockAspect": false})).unwrap();
|
||||
|
||||
let float_xy = |s: &Session| {
|
||||
let o = s.doc.para_at(&pos).unwrap().object_at(pos.off).unwrap();
|
||||
let (_, _, f) = o.frame().unwrap();
|
||||
(f.x, f.y)
|
||||
};
|
||||
|
||||
for value in ["center", "right"] {
|
||||
s.run("select.objects", &json!({"index": 0})).unwrap();
|
||||
s.run("arrange.align", &json!({"value": "left"})).unwrap();
|
||||
s.run("arrange.align", &json!({"value": value})).unwrap();
|
||||
let from_selected = float_xy(&s).0;
|
||||
|
||||
s.sel = caret_sel.clone();
|
||||
assert!(selected(&s).is_none(), "caret inside text box for align {value}");
|
||||
s.run("arrange.align", &json!({"value": "left"})).unwrap();
|
||||
s.run("arrange.align", &json!({"value": value})).unwrap();
|
||||
let from_caret = float_xy(&s).0;
|
||||
assert_eq!(from_caret, from_selected, "align {value} matches explicit selection");
|
||||
}
|
||||
|
||||
for preset in ["middleCenter", "bottomRight"] {
|
||||
s.run("select.objects", &json!({"index": 0})).unwrap();
|
||||
s.run("arrange.position", &json!({"preset": "topLeft"})).unwrap();
|
||||
s.run("arrange.position", &json!({"preset": preset})).unwrap();
|
||||
let from_selected = float_xy(&s);
|
||||
|
||||
s.sel = caret_sel.clone();
|
||||
assert!(selected(&s).is_none(), "caret inside text box for position {preset}");
|
||||
s.run("arrange.position", &json!({"preset": "topLeft"})).unwrap();
|
||||
s.run("arrange.position", &json!({"preset": preset})).unwrap();
|
||||
let from_caret = float_xy(&s);
|
||||
assert_eq!(from_caret, from_selected, "position {preset} matches explicit selection");
|
||||
}
|
||||
}
|
||||
|
||||
/// Issue #5896 P2: typing inside a canvas text box routes Fill, Outline, Effects, Size, and
|
||||
/// Rotation to that text box member (leaving the canvas and siblings untouched), keeps
|
||||
/// canvas-owned placement commands disabled, and keeps commands disabled inside a regular group.
|
||||
#[test]
|
||||
fn typing_in_canvas_text_box_formats_member_not_canvas() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.run("insert.canvas", &json!({"width": 400, "height": 300, "fill": "FFF2CC", "outline": "1F4E79"})).unwrap();
|
||||
s.run("insert.shape", &json!({"kind": "rectangle", "width": 100, "height": 40})).unwrap();
|
||||
s.run("select.objects", &json!({"index": 0})).unwrap();
|
||||
let tb_res = s.run("insert.textBox", &json!({"text": "Canvas note"})).unwrap();
|
||||
let tb_id = tb_res["story"].as_u64().unwrap() as u32;
|
||||
assert_eq!(s.sel.focus.story, StoryRef::Part(tb_id));
|
||||
assert!(selected(&s).is_none());
|
||||
assert!(crate::cmd::canvas::selected_member(&s).is_none());
|
||||
|
||||
s.run("shape.fill", &json!({"color": "FF0000"})).unwrap();
|
||||
s.run("shape.outline", &json!({"color": null})).unwrap();
|
||||
let canvas_mid = all_objects(&s).into_iter().next().unwrap().1;
|
||||
let InlineObject::Group { children: mid_children, .. } = &canvas_mid else { panic!("{canvas_mid:?}") };
|
||||
assert!(matches!(&mid_children[1].obj, InlineObject::Shape { stroke: None, .. }));
|
||||
assert_eq!(canvas_mid.canvas_style().and_then(|st| st.stroke), Rgb::parse("1F4E79"));
|
||||
|
||||
s.run("shape.outline", &json!({"color": "00AA00", "width": 2.0, "dash": "dash", "cap": "rnd"})).unwrap();
|
||||
s.run("shape.effects", &json!({"shadow": "offsetBottomRight"})).unwrap();
|
||||
s.run("picture.size", &json!({"width": 180.0, "height": 90.0, "lockAspect": false})).unwrap();
|
||||
s.run("arrange.rotation", &json!({"degrees": 15.0})).unwrap();
|
||||
|
||||
let canvas = all_objects(&s).into_iter().next().unwrap().1;
|
||||
let InlineObject::Group { w: cw, h: ch, float: cf, children, canvas: Some(style), .. } = &canvas else {
|
||||
panic!("expected canvas: {canvas:?}");
|
||||
};
|
||||
assert_eq!((*cw, *ch, cf.spin().deg), (400.0, 300.0, 0.0));
|
||||
assert_eq!(style.fill, Rgb::parse("FFF2CC").map(wordcraft_doc::fill::Fill::solid));
|
||||
assert_eq!(style.stroke, Rgb::parse("1F4E79"));
|
||||
assert_eq!(style.stroke_width, 0.75);
|
||||
|
||||
assert_eq!(obj_size(&children[0].obj), (100.0, 40.0), "sibling shape size untouched");
|
||||
let InlineObject::Shape { effects: sib_fx, .. } = &children[0].obj else { panic!() };
|
||||
assert!(sib_fx.shadow.is_none(), "sibling shape effects untouched");
|
||||
|
||||
let InlineObject::Shape { w, h, fill, stroke, stroke_width, float, effects, extra, story, .. } = &children[1].obj else {
|
||||
panic!("expected text box member");
|
||||
};
|
||||
assert_eq!(*story, Some(tb_id));
|
||||
assert_eq!((*w, *h), (180.0, 90.0));
|
||||
assert_eq!(*fill, Rgb::parse("FF0000").map(wordcraft_doc::fill::Fill::solid));
|
||||
assert_eq!(*stroke, Rgb::parse("00AA00"));
|
||||
assert_eq!(*stroke_width, 2.0);
|
||||
assert_eq!(extra.dash, wordcraft_doc::line_dash::LineDash::Dash);
|
||||
assert_eq!(extra.cap, wordcraft_doc::connector::LineCap::Round);
|
||||
assert!(effects.shadow.is_some());
|
||||
assert_eq!(float.spin().deg, 15.0);
|
||||
|
||||
for (cmd, params) in [
|
||||
("arrange.wrap", json!({"wrap": "square"})),
|
||||
("arrange.align", json!({"value": "center"})),
|
||||
("arrange.position", json!({"preset": "middleCenter"})),
|
||||
("arrange.moveWithText", json!({"value": true})),
|
||||
("arrange.copyTo", json!({"x": 50.0, "y": 50.0})),
|
||||
] {
|
||||
assert!(matches!(s.run(cmd, ¶ms), Err(CmdError::Disabled(_))), "{cmd} stays disabled for canvas member");
|
||||
}
|
||||
|
||||
// Regular group: typing inside a grouped text box leaves shape commands disabled without modifying the group.
|
||||
let mut g = Session::new(wordcraft_doc::Document::new());
|
||||
g.run("insert.shape", &json!({"kind": "rectangle"})).unwrap();
|
||||
g.run("arrange.wrap", &json!({"wrap": "square"})).unwrap();
|
||||
g.sel = Selection::caret(g.doc.end_of(StoryRef::Body));
|
||||
let grouped_tb_id = g.run("insert.textBox", &json!({"text": "Grouped note"})).unwrap()["story"].as_u64().unwrap() as u32;
|
||||
g.run("arrange.wrap", &json!({"wrap": "square"})).unwrap();
|
||||
g.run("select.objects", &json!({"index": 0})).unwrap();
|
||||
g.run("select.addObject", &json!({"index": 1})).unwrap();
|
||||
g.run("arrange.group", &json!({})).unwrap();
|
||||
g.sel = Selection::caret(g.doc.end_of(StoryRef::Part(grouped_tb_id)));
|
||||
let before_group = all_objects(&g).into_iter().next().unwrap().1;
|
||||
for (cmd, params) in [
|
||||
("shape.fill", json!({"color": "FF0000"})),
|
||||
("shape.outline", json!({"color": null})),
|
||||
("shape.effects", json!({"shadow": "offsetBottomRight"})),
|
||||
("picture.size", json!({"width": 180.0, "lockAspect": false})),
|
||||
("arrange.rotation", json!({"degrees": 15.0})),
|
||||
] {
|
||||
assert!(matches!(g.run(cmd, ¶ms), Err(CmdError::Disabled(_))), "{cmd} disabled inside regular group");
|
||||
}
|
||||
assert_eq!(all_objects(&g).into_iter().next().unwrap().1, before_group);
|
||||
}
|
||||
|
||||
/// Issue #5896: `shape.outline` rejects unknown or non-string `dash` and `cap` parameters
|
||||
/// instead of silently falling back to Solid / Flat.
|
||||
#[test]
|
||||
fn shape_outline_rejects_unknown_dash_and_cap() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.run("insert.shape", &json!({"kind": "rectangle"})).unwrap();
|
||||
s.run("shape.outline", &json!({"color": "156082", "width": 2.0, "dash": "dash", "cap": "rnd"})).unwrap();
|
||||
|
||||
for bad in
|
||||
[json!({"cap": "round"}), json!({"dash": "dotted"}), json!({"cap": 42}), json!({"dash": false}), json!({"dash": null}), json!({"cap": null})]
|
||||
{
|
||||
assert!(matches!(s.run("shape.outline", &bad), Err(CmdError::Params(_))), "expected Params error for {bad}");
|
||||
}
|
||||
|
||||
let (_, o) = selected(&s).unwrap();
|
||||
let InlineObject::Shape { stroke, stroke_width, extra, .. } = o else { panic!("{o:?}") };
|
||||
assert_eq!(stroke, Rgb::parse("156082"));
|
||||
assert_eq!(stroke_width, 2.0);
|
||||
assert_eq!(extra.dash, wordcraft_doc::line_dash::LineDash::Dash);
|
||||
assert_eq!(extra.cap, wordcraft_doc::connector::LineCap::Round);
|
||||
}
|
||||
|
||||
/// Issue #5896: with multiple shapes selected, Line and Layout commands update every selected target.
|
||||
#[test]
|
||||
fn multi_shape_selection_updates_outline_and_layout_on_all() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
let id0 = s.run("insert.textBox", &json!({"text": "First", "width": 120.0, "height": 60.0})).unwrap()["story"].as_u64().unwrap() as u32;
|
||||
s.run("arrange.wrap", &json!({"wrap": "square"})).unwrap();
|
||||
s.sel = Selection::caret(s.doc.end_of(StoryRef::Body));
|
||||
let id1 = s.run("insert.textBox", &json!({"text": "Second", "width": 200.0, "height": 90.0})).unwrap()["story"].as_u64().unwrap() as u32;
|
||||
s.run("arrange.wrap", &json!({"wrap": "square"})).unwrap();
|
||||
|
||||
s.run("select.objects", &json!({"index": 0})).unwrap();
|
||||
s.run("select.addObject", &json!({"index": 1})).unwrap();
|
||||
|
||||
s.run("shape.outline", &json!({"color": "156082", "width": 2.5, "dash": "lgDash", "cap": "sq"})).unwrap();
|
||||
s.run("picture.size", &json!({"width": 160.0, "lockAspect": false})).unwrap();
|
||||
s.run("arrange.rotation", &json!({"degrees": 30.0})).unwrap();
|
||||
s.run("shape.alignText", &json!({"anchor": "ctr"})).unwrap();
|
||||
s.run("shape.textDirection", &json!({"dir": "vert"})).unwrap();
|
||||
assert_eq!(picked_objects(&s).len(), 2, "multi-selection preserved across formatting and layout");
|
||||
|
||||
let objs = all_objects(&s);
|
||||
assert_eq!(objs.len(), 2);
|
||||
for (idx, ((_, o), expected_h)) in objs.iter().zip([60.0, 90.0]).enumerate() {
|
||||
let InlineObject::Shape { w, h, stroke, stroke_width, float, extra, .. } = o else { panic!("{o:?}") };
|
||||
assert_eq!((*w, *h), (160.0, expected_h), "box {idx} kept its own height");
|
||||
assert_eq!(*stroke, Rgb::parse("156082"), "box {idx} stroke");
|
||||
assert_eq!(*stroke_width, 2.5, "box {idx} stroke width");
|
||||
assert_eq!(extra.dash, wordcraft_doc::line_dash::LineDash::LongDash, "box {idx} dash");
|
||||
assert_eq!(extra.cap, wordcraft_doc::connector::LineCap::Square, "box {idx} cap");
|
||||
assert_eq!(float.spin().deg, 30.0, "box {idx} rotation");
|
||||
}
|
||||
for id in [id0, id1] {
|
||||
let body = s.doc.parts.get(&id).unwrap().body;
|
||||
assert_eq!(body.anchor, VAlign::Center);
|
||||
assert_eq!(body.vert, TextVert::Vert);
|
||||
}
|
||||
|
||||
s.run("shape.outline", &json!({"color": null})).unwrap();
|
||||
for (_, o) in all_objects(&s) {
|
||||
let InlineObject::Shape { stroke, .. } = o else { panic!("{o:?}") };
|
||||
assert_eq!(stroke, None);
|
||||
}
|
||||
}
|
||||
|
||||
/// Issue #5896: "No line", dash preset, and line cap set via `shape.outline` survive a DOCX save/open round trip.
|
||||
#[test]
|
||||
fn shape_outline_no_line_dash_and_cap_round_trip_docx() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.run("insert.textBox", &json!({"text": "Borderless"})).unwrap();
|
||||
s.run("shape.outline", &json!({"color": null})).unwrap();
|
||||
|
||||
s.sel = Selection::caret(s.doc.end_of(StoryRef::Body));
|
||||
s.run("insert.shape", &json!({"kind": "rectangle"})).unwrap();
|
||||
s.run("shape.outline", &json!({"color": "156082", "width": 2.25, "dash": "dashDot", "cap": "rnd"})).unwrap();
|
||||
|
||||
s.sel = Selection::caret(s.doc.end_of(StoryRef::Body));
|
||||
s.run("insert.shape", &json!({"kind": "ellipse"})).unwrap();
|
||||
s.run("shape.outline", &json!({"color": "C00000", "width": 1.5, "dash": "sysDot", "cap": "sq"})).unwrap();
|
||||
|
||||
let bytes = crate::io::save_bytes("out.docx", &s.doc).unwrap();
|
||||
let mut s2 = Session::new(wordcraft_doc::Document::new());
|
||||
s2.run("file.open", &json!({"path": "out.docx", "data": crate::cmd::insert::base64_encode(&bytes)})).unwrap();
|
||||
|
||||
let objs = all_objects(&s2);
|
||||
assert_eq!(objs.len(), 3);
|
||||
let InlineObject::Shape { stroke: tb_stroke, story, .. } = &objs[0].1 else { panic!("{:?}", objs[0]) };
|
||||
assert!(story.is_some());
|
||||
assert_eq!(*tb_stroke, None, "No line preserved through DOCX round trip");
|
||||
|
||||
let InlineObject::Shape { stroke, stroke_width, extra, .. } = &objs[1].1 else { panic!("{:?}", objs[1]) };
|
||||
assert_eq!(*stroke, Rgb::parse("156082"));
|
||||
assert!((*stroke_width - 2.25).abs() < 0.05, "width {stroke_width}");
|
||||
assert_eq!(extra.dash, wordcraft_doc::line_dash::LineDash::DashDot);
|
||||
assert_eq!(extra.cap, wordcraft_doc::connector::LineCap::Round);
|
||||
|
||||
let InlineObject::Shape { stroke, stroke_width, extra, .. } = &objs[2].1 else { panic!("{:?}", objs[2]) };
|
||||
assert_eq!(*stroke, Rgb::parse("C00000"));
|
||||
assert!((*stroke_width - 1.5).abs() < 0.05, "width {stroke_width}");
|
||||
assert_eq!(extra.dash, wordcraft_doc::line_dash::LineDash::SystemDot);
|
||||
assert_eq!(extra.cap, wordcraft_doc::connector::LineCap::Square);
|
||||
}
|
||||
|
||||
/// Issue #5896: mixed multi-selections enable `shape.fill`, `shape.outline`, `shape.effects`,
|
||||
/// `shape.alignText`, and `shape.textDirection` whenever at least one selected target matches.
|
||||
#[test]
|
||||
fn mixed_object_multi_selection_enables_shape_and_text_box_commands() {
|
||||
// Picture selected first + rectangle added via select.addObject.
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
let data = super::super::insert::base64_encode(&png(12, 12));
|
||||
s.run("insert.picture", &json!({"data": data, "width": 60})).unwrap();
|
||||
s.sel = Selection::caret(s.doc.end_of(StoryRef::Body));
|
||||
s.run("insert.shape", &json!({"kind": "rectangle"})).unwrap();
|
||||
s.run("select.objects", &json!({"index": 0})).unwrap();
|
||||
s.run("select.addObject", &json!({"index": 1})).unwrap();
|
||||
|
||||
s.run("shape.fill", &json!({"color": "00AA00"})).unwrap();
|
||||
s.run("shape.outline", &json!({"color": "FF0000", "dash": "dash"})).unwrap();
|
||||
s.run("shape.effects", &json!({"shadow": "offsetBottomRight"})).unwrap();
|
||||
assert!(matches!(s.run("shape.alignText", &json!({"anchor": "b"})), Err(CmdError::Disabled(_))));
|
||||
assert!(matches!(s.run("shape.textDirection", &json!({"dir": "vert"})), Err(CmdError::Disabled(_))));
|
||||
|
||||
let objs = all_objects(&s);
|
||||
assert!(matches!(&objs[0].1, InlineObject::Image { .. }));
|
||||
let InlineObject::Shape { fill, stroke, effects, extra, .. } = &objs[1].1 else { panic!("{:?}", objs[1]) };
|
||||
assert_eq!(*fill, Rgb::parse("00AA00").map(wordcraft_doc::fill::Fill::solid));
|
||||
assert_eq!(*stroke, Rgb::parse("FF0000"));
|
||||
assert_eq!(extra.dash, wordcraft_doc::line_dash::LineDash::Dash);
|
||||
assert!(effects.shadow.is_some());
|
||||
|
||||
// Plain shape selected first + text box added via select.addObject.
|
||||
let mut s2 = Session::new(wordcraft_doc::Document::new());
|
||||
s2.run("insert.shape", &json!({"kind": "rectangle"})).unwrap();
|
||||
s2.sel = Selection::caret(s2.doc.end_of(StoryRef::Body));
|
||||
let tb_id = s2.run("insert.textBox", &json!({"text": "Mixed box"})).unwrap()["story"].as_u64().unwrap() as u32;
|
||||
s2.run("select.objects", &json!({"index": 0})).unwrap();
|
||||
s2.run("select.addObject", &json!({"index": 1})).unwrap();
|
||||
|
||||
s2.run("shape.alignText", &json!({"anchor": "b"})).unwrap();
|
||||
s2.run("shape.textDirection", &json!({"dir": "vert270"})).unwrap();
|
||||
let body = s2.doc.parts.get(&tb_id).unwrap().body;
|
||||
assert_eq!(body.anchor, VAlign::Bottom);
|
||||
assert_eq!(body.vert, TextVert::Vert270);
|
||||
}
|
||||
|
||||
/// Issue #5896: `arrange.align` and `arrange.position` inside an active text box anchored in
|
||||
/// a later section use that anchor section's margins rather than section 0's.
|
||||
#[test]
|
||||
fn arrange_align_and_position_use_text_box_anchor_section() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.run("layout.break", &json!({"kind": "nextPage"})).unwrap();
|
||||
s.run("layout.margins", &json!({"left": 144.0, "right": 144.0})).unwrap();
|
||||
let sect1_tw = crate::cmd::page::sect(&s).text_width();
|
||||
let sect0_tw = s.doc.sections()[0].1.text_width();
|
||||
assert!(sect1_tw < sect0_tw, "section 1 has narrower text area");
|
||||
|
||||
s.run("insert.textBox", &json!({"text": "Section 1 box", "width": 100.0, "height": 50.0})).unwrap();
|
||||
s.run("arrange.align", &json!({"value": "right"})).unwrap();
|
||||
let (pos, o) = selected_or_text_box(&s).unwrap();
|
||||
let (_, _, f) = o.frame().unwrap();
|
||||
assert!((f.x - (sect1_tw - 100.0)).abs() < 0.01, "aligned to section 1 right margin ({} vs {})", f.x, sect1_tw - 100.0);
|
||||
|
||||
s.run("arrange.position", &json!({"preset": "topRight"})).unwrap();
|
||||
let o2 = s.doc.para_at(&pos).unwrap().object_at(pos.off).unwrap();
|
||||
let (_, _, f2) = o2.frame().unwrap();
|
||||
assert!((f2.x - (sect1_tw - 100.0)).abs() < 0.01, "positioned to section 1 right margin ({} vs {})", f2.x, sect1_tw - 100.0);
|
||||
}
|
||||
|
||||
/// Issue #5896: bulk rotation commands stay enabled when a chart is primary selection and a
|
||||
/// movable shape is added via `select.addObject`.
|
||||
#[test]
|
||||
fn chart_primary_with_added_shape_allows_rotation() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.run("insert.chart", &json!({"type": "column"})).unwrap();
|
||||
s.sel = Selection::caret(s.doc.end_of(StoryRef::Body));
|
||||
s.run("insert.shape", &json!({"kind": "rectangle"})).unwrap();
|
||||
s.run("select.objects", &json!({"index": 0})).unwrap();
|
||||
s.run("select.addObject", &json!({"index": 1})).unwrap();
|
||||
|
||||
s.run("arrange.rotation", &json!({"degrees": 45.0})).unwrap();
|
||||
s.run("arrange.rotate", &json!({"direction": "right"})).unwrap();
|
||||
let objs = all_objects(&s);
|
||||
let (_, _, chart_f) = objs[0].1.frame().unwrap();
|
||||
let (_, _, shape_f) = objs[1].1.frame().unwrap();
|
||||
assert_eq!(chart_f.spin().deg, 0.0);
|
||||
assert_eq!(shape_f.spin().deg, 135.0);
|
||||
}
|
||||
|
||||
/// Issue #5896: `shape.size` and `shape.rotation` only change shapes/canvases in a mixed
|
||||
/// Picture + Chart + Shape selection, while generic `picture.size` keeps resizing all targets.
|
||||
#[test]
|
||||
fn shape_size_and_rotation_only_affect_shapes_in_mixed_selection() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
let data = super::super::insert::base64_encode(&png(12, 12));
|
||||
s.run("insert.picture", &json!({"data": data})).unwrap();
|
||||
s.run("picture.size", &json!({"width": 60.0, "height": 40.0, "lockAspect": false})).unwrap();
|
||||
s.run("arrange.rotation", &json!({"degrees": 10.0})).unwrap();
|
||||
s.sel = Selection::caret(s.doc.end_of(StoryRef::Body));
|
||||
s.run("insert.chart", &json!({"type": "column"})).unwrap();
|
||||
let (chart_w0, chart_h0, _) = all_objects(&s)[1].1.frame().unwrap();
|
||||
s.sel = Selection::caret(s.doc.end_of(StoryRef::Body));
|
||||
s.run("insert.shape", &json!({"kind": "rectangle", "width": 150.0, "height": 80.0})).unwrap();
|
||||
|
||||
s.run("select.objects", &json!({"index": 0})).unwrap();
|
||||
s.run("select.addObject", &json!({"index": 1})).unwrap();
|
||||
s.run("select.addObject", &json!({"index": 2})).unwrap();
|
||||
|
||||
s.run("shape.size", &json!({"width": 210.0, "lockAspect": false})).unwrap();
|
||||
s.run("shape.rotation", &json!({"degrees": 45.0})).unwrap();
|
||||
assert_eq!(picked_objects(&s).len(), 3, "multi-selection preserved across shape.size and shape.rotation");
|
||||
|
||||
let objs = all_objects(&s);
|
||||
let (pw, ph, pf) = objs[0].1.frame().unwrap();
|
||||
assert_eq!((pw, ph, pf.spin().deg), (60.0, 40.0, 10.0), "picture untouched by shape.size/rotation");
|
||||
let (cw, ch, _) = objs[1].1.frame().unwrap();
|
||||
assert_eq!((cw, ch), (chart_w0, chart_h0), "chart untouched by shape.size");
|
||||
let (sw, sh, sf) = objs[2].1.frame().unwrap();
|
||||
assert_eq!((sw, sh, sf.spin().deg), (210.0, 80.0, 45.0), "shape updated");
|
||||
|
||||
// Generic picture.size continues to resize every sizable object in the selection.
|
||||
s.run("picture.size", &json!({"width": 180.0, "lockAspect": false})).unwrap();
|
||||
let objs2 = all_objects(&s);
|
||||
assert_eq!(objs2[0].1.frame().unwrap().0, 180.0);
|
||||
assert_eq!(objs2[1].1.frame().unwrap().0, 180.0);
|
||||
assert_eq!(objs2[2].1.frame().unwrap().0, 180.0);
|
||||
}
|
||||
|
||||
@@ -224,7 +224,7 @@ fn manual_hyphenation(s: &mut Session, v: &Value) -> CmdResult {
|
||||
Ok(best.map(|(_, v)| v).unwrap_or_else(|| json!({"done": true})))
|
||||
}
|
||||
|
||||
fn section_of_part(s: &Session, id: u32) -> usize {
|
||||
pub(crate) fn section_of_part(s: &Session, id: u32) -> usize {
|
||||
let sections = s.doc.sections();
|
||||
for (i, (_, sp)) in sections.iter().enumerate() {
|
||||
if [sp.headers.default, sp.headers.first, sp.headers.even, sp.footers.default, sp.footers.first, sp.footers.even].contains(&Some(id)) {
|
||||
|
||||
@@ -49,10 +49,12 @@ fn clip_text(s: &Session, v: &Value) -> Option<String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the string starts with an RTF file header.
|
||||
fn looks_like_rtf(t: &str) -> bool {
|
||||
t.trim_start().starts_with("{\\rtf")
|
||||
}
|
||||
|
||||
/// Whether the string looks like an HTML fragment.
|
||||
fn looks_like_html(t: &str) -> bool {
|
||||
let t = t.trim_start();
|
||||
t.starts_with('<') && (t.contains("</") || t.contains("/>"))
|
||||
@@ -65,18 +67,53 @@ fn owns_clipboard(v: &Value) -> bool {
|
||||
p::bool(v, "privateClipboard").unwrap_or(true)
|
||||
}
|
||||
|
||||
/// Accommodate macOS arboard wrapping: `<html><head>...</head><body>...</body></html>`.
|
||||
fn extract_body(html: &str) -> Option<&str> {
|
||||
let lower = html.to_ascii_lowercase();
|
||||
let body_start = lower.find("<body")?;
|
||||
let after_body = html.get(body_start..)?;
|
||||
let tag_end_rel = after_body.find('>')?;
|
||||
let tag_end = body_start.checked_add(tag_end_rel)?.checked_add(1)?;
|
||||
let end = lower.rfind("</body>")?;
|
||||
if tag_end <= end { html.get(tag_end..end) } else { None }
|
||||
}
|
||||
|
||||
/// Whether the supplied HTML string matches WordCraft's session clipboard HTML,
|
||||
/// accounting for macOS arboard wrapping.
|
||||
fn html_matches_clipboard(h: &str, clip: &str) -> bool {
|
||||
if h == clip {
|
||||
return true;
|
||||
}
|
||||
if clip.is_empty() {
|
||||
return false;
|
||||
}
|
||||
extract_body(h).is_some_and(|body| body == clip || body.trim() == clip.trim())
|
||||
}
|
||||
|
||||
/// Whether the clipboard payload matches WordCraft's session clipboard copy, so the session's
|
||||
/// formatted fragment can be used.
|
||||
pub(crate) fn matches_session_clipboard(s: &Session, v: &Value) -> bool {
|
||||
let text = p::str(v, "text").map(|t| t.replace("\r\n", "\n"));
|
||||
let html = p::str(v, "html");
|
||||
let rtf = p::str(v, "rtf");
|
||||
let has_rich = html.is_some_and(|h| !h.is_empty()) || rtf.is_some_and(|r| !r.is_empty());
|
||||
let html_matches = html.is_none_or(|h| html_matches_clipboard(h, &s.clipboard_html));
|
||||
let rtf_matches = rtf.is_none_or(|r| r == s.clipboard_rtf);
|
||||
|
||||
owns_clipboard(v)
|
||||
&& s.clipboard.as_ref().is_some_and(|f| {
|
||||
text.as_ref().is_none_or(|t| f.clipboard_text() == *t || (t.is_empty() && has_rich))
|
||||
&& html_matches
|
||||
&& rtf_matches
|
||||
&& (text.is_some() || has_rich || (html.is_none() && rtf.is_none()))
|
||||
})
|
||||
}
|
||||
|
||||
/// The source for a format, if the clipboard has it.
|
||||
fn source(s: &Session, v: &Value, fmt: &str) -> Option<String> {
|
||||
let non_empty = |t: String| if t.is_empty() { None } else { Some(t) };
|
||||
match fmt {
|
||||
"formatted" if owns_clipboard(v) => {
|
||||
let f = s.clipboard.as_ref()?;
|
||||
// System clipboard text that isn't our own copy means someone else copied since.
|
||||
match p::str(v, "text") {
|
||||
Some(t) if f.clipboard_text() != t.replace("\r\n", "\n") => None,
|
||||
_ => Some(String::new()),
|
||||
}
|
||||
}
|
||||
"formatted" if matches_session_clipboard(s, v) => Some(String::new()),
|
||||
"formatted" => None,
|
||||
"rtf" => p::str(v, "rtf").map(str::to_string).or_else(|| clip_text(s, v).filter(|t| looks_like_rtf(t))).and_then(non_empty),
|
||||
"html" => p::str(v, "html").map(str::to_string).or_else(|| clip_text(s, v).filter(|t| looks_like_html(t))).and_then(non_empty),
|
||||
@@ -289,17 +326,15 @@ pub fn paste_content(s: &mut Session, v: &Value) -> Result<Pasted, CmdError> {
|
||||
}
|
||||
|
||||
fn clipboard_content(s: &mut Session, v: &Value) -> Result<Pasted, CmdError> {
|
||||
let text = p::str(v, "text").map(|t| t.replace("\r\n", "\n"));
|
||||
if owns_clipboard(v)
|
||||
if matches_session_clipboard(s, v)
|
||||
&& let Some(f) = &s.clipboard
|
||||
&& text.as_ref().is_none_or(|t| f.clipboard_text() == *t)
|
||||
&& (text.is_some() || (p::str(v, "html").is_none() && p::str(v, "rtf").is_none()))
|
||||
{
|
||||
return Ok(Pasted::Fragment(f.clone()));
|
||||
}
|
||||
if let Some(f) = rich_fragment(s, v) {
|
||||
return Ok(Pasted::Fragment(f));
|
||||
}
|
||||
let text = p::str(v, "text").map(|t| t.replace("\r\n", "\n"));
|
||||
match text {
|
||||
Some(t) if !t.is_empty() => Ok(Pasted::Text(t)),
|
||||
_ => Err(CmdError::Failed("the clipboard is empty".into())),
|
||||
@@ -365,8 +400,19 @@ pub fn merge_formatting(s: &Session, frag: &mut Fragment) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Replace the selection with `frag`, marking it as an insertion under Track Changes.
|
||||
pub fn insert(s: &mut Session, mut frag: Fragment) -> Result<(), CmdError> {
|
||||
/// Paste `frag` at the selection. A copied table pasted with the caret in a table cell goes the way
|
||||
/// Word's Paste does it (rows inserted or cells overwritten, #6739; see [`super::paste_cells`]);
|
||||
/// anything else is [`insert_as_is`].
|
||||
pub fn insert(s: &mut Session, frag: Fragment) -> Result<(), CmdError> {
|
||||
if super::paste_cells::paste_cells(s, &frag)? {
|
||||
return Ok(());
|
||||
}
|
||||
insert_as_is(s, frag)
|
||||
}
|
||||
|
||||
/// Replace the selection with `frag`, marking it as an insertion under Track Changes. A table pasted
|
||||
/// with the caret in a cell nests in that cell (Word's Paste as Nested Table).
|
||||
pub fn insert_as_is(s: &mut Session, mut frag: Fragment) -> Result<(), CmdError> {
|
||||
// The pasted text keeps its own formatting; what Backspace carried over is not for after it (#6518).
|
||||
s.forget_carried();
|
||||
super::controls::prepare_edit(s)?;
|
||||
@@ -392,7 +438,11 @@ pub fn insert(s: &mut Session, mut frag: Fragment) -> Result<(), CmdError> {
|
||||
});
|
||||
}
|
||||
}
|
||||
let before_props = track.then(|| s.doc.para_at(&at).map(|p| p.props.clone())).flatten();
|
||||
let end = s.doc.insert_fragment(&at, &frag)?;
|
||||
if track && let Some(before) = before_props {
|
||||
crate::cmd::fmt_revisions::record_para_props(s, at.story, &at.path, &before)?;
|
||||
}
|
||||
// The paragraph marks the paste added are inserted too, so rejecting it joins the
|
||||
// paragraphs again. The last paragraph ends with the original mark and keeps it.
|
||||
if let Some(r) = rid
|
||||
@@ -449,10 +499,23 @@ pub(crate) fn unlink_sections(blocks: &mut [Block]) {
|
||||
/// lists and styles it refers to (renumbered so they can't collide with ours).
|
||||
fn adopt(s: &mut Session, src: Document) -> Fragment {
|
||||
let mut frag = s.doc.adopt(src);
|
||||
// Pasted pictures fit our text width, like Insert › Pictures (layout keeps their size).
|
||||
let max_w = crate::io::text_width(&s.doc);
|
||||
// Pasted pictures fit the room where they go, like Insert › Pictures: the table cell, the
|
||||
// column, its own section (#5428; layout keeps their size). Measured (a layout) only when
|
||||
// the fragment holds an inline picture.
|
||||
let mut has_picture = false;
|
||||
for b in &mut frag.blocks {
|
||||
crate::io::fit_block_pictures(b, max_w);
|
||||
each_para(b, 0, &mut |p| {
|
||||
has_picture |= p
|
||||
.objects
|
||||
.iter()
|
||||
.any(|o| matches!(o, wordcraft_doc::InlineObject::Image { float, .. } if float.wrap == wordcraft_doc::para::Wrap::Inline));
|
||||
});
|
||||
}
|
||||
if has_picture {
|
||||
let max_w = s.room_at(&s.sel.ordered().0);
|
||||
for b in &mut frag.blocks {
|
||||
crate::io::fit_block_pictures(b, max_w);
|
||||
}
|
||||
}
|
||||
unlink_sections(&mut frag.blocks);
|
||||
frag
|
||||
|
||||
@@ -0,0 +1,267 @@
|
||||
//! Paste with the caret inside a table cell (#6739). Word does not nest a copied table there (that
|
||||
//! is its Paste as Nested Table, `edit.pasteNestedTable` here); observed black-box with synthetic
|
||||
//! tables:
|
||||
//!
|
||||
//! - a copied table (or whole rows) whose caret is in the first column of a table of the same
|
||||
//! width: its rows are inserted above the caret's row;
|
||||
//! - otherwise the copied cells overwrite the cells from the caret's cell rightwards and down,
|
||||
//! adding the rows and columns they need (new cells empty).
|
||||
//!
|
||||
//! With a cell selection, Paste overwrites from its top-left, including when the copy is wider
|
||||
//! than the selection.
|
||||
//!
|
||||
//! Pasted cells take the destination's cell formatting (Word's default keeps the source's; not
|
||||
//! done yet). What this does not cover falls back to the old behaviour, a nested table (see
|
||||
//! [`paste_cells`]).
|
||||
|
||||
use wordcraft_doc::edit::Fragment;
|
||||
use wordcraft_doc::props::VMerge;
|
||||
use wordcraft_doc::table::{MAX_COLS, MAX_ROWS};
|
||||
use wordcraft_doc::{Block, Cell, InlineObject, Path, Pos, Row, StoryRef, Table};
|
||||
|
||||
use crate::{CmdError, Selection, Session};
|
||||
|
||||
/// The fragment's table when it is one table and nothing else (empty paragraphs around it aside).
|
||||
fn lone_table(frag: &Fragment) -> Option<&Table> {
|
||||
let mut table = None;
|
||||
for b in &frag.blocks {
|
||||
match b {
|
||||
Block::Table(t) if table.is_none() => table = Some(t),
|
||||
Block::Para(p) if p.is_empty() && p.objects.is_empty() => {}
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
table
|
||||
}
|
||||
|
||||
/// The width of a rectangular table that can be pasted cell by cell. Merges, offsets,
|
||||
/// objects and content control wrappers require preserving the table structure.
|
||||
fn plain_source(t: &Table) -> Option<usize> {
|
||||
let cols = t.rows.first()?.cells.len();
|
||||
let simple = |c: &Cell| {
|
||||
c.span() == 1
|
||||
&& c.props.vmerge == VMerge::None
|
||||
&& !c.blocks.is_empty()
|
||||
&& c.controls.is_empty()
|
||||
&& c.blocks.iter().all(|b| matches!(&**b, Block::Para(p) if p.objects.is_empty() && p.section.is_none()))
|
||||
};
|
||||
let ok = cols > 0
|
||||
&& t.controls.is_empty()
|
||||
&& t.rows.iter().all(|r| {
|
||||
r.cells.len() == cols
|
||||
&& r.first_grid() == 0
|
||||
&& r.grid_after() == 0
|
||||
&& r.props.exceptions.is_none()
|
||||
&& r.controls.is_empty()
|
||||
&& r.cells.iter().all(simple)
|
||||
});
|
||||
ok.then_some(cols)
|
||||
}
|
||||
|
||||
/// Whether the destination table's rows are a plain grid: one cell per grid column, no merges,
|
||||
/// offsets or row exceptions.
|
||||
fn plain_destination(t: &Table) -> bool {
|
||||
let cols = t.grid.len();
|
||||
cols > 0
|
||||
&& t.rows.iter().all(|r| {
|
||||
r.cells.len() == cols
|
||||
&& r.first_grid() == 0
|
||||
&& r.grid_after() == 0
|
||||
&& r.props.exceptions.is_none()
|
||||
&& r.cells.iter().all(|c| c.span() == 1 && c.props.vmerge == VMerge::None)
|
||||
})
|
||||
}
|
||||
|
||||
/// How deep [`has_control`] looks into tables nested in a cell; a deeper cell counts as holding a
|
||||
/// control, so a hostile document can't make the walk recurse without bound.
|
||||
const MAX_CONTROL_DEPTH: usize = 16;
|
||||
|
||||
/// Whether a cell holds a content control, or a control's start or end in its text, at any depth
|
||||
/// of nested tables, or a text box anchor (whose story may hold one): overwriting the cell
|
||||
/// replaces all of its blocks, which could remove a locked control (the caret's own cell is
|
||||
/// checked by the caller's edit rules).
|
||||
fn has_control(c: &Cell) -> bool {
|
||||
cell_has_control(c, 0)
|
||||
}
|
||||
|
||||
fn cell_has_control(c: &Cell, depth: usize) -> bool {
|
||||
if !c.controls.is_empty() || depth > MAX_CONTROL_DEPTH {
|
||||
return true;
|
||||
}
|
||||
c.blocks.iter().any(|b| match &**b {
|
||||
// A text box (or a group holding one) anchored here has its own story, which may hold a locked
|
||||
// control; it is not walked, so a cell with one counts as holding a control.
|
||||
Block::Para(p) => {
|
||||
p.objects.iter().any(|o| matches!(o, InlineObject::ControlStart { .. } | InlineObject::ControlEnd) || !o.text_boxes().is_empty())
|
||||
}
|
||||
Block::Table(t) => {
|
||||
!t.controls.is_empty() || t.rows.iter().any(|r| !r.controls.is_empty() || r.cells.iter().any(|c| cell_has_control(c, depth + 1)))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// What a paste into a cell does with the copied table `src` at (`row0`, `col0`) of `dest`.
|
||||
enum Plan {
|
||||
/// Insert the copy's rows above `row0`.
|
||||
InsertRows,
|
||||
/// Lay the copy's cells over the table from the cell.
|
||||
Overwrite,
|
||||
}
|
||||
|
||||
/// How `src` goes into `dest` at (`row0`, `col0`), or `None` when it can't be laid over it (the
|
||||
/// paste nests the table instead).
|
||||
fn plan(dest: &Table, src: &Table, src_cols: usize, row0: usize, col0: usize, allow_row_insertion: bool) -> Option<Plan> {
|
||||
if !plain_destination(dest) || col0 >= dest.grid.len() || row0 >= dest.rows.len() {
|
||||
return None;
|
||||
}
|
||||
let (src_rows, dest_cols) = (src.rows.len(), dest.grid.len());
|
||||
// A one-column table is a layout wrapper more often than a grid: a wider copy nests in it.
|
||||
if dest_cols == 1 && src_cols > 1 {
|
||||
return None;
|
||||
}
|
||||
// Word inserts whole rows above the caret's row when the caret is in the first column and
|
||||
// the rows are as wide as the table; a one-column table can't tell rows from a cell.
|
||||
if allow_row_insertion && col0 == 0 && src_cols == dest_cols && dest_cols > 1 {
|
||||
return (dest.rows.len().saturating_add(src_rows) <= MAX_ROWS).then_some(Plan::InsertRows);
|
||||
}
|
||||
if dest.rows.len().max(row0.saturating_add(src_rows)) > MAX_ROWS || dest_cols.max(col0.saturating_add(src_cols)) > MAX_COLS {
|
||||
return None;
|
||||
}
|
||||
// A wrapper may open before the first overwritten row or cell and close after the last.
|
||||
// Use ordinary paste for wrapped grids so an overwrite cannot bypass a structural control.
|
||||
if !dest.controls.is_empty() || dest.rows.iter().any(|row| !row.controls.is_empty() || row.cells.iter().any(|cell| !cell.controls.is_empty())) {
|
||||
return None;
|
||||
}
|
||||
let hit = |r: usize| dest.rows.get(r).is_some_and(|row| row.cells.iter().skip(col0).take(src_cols).any(has_control));
|
||||
(!(row0..row0.saturating_add(src_rows).min(dest.rows.len())).any(hit)).then_some(Plan::Overwrite)
|
||||
}
|
||||
|
||||
/// Overwrite cells from the top-left of a selection while it still identifies a rectangle.
|
||||
pub(super) fn paste_over_selection(s: &mut Session, frag: &Fragment) -> Result<bool, CmdError> {
|
||||
let Some(range) = s.cell_range() else { return Ok(false) };
|
||||
if s.doc.settings.track_changes || s.doc.control_at(&s.sel.ordered().0).is_some() {
|
||||
return Ok(false);
|
||||
}
|
||||
let Some(src) = lone_table(frag) else { return Ok(false) };
|
||||
let Some(src_cols) = plain_source(src) else { return Ok(false) };
|
||||
let (row, col) = (range.rows.0, range.cols.0);
|
||||
let story = range.story;
|
||||
let table = range.table.clone();
|
||||
let Some(dest) = s.doc.table(story, &table) else { return Ok(false) };
|
||||
let Some(edit) = plan(dest, src, src_cols, row, col, false) else { return Ok(false) };
|
||||
apply_plan(s, src, story, &table, row, col, edit)?;
|
||||
s.column = None;
|
||||
s.goal_x = None;
|
||||
s.pending = None;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// A copied table pasted with the caret in a table cell, as Word's default Paste does it.
|
||||
/// `false` (nothing done; the caller pastes as before, nesting the table) when:
|
||||
/// - the selection is not a caret in a cell, or the clipboard is not one table;
|
||||
/// - Track Changes is on (the cell edits aren't tracked here);
|
||||
/// - the copied table has merged cells, ragged rows, empty cells, pictures or other objects,
|
||||
/// a paragraph with a section break, or a control wrapping the table, a row or a cell;
|
||||
/// - the destination table has merged cells or offset rows, or an overwrite would affect a
|
||||
/// destination with structural wrappers or a cell containing a control in its blocks;
|
||||
/// - the caret is in a content control that shows its placeholder (the ordinary paste replaces
|
||||
/// the placeholder);
|
||||
/// - the destination has one column and the copy more (a layout wrapper), or the paste would pass
|
||||
/// the limits on a table's rows or columns.
|
||||
pub fn paste_cells(s: &mut Session, frag: &Fragment) -> Result<bool, CmdError> {
|
||||
if s.doc.settings.track_changes || !s.sel.is_collapsed() || s.cell_range().is_some() {
|
||||
return Ok(false);
|
||||
}
|
||||
let Some(src) = lone_table(frag) else { return Ok(false) };
|
||||
let Some(src_cols) = plain_source(src) else { return Ok(false) };
|
||||
let Some((tp, row0, col0)) = s.sel.focus.path.cell() else { return Ok(false) };
|
||||
let Some(dest) = s.doc.table(s.sel.focus.story, &tp) else { return Ok(false) };
|
||||
if plan(dest, src, src_cols, row0, col0, true).is_none() {
|
||||
return Ok(false);
|
||||
}
|
||||
// A caret in a control that shows its placeholder: the edit rules would select the
|
||||
// placeholder to replace it, which the row insertion would not do. The ordinary paste does.
|
||||
// This also covers a caret at the edge of such a control (drop-down, check box): rows used to
|
||||
// be inserted there, now the table nests. Overwrite already declined for cells with controls.
|
||||
if s.doc.control_at(&s.sel.focus).is_some_and(|r| r.control.showing_placeholder) {
|
||||
return Ok(false);
|
||||
}
|
||||
// Pasting ends Backspace's carried formatting, as in the ordinary paste path.
|
||||
s.forget_carried();
|
||||
// Protection: the edit rules may move the caret (to where typing goes) or refuse.
|
||||
if super::controls::prepare_edit(s)?.is_some() {
|
||||
// Normalizing the caret can enter a control and select its placeholder.
|
||||
// Let ordinary paste replace that selection.
|
||||
return Ok(false);
|
||||
}
|
||||
let at = s.sel.focus.clone();
|
||||
let Some((tp, row0, col0)) = at.path.cell() else { return Ok(false) };
|
||||
let story = at.story;
|
||||
let Some(dest) = s.doc.table(story, &tp) else { return Ok(false) };
|
||||
let Some(edit) = plan(dest, src, src_cols, row0, col0, true) else { return Ok(false) };
|
||||
apply_plan(s, src, story, &tp, row0, col0, edit)?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
fn apply_plan(s: &mut Session, src: &Table, story: StoryRef, tp: &Path, row0: usize, col0: usize, plan: Plan) -> Result<(), CmdError> {
|
||||
let t = s.doc.table_mut(story, tp)?;
|
||||
let first = match plan {
|
||||
Plan::InsertRows => insert_source_rows(t, src, row0),
|
||||
Plan::Overwrite => overwrite_cells(t, src, row0, col0),
|
||||
};
|
||||
super::table::touch_cells(s, tp)?;
|
||||
let mut path = tp.0.clone();
|
||||
path.extend([first.0 as u32, first.1 as u32, 0]);
|
||||
s.sel = Selection::caret(Pos { story, path: Path(path), off: 0 });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Insert the rows of `src` above row `at` of `t` (same column count), formatted as that row.
|
||||
/// Returns the (row, cell) of the first pasted cell.
|
||||
fn insert_source_rows(t: &mut Table, src: &Table, at: usize) -> (usize, usize) {
|
||||
let Some(template) = t.rows.get(at) else { return (at, 0) };
|
||||
let new_rows: Vec<Row> = src
|
||||
.rows
|
||||
.iter()
|
||||
.map(|sr| {
|
||||
let mut row = Row { props: template.props.clone(), ..Row::default() };
|
||||
row.props.header = false;
|
||||
row.cells = template
|
||||
.cells
|
||||
.iter()
|
||||
.zip(&sr.cells)
|
||||
.map(|(dc, sc)| {
|
||||
let mut c = Cell::empty();
|
||||
c.props = dc.props.clone();
|
||||
c.blocks = sc.blocks.clone();
|
||||
c
|
||||
})
|
||||
.collect();
|
||||
row
|
||||
})
|
||||
.collect();
|
||||
t.rows.splice(at..at, new_rows);
|
||||
(at, 0)
|
||||
}
|
||||
|
||||
/// Lay the cells of `src` over those of `t` from (`row0`, column `col0`), adding the rows and
|
||||
/// columns they need. Returns the (row, cell) of the first pasted cell.
|
||||
fn overwrite_cells(t: &mut Table, src: &Table, row0: usize, col0: usize) -> (usize, usize) {
|
||||
let src_cols = src.rows.first().map_or(0, |r| r.cells.len());
|
||||
while t.grid.len() < col0.saturating_add(src_cols) && t.grid.len() < MAX_COLS {
|
||||
t.insert_col(t.grid.len());
|
||||
}
|
||||
while t.rows.len() < row0.saturating_add(src.rows.len()) && t.rows.len() < MAX_ROWS {
|
||||
let at = t.rows.len();
|
||||
t.insert_row(at, at.saturating_sub(1));
|
||||
}
|
||||
for (i, sr) in src.rows.iter().enumerate() {
|
||||
let Some(row) = t.rows.get_mut(row0 + i) else { break };
|
||||
for (j, sc) in sr.cells.iter().enumerate() {
|
||||
if let Some(dc) = row.cells.get_mut(col0 + j) {
|
||||
dc.blocks = sc.blocks.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
(row0, col0)
|
||||
}
|
||||
@@ -1122,3 +1122,87 @@ mod spelling_navigation_tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// #6086 review: A pre-existing table whose cell paragraphs and runs are all redlined (including an
|
||||
/// empty cell with a deleted/inserted paragraph mark) is not a structural table revision; Accept
|
||||
/// All / Reject All and whole-table selection resolution must preserve the table shell.
|
||||
#[test]
|
||||
fn preexisting_table_with_redlined_cell_content_preserves_table_shell() {
|
||||
use std::sync::Arc;
|
||||
use wordcraft_doc::{Block, CharProps, Paragraph, Path, Pos, Revision, RevisionKind, StoryRef, table::Table};
|
||||
|
||||
struct Cleanup(std::path::PathBuf);
|
||||
impl Drop for Cleanup {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
let dir = std::env::temp_dir().join(format!("wc-review-preexisting-tbl-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let _cleanup = Cleanup(dir.clone());
|
||||
|
||||
let make_redlined_table = |del: bool| -> Document {
|
||||
let mut d = Document::new();
|
||||
let kind = if del { RevisionKind::Delete } else { RevisionKind::Insert };
|
||||
d.revisions.push(Revision::new(kind, "Alice", "2026-11-24T00:00:00Z"));
|
||||
let rev = Some(0);
|
||||
let mark_props = if del { CharProps { del: rev, ..Default::default() } } else { CharProps { ins: rev, ..Default::default() } };
|
||||
|
||||
let mut p0 = Paragraph::with_text("Cell text", mark_props.clone());
|
||||
p0.mark = mark_props.clone();
|
||||
let mut p1 = Paragraph::new();
|
||||
p1.mark = mark_props;
|
||||
|
||||
let mut t = Table::new(1, 2, 240.0);
|
||||
t.rows[0].cells[0].blocks = vec![Arc::new(Block::Para(p0))];
|
||||
t.rows[0].cells[1].blocks = vec![Arc::new(Block::Para(p1))];
|
||||
d.body = vec![Arc::new(Block::Table(t)), Arc::new(Block::Para(Paragraph::new()))];
|
||||
d
|
||||
};
|
||||
|
||||
let assert_shell_preserved = |doc: &Document, label: &str| {
|
||||
let tables: Vec<&Table> = doc.body.iter().filter_map(|b| b.as_table()).collect();
|
||||
assert_eq!(tables.len(), 1, "{label}: pre-existing table shell must remain");
|
||||
assert_eq!(tables[0].rows.len(), 1, "{label}: row count must remain 1");
|
||||
assert_eq!(tables[0].rows[0].cells.len(), 2, "{label}: cell count must remain 2");
|
||||
assert_eq!(tables[0].rows[0].cells[0].blocks[0].as_para().unwrap().plain_text(), "", "{label}: cell 0 text cleared");
|
||||
assert_eq!(tables[0].rows[0].cells[1].blocks[0].as_para().unwrap().plain_text(), "", "{label}: cell 1 stays empty");
|
||||
};
|
||||
|
||||
for (del, all_cmd, sel_cmd, label) in [
|
||||
(true, "review.acceptAll", "review.accept", "deleted cell content + Accept"),
|
||||
(false, "review.rejectAll", "review.reject", "inserted cell content + Reject"),
|
||||
] {
|
||||
let doc = make_redlined_table(del);
|
||||
|
||||
// Global Accept All / Reject All in memory.
|
||||
let mut s_all = Session::new(doc.clone());
|
||||
s_all.run(all_cmd, &json!({})).unwrap();
|
||||
assert_shell_preserved(&s_all.doc, &format!("{label} (in-memory all)"));
|
||||
assert!(s_all.run("review.changes", &json!({})).unwrap().as_array().unwrap().is_empty());
|
||||
|
||||
// Whole-body selection Accept / Reject.
|
||||
let mut s_body = Session::new(doc.clone());
|
||||
s_body.run("select.all", &json!({})).unwrap();
|
||||
s_body.run(sel_cmd, &json!({})).unwrap();
|
||||
assert_shell_preserved(&s_body.doc, &format!("{label} (whole-body sel)"));
|
||||
|
||||
// Whole-table selection Accept / Reject.
|
||||
let mut s_tbl = Session::new(doc.clone());
|
||||
s_tbl.sel = crate::Selection {
|
||||
anchor: Pos { story: StoryRef::Body, path: Path(vec![0, 0, 0, 0]), off: 0 },
|
||||
focus: Pos { story: StoryRef::Body, path: Path(vec![0, 0, 1, 0]), off: 0 },
|
||||
};
|
||||
s_tbl.run(sel_cmd, &json!({})).unwrap();
|
||||
assert_shell_preserved(&s_tbl.doc, &format!("{label} (whole-table sel)"));
|
||||
|
||||
// DOCX save/open round-trip followed by Accept All / Reject All.
|
||||
let path = dir.join(format!("preexisting-{del}.docx"));
|
||||
crate::io::save_path(&path, &doc).unwrap();
|
||||
let reopened = crate::io::open_path(&path).unwrap();
|
||||
let mut s_rt = Session::new(reopened);
|
||||
s_rt.run(all_cmd, &json!({})).unwrap();
|
||||
assert_shell_preserved(&s_rt.doc, &format!("{label} (DOCX round-trip all)"));
|
||||
assert!(s_rt.run("review.changes", &json!({})).unwrap().as_array().unwrap().is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,11 +9,9 @@ use wordcraft_doc::para::InlineObject;
|
||||
use wordcraft_doc::props::Rgb;
|
||||
use wordcraft_doc::wordart::GradStop;
|
||||
|
||||
use super::objects::{edit_obj, picked_objects, selected_all};
|
||||
use super::objects::{edit_obj, target_objects};
|
||||
use crate::{CmdError, CmdResult, CommandSpec, Session, p};
|
||||
|
||||
/// Most shapes one command fills (a selection over a whole document).
|
||||
const MAX_FILL_SHAPES: usize = 10_000;
|
||||
/// Most stops read from a command (the fill keeps at most `MAX_STOPS` after sanitizing).
|
||||
const MAX_PARAM_STOPS: usize = 64;
|
||||
|
||||
@@ -68,16 +66,9 @@ fn shape_fill(s: &mut Session, v: &Value) -> CmdResult {
|
||||
Ok(serde_json::json!({"object": last, "count": targets.len()}))
|
||||
}
|
||||
|
||||
/// The shapes and canvases in the selection and those added to it (Shift+click).
|
||||
/// The shapes and canvases in the selection, those added with `select.addObject`, or the active text box.
|
||||
fn targets(s: &Session) -> Vec<Pos> {
|
||||
let fillable = |o: &InlineObject| matches!(o, InlineObject::Shape { .. }) || o.is_canvas();
|
||||
let mut out: Vec<Pos> = selected_all(s, MAX_FILL_SHAPES).into_iter().filter(|(_, o)| fillable(o)).map(|(pos, _)| pos).collect();
|
||||
for pos in picked_objects(s) {
|
||||
if !out.contains(&pos) && s.doc.para_at(&pos).and_then(|q| q.object_at(pos.off)).is_some_and(fillable) {
|
||||
out.push(pos);
|
||||
}
|
||||
}
|
||||
out
|
||||
target_objects(s, |o| matches!(o, InlineObject::Shape { .. }) || o.is_canvas()).into_iter().map(|(pos, _)| pos).collect()
|
||||
}
|
||||
|
||||
fn color(v: &Value) -> Result<Rgb, CmdError> {
|
||||
|
||||
@@ -21,7 +21,7 @@ mod typing;
|
||||
|
||||
pub use autocorrect::{AUTOCORRECT, AutoCap, AutoCorrectPrefs, lenient_autocorrect};
|
||||
#[cfg(test)]
|
||||
use compare::{Op, collapse_noise_matches, lcs_ops};
|
||||
use compare::{Op, collapse_noise_matches, lcs_len, lcs_ops};
|
||||
pub use specs::specs;
|
||||
pub use typing::{INITIAL_CAPS_EXCEPTIONS, autocorrect, autocorrect_word, emphasis_autoformat, has_emphasis};
|
||||
pub(crate) use typing::{is_turkic, lower_char, upper_char};
|
||||
|
||||
@@ -204,6 +204,43 @@ impl Session {
|
||||
Arc::new(wordcraft_layout::layout(doc, &mut LayoutCache::new(), &opts))
|
||||
}
|
||||
|
||||
/// How wide a picture put in at `pos` may be, as Word fits an inserted or pasted picture
|
||||
/// (#5428): the room its paragraph's lines have (the width available to its widest laid-out line,
|
||||
/// so the paragraph's indents are already taken out; inside a table cell, the innermost cell's
|
||||
/// text area, nested tables included; a turned cell isn't measured and falls back to the
|
||||
/// column width), never wider than the column it is in, of its own section. The narrowest
|
||||
/// section's text width ([`crate::io::text_width`]) when `pos` isn't laid out. It is measured on the pages, whatever the view: Web Layout and Read Mode reflow the
|
||||
/// text to the window, and a picture put in there keeps the size it gets in the document.
|
||||
pub(crate) fn room_at(&mut self, pos: &wordcraft_doc::Pos) -> f32 {
|
||||
let first = crate::io::text_width(&self.doc);
|
||||
let l =
|
||||
if !self.view.read_mode && self.view.mode == ViewMode::Print { self.layout() } else { self.output_layout_of(&self.doc, false, false) };
|
||||
let Some((caret, page)) = l.caret_on(pos, self.page_hint).and_then(|c| Some((c, l.pages.get(c.page)?))) else { return first };
|
||||
// A page can hold several continuous sections: the body's own comes from the position.
|
||||
let at = match (pos.story, pos.path.0.first()) {
|
||||
(StoryRef::Body, Some(b)) => self.doc.section_index_of(*b as usize),
|
||||
_ => page.section,
|
||||
};
|
||||
let section = self.doc.sections().get(at).map(|(_, sp)| (*sp).clone());
|
||||
let column = match (§ion, pos.story) {
|
||||
(Some(sp), StoryRef::Body) => {
|
||||
let boxes = sp.column_boxes();
|
||||
let x = caret.x - page.body.x;
|
||||
boxes.iter().find(|(cx, w)| x >= cx - 0.5 && x <= cx + w + 0.5).map_or_else(|| sp.text_width(), |(_, w)| *w)
|
||||
}
|
||||
(Some(sp), StoryRef::Part(_)) => sp.text_width(),
|
||||
(None, _) => first,
|
||||
};
|
||||
let lines = wordcraft_layout::hit::page_lines(page, pos.story)
|
||||
.iter()
|
||||
.filter(|h| *h.path == pos.path)
|
||||
.map(|h| h.right - h.left)
|
||||
.filter(|w| w.is_finite())
|
||||
.fold(0.0f32, f32::max);
|
||||
let room = if lines >= 1.0 { lines.min(column) } else { column };
|
||||
if room.is_finite() && room >= 1.0 { room } else { first }
|
||||
}
|
||||
|
||||
/// Invalidate the cached layout (fonts changed etc.).
|
||||
pub fn relayout(&mut self) {
|
||||
self.layout = Default::default();
|
||||
|
||||
@@ -443,7 +443,22 @@ impl Session {
|
||||
crate::cmd::outline::after_command(self, sel_before, self.rev != rev_before);
|
||||
// Extra selected objects last until something else is edited or selected; formatting
|
||||
// them keeps them selected, as in Word.
|
||||
if !matches!(id, "select.addObject" | "arrange.ungroup" | "shape.fill" | "shape.effects") && (spec.mutates || self.sel != *sel_before) {
|
||||
let keeps_multi_select = matches!(id, "select.addObject" | "arrange.ungroup")
|
||||
|| (self.sel == *sel_before
|
||||
&& matches!(
|
||||
id,
|
||||
"shape.fill"
|
||||
| "shape.effects"
|
||||
| "shape.outline"
|
||||
| "shape.size"
|
||||
| "shape.rotation"
|
||||
| "picture.size"
|
||||
| "arrange.rotate"
|
||||
| "arrange.rotation"
|
||||
| "shape.alignText"
|
||||
| "shape.textDirection"
|
||||
));
|
||||
if !keeps_multi_select && (spec.mutates || self.sel != *sel_before) {
|
||||
self.also_selected.clear();
|
||||
}
|
||||
// A canvas member stays picked while its canvas does and nothing else is selected.
|
||||
|
||||
@@ -20,6 +20,7 @@ mod fonts;
|
||||
mod ime_noop;
|
||||
mod page_number_formats_in_lists;
|
||||
mod para_tools;
|
||||
mod paste_table_in_cell;
|
||||
mod revision_checks;
|
||||
mod typing;
|
||||
mod wordart;
|
||||
@@ -1662,10 +1663,9 @@ fn copying_puts_rtf_on_the_clipboard() {
|
||||
assert!(r["rtf"].as_str().is_some_and(|t| t.starts_with("{\\rtf1") && t.contains("bold")), "{r}");
|
||||
assert_eq!(text(&s).lines().next(), Some("plain "));
|
||||
|
||||
// Nothing selected: nothing copied, no RTF.
|
||||
// Nothing selected: Copy is refused, so nothing is copied.
|
||||
run(&mut s, "caret.docEnd", json!({}));
|
||||
let r = run(&mut s, "edit.copy", json!({}));
|
||||
assert!(r.get("rtf").is_none(), "{r}");
|
||||
assert!(s.run("edit.copy", &json!({})).is_err(), "Copy with nothing selected");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -2070,6 +2070,205 @@ fn paste_keeps_source_formatting_from_other_programs() {
|
||||
assert_eq!(props_at(&s, 4).italic, Some(true));
|
||||
}
|
||||
|
||||
/// Verify that pasting syntax-highlighted code from VS Code retains syntax colors and font styling
|
||||
/// without inheriting dark background shading strips from outer container elements (#6157).
|
||||
#[test]
|
||||
fn pasted_code_from_vscode_has_syntax_colors_and_no_character_shading() {
|
||||
// #6157: VS Code wraps copied code in an outer div with `background-color: #1e1e1e`.
|
||||
// In Word and per CSS (background-color does not inherit), pasting into a document keeps the
|
||||
// syntax colors and mono font without painting dark character shading strips over the runs.
|
||||
let mut s = s();
|
||||
let vscode_html = r#"<div style="color: #d4d4d4;background-color: #1e1e1e;font-family: Consolas, 'Courier New', monospace;font-weight: normal;font-size: 14px;line-height: 19px;white-space: pre;"><div><span style="color: #569cd6;">const</span><span style="color: #d4d4d4;"> x = </span><span style="color: #b5cea8;">1</span><span style="color: #d4d4d4;">;</span></div></div>"#;
|
||||
run(&mut s, "edit.paste", json!({"text": "const x = 1;", "html": vscode_html}));
|
||||
assert_eq!(text(&s), "const x = 1;");
|
||||
let p = s.doc.para_at(&s.sel.focus).unwrap();
|
||||
for r in &p.runs {
|
||||
assert_eq!(r.props.shading, None, "character should have no shading from container div");
|
||||
}
|
||||
assert_eq!(p.props.shading, Some(wordcraft_doc::Rgb(0x1e, 0x1e, 0x1e)), "container background is kept as paragraph shading");
|
||||
assert!(p.runs.iter().any(|r| r.props.color == Some(wordcraft_doc::TextColor::Rgb(wordcraft_doc::Rgb(0x56, 0x9c, 0xd6)))));
|
||||
}
|
||||
|
||||
/// A multi-block paste keeps the first pasted paragraph's shading when the destination has its own properties (#6157).
|
||||
#[test]
|
||||
fn multi_block_paste_keeps_first_paragraph_shading() {
|
||||
let mut s = s();
|
||||
run(&mut s, "para.align", json!({"value": "center"}));
|
||||
let html = r#"<div style="background-color:#1e1e1e"><p>one</p><p>two</p></div>"#;
|
||||
run(&mut s, "edit.paste", json!({"text": "one\ntwo", "html": html}));
|
||||
assert_eq!(text(&s), "one\ntwo");
|
||||
let p = s.doc.body.first().and_then(|b| b.as_para()).unwrap();
|
||||
assert_eq!(p.props.shading, Some(wordcraft_doc::Rgb(0x1e, 0x1e, 0x1e)), "first pasted paragraph keeps its shading");
|
||||
}
|
||||
|
||||
/// A destination paragraph whose style shades keeps that shading when a shaded paragraph is pasted (#6157).
|
||||
#[test]
|
||||
fn paste_keeps_destination_style_shading() {
|
||||
let mut s = s();
|
||||
Arc::make_mut(&mut s.doc.styles).upsert(wordcraft_doc::Style {
|
||||
id: "Shaded".into(),
|
||||
name: "Shaded".into(),
|
||||
kind: wordcraft_doc::StyleKind::Paragraph,
|
||||
based_on: Some("Normal".into()),
|
||||
para: wordcraft_doc::props::ParaProps { shading: Some(wordcraft_doc::Rgb(0x22, 0x22, 0x22)), ..Default::default() },
|
||||
..Default::default()
|
||||
});
|
||||
run(&mut s, "para.style", json!({"style": "Shaded"}));
|
||||
let html = r#"<div style="background-color:#1e1e1e"><span>text</span></div>"#;
|
||||
run(&mut s, "edit.paste", json!({"text": "text", "html": html}));
|
||||
let p = s.doc.body.first().and_then(|b| b.as_para()).unwrap();
|
||||
assert_eq!(p.props.shading, None, "source shading must not override the destination style");
|
||||
assert_eq!(
|
||||
s.doc.styles.resolve_para(&p.props).shading,
|
||||
Some(wordcraft_doc::Rgb(0x22, 0x22, 0x22)),
|
||||
"destination style shading remains effective"
|
||||
);
|
||||
}
|
||||
|
||||
/// Multi-line VS Code paste keeps removable paragraph shading rather than stuck character shading,
|
||||
/// so Shading › No Color, Clear All Formatting, and Merge Formatting all clear the dark background (#6157).
|
||||
#[test]
|
||||
fn pasted_code_from_vscode_shading_is_removable() {
|
||||
let vscode_html = concat!(
|
||||
r#"<div style="color: #d4d4d4;background-color: #1e1e1e;font-family: Consolas, 'Courier New', monospace;font-size: 14px;white-space: pre;">"#,
|
||||
r#"<div><span style="color: #569cd6;">const</span><span style="color: #d4d4d4;"> a = 1;</span></div>"#,
|
||||
r#"<div><span style="color: #569cd6;">const</span><span style="color: #d4d4d4;"> b = 2;</span></div>"#,
|
||||
r#"</div>"#,
|
||||
);
|
||||
let plain = "const a = 1;\nconst b = 2;";
|
||||
|
||||
// Home › Paragraph › Shading › No Color removes the dark background across all pasted lines.
|
||||
let mut s = self::s();
|
||||
run(&mut s, "edit.paste", json!({"text": plain, "html": vscode_html}));
|
||||
assert_eq!(s.doc.body.len(), 2);
|
||||
for b in &s.doc.body {
|
||||
let p = b.as_para().unwrap();
|
||||
assert_eq!(p.props.shading, Some(wordcraft_doc::Rgb(0x1e, 0x1e, 0x1e)));
|
||||
assert!(p.runs.iter().all(|r| r.props.shading.is_none()));
|
||||
}
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "para.shading", json!({"color": null}));
|
||||
for b in &s.doc.body {
|
||||
let p = b.as_para().unwrap();
|
||||
assert_eq!(p.props.shading, None, "Shading › No Color clears the container background");
|
||||
assert!(p.runs.iter().all(|r| r.props.shading.is_none()));
|
||||
}
|
||||
|
||||
// Clear All Formatting clears both the dark paragraph shading and light syntax colors.
|
||||
let mut s = self::s();
|
||||
run(&mut s, "edit.paste", json!({"text": plain, "html": vscode_html}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "format.clear", json!({}));
|
||||
for b in &s.doc.body {
|
||||
let p = b.as_para().unwrap();
|
||||
assert_eq!(p.props.shading, None);
|
||||
assert!(p.runs.iter().all(|r| r.props.shading.is_none() && r.props.color.is_none()));
|
||||
}
|
||||
|
||||
// Paste › Merge Formatting drops the dark container background and light text colors up front.
|
||||
let mut s = self::s();
|
||||
run(&mut s, "edit.pasteMerge", json!({"text": plain, "html": vscode_html}));
|
||||
for b in &s.doc.body {
|
||||
let p = b.as_para().unwrap();
|
||||
assert_eq!(p.props.shading, None);
|
||||
assert!(p.runs.iter().all(|r| r.props.shading.is_none() && r.props.color.is_none()));
|
||||
}
|
||||
}
|
||||
|
||||
/// Copying a paragraph shaded via its style writes `background-color` to the clipboard HTML (#6157).
|
||||
#[test]
|
||||
fn copy_exports_style_inherited_paragraph_shading_to_clipboard_html() {
|
||||
let mut s = s();
|
||||
Arc::make_mut(&mut s.doc.styles).upsert(wordcraft_doc::Style {
|
||||
id: "CodeBlock".into(),
|
||||
name: "Code Block".into(),
|
||||
kind: wordcraft_doc::StyleKind::Paragraph,
|
||||
based_on: Some("Normal".into()),
|
||||
para: wordcraft_doc::props::ParaProps { shading: Some(wordcraft_doc::Rgb(0x1e, 0x1e, 0x1e)), ..Default::default() },
|
||||
..Default::default()
|
||||
});
|
||||
run(&mut s, "document.setText", json!({"text": "const x = 1;"}));
|
||||
run(&mut s, "para.style", json!({"style": "CodeBlock"}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
let r = run(&mut s, "edit.copy", json!({}));
|
||||
let html = r["html"].as_str().unwrap_or_default();
|
||||
assert!(html.contains("background-color:#1E1E1E"), "clipboard HTML carries style paragraph shading: {html}");
|
||||
|
||||
let mut dst = self::s();
|
||||
run(&mut dst, "edit.paste", json!({"text": "const x = 1;", "html": html, "privateClipboard": false}));
|
||||
let p = dst.doc.body.first().and_then(|b| b.as_para()).unwrap();
|
||||
assert_eq!(p.props.shading, Some(wordcraft_doc::Rgb(0x1e, 0x1e, 0x1e)));
|
||||
}
|
||||
|
||||
/// Pasting a single inline-highlighted word into the middle of an unshaded paragraph keeps run
|
||||
/// shading on that word alone and leaves the destination paragraph unshaded (#6157).
|
||||
#[test]
|
||||
fn pasting_inline_highlighted_word_mid_paragraph_keeps_run_shading_only() {
|
||||
for (html, want) in [
|
||||
(r#"<span style="background-color:yellow">word</span>"#, wordcraft_doc::Rgb(0xff, 0xff, 0x00)),
|
||||
(r"<mark>word</mark>", wordcraft_doc::Rgb(0xff, 0xff, 0x00)),
|
||||
(r#"<code style="background-color:#eeeeee">word</code>"#, wordcraft_doc::Rgb(0xee, 0xee, 0xee)),
|
||||
] {
|
||||
let mut s = self::s();
|
||||
run(&mut s, "document.setText", json!({"text": "before after"}));
|
||||
run(&mut s, "select.range", json!({"anchor": {"block": 0, "off": 7}, "focus": {"block": 0, "off": 7}}));
|
||||
run(&mut s, "edit.paste", json!({"text": "word", "html": html}));
|
||||
assert_eq!(text(&s), "before word after", "{html}");
|
||||
let p = s.doc.body.first().and_then(|b| b.as_para()).unwrap();
|
||||
assert_eq!(p.props.shading, None, "destination paragraph stays unshaded: {html}");
|
||||
assert_eq!(p.props_of_char(0).shading, None, "{html}");
|
||||
assert_eq!(p.props_of_char(7).shading, Some(want), "pasted word keeps run shading: {html}");
|
||||
assert_eq!(p.props_of_char(12).shading, None, "{html}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Pasting a container-wrapped one-line snippet (no paragraph break) into the middle of a
|
||||
/// paragraph leaves the destination paragraph unshaded (#6157).
|
||||
#[test]
|
||||
fn container_wrapped_one_line_paste_mid_paragraph_leaves_paragraph_unshaded() {
|
||||
let mut s = self::s();
|
||||
run(&mut s, "document.setText", json!({"text": "Call now."}));
|
||||
run(&mut s, "select.range", json!({"anchor": {"block": 0, "off": 5}, "focus": {"block": 0, "off": 5}}));
|
||||
let vscode_html = r#"<div style="color: #d4d4d4;background-color: #1e1e1e;font-family: Consolas, 'Courier New', monospace;font-size: 14px;white-space: pre;"><span style="color: #569cd6;">foo</span></div>"#;
|
||||
run(&mut s, "edit.paste", json!({"text": "foo", "html": vscode_html}));
|
||||
assert_eq!(text(&s), "Call foo now.");
|
||||
let p = s.doc.body.first().and_then(|b| b.as_para()).unwrap();
|
||||
assert_eq!(p.props.shading, None, "destination paragraph stays unshaded");
|
||||
assert_eq!(p.props_of_char(0).shading, None);
|
||||
assert_eq!(p.props_of_char(5).shading, None);
|
||||
}
|
||||
|
||||
/// Under Track Changes, rejecting a paste restores the destination paragraph formatting (#6157).
|
||||
#[test]
|
||||
fn tracked_paste_reject_restores_destination_paragraph_shading() {
|
||||
let mut s = self::s();
|
||||
run(&mut s, "document.setText", json!({"text": "Call now."}));
|
||||
run(&mut s, "review.trackChanges", json!({"enabled": true}));
|
||||
run(&mut s, "select.range", json!({"anchor": {"block": 0, "off": 5}, "focus": {"block": 0, "off": 5}}));
|
||||
let vscode_html = r#"<div style="color: #d4d4d4;background-color: #1e1e1e;font-family: Consolas, 'Courier New', monospace;font-size: 14px;white-space: pre;"><span style="color: #569cd6;">foo</span></div>"#;
|
||||
run(&mut s, "edit.paste", json!({"text": "foo", "html": vscode_html}));
|
||||
assert_eq!(text(&s), "Call foo now.");
|
||||
let p = s.doc.body.first().and_then(|b| b.as_para()).unwrap();
|
||||
assert_eq!(p.props.shading, None);
|
||||
run(&mut s, "review.rejectAll", json!({}));
|
||||
assert_eq!(text(&s), "Call now.");
|
||||
let p_after = s.doc.body.first().and_then(|b| b.as_para()).unwrap();
|
||||
assert_eq!(p_after.props.shading, None, "rejecting paste leaves paragraph unshaded");
|
||||
|
||||
// Also verify that pasting into an empty paragraph under Track Changes restores the empty
|
||||
// paragraph's unshaded state on Reject All.
|
||||
let mut s2 = self::s();
|
||||
run(&mut s2, "review.trackChanges", json!({"enabled": true}));
|
||||
run(&mut s2, "edit.paste", json!({"text": "foo", "html": vscode_html}));
|
||||
assert_eq!(text(&s2), "foo");
|
||||
let p2 = s2.doc.body.first().and_then(|b| b.as_para()).unwrap();
|
||||
assert_eq!(p2.props.shading, Some(wordcraft_doc::Rgb(0x1e, 0x1e, 0x1e)));
|
||||
run(&mut s2, "review.rejectAll", json!({}));
|
||||
assert_eq!(text(&s2), "");
|
||||
let p2_after = s2.doc.body.first().and_then(|b| b.as_para()).unwrap();
|
||||
assert_eq!(p2_after.props.shading, None, "rejecting paste into empty paragraph clears paragraph shading");
|
||||
}
|
||||
|
||||
/// A CF_HTML ("HTML Format") clipboard payload around `html`, with the byte offsets Windows writes.
|
||||
fn cf_html(html: &str) -> String {
|
||||
let n = "Version:1.0\r\nStartHTML:0000000000\r\nEndHTML:0000000000\r\nStartFragment:0000000000\r\nEndFragment:0000000000\r\n".len();
|
||||
@@ -2417,6 +2616,122 @@ fn copy_whole_table_pastes_a_table() {
|
||||
assert_eq!(body_table_cells(&s), vec![want.clone(), want]);
|
||||
}
|
||||
|
||||
/// #5906: Copying select-all in a document starting with a table must preserve the table.
|
||||
#[test]
|
||||
fn select_all_in_document_starting_with_table_preserves_table() {
|
||||
let mut s = s();
|
||||
run(&mut s, "insert.table", json!({"rows": 2, "cols": 2}));
|
||||
run(&mut s, "text.insert", json!({"text": "A1"}));
|
||||
run(&mut s, "select.all", json!({"whole": true}));
|
||||
run(&mut s, "edit.copy", json!({}));
|
||||
let clip = s.clipboard.as_ref().unwrap();
|
||||
assert!(
|
||||
clip.blocks.iter().any(|b| matches!(b, wordcraft_doc::Block::Table(_))),
|
||||
"copying select-all in a document starting with a table must preserve table structure, got {:?}",
|
||||
clip.blocks
|
||||
);
|
||||
let table = clip
|
||||
.blocks
|
||||
.iter()
|
||||
.find_map(|b| match b {
|
||||
wordcraft_doc::Block::Table(t) => Some(t),
|
||||
_ => None,
|
||||
})
|
||||
.expect("table block in clipboard");
|
||||
assert_eq!(table.rows.len(), 2, "copied table row count");
|
||||
assert_eq!(table.cols(), 2, "copied table col count");
|
||||
let c00 = table.rows[0].cells[0].blocks.first().and_then(|b| match &**b {
|
||||
wordcraft_doc::Block::Para(p) => Some(p.text.as_str()),
|
||||
_ => None,
|
||||
});
|
||||
assert_eq!(c00, Some("A1"), "cell (0, 0) text");
|
||||
}
|
||||
|
||||
/// #5906: Cut and Spike across table cells with non-corner endpoints must preserve every removed character.
|
||||
#[test]
|
||||
fn cut_and_spike_across_table_cells_preserves_every_removed_character() {
|
||||
// 1. Test Spike then insertSpike
|
||||
{
|
||||
let mut s = s();
|
||||
run(&mut s, "insert.table", json!({"rows": 3, "cols": 3}));
|
||||
for (i, text) in ["R0C0", "R0C1", "R0C2", "R1C0", "R1C1", "R1C2", "R2C0", "R2C1", "R2C2"].iter().enumerate() {
|
||||
if i > 0 {
|
||||
run(&mut s, "text.tab", json!({}));
|
||||
}
|
||||
run(&mut s, "text.insert", json!({"text": text}));
|
||||
}
|
||||
|
||||
// Set linear text range across non-corner cells: (0, 1) off 1 ("0C1") through (1, 1) off 3 ("R1C").
|
||||
// Traversed in linear document order: (0, 1) "0C1", (0, 2) "R0C2", (1, 0) "R1C0", (1, 1) "R1C".
|
||||
s.sel = crate::Selection {
|
||||
anchor: wordcraft_doc::Pos { story: wordcraft_doc::StoryRef::Body, path: wordcraft_doc::Path(vec![0, 0, 1, 0]), off: 1 },
|
||||
focus: wordcraft_doc::Pos { story: wordcraft_doc::StoryRef::Body, path: wordcraft_doc::Path(vec![0, 1, 1, 0]), off: 3 },
|
||||
};
|
||||
s.column = None;
|
||||
|
||||
run(&mut s, "edit.spike", json!({}));
|
||||
|
||||
// Verify the table content after spike:
|
||||
// (0, 1) has "R" remaining, (0, 2) emptied, (1, 0) emptied, (1, 1) has "1" remaining.
|
||||
let cells_after = body_table_cells(&s);
|
||||
assert_eq!(
|
||||
cells_after,
|
||||
vec![vec!["R0C0".to_string(), "R".into(), "".into(), "".into(), "1".into(), "R1C2".into(), "R2C0".into(), "R2C1".into(), "R2C2".into(),]]
|
||||
);
|
||||
|
||||
// Paste the spike at the end of the document: all 4 removed pieces must be present.
|
||||
run(&mut s, "caret.docEnd", json!({}));
|
||||
run(&mut s, "edit.insertSpike", json!({}));
|
||||
let texts = body_texts(&s);
|
||||
assert!(
|
||||
texts.iter().any(|t| t == "0C1")
|
||||
&& texts.iter().any(|t| t == "R0C2")
|
||||
&& texts.iter().any(|t| t == "R1C0")
|
||||
&& texts.iter().any(|t| t == "R1C"),
|
||||
"every removed character must be preserved and inserted from spike, got: {:?}",
|
||||
texts
|
||||
);
|
||||
}
|
||||
|
||||
// 2. Test Cut then paste
|
||||
{
|
||||
let mut s = s();
|
||||
run(&mut s, "insert.table", json!({"rows": 3, "cols": 3}));
|
||||
for (i, text) in ["R0C0", "R0C1", "R0C2", "R1C0", "R1C1", "R1C2", "R2C0", "R2C1", "R2C2"].iter().enumerate() {
|
||||
if i > 0 {
|
||||
run(&mut s, "text.tab", json!({}));
|
||||
}
|
||||
run(&mut s, "text.insert", json!({"text": text}));
|
||||
}
|
||||
|
||||
s.sel = crate::Selection {
|
||||
anchor: wordcraft_doc::Pos { story: wordcraft_doc::StoryRef::Body, path: wordcraft_doc::Path(vec![0, 0, 1, 0]), off: 1 },
|
||||
focus: wordcraft_doc::Pos { story: wordcraft_doc::StoryRef::Body, path: wordcraft_doc::Path(vec![0, 1, 1, 0]), off: 3 },
|
||||
};
|
||||
s.column = None;
|
||||
|
||||
run(&mut s, "edit.cut", json!({}));
|
||||
|
||||
let cells_after_cut = body_table_cells(&s);
|
||||
assert_eq!(
|
||||
cells_after_cut,
|
||||
vec![vec!["R0C0".to_string(), "R".into(), "".into(), "".into(), "1".into(), "R1C2".into(), "R2C0".into(), "R2C1".into(), "R2C2".into(),]]
|
||||
);
|
||||
|
||||
run(&mut s, "caret.docEnd", json!({}));
|
||||
run(&mut s, "edit.paste", json!({}));
|
||||
let texts_cut = body_texts(&s);
|
||||
assert!(
|
||||
texts_cut.iter().any(|t| t == "0C1")
|
||||
&& texts_cut.iter().any(|t| t == "R0C2")
|
||||
&& texts_cut.iter().any(|t| t == "R1C0")
|
||||
&& texts_cut.iter().any(|t| t == "R1C"),
|
||||
"every removed character must be preserved and inserted from cut, got: {:?}",
|
||||
texts_cut
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// #1744: Select Table → Cut removes the whole table, and one Undo brings it back.
|
||||
#[test]
|
||||
fn cut_whole_table_removes_it_and_undoes() {
|
||||
@@ -2635,6 +2950,20 @@ fn tracked_cut_of_a_table_or_row_marks_text_deleted() {
|
||||
assert_eq!(body_table_final(&s), full);
|
||||
}
|
||||
|
||||
/// Cut and Copy are off with nothing selected (the ribbon buttons read this) and on with text selected.
|
||||
#[test]
|
||||
fn cut_and_copy_are_disabled_without_a_selection() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
run(&mut s, "text.insert", json!({"text": "Hello"}));
|
||||
for id in ["edit.cut", "edit.copy"] {
|
||||
assert!(s.why_disabled(id).is_some(), "{id} with a caret only");
|
||||
}
|
||||
run(&mut s, "select.text", json!({"text": "Hello"}));
|
||||
for id in ["edit.cut", "edit.copy"] {
|
||||
assert!(s.why_disabled(id).is_none(), "{id} with a selection");
|
||||
}
|
||||
}
|
||||
|
||||
/// #1744 review: Cut of a table, or of cells, holding a content control locked against deletion
|
||||
/// is refused and changes nothing in the document; the copy is made first, so the clipboard
|
||||
/// holds the table, as for any refused Cut.
|
||||
@@ -3000,11 +3329,19 @@ fn tables_nest_only_as_deep_as_a_json_save_reads() {
|
||||
let e = s.run("insert.table", &json!({"rows": 1, "cols": 1})).unwrap_err();
|
||||
assert!(e.to_string().contains(&format!("{MAX_TABLE_DEPTH} deep")), "{e}");
|
||||
assert_eq!(s.doc, before);
|
||||
run(&mut s, "edit.paste", json!({"text": "b", "html": "<table><tr><td>b</td></tr></table>"}));
|
||||
// Paste as Nested Table is the path the depth guard sits on: the table's text comes as paragraphs.
|
||||
run(&mut s, "edit.pasteNestedTable", json!({"text": "b", "html": "<table><tr><td>b</td></tr></table>"}));
|
||||
let cell = s.sel.focus.path.clone();
|
||||
let blocks: Vec<_> = (0..).map_while(|i| s.doc.block(StoryRef::Body, &cell.with_last(i))).collect();
|
||||
assert!(blocks.iter().all(|b| b.as_table().is_none()), "no table below the limit");
|
||||
assert!(blocks.iter().any(|b| b.as_para().is_some_and(|p| p.text.contains('b'))), "the pasted text is there");
|
||||
// Paste lays a one-cell table over the cell (#6739): no new level either.
|
||||
run(&mut s, "edit.paste", json!({"text": "c", "html": "<table><tr><td>c</td></tr></table>"}));
|
||||
let cell = s.sel.focus.path.clone();
|
||||
let blocks: Vec<_> = (0..).map_while(|i| s.doc.block(StoryRef::Body, &cell.with_last(i))).collect();
|
||||
assert!(blocks.iter().all(|b| b.as_table().is_none()), "no table below the limit");
|
||||
assert!(blocks.iter().any(|b| b.as_para().is_some_and(|p| p.text.contains('c'))), "the pasted text is there");
|
||||
assert_eq!(s.sel.focus.path.depth(), MAX_TABLE_DEPTH);
|
||||
}
|
||||
|
||||
/// #3618: a text box story sits two JSON levels below the body, and its deepest cell still reads
|
||||
@@ -5839,6 +6176,318 @@ fn copy_paste_text_box_makes_an_independent_copy() {
|
||||
assert_eq!(s.doc.parts.len(), parts);
|
||||
}
|
||||
|
||||
/// Copying and pasting a selected custom text box duplicates its dimensions, styling, and text
|
||||
/// while giving the copy an independent story ID.
|
||||
#[test]
|
||||
fn copy_and_paste_selected_custom_text_box_duplicates_dimensions_styling_and_text() {
|
||||
let mut s = s();
|
||||
let id = run(
|
||||
&mut s,
|
||||
"insert.textBox",
|
||||
json!({
|
||||
"text": "Custom content",
|
||||
"width": 180.0,
|
||||
"height": 90.0
|
||||
}),
|
||||
)["story"]
|
||||
.as_u64()
|
||||
.unwrap() as u32;
|
||||
|
||||
// Apply custom styling (fill and outline).
|
||||
run(&mut s, "select.range", json!({"anchor": Pos::body(0, 0), "focus": Pos::body(0, 3)}));
|
||||
run(&mut s, "shape.fill", json!({"color": "FFEEDD"}));
|
||||
run(&mut s, "shape.outline", json!({"color": "112233", "width": 2.5}));
|
||||
|
||||
let para = s.doc.para(StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap();
|
||||
let orig_obj = para.objects[0].clone();
|
||||
let wordcraft_doc::InlineObject::Shape { w, h, stroke_width, fill, stroke, .. } = &orig_obj else { panic!("not a shape") };
|
||||
assert_eq!((*w, *h), (180.0, 90.0));
|
||||
assert_eq!(*stroke_width, 2.5);
|
||||
assert!(fill.is_some());
|
||||
assert!(stroke.is_some());
|
||||
|
||||
// Copy selected custom text box (non-collapsed, object_selection, #5785, #5859).
|
||||
run(&mut s, "select.range", json!({"anchor": Pos::body(0, 0), "focus": Pos::body(0, 3)}));
|
||||
assert!(crate::cmd::objects::object_selection(&s).is_some());
|
||||
let copy_res = run(&mut s, "edit.copy", json!({}));
|
||||
assert_eq!(copy_res["text"], "Custom content");
|
||||
assert_eq!(s.clipboard_text, "Custom content");
|
||||
assert!(s.clipboard.is_some());
|
||||
|
||||
// Move caret after original and paste.
|
||||
run(&mut s, "caret.set", json!({"pos": Pos::body(0, 3)}));
|
||||
run(&mut s, "edit.paste", json!({}));
|
||||
|
||||
let para = s.doc.para(StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap();
|
||||
assert_eq!(para.objects.len(), 2);
|
||||
let pasted = ¶.objects[1];
|
||||
|
||||
let wordcraft_doc::InlineObject::Shape { w: pw, h: ph, stroke_width: psw, fill: pfill, stroke: pstroke, story: pstory, .. } = pasted else {
|
||||
panic!("pasted not a shape");
|
||||
};
|
||||
|
||||
assert_eq!((*pw, *ph), (180.0, 90.0), "dimensions duplicated");
|
||||
assert_eq!(*psw, 2.5, "stroke width duplicated");
|
||||
assert_eq!(pfill, fill, "fill duplicated");
|
||||
assert_eq!(pstroke, stroke, "stroke duplicated");
|
||||
assert!(pstory.is_some());
|
||||
assert_ne!(pstory.unwrap(), id, "independent story ID");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Part(pstory.unwrap())), "Custom content", "inner text duplicated");
|
||||
|
||||
// Cut the pasted text box by selecting it (non-collapsed, object_selection).
|
||||
run(&mut s, "select.range", json!({"anchor": Pos::body(0, 3), "focus": Pos::body(0, 6)}));
|
||||
assert!(crate::cmd::objects::object_selection(&s).is_some());
|
||||
let cut_res = run(&mut s, "edit.cut", json!({}));
|
||||
assert_eq!(cut_res["text"], "Custom content");
|
||||
|
||||
let para = s.doc.para(StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap();
|
||||
assert_eq!(para.objects.len(), 1);
|
||||
assert_eq!(para.objects[0].text_box(), Some(id));
|
||||
|
||||
// Paste it back.
|
||||
run(&mut s, "edit.paste", json!({}));
|
||||
let para = s.doc.para(StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap();
|
||||
assert_eq!(para.objects.len(), 2);
|
||||
|
||||
// Copy and paste a shape without text.
|
||||
run(&mut s, "caret.set", json!({"pos": Pos::body(0, 6)}));
|
||||
run(&mut s, "insert.shape", json!({"kind": "star", "width": 64.0, "height": 48.0}));
|
||||
run(&mut s, "shape.fill", json!({"color": "00FF00"}));
|
||||
|
||||
run(&mut s, "select.range", json!({"anchor": Pos::body(0, 6), "focus": Pos::body(0, 9)}));
|
||||
run(&mut s, "edit.copy", json!({}));
|
||||
assert!(s.clipboard.is_some());
|
||||
|
||||
run(&mut s, "caret.set", json!({"pos": Pos::body(0, 9)}));
|
||||
run(&mut s, "edit.paste", json!({}));
|
||||
|
||||
let para = s.doc.para(StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap();
|
||||
assert_eq!(para.objects.len(), 4);
|
||||
let star_copy = ¶.objects[3];
|
||||
let wordcraft_doc::InlineObject::Shape { kind, w, h, fill, .. } = star_copy else { panic!("not a shape") };
|
||||
assert_eq!(*kind, wordcraft_doc::para::ShapeKind::Star);
|
||||
assert_eq!((*w, *h), (64.0, 48.0));
|
||||
assert!(fill.is_some());
|
||||
}
|
||||
|
||||
/// Cut and Copy with a bare caret beside an object (collapsed selection) change nothing (#5859).
|
||||
#[test]
|
||||
fn cut_and_copy_with_bare_caret_beside_object_change_nothing() {
|
||||
let mut s = s();
|
||||
let id = run(&mut s, "insert.textBox", json!({"text": "Box content"}))["story"].as_u64().unwrap() as u32;
|
||||
|
||||
// 1. Bare caret immediately before the object (Pos::body(0, 0)).
|
||||
run(&mut s, "caret.set", json!({"pos": Pos::body(0, 0)}));
|
||||
assert!(s.sel.is_collapsed());
|
||||
assert!(crate::cmd::objects::object_selection(&s).is_none());
|
||||
|
||||
let copy_res = s.run("edit.copy", &json!({}));
|
||||
assert!(matches!(copy_res, Err(crate::CmdError::Disabled(_))), "copy on bare caret is disabled");
|
||||
assert!(s.clipboard.is_none(), "clipboard remains unset");
|
||||
|
||||
let cut_res = s.run("edit.cut", &json!({}));
|
||||
assert!(matches!(cut_res, Err(crate::CmdError::Disabled(_))), "cut on bare caret is disabled");
|
||||
|
||||
let para = s.doc.para(StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap();
|
||||
assert_eq!(para.objects.len(), 1, "object was not deleted");
|
||||
assert_eq!(para.objects[0].text_box(), Some(id));
|
||||
|
||||
// 2. Bare caret immediately after the object (Pos::body(0, 3)).
|
||||
run(&mut s, "caret.set", json!({"pos": Pos::body(0, 3)}));
|
||||
assert!(s.sel.is_collapsed());
|
||||
assert!(crate::cmd::objects::object_selection(&s).is_none());
|
||||
|
||||
let copy_res = s.run("edit.copy", &json!({}));
|
||||
assert!(matches!(copy_res, Err(crate::CmdError::Disabled(_))), "copy on bare caret is disabled");
|
||||
assert!(s.clipboard.is_none(), "clipboard remains unset");
|
||||
|
||||
let cut_res = s.run("edit.cut", &json!({}));
|
||||
assert!(matches!(cut_res, Err(crate::CmdError::Disabled(_))), "cut on bare caret is disabled");
|
||||
|
||||
let para = s.doc.para(StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap();
|
||||
assert_eq!(para.objects.len(), 1, "object was not deleted");
|
||||
assert_eq!(para.objects[0].text_box(), Some(id));
|
||||
}
|
||||
|
||||
/// Fallback plain text / clipboard text when paragraphs contain text boxes (#5785).
|
||||
#[test]
|
||||
fn fallback_plain_text_extracts_text_box_story_when_body_contains_paragraph_marks() {
|
||||
let mut f = wordcraft_doc::edit::Fragment::default();
|
||||
let mut p = wordcraft_doc::Paragraph::new();
|
||||
p.text = format!("{}\n", wordcraft_doc::para::OBJ);
|
||||
let mut part_p = wordcraft_doc::Paragraph::new();
|
||||
part_p.text = "Box text".to_string();
|
||||
let part = wordcraft_doc::Part {
|
||||
kind: wordcraft_doc::PartKind::TextBox,
|
||||
blocks: vec![std::sync::Arc::new(wordcraft_doc::Block::Para(part_p))],
|
||||
body: Default::default(),
|
||||
};
|
||||
f.blocks = vec![wordcraft_doc::Block::Para(p)];
|
||||
f.parts.insert(100, part);
|
||||
assert_eq!(f.plain_text(), "Box text");
|
||||
assert_eq!(f.clipboard_text(), "Box text");
|
||||
}
|
||||
|
||||
/// Pasting formatted content with matching RTF but mismatched HTML from an external app prefers HTML (#5785).
|
||||
#[test]
|
||||
fn paste_content_prefers_external_html_when_rtf_matches_session_clipboard() {
|
||||
let mut s = s();
|
||||
run(&mut s, "insert.textBox", json!({"text": "Internal text"}));
|
||||
run(&mut s, "select.range", json!({"anchor": Pos::body(0, 0), "focus": Pos::body(0, 3)}));
|
||||
run(&mut s, "edit.copy", json!({}));
|
||||
let my_rtf = s.clipboard_rtf.clone();
|
||||
let external_html = "<p>External rich text</p>";
|
||||
let pasted_res = crate::cmd::paste::paste_content(&mut s, &json!({"html": external_html, "rtf": my_rtf}));
|
||||
assert!(matches!(pasted_res, Ok(crate::cmd::paste::Pasted::Fragment(_))));
|
||||
if let Ok(crate::cmd::paste::Pasted::Fragment(frag)) = pasted_res {
|
||||
assert_eq!(frag.plain_text(), "External rich text");
|
||||
}
|
||||
}
|
||||
|
||||
/// Pasting with no text payload or empty text but matching HTML and RTF uses WordCraft's session clipboard
|
||||
/// fragment, preserving custom text box parts (#5785, #5859).
|
||||
#[test]
|
||||
fn paste_content_uses_session_clipboard_when_html_and_rtf_match_without_text() {
|
||||
let mut s = s();
|
||||
run(&mut s, "insert.textBox", json!({"text": "Internal text box"}));
|
||||
run(&mut s, "select.range", json!({"anchor": Pos::body(0, 0), "focus": Pos::body(0, 3)}));
|
||||
run(&mut s, "edit.copy", json!({}));
|
||||
let my_html = s.clipboard_html.clone();
|
||||
let my_rtf = s.clipboard_rtf.clone();
|
||||
assert!(!my_html.is_empty());
|
||||
assert!(!my_rtf.is_empty());
|
||||
assert!(s.clipboard.as_ref().is_some_and(|f| !f.parts.is_empty()));
|
||||
|
||||
let pasted_res = crate::cmd::paste::paste_content(&mut s, &json!({"html": my_html, "rtf": my_rtf}));
|
||||
assert!(matches!(pasted_res, Ok(crate::cmd::paste::Pasted::Fragment(_))));
|
||||
if let Ok(crate::cmd::paste::Pasted::Fragment(frag)) = pasted_res {
|
||||
assert_eq!(frag.parts.len(), 1, "session text box parts preserved");
|
||||
assert_eq!(frag.plain_text(), "Internal text box");
|
||||
}
|
||||
|
||||
let pasted_with_empty_text = crate::cmd::paste::paste_content(&mut s, &json!({"text": "", "html": my_html, "rtf": my_rtf}));
|
||||
assert!(matches!(pasted_with_empty_text, Ok(crate::cmd::paste::Pasted::Fragment(_))));
|
||||
if let Ok(crate::cmd::paste::Pasted::Fragment(frag)) = pasted_with_empty_text {
|
||||
assert_eq!(frag.parts.len(), 1, "session text box parts preserved with empty text");
|
||||
assert_eq!(frag.plain_text(), "Internal text box");
|
||||
}
|
||||
|
||||
let avail = crate::cmd::paste::available(&s, &json!({"text": "", "html": my_html, "rtf": my_rtf}));
|
||||
assert!(avail.contains(&"formatted"), "formatted format is available for pasteSpecial when text is empty but rich formats match");
|
||||
let paste_special_res = s.run("edit.pasteSpecial", &json!({"as": "formatted", "text": "", "html": my_html, "rtf": my_rtf}));
|
||||
assert!(paste_special_res.is_ok(), "pasteSpecial as formatted succeeds with empty text and matching rich formats");
|
||||
}
|
||||
|
||||
/// On macOS, arboard wraps HTML in `<html><head>…</head><body>…</body></html>`, so the
|
||||
/// round-tripped HTML never equals what WordCraft stored. The session clipboard must still be
|
||||
/// recognised when RTF matches or HTML matches after unwrapping (#5859).
|
||||
#[test]
|
||||
fn paste_content_uses_session_clipboard_when_macos_wraps_html() {
|
||||
let mut s = s();
|
||||
run(&mut s, "insert.textBox", json!({"text": "Internal text box"}));
|
||||
run(&mut s, "select.range", json!({"anchor": Pos::body(0, 0), "focus": Pos::body(0, 3)}));
|
||||
run(&mut s, "edit.copy", json!({}));
|
||||
let my_rtf = s.clipboard_rtf.clone();
|
||||
assert!(!my_rtf.is_empty());
|
||||
assert!(s.clipboard.as_ref().is_some_and(|f| !f.parts.is_empty()));
|
||||
|
||||
// Simulate macOS wrapping: HTML is wrapped by arboard, RTF is raw.
|
||||
let wrapped_html =
|
||||
format!("<html><head><meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\"></head><body>{}</body></html>", s.clipboard_html);
|
||||
assert_ne!(wrapped_html, s.clipboard_html, "wrapped HTML differs from stored");
|
||||
|
||||
// With empty text (front-end path for shapes/text-boxes without text), session clipboard matched.
|
||||
let pasted = crate::cmd::paste::paste_content(&mut s, &json!({"text": "", "html": wrapped_html, "rtf": my_rtf}));
|
||||
assert!(matches!(pasted, Ok(crate::cmd::paste::Pasted::Fragment(_))));
|
||||
if let Ok(crate::cmd::paste::Pasted::Fragment(frag)) = pasted {
|
||||
assert_eq!(frag.parts.len(), 1, "session text box parts preserved despite wrapped HTML");
|
||||
assert_eq!(frag.plain_text(), "Internal text box");
|
||||
}
|
||||
|
||||
// With non-empty text that matches, session clipboard matched via main's text rule.
|
||||
let my_text = s.clipboard_text.clone();
|
||||
let pasted_text = crate::cmd::paste::paste_content(&mut s, &json!({"text": my_text, "html": wrapped_html, "rtf": my_rtf}));
|
||||
assert!(matches!(pasted_text, Ok(crate::cmd::paste::Pasted::Fragment(_))));
|
||||
if let Ok(crate::cmd::paste::Pasted::Fragment(frag)) = pasted_text {
|
||||
assert_eq!(frag.parts.len(), 1, "session text box parts preserved with text match");
|
||||
}
|
||||
|
||||
// Paste Special as formatted is available despite wrapped HTML.
|
||||
let avail = crate::cmd::paste::available(&s, &json!({"text": my_text, "html": wrapped_html, "rtf": my_rtf}));
|
||||
assert!(avail.contains(&"formatted"), "formatted format is available for pasteSpecial when HTML is wrapped on macOS");
|
||||
}
|
||||
|
||||
/// Pasting external RTF when HTML matches WordCraft's session clipboard does not return the old
|
||||
/// session fragment with its custom parts (#5785, #5859).
|
||||
#[test]
|
||||
fn paste_content_does_not_use_session_clipboard_when_html_matches_but_rtf_differs() {
|
||||
let mut s = s();
|
||||
run(&mut s, "insert.textBox", json!({"text": "Internal text box"}));
|
||||
run(&mut s, "select.range", json!({"anchor": Pos::body(0, 0), "focus": Pos::body(0, 3)}));
|
||||
run(&mut s, "edit.copy", json!({}));
|
||||
let my_html = s.clipboard_html.clone();
|
||||
let external_rtf = "{\\rtf1\\ansi External rich text}";
|
||||
let pasted_res = crate::cmd::paste::paste_content(&mut s, &json!({"html": my_html, "rtf": external_rtf}));
|
||||
assert!(matches!(pasted_res, Ok(crate::cmd::paste::Pasted::Fragment(_))));
|
||||
if let Ok(crate::cmd::paste::Pasted::Fragment(frag)) = pasted_res {
|
||||
assert!(frag.parts.is_empty(), "session text box parts not reused when RTF differs");
|
||||
}
|
||||
}
|
||||
|
||||
/// Pasting external RTF when plain text matches WordCraft's session clipboard does not return the
|
||||
/// old session fragment with its custom parts, even when privateClipboard is omitted (#5785, #5859).
|
||||
#[test]
|
||||
fn paste_content_does_not_use_session_clipboard_when_text_matches_but_rtf_differs() {
|
||||
let mut s = s();
|
||||
run(&mut s, "insert.textBox", json!({"text": "Internal text box"}));
|
||||
run(&mut s, "select.range", json!({"anchor": Pos::body(0, 0), "focus": Pos::body(0, 3)}));
|
||||
run(&mut s, "edit.copy", json!({}));
|
||||
let my_text = s.clipboard_text.clone();
|
||||
let external_rtf = "{\\rtf1\\ansi External rich text}";
|
||||
let pasted_res = crate::cmd::paste::paste_content(&mut s, &json!({"text": my_text, "rtf": external_rtf}));
|
||||
assert!(matches!(pasted_res, Ok(crate::cmd::paste::Pasted::Fragment(_))));
|
||||
if let Ok(crate::cmd::paste::Pasted::Fragment(frag)) = pasted_res {
|
||||
assert!(frag.parts.is_empty(), "session text box parts not reused when RTF differs");
|
||||
}
|
||||
|
||||
let avail = crate::cmd::paste::available(&s, &json!({"text": my_text, "rtf": external_rtf}));
|
||||
assert!(!avail.contains(&"formatted"), "formatted is unavailable when supplied RTF differs");
|
||||
}
|
||||
|
||||
/// When another app copies different RTF (`privateClipboard: false`), plain text matching
|
||||
/// WordCraft's session clipboard does not return the old session fragment (#5785, #5859).
|
||||
#[test]
|
||||
fn paste_content_does_not_use_session_clipboard_when_another_app_copied_rtf() {
|
||||
let mut s = s();
|
||||
run(&mut s, "insert.textBox", json!({"text": "Internal text box"}));
|
||||
run(&mut s, "select.range", json!({"anchor": Pos::body(0, 0), "focus": Pos::body(0, 3)}));
|
||||
run(&mut s, "edit.copy", json!({}));
|
||||
let my_text = s.clipboard_text.clone();
|
||||
let external_rtf = "{\\rtf1\\ansi External rich text}";
|
||||
let pasted_res = crate::cmd::paste::paste_content(&mut s, &json!({"privateClipboard": false, "text": my_text, "rtf": external_rtf}));
|
||||
assert!(matches!(pasted_res, Ok(crate::cmd::paste::Pasted::Fragment(_))));
|
||||
if let Ok(crate::cmd::paste::Pasted::Fragment(frag)) = pasted_res {
|
||||
assert!(frag.parts.is_empty(), "session text box parts not reused when another app copied");
|
||||
}
|
||||
}
|
||||
|
||||
/// The public `edit.paste` command does not reuse session text box parts when supplied RTF differs,
|
||||
/// even when privateClipboard is omitted (#5859).
|
||||
#[test]
|
||||
fn paste_command_does_not_use_session_clipboard_when_text_matches_but_rtf_differs() {
|
||||
let mut s = s();
|
||||
run(&mut s, "insert.textBox", json!({"text": "Internal text box"}));
|
||||
run(&mut s, "select.range", json!({"anchor": Pos::body(0, 0), "focus": Pos::body(0, 3)}));
|
||||
run(&mut s, "edit.copy", json!({}));
|
||||
let my_text = s.clipboard_text.clone();
|
||||
let external_rtf = "{\\rtf1\\ansi External rich text}";
|
||||
|
||||
run(&mut s, "caret.docEnd", json!({}));
|
||||
run(&mut s, "edit.paste", json!({"text": my_text, "rtf": external_rtf}));
|
||||
assert_eq!(s.doc.parts.len(), 1, "no second text box part created from session fragment");
|
||||
assert!(s.doc.plain_text(StoryRef::Body).contains("External rich text"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn word_count_includes_text_boxes_by_default() {
|
||||
let mut s = s();
|
||||
@@ -14294,6 +14943,143 @@ fn page_down_extends_a_selection_that_ends_in_collapsed_outline_text() {
|
||||
assert!(s.layout().caret(&s.sel.focus).is_some(), "to a place the outline shows");
|
||||
}
|
||||
|
||||
/// #5428: an inserted or pasted picture fits where it goes, as in Word: a table cell's width
|
||||
/// (a nested cell's too), a column's, not the whole page's text width.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn an_inserted_or_pasted_picture_fits_where_it_goes() {
|
||||
let png = |w: u32, h: u32| {
|
||||
let mut b = Vec::new();
|
||||
image::RgbaImage::from_pixel(w, h, image::Rgba([30, 90, 200, 255]))
|
||||
.write_to(&mut std::io::Cursor::new(&mut b), image::ImageFormat::Png)
|
||||
.unwrap();
|
||||
cmd::insert::base64_encode(&b)
|
||||
};
|
||||
let widths = |s: &Session| {
|
||||
let mut v = Vec::new();
|
||||
for b in s.doc.body.iter() {
|
||||
let mut b = (**b).clone();
|
||||
cmd::paste::each_para(&mut b, 0, &mut |p| {
|
||||
for o in &p.objects {
|
||||
if let wordcraft_doc::InlineObject::Image { w, h, .. } = o {
|
||||
v.push((*w, *h));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
v
|
||||
};
|
||||
let text_w = crate::io::text_width(&Session::new(wordcraft_doc::Document::new()).doc);
|
||||
let in_cell = |cols: u32| {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
run(&mut s, "insert.table", json!({"rows": 1, "cols": cols}));
|
||||
assert!(s.sel.focus.path.depth() > 0, "the caret is in the first cell");
|
||||
s
|
||||
};
|
||||
// Insert › Pictures and Paste in a cell of a three-column table.
|
||||
let cell = text_w / 3.0;
|
||||
let mut s = in_cell(3);
|
||||
run(&mut s, "insert.picture", json!({"data": png(1000, 200)}));
|
||||
let mut p = in_cell(3);
|
||||
let html = format!("<p><img src=\"data:image/png;base64,{}\"></p>", png(1000, 200));
|
||||
run(&mut p, "edit.pasteSpecial", json!({"as": "html", "html": html}));
|
||||
for (how, s) in [("inserted", &s), ("pasted", &p)] {
|
||||
let got = widths(s);
|
||||
let [(w, h)] = got.as_slice() else { panic!("{how}: {got:?}") };
|
||||
assert!(*w <= cell && *w > cell - 20.0, "{how}: {w} fits the cell's text area ({cell} less its margins)");
|
||||
assert!((h * 5.0 - w).abs() < 0.1, "{how}: proportions kept: {w} × {h}");
|
||||
}
|
||||
// A table in that cell: its own narrower cell.
|
||||
let mut s = in_cell(2);
|
||||
let outer = s.room_at(&s.sel.focus.clone());
|
||||
// (A table inserted in a cell takes the page's text width for its columns, so four columns
|
||||
// make its cells narrower than the outer one.)
|
||||
run(&mut s, "insert.table", json!({"rows": 1, "cols": 4}));
|
||||
assert!(s.sel.focus.path.depth() > 1, "the caret is in the nested cell");
|
||||
let nested = s.room_at(&s.sel.focus.clone());
|
||||
assert!(nested < outer - 50.0, "the nested cell ({nested}) is narrower than the outer one ({outer})");
|
||||
run(&mut s, "insert.picture", json!({"data": png(1000, 200)}));
|
||||
let w = widths(&s)[0].0;
|
||||
assert!((w - nested).abs() < 0.5 && w <= text_w / 4.0, "{w} fits the nested cell ({nested})");
|
||||
// Two text columns: one column's width.
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
run(&mut s, "layout.columns", json!({"count": 2}));
|
||||
let column = s.doc.sections()[0].1.column_boxes()[0].1;
|
||||
run(&mut s, "insert.picture", json!({"data": png(1000, 200)}));
|
||||
let w = widths(&s)[0].0;
|
||||
assert!((w - column).abs() < 0.5, "{w} fits the column ({column})");
|
||||
// Body text keeps the full text width.
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
run(&mut s, "insert.picture", json!({"data": png(1000, 200)}));
|
||||
assert!((widths(&s)[0].0 - text_w).abs() < 0.5);
|
||||
}
|
||||
|
||||
/// #5428 review: a page can hold several continuous sections; a picture goes by the section of the
|
||||
/// position, not of the page's first one (two columns, then a continuous single-column section).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_picture_after_a_continuous_break_fits_its_own_section() {
|
||||
let sect = |cols: &str, kind: &str| format!(r#"<w:sectPr>{kind}<w:pgSz w:w="11906" w:h="16838"/><w:cols {cols} w:space="708"/></w:sectPr>"#);
|
||||
let body = [
|
||||
"<w:p><w:r><w:t>one</w:t></w:r></w:p>".to_string(),
|
||||
format!("<w:p><w:pPr>{}</w:pPr></w:p>", sect(r#"w:num="2""#, "")),
|
||||
"<w:p><w:r><w:t>two</w:t></w:r></w:p>".to_string(),
|
||||
sect("", r#"<w:type w:val="continuous"/>"#),
|
||||
]
|
||||
.concat();
|
||||
let mut s = Session::new(wordcraft_docx::read(&docx_with_styles(&body, "")).unwrap());
|
||||
let last = s.doc.body.len() - 1;
|
||||
s.sel = crate::Selection::caret(Pos::body(last, 0));
|
||||
let room = s.room_at(&s.sel.focus.clone());
|
||||
let column = s.doc.sections()[0].1.column_boxes()[0].1;
|
||||
assert!(room > column + 50.0, "{room} is the single column's width, not the earlier two columns' ({column})");
|
||||
}
|
||||
|
||||
/// #5428 review: Web Layout and Read Mode reflow the text to the window, but a picture put in
|
||||
/// there is fitted to the page's text width, as in Print Layout: the size stays in the document.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_picture_put_in_in_web_layout_fits_the_page_not_the_window() {
|
||||
let png = |w: u32, h: u32| {
|
||||
let mut b = Vec::new();
|
||||
image::RgbaImage::from_pixel(w, h, image::Rgba([30, 90, 200, 255]))
|
||||
.write_to(&mut std::io::Cursor::new(&mut b), image::ImageFormat::Png)
|
||||
.unwrap();
|
||||
cmd::insert::base64_encode(&b)
|
||||
};
|
||||
let width = |s: &Session| {
|
||||
s.doc.body.iter().filter_map(|b| b.as_para()).flat_map(|p| p.objects.iter()).find_map(|o| match o {
|
||||
wordcraft_doc::InlineObject::Image { w, .. } => Some(*w),
|
||||
_ => None,
|
||||
})
|
||||
};
|
||||
let text_w = crate::io::text_width(&Session::new(wordcraft_doc::Document::new()).doc);
|
||||
let web = || {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
run(&mut s, "view.webLayout", json!({}));
|
||||
// A narrow window, or a high zoom.
|
||||
s.view.web_width = 350.0;
|
||||
assert!(s.layout().pages[0].w < text_w, "the window is narrower than the page's text");
|
||||
s
|
||||
};
|
||||
let mut s = web();
|
||||
run(&mut s, "insert.picture", json!({"data": png(1000, 200)}));
|
||||
let mut p = web();
|
||||
let html = format!("<p><img src=\"data:image/png;base64,{}\"></p>", png(1000, 200));
|
||||
run(&mut p, "edit.pasteSpecial", json!({"as": "html", "html": html}));
|
||||
for (how, s) in [("inserted", &s), ("pasted", &p)] {
|
||||
let w = width(s).unwrap();
|
||||
assert!((w - text_w).abs() < 0.5, "{how}: {w} fits the page's text width ({text_w})");
|
||||
}
|
||||
// Read Mode's narrow pages don't set it either.
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
run(&mut s, "text.insert", json!({"text": "Read"}));
|
||||
run(&mut s, "view.readMode", json!({}));
|
||||
s.view.read_width = 240.0;
|
||||
let room = s.room_at(&s.sel.focus.clone());
|
||||
assert!((room - text_w).abs() < 0.5, "Read Mode: {room} is the page's text width ({text_w})");
|
||||
}
|
||||
|
||||
/// A picture an OpenDocument file gives no size is shown at its own, fitted to the text as other
|
||||
/// formats' are; one with a stated size keeps it, in line too.
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,532 @@
|
||||
//! #6739: a copied table pasted with the caret in a table cell does what Word's Paste does (rows
|
||||
//! inserted above, or cells overwritten from the caret's), and nests only when asked to.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::json;
|
||||
use wordcraft_doc::edit::Fragment;
|
||||
use wordcraft_doc::{Block, Cell, Document, Paragraph, Path, Pos, StoryRef, Table, para_block};
|
||||
|
||||
use crate::cmd::table::cell_text;
|
||||
use crate::{Selection, Session};
|
||||
|
||||
/// A table of `rows` x `cols` cells whose texts are `<prefix><row><col>` (from 1), 100 pt wide cells.
|
||||
fn table(prefix: &str, rows: usize, cols: usize) -> Table {
|
||||
let mut t = Table::new(rows, cols, 100.0 * cols as f32);
|
||||
for (r, row) in t.rows.iter_mut().enumerate() {
|
||||
for (c, cell) in row.cells.iter_mut().enumerate() {
|
||||
cell.blocks = Cell::with_text(&format!("{prefix}{}{}", r + 1, c + 1)).blocks;
|
||||
}
|
||||
}
|
||||
t
|
||||
}
|
||||
|
||||
/// A document of the 3 x 3 table d11..d33 and an empty paragraph, the caret in cell (`row`, `col`).
|
||||
fn dest(row: usize, col: usize) -> Session {
|
||||
let mut d = Document::new();
|
||||
d.body = vec![Arc::new(Block::Table(table("d", 3, 3))), para_block(Paragraph::new())];
|
||||
let mut s = Session::new(d);
|
||||
s.sel = Selection::caret(Pos::new(StoryRef::Body, Path(vec![0, row as u32, col as u32, 0]), 0));
|
||||
s
|
||||
}
|
||||
|
||||
fn copy(s: &mut Session, t: Table) {
|
||||
s.clipboard = Some(Fragment { blocks: vec![Block::Table(t)], ..Default::default() });
|
||||
}
|
||||
|
||||
fn paste(s: &mut Session) {
|
||||
s.run("edit.paste", &json!({})).unwrap();
|
||||
}
|
||||
|
||||
fn t0(s: &Session) -> &Table {
|
||||
s.doc.body[0].as_table().expect("the table")
|
||||
}
|
||||
|
||||
/// The texts of the table's rows, a nested table shown as `[nested]`.
|
||||
fn grid(t: &Table) -> Vec<Vec<String>> {
|
||||
t.rows
|
||||
.iter()
|
||||
.map(|r| r.cells.iter().map(|c| if c.blocks.iter().any(|b| b.as_table().is_some()) { "[nested]".into() } else { cell_text(c) }).collect())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn rows(spec: &[&str]) -> Vec<Vec<String>> {
|
||||
spec.iter().map(|r| r.split(',').map(str::to_string).collect()).collect()
|
||||
}
|
||||
|
||||
fn nested(t: &Table) -> bool {
|
||||
t.rows.iter().flat_map(|r| &r.cells).any(|c| c.blocks.iter().any(|b| b.as_table().is_some()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paste_all_keeps_tables_in_copy_order_inside_the_cell() {
|
||||
for col in [0, 1] {
|
||||
let mut s = dest(1, col);
|
||||
for prefix in ["first", "second"] {
|
||||
copy(&mut s, table(prefix, 1, 3));
|
||||
let frag = s.clipboard.as_ref().unwrap();
|
||||
s.clip_history.push(frag, &frag.clipboard_text());
|
||||
}
|
||||
s.run("edit.pasteAllClipboard", &json!({})).unwrap();
|
||||
let pasted: Vec<_> = t0(&s).rows[1].cells[col].blocks.iter().filter_map(|b| b.as_table()).map(|t| cell_text(&t.rows[0].cells[0])).collect();
|
||||
assert_eq!(pasted, ["first11", "second11"]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_copied_table_over_selected_cells_overwrites_from_the_top_left() {
|
||||
for (source_cols, expected) in
|
||||
[(2, rows(&["s11,s12,d13", "s21,s22,d23", "d31,d32,d33"])), (3, rows(&["s11,s12,s13", "s21,s22,s23", "d31,d32,d33"]))]
|
||||
{
|
||||
let mut s = dest(1, 1);
|
||||
crate::cmd::table::extend_selection(&mut s, Pos::new(StoryRef::Body, Path(vec![0, 0, 0, 0]), 0));
|
||||
let range = s.cell_range().unwrap();
|
||||
assert_eq!((range.rows, range.cols, range.stream), ((0, 1), (0, 1), false));
|
||||
copy(&mut s, table("s", 2, source_cols));
|
||||
paste(&mut s);
|
||||
assert_eq!(grid(t0(&s)), expected, "source width {source_cols}");
|
||||
assert_eq!(s.sel, Selection::caret(Pos::new(StoryRef::Body, Path(vec![0, 0, 0, 0]), 0)));
|
||||
assert!(s.cell_range().is_none());
|
||||
|
||||
s.run("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(grid(t0(&s)), grid(&table("d", 3, 3)));
|
||||
s.run("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(grid(t0(&s)), expected);
|
||||
let reopened = wordcraft_docx::read(&wordcraft_docx::write(&s.doc).unwrap()).unwrap();
|
||||
assert_eq!(grid(reopened.body[0].as_table().unwrap()), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plain_text_paste_still_replaces_a_cell_rectangle() {
|
||||
let mut s = dest(0, 0);
|
||||
crate::cmd::table::extend_selection(&mut s, Pos::new(StoryRef::Body, Path(vec![0, 1, 1, 0]), 0));
|
||||
s.run("edit.paste", &json!({"text": "replacement"})).unwrap();
|
||||
assert_eq!(grid(t0(&s)), rows(&["replacement,,d13", ",,d23", "d31,d32,d33"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_whole_table_with_the_caret_in_the_first_column_inserts_its_rows_above() {
|
||||
for (row, want) in [
|
||||
(1, rows(&["d11,d12,d13", "s11,s12,s13", "s21,s22,s23", "s31,s32,s33", "d21,d22,d23", "d31,d32,d33"])),
|
||||
(0, rows(&["s11,s12,s13", "s21,s22,s23", "s31,s32,s33", "d11,d12,d13", "d21,d22,d23", "d31,d32,d33"])),
|
||||
] {
|
||||
let mut s = dest(row, 0);
|
||||
copy(&mut s, table("s", 3, 3));
|
||||
paste(&mut s);
|
||||
assert_eq!(grid(t0(&s)), want, "caret in row {row}");
|
||||
assert!(!nested(t0(&s)));
|
||||
assert_eq!(s.doc.body.iter().filter(|b| b.as_table().is_some()).count(), 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_whole_table_with_the_caret_further_right_overwrites_cells_and_grows_the_table() {
|
||||
let mut s = dest(1, 2);
|
||||
copy(&mut s, table("s", 3, 3));
|
||||
paste(&mut s);
|
||||
let want = rows(&["d11,d12,d13,,", "d21,d22,s11,s12,s13", "d31,d32,s21,s22,s23", ",,s31,s32,s33"]);
|
||||
assert_eq!(grid(t0(&s)), want);
|
||||
assert_eq!(t0(&s).grid.len(), 5);
|
||||
assert!(t0(&s).rows.iter().all(|r| r.cells.len() == 5));
|
||||
// The last cell of the last row: the table grows two columns and two rows.
|
||||
let mut s = dest(2, 2);
|
||||
copy(&mut s, table("s", 3, 3));
|
||||
paste(&mut s);
|
||||
let want = rows(&["d11,d12,d13,,", "d21,d22,d23,,", "d31,d32,s11,s12,s13", ",,s21,s22,s23", ",,s31,s32,s33"]);
|
||||
assert_eq!(grid(t0(&s)), want);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cells_copied_from_part_of_a_table_overwrite_from_the_caret_in_any_column() {
|
||||
// Two cells of one column (Word: s12, s22 into the cells below the caret).
|
||||
let mut s = dest(1, 0);
|
||||
copy(&mut s, table("s", 2, 1));
|
||||
paste(&mut s);
|
||||
assert_eq!(grid(t0(&s)), rows(&["d11,d12,d13", "s11,d22,d23", "s21,d32,d33"]));
|
||||
// At the last row a row is added.
|
||||
let mut s = dest(2, 0);
|
||||
copy(&mut s, table("s", 2, 1));
|
||||
paste(&mut s);
|
||||
assert_eq!(grid(t0(&s)), rows(&["d11,d12,d13", "d21,d22,d23", "s11,d32,d33", "s21,,"]));
|
||||
// Two columns wide, from the middle column: it fits the table.
|
||||
let mut s = dest(0, 1);
|
||||
copy(&mut s, table("s", 2, 2));
|
||||
paste(&mut s);
|
||||
assert_eq!(grid(t0(&s)), rows(&["d11,s11,s12", "d21,s21,s22", "d31,d32,d33"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_copied_cell_replaces_the_cell_it_is_pasted_in() {
|
||||
for (r, c) in [(0, 0), (1, 2), (2, 2)] {
|
||||
let mut s = dest(r, c);
|
||||
copy(&mut s, table("s", 1, 1));
|
||||
paste(&mut s);
|
||||
let mut want = grid(&table("d", 3, 3));
|
||||
want[r][c] = "s11".into();
|
||||
assert_eq!(grid(t0(&s)), want, "cell ({r}, {c})");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_caret_goes_to_the_first_pasted_cell() {
|
||||
let mut s = dest(1, 0);
|
||||
copy(&mut s, table("s", 3, 3));
|
||||
paste(&mut s);
|
||||
assert_eq!(s.sel.focus.path, Path(vec![0, 1, 0, 0]));
|
||||
assert!(s.sel.is_collapsed());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paste_as_nested_table_nests_the_table_in_the_cell() {
|
||||
let mut s = dest(1, 0);
|
||||
copy(&mut s, table("s", 3, 3));
|
||||
s.run("edit.pasteNestedTable", &json!({})).unwrap();
|
||||
let t = t0(&s);
|
||||
assert_eq!(t.rows.len(), 3, "no rows inserted");
|
||||
assert!(t.rows[1].cells[0].blocks.iter().any(|b| b.as_table().is_some()), "a table nests in the cell");
|
||||
assert_eq!(cell_text(&t.rows[1].cells[1]), "d22");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pasting_a_wrapped_table_keeps_its_source_controls() {
|
||||
use wordcraft_doc::{ContentControl, ControlKind};
|
||||
|
||||
for on_row in [false, true] {
|
||||
// A same-width copy can insert rows at column zero or overwrite cells further right.
|
||||
for col in [0, 1] {
|
||||
let mut s = dest(1, col);
|
||||
let mut source = table("s", 2, 3);
|
||||
let controls = if on_row { &mut source.rows[0].controls } else { &mut source.controls };
|
||||
let mut wrapper = ContentControl::new(ControlKind::RichText);
|
||||
wrapper.tag = "source wrapper".into();
|
||||
controls.open.push(wrapper);
|
||||
controls.close = 1;
|
||||
let expected = controls.clone();
|
||||
|
||||
copy(&mut s, source);
|
||||
paste(&mut s);
|
||||
|
||||
let pasted = t0(&s).rows[1].cells[col]
|
||||
.blocks
|
||||
.iter()
|
||||
.find_map(|b| b.as_table())
|
||||
.unwrap_or_else(|| panic!("the wrapped source should nest (row wrapper: {on_row}, column: {col})"));
|
||||
let controls = if on_row { &pasted.rows[0].controls } else { &pasted.controls };
|
||||
assert_eq!(controls, &expected, "row wrapper: {on_row}, column: {col}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_cannot_be_laid_over_the_cells_nests_as_before() {
|
||||
let nests = |s: &mut Session| {
|
||||
paste(s);
|
||||
assert!(nested(t0(s)), "nested");
|
||||
assert_eq!(t0(s).rows.len(), 3);
|
||||
};
|
||||
// Merged cells in the copy.
|
||||
let mut merged = table("s", 2, 3);
|
||||
merged.rows[0].cells[0].props.span = 2;
|
||||
merged.rows[0].cells.remove(1);
|
||||
let mut s = dest(1, 0);
|
||||
copy(&mut s, merged);
|
||||
nests(&mut s);
|
||||
// Ragged rows in the copy.
|
||||
let mut ragged = table("s", 2, 3);
|
||||
ragged.rows[1].cells.pop();
|
||||
let mut s = dest(1, 0);
|
||||
copy(&mut s, ragged);
|
||||
nests(&mut s);
|
||||
// More columns than a table may have.
|
||||
let mut s = dest(1, 2);
|
||||
copy(&mut s, table("s", 1, 62));
|
||||
nests(&mut s);
|
||||
// A table inside a copied cell.
|
||||
let mut inner = table("s", 1, 1);
|
||||
inner.rows[0].cells[0].blocks = vec![Arc::new(Block::Table(table("n", 1, 1)))];
|
||||
let mut s = dest(1, 0);
|
||||
copy(&mut s, inner);
|
||||
nests(&mut s);
|
||||
// Merged cells in the destination.
|
||||
let mut s = dest(1, 0);
|
||||
if let Some(Block::Table(t)) = s.doc.body.get_mut(0).map(Arc::make_mut) {
|
||||
t.rows[1].cells[0].props.span = 2;
|
||||
t.rows[1].cells.remove(1);
|
||||
}
|
||||
copy(&mut s, table("s", 1, 1));
|
||||
nests(&mut s);
|
||||
// A copied cell without any block (hostile fragment): nothing to lay over the cell.
|
||||
let mut hollow = table("s", 1, 1);
|
||||
hollow.rows[0].cells[0].blocks.clear();
|
||||
let mut s = dest(1, 0);
|
||||
copy(&mut s, hollow);
|
||||
let _ = s.run("edit.paste", &json!({}));
|
||||
assert_eq!(t0(&s).rows.len(), 3, "nothing laid over the cells");
|
||||
// A wider copy into a one-column table (a layout wrapper) nests instead of widening it.
|
||||
let mut s = dest(1, 0);
|
||||
s.doc.body[0] = Arc::new(Block::Table(table("w", 3, 1)));
|
||||
copy(&mut s, table("s", 2, 3));
|
||||
paste(&mut s);
|
||||
assert!(nested(t0(&s)));
|
||||
assert_eq!(t0(&s).grid.len(), 1);
|
||||
// A content control in a cell the copy would overwrite.
|
||||
let mut s = dest(1, 0);
|
||||
if let Some(Block::Table(t)) = s.doc.body.get_mut(0).map(Arc::make_mut) {
|
||||
t.rows[2].cells[0].controls.close = 1;
|
||||
}
|
||||
copy(&mut s, table("s", 3, 1));
|
||||
nests(&mut s);
|
||||
// Row exceptions on the destination.
|
||||
let mut s = dest(1, 0);
|
||||
if let Some(Block::Table(t)) = s.doc.body.get_mut(0).map(Arc::make_mut) {
|
||||
t.rows[0].props.exceptions = Some(Default::default());
|
||||
}
|
||||
copy(&mut s, table("s", 1, 1));
|
||||
nests(&mut s);
|
||||
// Track Changes on.
|
||||
let mut s = dest(1, 0);
|
||||
s.doc.settings.track_changes = true;
|
||||
copy(&mut s, table("s", 3, 3));
|
||||
nests(&mut s);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_shapes_never_panic() {
|
||||
// An empty table, a table with empty rows, 30,000 columns and 30,000 rows in a copy.
|
||||
let mut wide = table("s", 1, 1);
|
||||
wide.grid = vec![1.0; 30_000];
|
||||
wide.rows[0].cells = (0..30_000).map(|_| Cell::empty()).collect();
|
||||
let mut tall = table("s", 1, 2);
|
||||
tall.rows = (0..30_000).map(|_| tall.rows[0].clone()).collect();
|
||||
let mut no_rows = table("s", 1, 1);
|
||||
no_rows.rows.clear();
|
||||
let mut no_cells = table("s", 1, 1);
|
||||
no_cells.rows[0].cells.clear();
|
||||
// 30,000 columns and empty tables can't be laid over the cells: they nest (the old path).
|
||||
for t in [wide, no_rows, no_cells] {
|
||||
for (r, c) in [(0, 0), (2, 2)] {
|
||||
let mut s = dest(r, c);
|
||||
copy(&mut s, t.clone());
|
||||
let _ = s.run("edit.paste", &json!({}));
|
||||
assert_eq!((t0(&s).rows.len(), t0(&s).grid.len()), (3, 3), "unchanged table");
|
||||
}
|
||||
}
|
||||
// 30,000 rows are laid over the cells: rows are added up to the limit, never past it.
|
||||
for (r, c) in [(0, 0), (2, 1)] {
|
||||
let mut s = dest(r, c);
|
||||
copy(&mut s, tall.clone());
|
||||
s.run("edit.paste", &json!({})).unwrap();
|
||||
assert_eq!(t0(&s).rows.len(), r + 30_000);
|
||||
assert!(t0(&s).rows.iter().all(|row| row.cells.len() == t0(&s).grid.len()));
|
||||
}
|
||||
// More rows than a table may have nest instead.
|
||||
let mut huge = table("s", 1, 2);
|
||||
huge.rows = (0..wordcraft_doc::table::MAX_ROWS).map(|_| huge.rows[0].clone()).collect();
|
||||
let mut s = dest(1, 1);
|
||||
copy(&mut s, huge);
|
||||
let _ = s.run("edit.paste", &json!({}));
|
||||
assert_eq!(t0(&s).rows.len(), 3);
|
||||
// A caret path that is not a cell of the table.
|
||||
let mut s = dest(0, 0);
|
||||
s.sel = Selection::caret(Pos::new(StoryRef::Body, Path(vec![0, 9, 9, 0]), 0));
|
||||
copy(&mut s, table("s", 1, 1));
|
||||
let _ = s.run("edit.paste", &json!({}));
|
||||
assert_eq!(t0(&s).rows.len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_copied_table_with_empty_paragraphs_around_it_is_laid_over_the_cells_too() {
|
||||
let mut s = dest(1, 0);
|
||||
s.clipboard = Some(Fragment {
|
||||
blocks: vec![Block::Para(Paragraph::new()), Block::Table(table("s", 1, 3)), Block::Para(Paragraph::new())],
|
||||
..Default::default()
|
||||
});
|
||||
paste(&mut s);
|
||||
assert_eq!(grid(t0(&s)), rows(&["d11,d12,d13", "s11,s12,s13", "d21,d22,d23", "d31,d32,d33"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undo_takes_the_paste_back_in_one_step_and_redo_does_it_again() {
|
||||
for (row, col) in [(1, 0), (1, 2)] {
|
||||
let mut s = dest(row, col);
|
||||
let before = t0(&s).clone();
|
||||
copy(&mut s, table("s", 3, 3));
|
||||
paste(&mut s);
|
||||
let after = t0(&s).clone();
|
||||
assert_ne!(after, before);
|
||||
s.run("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(t0(&s), &before, "one undo restores the table ({row}, {col})");
|
||||
s.run("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(t0(&s), &after);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_pasted_rows_survive_saving_and_reopening_as_docx() {
|
||||
let mut s = dest(1, 0);
|
||||
copy(&mut s, table("s", 3, 3));
|
||||
paste(&mut s);
|
||||
let bytes = crate::io::save_bytes("t.docx", &s.doc).unwrap();
|
||||
let back = crate::io::open_bytes("t.docx", &bytes).unwrap();
|
||||
let t = back.body.iter().find_map(|b| b.as_table()).expect("a table");
|
||||
assert_eq!(grid(t), grid(t0(&s)));
|
||||
let mut s = dest(1, 2);
|
||||
copy(&mut s, table("s", 3, 3));
|
||||
paste(&mut s);
|
||||
let back = crate::io::open_bytes("t.docx", &crate::io::save_bytes("t.docx", &s.doc).unwrap()).unwrap();
|
||||
let t = back.body.iter().find_map(|b| b.as_table()).expect("a table");
|
||||
assert_eq!((t.rows.len(), t.grid.len()), (4, 5));
|
||||
assert_eq!(grid(t), grid(t0(&s)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_paste_into_a_cell_of_a_table_inside_a_cell_works_on_that_table() {
|
||||
let mut inner_host = table("o", 1, 1);
|
||||
inner_host.rows[0].cells[0].blocks = vec![Arc::new(Block::Table(table("d", 3, 3))), para_block(Paragraph::new())];
|
||||
let mut d = Document::new();
|
||||
d.body = vec![Arc::new(Block::Table(inner_host)), para_block(Paragraph::new())];
|
||||
let mut s = Session::new(d);
|
||||
// Body table 0, row 0, cell 0, its block 0 (the inner table), row 1, cell 0, block 0.
|
||||
s.sel = Selection::caret(Pos::new(StoryRef::Body, Path(vec![0, 0, 0, 0, 1, 0, 0]), 0));
|
||||
copy(&mut s, table("s", 3, 3));
|
||||
paste(&mut s);
|
||||
let inner = t0(&s).rows[0].cells[0].blocks[0].as_table().expect("the inner table").clone();
|
||||
assert_eq!(grid(&inner).len(), 6);
|
||||
assert!(!nested(&inner));
|
||||
}
|
||||
|
||||
/// A locked control in a table nested in a cell the copy would overwrite is not deleted: the
|
||||
/// paste nests instead (#6739 review).
|
||||
#[test]
|
||||
fn a_locked_control_in_a_nested_table_of_an_overwritten_cell_is_kept() {
|
||||
use wordcraft_doc::{ContentControl, ControlKind, ControlLock};
|
||||
let mut s = dest(0, 0);
|
||||
let mut inner = table("n", 1, 1);
|
||||
let mut ctl = ContentControl::new(ControlKind::RichText);
|
||||
ctl.lock = ControlLock::SdtContentLocked;
|
||||
inner.rows[0].cells[0].controls.open.push(ctl);
|
||||
inner.rows[0].cells[0].controls.close = 1;
|
||||
if let Some(Block::Table(t)) = s.doc.body.get_mut(0).map(Arc::make_mut) {
|
||||
t.rows[1].cells[0].blocks = vec![Arc::new(Block::Table(inner)), para_block(Paragraph::new())];
|
||||
}
|
||||
let before = t0(&s).rows[1].cells[0].clone();
|
||||
// Copy one cell, caret above the cell with the nested table: it would be overwritten.
|
||||
copy(&mut s, table("s", 2, 1));
|
||||
paste(&mut s);
|
||||
let kept = |t: &Table| t.rows.iter().flat_map(|r| &r.cells).any(|c| c.blocks == before.blocks);
|
||||
assert!(kept(t0(&s)), "the cell with the locked control survives");
|
||||
}
|
||||
|
||||
/// A caret in a control that shows its placeholder: no rows are inserted above the caret's row;
|
||||
/// the table nests in the cell as the ordinary paste does (#6739 review).
|
||||
#[test]
|
||||
fn a_control_showing_its_placeholder_gets_the_ordinary_paste_not_inserted_rows() {
|
||||
let mut s = dest(1, 0);
|
||||
s.run("developer.plainText", &json!({})).unwrap();
|
||||
let before = s.doc.body[0].as_table().map(|t| t.rows.len());
|
||||
copy(&mut s, table("s", 3, 3));
|
||||
paste(&mut s);
|
||||
assert_eq!(t0(&s).rows.len(), before.unwrap_or(0), "no rows inserted above the caret's row");
|
||||
assert!(nested(t0(&s)), "the table nests in the cell");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paste_from_before_a_block_control_replaces_its_placeholder() {
|
||||
let mut s = dest(1, 0);
|
||||
let start = s.sel.focus.clone();
|
||||
s.run("developer.plainText", &json!({})).unwrap();
|
||||
let range = s.doc.control_at(&s.sel.focus).unwrap();
|
||||
assert_eq!(range.start, start);
|
||||
assert!(range.control.showing_placeholder);
|
||||
let placeholder = s.doc.para_at(&start).unwrap().text[range.content_start().off..range.end.off].to_owned();
|
||||
assert!(!placeholder.is_empty());
|
||||
s.doc.control_mut(&start).unwrap().block = true;
|
||||
s.sel = Selection::caret(start);
|
||||
copy(&mut s, table("s", 1, 3));
|
||||
paste(&mut s);
|
||||
assert_eq!(t0(&s).rows.len(), 3);
|
||||
assert!(nested(t0(&s)));
|
||||
assert!(!cell_text(&t0(&s).rows[1].cells[0]).contains(&placeholder));
|
||||
}
|
||||
|
||||
/// A locked control in a text box anchored in a cell the copy would overwrite is not lost: the
|
||||
/// paste nests instead (#6739 review).
|
||||
#[test]
|
||||
fn a_locked_control_in_a_text_box_of_an_overwritten_cell_is_kept() {
|
||||
use wordcraft_doc::para::ShapeKind;
|
||||
use wordcraft_doc::{ContentControl, ControlKind, ControlLock, InlineObject, PartKind};
|
||||
let mut s = dest(0, 0);
|
||||
let mut ctl = ContentControl::new(ControlKind::RichText);
|
||||
ctl.lock = ControlLock::SdtContentLocked;
|
||||
let mut inner = Paragraph::with_text("Locked", Default::default());
|
||||
inner.insert_object(0, InlineObject::ControlStart { control: Box::new(ctl) }, &Default::default()).unwrap();
|
||||
let end = inner.text.chars().count();
|
||||
inner.insert_object(end, InlineObject::ControlEnd, &Default::default()).unwrap();
|
||||
let id = s.doc.add_part(PartKind::TextBox, vec![para_block(inner)]);
|
||||
let shape = InlineObject::Shape {
|
||||
kind: ShapeKind::TextBox,
|
||||
w: 72.0,
|
||||
h: 36.0,
|
||||
fill: None,
|
||||
stroke: None,
|
||||
stroke_width: 0.75,
|
||||
float: Default::default(),
|
||||
story: Some(id),
|
||||
freeform: None,
|
||||
effects: Default::default(),
|
||||
extra: Default::default(),
|
||||
};
|
||||
let mut anchor = Paragraph::with_text("Box", Default::default());
|
||||
anchor.insert_object(0, shape, &Default::default()).unwrap();
|
||||
if let Some(Block::Table(t)) = s.doc.body.get_mut(0).map(Arc::make_mut) {
|
||||
t.rows[1].cells[0].blocks = vec![para_block(anchor)];
|
||||
}
|
||||
let before = t0(&s).rows[1].cells[0].blocks.clone();
|
||||
// One column of two cells from the caret in the top cell: the cell with the box is overwritten.
|
||||
copy(&mut s, table("s", 2, 1));
|
||||
paste(&mut s);
|
||||
let kept = |t: &Table| t.rows.iter().flat_map(|r| &r.cells).any(|c| c.blocks == before);
|
||||
assert!(kept(t0(&s)), "the cell anchoring the text box survives");
|
||||
assert!(nested(t0(&s)), "the table nests in the cell instead");
|
||||
}
|
||||
|
||||
/// A row-level content control on a row the copy would overwrite is not bypassed: the paste nests
|
||||
/// instead (#6739 review).
|
||||
#[test]
|
||||
fn a_row_level_control_on_an_overwritten_row_declines_the_overwrite() {
|
||||
use wordcraft_doc::{ContentControl, ControlKind, ControlLock};
|
||||
let mut s = dest(0, 0);
|
||||
let mut ctl = ContentControl::new(ControlKind::RichText);
|
||||
ctl.lock = ControlLock::SdtContentLocked;
|
||||
if let Some(Block::Table(t)) = s.doc.body.get_mut(0).map(Arc::make_mut) {
|
||||
t.rows[1].controls.open.push(ctl);
|
||||
t.rows[1].controls.close = 1;
|
||||
}
|
||||
let before = grid(t0(&s));
|
||||
copy(&mut s, table("s", 2, 1));
|
||||
paste(&mut s);
|
||||
assert_eq!(grid(t0(&s))[1], before[1], "the row under the control is not overwritten");
|
||||
assert!(nested(t0(&s)), "the table nests in the cell instead");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_overwrite_inside_a_spanning_row_control_preserves_the_row() {
|
||||
use wordcraft_doc::{ContentControl, ControlKind, ControlLock};
|
||||
|
||||
let mut s = dest(1, 1);
|
||||
let mut control = ContentControl::new(ControlKind::RichText);
|
||||
control.lock = ControlLock::SdtContentLocked;
|
||||
let destination = s.doc.table_mut(StoryRef::Body, &Path(vec![0])).unwrap();
|
||||
destination.rows[0].controls.open.push(control);
|
||||
destination.rows[2].controls.close = 1;
|
||||
copy(&mut s, table("s", 1, 1));
|
||||
paste(&mut s);
|
||||
|
||||
let table = t0(&s);
|
||||
let cell = &table.rows[1].cells[1];
|
||||
assert!(cell_text(cell).lines().any(|line| line == "d22"));
|
||||
assert!(cell.blocks.iter().any(|block| block.as_table().is_some()));
|
||||
assert_eq!(table.rows[0].controls.open[0].lock, ControlLock::SdtContentLocked);
|
||||
assert_eq!(table.rows[2].controls.close, 1);
|
||||
}
|
||||
@@ -30,7 +30,7 @@ pub use face::{FALLBACK_FAMILY, FaceRef, FontFace, bundled};
|
||||
use fallback_data::{Coverage, RUN_FALLBACK_CACHE_CHARS, SYS_FALLBACK_MAX_FILE, file_coverage, ranges_hold};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use fallback_data::{CoverageIndex, SysFallback};
|
||||
use fallback_data::{FallbackCache, RunFallbackCache};
|
||||
use fallback_data::{DiagramFallbackCache, FallbackCache, RunFallbackCache};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use names::CatalogEntry;
|
||||
pub use names::{LocalName, base_style, name_language_matches, system_font_dirs};
|
||||
@@ -56,6 +56,13 @@ pub struct FontDb {
|
||||
/// (Thai, #59) got slower with every font loaded.
|
||||
fallbacks: RwLock<FallbackCache>,
|
||||
run_fallbacks: RwLock<RunFallbackCache>,
|
||||
diagram_fallbacks: RwLock<DiagramFallbackCache>,
|
||||
#[cfg(test)]
|
||||
diagram_searches: std::sync::atomic::AtomicU64,
|
||||
#[cfg(test)]
|
||||
diagram_search_hook: Mutex<Option<Box<dyn FnOnce(&FontDb) + Send>>>,
|
||||
#[cfg(test)]
|
||||
diagram_publish_hook: Mutex<Option<Box<dyn FnOnce(&FontDb) + Send>>>,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
catalog: RwLock<Vec<CatalogEntry>>,
|
||||
/// Fonts the user added at run time, and the folder they are stored in (#582).
|
||||
@@ -119,6 +126,13 @@ impl FontDb {
|
||||
hinters: Mutex::new(HashMap::new()),
|
||||
fallbacks: RwLock::new(FallbackCache::default()),
|
||||
run_fallbacks: RwLock::new(RunFallbackCache::default()),
|
||||
diagram_fallbacks: RwLock::new(DiagramFallbackCache::default()),
|
||||
#[cfg(test)]
|
||||
diagram_searches: std::sync::atomic::AtomicU64::new(0),
|
||||
#[cfg(test)]
|
||||
diagram_search_hook: Mutex::new(None),
|
||||
#[cfg(test)]
|
||||
diagram_publish_hook: Mutex::new(None),
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
catalog: RwLock::new(Vec::new()),
|
||||
user: RwLock::new(user::UserFonts::default()),
|
||||
@@ -147,8 +161,10 @@ impl FontDb {
|
||||
self.sys.lock().unwrap_or_else(std::sync::PoisonError::into_inner).enabled = on;
|
||||
}
|
||||
// Misses remembered while it was off may be found now.
|
||||
self.fallbacks.write().unwrap_or_else(std::sync::PoisonError::into_inner).map.clear();
|
||||
self.generation.fetch_add(1, Ordering::AcqRel);
|
||||
*self.fallbacks.write().unwrap_or_else(std::sync::PoisonError::into_inner) = FallbackCache::default();
|
||||
*self.run_fallbacks.write().unwrap_or_else(std::sync::PoisonError::into_inner) = RunFallbackCache::default();
|
||||
*self.diagram_fallbacks.write().unwrap_or_else(std::sync::PoisonError::into_inner) = DiagramFallbackCache::default();
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let _ = on;
|
||||
}
|
||||
|
||||
@@ -396,6 +396,147 @@ impl FontFace {
|
||||
pub fn is_east_asian(&self) -> bool {
|
||||
self.skrifa().is_some_and(|f| east_asian_font(&f))
|
||||
}
|
||||
/// Is this a serif face? Checks family name conventions (e.g. Mincho, Song, Times vs Sans, Gothic, Arial),
|
||||
/// falling back to the OS/2 family class and Panose serif style.
|
||||
pub fn is_serif(&self) -> bool {
|
||||
if is_explicit_sans(&self.family) {
|
||||
return false;
|
||||
}
|
||||
if is_explicit_serif(&self.family) {
|
||||
return true;
|
||||
}
|
||||
use skrifa::raw::TableProvider;
|
||||
if let Some(sk) = self.skrifa()
|
||||
&& let Ok(os2) = sk.os2()
|
||||
{
|
||||
let class_id = (os2.s_family_class() >> 8) as u8;
|
||||
if (1..=5).contains(&class_id) || class_id == 7 {
|
||||
return true;
|
||||
}
|
||||
if class_id == 8 {
|
||||
return false;
|
||||
}
|
||||
let panose = os2.panose_10();
|
||||
if panose[0] == 2 {
|
||||
let serif_style = panose[1];
|
||||
if (2..=10).contains(&serif_style) {
|
||||
return true;
|
||||
}
|
||||
if (11..=15).contains(&serif_style) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Tokens identifying known sans-serif font families by naming convention (#5672).
|
||||
const SANS_TOKENS: &[&str] = &[
|
||||
"sans",
|
||||
"gothic",
|
||||
"hei",
|
||||
"yahei",
|
||||
"simhei",
|
||||
"zenhei",
|
||||
"heiti",
|
||||
"meiryo",
|
||||
"pingfang",
|
||||
"dotum",
|
||||
"gulim",
|
||||
"malgun",
|
||||
"arial",
|
||||
"calibri",
|
||||
"aptos",
|
||||
"carlito",
|
||||
"inter",
|
||||
"helvetica",
|
||||
"segoe",
|
||||
"tahoma",
|
||||
"verdana",
|
||||
];
|
||||
|
||||
/// Tokens identifying known serif font families by naming convention (#5672).
|
||||
const SERIF_TOKENS: &[&str] = &[
|
||||
"serif",
|
||||
"mincho",
|
||||
"song",
|
||||
"songti",
|
||||
"simsun",
|
||||
"nsimsun",
|
||||
"fangsong",
|
||||
"ming",
|
||||
"mingti",
|
||||
"batang",
|
||||
"sun",
|
||||
"times",
|
||||
"cambria",
|
||||
"georgia",
|
||||
"garamond",
|
||||
"palatino",
|
||||
"century",
|
||||
"bookman",
|
||||
"baskerville",
|
||||
"caladea",
|
||||
"tinos",
|
||||
];
|
||||
|
||||
/// Split a font family name into lowercased tokens along non-alphanumeric boundaries,
|
||||
/// camelCase / acronym transitions, and letter-to-digit/digit-to-letter boundaries (#5672).
|
||||
fn font_name_tokens(name: &str) -> Vec<String> {
|
||||
let mut tokens = Vec::new();
|
||||
let mut current = String::new();
|
||||
let mut prev_char: Option<char> = None;
|
||||
let mut chars = name.chars().peekable();
|
||||
|
||||
while let Some(c) = chars.next() {
|
||||
if !c.is_alphanumeric() {
|
||||
if !current.is_empty() {
|
||||
tokens.push(std::mem::take(&mut current).to_ascii_lowercase());
|
||||
}
|
||||
prev_char = None;
|
||||
continue;
|
||||
}
|
||||
let next_lower = chars.peek().is_some_and(|n| n.is_lowercase());
|
||||
let is_split = if let Some(prev) = prev_char {
|
||||
(prev.is_lowercase() && c.is_uppercase())
|
||||
|| (prev.is_uppercase() && c.is_uppercase() && next_lower)
|
||||
|| (prev.is_alphabetic() && c.is_numeric())
|
||||
|| (prev.is_numeric() && c.is_alphabetic())
|
||||
} else {
|
||||
false
|
||||
};
|
||||
|
||||
if is_split && !current.is_empty() {
|
||||
tokens.push(std::mem::take(&mut current).to_ascii_lowercase());
|
||||
}
|
||||
|
||||
current.push(c);
|
||||
prev_char = Some(c);
|
||||
}
|
||||
|
||||
if !current.is_empty() {
|
||||
tokens.push(current.to_ascii_lowercase());
|
||||
}
|
||||
|
||||
let flattened: String = name.chars().filter(|c| c.is_alphanumeric()).collect::<String>().to_ascii_lowercase();
|
||||
if !flattened.is_empty() && !tokens.iter().any(|t| t == &flattened) {
|
||||
tokens.push(flattened);
|
||||
}
|
||||
|
||||
tokens
|
||||
}
|
||||
|
||||
/// Does a family name explicitly identify a sans-serif font by whole tokens?
|
||||
fn is_explicit_sans(name: &str) -> bool {
|
||||
let tokens = font_name_tokens(name);
|
||||
tokens.iter().any(|t| SANS_TOKENS.contains(&t.as_str()))
|
||||
}
|
||||
|
||||
/// Does a family name explicitly identify a serif font by whole tokens?
|
||||
fn is_explicit_serif(name: &str) -> bool {
|
||||
let tokens = font_name_tokens(name);
|
||||
tokens.iter().any(|t| SERIF_TOKENS.contains(&t.as_str()))
|
||||
}
|
||||
|
||||
pub(super) static NEXT_ID: AtomicU32 = AtomicU32::new(1);
|
||||
@@ -460,3 +601,33 @@ impl OutlinePen for FlipPen {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn whole_token_serif_sans_matching() {
|
||||
// #5672: Whole tokens match rather than bare substrings ("hei", "sun").
|
||||
assert!(!is_explicit_sans("Heisei Mincho"), "Heisei Mincho must not match sans 'hei'");
|
||||
assert!(is_explicit_serif("Heisei Mincho"), "Heisei Mincho is serif");
|
||||
|
||||
assert!(!is_explicit_serif("Sunflower"), "Sunflower must not match serif 'sun'");
|
||||
assert!(!is_explicit_sans("Sunflower"));
|
||||
|
||||
assert!(is_explicit_sans("SimHei"));
|
||||
assert!(is_explicit_sans("STHeiti"));
|
||||
assert!(is_explicit_sans("BIZ UDPGothic"));
|
||||
assert!(is_explicit_sans("MS PGothic"));
|
||||
assert!(is_explicit_sans("Microsoft YaHei"));
|
||||
assert!(is_explicit_sans("WenQuanYi Zen Hei"));
|
||||
assert!(is_explicit_sans("Source Sans 3"));
|
||||
|
||||
assert!(is_explicit_serif("SimSun"));
|
||||
assert!(is_explicit_serif("NSimSun"));
|
||||
assert!(is_explicit_serif("BIZ UDPMincho"));
|
||||
assert!(is_explicit_serif("MS PMincho"));
|
||||
assert!(is_explicit_serif("Shippori Mincho"));
|
||||
assert!(is_explicit_serif("Source Serif 4"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
use super::face::{FALLBACK_FAMILY, FontFace};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use super::fallback_data::{CoverageIndex, IndexedFile, SYS_MISSES_MAX, SYSTEM_FALLBACKS, file_stamp, ranges_hold, read_fallback_file};
|
||||
use super::fallback_data::{FALLBACK_CACHE_MAX, RTL_FALLBACKS, RUN_FALLBACK_CACHE_CHARS, RUN_FALLBACK_CACHE_MAX, arabic_block, fallback_order};
|
||||
use super::fallback_data::{
|
||||
DiagramFallbackKey, FALLBACK_CACHE_MAX, RTL_FALLBACKS, RUN_FALLBACK_CACHE_CHARS, RUN_FALLBACK_CACHE_MAX, arabic_block, fallback_order,
|
||||
};
|
||||
use super::{Arc, FontDb};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use super::{HashMap, Ordering};
|
||||
@@ -29,28 +31,35 @@ impl FontDb {
|
||||
Some(if styled.family.eq_ignore_ascii_case(&base.family) && styled.covers(c) && styled.id != exclude { styled } else { base })
|
||||
}
|
||||
|
||||
/// The fallback search, cached per (character, excluded face) until more faces load.
|
||||
/// The fallback search, cached per (character, excluded face) until loaded faces or font
|
||||
/// generation change.
|
||||
fn cached_fallback(&self, c: char, exclude: u32) -> Option<Arc<FontFace>> {
|
||||
let generation = self.generation();
|
||||
let n = self.read_faces().len();
|
||||
{
|
||||
let cache = self.fallbacks.read().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if cache.faces == n
|
||||
&& cache.generation == generation
|
||||
&& let Some(hit) = cache.map.get(&(c, exclude))
|
||||
{
|
||||
return hit.clone();
|
||||
}
|
||||
}
|
||||
let (found, n) = self.search_fallback(c, exclude);
|
||||
// Keyed by the face count the answer was chosen from (a system fallback may have loaded
|
||||
// fonts, and another thread may have loaded more since: an answer from before that load
|
||||
// is returned but not cached under the new count).
|
||||
if n != self.read_faces().len() {
|
||||
// Keyed by the face count and generation the answer was chosen from (a system fallback may
|
||||
// have loaded fonts, and another thread may have loaded or changed fonts since: an answer
|
||||
// from before that change is returned but not cached under the new state).
|
||||
if n != self.read_faces().len() || generation != self.generation() {
|
||||
return found;
|
||||
}
|
||||
let mut cache = self.fallbacks.write().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if cache.faces != n || cache.map.len() >= FALLBACK_CACHE_MAX {
|
||||
if n != self.read_faces().len() || generation != self.generation() {
|
||||
return found;
|
||||
}
|
||||
if cache.faces != n || cache.generation != generation || cache.map.len() >= FALLBACK_CACHE_MAX {
|
||||
cache.map.clear();
|
||||
cache.faces = n;
|
||||
cache.generation = generation;
|
||||
}
|
||||
cache.map.insert((c, exclude), found.clone());
|
||||
found
|
||||
@@ -151,23 +160,36 @@ impl FontDb {
|
||||
set.sort_unstable();
|
||||
set.dedup();
|
||||
let key = (set, exclude, bold, italic);
|
||||
let generation = self.generation();
|
||||
let n = self.read_faces().len();
|
||||
{
|
||||
let cache = self.run_fallbacks.read().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if cache.faces == n
|
||||
&& cache.generation == generation
|
||||
&& let Some(hit) = cache.map.get(&key)
|
||||
{
|
||||
return hit.clone();
|
||||
}
|
||||
}
|
||||
// Keyed by the face count the search last looked at, not the count after it: a face loaded
|
||||
// meanwhile by another thread (one its search, or a family named by a document) must make
|
||||
// a miss count as stale, not as the answer for the new count.
|
||||
// Keyed by the face count and generation the search last looked at, not the state after it:
|
||||
// a face loaded or changed meanwhile by another thread (one its search, a family named by a
|
||||
// document, or a user font change) must not be overwritten with a stale answer.
|
||||
let (found, n) = self.search_run(&key.0, exclude, bold, italic);
|
||||
if n != self.read_faces().len() || generation != self.generation() {
|
||||
return found;
|
||||
}
|
||||
let mut cache = self.run_fallbacks.write().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if cache.faces != n || cache.map.len() >= RUN_FALLBACK_CACHE_MAX || cache.chars.saturating_add(key.0.len()) > RUN_FALLBACK_CACHE_CHARS {
|
||||
if n != self.read_faces().len() || generation != self.generation() {
|
||||
return found;
|
||||
}
|
||||
if cache.faces != n
|
||||
|| cache.generation != generation
|
||||
|| cache.map.len() >= RUN_FALLBACK_CACHE_MAX
|
||||
|| cache.chars.saturating_add(key.0.len()) > RUN_FALLBACK_CACHE_CHARS
|
||||
{
|
||||
cache.map.clear();
|
||||
cache.faces = n;
|
||||
cache.generation = generation;
|
||||
cache.chars = 0;
|
||||
}
|
||||
cache.chars = cache.chars.saturating_add(key.0.len());
|
||||
@@ -213,7 +235,11 @@ impl FontDb {
|
||||
(true, false) => "Bold",
|
||||
_ => "Italic",
|
||||
};
|
||||
let before_style = self.read_faces().len();
|
||||
let styled = self.face(&base.family, style);
|
||||
if before_style == checked {
|
||||
checked = self.read_faces().len();
|
||||
}
|
||||
let face = if styled.family.eq_ignore_ascii_case(&base.family) && chars.iter().all(|c| styled.covers(*c)) && styled.id != exclude {
|
||||
styled
|
||||
} else {
|
||||
@@ -234,11 +260,140 @@ impl FontDb {
|
||||
(found, faces.len())
|
||||
}
|
||||
|
||||
/// First face covering all characters in `chars`, preferring faces matching `prefer_serif`
|
||||
/// (so a diagram maintains a consistent fallback face across its nodes matching the
|
||||
/// diagram's primary style, #5672). Does not alter body text fallback ordering. Cached until
|
||||
/// the loaded faces or font database generation changes, so page redraws do not repeat system scans.
|
||||
pub fn fallback_for_diagram(&self, chars: &[char], exclude: u32, prefer_serif: bool) -> Option<Arc<FontFace>> {
|
||||
if chars.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut set: Vec<char> = chars.to_vec();
|
||||
set.sort_unstable();
|
||||
set.dedup();
|
||||
let key: DiagramFallbackKey = (set, exclude, prefer_serif);
|
||||
let generation = self.generation();
|
||||
let n = self.read_faces().len();
|
||||
{
|
||||
let cache = self.diagram_fallbacks.read().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if cache.faces == n
|
||||
&& cache.generation == generation
|
||||
&& let Some(hit) = cache.map.get(&key)
|
||||
{
|
||||
return hit.clone();
|
||||
}
|
||||
}
|
||||
// Keyed by the face count and generation the search last looked at, not the state after it:
|
||||
// a face loaded or added meanwhile (for instance via `add_font`) must not be shadowed by
|
||||
// caching an older answer under the newer face count.
|
||||
let (found, n) = self.search_diagram(&key.0, exclude, prefer_serif);
|
||||
if n != self.read_faces().len() || generation != self.generation() || key.0.len() > RUN_FALLBACK_CACHE_CHARS {
|
||||
return found;
|
||||
}
|
||||
#[cfg(test)]
|
||||
if let Some(hook) = self.diagram_publish_hook.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take() {
|
||||
hook(self);
|
||||
}
|
||||
let mut cache = self.diagram_fallbacks.write().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if n != self.read_faces().len() || generation != self.generation() {
|
||||
return found;
|
||||
}
|
||||
if cache.faces != n
|
||||
|| cache.generation != generation
|
||||
|| cache.map.len() >= RUN_FALLBACK_CACHE_MAX
|
||||
|| cache.chars.saturating_add(key.0.len()) > RUN_FALLBACK_CACHE_CHARS
|
||||
{
|
||||
cache.map.clear();
|
||||
cache.faces = n;
|
||||
cache.generation = generation;
|
||||
cache.chars = 0;
|
||||
}
|
||||
cache.chars = cache.chars.saturating_add(key.0.len());
|
||||
cache.map.insert(key, found.clone());
|
||||
found
|
||||
}
|
||||
|
||||
/// The face covering a diagram's missing character set, and the face count it was chosen from.
|
||||
/// Prefers faces matching `prefer_serif`; when the best loaded face has a mismatched serif
|
||||
/// classification, checks system font candidates and retains the loaded face only when no
|
||||
/// matching candidate covers the full set (#5672).
|
||||
fn search_diagram(&self, chars: &[char], exclude: u32, prefer_serif: bool) -> (Option<Arc<FontFace>>, usize) {
|
||||
#[cfg(test)]
|
||||
self.diagram_searches.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
#[cfg_attr(target_arch = "wasm32", allow(unused_mut))]
|
||||
let (mut base, mut checked) = self.loaded_diagram_covering(chars, exclude, prefer_serif);
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if base.is_none() || base.as_ref().is_some_and(|f| f.is_serif() != prefer_serif) {
|
||||
for c in chars {
|
||||
if self.read_faces().iter().any(|f| f.id != exclude && f.covers(*c) && f.is_serif() == prefer_serif) {
|
||||
continue;
|
||||
}
|
||||
if self.system_fallback_matching(*c, Some((exclude, prefer_serif))) {
|
||||
let (cand, cand_checked) = self.loaded_diagram_covering(chars, exclude, prefer_serif);
|
||||
let matching = cand.as_ref().is_some_and(|f| f.is_serif() == prefer_serif);
|
||||
if let Some(f) = cand {
|
||||
base = Some(f);
|
||||
checked = cand_checked;
|
||||
} else if base.is_none() {
|
||||
checked = cand_checked;
|
||||
}
|
||||
if matching {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if base.as_ref().is_none_or(|f| f.is_serif() != prefer_serif) {
|
||||
self.indexed_run_fallback_matching(chars, Some((exclude, prefer_serif)));
|
||||
let (cand, cand_checked) = self.loaded_diagram_covering(chars, exclude, prefer_serif);
|
||||
if let Some(f) = cand {
|
||||
base = Some(f);
|
||||
checked = cand_checked;
|
||||
} else if base.is_none() {
|
||||
checked = cand_checked;
|
||||
}
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
if let Some(hook) = self.diagram_search_hook.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take() {
|
||||
hook(self);
|
||||
}
|
||||
(base, checked)
|
||||
}
|
||||
|
||||
/// The first face covering every char in `chars`, preferring matching `prefer_serif`,
|
||||
/// and the number of loaded faces it was chosen from.
|
||||
fn loaded_diagram_covering(&self, chars: &[char], exclude: u32, prefer_serif: bool) -> (Option<Arc<FontFace>>, usize) {
|
||||
let faces = self.read_faces();
|
||||
let rtl = chars.iter().any(|c| crate::is_rtl(*c) || arabic_block(*c));
|
||||
let complex = chars.iter().copied().find(|c| crate::needs_layout_tables(*c));
|
||||
let mut candidates: Vec<&Arc<FontFace>> = faces.iter().filter(|f| f.id != exclude && chars.iter().all(|c| f.covers(*c))).collect();
|
||||
let rank = |f: &FontFace| {
|
||||
if rtl { RTL_FALLBACKS.iter().position(|n| f.family.eq_ignore_ascii_case(n)).unwrap_or(RTL_FALLBACKS.len()) } else { 0 }
|
||||
};
|
||||
let shaping = |f: &FontFace| match complex {
|
||||
Some(c) => (!f.has_layout_tables(), crate::fallback_rank(c, &f.family)),
|
||||
None => (false, 0),
|
||||
};
|
||||
let serif_mismatch = |f: &FontFace| f.is_serif() != prefer_serif;
|
||||
candidates.sort_by_cached_key(|f| {
|
||||
(rank(f), shaping(f), serif_mismatch(f), !f.family.eq_ignore_ascii_case(FALLBACK_FAMILY), f.italic, (f.weight - 400.0).abs() as i32)
|
||||
});
|
||||
(candidates.first().map(|f| (*f).clone()), faces.len())
|
||||
}
|
||||
|
||||
/// Load a system font covering `c` (preferred fallback families first, then any cataloged
|
||||
/// file under 40 MB, both found through the coverage index). Returns true if one was loaded.
|
||||
/// Misses are remembered.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn system_fallback(&self, c: char) -> bool {
|
||||
self.system_fallback_matching(c, None)
|
||||
}
|
||||
|
||||
/// Like [`Self::system_fallback`], optionally requiring the covering face to not be `exclude`
|
||||
/// and to match `prefer_serif` (so a loaded mismatched face does not short-circuit the search
|
||||
/// before a matching installed candidate is checked, #5672).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn system_fallback_matching(&self, c: char, style: Option<(u32, bool)>) -> bool {
|
||||
if c.is_control() || c.is_whitespace() {
|
||||
return false;
|
||||
}
|
||||
@@ -248,7 +403,9 @@ impl FontDb {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
let covered = |db: &FontDb| db.read_faces().iter().any(|f| f.covers(c));
|
||||
let covered = |db: &FontDb| {
|
||||
db.read_faces().iter().any(|f| f.covers(c) && style.is_none_or(|(exclude, prefer_serif)| f.id != exclude && f.is_serif() == prefer_serif))
|
||||
};
|
||||
let cataloged: Vec<String> = self.read_catalog().iter().map(|e| e.family.clone()).collect();
|
||||
let rtl = crate::is_rtl(c) || arabic_block(c);
|
||||
let preferred = RTL_FALLBACKS.iter().filter(|_| rtl);
|
||||
@@ -270,14 +427,20 @@ impl FontDb {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if self.indexed_fallback(c) {
|
||||
if style.is_none() {
|
||||
if self.indexed_fallback(c) {
|
||||
return true;
|
||||
}
|
||||
} else if self.load_indexed_matching(&[c], false, style) {
|
||||
return true;
|
||||
}
|
||||
let mut sys = self.sys.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if sys.misses.len() >= SYS_MISSES_MAX {
|
||||
sys.misses.clear();
|
||||
if style.is_none() || !self.read_faces().iter().any(|f| f.covers(c)) {
|
||||
let mut sys = self.sys.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if sys.misses.len() >= SYS_MISSES_MAX {
|
||||
sys.misses.clear();
|
||||
}
|
||||
sys.misses.insert(c);
|
||||
}
|
||||
sys.misses.insert(c);
|
||||
false
|
||||
}
|
||||
|
||||
@@ -324,7 +487,7 @@ impl FontDb {
|
||||
/// now covers `c`.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn indexed_fallback(&self, c: char) -> bool {
|
||||
self.load_indexed(&[c], false)
|
||||
self.load_indexed_matching(&[c], false, None)
|
||||
}
|
||||
|
||||
/// Load the family of the first cataloged font file (in path order) that maps every char of a
|
||||
@@ -332,10 +495,17 @@ impl FontDb {
|
||||
/// before the Regular.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn indexed_run_fallback(&self, chars: &[char]) {
|
||||
self.indexed_run_fallback_matching(chars, None);
|
||||
}
|
||||
|
||||
/// Like [`Self::indexed_run_fallback`], optionally requiring a loaded face matching
|
||||
/// `(exclude, prefer_serif)` to stop scanning (#5672).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn indexed_run_fallback_matching(&self, chars: &[char], style: Option<(u32, bool)>) {
|
||||
if !self.sys.lock().unwrap_or_else(std::sync::PoisonError::into_inner).enabled || chars.iter().any(|c| c.is_control()) {
|
||||
return;
|
||||
}
|
||||
self.load_indexed(chars, true);
|
||||
self.load_indexed_matching(chars, true, style);
|
||||
}
|
||||
|
||||
/// Load the cataloged font files (in path order) that map every char of `chars`, reading the
|
||||
@@ -344,8 +514,12 @@ impl FontDb {
|
||||
/// of it isn't loaded yet). A collection's faces only together may map them: the search then
|
||||
/// goes on. Returns whether a loaded face now covers them all.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn load_indexed(&self, chars: &[char], whole_family: bool) -> bool {
|
||||
let covered = |db: &FontDb| db.read_faces().iter().any(|f| chars.iter().all(|c| f.covers(*c)));
|
||||
fn load_indexed_matching(&self, chars: &[char], whole_family: bool, style: Option<(u32, bool)>) -> bool {
|
||||
let covered = |db: &FontDb| {
|
||||
db.read_faces().iter().any(|f| {
|
||||
style.is_none_or(|(exclude, prefer_serif)| f.id != exclude && f.is_serif() == prefer_serif) && chars.iter().all(|c| f.covers(*c))
|
||||
})
|
||||
};
|
||||
let cps: Vec<u32> = chars.iter().map(|c| u32::from(*c)).collect();
|
||||
let maps_all = |ranges: &[(u32, u32)]| cps.iter().all(|cp| ranges_hold(ranges, *cp));
|
||||
let mut index = self.coverage_index();
|
||||
|
||||
@@ -281,6 +281,7 @@ pub(super) fn arabic_block(c: char) -> bool {
|
||||
#[derive(Default)]
|
||||
pub(super) struct FallbackCache {
|
||||
pub(super) faces: usize,
|
||||
pub(super) generation: u64,
|
||||
pub(super) map: HashMap<(char, u32), Option<Arc<FontFace>>>,
|
||||
}
|
||||
|
||||
@@ -288,15 +289,31 @@ pub(super) struct FallbackCache {
|
||||
pub(super) type RunFallbackKey = (Vec<char>, u32, bool, bool);
|
||||
|
||||
/// [`FontDb::fallback_for_run`] results: (sorted, deduplicated chars, excluded face, bold,
|
||||
/// italic) → face, valid while the loaded face count is `faces`.
|
||||
/// italic) → face, valid while the loaded face count is `faces` and [`FontDb::generation`] is
|
||||
/// `generation`.
|
||||
#[derive(Default)]
|
||||
pub(super) struct RunFallbackCache {
|
||||
pub(super) faces: usize,
|
||||
pub(super) generation: u64,
|
||||
/// Chars held in the keys (bounds memory: hostile runs can be long).
|
||||
pub(super) chars: usize,
|
||||
pub(super) map: HashMap<RunFallbackKey, Option<Arc<FontFace>>>,
|
||||
}
|
||||
|
||||
/// What a diagram-level fallback lookup is keyed by: sorted, deduplicated chars, excluded face,
|
||||
/// serif preference.
|
||||
pub(super) type DiagramFallbackKey = (Vec<char>, u32, bool);
|
||||
|
||||
/// [`FontDb::fallback_for_diagram`] results, valid while the loaded face count and generation match.
|
||||
#[derive(Default)]
|
||||
pub(super) struct DiagramFallbackCache {
|
||||
pub(super) faces: usize,
|
||||
pub(super) generation: u64,
|
||||
/// Chars held in the keys (bounds memory: diagram text can be long).
|
||||
pub(super) chars: usize,
|
||||
pub(super) map: HashMap<DiagramFallbackKey, Option<Arc<FontFace>>>,
|
||||
}
|
||||
|
||||
/// Most cached run-level fallbacks, and most chars in their keys, before the cache is reset.
|
||||
pub(super) const RUN_FALLBACK_CACHE_MAX: usize = 4096;
|
||||
|
||||
|
||||
@@ -893,3 +893,202 @@ fn catalog_postscript_names() {
|
||||
assert!(!has(&db.families(), "SysfontSans-Bold"));
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
/// Diagram fallback matches the primary font's serif/sans classification while body-text
|
||||
/// fallback preserves loaded order (#5672), and changing user fonts invalidates run fallbacks.
|
||||
#[test]
|
||||
fn fallback_order_matches_primary_font_serif_nature() {
|
||||
// #5672: When picking fallback faces for diagrams, sans-serif primary fonts prefer sans-serif
|
||||
// fallback fonts, and serif primary fonts prefer serif fallback fonts. Body text fallback
|
||||
// order remains unaffected.
|
||||
use crate::fontdb::fallback_data::fallback_order;
|
||||
let dir = font_dir("serif-sans-fallback");
|
||||
std::fs::write(dir.join("TestMincho.ttf"), mapping("SourceSans3-Regular.ttf", "Test Mincho 1", 0xF_0010, 0xF_0011)).unwrap();
|
||||
std::fs::write(dir.join("TestGothic.ttf"), mapping("SourceSans3-Regular.ttf", "Test Gothic 1", 0xF_0010, 0xF_0011)).unwrap();
|
||||
let db = FontDb::with_font_dirs(vec![dir.clone()]);
|
||||
db.set_system_fallback(false);
|
||||
let mincho = db.face("Test Mincho 1", "Regular");
|
||||
let gothic = db.face("Test Gothic 1", "Regular");
|
||||
assert!(mincho.is_serif(), "Mincho is serif");
|
||||
assert!(!gothic.is_serif(), "Gothic is sans");
|
||||
|
||||
let sans_primary = db.face("Source Sans 3", "Regular");
|
||||
let serif_primary = db.face("Source Serif 4", "Regular");
|
||||
|
||||
// Diagram fallback: matches serif/sans nature of primary font.
|
||||
let diag_run = ['\u{F0010}', '\u{F0011}'];
|
||||
let diag_sans = db.fallback_for_diagram(&diag_run, sans_primary.id(), sans_primary.is_serif()).unwrap();
|
||||
assert_eq!(diag_sans.family, "Test Gothic 1", "sans-serif diagram prefers sans-serif fallback (Gothic)");
|
||||
let diag_serif = db.fallback_for_diagram(&diag_run, serif_primary.id(), serif_primary.is_serif()).unwrap();
|
||||
assert_eq!(diag_serif.family, "Test Mincho 1", "serif diagram prefers serif fallback (Mincho)");
|
||||
|
||||
// Body text fallback: fallback_order is not altered by the primary font's serif/sans nature.
|
||||
let faces = db.read_faces();
|
||||
let for_sans = fallback_order(&faces, sans_primary.id(), false, None);
|
||||
let for_serif = fallback_order(&faces, serif_primary.id(), false, None);
|
||||
let mincho_sans = for_sans.iter().position(|f| f.family == "Test Mincho 1").unwrap();
|
||||
let gothic_sans = for_sans.iter().position(|f| f.family == "Test Gothic 1").unwrap();
|
||||
let mincho_serif = for_serif.iter().position(|f| f.family == "Test Mincho 1").unwrap();
|
||||
let gothic_serif = for_serif.iter().position(|f| f.family == "Test Gothic 1").unwrap();
|
||||
assert_eq!(mincho_sans < gothic_sans, mincho_serif < gothic_serif, "body text fallback order does not invert between sans and serif primaries");
|
||||
drop(faces);
|
||||
|
||||
// Replacing a user font with another of the same face count invalidates both fallbacks and run_fallbacks.
|
||||
db.install_font("UserGothic.ttf", &mapping("SourceSans3-Regular.ttf", "User1 Gothic1", 0xF_0001, 0xF_0002)).unwrap();
|
||||
let run = ['\u{F0001}', '\u{F0002}'];
|
||||
let first_char = db.fallback_for('\u{F0001}', serif_primary.id()).unwrap();
|
||||
assert_eq!(first_char.family, "User1 Gothic1");
|
||||
assert_eq!(db.fallbacks.read().unwrap().generation, db.generation());
|
||||
let first = db.fallback_for_run(&run, serif_primary.id(), false, false).unwrap();
|
||||
assert_eq!(first.family, "User1 Gothic1");
|
||||
let face_count = db.read_faces().len();
|
||||
db.remove_user_font("User1 Gothic1").unwrap();
|
||||
db.install_font("UserMincho.ttf", &mapping("SourceSans3-Regular.ttf", "User2 Mincho2", 0xF_0001, 0xF_0002)).unwrap();
|
||||
assert_eq!(db.read_faces().len(), face_count);
|
||||
let updated_char = db.fallback_for('\u{F0001}', serif_primary.id()).unwrap();
|
||||
assert_eq!(updated_char.family, "User2 Mincho2");
|
||||
assert_eq!(db.fallbacks.read().unwrap().generation, db.generation());
|
||||
let updated = db.fallback_for_run(&run, serif_primary.id(), false, false).unwrap();
|
||||
assert_eq!(updated.family, "User2 Mincho2");
|
||||
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn diagram_fallback_checks_system_fonts_when_loaded_face_mismatches_serif() {
|
||||
let dir = font_dir("diag-mismatch");
|
||||
let regular = "SourceSans3-Regular.ttf";
|
||||
// Put a preferred non-covering family ("Malgun Gothic") and an alphabetically earlier serif
|
||||
// font ("AA Sys Mincho") in the directory alongside the matching sans CJK candidate
|
||||
// ("Sys Gothic 11"). Neither the non-covering preferred family nor the earlier serif font may
|
||||
// short-circuit the search just because a mismatched loaded face already covers the chars.
|
||||
std::fs::write(dir.join("00_MalgunGothic.ttf"), mapping(regular, "Malgun Gothic", 0x0041, 0x005A)).unwrap();
|
||||
std::fs::write(dir.join("AA_SysMincho.ttf"), mapping(regular, "AA Sys Mincho", 0xF_0020, 0xF_0021)).unwrap();
|
||||
std::fs::write(dir.join("SysGothic.ttf"), mapping(regular, "Sys Gothic 11", 0xF_0020, 0xF_0021)).unwrap();
|
||||
let db = FontDb::with_font_dirs(vec![dir.clone()]);
|
||||
// Pre-load a serif font covering the same characters into db as a document font.
|
||||
db.add_document_fonts(vec![(mapping(regular, "Load Mincho 1", 0xF_0020, 0xF_0021), "Load Mincho 1".to_string())]);
|
||||
let mincho = db.face("Load Mincho 1", "Regular");
|
||||
assert!(mincho.is_serif());
|
||||
|
||||
// 1. Single-character sans-serif diagram: loaded face is serif (mismatched), so search_diagram
|
||||
// must check past Malgun Gothic (non-covering preferred family) and AA Sys Mincho (earlier
|
||||
// serif cataloged file) to find & load "Sys Gothic 11" (sans-serif).
|
||||
let single = ['\u{F0020}'];
|
||||
let sans = db.fallback_for_diagram(&single, 0, false).unwrap();
|
||||
assert_eq!(sans.family, "Sys Gothic 11", "sans diagram checks system fonts to find matching sans candidate");
|
||||
assert!(!sans.is_serif());
|
||||
|
||||
// 2. Multi-character run also resolves to the matching sans candidate.
|
||||
let run = ['\u{F0020}', '\u{F0021}'];
|
||||
let sans_run = db.fallback_for_diagram(&run, 0, false).unwrap();
|
||||
assert_eq!(sans_run.family, "Sys Gothic 11");
|
||||
|
||||
// 3. When no matching candidate covers the run, retain the mismatched loaded face.
|
||||
let uncataloged_run = ['\u{F0020}'];
|
||||
let retained = db.fallback_for_diagram(&uncataloged_run, sans.id(), false).unwrap();
|
||||
assert_eq!(retained.family, "Load Mincho 1", "retains loaded face when no matching candidate covers the run");
|
||||
|
||||
db.remove_document_fonts(&["Load Mincho 1"]);
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn diagram_fallback_caches_a_mismatched_loaded_face_after_system_search() {
|
||||
let dir = font_dir("diag-fallback-cache");
|
||||
let regular = "SourceSans3-Regular.ttf";
|
||||
std::fs::write(dir.join("CacheGothic.ttf"), mapping(regular, "Cache Gothic1", 0xF_0030, 0xF_0031)).unwrap();
|
||||
let db = FontDb::with_font_dirs(vec![dir.clone()]);
|
||||
db.add_document_fonts(vec![(mapping(regular, "Loaded Gothic", 0xF_0030, 0xF_0031), "Loaded Gothic".to_string())]);
|
||||
let primary = db.face("Source Serif 4", "Regular");
|
||||
let run = ['\u{F0030}', '\u{F0031}'];
|
||||
|
||||
let first = db.fallback_for_diagram(&run, primary.id(), true).unwrap();
|
||||
assert_eq!(first.family, "Loaded Gothic", "retain the loaded mismatched face when no serif face covers the run");
|
||||
let reads = db.coverage.lock().unwrap().reads;
|
||||
assert!(reads > 0, "the initial search reaches the system-font coverage index");
|
||||
assert_eq!(db.diagram_searches.load(std::sync::atomic::Ordering::Relaxed), 1);
|
||||
|
||||
assert_eq!(db.fallback_for_diagram(&run, primary.id(), true).unwrap().id(), first.id());
|
||||
assert_eq!(db.diagram_searches.load(std::sync::atomic::Ordering::Relaxed), 1, "the redraw reuses the diagram fallback");
|
||||
assert_eq!(db.coverage.lock().unwrap().reads, reads);
|
||||
|
||||
db.install_font("UserMincho.ttf", &mapping(regular, "User Mincho 1", 0xF_0030, 0xF_0031)).unwrap();
|
||||
assert_eq!(db.fallback_for_diagram(&run, primary.id(), true).unwrap().family, "User Mincho 1");
|
||||
assert_eq!(db.diagram_searches.load(std::sync::atomic::Ordering::Relaxed), 2, "adding a user font invalidates the cached result");
|
||||
|
||||
let face_count = db.read_faces().len();
|
||||
db.remove_user_font("User Mincho 1").unwrap();
|
||||
db.install_font("UserMincho.ttf", &mapping(regular, "User Mincho 2", 0xF_0030, 0xF_0031)).unwrap();
|
||||
assert_eq!(db.read_faces().len(), face_count);
|
||||
assert_eq!(db.fallback_for_diagram(&run, primary.id(), true).unwrap().family, "User Mincho 2");
|
||||
assert_eq!(db.diagram_searches.load(std::sync::atomic::Ordering::Relaxed), 3, "generation invalidates the cache when face count stays unchanged");
|
||||
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn diagram_fallback_skips_stale_cache_publish_when_add_font_arrives_between_selection_and_publication() {
|
||||
let dir = font_dir("diag-concurrent-add-font");
|
||||
let regular = "SourceSans3-Regular.ttf";
|
||||
let italic = "SourceSans3-It.ttf";
|
||||
let db = FontDb::with_font_dirs(vec![dir.clone()]);
|
||||
let primary = db.face("Source Sans 3", "Regular");
|
||||
assert!(!primary.is_serif());
|
||||
|
||||
// 1. A matching sans face arrives via `add_font` (no generation bump) after `search_diagram`
|
||||
// selects the loaded mismatched serif face and before `search_diagram` returns its count.
|
||||
assert!(db.add_font(mapping(regular, "Load Mincho A", 0xF_0040, 0xF_0041)) > 0);
|
||||
let arriving_a = mapping(regular, "New Gothic AA", 0xF_0040, 0xF_0041);
|
||||
*db.diagram_search_hook.lock().unwrap() = Some(Box::new(move |db| {
|
||||
assert!(db.add_font(arriving_a) > 0);
|
||||
}));
|
||||
let gen_before = db.generation();
|
||||
let run_a = ['\u{F0040}', '\u{F0041}'];
|
||||
let first_a = db.fallback_for_diagram(&run_a, primary.id(), false).unwrap();
|
||||
assert_eq!(first_a.family, "Load Mincho A");
|
||||
assert_eq!(db.generation(), gen_before, "add_font does not change generation");
|
||||
assert_ne!(
|
||||
db.diagram_fallbacks.read().unwrap().faces,
|
||||
db.read_faces().len(),
|
||||
"stale selection from before add_font must not be cached under the newer face count"
|
||||
);
|
||||
let second_a = db.fallback_for_diagram(&run_a, primary.id(), false).unwrap();
|
||||
assert_eq!(second_a.family, "New Gothic AA", "subsequent lookup sees the newly added matching face");
|
||||
assert_eq!(db.diagram_fallbacks.read().unwrap().faces, db.read_faces().len());
|
||||
let searches_after_a = db.diagram_searches.load(std::sync::atomic::Ordering::Relaxed);
|
||||
assert_eq!(db.fallback_for_diagram(&run_a, primary.id(), false).unwrap().id(), second_a.id());
|
||||
assert_eq!(db.diagram_searches.load(std::sync::atomic::Ordering::Relaxed), searches_after_a);
|
||||
|
||||
// 2. Fast-path match (no system search): an upright sans face arrives via `add_font` after
|
||||
// `loaded_diagram_covering` picks an italic sans face and before `search_diagram` returns.
|
||||
assert!(db.add_font(mapping(italic, "Load Gothic C", 0xF_0060, 0xF_0061)) > 0);
|
||||
let arriving_c = mapping(regular, "New Gothic CC", 0xF_0060, 0xF_0061);
|
||||
*db.diagram_search_hook.lock().unwrap() = Some(Box::new(move |db| {
|
||||
assert!(db.add_font(arriving_c) > 0);
|
||||
}));
|
||||
let run_c = ['\u{F0060}', '\u{F0061}'];
|
||||
let first_c = db.fallback_for_diagram(&run_c, primary.id(), false).unwrap();
|
||||
assert_eq!(first_c.family, "Load Gothic C");
|
||||
assert_eq!(db.generation(), gen_before);
|
||||
assert_ne!(db.diagram_fallbacks.read().unwrap().faces, db.read_faces().len());
|
||||
let second_c = db.fallback_for_diagram(&run_c, primary.id(), false).unwrap();
|
||||
assert_eq!(second_c.family, "New Gothic CC", "fast-path selection also avoids caching under a newer face count");
|
||||
|
||||
// 3. A matching sans face arrives via `add_font` after `search_diagram` returns and before
|
||||
// `diagram_fallbacks.write()` publishes the entry.
|
||||
assert!(db.add_font(mapping(regular, "Load Mincho B", 0xF_0050, 0xF_0051)) > 0);
|
||||
let arriving_b = mapping(regular, "New Gothic BB", 0xF_0050, 0xF_0051);
|
||||
*db.diagram_publish_hook.lock().unwrap() = Some(Box::new(move |db| {
|
||||
assert!(db.add_font(arriving_b) > 0);
|
||||
}));
|
||||
let run_b = ['\u{F0050}', '\u{F0051}'];
|
||||
let first_b = db.fallback_for_diagram(&run_b, primary.id(), false).unwrap();
|
||||
assert_eq!(first_b.family, "Load Mincho B");
|
||||
assert_eq!(db.generation(), gen_before);
|
||||
assert_ne!(db.diagram_fallbacks.read().unwrap().faces, db.read_faces().len());
|
||||
let second_b = db.fallback_for_diagram(&run_b, primary.id(), false).unwrap();
|
||||
assert_eq!(second_b.family, "New Gothic BB");
|
||||
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
@@ -481,6 +481,21 @@ impl FontDb {
|
||||
added
|
||||
}
|
||||
|
||||
/// Remove document fonts added for `families`: their faces leave the font list
|
||||
/// and cached fallback choices are forgotten ([`FontDb::generation`]).
|
||||
#[cfg(any(test, feature = "test-support"))]
|
||||
pub fn remove_document_fonts(&self, families: &[&str]) {
|
||||
let ids: Vec<u32> = {
|
||||
let faces = self.read_faces();
|
||||
faces.iter().filter(|f| families.iter().any(|name| f.named(name))).map(|f| f.id).collect()
|
||||
};
|
||||
if ids.is_empty() {
|
||||
return;
|
||||
}
|
||||
self.faces.write().unwrap_or_else(|e| e.into_inner()).retain(|f| !ids.contains(&f.id));
|
||||
self.fonts_changed();
|
||||
}
|
||||
|
||||
/// Check the faces in `sfnt` and add the new ones, recording them as a user font.
|
||||
fn add_user_faces(&self, name: &str, sfnt: Vec<u8>, path: Option<PathBuf>) -> Result<UserFont, UserFontError> {
|
||||
if self.read_user().fonts.len() >= MAX_USER_FONTS {
|
||||
@@ -543,8 +558,10 @@ impl FontDb {
|
||||
|
||||
/// Forget cached fallback choices and tell watchers ([`FontDb::generation`]).
|
||||
fn fonts_changed(&self) {
|
||||
self.fallbacks.write().unwrap_or_else(|e| e.into_inner()).map.clear();
|
||||
self.generation.fetch_add(1, Ordering::AcqRel);
|
||||
*self.fallbacks.write().unwrap_or_else(|e| e.into_inner()) = super::FallbackCache::default();
|
||||
*self.run_fallbacks.write().unwrap_or_else(|e| e.into_inner()) = super::RunFallbackCache::default();
|
||||
*self.diagram_fallbacks.write().unwrap_or_else(std::sync::PoisonError::into_inner) = super::DiagramFallbackCache::default();
|
||||
}
|
||||
|
||||
/// Remove the user fonts that added `family` (a typographic or legacy family name): their
|
||||
|
||||
@@ -1207,3 +1207,54 @@ fn latex_export_keeps_repeated_spaces() {
|
||||
let d = crate::import("tex", tex.as_bytes()).unwrap().unwrap();
|
||||
assert_eq!(para_texts(&d), vec!["a b c".to_string()]);
|
||||
}
|
||||
|
||||
/// Container `background-color` imports and round-trips as paragraph shading (including mixed
|
||||
/// inline highlights and blank lines), while inline `<span style="background-color:...">` and
|
||||
/// `<mark>` highlights remain character shading (#6157).
|
||||
#[test]
|
||||
fn html_container_shading_is_paragraph_shading_while_inline_highlight_stays_on_runs() {
|
||||
let html = concat!(
|
||||
r#"<div style="background-color:#1e1e1e"><p><span style="color:#569cd6">const</span> x = 1;</p></div>"#,
|
||||
r#"<p><span style="background-color:#ffff00">highlighted</span></p>"#,
|
||||
r#"<p><mark>marked</mark></p>"#,
|
||||
r#"<div style="background-color:#1e1e1e"><p>text <code style="background-color:#eeeeee">x</code></p></div>"#,
|
||||
r#"<div style="background-color:#1e1e1e"><div>a</div><div> </div><div>b</div></div>"#,
|
||||
);
|
||||
let doc = crate::html::import(html);
|
||||
assert_eq!(doc.body.len(), 7);
|
||||
|
||||
let Block::Para(code) = &*doc.body[0] else { panic!("expected code paragraph") };
|
||||
assert_eq!(code.props.shading, Some(wordcraft_doc::Rgb(0x1e, 0x1e, 0x1e)));
|
||||
assert!(code.runs.iter().all(|r| r.props.shading.is_none()), "container background must not leak to runs");
|
||||
|
||||
let Block::Para(span_hl) = &*doc.body[1] else { panic!("expected highlighted paragraph") };
|
||||
assert_eq!(span_hl.props.shading, None, "inline span highlight must not become paragraph shading");
|
||||
assert_eq!(span_hl.runs.first().and_then(|r| r.props.shading), Some(wordcraft_doc::Rgb(0xff, 0xff, 0x00)));
|
||||
|
||||
let Block::Para(mark_hl) = &*doc.body[2] else { panic!("expected mark paragraph") };
|
||||
assert_eq!(mark_hl.props.shading, None, "inline <mark> must not become paragraph shading");
|
||||
assert_eq!(mark_hl.runs.first().and_then(|r| r.props.shading), Some(wordcraft_doc::Rgb(0xff, 0xff, 0x00)));
|
||||
|
||||
let Block::Para(mixed) = &*doc.body[3] else { panic!("expected mixed paragraph") };
|
||||
assert_eq!(mixed.props.shading, Some(wordcraft_doc::Rgb(0x1e, 0x1e, 0x1e)));
|
||||
assert_eq!(mixed.props_of_char(0).shading, None, "unhighlighted text in shaded container has no run shading");
|
||||
assert_eq!(mixed.props_of_char(5).shading, Some(wordcraft_doc::Rgb(0xee, 0xee, 0xee)), "inline <code> keeps its own run shading");
|
||||
|
||||
for idx in [4, 5, 6] {
|
||||
let Block::Para(line) = &*doc.body[idx] else { panic!("expected block {idx}") };
|
||||
assert_eq!(line.props.shading, Some(wordcraft_doc::Rgb(0x1e, 0x1e, 0x1e)), "line {idx} (blank included) keeps container shading");
|
||||
}
|
||||
|
||||
for exported in [crate::html::export(&doc), crate::html::export_fragment(&doc)] {
|
||||
let back = crate::html::import(&exported);
|
||||
let Block::Para(p0) = &*back.body[0] else { panic!("expected paragraph 0") };
|
||||
let Block::Para(p1) = &*back.body[1] else { panic!("expected paragraph 1") };
|
||||
let Block::Para(p2) = &*back.body[2] else { panic!("expected paragraph 2") };
|
||||
assert_eq!(p0.props.shading, Some(wordcraft_doc::Rgb(0x1e, 0x1e, 0x1e)), "{exported}");
|
||||
assert!(p0.runs.iter().all(|r| r.props.shading.is_none()), "{exported}");
|
||||
assert_eq!(p1.props.shading, None, "{exported}");
|
||||
assert_eq!(p1.runs.first().and_then(|r| r.props.shading), Some(wordcraft_doc::Rgb(0xff, 0xff, 0x00)), "{exported}");
|
||||
assert_eq!(p2.props.shading, None, "<p><mark>x</mark></p> round-trips as run shading: {exported}");
|
||||
assert_eq!(p2.runs.first().and_then(|r| r.props.shading), Some(wordcraft_doc::Rgb(0xff, 0xff, 0x00)), "{exported}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
use super::ctx::{Ctx, page_anchored};
|
||||
use super::ctx::{Ctx, Joining, page_anchored};
|
||||
use super::floats::{
|
||||
ObjFrame, ObjectPlacement, WrapArea, align_in, float_rect, floating, left_out_objects, place_objects, rel_exclusions, wrap_area,
|
||||
};
|
||||
use super::flow::again;
|
||||
use super::page::PageFrame;
|
||||
use super::placed::Placed;
|
||||
use super::table_flow::below;
|
||||
@@ -262,12 +263,19 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
|
||||
let frames = !matches!(story, StoryRef::Part(id) if ctx.doc.parts.get(&id).is_some_and(|p| p.kind == wordcraft_doc::PartKind::TextBox));
|
||||
// The bottom of the last paragraph's lines.
|
||||
let mut prev_end = 0.0f32;
|
||||
// Where the last paragraph, whose mark is hidden, ended: the next one goes on from there.
|
||||
let mut joint: Option<Joint> = None;
|
||||
let outer_joined = ctx.joined;
|
||||
for (i, b) in blocks.iter().enumerate() {
|
||||
last_top = y;
|
||||
let mut path = prefix.to_vec();
|
||||
path.push(i as u32);
|
||||
match &**b {
|
||||
Block::Para(p) => {
|
||||
// A paragraph after one whose mark is hidden goes on from that one's last line
|
||||
// (Word, #3986; see `Joint`); one that shows nothing passes the place on.
|
||||
let (mark_hidden, shows_nothing, taken) = Joint::arrive(ctx, &mut joint, (i, p), (width, frames), table);
|
||||
let p = taken.as_ref().map_or(p, |t| &t.para);
|
||||
let label = ctx.next_label(p);
|
||||
let listed = label.is_some();
|
||||
let mut pl = ctx.para_labelled(p, width, table, &[], label.clone());
|
||||
@@ -306,8 +314,10 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
|
||||
});
|
||||
// Paragraph-relative floats start above the effective space before, as in the
|
||||
// body path. Keep text and wrap exclusions relative to the text's actual top.
|
||||
let para_top = y;
|
||||
// A paragraph going on from a shared line has its origin at that line's top.
|
||||
let para_top = taken.as_ref().map_or(y, |t| t.joint.top);
|
||||
y += if i == 0 { before } else { before.max(0.0) };
|
||||
TakenUp::start(taken.as_ref(), &mut y, &mut excl);
|
||||
// Floating objects anchored here: place them, then wrap the text around them.
|
||||
// One left out of the layout (hidden, or deleted in the final text) takes no room.
|
||||
let mut floats = HashMap::new();
|
||||
@@ -354,10 +364,11 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
|
||||
if !rel.is_empty() {
|
||||
pl = ctx.para_labelled(p, width, table, &rel, label);
|
||||
}
|
||||
TakenUp::clear(taken.as_ref(), &mut excl);
|
||||
// Bordered paragraphs: room for their borders, those of a group joined in one box.
|
||||
let cell = table.map(|t| &t.para);
|
||||
let (above, below) = (joined(ctx.doc, blocks, i, i.checked_sub(1), cell), joined(ctx.doc, blocks, i, Some(i + 1), cell));
|
||||
let mut edges = Edges::own(&pl, 0, pl.lines.len());
|
||||
let mut edges = Edges::own(&pl, 0, pl.lines.len()).sharing(&pl);
|
||||
if above {
|
||||
edges.top = 0.0;
|
||||
}
|
||||
@@ -370,6 +381,7 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
|
||||
edges.up = (y + lead - prev_end).max(0.0);
|
||||
}
|
||||
prev_end = push_para(&mut items, (story, &path), &pl, (0, pl.lines.len()), (0.0, y + lead), width, edges);
|
||||
joint = Joint::after(&pl, (0, pl.lines.len()), i, (0.0, y + lead), edges.bottom).filter(|_| mark_hidden && !shows_nothing).or(joint);
|
||||
// Pictures, shapes and text boxes: drawn, their areas and text boxes' text.
|
||||
if !p.objects.is_empty() {
|
||||
let at = ObjFrame {
|
||||
@@ -412,7 +424,9 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
|
||||
let last = i + 1 == blocks.len();
|
||||
let normal = || pl.rp.style == "Normal" || ctx.doc.styles.get(&pl.rp.style).is_none();
|
||||
let after = if last && (pl.rp.after_auto || (in_cell && ctxl && normal())) { 0.0 } else { pl.rp.space_after };
|
||||
y += edges.top + pl.height + edges.bottom + after;
|
||||
y += edges.top + pl.height + edges.bottom;
|
||||
// One going on from the line of the paragraph before ends below that line (#3986).
|
||||
y = TakenUp::end(taken.as_ref(), ctx, (y, after), outer_joined);
|
||||
prev_after = after;
|
||||
prev_after_auto = pl.rp.after_auto;
|
||||
prev_listed = listed;
|
||||
@@ -445,6 +459,7 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
|
||||
y = y.max(legacy_header_reach(y, &legacy_reach));
|
||||
let floats_bottom = float_tables.iter().map(|r| r.bottom()).fold(float_objects_bottom, f32::max);
|
||||
ctx.hide_deleted = outer_hide;
|
||||
ctx.joined = outer_joined;
|
||||
BoxLayout { items, height: y.max(0.0), floats_bottom, last_top: last_top.max(0.0), table_areas, page_table_wraps }
|
||||
}
|
||||
|
||||
@@ -700,6 +715,162 @@ impl Edges {
|
||||
joined: [false; 2],
|
||||
}
|
||||
}
|
||||
|
||||
/// A paragraph going on from the line of the one before, whose mark is hidden (#3986), takes
|
||||
/// no room for its borders on that line, nor below it when that line is all it has: the
|
||||
/// shared line shows the first paragraph's shading and borders (Word).
|
||||
pub(crate) fn sharing(mut self, pl: &ParaLayout) -> Edges {
|
||||
if pl.shares_line() {
|
||||
self.top = 0.0;
|
||||
if pl.lines.len() <= 1 {
|
||||
self.bottom = 0.0;
|
||||
}
|
||||
}
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a paragraph whose mark is hidden ends (#3986). Word shows it on one line with the next
|
||||
/// paragraph: that one's text goes on from where this one's ends, beside it on its last line.
|
||||
/// Paragraphs that show nothing (an empty one with a hidden mark, say) pass the place on.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) struct Joint {
|
||||
/// The block that goes on from here.
|
||||
pub(crate) next: usize,
|
||||
/// The page (the count of pages) and column of the last line (body text only).
|
||||
pub(crate) page: usize,
|
||||
pub(crate) col: usize,
|
||||
/// The last line's top, height and baseline (from its top), the left edge of its column and
|
||||
/// the x its text ends at.
|
||||
pub(crate) top: f32,
|
||||
pub(crate) height: f32,
|
||||
baseline: f32,
|
||||
left: f32,
|
||||
end: f32,
|
||||
/// The room under the line for the paragraph's bottom border: what follows the shared line
|
||||
/// starts below it.
|
||||
room: f32,
|
||||
}
|
||||
|
||||
impl Joint {
|
||||
/// After lines `l0..l1` of paragraph layout `pl`, block `block`, the first of them at `y` in
|
||||
/// a column whose left edge is at `x`, with `room` under them for its bottom border.
|
||||
pub(crate) fn after(pl: &ParaLayout, (l0, l1): (usize, usize), block: usize, (x, y): (f32, f32), room: f32) -> Option<Joint> {
|
||||
let li = l1.checked_sub(1)?;
|
||||
let (first, last) = (pl.lines.get(l0)?, pl.lines.get(li)?);
|
||||
// Right-to-left text runs the other way: its lines aren't joined.
|
||||
if pl.rp.bidi || !last.vis.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let end = pl.x_of(li, pl.text_len)?;
|
||||
let (top, height, baseline) = (y + last.top - first.top, last.height, last.baseline - last.top);
|
||||
Some(Joint { next: block + 1, page: 0, col: 0, top, height, baseline, left: x, end: x + end, room })
|
||||
}
|
||||
|
||||
/// Paragraph `p`, block `i`, arriving at `joint`: whether its mark is hidden, whether it shows
|
||||
/// nothing, and how it goes on from the place the one before left (if that one's mark was hidden).
|
||||
fn arrive(
|
||||
ctx: &mut Ctx,
|
||||
joint: &mut Option<Joint>,
|
||||
(i, p): (usize, &Paragraph),
|
||||
(width, frames): (f32, bool),
|
||||
table: Option<¶::CellText>,
|
||||
) -> (bool, bool, Option<TakenUp>) {
|
||||
let chr = table.map(|t| &t.chr);
|
||||
let mark_hidden = ctx.mark_hidden(p, chr);
|
||||
let shows_nothing = mark_hidden && ctx.text_hidden(p, chr);
|
||||
let came = joint.take().filter(|j| j.next == i);
|
||||
*joint = came.filter(|_| shows_nothing).map(|j| Joint { next: i + 1, ..j });
|
||||
let taken = came.filter(|_| !shows_nothing).and_then(|j| j.take_up(ctx, p, (width, frames), table));
|
||||
(mark_hidden, shows_nothing, taken)
|
||||
}
|
||||
|
||||
/// The bottom of the shared line, with the room for the first paragraph's bottom border.
|
||||
pub(crate) fn bottom(&self) -> f32 {
|
||||
self.top + self.height + self.room
|
||||
}
|
||||
|
||||
/// How the next paragraph `q`, laid out `width` wide, goes on from here: how far below the
|
||||
/// shared line's top it starts (its first line's text sits on this paragraph's baseline, not
|
||||
/// above it), and the areas it keeps clear of: its first line, this paragraph's text, down to
|
||||
/// the bottom of that line only; its later lines, the rest of the shared line (a heading's,
|
||||
/// taller than the text going on from it), with the room for its bottom border (Word).
|
||||
pub(crate) fn fit(&self, ctx: &mut Ctx, q: &Paragraph, width: f32, table: Option<¶::CellText>) -> (f32, Vec<WrapArea>) {
|
||||
let eq = ctx.eq_count;
|
||||
let probe = again(ctx, eq, |ctx| ctx.para_labelled(q, width, table, &[], None));
|
||||
let (gap, height) = probe.lines.first().map_or((0.0, self.height), |l| ((self.baseline - (l.baseline - l.top)).max(0.0), l.height));
|
||||
let rect = Rect::new(self.left, self.top, (self.end - self.left).max(0.0), (gap + height - 0.01).max(0.01));
|
||||
let mut areas = vec![(rect, false, None, WrapText::Right, false)];
|
||||
// Just below the first row as the line breaker tests it: the breaker tests every row at
|
||||
// its estimate (`row_est`), not at the line's height, so the first row never meets this
|
||||
// area and every later row, starting lower, does and moves below it. The probe's own first
|
||||
// line can be taller than the real one (a large word that wraps off the narrower shared
|
||||
// line), so its height can't be used here.
|
||||
let below = self.top + gap + probe.row_est + 0.01;
|
||||
if self.bottom() > below {
|
||||
areas.push((Rect::new(self.left, below, width.max(0.01), self.bottom() - below), true, None, WrapText::BothSides, false));
|
||||
}
|
||||
(gap, areas)
|
||||
}
|
||||
|
||||
/// The areas [`Joint::fit`] gave taken out of `excl` again, the paragraph laid out.
|
||||
pub(crate) fn unfit(areas: &[WrapArea], excl: &mut Vec<WrapArea>) {
|
||||
for area in areas {
|
||||
if let Some(k) = excl.iter().position(|a| a.0 == area.0 && a.1 == area.1 && a.2.is_none() && a.3 == area.3) {
|
||||
excl.remove(k);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Paragraph `p` of a box `width` wide going on from here, unless a page break comes before
|
||||
/// it, it runs right to left or it is a text frame (`frames`: placed apart, sharing no line):
|
||||
/// without its space before, as [`Joint::fit`] lays it out.
|
||||
fn take_up(self, ctx: &mut Ctx, p: &Paragraph, (width, frames): (f32, bool), table: Option<¶::CellText>) -> Option<TakenUp> {
|
||||
let own = ctx.doc.styles.resolve_para_in(&p.props, table.map(|t| &t.para));
|
||||
if own.page_break_before || own.bidi || (frames && own.frame.is_some()) {
|
||||
return None;
|
||||
}
|
||||
let mut para = p.clone();
|
||||
para.props.space_before = Some(0.0);
|
||||
para.props.space_before_auto = Some(false);
|
||||
ctx.joined = Some(Joining::new(para.rev, 0.0));
|
||||
let (gap, areas) = self.fit(ctx, ¶, width, table);
|
||||
Some(TakenUp { joint: self, para, gap, areas })
|
||||
}
|
||||
}
|
||||
|
||||
/// A paragraph of a box going on from a [`Joint`]: the paragraph without its space before, how
|
||||
/// far below the shared line's top it starts and the areas its lines keep clear of.
|
||||
struct TakenUp {
|
||||
joint: Joint,
|
||||
para: Paragraph,
|
||||
gap: f32,
|
||||
areas: Vec<WrapArea>,
|
||||
}
|
||||
|
||||
impl TakenUp {
|
||||
/// Where it starts: `y` below the shared line's top, its lines keeping clear of that line.
|
||||
fn start(taken: Option<&TakenUp>, y: &mut f32, excl: &mut Vec<WrapArea>) {
|
||||
let Some(t) = taken else { return };
|
||||
*y = t.joint.top + t.gap;
|
||||
excl.extend(t.areas.iter().cloned());
|
||||
}
|
||||
|
||||
/// Its lines laid out: the areas they kept clear of come out of `excl`.
|
||||
fn clear(taken: Option<&TakenUp>, excl: &mut Vec<WrapArea>) {
|
||||
if let Some(t) = taken {
|
||||
Joint::unfit(&t.areas, excl);
|
||||
}
|
||||
}
|
||||
|
||||
/// Where what follows a paragraph ending at `y`, with `after` its space after, starts: below
|
||||
/// the shared line at least, with the first paragraph's bottom border. With the copy laid
|
||||
/// out, the paragraph's own layouts are its own again (`outer`).
|
||||
fn end(taken: Option<&TakenUp>, ctx: &mut Ctx, (y, after): (f32, f32), outer: Option<Joining>) -> f32 {
|
||||
let Some(t) = taken else { return y + after };
|
||||
ctx.joined = outer;
|
||||
y.max(t.joint.bottom()) + after
|
||||
}
|
||||
}
|
||||
|
||||
/// Paragraph lines plus their shading and borders; returns the bottom of the lines. The
|
||||
@@ -717,12 +888,21 @@ pub(crate) fn push_para(
|
||||
return y;
|
||||
};
|
||||
let h = last.top + last.height - first.top;
|
||||
let lines = Placed::Lines { story, path: Path(path.to_vec()), para: pl.clone(), l0, l1, x, y, turn: TextDirection::Horizontal };
|
||||
// The line a paragraph shares with the one before, whose mark is hidden, shows that one's
|
||||
// shading and borders: this one's start on its own next line, without a top border (Word, #3986).
|
||||
let shared = l0 == 0 && pl.shares_line();
|
||||
let Some(own) = pl.lines.get(if shared { 1 } else { l0 }).filter(|_| !shared || l1 > 1) else {
|
||||
items.push(lines);
|
||||
return y + h;
|
||||
};
|
||||
let (y_own, e) = if shared { (y + own.top - first.top, Edges { top: 0.0, up: 0.0, ..e }) } else { (y, e) };
|
||||
// Indents are logical: a right-to-left paragraph's start indent (and hanging indent) is on the right.
|
||||
let start = pl.rp.indent_left.min(pl.rp.indent_left + pl.rp.indent_first);
|
||||
let (li, ri) = if pl.rp.bidi { (pl.rp.indent_right, start) } else { (start, pl.rp.indent_right) };
|
||||
let left = x + li;
|
||||
let right = x + width - ri;
|
||||
let (top, bottom) = (y - e.top - e.up, y + h + e.bottom);
|
||||
let (top, bottom) = (y_own - e.top - e.up, y + h + e.bottom);
|
||||
// The outer edges of the side borders.
|
||||
let sides = pl.rp.borders.unwrap_or_default();
|
||||
let (lx, rx) = (left - border_room(sides.left), right + border_room(sides.right));
|
||||
@@ -731,7 +911,7 @@ pub(crate) fn push_para(
|
||||
let (sl, sr) = (lx.min(left - pad), rx.max(right + pad));
|
||||
items.push(Placed::Fill { rect: Rect::new(sl, top, sr - sl, bottom - top), color: c });
|
||||
}
|
||||
items.push(Placed::Lines { story, path: Path(path.to_vec()), para: pl.clone(), l0, l1, x, y, turn: TextDirection::Horizontal });
|
||||
items.push(lines);
|
||||
if let Some(b) = &pl.rp.borders {
|
||||
// All four lines lie beyond their distance from the text (`lx`, `rx`: the side lines'
|
||||
// outer edges); `box_rules` runs the top and bottom over the side lines to those edges.
|
||||
@@ -739,9 +919,10 @@ pub(crate) fn push_para(
|
||||
let (cl, cr) = (lx + half(b.left), rx - half(b.right));
|
||||
let tb = b.top.filter(|t| e.top > 0.0 && t.is_visible());
|
||||
let bb = b.bottom.filter(|t| e.bottom > 0.0 && t.is_visible());
|
||||
let ty = tb.map_or(top, |t| y - t.space - t.width / 2.0);
|
||||
let ty = tb.map_or(top, |t| y_own - t.space - t.width / 2.0);
|
||||
let by = bb.map_or(bottom, |t| y + h + t.space + t.width / 2.0);
|
||||
box_rules(items, (cl, ty, cr, by), [tb, bb, b.left, b.right], e.joined);
|
||||
// Open at the top where it goes on over the shared line.
|
||||
box_rules(items, (cl, ty, cr, by), [tb, bb, b.left, b.right], [e.joined[0] || shared, e.joined[1]]);
|
||||
}
|
||||
y + h
|
||||
}
|
||||
|
||||
@@ -27,6 +27,9 @@ pub(crate) struct Key {
|
||||
pub(crate) sref: u64,
|
||||
/// The word being typed in this paragraph, left without a spelling squiggle.
|
||||
pub(crate) typing: Option<(usize, usize)>,
|
||||
/// A copy of the paragraph going on from the line of the one before (`ctx::Joining`): its
|
||||
/// space before and whether it shares that line ([`ParaEnv::joined`](crate::para::ParaEnv)).
|
||||
pub(crate) joined: Option<(u32, bool)>,
|
||||
}
|
||||
|
||||
/// Memoised paragraph layouts.
|
||||
|
||||
@@ -51,6 +51,9 @@ pub(crate) struct Ctx<'a> {
|
||||
/// Empty body paragraphs with hidden marks or continuous section breaks, in order:
|
||||
/// they take no room (see [`place_para`]).
|
||||
pub(crate) quiet_marks: Vec<usize>,
|
||||
/// The paragraph being laid out as going on from the line of the one before, whose mark is
|
||||
/// hidden: its list number is counted but not drawn (#3986).
|
||||
pub(crate) joined: Option<Joining>,
|
||||
/// Empty paragraphs closing a continuous section right after another section's mark, in
|
||||
/// order: each takes its line while it fits, then stays at the page's bottom (#3907).
|
||||
pub(crate) stacked_marks: Vec<usize>,
|
||||
@@ -79,6 +82,31 @@ pub(crate) struct Ctx<'a> {
|
||||
pub(crate) header_repeats: usize,
|
||||
}
|
||||
|
||||
/// A paragraph going on from the line of the one before, whose mark is hidden (#3986): a copy of
|
||||
/// the document's, which keeps its revision, given the space before that puts its text on that
|
||||
/// line's baseline.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) struct Joining {
|
||||
/// The paragraph's revision.
|
||||
pub(crate) rev: u64,
|
||||
/// The space before the copy is given.
|
||||
before: f32,
|
||||
/// Whether it still shares that line: not once its first line has moved on to the next
|
||||
/// column or page, where it is laid out as on its own (the copy's space before kept).
|
||||
pub(crate) shares: bool,
|
||||
}
|
||||
|
||||
impl Joining {
|
||||
pub(crate) fn new(rev: u64, before: f32) -> Self {
|
||||
Joining { rev, before, shares: true }
|
||||
}
|
||||
|
||||
/// What tells the copy's layouts apart from each other and from the paragraph's own.
|
||||
fn key(self) -> (u32, bool) {
|
||||
(self.before.to_bits(), self.shares)
|
||||
}
|
||||
}
|
||||
|
||||
struct ParaEnvInput<'a> {
|
||||
width: f32,
|
||||
label: Option<(String, Level)>,
|
||||
@@ -87,6 +115,7 @@ struct ParaEnvInput<'a> {
|
||||
eq_number: u32,
|
||||
typing_word: Option<(usize, usize)>,
|
||||
fitted: &'a [(usize, f32)],
|
||||
joined: bool,
|
||||
}
|
||||
|
||||
/// A header or footer (`story`) laid out for page `number` of a section (`sect`, `mirror`): its
|
||||
@@ -227,12 +256,31 @@ impl Ctx<'_> {
|
||||
grid: para::Grid::default(),
|
||||
fit_objects: false,
|
||||
fitted: &[],
|
||||
joined: false,
|
||||
};
|
||||
let pl = Arc::new(para::layout_para(&p, &env));
|
||||
self.numbers.insert(n, pl.clone());
|
||||
pl
|
||||
}
|
||||
|
||||
/// Whether `p` is laid out going on from the line of the paragraph before, sharing it (#3986).
|
||||
fn shares_line(&self, p: &Paragraph) -> bool {
|
||||
self.joined.is_some_and(|j| j.rev == p.rev && j.shares)
|
||||
}
|
||||
|
||||
/// Whether `p`'s paragraph mark is hidden, with hidden text not shown: Word then shows the
|
||||
/// paragraph on one line with the next one (#3986). A section's closing mark never joins.
|
||||
pub(crate) fn mark_hidden(&self, p: &Paragraph, table_chr: Option<&CharProps>) -> bool {
|
||||
!self.opts.show_hidden && p.section.is_none() && self.doc.styles.resolve_char_in(p.props.style.as_deref(), table_chr, &p.mark).hidden
|
||||
}
|
||||
|
||||
/// Whether `p` shows none of its text (it has none, or all of it is hidden and not shown).
|
||||
pub(crate) fn text_hidden(&self, p: &Paragraph, table_chr: Option<&CharProps>) -> bool {
|
||||
p.text.is_empty()
|
||||
|| (!self.opts.show_hidden
|
||||
&& p.runs.iter().all(|r| r.len == 0 || self.doc.styles.resolve_char_in(p.props.style.as_deref(), table_chr, &r.props).hidden))
|
||||
}
|
||||
|
||||
/// The list label of `p`, advancing the list counters: call it once per paragraph, in
|
||||
/// document order (only for paragraphs that will show).
|
||||
/// Whether `p` gets a list label ([`Ctx::next_label`] is `Some`), without counting it.
|
||||
@@ -269,7 +317,16 @@ impl Ctx<'_> {
|
||||
let typing = key.typing;
|
||||
let pl = Arc::new(para::layout_para(
|
||||
p,
|
||||
&self.para_env(ParaEnvInput { width, label, table, exclusions, eq_number, typing_word: typing, fitted: &fitted }),
|
||||
&self.para_env(ParaEnvInput {
|
||||
width,
|
||||
label,
|
||||
table,
|
||||
exclusions,
|
||||
eq_number,
|
||||
typing_word: typing,
|
||||
fitted: &fitted,
|
||||
joined: self.shares_line(p),
|
||||
}),
|
||||
));
|
||||
self.cache.paras.insert(key, pl.clone());
|
||||
pl
|
||||
@@ -302,7 +359,16 @@ impl Ctx<'_> {
|
||||
self.cache.misses += 1;
|
||||
let pl = Arc::new(para::layout_para(
|
||||
p,
|
||||
&self.para_env(ParaEnvInput { width, label, table: None, exclusions: &[], eq_number, typing_word: None, fitted: &[] }),
|
||||
&self.para_env(ParaEnvInput {
|
||||
width,
|
||||
label,
|
||||
table: None,
|
||||
exclusions: &[],
|
||||
eq_number,
|
||||
typing_word: None,
|
||||
fitted: &[],
|
||||
joined: self.shares_line(p),
|
||||
}),
|
||||
));
|
||||
self.cache.paras.insert(key, pl.clone());
|
||||
Some(pl)
|
||||
@@ -330,7 +396,16 @@ impl Ctx<'_> {
|
||||
let typing = key.typing;
|
||||
let m = measure(¶::layout_para(
|
||||
p,
|
||||
&self.para_env(ParaEnvInput { width, label, table, exclusions: &[], eq_number, typing_word: typing, fitted: &fitted }),
|
||||
&self.para_env(ParaEnvInput {
|
||||
width,
|
||||
label,
|
||||
table,
|
||||
exclusions: &[],
|
||||
eq_number,
|
||||
typing_word: typing,
|
||||
fitted: &fitted,
|
||||
joined: self.shares_line(p),
|
||||
}),
|
||||
));
|
||||
self.cache.measures.insert(key, m);
|
||||
m
|
||||
@@ -415,6 +490,7 @@ impl Ctx<'_> {
|
||||
hide_deleted: self.hide_deleted,
|
||||
sref: if self.fields.styleref.is_some() && styleref::has_styleref(p) { self.fields.styleref_key(p) } else { 0 },
|
||||
typing: self.opts.typing_word.filter(|t| t.rev == p.rev).map(|t| (t.start, t.end)),
|
||||
joined: self.joined.filter(|j| j.rev == p.rev).map(Joining::key),
|
||||
};
|
||||
(key, eq_number)
|
||||
}
|
||||
@@ -435,7 +511,7 @@ impl Ctx<'_> {
|
||||
}
|
||||
|
||||
fn para_env<'b>(&'b self, input: ParaEnvInput<'b>) -> para::ParaEnv<'b> {
|
||||
let ParaEnvInput { width, label, table, exclusions, eq_number, typing_word, fitted } = input;
|
||||
let ParaEnvInput { width, label, table, exclusions, eq_number, typing_word, fitted, joined } = input;
|
||||
para::ParaEnv {
|
||||
doc: self.doc,
|
||||
width,
|
||||
@@ -454,6 +530,7 @@ impl Ctx<'_> {
|
||||
grid: self.grid,
|
||||
fit_objects: self.boxes.inside(),
|
||||
fitted,
|
||||
joined,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -525,6 +602,7 @@ mod tests {
|
||||
track_totals: false,
|
||||
pct_base: None,
|
||||
quiet_marks: Vec::new(),
|
||||
joined: None,
|
||||
stacked_marks: Vec::new(),
|
||||
mirror: false,
|
||||
table_keys: Vec::new(),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::options::DisplayOptions;
|
||||
use super::paint::{Paint, paint_for};
|
||||
use super::{BezPath, Document, Draw, FaceRef, Graphic, GraphicItem, GraphicKind, InlineObject, PathSeg, Rect, Rgb, ShapeKind, Spin, TextAlign};
|
||||
use wordcraft_doc::connector::ArrowStyle;
|
||||
use wordcraft_doc::connector::{ArrowStyle, LineCap};
|
||||
|
||||
/// The draws of a chart or diagram's items inside `rect` (page coordinates). The items were built
|
||||
/// for the size `g.w` × `g.h` (0: `rect`'s own size), so they are scaled to `rect`; strokes and text
|
||||
@@ -10,8 +10,63 @@ pub(super) fn graphic_draws(doc: &Document, g: &Graphic, rect: Rect, alpha: f32)
|
||||
let (sx, sy) = (scale_of(rect.w, g.w), scale_of(rect.h, g.h));
|
||||
let k = (sx + sy) / 2.0;
|
||||
let inside = |r: &[f32; 4]| Rect::new(rect.x + r[0] * sx, rect.y + r[1] * sy, r[2] * sx, r[3] * sy);
|
||||
let mut out = Vec::with_capacity(g.items.len());
|
||||
let joins = |c: char| c.is_whitespace() || wordcraft_doc::math_linear::is_combining(c);
|
||||
let db = wordcraft_fonts::FontDb::global();
|
||||
|
||||
// A graphic (SmartArt diagram or chart) should maintain a consistent fallback font family
|
||||
// across all its text nodes (#5672). Collect all characters across the graphic that each
|
||||
// item's primary font lacks, and find one fallback face that covers them all (or, when
|
||||
// unrelated symbols need another face, one fallback face that covers all missing East Asian
|
||||
// characters). The serif/sans preference comes from the first text item with a missing
|
||||
// character (or the first with a missing East Asian character on the East Asian-only retry),
|
||||
// so mixed-style graphics follow that leading label's style across nodes.
|
||||
let mut text_resolved: Vec<Option<wordcraft_fonts::word::Resolved>> = Vec::with_capacity(g.items.len());
|
||||
let mut diagram_chars: Vec<char> = Vec::new();
|
||||
let mut cjk_chars: Vec<char> = Vec::new();
|
||||
let mut primary_face: Option<FaceRef> = None;
|
||||
let mut cjk_primary_face: Option<FaceRef> = None;
|
||||
for it in &g.items {
|
||||
if let GraphicItem::Text { text, font, bold, .. } = it {
|
||||
let family = font.as_deref().filter(|f| !f.is_empty()).unwrap_or(&doc.settings.minor_font);
|
||||
let resolved = wordcraft_fonts::word::resolve(family, *bold, false);
|
||||
let primary = resolved.face;
|
||||
for c in text.chars() {
|
||||
if !joins(c) && !primary.covers(c) {
|
||||
if primary_face.is_none() {
|
||||
primary_face = Some(primary);
|
||||
}
|
||||
diagram_chars.push(c);
|
||||
if crate::para::is_east_asian(c) {
|
||||
if cjk_primary_face.is_none() {
|
||||
cjk_primary_face = Some(primary);
|
||||
}
|
||||
cjk_chars.push(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
text_resolved.push(Some(resolved));
|
||||
} else {
|
||||
text_resolved.push(None);
|
||||
}
|
||||
}
|
||||
let diagram_fallback = if !diagram_chars.is_empty() {
|
||||
let prefer_serif = primary_face.is_some_and(|p| p.get().is_serif());
|
||||
let exclude = primary_face.map_or(0, |p| p.id());
|
||||
db.fallback_for_diagram(&diagram_chars, exclude, prefer_serif).or_else(|| {
|
||||
if !cjk_chars.is_empty() {
|
||||
let cjk_prefer_serif = cjk_primary_face.is_some_and(|p| p.get().is_serif());
|
||||
let cjk_exclude = cjk_primary_face.map_or(0, |p| p.id());
|
||||
db.fallback_for_diagram(&cjk_chars, cjk_exclude, cjk_prefer_serif)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let mut out = Vec::with_capacity(g.items.len());
|
||||
for (i, it) in g.items.iter().enumerate() {
|
||||
match it {
|
||||
GraphicItem::Shape { rect: r, kind, fill, stroke, stroke_width } => out.push(Draw::Shape {
|
||||
rect: inside(r),
|
||||
@@ -42,12 +97,16 @@ pub(super) fn graphic_draws(doc: &Document, g: &Graphic, rect: Rect, alpha: f32)
|
||||
let (cx, cy) = (at.x + at.w / 2.0, at.y + at.h / 2.0);
|
||||
let quarter = ((angle / 90.0).round() as i64).rem_euclid(2) == 1;
|
||||
let level = if quarter { Rect::new(cx - at.h / 2.0, cy - at.w / 2.0, at.h, at.w) } else { at };
|
||||
let items = text_glyphs(doc, level, it, alpha, k);
|
||||
let resolved = text_resolved.get(i).copied().flatten();
|
||||
let items = text_glyphs(doc, level, it, alpha, k, resolved, diagram_fallback.as_ref());
|
||||
if !items.is_empty() {
|
||||
out.push(Draw::Rotated { cx, cy, spin: Spin::new(*angle, false, false), items });
|
||||
}
|
||||
}
|
||||
GraphicItem::Text { rect: r, .. } => out.extend(text_glyphs(doc, inside(r), it, alpha, k)),
|
||||
GraphicItem::Text { rect: r, .. } => {
|
||||
let resolved = text_resolved.get(i).copied().flatten();
|
||||
out.extend(text_glyphs(doc, inside(r), it, alpha, k, resolved, diagram_fallback.as_ref()));
|
||||
}
|
||||
GraphicItem::Image { rect: r, media } => out.push(Draw::Image {
|
||||
rect: inside(r),
|
||||
media: media.clone(),
|
||||
@@ -235,9 +294,14 @@ fn line_draws(
|
||||
out: &mut Vec<Draw>,
|
||||
) {
|
||||
use wordcraft_doc::connector::{connector_segs, end_direction};
|
||||
let start_dir = end_direction(kind, rect.w, rect.h, false);
|
||||
let end_dir = end_direction(kind, rect.w, rect.h, true);
|
||||
// An arrowed end stops inside its head, which the stroke would otherwise stick out of.
|
||||
let inset = |on: bool, style| if on && stroke.is_some() { arrow_inset(stroke_width, style, extra.cap) } else { 0.0 };
|
||||
let ends = [(inset(extra.arrow_start, extra.start_style), start_dir), (inset(extra.arrow_end, extra.end_style), end_dir)];
|
||||
match connector_segs(kind, rect.w, rect.h) {
|
||||
Some(segs) => {
|
||||
let segs = segs
|
||||
let mut segs: Vec<PathSeg> = segs
|
||||
.into_iter()
|
||||
.map(|s| match s {
|
||||
PathSeg::Move(x, y) => PathSeg::Move(rect.x + x, rect.y + y),
|
||||
@@ -246,32 +310,92 @@ fn line_draws(
|
||||
PathSeg::Close => PathSeg::Close,
|
||||
})
|
||||
.collect();
|
||||
shorten_ends(&mut segs, ends);
|
||||
let width = path_stroke_width(stroke_width);
|
||||
out.push(Draw::Path { segs, fill: None, stroke, stroke_width: width, dash: extra.dash.pattern(width), cap: extra.cap });
|
||||
}
|
||||
None => out.push(Draw::Shape {
|
||||
rect,
|
||||
kind,
|
||||
fill: None,
|
||||
stroke,
|
||||
stroke_width,
|
||||
effects,
|
||||
corner: None,
|
||||
dash: extra.dash.pattern(stroke_width),
|
||||
cap: extra.cap,
|
||||
}),
|
||||
None => {
|
||||
// A line's frame is its diagonal, top left to bottom right: shortened, it stays one.
|
||||
let mut segs = [PathSeg::Move(rect.x, rect.y), PathSeg::Line(rect.right(), rect.bottom())];
|
||||
shorten_ends(&mut segs, ends);
|
||||
let line = match segs {
|
||||
[PathSeg::Move(x0, y0), PathSeg::Line(x1, y1)] => Rect::new(x0.min(x1), y0.min(y1), (x1 - x0).abs(), (y1 - y0).abs()),
|
||||
_ => rect,
|
||||
};
|
||||
out.push(Draw::Shape {
|
||||
rect: line,
|
||||
kind,
|
||||
fill: None,
|
||||
stroke,
|
||||
stroke_width,
|
||||
effects,
|
||||
corner: None,
|
||||
dash: extra.dash.pattern(stroke_width),
|
||||
cap: extra.cap,
|
||||
});
|
||||
}
|
||||
}
|
||||
let Some(color) = stroke else { return };
|
||||
// A line runs from the top-left corner to the bottom-right, as it is drawn (DrawingML's
|
||||
// `line`), and so do connectors; flips are the frame's turn.
|
||||
let (start, end) = ((rect.x, rect.y), (rect.right(), rect.bottom()));
|
||||
for (on, tip, at_end, style) in [(extra.arrow_start, start, false, extra.start_style), (extra.arrow_end, end, true, extra.end_style)] {
|
||||
for (on, tip, dir, style) in [(extra.arrow_start, start, start_dir, extra.start_style), (extra.arrow_end, end, end_dir, extra.end_style)] {
|
||||
if on {
|
||||
out.push(arrowhead(tip, end_direction(kind, rect.w, rect.h, at_end), stroke_width, style, color));
|
||||
out.push(arrowhead(tip, dir, stroke_width, style, color));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How far short of an arrowhead's tip a line `stroke_width` wide with `cap` ends stops, so that
|
||||
/// none of its stroke shows outside the head (#6767): where the head is as wide as the stroke,
|
||||
/// plus what the cap reaches past the end. A head is at least twice as wide as its line, so this
|
||||
/// is inside the head; never past its base.
|
||||
fn arrow_inset(stroke_width: f32, style: ArrowStyle, cap: LineCap) -> f32 {
|
||||
let width = path_stroke_width(stroke_width);
|
||||
let (len, wide) = style.dims(stroke_width);
|
||||
let reach = if cap == LineCap::Flat { 0.0 } else { width / 2.0 };
|
||||
(len * width / wide.max(f32::EPSILON) + reach).clamp(0.0, len)
|
||||
}
|
||||
|
||||
/// Draw the path `segs` (a line's or connector's, from its start to its end) short of its ends:
|
||||
/// each end by its distance, back against its unit direction (where its arrowhead points). An end
|
||||
/// moves at most half way to its neighbouring point, so the path keeps its shape, and a curve its
|
||||
/// direction at the end. The two ends of a single straight segment share its length in proportion
|
||||
/// to their distances instead, so an end without an arrowhead leaves its share to the other.
|
||||
fn shorten_ends(segs: &mut [PathSeg], [(start, start_dir), (end, end_dir)]: [(f32, (f32, f32)); 2]) {
|
||||
let distance = |by: f32| if by.is_finite() { by.max(0.0) } else { 0.0 };
|
||||
let (start, end) = (distance(start), distance(end));
|
||||
let share = |by: f32| match segs {
|
||||
[PathSeg::Move(..), PathSeg::Line(..)] => by / (start + end).max(f32::EPSILON),
|
||||
_ => 0.5,
|
||||
};
|
||||
let (start_share, end_share) = (share(start), share(end));
|
||||
let pull = |(x, y): (f32, f32), toward: Option<(f32, f32)>, by: f32, share: f32, (dx, dy): (f32, f32)| {
|
||||
let room = toward.map_or(0.0, |(tx, ty)| (tx - x).hypot(ty - y) * share);
|
||||
let by = if room.is_finite() { by.min(room) } else { 0.0 };
|
||||
(x - dx * by, y - dy * by)
|
||||
};
|
||||
// The points next to each end, before either moves.
|
||||
let after_first = match segs.get(1) {
|
||||
Some(PathSeg::Line(x, y) | PathSeg::Cubic(x, y, ..)) => Some((*x, *y)),
|
||||
_ => None,
|
||||
};
|
||||
let before_last = match segs.len().checked_sub(1).map(|i| segs.split_at(i)) {
|
||||
Some((_, [PathSeg::Cubic(_, _, x, y, ..)])) => Some((*x, *y)),
|
||||
Some((head, [PathSeg::Line(..)])) => match head.last() {
|
||||
Some(PathSeg::Move(x, y) | PathSeg::Line(x, y) | PathSeg::Cubic(.., x, y)) => Some((*x, *y)),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
};
|
||||
if let Some(PathSeg::Move(x, y)) = segs.first_mut() {
|
||||
(*x, *y) = pull((*x, *y), after_first, start, start_share, start_dir);
|
||||
}
|
||||
if let Some(PathSeg::Line(x, y) | PathSeg::Cubic(.., x, y)) = segs.last_mut() {
|
||||
(*x, *y) = pull((*x, *y), before_last, end, end_share, end_dir);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn seg_path(segs: &[PathSeg]) -> BezPath {
|
||||
let mut p = BezPath::new();
|
||||
for s in segs {
|
||||
@@ -291,18 +415,28 @@ pub fn seg_path(segs: &[PathSeg]) -> BezPath {
|
||||
/// in body text: one draw per run of a face, in reading order. Empty when there is nothing to draw,
|
||||
/// or the item's rectangle or size isn't a finite number (a degenerate scale: `r` itself is always
|
||||
/// finite, as [`Rect::new`] makes it).
|
||||
fn text_glyphs(doc: &Document, r: Rect, it: &GraphicItem, alpha: f32, k: f32) -> Vec<Draw> {
|
||||
fn text_glyphs(
|
||||
doc: &Document,
|
||||
r: Rect,
|
||||
it: &GraphicItem,
|
||||
alpha: f32,
|
||||
k: f32,
|
||||
resolved: Option<wordcraft_fonts::word::Resolved>,
|
||||
diagram_fallback: Option<&std::sync::Arc<wordcraft_fonts::FontFace>>,
|
||||
) -> Vec<Draw> {
|
||||
let GraphicItem::Text { rect, text, size, color, bold, align, font, .. } = it else { return Vec::new() };
|
||||
let size = *size * k;
|
||||
if !rect.iter().chain([&size]).all(|v| v.is_finite()) {
|
||||
return Vec::new();
|
||||
}
|
||||
let family = font.as_deref().filter(|f| !f.is_empty()).unwrap_or(&doc.settings.minor_font);
|
||||
let size = size.clamp(1.0, 400.0);
|
||||
let resolved = wordcraft_fonts::word::resolve(family, *bold, false);
|
||||
let resolved = resolved.unwrap_or_else(|| {
|
||||
let family = font.as_deref().filter(|f| !f.is_empty()).unwrap_or(&doc.settings.minor_font);
|
||||
wordcraft_fonts::word::resolve(family, *bold, false)
|
||||
});
|
||||
let primary = resolved.face;
|
||||
let scale = |f: FaceRef| size / f.upem.max(1.0) as f32;
|
||||
let runs: Vec<_> = face_runs(text, primary, *bold)
|
||||
let runs: Vec<_> = face_runs(text, primary, *bold, diagram_fallback)
|
||||
.into_iter()
|
||||
.map(|(face, s)| (face, s, wordcraft_fonts::shape(face.get(), s, &[], |c| c)))
|
||||
.filter(|(_, _, shaped)| !shaped.is_empty())
|
||||
@@ -349,7 +483,12 @@ fn text_glyphs(doc: &Document, r: Rect, it: &GraphicItem, alpha: f32, k: f32) ->
|
||||
/// fallback face. A run the primary lacks takes one face covering all of it when one does (so a
|
||||
/// Chinese label doesn't mix serif and sans glyphs), else each character its own fallback. Spaces
|
||||
/// and combining marks stay in the run before them; a character no face has stays in `primary`.
|
||||
fn face_runs(text: &str, primary: FaceRef, bold: bool) -> Vec<(FaceRef, &str)> {
|
||||
fn face_runs<'a>(
|
||||
text: &'a str,
|
||||
primary: FaceRef,
|
||||
bold: bool,
|
||||
diagram_fallback: Option<&std::sync::Arc<wordcraft_fonts::FontFace>>,
|
||||
) -> Vec<(FaceRef, &'a str)> {
|
||||
let joins = |c: char| c.is_whitespace() || wordcraft_doc::math_linear::is_combining(c);
|
||||
// (start, end, drawn by `primary`)
|
||||
let mut spans: Vec<(usize, usize, bool)> = Vec::new();
|
||||
@@ -370,7 +509,25 @@ fn face_runs(text: &str, primary: FaceRef, bold: bool) -> Vec<(FaceRef, &str)> {
|
||||
continue;
|
||||
}
|
||||
let chars: Vec<char> = s.chars().filter(|c| !joins(*c)).collect();
|
||||
if let Some(f) = db.fallback_for_run(&chars, primary.id(), bold, false) {
|
||||
let df_face_for = |df: &std::sync::Arc<wordcraft_fonts::FontFace>, covered: &[char]| {
|
||||
if bold {
|
||||
let styled = db.face(&df.family, "Bold");
|
||||
if styled.family.eq_ignore_ascii_case(&df.family) && covered.iter().all(|c| styled.covers(*c)) {
|
||||
return FaceRef::of(&styled);
|
||||
}
|
||||
}
|
||||
FaceRef::of(df)
|
||||
};
|
||||
// A single SmartArt or chart diagram maintains a consistent fallback face across its labels (#5672).
|
||||
if let Some(df) = diagram_fallback
|
||||
&& chars.iter().all(|c| df.covers(*c))
|
||||
{
|
||||
out.push((df_face_for(df, &chars), s));
|
||||
continue;
|
||||
}
|
||||
if diagram_fallback.is_none_or(|df| !chars.iter().any(|c| df.covers(*c)))
|
||||
&& let Some(f) = db.fallback_for_run(&chars, primary.id(), bold, false)
|
||||
{
|
||||
out.push((FaceRef::of(&f), s));
|
||||
continue;
|
||||
}
|
||||
@@ -378,8 +535,13 @@ fn face_runs(text: &str, primary: FaceRef, bold: bool) -> Vec<(FaceRef, &str)> {
|
||||
// in one run.
|
||||
let mut run: Option<(FaceRef, usize)> = None;
|
||||
for (i, c) in s.char_indices() {
|
||||
let face =
|
||||
if joins(c) { None } else { Some(db.fallback_styled(c, primary.id(), bold, false).map(|f| FaceRef::of(&f)).unwrap_or(primary)) };
|
||||
let face = if joins(c) {
|
||||
None
|
||||
} else if let Some(df) = diagram_fallback.filter(|df| df.covers(c)) {
|
||||
Some(df_face_for(df, &[c]))
|
||||
} else {
|
||||
Some(db.fallback_styled(c, primary.id(), bold, false).map(|f| FaceRef::of(&f)).unwrap_or(primary))
|
||||
};
|
||||
match (run, face) {
|
||||
(Some((cur, from)), Some(f)) if f.id() != cur.id() => {
|
||||
out.extend(s.get(from..i).map(|t| (cur, t)));
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::boxes::{BoxInput, BoxLayout, Edges, joined, layout_box, push_para};
|
||||
use super::boxes::{BoxInput, BoxLayout, Edges, Joint, joined, layout_box, push_para};
|
||||
use super::cache::has_page_number_fields;
|
||||
use super::ctx::Ctx;
|
||||
use super::ctx::{Ctx, Joining};
|
||||
use super::floats::{
|
||||
FloatAnchor, LateFloats, ObjFrame, ObjectPlacement, anchor_floats, body_wraps, continued_exclusions, fitting, late_floats, place_late,
|
||||
place_objects,
|
||||
@@ -15,9 +15,89 @@ use super::{
|
||||
#[cfg(test)]
|
||||
use crate::WRAP_RELAYS;
|
||||
|
||||
/// A body paragraph. One after a paragraph whose mark is hidden goes on from that one's last line,
|
||||
/// as Word shows them, on one line (#3986): see [`Joint`].
|
||||
pub(crate) fn place_para(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block: usize, body_top: f32) {
|
||||
let joint = pb.joint.take().filter(|j| !pb.web && j.next == block && j.page == pb.pages.len() && j.col == pb.col);
|
||||
let mark_hidden = ctx.mark_hidden(p, None);
|
||||
// Nothing of it is shown: the place passes on to the paragraph after it.
|
||||
if mark_hidden && ctx.text_hidden(p, None) {
|
||||
place_para_alone(ctx, pb, p, block, body_top);
|
||||
pb.joint = joint.map(|mut j| {
|
||||
j.next = block + 1;
|
||||
j
|
||||
});
|
||||
return;
|
||||
}
|
||||
let goes_on = joint.filter(|_| {
|
||||
p.section.is_none()
|
||||
&& ctx.quiet_marks.binary_search(&block).is_err()
|
||||
&& ctx.stacked_marks.binary_search(&block).is_err()
|
||||
&& !ctx.doc.styles.resolve_para(&p.props).page_break_before
|
||||
&& !ctx.doc.styles.resolve_para(&p.props).bidi
|
||||
});
|
||||
match goes_on {
|
||||
Some(j) => place_para_joined(ctx, pb, p, (block, body_top), j),
|
||||
None => place_para_alone(ctx, pb, p, block, body_top),
|
||||
}
|
||||
if mark_hidden {
|
||||
let path = Path::top(block);
|
||||
pb.joint = pb.page().and_then(|page| {
|
||||
page.items.iter().rev().find_map(|it| match it {
|
||||
Placed::Lines { story: StoryRef::Body, path: at, para, l0, l1, x, y, turn: TextDirection::Horizontal, .. } if *at == path => {
|
||||
let room = if *l1 >= para.lines.len() { Rooms::of(ctx, block, para).bottom } else { 0.0 };
|
||||
Joint::after(para, (*l0, *l1), block, (*x, *y), room)
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
});
|
||||
if let Some(j) = pb.joint.as_mut() {
|
||||
(j.page, j.col) = (pb.pages.len(), pb.col);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `p` going on from the last line of the paragraph before (`j`): its first line starts at that
|
||||
/// line's top, beside that paragraph's text, with no space before and its list number counted
|
||||
/// but not drawn; its space after and line spacing are its own (Word, #3986).
|
||||
fn place_para_joined(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, (block, body_top): (usize, f32), j: Joint) {
|
||||
// The copy keeps the paragraph's revision, so the word being typed in it is found and its
|
||||
// layouts are reused from one pass to the next: the cache tells them apart by `Joining`.
|
||||
let mut q = p.clone();
|
||||
q.props.space_before = Some(0.0);
|
||||
q.props.space_before_auto = Some(false);
|
||||
let outer = ctx.joined.replace(Joining::new(q.rev, 0.0));
|
||||
let (gap, areas) = j.fit(ctx, &q, pb.col_w(), None);
|
||||
if gap > 0.0 {
|
||||
q.props.space_before = Some(gap);
|
||||
ctx.joined = Some(Joining::new(q.rev, gap));
|
||||
}
|
||||
pb.y = j.top;
|
||||
pb.prev = None;
|
||||
pb.unmark_block();
|
||||
pb.excl.extend(areas.iter().cloned());
|
||||
place_para_alone(ctx, pb, &q, block, body_top);
|
||||
ctx.joined = outer;
|
||||
Joint::unfit(&areas, &mut pb.excl);
|
||||
// The shared line is at least as tall as the first paragraph's, with its bottom border: what
|
||||
// follows starts below it.
|
||||
if (pb.pages.len(), pb.col) == (j.page, j.col) {
|
||||
pb.y = pb.y.max(j.bottom() + ctx.doc.styles.resolve_para(&q.props).space_after);
|
||||
}
|
||||
}
|
||||
|
||||
/// A paragraph going on from the line of the one before (#3986) whose first line moves on to the
|
||||
/// next column or page no longer shares that line: it is laid out as it is on its own there, its
|
||||
/// list number drawn and its first-line indent and alignment its own.
|
||||
fn unjoin(ctx: &mut Ctx, p: &Paragraph) {
|
||||
if let Some(j) = ctx.joined.as_mut().filter(|j| j.rev == p.rev) {
|
||||
j.shares = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// A closing mark before a continuous section takes no room after content. An otherwise empty
|
||||
/// section starting a new page retains its paragraph line.
|
||||
pub(crate) fn place_para(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block: usize, body_top: f32) {
|
||||
fn place_para_alone(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block: usize, body_top: f32) {
|
||||
if !pb.web && ctx.quiet_marks.binary_search(&block).is_ok() {
|
||||
let follows_section = block.checked_sub(1).and_then(|i| ctx.doc.body.get(i)).and_then(|b| b.as_para()).is_some_and(|p| p.section.is_some());
|
||||
let section = pb.sect_idx;
|
||||
@@ -127,7 +207,7 @@ impl Rooms {
|
||||
fn of(ctx: &Ctx, block: usize, pl: &ParaLayout) -> Self {
|
||||
let above = joined(ctx.doc, &ctx.doc.body, block, block.checked_sub(1), None);
|
||||
let below = joined(ctx.doc, &ctx.doc.body, block, Some(block + 1), None);
|
||||
let own = Edges::own(pl, 0, pl.lines.len());
|
||||
let own = Edges::own(pl, 0, pl.lines.len()).sharing(pl);
|
||||
Rooms { above, below, top: if above { 0.0 } else { own.top }, bottom: if below { 0.0 } else { own.bottom } }
|
||||
}
|
||||
}
|
||||
@@ -360,6 +440,7 @@ impl<'a> Flow<'a> {
|
||||
// keeps the lines and the next paragraph together at the top of a column too (#6821).
|
||||
if pb.y + need > pb.bottom + 0.01 && (!pb.fresh() || Self::strict_widow_control(ctx, pb)) && need <= pb.next_room(self.body_top) {
|
||||
pb.advance(self.block, self.body_top);
|
||||
unjoin(ctx, self.p);
|
||||
pb.y += rp.space_before.min(0.0);
|
||||
return rp.space_before.min(0.0);
|
||||
}
|
||||
@@ -557,6 +638,7 @@ impl<'a> Flow<'a> {
|
||||
fn move_on(&mut self, ctx: &mut Ctx, pb: &mut PageBuilder) {
|
||||
pb.advance(self.block, self.body_top);
|
||||
if self.l0 == 0 {
|
||||
unjoin(ctx, self.p);
|
||||
let y0 = pb.y;
|
||||
self.reanchor(ctx, pb, (y0, 0.0), &[]);
|
||||
self.anchor_y = y0;
|
||||
@@ -846,6 +928,11 @@ fn line_numbers(ctx: &mut Ctx, pb: &mut PageBuilder, pl: &ParaLayout, (l0, l1):
|
||||
{
|
||||
for li in l0..l1 {
|
||||
let Some(line) = pl.lines.get(li).filter(|l| !l.beside) else { continue };
|
||||
// The first line of a paragraph going on from the line of the one before (#3986)
|
||||
// shares that line, numbered already, unless its first word went on the next one.
|
||||
if li == 0 && pl.shares_line() {
|
||||
continue;
|
||||
}
|
||||
pb.line_no = pb.line_no.saturating_add(1);
|
||||
let n = pb.line_no.saturating_add(ln.start.saturating_sub(1));
|
||||
if ln.count_by > 1 && !n.is_multiple_of(ln.count_by) {
|
||||
@@ -895,7 +982,7 @@ fn place_para_in_flow(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block:
|
||||
}
|
||||
let before = f.gap_before(ctx, pb, broke_before);
|
||||
pb.y += before;
|
||||
let rooms = Rooms::of(ctx, block, &f.pl);
|
||||
let mut rooms = Rooms::of(ctx, block, &f.pl);
|
||||
let applied_before = f.keep_together(ctx, pb, rooms, before);
|
||||
// A different top only matters when there is something to wrap around.
|
||||
if spot(pb) != placed_at || ((pb.y - f.guess).abs() > 0.01 && !pb.excl.is_empty()) {
|
||||
@@ -904,7 +991,10 @@ fn place_para_in_flow(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block:
|
||||
f.anchor_y = y0 - applied_before;
|
||||
}
|
||||
while f.l0 < f.n() {
|
||||
// A paragraph moved on from the shared line (`unjoin`) is laid out again with borders of its own.
|
||||
rooms = Rooms::of(ctx, block, &f.pl);
|
||||
f.keep_again(ctx, pb, rooms);
|
||||
rooms = Rooms::of(ctx, block, &f.pl);
|
||||
f.place_due_late(ctx, pb);
|
||||
f.relay_wrap(ctx, pb);
|
||||
f.relay_pages(ctx, pb);
|
||||
@@ -1098,6 +1188,7 @@ fn next_first_line(ctx: &mut Ctx, block: usize, width: f32, depth: usize, new_pa
|
||||
grid: ctx.grid,
|
||||
fit_objects: false,
|
||||
fitted: &[],
|
||||
joined: false,
|
||||
};
|
||||
Arc::new(para::layout_para(p, &env))
|
||||
}
|
||||
|
||||
@@ -279,6 +279,19 @@ fn story_items(page: &Page, story: StoryRef) -> Box<dyn Iterator<Item = &Placed>
|
||||
}
|
||||
}
|
||||
|
||||
/// The topmost uncovered table cell in `story` under `(x, y)` on `page`.
|
||||
fn story_cell_at(page: &Page, story: StoryRef, x: f32, y: f32) -> Option<(&Path, usize, usize)> {
|
||||
let pt = Point::new(x, y);
|
||||
story_items(page, story)
|
||||
.filter_map(|it| match it {
|
||||
Placed::Cell { rect, table, row, cell, story: s, covered: false, .. } if *s == story && rect.contains(pt) => Some((table, *row, *cell)),
|
||||
_ => None,
|
||||
})
|
||||
// Nested tables emit their cells before the enclosing cell, so prefer the deepest match
|
||||
// and keep the last (topmost) cell on ties at the same nesting level.
|
||||
.max_by_key(|(table, _, _)| table.0.len())
|
||||
}
|
||||
|
||||
/// Whether header/footer part `id` has text near (x, y) on the page (its header or footer
|
||||
/// lines). Used so an object behind the header text is only grabbed where there's no text,
|
||||
/// mirroring `text_at` for the body.
|
||||
@@ -319,6 +332,14 @@ pub fn page_lines(page: &Page, story: StoryRef) -> Vec<LineHit<'_>> {
|
||||
}
|
||||
}
|
||||
}
|
||||
// A paragraph going on from the last line of one whose mark is hidden shares that line
|
||||
// (#3986): the first one's part of it ends where the second one's text starts.
|
||||
let joins: Vec<(f32, f32, f32)> = v.iter().filter(|l| l.para.shares_line() && l.li == 0).map(|l| (l.top, l.bottom, l.left)).collect();
|
||||
for (top, bottom, left) in joins {
|
||||
for l in v.iter_mut().filter(|l| l.top < bottom && top < l.bottom && l.left < left && left < l.right) {
|
||||
l.right = left;
|
||||
}
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
@@ -443,17 +464,31 @@ impl DocLayout {
|
||||
// other text on the page: below one, it goes to the text beside or after it (#2038).
|
||||
let floats = if story == StoryRef::Body { float_table_areas(p) } else { Vec::new() };
|
||||
let away = |path: &Path| floats.iter().any(|(t, r)| path.0.len() > t.0.len() && path.0.starts_with(&t.0) && !r.contains(Point::new(x, y)));
|
||||
// Turned cell text takes a click up to 2pt outside it, so outside a floating table too.
|
||||
if let Some(pos) = turned_hit(p, story, x, y, &away) {
|
||||
let cell = story_cell_at(p, story, x, y);
|
||||
let in_cell = |path: &Path, table: &Path, row: usize, col: usize| {
|
||||
path.0.starts_with(&table.0) && path.0.get(table.0.len()) == Some(&(row as u32)) && path.0.get(table.0.len() + 1) == Some(&(col as u32))
|
||||
};
|
||||
// Turned cell text takes a click up to 2pt outside it, so outside a floating table too,
|
||||
// but a click inside one table cell must never be stolen by a neighbouring cell's text.
|
||||
let skip_turned = |path: &Path| away(path) || cell.is_some_and(|(table, row, col)| !in_cell(path, table, row, col));
|
||||
if let Some(pos) = turned_hit(p, story, x, y, &skip_turned) {
|
||||
return Some(pos);
|
||||
}
|
||||
let lines = page_lines(p, story);
|
||||
let nearest = |a: &&LineHit, b: &&LineHit| score(a, x, y).total_cmp(&score(b, x, y));
|
||||
let at = |l: &LineHit| Pos { story: l.story, path: l.path.clone(), off: l.para.off_at_x(l.li, x - l.x) };
|
||||
if let Some((table, row, col)) = cell {
|
||||
if let Some(best) = lines.iter().filter(|l| in_cell(l.path, table, row, col)).min_by(nearest) {
|
||||
return Some(at(best));
|
||||
}
|
||||
if let Some(pos) = nearest_turned(p, story, x, y, &|path| !in_cell(path, table, row, col)) {
|
||||
return Some(pos);
|
||||
}
|
||||
}
|
||||
if lines.is_empty() {
|
||||
// A page of turned text (a vertical section): the nearest turned line.
|
||||
return nearest_turned(p, story, x, y, &away).or_else(|| nearest_turned(p, story, x, y, &|_: &Path| false));
|
||||
}
|
||||
let nearest = |a: &&LineHit, b: &&LineHit| score(a, x, y).total_cmp(&score(b, x, y));
|
||||
let at = |l: &LineHit| Pos { story: l.story, path: l.path.clone(), off: l.para.off_at_x(l.li, x - l.x) };
|
||||
if let Some(best) = lines.iter().filter(|l| !away(l.path)).min_by(nearest) {
|
||||
return Some(at(best));
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::boxes::{BoxInput, box_rules, layout_box};
|
||||
use super::boxes::{BoxInput, Joint, box_rules, layout_box};
|
||||
use super::ctx::{Ctx, with_pin};
|
||||
use super::floats::{EarlyFloats, WrapArea};
|
||||
use super::notes::{NOTE_SEP, NOTE_SEP_W, NoteBox, NoteSeps, v_span};
|
||||
@@ -35,6 +35,8 @@ pub(crate) struct PageBuilder<'a> {
|
||||
/// The previous paragraph ended with a page break (its mark stayed with the break): the next
|
||||
/// paragraph, first on the new page, gets no space before (Word).
|
||||
pub(crate) after_break_mark: bool,
|
||||
/// Where the last paragraph, whose mark is hidden, ended: the next one goes on from there.
|
||||
pub(crate) joint: Option<Joint>,
|
||||
/// The next section starts on a new page: this section's closing mark, when empty, needs no
|
||||
/// room (Word leaves it on a full page rather than starting a page for it).
|
||||
pub(crate) next_starts_page: bool,
|
||||
@@ -228,6 +230,16 @@ impl PageBuilder<'_> {
|
||||
self.block_marks.push(pg.items.len().saturating_sub(behind));
|
||||
}
|
||||
}
|
||||
/// Takes back the mark of a block that has placed nothing yet: it goes on from the line of
|
||||
/// the block before (#3986), and justified vertical alignment keeps the two together.
|
||||
pub(crate) fn unmark_block(&mut self) {
|
||||
if let Some(pg) = self.pages.last() {
|
||||
let behind = self.behind.last().copied().unwrap_or(0);
|
||||
if self.block_marks.last() == Some(&pg.items.len().saturating_sub(behind)) {
|
||||
self.block_marks.pop();
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Justified vertical alignment: share the room left below the page's text out equally
|
||||
/// between the gaps of its blocks, so the last line sits on the bottom margin (above the
|
||||
/// footnotes). A page with one block, or several columns, stays at the top.
|
||||
|
||||
@@ -101,9 +101,20 @@ pub struct ParaLayout {
|
||||
/// Room after a cluster between Asian text and Latin text or digits ([`auto_space`]), by
|
||||
/// cluster index, sorted. It is part of the cluster's advance, but takes no room at a line's end.
|
||||
pub auto_space: Vec<(usize, f32)>,
|
||||
/// It goes on from the last line of the paragraph before, whose mark is hidden, and shares
|
||||
/// that line ([`ParaEnv::joined`]).
|
||||
pub joined: bool,
|
||||
/// How tall the line breaker takes a row to be when it checks it against wrap areas.
|
||||
pub(crate) row_est: f32,
|
||||
}
|
||||
|
||||
impl ParaLayout {
|
||||
/// Whether its first line is the one it shares with the paragraph before, whose mark is
|
||||
/// hidden (#3986), rather than a line of its own below it (its first word didn't fit there).
|
||||
pub(crate) fn shares_line(&self) -> bool {
|
||||
self.joined && self.lines.first().is_some_and(|l| l.top <= 0.01)
|
||||
}
|
||||
|
||||
/// The room a horizontal rule at cluster `k` is placed in, from its left edge to the end of
|
||||
/// what the line has left. A first-line indent moves that end along (Word, measured with
|
||||
/// 50 % and fixed-width rules beside floats on either side and with first-line and hanging
|
||||
@@ -359,6 +370,7 @@ mod label_spacing_tests {
|
||||
read_line_spacing: None,
|
||||
fit_objects: false,
|
||||
fitted: &[],
|
||||
joined: false,
|
||||
};
|
||||
let mut p = Paragraph::with_text(if wrap { "Alpha probe synthetic business text repeated" } else { "Alpha probe" }, Default::default());
|
||||
p.props.line_spacing = Some(spacing);
|
||||
@@ -476,4 +488,60 @@ mod tests {
|
||||
}
|
||||
assert_eq!(lookup_family(&d, "No Such Roman Font"), MISSING_ROMAN_FONT);
|
||||
}
|
||||
|
||||
/// #5847: shrink_line_spaces is a no-op when there are no spaces after the line's last tab,
|
||||
/// guarding against division by zero, negative room, or shifting pre-tab clusters.
|
||||
#[test]
|
||||
fn shrink_line_spaces_with_no_spaces_after_last_tab_is_noop() {
|
||||
crate::test_fonts();
|
||||
let chr = CharProps { font: Some("Source Sans 3".into()), size: Some(12.0), ..Default::default() };
|
||||
let mut d = Document::new();
|
||||
d.settings.compat_mode = 15;
|
||||
let fields = FieldCtx::default();
|
||||
let env = ParaEnv {
|
||||
doc: &d,
|
||||
fields: &fields,
|
||||
width: 468.0,
|
||||
label: None,
|
||||
show_hidden: false,
|
||||
hide_deleted: Default::default(),
|
||||
table: None,
|
||||
proofing: None,
|
||||
typing_word: None,
|
||||
field_codes: false,
|
||||
grid: Grid::default(),
|
||||
exclusions: &[],
|
||||
eq_number: 0,
|
||||
numeral: Default::default(),
|
||||
read_line_spacing: None,
|
||||
fit_objects: false,
|
||||
fitted: &[],
|
||||
joined: false,
|
||||
};
|
||||
let mut p = Paragraph::with_text("n n n n\tWordWithoutSpaces", chr);
|
||||
p.props = ParaProps {
|
||||
align: Some(Align::Justify),
|
||||
tabs: Some(vec![TabStop { pos: 150.0, align: TabAlign::Left, leader: Default::default() }]),
|
||||
..Default::default()
|
||||
};
|
||||
let mut pl = layout_para(&p, &env);
|
||||
let mark_style = pl.clusters[0].style;
|
||||
break_lines(&mut pl, &env, mark_style, None);
|
||||
let c0 = pl.lines[0].c0;
|
||||
let c1 = pl.lines[0].c1;
|
||||
let last_tab = (c0..c1).rev().find(|k| pl.clusters.get(*k).is_some_and(|c| c.kind == ClKind::Tab)).unwrap();
|
||||
let from = last_tab + 1;
|
||||
|
||||
let spaces_after = (from..c1).filter(|k| pl.clusters.get(*k).is_some_and(|c| c.kind == ClKind::Space)).count();
|
||||
assert_eq!(spaces_after, 0);
|
||||
|
||||
let orig_xs = pl.lines[0].xs.clone();
|
||||
let content_end = *orig_xs.last().unwrap();
|
||||
|
||||
for slack in [-20.0, 0.0, f32::NEG_INFINITY] {
|
||||
let mut xs = orig_xs.clone();
|
||||
justify::shrink_line_spaces(&pl, &mut xs, (c0, from), c1, content_end, slack);
|
||||
assert_eq!(xs, orig_xs, "slack {slack} with 0 post-tab spaces must not shift any cluster");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,23 +22,29 @@ pub(super) fn space_room(spaces: f32, word: f32) -> f32 {
|
||||
(spaces * MAX_SPACE_SHRINK).min(word.max(0.0) * MAX_WORD_OVERRUN)
|
||||
}
|
||||
|
||||
/// Take `-slack` (an overflow) out of the line's inner spaces, in proportion to their widths and
|
||||
/// never more than [`MAX_SPACE_SHRINK`] of them. Trailing spaces hang and are left alone.
|
||||
pub(super) fn shrink_line_spaces(pl: &ParaLayout, xs: &mut [f32], c0: usize, c1: usize, content_end: f32, slack: f32) {
|
||||
let spaces: Vec<(usize, f32)> = (c0..c1)
|
||||
/// Take `-slack` (an overflow) out of the line's inner spaces from `from` on (after the line's last
|
||||
/// left/default tab), in proportion to their widths and never more than [`MAX_SPACE_SHRINK`] of them.
|
||||
/// Trailing spaces hang and are left alone.
|
||||
///
|
||||
/// `c0` is the first cluster on the line, and `from` is where space shrinking begins (the cluster
|
||||
/// following the line's last tab, or `c0` when there are no tabs on the line). `c1` is the end of
|
||||
/// the line's cluster range.
|
||||
pub(super) fn shrink_line_spaces(pl: &ParaLayout, xs: &mut [f32], (c0, from): (usize, usize), c1: usize, content_end: f32, slack: f32) {
|
||||
let from = from.max(c0);
|
||||
let spaces: Vec<(usize, f32)> = (from..c1)
|
||||
.filter_map(|k| {
|
||||
let c = pl.clusters.get(k).filter(|c| c.kind == ClKind::Space)?;
|
||||
(xs.get(k - c0).copied().unwrap_or(f32::MAX) < content_end - 0.01).then_some((k, c.adv))
|
||||
})
|
||||
.collect();
|
||||
let total: f32 = spaces.iter().map(|s| s.1).sum();
|
||||
if total <= 0.0 || !slack.is_finite() {
|
||||
if !total.is_finite() || total <= 0.0 || !slack.is_finite() {
|
||||
return;
|
||||
}
|
||||
let ratio = (-slack / total).clamp(0.0, MAX_SPACE_SHRINK);
|
||||
let mut take = 0.0;
|
||||
let mut next = spaces.iter().peekable();
|
||||
for k in c0..c1 {
|
||||
for k in from..c1 {
|
||||
if let Some(v) = xs.get_mut(k - c0) {
|
||||
*v -= take;
|
||||
}
|
||||
|
||||
@@ -25,7 +25,7 @@ struct Breaker<'e> {
|
||||
/// Where default tab stops are counted from (see [`next_tab`]).
|
||||
tab_origin: f32,
|
||||
/// Word 2013+ (compatibility mode 15) fits more text on a justified line by shrinking its
|
||||
/// spaces (`space_room`); never on lines with tabs.
|
||||
/// spaces (`space_room`); on a line with tabs, only the spaces after a final left/default tab.
|
||||
shrink_spaces: bool,
|
||||
/// Word 2003's indent rules (`w:doNotSuppressIndentation`) before Word 2013's layout, for an
|
||||
/// unnumbered paragraph: a row starts right after a floating object before the indent.
|
||||
@@ -63,6 +63,9 @@ struct Breaker<'e> {
|
||||
row_first: usize,
|
||||
/// Spans skipped in a row because the next word didn't fit (see `Scan::skip`).
|
||||
skipped: usize,
|
||||
/// The paragraph goes on from the line of the one before (#3986): its first line starts right
|
||||
/// after that one's text, and takes its place there whatever its own alignment.
|
||||
joined: bool,
|
||||
/// A left tab past the right indent that wrapped to start the next line.
|
||||
wrapped_tab: Option<usize>,
|
||||
}
|
||||
@@ -97,9 +100,13 @@ struct Scan {
|
||||
pending_tab: Option<(usize, TabStop, f32)>,
|
||||
/// The text after a pending decimal tab looked at so far for its '.'.
|
||||
decimal: Option<DecimalScan>,
|
||||
/// The width of the spaces so far on this line.
|
||||
/// The width of the spaces so far on this line, after its last tab.
|
||||
space_w: f32,
|
||||
has_tab: bool,
|
||||
/// Whether spaces after the last tab so far may shrink (true initially and after left/default
|
||||
/// tabs; false after right, center, or decimal tabs whose anchors use unshrunk widths).
|
||||
shrink_tab: bool,
|
||||
/// Tab cluster indices on this line whose alignment is not `TabAlign::Left`.
|
||||
non_left_tabs: Vec<usize>,
|
||||
/// The first word doesn't fit a span narrowed by a floating object: it moves on whole.
|
||||
skip: bool,
|
||||
}
|
||||
@@ -188,7 +195,9 @@ impl<'e> Breaker<'e> {
|
||||
n: pl.clusters.len(),
|
||||
width,
|
||||
base_right: (width - rp.indent_right).max(1.0),
|
||||
first_left: rp.indent_left + rp.indent_first,
|
||||
// On the line it shares with the paragraph before (#3986), kept clear of that one's
|
||||
// text by an exclusion, a joined paragraph's own indents don't hold its text back.
|
||||
first_left: if env.joined { (rp.indent_left + rp.indent_first).min(0.0) } else { rp.indent_left + rp.indent_first },
|
||||
default_tab: settings.default_tab,
|
||||
hanging_at: if rp.indent_first < 0.0 { Some(rp.indent_left) } else { None },
|
||||
tab_origin: if settings.odf.is_some_and(|o| o.tabs_from_indent) { rp.indent_left } else { 0.0 },
|
||||
@@ -222,13 +231,20 @@ impl<'e> Breaker<'e> {
|
||||
row_rest: VecDeque::new(),
|
||||
row_first: 0,
|
||||
skipped: 0,
|
||||
joined: env.joined,
|
||||
wrapped_tab: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The first line's start: a joined paragraph's first line pushed below the shared line (its
|
||||
/// first word didn't fit there) starts at the paragraph's left indent, as its other lines do.
|
||||
fn first_indent(&self) -> f32 {
|
||||
if self.joined && self.top > 0.0 { self.rp.indent_left } else { self.first_left }
|
||||
}
|
||||
|
||||
/// The left edge of the row's first span: the indent, behind a drop cap on its lines.
|
||||
fn row_left(&self, pl: &ParaLayout) -> f32 {
|
||||
let lo = if self.first { self.first_left } else { self.rp.indent_left };
|
||||
let lo = if self.first { self.first_indent() } else { self.rp.indent_left };
|
||||
match pl.drop_cap {
|
||||
Some((_, dl, dw)) if dw > 0.0 && self.lines.len() < dl as usize => self.first_left.max(self.rp.indent_left) + dw,
|
||||
_ => lo,
|
||||
@@ -271,7 +287,7 @@ impl<'e> Breaker<'e> {
|
||||
/// The start of a line: its span, and the list label if it is the first.
|
||||
fn begin_line(&mut self, pl: &mut ParaLayout) -> Scan {
|
||||
let beside = !self.row_rest.is_empty() && self.lines.len() > self.row_first;
|
||||
let row_lo = if self.first { self.first_left } else { self.rp.indent_left };
|
||||
let row_lo = if self.first { self.first_indent() } else { self.rp.indent_left };
|
||||
let (left, right_edge, narrowed) = self.next_span(pl);
|
||||
let x = if self.first { self.place_label(pl, left) } else { left };
|
||||
Scan {
|
||||
@@ -294,7 +310,8 @@ impl<'e> Breaker<'e> {
|
||||
pending_tab: None,
|
||||
decimal: None,
|
||||
space_w: 0.0,
|
||||
has_tab: false,
|
||||
shrink_tab: true,
|
||||
non_left_tabs: Vec::new(),
|
||||
skip: false,
|
||||
}
|
||||
}
|
||||
@@ -563,7 +580,10 @@ impl<'e> Breaker<'e> {
|
||||
let last_tab = (c0..c1).rev().find(|k| pl.clusters.get(*k).is_some_and(|c| c.kind == ClKind::Tab));
|
||||
let align_from = last_tab.map(|k| k + 1).unwrap_or(c0);
|
||||
let display = pl.displays.iter().find(|(ci, _)| *ci >= c0 && *ci < c1).map(|d| d.1);
|
||||
let shift = match (display, rp.align) {
|
||||
// The line a paragraph shares with the one before, whose mark is hidden, starts in that
|
||||
// one, and takes its place right after that one's text (Word, #3986).
|
||||
let align = if self.joined && self.lines.is_empty() { Align::Left } else { rp.align };
|
||||
let shift = match (display, align) {
|
||||
(Some(MathJc::Left), _) => 0.0,
|
||||
(Some(MathJc::Right), _) => slack,
|
||||
(Some(_), _) => slack / 2.0,
|
||||
@@ -587,13 +607,15 @@ impl<'e> Breaker<'e> {
|
||||
}
|
||||
// A line ending in a manual line break is stretched too, unless `doNotExpandShiftReturn` says not to.
|
||||
let stretch_end = sc.end == LineEnd::Wrap || (sc.end == LineEnd::LineBreak && self.expand_break);
|
||||
let justify = display.is_none() && ((rp.align == Align::Justify && stretch_end) || rp.align == Align::Distribute);
|
||||
// A line that only fits with shrunk spaces is shrunk, the last line of the paragraph too.
|
||||
let shrink = display.is_none() && self.shrink_spaces && slack < 0.0 && last_tab.is_none();
|
||||
let justify = display.is_none() && ((align == Align::Justify && stretch_end) || align == Align::Distribute);
|
||||
// A line that only fits with shrunk spaces is shrunk, the last line of the paragraph too,
|
||||
// unless its last tab is a non-left tab whose anchor was resolved with unshrunk widths.
|
||||
let can_shrink_tab = last_tab.is_none_or(|k| !sc.non_left_tabs.contains(&k));
|
||||
let shrink = display.is_none() && self.shrink_spaces && slack < 0.0 && can_shrink_tab;
|
||||
if shrink {
|
||||
shrink_line_spaces(pl, &mut sc.xs, c0, c1, content_end, slack);
|
||||
shrink_line_spaces(pl, &mut sc.xs, (c0, align_from), c1, content_end, slack);
|
||||
} else if justify && slack > 0.0 {
|
||||
justify_line(pl, &mut sc.xs, (c0, c1, align_from), (content_end, slack), rp.align == Align::Distribute);
|
||||
justify_line(pl, &mut sc.xs, (c0, c1, align_from), (content_end, slack), align == Align::Distribute);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -692,6 +714,7 @@ impl<'e> Breaker<'e> {
|
||||
fn finish(mut self, pl: &mut ParaLayout) {
|
||||
self.hang_drop_cap(pl);
|
||||
pl.height = self.top;
|
||||
pl.row_est = self.est_h;
|
||||
pl.lines = std::mem::take(&mut self.lines);
|
||||
let label_shift = self.label_shifts.get(pl.label_line()).copied().unwrap_or(0.0);
|
||||
if let Some(lab) = pl.label.as_mut() {
|
||||
@@ -818,7 +841,8 @@ impl Scan {
|
||||
/// A tab: its stop, and the room to it. True when the line ends before it.
|
||||
fn tab(&mut self, bk: &mut Breaker, pl: &mut ParaLayout) -> bool {
|
||||
let j = self.j;
|
||||
self.has_tab = true;
|
||||
// Only the spaces after a line's last tab shrink (measured in Word for Mac).
|
||||
self.space_w = 0.0;
|
||||
resolve_tab(pl, &mut self.pending_tab, &mut self.xs, self.c0, self.x, &mut self.x);
|
||||
let rp = &bk.rp;
|
||||
let ptab = pl.ptabs.iter().find(|t| t.0 == j).map(|&(_, a, b, l)| ptab_stop(a, b, l, bk.width, (rp.indent_left, rp.indent_right)));
|
||||
@@ -861,6 +885,10 @@ impl Scan {
|
||||
/// decimal tab).
|
||||
fn place_tab(&mut self, pl: &mut ParaLayout, stop: TabStop) {
|
||||
let j = self.j;
|
||||
self.shrink_tab = stop.align == TabAlign::Left;
|
||||
if !self.shrink_tab {
|
||||
self.non_left_tabs.push(j);
|
||||
}
|
||||
match stop.align {
|
||||
TabAlign::Left | TabAlign::Bar | TabAlign::Clear => {
|
||||
let w = (stop.pos - self.x).max(0.0);
|
||||
@@ -901,7 +929,7 @@ impl Scan {
|
||||
// each segment's font, glyphs and position for painting.
|
||||
let advance = pl.atomic_advance(j);
|
||||
let absorbs = self.absorbs(pl, advance);
|
||||
let shrink = if bk.shrink_spaces && !self.has_tab {
|
||||
let shrink = if bk.shrink_spaces && self.shrink_tab {
|
||||
space_room(self.space_w, self.x + advance - pl.auto_space_after(j) - self.word_from)
|
||||
} else {
|
||||
0.0
|
||||
@@ -1041,6 +1069,7 @@ impl Scan {
|
||||
self.last_break = Some(tj - 1);
|
||||
self.pending_tab = None;
|
||||
self.leaders.retain(|(k, _)| *k < tj);
|
||||
self.non_left_tabs.retain(|&k| k < tj);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -401,4 +401,7 @@ pub struct ParaEnv<'a> {
|
||||
/// Heights of the paragraph's inline text boxes that resize to fit their text, by object
|
||||
/// index: they take these instead of their saved heights.
|
||||
pub fitted: &'a [(usize, f32)],
|
||||
/// The paragraph goes on from the line of the one before, whose mark is hidden (#3986): its
|
||||
/// list number is counted and sets its indents, but isn't drawn.
|
||||
pub joined: bool,
|
||||
}
|
||||
|
||||
@@ -533,13 +533,14 @@ fn mark_break_opportunities(clusters: &mut [Cluster], bt: &BreakText, rp: &Resol
|
||||
}
|
||||
}
|
||||
|
||||
/// The list label, shaped; none on a paragraph containing only a page break: Word hides it there.
|
||||
/// The list counter has already advanced, so the following item keeps its number.
|
||||
/// The list label, shaped; none on a paragraph containing only a page break, nor on one that goes
|
||||
/// on from the line of the paragraph before (#3986): Word hides it there. The list counter has
|
||||
/// already advanced, so the following item keeps its number.
|
||||
fn list_label(cx: &Cx, b: &mut Builder, mark_style: u32) -> Option<Label> {
|
||||
let (p, rp) = (cx.p, cx.rp);
|
||||
let break_only =
|
||||
b.clusters.iter().any(|c| c.kind == ClKind::PageBreak) && b.clusters.iter().all(|c| matches!(c.kind, ClKind::PageBreak | ClKind::Marker));
|
||||
let (text, lvl) = cx.env.label.as_ref().filter(|_| !break_only)?;
|
||||
let (text, lvl) = cx.env.label.as_ref().filter(|_| !break_only && !cx.env.joined)?;
|
||||
let rc = cx.res.char(&p.mark.clone().overlaid(&lvl.chr));
|
||||
// A bullet no installed font can draw would come from whatever icon font has its
|
||||
// private-use code (Font Awesome's Twitter logo at U+F081, #1683): it shows the level's
|
||||
@@ -713,6 +714,8 @@ pub fn layout_para(p: &Paragraph, env: &ParaEnv) -> ParaLayout {
|
||||
left_out: Vec::new(),
|
||||
enclosures,
|
||||
auto_space,
|
||||
joined: env.joined,
|
||||
row_est: 0.0,
|
||||
};
|
||||
let auto = env.doc.settings.auto_hyphenation && !pl.rp.suppress_hyphens;
|
||||
pl.hyph_after = hyphenation_points(&bt.text, |i| bt.to_para(i), &pl, auto, env.doc.settings.hyphenate_caps, &runs);
|
||||
|
||||
@@ -110,6 +110,7 @@ fn new_ctx<'a>(
|
||||
track_totals: true,
|
||||
pct_base: None,
|
||||
quiet_marks: Vec::new(),
|
||||
joined: None,
|
||||
stacked_marks: Vec::new(),
|
||||
mirror: false,
|
||||
table_keys: Vec::new(),
|
||||
@@ -211,6 +212,7 @@ fn new_page_builder<'p>(
|
||||
orig_bottom: 0.0,
|
||||
prev: None,
|
||||
after_break_mark: false,
|
||||
joint: None,
|
||||
next_starts_page: false,
|
||||
restart_at: None,
|
||||
excl: Vec::new(),
|
||||
|
||||
@@ -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;
|
||||
@@ -233,6 +233,7 @@ pub fn measure_table_columns(doc: &wordcraft_doc::Document, t: &Table) -> Vec<(f
|
||||
grid: crate::para::Grid::default(),
|
||||
fit_objects: false,
|
||||
fitted: &[],
|
||||
joined: false,
|
||||
};
|
||||
let (mut min, mut max) = (EMPTY_TEXT, EMPTY_TEXT);
|
||||
if cell.props.vmerge != VMerge::Continue && !cell.props.text_direction.is_turned() {
|
||||
@@ -430,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;
|
||||
@@ -476,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.
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
//! A paragraph going on from the line of one whose mark is hidden (#3986): what changes when it
|
||||
//! moves off that line or is placed apart from it.
|
||||
|
||||
use super::lay;
|
||||
use crate::{Arc, DocLayout, Placed, StoryRef, hit};
|
||||
use wordcraft_doc::para::{Anchor, Float, Wrap};
|
||||
use wordcraft_doc::props::{Border, Borders, LineSpacing, NumRef, TextFrame};
|
||||
use wordcraft_doc::{Block, Document, Path, Pos, Table};
|
||||
|
||||
/// A table around the document's paragraphs (the cell paths are `[0, 0, 0, i]`).
|
||||
fn in_cell(d: &mut Document) {
|
||||
let mut table = Table::new(1, 1, 400.0);
|
||||
table.rows[0].cells[0].blocks = std::mem::take(&mut d.body);
|
||||
d.body = vec![Arc::new(Block::Table(table))];
|
||||
}
|
||||
|
||||
/// The top of the lines of the body block or cell paragraph at `path`.
|
||||
fn top_of(l: &DocLayout, path: &Path) -> f32 {
|
||||
l.pages[0]
|
||||
.items
|
||||
.iter()
|
||||
.find_map(|it| match it {
|
||||
Placed::Lines { story: StoryRef::Body, path: p, y, .. } if p == path => Some(*y),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or_else(|| panic!("no lines at {path:?}"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_joined_paragraph_moved_to_the_next_page_gets_its_top_border() {
|
||||
// Sharing the line it takes no room for a top border; moved whole to the next page it is
|
||||
// laid out on its own and draws one above its first line.
|
||||
let omega = "Omega ".repeat(60);
|
||||
let boxed = Some(Borders::all(Border { space: 1.0, ..Border::single(1.5) }));
|
||||
for filler in 20..80 {
|
||||
let mut text: Vec<String> = (0..filler).map(|i| format!("Filler {i}")).collect();
|
||||
text.push("Alpha".into());
|
||||
text.push(omega.clone());
|
||||
let mut d = Document::from_text(&text.join("\n"));
|
||||
d.para_mut(StoryRef::Body, &Path::top(filler)).unwrap().mark.hidden = Some(true);
|
||||
let o = d.para_mut(StoryRef::Body, &Path::top(filler + 1)).unwrap();
|
||||
(o.props.keep_lines, o.props.borders) = (Some(true), boxed);
|
||||
let l = lay(&d);
|
||||
let o = l.caret(&Pos::body(filler + 1, 0)).unwrap();
|
||||
if l.caret(&Pos::body(filler, 0)).unwrap().page != 0 || o.page != 1 {
|
||||
continue;
|
||||
}
|
||||
let tops = l.pages[1].items.iter().filter(|i| matches!(i, Placed::Rule { y0, y1, border, .. } if y0 == y1 && border.width == 1.5));
|
||||
let above = tops.filter(|i| matches!(i, Placed::Rule { y0, .. } if *y0 < o.top)).count();
|
||||
assert_eq!(above, 1, "the moved paragraph draws its top border above its first line");
|
||||
return;
|
||||
}
|
||||
panic!("no filler moved the joined paragraph to the next page");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_joined_first_line_below_the_shared_line_does_not_cut_the_line_above() {
|
||||
// "Omega"'s first word does not fit after "Alpha", so its first line goes below; its indent
|
||||
// (inside "Alpha"'s text) must not cut "Alpha"'s hit extent.
|
||||
let mut d = Document::from_text(&format!("Alpha\n{} tail", "W".repeat(48)));
|
||||
d.para_mut(StoryRef::Body, &Path::top(0)).unwrap().mark.hidden = Some(true);
|
||||
d.para_mut(StoryRef::Body, &Path::top(1)).unwrap().props.indent_left = Some(20.0);
|
||||
let l = lay(&d);
|
||||
let lines = hit::page_lines(&l.pages[0], StoryRef::Body);
|
||||
let alpha = lines.iter().find(|h| h.path == &Path::top(0)).unwrap();
|
||||
let omega = lines.iter().find(|h| h.path == &Path::top(1) && h.li == 0).unwrap();
|
||||
assert!(omega.top > alpha.top + 1.0, "setup: the first word moved below the shared line");
|
||||
let text_end = l.caret(&Pos::body(0, 5)).unwrap().x;
|
||||
assert!(alpha.right >= text_end - 0.5, "Alpha's line reaches {} but its text ends at {text_end}", alpha.right);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_joined_paragraphs_drawings_are_relative_to_the_shared_line() {
|
||||
// A drawing anchored to the paragraph, at its top: the paragraph's top is the shared line's,
|
||||
// not the end of the paragraph before.
|
||||
let mut d = Document::from_text("Alpha\nOmega\nAfter");
|
||||
d.para_mut(StoryRef::Body, &Path::top(0)).unwrap().mark.hidden = Some(true);
|
||||
let float =
|
||||
Float { wrap: Wrap::InFrontOfText, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, x: 200.0, y: 0.0, dist: 0.0, ..Default::default() };
|
||||
super::text_box_at(&mut d, &Pos::body(1, 0), "Box", 100.0, 40.0, float);
|
||||
in_cell(&mut d);
|
||||
let l = lay(&d);
|
||||
let alpha = top_of(&l, &Path(vec![0, 0, 0, 0]));
|
||||
let boxed = l.pages[0].items.iter().find_map(|it| match it {
|
||||
Placed::Lines { story: StoryRef::Part(_), y, .. } => Some(*y),
|
||||
_ => None,
|
||||
});
|
||||
let boxed = boxed.expect("the box's text is laid out");
|
||||
assert!(boxed < alpha + 12.0, "the box's text at {boxed} is below the shared line at {alpha}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_text_frame_after_a_hidden_mark_is_not_joined() {
|
||||
// A framed paragraph is placed apart, so it shares no line with the one before: its number is
|
||||
// drawn (it is counted either way). The frame is its own, or given by the table's style.
|
||||
let frame =
|
||||
TextFrame { x_align: Some("right".into()), h_anchor: "text".into(), v_anchor: "text".into(), wrap: "around".into(), ..Default::default() };
|
||||
for from_style in [false, true] {
|
||||
let mut d = Document::from_text("Alpha\n7");
|
||||
let id = Arc::make_mut(&mut d.numbering).add_list(wordcraft_doc::ListKind::Numbered);
|
||||
d.format_paragraphs(&Pos::body(0, 0), &Pos::body(1, 1), &|p| p.numbering = Some(NumRef { num: id, level: 0 })).unwrap();
|
||||
d.para_mut(StoryRef::Body, &Path::top(0)).unwrap().mark.hidden = Some(true);
|
||||
// From the table's style, the frame is given to "Alpha" too: zero dimensions cancel it there.
|
||||
let (at, own) = if from_style { (0, TextFrame { w: Some(0.0), h: Some(0.0), ..frame.clone() }) } else { (1, frame.clone()) };
|
||||
d.para_mut(StoryRef::Body, &Path::top(at)).unwrap().props.frame = Some(own);
|
||||
in_cell(&mut d);
|
||||
if from_style {
|
||||
Arc::make_mut(&mut d.styles).get_mut("TableGrid").expect("Table Grid").para.frame = Some(frame.clone());
|
||||
if let Some(Block::Table(t)) = d.body.first_mut().map(Arc::make_mut) {
|
||||
t.props.style = Some("TableGrid".into());
|
||||
}
|
||||
}
|
||||
let l = lay(&d);
|
||||
let label = l.pages[0].items.iter().find_map(|it| match it {
|
||||
Placed::Lines { path, para, .. } if path.0 == [0, 0, 0, 1] => Some(para.label.is_some()),
|
||||
_ => None,
|
||||
});
|
||||
assert_eq!(label, Some(true), "the framed paragraph keeps its number (frame from the table style: {from_style})");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_joined_paragraphs_later_lines_start_below_a_taller_shared_line() {
|
||||
// A heading whose mark is hidden, then body text going on from it: the text's first line
|
||||
// shares the heading's line; its later lines start below that line and the heading's bottom
|
||||
// border, not inside it (Word), whatever the text's line spacing.
|
||||
let spacings = [None, Some(LineSpacing::Exactly(12.0)), Some(LineSpacing::AtLeast(12.0)), Some(LineSpacing::Multiple(2.0))];
|
||||
// A large word that fits the first line of the text laid out alone but wraps off the
|
||||
// narrower shared line onto the second (`big`), so the two first lines differ in height.
|
||||
let cases = [false, true].into_iter().flat_map(|c| spacings.into_iter().flat_map(move |s| [(c, s, false, None), (c, s, true, None)]));
|
||||
let big = [60, 70, 80].into_iter().flat_map(|at| [(false, None, false, Some(at)), (true, None, false, Some(at))]);
|
||||
for (cell, spacing, bordered, large) in cases.chain(big) {
|
||||
let case = format!("cell {cell}, {spacing:?}, border {bordered}, large word at {large:?}");
|
||||
let mut d = Document::from_text(&format!("Heading\n{}", "body text ".repeat(40)));
|
||||
d.format_range(&Pos::body(0, 0), &Pos::body(0, 7), &|c| c.size = Some(40.0)).unwrap();
|
||||
if let Some(at) = large {
|
||||
d.format_range(&Pos::body(1, at), &Pos::body(1, at + 4), &|c| c.size = Some(30.0)).unwrap();
|
||||
}
|
||||
let heading = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
|
||||
heading.mark.hidden = Some(true);
|
||||
if bordered {
|
||||
heading.props.borders = Some(Borders { bottom: Some(Border { space: 4.0, ..Border::single(1.5) }), ..Default::default() });
|
||||
}
|
||||
d.para_mut(StoryRef::Body, &Path::top(1)).unwrap().props.line_spacing = spacing;
|
||||
if cell {
|
||||
in_cell(&mut d);
|
||||
}
|
||||
let l = lay(&d);
|
||||
let lines = hit::page_lines(&l.pages[0], StoryRef::Body);
|
||||
let heading = lines.iter().find(|h| h.path.0.last() == Some(&0)).unwrap();
|
||||
// The shared line's bottom, with the heading's bottom border under it.
|
||||
let rule = l.pages[0].items.iter().filter_map(|it| match it {
|
||||
Placed::Rule { y0, y1, border, .. } if y0 == y1 && border.width == 1.5 => Some(*y0),
|
||||
_ => None,
|
||||
});
|
||||
let floor = rule.fold(heading.bottom, f32::max);
|
||||
assert!(!bordered || floor > heading.bottom, "setup: the border is drawn below the shared line ({case})");
|
||||
let body: Vec<_> = lines.iter().filter(|h| h.path.0.last() == Some(&1)).collect();
|
||||
assert!(body.len() > 2, "setup: the body text runs to several lines ({case})");
|
||||
assert!(body[0].top < heading.bottom - 1.0, "the first line at {} shares the heading's line ({case})", body[0].top);
|
||||
for line in &body[1..] {
|
||||
assert!(line.top >= floor - 0.01, "line {} at {} starts inside the shared line, ending {floor} ({case})", line.li, line.top);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 = "b436ae992591173ce53fdb1314421ba2d8897e49" }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541" }
|
||||
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 = "b436ae992591173ce53fdb1314421ba2d8897e49", features = ["subset"] }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "0b8bbaf4c842da2d47de7b3fddd7170ba6115541", features = ["subset"] }
|
||||
serde_json = { workspace = true }
|
||||
toml = "1"
|
||||
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" width="20" height="20">
|
||||
<path d="M8.6 5.4 L13.2 5.4 M6.8 16.5 L11.4 16.5 M10.9 5.4 L9.1 16.5" fill="none" stroke="currentColor" stroke-width="1.25" stroke-linecap="round"/>
|
||||
<path d="M8 5.4 L13.8 5.4 L13.8 7 L11.6 7 L10.3 14.9 L12 14.9 L12 16.5 L6.2 16.5 L6.2 14.9 L8.4 14.9 L9.7 7 L8 7 Z" fill="currentColor"/>
|
||||
</svg>
|
||||
|
||||
|
Before Width: | Height: | Size: 242 B After Width: | Height: | Size: 231 B |
@@ -0,0 +1,7 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" width="20" height="20">
|
||||
<rect x="3" y="3" width="6" height="6" rx="1" fill="#1E6FD9" class="accent" fill-opacity="0.251"/>
|
||||
<rect x="3" y="3" width="6" height="6" rx="1" fill="none" stroke="currentColor" stroke-width="1.25"/>
|
||||
<rect x="11" y="3" width="6" height="6" rx="1" fill="none" stroke="currentColor" stroke-width="1.25"/>
|
||||
<rect x="3" y="11" width="6" height="6" rx="1" fill="none" stroke="currentColor" stroke-width="1.25"/>
|
||||
<rect x="11" y="11" width="6" height="6" rx="1" fill="none" stroke="currentColor" stroke-width="1.25"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 612 B |
@@ -0,0 +1,9 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" width="20" height="20">
|
||||
<rect x="3" y="3" width="14" height="4" rx="1" fill="#1E6FD9" class="accent"/>
|
||||
<rect x="3" y="3" width="14" height="14" rx="1" fill="none" stroke="currentColor" stroke-width="1.25"/>
|
||||
<path d="M3 7 L17 7" fill="none" stroke="currentColor" stroke-width="1.25"/>
|
||||
<rect x="5" y="9" width="2.5" height="2.5" fill="none" stroke="currentColor" stroke-width="1.25"/>
|
||||
<path d="M9.5 10.25 L15 10.25" fill="none" stroke="currentColor" stroke-width="1.25"/>
|
||||
<rect x="5" y="13" width="2.5" height="2.5" fill="none" stroke="currentColor" stroke-width="1.25"/>
|
||||
<path d="M9.5 14.25 L15 14.25" fill="none" stroke="currentColor" stroke-width="1.25"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 738 B |
@@ -0,0 +1,9 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" width="20" height="20">
|
||||
<rect x="3" y="3" width="14" height="4" rx="1" fill="#1E6FD9" class="accent"/>
|
||||
<rect x="3" y="11" width="14" height="3" fill="#1E6FD9" class="accent" fill-opacity="0.251"/>
|
||||
<rect x="3" y="3" width="14" height="14" rx="1" fill="none" stroke="currentColor" stroke-width="1.25"/>
|
||||
<path d="M3 7 L17 7" fill="none" stroke="currentColor" stroke-width="1.25"/>
|
||||
<path d="M3 11 L17 11" fill="none" stroke="currentColor" stroke-width="1.25"/>
|
||||
<path d="M3 14 L17 14" fill="none" stroke="currentColor" stroke-width="1.25"/>
|
||||
<path d="M8 7 L8 17" fill="none" stroke="currentColor" stroke-width="1.25"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 694 B |
@@ -1,4 +1,3 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" width="20" height="20">
|
||||
<path d="M5.8 4.24 L5.8 10.4 C5.8 13.1 7.4 14.6 10 14.6 C12.6 14.6 14.2 13.1 14.2 10.4 L14.2 4.24" fill="none" stroke="currentColor" stroke-width="1.25" stroke-linecap="round"/>
|
||||
<path d="M5 17 L15 17" fill="none" stroke="currentColor" stroke-width="1.25"/>
|
||||
<path d="M5.4 5.4 L7.8 5.4 L7.8 11.45 C7.8 13.57 8.6 14.38 10 14.38 C11.4 14.38 12.2 13.57 12.2 11.45 L12.2 5.4 L14.6 5.4 L14.6 11.66 C14.6 14.89 12.8 16.5 10 16.5 C7.2 16.5 5.4 14.89 5.4 11.66 Z M4.6 17.7 L15.4 17.7 L15.4 19.2 L4.6 19.2 Z" fill="currentColor"/>
|
||||
</svg>
|
||||
|
||||
|
Before Width: | Height: | Size: 352 B After Width: | Height: | Size: 356 B |
@@ -17,6 +17,8 @@ mod commands;
|
||||
mod control;
|
||||
mod files;
|
||||
pub(crate) use files::Closing;
|
||||
#[cfg(test)]
|
||||
pub(crate) use files::suggested_stem;
|
||||
pub(crate) mod fonts;
|
||||
mod frame;
|
||||
mod input;
|
||||
@@ -78,6 +80,7 @@ impl WordApp {
|
||||
dialog_hooks,
|
||||
dialog_answers,
|
||||
edits,
|
||||
edits_gesture,
|
||||
keytips_active,
|
||||
options_state,
|
||||
print,
|
||||
@@ -102,6 +105,8 @@ impl WordApp {
|
||||
command_catalog_lang: "",
|
||||
key_overrides: Default::default(),
|
||||
command_states: Default::default(),
|
||||
command_states_cache: None,
|
||||
keytip_cache: None,
|
||||
fonts_frames: 0,
|
||||
clipboard_published: false,
|
||||
printing: Default::default(),
|
||||
@@ -163,6 +168,7 @@ impl WordApp {
|
||||
dialog_hooks,
|
||||
dialog_answers,
|
||||
edits,
|
||||
edits_gesture,
|
||||
keytips_active,
|
||||
options_state,
|
||||
print,
|
||||
@@ -313,6 +319,7 @@ impl WordApp {
|
||||
pub fn logic(&mut self, ctx: &egui::Context) {
|
||||
let lang = i18n::Lang::from_pref(&self.ui.language);
|
||||
if self.ctx.is_none() {
|
||||
theme::set_dark_text_curve(ctx);
|
||||
self.ctx = Some(ctx.clone());
|
||||
}
|
||||
updates_ui::tick(self, ctx);
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
//! The app's side of the framework command runtime: the catalog of commands and their default
|
||||
//! chords, the per-frame state (enabled, checked, hint) and the running of what the runtime fired.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft::keymap::Overrides;
|
||||
use craft::ui::runtime::commands::CommandSet as _;
|
||||
use craft::ui::runtime::commands::{
|
||||
AppCatalog, Binding, CommandDef, CommandInput, CommandRef, CommandState, CommandStates, FireSource, Scope, TypingRule,
|
||||
};
|
||||
@@ -83,6 +84,69 @@ fn with_word_chords(catalog: AppCatalog) -> AppCatalog {
|
||||
.fold(catalog, |catalog, command| catalog.replace_defaults(command.id(), Vec::new()))
|
||||
}
|
||||
|
||||
/// Precomputed command references, translated hints, and last gate results for
|
||||
/// [`WordApp::command_input`], rebuilt when the engine registry or interface language changes.
|
||||
///
|
||||
/// Every command's gate predicate still runs on every frame so enabled/disabled state is never
|
||||
/// stale; only the per-frame `CATALOG.lines()` parsing, `i18n` hint formatting, and full
|
||||
/// `CommandStates` map rebuild are skipped when nothing changed.
|
||||
pub(crate) struct CommandStatesCache {
|
||||
registry: Arc<wordcraft_engine::Registry>,
|
||||
lang: &'static str,
|
||||
/// `(id, location, label, prebuilt CommandRef, last (enabled, reason))` for every registered
|
||||
/// engine command, in registry order.
|
||||
registered: Vec<(&'static str, &'static str, &'static str, CommandRef, Option<(bool, Option<&'static str>)>)>,
|
||||
/// `(id, prebuilt CommandRef, last enabled)` for gated `ui.*` commands.
|
||||
ui_commands: Vec<(&'static str, CommandRef, Option<bool>)>,
|
||||
/// `(id, prebuilt CommandRef, last enabled)` for unimplemented Word catalog commands.
|
||||
unimplemented: Vec<(&'static str, CommandRef, Option<bool>)>,
|
||||
/// Precomputed `CommandRef` and last enabled state for `ui.dialog {"name": "commands"}`.
|
||||
commands_dialog: (CommandRef, Option<bool>),
|
||||
/// Translated fallback hint shared by all unimplemented catalog commands.
|
||||
unavailable_hint: Option<Arc<str>>,
|
||||
/// Cached translated hints by `(spec index, disabled reason)` for the current language.
|
||||
hints: HashMap<(usize, Option<&'static str>), Option<Arc<str>>>,
|
||||
}
|
||||
|
||||
impl CommandStatesCache {
|
||||
fn new(registry: Arc<wordcraft_engine::Registry>, lang: &'static str) -> Self {
|
||||
let registered = registry.all().iter().map(|spec| (spec.id, spec.location, spec.label, CommandRef::new(spec.id), None)).collect();
|
||||
let ui_commands = ["ui.collapseRibbon", "ui.resetInterfaceSize", "ui.print", "ui.printSubmit"]
|
||||
.into_iter()
|
||||
.chain(GATED_UI_COMMANDS.iter().map(|(id, _)| *id))
|
||||
.map(|id| (id, CommandRef::new(id), None))
|
||||
.collect();
|
||||
let unimplemented = unimplemented_catalog_commands(®istry).map(|(id, _)| (id, CommandRef::new(id), None)).collect();
|
||||
let commands_dialog = (CommandRef::with_params("ui.dialog", json!({"name": "commands"})), None);
|
||||
let unavailable_hint = crate::widgets::command_hint("", "", Some("")).map(Arc::from);
|
||||
CommandStatesCache { registry, lang, registered, ui_commands, unimplemented, commands_dialog, unavailable_hint, hints: HashMap::new() }
|
||||
}
|
||||
|
||||
fn matches(&self, registry: &Arc<wordcraft_engine::Registry>, lang: &'static str) -> bool {
|
||||
self.lang == lang && Arc::ptr_eq(&self.registry, registry)
|
||||
}
|
||||
|
||||
fn hint_for(&mut self, idx: usize, location: &str, label: &str, reason: Option<&'static str>) -> Option<Arc<str>> {
|
||||
self.hints.entry((idx, reason)).or_insert_with(|| crate::widgets::command_hint(location, label, reason).map(Arc::from)).clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// Gate check for a command known to live in `app.session.registry` (skips the extra registry lookup).
|
||||
fn gate_registered(app: &WordApp, id: &str) -> (bool, Option<&'static str>) {
|
||||
if !app.has_document() && !super::commands::works_without_document(id) {
|
||||
return (false, None);
|
||||
}
|
||||
let reason = app.session.why_disabled(id);
|
||||
(reason.is_none(), reason)
|
||||
}
|
||||
|
||||
/// The framework edit commands the app's engine commands of the same id run through: the linked set owns their
|
||||
/// definition, the engine owns their chords.
|
||||
const LINKED_EDIT: [craft::ui::runtime::commands::EditCommands; 5] = {
|
||||
use craft::ui::runtime::commands::EditCommands::{Copy, Cut, Paste, Redo, Undo};
|
||||
[Cut, Copy, Paste, Undo, Redo]
|
||||
};
|
||||
|
||||
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
|
||||
@@ -115,7 +179,9 @@ impl WordApp {
|
||||
}
|
||||
defs.push(def);
|
||||
}
|
||||
for spec in registry.all().iter().filter(|spec| seen.insert(spec.id)) {
|
||||
// The framework's edit set defines Cut, Copy, Paste, Undo and Redo: a catalog def for them is shadowed (and
|
||||
// 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());
|
||||
for binding in default_bindings(spec.shortcut) {
|
||||
def = def.with_default(binding);
|
||||
@@ -135,6 +201,8 @@ impl WordApp {
|
||||
interface(CommandRef::new("ui.collapseRibbon"), "Collapse the Ribbon", "Mod+Alt+R");
|
||||
}
|
||||
interface(CommandRef::new("ui.resetInterfaceSize"), "Reset Interface Size", "Mod+Shift+0");
|
||||
// The File keytips fire it (one badge per page); without an entry it shows its id as its label.
|
||||
defs.push(CommandDef::new(CommandRef::new("ui.backstage"), tl!("File"), Scope::app()));
|
||||
for (id, label) in GATED_UI_COMMANDS {
|
||||
defs.push(CommandDef::new(CommandRef::new(*id), tl!(*label), Scope::app()));
|
||||
}
|
||||
@@ -148,6 +216,10 @@ impl WordApp {
|
||||
match AppCatalog::new(defs, generation) {
|
||||
Ok(catalog) => {
|
||||
let catalog = catalog.typing_rule(TypingRule::PlainKeysWait);
|
||||
let catalog = LINKED_EDIT.iter().fold(catalog, |catalog, command| {
|
||||
let chords = registry.get(command.id()).map(|spec| default_bindings(spec.shortcut).collect()).unwrap_or_default();
|
||||
catalog.replace_defaults(command.id(), chords)
|
||||
});
|
||||
self.command_catalog = Some((registry, with_word_chords(catalog)));
|
||||
}
|
||||
Err(error) => {
|
||||
@@ -177,36 +249,78 @@ impl WordApp {
|
||||
if let Some(catalog) = self.catalog() {
|
||||
input = input.catalog(catalog);
|
||||
}
|
||||
let mut states = CommandStates::new();
|
||||
for spec in registry.all() {
|
||||
let (enabled, reason) = gate(self, spec.id); // A toggle's checked state is bound at its ribbon button, not here.
|
||||
let mut state = CommandState::new().enabled(enabled);
|
||||
if let Some(hint) = crate::widgets::command_hint(spec.location, spec.label, reason) {
|
||||
state = state.hint(hint);
|
||||
let lang = crate::i18n::current().code();
|
||||
let (mut cache, fresh_cache) = match self.command_states_cache.take() {
|
||||
Some(cache) if cache.matches(®istry, lang) => (cache, false),
|
||||
_ => (CommandStatesCache::new(registry, lang), true),
|
||||
};
|
||||
|
||||
// Re-evaluate every command's gate without allocating on idle frames. A fresh cache has
|
||||
// `None` in every `last` slot, so the same compare pass collects every entry for it.
|
||||
let mut reg_changes: Vec<(usize, bool, Option<&'static str>)> = Vec::new();
|
||||
for (i, &(id, _, _, _, last)) in cache.registered.iter().enumerate() {
|
||||
let current = gate_registered(self, id);
|
||||
if last != Some(current) {
|
||||
reg_changes.push((i, current.0, current.1));
|
||||
}
|
||||
states.set(CommandRef::new(spec.id), state);
|
||||
}
|
||||
// Print acts on the document, so with none open it is off like the engine's commands (#1129); a command with
|
||||
// no state here resolves as enabled.
|
||||
let ids = ["ui.collapseRibbon", "ui.resetInterfaceSize", "ui.print", "ui.printSubmit"]
|
||||
.into_iter()
|
||||
.chain(GATED_UI_COMMANDS.iter().map(|(id, _)| *id));
|
||||
for id in ids {
|
||||
states.set(CommandRef::new(id), CommandState::new().enabled(command_enabled(self, id)));
|
||||
}
|
||||
let unavailable_hint: Option<Arc<str>> = crate::widgets::command_hint("", "", Some("")).map(Arc::from);
|
||||
for (id, _) in unimplemented_catalog_commands(®istry) {
|
||||
let mut state = CommandState::new().enabled(command_enabled(self, id));
|
||||
if let Some(hint) = unavailable_hint.as_ref() {
|
||||
state = state.hint(Arc::clone(hint));
|
||||
let mut ui_changes: Vec<(usize, bool)> = Vec::new();
|
||||
for (i, &(id, _, last)) in cache.ui_commands.iter().enumerate() {
|
||||
let enabled = command_enabled(self, id);
|
||||
if last != Some(enabled) {
|
||||
ui_changes.push((i, enabled));
|
||||
}
|
||||
states.set(CommandRef::new(id), state);
|
||||
}
|
||||
let commands = CommandRef::with_params("ui.dialog", json!({"name": "commands"}));
|
||||
states.set(commands, CommandState::new().enabled(command_enabled(self, "ui.dialog")));
|
||||
if *self.command_states != states {
|
||||
self.command_states.edit(|kept| *kept = states);
|
||||
let mut unimpl_changes: Vec<(usize, bool)> = Vec::new();
|
||||
for (i, &(id, _, last)) in cache.unimplemented.iter().enumerate() {
|
||||
let enabled = command_enabled(self, id);
|
||||
if last != Some(enabled) {
|
||||
unimpl_changes.push((i, enabled));
|
||||
}
|
||||
}
|
||||
let dialog_enabled = command_enabled(self, "ui.dialog");
|
||||
let dialog_changed = cache.commands_dialog.1 != Some(dialog_enabled);
|
||||
|
||||
let any_changed = !reg_changes.is_empty() || !ui_changes.is_empty() || !unimpl_changes.is_empty() || dialog_changed;
|
||||
if fresh_cache || any_changed {
|
||||
let apply = |kept: &mut CommandStates| {
|
||||
for (i, enabled, reason) in reg_changes {
|
||||
let (_, location, label, _, _) = cache.registered[i];
|
||||
cache.registered[i].4 = Some((enabled, reason));
|
||||
let mut state = CommandState::new().enabled(enabled);
|
||||
if let Some(hint) = cache.hint_for(i, location, label, reason) {
|
||||
state = state.hint(hint);
|
||||
}
|
||||
kept.set(cache.registered[i].3.clone(), state);
|
||||
}
|
||||
for (i, enabled) in ui_changes {
|
||||
cache.ui_commands[i].2 = Some(enabled);
|
||||
kept.set(cache.ui_commands[i].1.clone(), CommandState::new().enabled(enabled));
|
||||
}
|
||||
for (i, enabled) in unimpl_changes {
|
||||
cache.unimplemented[i].2 = Some(enabled);
|
||||
let mut state = CommandState::new().enabled(enabled);
|
||||
if let Some(hint) = cache.unavailable_hint.as_ref() {
|
||||
state = state.hint(Arc::clone(hint));
|
||||
}
|
||||
kept.set(cache.unimplemented[i].1.clone(), state);
|
||||
}
|
||||
if dialog_changed {
|
||||
cache.commands_dialog.1 = Some(dialog_enabled);
|
||||
kept.set(cache.commands_dialog.0.clone(), CommandState::new().enabled(dialog_enabled));
|
||||
}
|
||||
};
|
||||
if fresh_cache {
|
||||
let mut states = CommandStates::new();
|
||||
apply(&mut states);
|
||||
if *self.command_states != states {
|
||||
self.command_states.edit(|kept| *kept = states);
|
||||
}
|
||||
} else {
|
||||
self.command_states.edit(apply);
|
||||
}
|
||||
}
|
||||
self.command_states_cache = Some(cache);
|
||||
input.states(&self.command_states)
|
||||
}
|
||||
|
||||
@@ -230,6 +344,7 @@ impl WordApp {
|
||||
let mut host = std::mem::take(&mut self.edits);
|
||||
host.before_undo(ctx, self);
|
||||
self.edits = host;
|
||||
self.edits_gesture = None;
|
||||
}
|
||||
let result = if fired.source == FireSource::Automation { self.execute(id, params) } else { self.run(id, params) };
|
||||
if from_key && result.is_ok() {
|
||||
@@ -299,11 +414,13 @@ mod tests {
|
||||
app.run_fired(&ctx, &output);
|
||||
let after_undo = app.session.undo_depth();
|
||||
assert_eq!(after_undo + 1, before, "the gesture left no step, and Undo took the one from before it");
|
||||
assert!(app.edits_gesture.is_none(), "Undo clears running edit gesture state");
|
||||
|
||||
let mut end = EditEvents::new();
|
||||
end.push(EditEvent::commit(id, Mixed::Same(11.0_f32), 20.0_f32));
|
||||
crate::undo_marks::apply_edits(&mut app, end, apply);
|
||||
assert_eq!(app.session.undo_depth(), after_undo, "the late Commit of the taken-back gesture adds no step");
|
||||
assert!(app.edits_gesture.is_none());
|
||||
}
|
||||
|
||||
/// #7310: unimplemented Word feature catalog commands publish a disabled state so ribbon
|
||||
@@ -321,4 +438,64 @@ mod tests {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Cached `command_input()` keeps steady-state idle calls zero-change while immediately reflecting
|
||||
/// table/context transitions and document-open state changes.
|
||||
#[test]
|
||||
fn command_input_cache_tracks_state_transitions_and_is_noop_when_idle() {
|
||||
let mut app = WordApp::new(Session::new(wordcraft_doc::Document::new()), Default::default());
|
||||
let _ = app.command_input();
|
||||
let rev_after_first = app.command_states.revision();
|
||||
assert!(
|
||||
!app.command_states.get(&CommandRef::new("table.deleteRow")).unwrap().is_enabled(),
|
||||
"table.deleteRow starts disabled outside a table"
|
||||
);
|
||||
assert!(app.command_states.get(&CommandRef::new("format.bold")).unwrap().is_enabled(), "format.bold starts enabled");
|
||||
|
||||
// Repeated idle calls must not mutate `command_states` or bump its revision.
|
||||
for _ in 0..5 {
|
||||
let _ = app.command_input();
|
||||
}
|
||||
assert_eq!(app.command_states.revision(), rev_after_first, "idle frames leave command_states revision untouched");
|
||||
|
||||
// Entering a table enables `table.deleteRow` immediately on the next `command_input()`.
|
||||
app.run("insert.table", json!({"rows": 2, "cols": 2})).unwrap();
|
||||
let _ = app.command_input();
|
||||
let rev_after_table = app.command_states.revision();
|
||||
assert_ne!(rev_after_table, rev_after_first, "state change bumps command_states revision");
|
||||
assert!(app.command_states.get(&CommandRef::new("table.deleteRow")).unwrap().is_enabled(), "table.deleteRow is enabled inside a table");
|
||||
|
||||
// Closing the document disables document commands immediately.
|
||||
app.no_document = Some(app.session.document_id());
|
||||
let _ = app.command_input();
|
||||
assert!(!app.command_states.get(&CommandRef::new("format.bold")).unwrap().is_enabled(), "format.bold disables when no document is open");
|
||||
|
||||
// Dropping the cache and rebuilding from scratch must produce the exact same `CommandStates`.
|
||||
let incremental = (*app.command_states).clone();
|
||||
app.command_states_cache = None;
|
||||
let _ = app.command_input();
|
||||
assert_eq!(*app.command_states, incremental, "incremental cache matches full rebuild exactly");
|
||||
|
||||
// Swapping the registry rebuilds `command_states` cleanly and drops commands that are no
|
||||
// longer registered.
|
||||
app.no_document = None;
|
||||
let full_registry = app.session.registry.clone();
|
||||
app.session.registry = std::sync::Arc::new(wordcraft_engine::Registry::new(vec![wordcraft_engine::CommandSpec::new(
|
||||
"test.ephemeral",
|
||||
"Ephemeral",
|
||||
"Home",
|
||||
|_, _| Ok(json!({})),
|
||||
)]));
|
||||
let _ = app.command_input();
|
||||
assert!(
|
||||
app.command_states.get(&CommandRef::new("test.ephemeral")).is_some_and(|s| s.is_enabled()),
|
||||
"custom registry command is published when registered"
|
||||
);
|
||||
app.session.registry = full_registry;
|
||||
let _ = app.command_input();
|
||||
assert!(
|
||||
app.command_states.get(&CommandRef::new("test.ephemeral")).is_none(),
|
||||
"swapping back to the default registry clears removed commands from command_states"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use craft::host::{PickId, Picked};
|
||||
use craft::platform::open::{DropTarget, DroppedFile, Intake};
|
||||
use craft::platform::open::{DroppedFile, Intake};
|
||||
use craft::quit::{CloseAnswer, CloseGuard, CloseScope, GuardStep};
|
||||
use craft::ui::dialog::{DialogId, DialogResult, UnsavedChangesDialog};
|
||||
use craft::ui::shell::embed::CloseDecision;
|
||||
@@ -181,6 +181,7 @@ impl WordApp {
|
||||
/// Close prompt `id` from outside and drop the answer that leaves behind.
|
||||
pub(crate) fn close_prompt(&mut self, id: DialogId) {
|
||||
if let Some(ctx) = self.ctx.clone() {
|
||||
crate::dialogs::chrome::forget_nudge(&ctx, id);
|
||||
self.dialog_host.cancel_by_id(&ctx, id);
|
||||
}
|
||||
let _ = self.dialog_host.take_by_id::<UnsavedChangesDialog>(id);
|
||||
@@ -191,6 +192,9 @@ impl WordApp {
|
||||
pub(crate) fn pump_close_prompt(&mut self) {
|
||||
let Some(id) = self.closing.as_ref().and_then(|c| c.prompt) else { return };
|
||||
let Some(result) = self.dialog_host.take_by_id::<UnsavedChangesDialog>(id) else { return };
|
||||
if let Some(ctx) = self.ctx.as_ref() {
|
||||
crate::dialogs::chrome::forget_nudge(ctx, id);
|
||||
}
|
||||
if let Some(closing) = self.closing.as_mut() {
|
||||
closing.prompt = None;
|
||||
}
|
||||
@@ -329,7 +333,7 @@ impl WordApp {
|
||||
// A save that never reached its destination leaves no stamp of it, when the document is as
|
||||
// the save left it (an edit since keeps its own marks and stays unsaved).
|
||||
let mut undone = false;
|
||||
if !matches!(picked, Picked::Paths(_) | Picked::Downloaded(_))
|
||||
if !matches!(picked, Picked::Paths(_) | Picked::Saved { .. } | Picked::Downloaded(_))
|
||||
&& save.document == current
|
||||
&& save.rev == self.session.rev()
|
||||
&& let Some(undo) = save.undo_stamp.take()
|
||||
@@ -338,7 +342,7 @@ impl WordApp {
|
||||
undone = true;
|
||||
}
|
||||
// A download the browser accepted is a finished save too: the page holds no file of it.
|
||||
if matches!(picked, Picked::Paths(_) | Picked::Downloaded(_)) {
|
||||
if matches!(picked, Picked::Paths(_) | Picked::Saved { .. } | Picked::Downloaded(_)) {
|
||||
log::info!("saved {} through the save picker", save.name);
|
||||
// The page now holds the document as that file (a hosted Save As or first Save, S-L159):
|
||||
// the next Save goes back to it. A download names nothing the app could reopen.
|
||||
@@ -381,12 +385,14 @@ impl WordApp {
|
||||
}
|
||||
let result = match picked {
|
||||
// Only when nothing changed since and no later save of it is still unconfirmed.
|
||||
Picked::Paths(_) | Picked::Downloaded(_) if !self.session.dirty && self.session.rev() == save.rev && !self.save_unconfirmed() => {
|
||||
Picked::Paths(_) | Picked::Saved { .. } | Picked::Downloaded(_)
|
||||
if !self.session.dirty && self.session.rev() == save.rev && !self.save_unconfirmed() =>
|
||||
{
|
||||
let step = self.with_guard(|g| g.saved());
|
||||
self.drive_guard(step, None)
|
||||
}
|
||||
// Edited while the picker was open (those edits may not be written yet): ask again.
|
||||
Picked::Paths(_) | Picked::Downloaded(_) => {
|
||||
Picked::Paths(_) | Picked::Saved { .. } | Picked::Downloaded(_) => {
|
||||
let step = self.with_guard(|g| g.retry_after_failure());
|
||||
self.drive_guard(step, None)
|
||||
}
|
||||
@@ -632,7 +638,7 @@ impl WordApp {
|
||||
let Some(intake) = self.services.intake.as_ref() else { return };
|
||||
for item in intake.take() {
|
||||
match item {
|
||||
Intake::Dropped { files, target } => self.open_dropped(&files, target),
|
||||
Intake::Dropped { files } => self.open_dropped(&files),
|
||||
Intake::Open(paths) | Intake::OpenFor { paths, .. } => {
|
||||
for p in paths {
|
||||
// A path that is not Unicode cannot be passed on as text: skipped.
|
||||
@@ -664,7 +670,7 @@ impl WordApp {
|
||||
/// Route files dropped on the window, in drop order: the one place the drop rules live. A drop
|
||||
/// behind a modal dialog does nothing, since it would insert a picture or open a document
|
||||
/// under it. Every drop target routes by file kind, so `_target` does not change the routing.
|
||||
pub(crate) fn open_dropped(&mut self, files: &[DroppedFile], _target: DropTarget) {
|
||||
pub(crate) fn open_dropped(&mut self, files: &[DroppedFile]) {
|
||||
if self.modal_open() {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -151,11 +151,19 @@ impl WordApp {
|
||||
// PLAN: assumed `updates_ui::run(app: &mut WordApp)` (shell-w13, sh.A20) opens the updater's dialogs on the host.
|
||||
updates_ui::run(self);
|
||||
crate::dialogs::host::prepare(self);
|
||||
let had_dialogs = !self.dialog_host.is_empty();
|
||||
self.dialog_host.run(ui);
|
||||
crate::dialogs::host::settle(self, ctx);
|
||||
crate::dialogs::chrome::apply_modal_nudge(self, ui);
|
||||
if moved(self) {
|
||||
return;
|
||||
}
|
||||
if had_dialogs && self.dialog_host.is_empty() && !self.file_dialog_open() && !self.ui.backstage {
|
||||
self.canvas.focus_page(ctx);
|
||||
self.canvas.focus_pending = true;
|
||||
self.canvas.focus_page_after_pass();
|
||||
ctx.request_repaint();
|
||||
}
|
||||
self.refocus_after_chrome_click(ctx, regions);
|
||||
if let Some(url) = self.canvas.open_url.take() {
|
||||
ctx.open_url(egui::OpenUrl::new_tab(url));
|
||||
|
||||
@@ -176,7 +176,7 @@ pub(crate) fn show(ui: &mut Ui, cx: &mut BodyCx<'_>, app: &mut WordApp) {
|
||||
match command {
|
||||
BackstagePageCommand::Back => {
|
||||
let _ = app.run("ui.backstage", json!({"value": false}));
|
||||
app.canvas.focus_page(&ctx);
|
||||
app.canvas.focus_page_after_pass();
|
||||
}
|
||||
// PLAN: `print_requested(app, ctx)` is chrome-w10's new `pub(crate)` fn in print_page.rs (S-L263).
|
||||
BackstagePageCommand::Print if app.ui.backstage_page == "print" => crate::print_page::print_requested(app, &ctx),
|
||||
@@ -209,7 +209,7 @@ pub(crate) fn show(ui: &mut Ui, cx: &mut BodyCx<'_>, app: &mut WordApp) {
|
||||
});
|
||||
});
|
||||
if let Some(id) = choice.page.take() {
|
||||
go_to_page(app, id, &ctx);
|
||||
go_to_page(app, id);
|
||||
}
|
||||
if choice.about.get() {
|
||||
let _ = crate::dialogs::open(app, "about", &json!({}));
|
||||
@@ -250,7 +250,8 @@ 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);
|
||||
@@ -309,7 +310,7 @@ fn page_rows(ui: &mut Ui, current: &str, has_document: bool, choice: &MenuChoice
|
||||
let on = has_document || works_without_document(id);
|
||||
let row = Button::new(label(name))
|
||||
.id_salt(("backstage-page", id))
|
||||
.icon(crate::icons::id(icon))
|
||||
.icon(crate::icons::spec(icon))
|
||||
.variant(Variant::GHOST)
|
||||
.sizing(Sizing::FillWidth)
|
||||
// Icon and name at the reading start of the full-width row, as production's menu.
|
||||
@@ -325,7 +326,7 @@ fn page_rows(ui: &mut Ui, current: &str, has_document: bool, choice: &MenuChoice
|
||||
|
||||
/// Opens a side-menu page, as a click on it (or its keytip) does. Without a document only the
|
||||
/// pages that work without one open.
|
||||
pub(crate) fn go_to_page(app: &mut WordApp, id: &str, ctx: &egui::Context) {
|
||||
pub(crate) fn go_to_page(app: &mut WordApp, id: &str) {
|
||||
if !app.has_document() && !works_without_document(id) {
|
||||
return;
|
||||
}
|
||||
@@ -340,7 +341,7 @@ pub(crate) fn go_to_page(app: &mut WordApp, id: &str, ctx: &egui::Context) {
|
||||
let r = app.run("file.save", json!({}));
|
||||
if r.is_ok_and(|v| v.get("saved").and_then(serde_json::Value::as_bool) == Some(true) || v.get("downloaded").is_some()) {
|
||||
app.ui.backstage = false;
|
||||
app.canvas.focus_page(ctx);
|
||||
app.canvas.focus_page_after_pass();
|
||||
} else {
|
||||
app.ui.backstage_page = "saveAs".into();
|
||||
}
|
||||
@@ -391,10 +392,10 @@ fn matching_personal(query: &str, list: &[PersonalTemplate]) -> Vec<PersonalTemp
|
||||
|
||||
/// Make a new document from the personal template at `path` and close File; a template that
|
||||
/// can't be read keeps File open so the gallery can say why.
|
||||
fn open_personal(app: &mut WordApp, path: &str, ctx: &egui::Context) -> Result<(), String> {
|
||||
fn open_personal(app: &mut WordApp, path: &str) -> Result<(), String> {
|
||||
app.run("file.newFromTemplate", json!({"path": path}))?;
|
||||
app.ui.backstage = false;
|
||||
app.canvas.focus_page(ctx);
|
||||
app.canvas.focus_page_after_pass();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -30,7 +30,7 @@ pub(super) fn template_cards(list: &[(&str, &str)]) -> Vec<Template> {
|
||||
|
||||
/// Runs what the user did on a start screen or recent list. A failed open stays on the page as its
|
||||
/// error (`BackstageState::open_error`); a later success clears it.
|
||||
fn run_actions(app: &mut WordApp, ctx: &egui::Context, actions: Vec<StartAction>) {
|
||||
fn run_actions(app: &mut WordApp, actions: Vec<StartAction>) {
|
||||
for action in actions {
|
||||
match action {
|
||||
StartAction::New | StartAction::MoreTemplates => app.ui.backstage_page = "new".into(),
|
||||
@@ -40,7 +40,7 @@ fn run_actions(app: &mut WordApp, ctx: &egui::Context, actions: Vec<StartAction>
|
||||
StartAction::OpenRecent(path) => {
|
||||
let failed = open_recent(app, &path.to_string_lossy()).err();
|
||||
if failed.is_none() {
|
||||
app.canvas.focus_page(ctx);
|
||||
app.canvas.focus_page_after_pass();
|
||||
}
|
||||
app.backstage_state.open_error = failed;
|
||||
}
|
||||
@@ -53,7 +53,7 @@ fn run_actions(app: &mut WordApp, ctx: &egui::Context, actions: Vec<StartAction>
|
||||
StartAction::UseTemplate(id) => {
|
||||
let _ = app.run("file.new", json!({"template": id}));
|
||||
app.ui.backstage = false;
|
||||
app.canvas.focus_page(ctx);
|
||||
app.canvas.focus_page_after_pass();
|
||||
}
|
||||
// Pins, folders and reveal are not part of File.
|
||||
_ => {}
|
||||
@@ -84,6 +84,9 @@ pub(super) fn home(ui: &mut Ui, app: &mut WordApp) {
|
||||
let (mut view, mut sort) = (RecentView::List, RecentSort::Opened);
|
||||
let out = StartScreen::new(Bind::bound(&mut view), Bind::bound(&mut sort), &recent)
|
||||
.layout(StartLayout::Greeting)
|
||||
// The File rail beside the page has New and Open; production's Home had no second pair.
|
||||
.offers_new(false)
|
||||
.offers_open(false)
|
||||
.title(label(greeting))
|
||||
.templates(&cards)
|
||||
.more_templates(label("More templates →"))
|
||||
@@ -93,12 +96,11 @@ pub(super) fn home(ui: &mut Ui, app: &mut WordApp) {
|
||||
.page_paper(DataColor::new(Color32::WHITE))
|
||||
.thumbnails(&store, &source)
|
||||
.show(ui);
|
||||
run_actions(app, &ctx, out.actions);
|
||||
run_actions(app, out.actions);
|
||||
}
|
||||
|
||||
/// Open: Browse for a file, then the recent documents.
|
||||
pub(super) fn open(ui: &mut Ui, app: &mut WordApp) {
|
||||
let ctx = ui.ctx().clone();
|
||||
heading(ui, "Open");
|
||||
if clicked(&Button::new(label("Browse…")).id_salt("open-browse").show(ui)) {
|
||||
let _ = app.run("ui.openFileDialog", json!({}));
|
||||
@@ -119,5 +121,5 @@ pub(super) fn open(ui: &mut Ui, app: &mut WordApp) {
|
||||
}
|
||||
let recent = recent_files(app);
|
||||
let out = RecentList::new(&recent).max_recent(app.ui.recent_shown()).empty(label("Documents you open will show up here.")).show(ui);
|
||||
run_actions(app, &ctx, out.actions);
|
||||
run_actions(app, out.actions);
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
use craft::behavior::{IconId, keyed};
|
||||
use craft::behavior::keyed;
|
||||
use craft::theme::variant::Tone;
|
||||
use craft::ui::buttons::Button;
|
||||
use craft::ui::contract::{
|
||||
@@ -12,7 +12,7 @@ use craft::ui::contract::{
|
||||
use craft::ui::layout_components::Stack;
|
||||
use craft::ui::list::ThumbAspect;
|
||||
use craft::ui::notices::Notice;
|
||||
use craft::ui::primitives::{ContentPainterCx, IconSpec};
|
||||
use craft::ui::primitives::ContentPainterCx;
|
||||
use craft::ui::runtime::env::Label;
|
||||
use craft::ui::shell::{Template, ThumbKey};
|
||||
use craft::ui::style::DataColor;
|
||||
@@ -64,7 +64,7 @@ fn read_listing(app: &WordApp) -> PersonalListing {
|
||||
pub(super) fn paint_personal_card(cx: &ContentPainterCx, rect: Rect) {
|
||||
cx.data_shapes([Shape::rect_filled(rect, 2.0, Color32::WHITE)]);
|
||||
let icon_rect = Rect::from_center_size(rect.center(), vec2(44.0, 44.0));
|
||||
cx.icon(icon_rect, &IconSpec::svg(IconId::new("documentTemplate")).data_color(DataColor::new(Color32::from_gray(150))));
|
||||
cx.icon(icon_rect, &crate::icons::spec("documentTemplate").data_color(DataColor::new(Color32::from_gray(150))));
|
||||
}
|
||||
|
||||
/// New: the whole template gallery with a search box, then the personal templates (#2852); no
|
||||
@@ -112,7 +112,7 @@ pub(super) fn show(ui: &mut Ui, app: &mut WordApp) {
|
||||
for id in activated(out.response.events) {
|
||||
let _ = app.run("file.new", json!({"template": id}));
|
||||
app.ui.backstage = false;
|
||||
app.canvas.focus_page(&ctx);
|
||||
app.canvas.focus_page_after_pass();
|
||||
}
|
||||
}
|
||||
// Personal: the user templates folder's templates; a folder per category, as in Word.
|
||||
@@ -147,7 +147,7 @@ pub(super) fn show(ui: &mut Ui, app: &mut WordApp) {
|
||||
Tile::new(Label::from(p.label.clone())).thumb(ThumbAspect::new(PAGE_WIDE, PAGE_HIGH), paint_personal_card).tooltip(p.path.clone())
|
||||
});
|
||||
for path in activated(out.response.events) {
|
||||
let failed = open_personal(app, &path, &ctx).err();
|
||||
let failed = open_personal(app, &path).err();
|
||||
app.backstage_state.personal_error = failed;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
use craft::i18n::Direction;
|
||||
use craft::ui::buttons::Button;
|
||||
use craft::ui::choice::Checkbox;
|
||||
use craft::ui::contract::{Bind, Gap, Props as _, Show as _, ShowContainer as _, Sizing, clicked};
|
||||
use craft::ui::contract::{Bind, Gap, LeastWidth, Props as _, Show as _, ShowContainer as _, Sizing, clicked};
|
||||
use craft::ui::display::Text;
|
||||
use craft::ui::form::{Field, FieldGroup};
|
||||
use craft::ui::layout_components::{Row, Stack};
|
||||
@@ -16,7 +16,6 @@ use crate::WordApp;
|
||||
|
||||
/// Recovery is a separate copy. Leaving this page never discards it.
|
||||
pub(super) fn recovery(ui: &mut Ui, app: &mut WordApp) {
|
||||
let ctx = ui.ctx().clone();
|
||||
heading(ui, "Recover documents");
|
||||
let _ = Text::new(label("Restore opens an unsaved copy. Your original file stays unchanged.")).show(ui);
|
||||
if app.session.password.is_some() {
|
||||
@@ -48,7 +47,7 @@ pub(super) fn recovery(ui: &mut Ui, app: &mut WordApp) {
|
||||
let _ = Row::new().gap(Gap::Tight).show(ui, |ui, _| {
|
||||
if clicked(&Button::new(label("Continue without restoring")).id_salt("recover-continue").show(ui)) {
|
||||
let _ = app.run("ui.backstage", json!({"value": false}));
|
||||
app.canvas.focus_page(&ctx);
|
||||
app.canvas.focus_page_after_pass();
|
||||
}
|
||||
if clicked(&Button::new(label("Refresh")).id_salt("recover-refresh").enabled(!busy && app.session.recovery_ready()).show(ui)) {
|
||||
let _ = app.run("file.recover", json!({"refresh": true}));
|
||||
@@ -209,5 +208,9 @@ pub(super) fn export(ui: &mut Ui, app: &mut WordApp) {
|
||||
}
|
||||
heading(ui, "Export");
|
||||
let _ = Text::new(label("Save a copy in another format. Printing goes through a PDF you can print from any viewer.")).show(ui);
|
||||
crate::print_page::export_formats(app, ui);
|
||||
// The Print page's settings column: the format buttons fill it, not the page (as production's 320 pt rows).
|
||||
// The row keeps the page's width from reaching the column, so the column is as wide as its least width.
|
||||
let _ = Row::new().show(ui, |ui, _| {
|
||||
let _ = Stack::new().least_width(LeastWidth::Dialog).gap(Gap::Stack).show(ui, |ui, _| crate::print_page::export_formats(app, ui));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -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:?}");
|
||||
}
|
||||
|
||||
@@ -892,3 +894,50 @@ fn file_open_recent_list_has_no_thumbnail_letterboxing() {
|
||||
let row = recent_row(&h2, "sample.docx").expect("recent row renders");
|
||||
assert!(row.rect().height() > 0.0, "recent row has non-zero height: {:?}", row.rect());
|
||||
}
|
||||
|
||||
/// #2931: File › New › Blank document with a document open returns to the editor without
|
||||
/// AccessKit losing the focused node; and so does Home's Blank document tile and Escape.
|
||||
#[test]
|
||||
fn blank_document_from_the_file_page_with_accessibility_on() {
|
||||
let work = || {
|
||||
let a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::from_text("Work")), Services::default());
|
||||
harness(a, egui::vec2(1440.0, 900.0))
|
||||
};
|
||||
for page in ["new", "home"] {
|
||||
// A fresh "Work" document each time, so each path must really make a blank one.
|
||||
let mut h = work();
|
||||
h.state_mut().run("ui.backstage", json!({"value": true, "page": page})).unwrap();
|
||||
h.run_steps(4);
|
||||
h.get_by_label("Blank document").click();
|
||||
h.run_steps(4);
|
||||
assert!(!h.state().ui.backstage, "{page}: Blank document returns to the editor");
|
||||
assert_eq!(h.state().session.doc.plain_text(wordcraft_doc::StoryRef::Body), "", "{page}: a new blank document");
|
||||
assert!(h.state().dialog_host.is_empty(), "{page}: nothing asks first");
|
||||
}
|
||||
let mut h = work();
|
||||
h.state_mut().run("ui.backstage", json!({"value": true})).unwrap();
|
||||
h.run_steps(4);
|
||||
h.get_by_label("Back").click();
|
||||
h.run_steps(4);
|
||||
assert!(!h.state().ui.backstage, "the Back button closes the File page");
|
||||
assert_eq!(h.state().session.doc.plain_text(wordcraft_doc::StoryRef::Body), "Work", "Back keeps the document");
|
||||
}
|
||||
|
||||
/// #3041: clicking the plain sidebar background next to the back arrow must not also close
|
||||
/// the File page — only the button itself does (#2972, #3041).
|
||||
#[test]
|
||||
fn clicking_beside_the_back_arrow_does_not_close_the_file_page() {
|
||||
let a = new_app();
|
||||
let mut h = harness(a, egui::vec2(1440.0, 900.0));
|
||||
h.state_mut().run("ui.backstage", json!({"value": true})).unwrap();
|
||||
h.run_steps(4);
|
||||
assert!(h.state().ui.backstage, "File page opened");
|
||||
let back = h.get_by_label("Back").rect();
|
||||
// Well clear of the back button but still inside the side menu rail.
|
||||
let beside = egui::pos2(back.max.x + 50.0, back.center().y);
|
||||
h.event(egui::Event::PointerMoved(beside));
|
||||
h.event(egui::Event::PointerButton { pos: beside, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE });
|
||||
h.event(egui::Event::PointerButton { pos: beside, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE });
|
||||
h.run_steps(4);
|
||||
assert!(h.state().ui.backstage, "clicking beside the arrow leaves the File page open");
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ use std::cell::Cell;
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft::behavior::intent::EditCommand;
|
||||
use craft::behavior::kurbo::{Point, Size};
|
||||
use craft::pages::layout::{Fit, LayoutOptions, PageDisplay, SCREEN_POINTS_PER_POINT};
|
||||
use craft::pages::ui::reading::{ReadingMetrics, reading_size};
|
||||
@@ -17,7 +18,7 @@ use craft::ui::canvas::{Autoscroll, ContextSource, MiddleButton, NavigationOptio
|
||||
use craft::ui::contract::Show as _;
|
||||
|
||||
use craft::ui::runtime::env::Env;
|
||||
use craft::ui::runtime::focus::{self, FocusTarget};
|
||||
use craft::ui::runtime::focus::{self, EditSet, FocusTarget};
|
||||
use craft::ui::style::DataColor;
|
||||
use egui::{Color32, Pos2, Rect, Ui, pos2, vec2};
|
||||
use serde_json::json;
|
||||
@@ -644,7 +645,7 @@ fn sync_view_state(app: &WordApp, state: &mut PageViewState) {
|
||||
// A wheel or pinch zoom is the view's own, anchored at the pointer, and reaches the session rounded to a whole
|
||||
// percent (`show_pages`): the view keeps its exact zoom while it rounds to the session's, or the rounding would
|
||||
// move the place under the pointer on the next pass.
|
||||
let session_zoom = f64::from(v.zoom.clamp(0.1, 5.0));
|
||||
let session_zoom = f64::from(if v.zoom.is_finite() { v.zoom.clamp(0.1, 5.0) } else { 1.0 });
|
||||
if (state.zoom * 100.0).round() != (session_zoom * 100.0).round() {
|
||||
state.zoom = session_zoom;
|
||||
}
|
||||
@@ -715,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;
|
||||
@@ -808,12 +818,19 @@ fn show_pages(app: &mut WordApp, ui: &mut Ui, layout: &Arc<DocLayout>, full: Rec
|
||||
let mut fix = ScrollFix::default();
|
||||
// The caret the follow wants whose page the pass did not place: its page, the page's height and the caret.
|
||||
let mut unplaced = None;
|
||||
// The page answers for the linked Cut and Copy while it has focus: with nothing selected they are inactive, so the
|
||||
// ribbon, the context menu and the command search grey them as production did.
|
||||
let inactive_edits = [(EditCommand::Cut, "edit.cut"), (EditCommand::Copy, "edit.copy")]
|
||||
.into_iter()
|
||||
.filter(|(_, id)| !crate::app::command_board::command_enabled(app, id))
|
||||
.fold(EditSet::NONE, |set, (command, _)| set.with(command));
|
||||
let out = PageView::new(tl!("Document"), &source, &mut state, paper)
|
||||
.options(options)
|
||||
// Hide White Space cuts each page to its text area: without the bodies the pages show whole.
|
||||
.bodies(&bodies)
|
||||
.navigation(navigation_options())
|
||||
.editor(craft::ui::primitives::EditorPurpose::Text)
|
||||
.inactive_edits(inactive_edits)
|
||||
.rulers(show_rulers)
|
||||
.snap(crate::objects::snap(app, layout))
|
||||
.tool_regions(regions)
|
||||
|
||||
@@ -67,7 +67,7 @@ pub(crate) fn show(app: &mut WordApp, ui: &mut Ui, opener: &Response, ask: Optio
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
if !open {
|
||||
if !open || app.modal_open() {
|
||||
app.canvas.context_menu_open = false;
|
||||
app.canvas.context_menu_at = None;
|
||||
return;
|
||||
@@ -107,7 +107,8 @@ pub(crate) fn show(app: &mut WordApp, ui: &mut Ui, opener: &Response, ask: Optio
|
||||
/// A row labelled `label` that runs command `id` with `params`; its chord, enabled state and
|
||||
/// action come from the command, its wording from the menu (one command id serves several rows).
|
||||
fn item(ui: &mut Ui, label: &str, id: &str, params: Value) {
|
||||
let _ = MenuItem::new(tl!(label).to_string()).command(CommandRef::with_params(id, params)).show(ui);
|
||||
// `MenuItem::command`, not `new(..).command(..)`: only the row's own binding shows the command's chord.
|
||||
let _ = MenuItem::command(CommandRef::with_params(id, params)).label(tl!(label).to_string()).show(ui);
|
||||
}
|
||||
|
||||
fn rule(ui: &mut Ui) {
|
||||
|
||||
@@ -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,66 @@ 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]
|
||||
fn caret_colour_is_not_worked_out_while_the_caret_is_hidden() {
|
||||
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::from_text("Hello WordCraft")), Default::default());
|
||||
a.run("select.text", json!({"text": "Hello"})).unwrap();
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|
||||
|ui, app: &mut WordApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
a,
|
||||
);
|
||||
h.run_steps(4);
|
||||
assert!(h.state().canvas.caret_bg.is_none(), "no caret, no colour lookup");
|
||||
}
|
||||
|
||||
/// Show revisions in balloons: a document whose only revision is a deletion gets the markup
|
||||
/// area for its balloon; the other modes have nothing to show there, and neither does the view
|
||||
/// while the Comments pane is open.
|
||||
@@ -2301,3 +2361,126 @@ fn a_linked_text_box_shows_and_follows_its_link_from_inside() {
|
||||
let (start, _) = wordcraft_engine::cmd::insert::bookmark_range(&s.doc, "Spot").unwrap();
|
||||
assert!(s.sel.is_collapsed() && s.sel.focus == start, "the caret went to the bookmark: {:?}", s.sel);
|
||||
}
|
||||
|
||||
/// Unit-level checks for #7742 (`hostile_numbers_are_ignored` logic): invalid `ScrollSpeed`
|
||||
/// codes, non-finite framework wheel/ease inputs, out-of-range `view.zoom` commands, and
|
||||
/// `sync_view_state` recovery from non-finite `session.view.zoom`.
|
||||
#[test]
|
||||
fn hostile_scroll_and_zoom_logic_is_ignored() {
|
||||
use crate::scroll::ScrollSpeed;
|
||||
use craft::behavior::{Wheel, WheelEase, WheelPhase, WheelUnit};
|
||||
use craft::keymap::{Mods, Platform};
|
||||
use craft::ui::canvas::{NavigationOptions, WheelInput, WheelNavigation};
|
||||
use egui::Vec2;
|
||||
|
||||
for bad in ["", "warp", "NaN", "infinity"] {
|
||||
assert_eq!(ScrollSpeed::from_code(bad), None);
|
||||
assert_eq!(ScrollSpeed::from(bad.to_string()), ScrollSpeed::Normal);
|
||||
}
|
||||
for speed in ScrollSpeed::ALL {
|
||||
assert!(speed.wheel_factor().is_finite() && speed.wheel_factor() > 0.0);
|
||||
assert!(speed.touchpad_factor().is_finite() && speed.touchpad_factor() > 0.0);
|
||||
}
|
||||
|
||||
let mut nav_wheel = WheelNavigation::default();
|
||||
let opts = NavigationOptions::default();
|
||||
let wheel_input = |scroll: Vec2, zoom: f32| {
|
||||
WheelInput::of(&Wheel::new(scroll, Mods::NONE, WheelUnit::Point, WheelPhase::Move).zoom(zoom), 16.0, Platform::current())
|
||||
};
|
||||
assert!(nav_wheel.classify(wheel_input(Vec2::new(f32::NAN, f32::INFINITY), 1.0), &opts).is_none());
|
||||
assert!(nav_wheel.classify(wheel_input(Vec2::new(0.0, f32::NEG_INFINITY), 1.0), &opts).is_none());
|
||||
for bad_zoom in [f32::NAN, f32::INFINITY, 0.0, -1.0] {
|
||||
assert!(nav_wheel.classify(wheel_input(Vec2::ZERO, bad_zoom), &opts).is_none());
|
||||
}
|
||||
|
||||
let mut ease = WheelEase::default();
|
||||
ease.feed(Vec2::new(f32::NAN, f32::INFINITY), 1.0);
|
||||
ease.feed(Vec2::new(0.0, -30.0), f64::NAN);
|
||||
assert!(!ease.owes());
|
||||
ease.feed(Vec2::new(0.0, -30.0), 1.0);
|
||||
assert_eq!(ease.step(f64::NAN), Vec2::ZERO);
|
||||
assert!(!ease.owes());
|
||||
|
||||
let mut app = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
|
||||
for bad_cmd in [json!({"value": -10.0}), json!({"value": 1e30}), json!({"value": "warp"})] {
|
||||
assert!(app.run("view.zoom", bad_cmd).is_err());
|
||||
}
|
||||
|
||||
let mut state = PageViewState::default();
|
||||
state.zoom = 1.5;
|
||||
for bad_zoom in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
|
||||
app.session.view.zoom = bad_zoom;
|
||||
sync_view_state(&app, &mut state);
|
||||
assert_eq!(state.zoom, 1.0, "non-finite session zoom {bad_zoom:?} falls back to 1.0");
|
||||
}
|
||||
app.session.view.zoom = 1.25;
|
||||
sync_view_state(&app, &mut state);
|
||||
assert_eq!(state.zoom, 1.25);
|
||||
}
|
||||
|
||||
/// Restored from pre-#7101 `scroll::tests::hostile_numbers_are_ignored` (#7317) against the
|
||||
/// post-#7101 `ScrollSpeed` + `PageView` canvas wheel/zoom pipeline: hostile zoom/rotation
|
||||
/// events, extreme finite wheel deltas, and non-finite view state are ignored or bounded
|
||||
/// without poisoning `offset` or `zoom`.
|
||||
#[test]
|
||||
fn hostile_numbers_are_ignored() {
|
||||
use egui::{Event, Modifiers, MouseWheelSource, MouseWheelUnit, TouchPhase, Vec2};
|
||||
|
||||
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
|
||||
a.run("text.insert", json!({"text": "Page text"})).unwrap();
|
||||
a.run("layout.break", json!({"kind": "page"})).unwrap();
|
||||
a.run("view.commentsPane", json!({"value": false})).unwrap();
|
||||
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).with_step_dt(1.0 / 60.0).build_eframe(|_| a);
|
||||
h.run_steps(2);
|
||||
|
||||
let at = h.state().canvas.shown.rect.center();
|
||||
let wheel = |unit, delta, modifiers, source| Event::MouseWheel { unit, delta, phase: TouchPhase::Move, modifiers, source };
|
||||
let finite_view = |app: &WordApp| {
|
||||
let v = &app.canvas.view;
|
||||
v.offset.0.is_finite() && v.offset.1.is_finite() && v.zoom.is_finite() && v.zoom > 0.0 && app.session.view.zoom.is_finite()
|
||||
};
|
||||
|
||||
let start_offset = h.state().canvas.view.offset;
|
||||
let start_zoom = h.state().canvas.view.zoom;
|
||||
|
||||
// Hostile zoom and rotation events over the canvas are ignored.
|
||||
h.event(Event::PointerMoved(at));
|
||||
for bad in [
|
||||
Event::Zoom(f32::NAN),
|
||||
Event::Zoom(f32::INFINITY),
|
||||
Event::Zoom(0.0),
|
||||
Event::Zoom(-1.0),
|
||||
Event::Rotate(f32::NAN),
|
||||
Event::Rotate(f32::INFINITY),
|
||||
] {
|
||||
h.event(bad);
|
||||
}
|
||||
h.run_steps(1);
|
||||
assert!(finite_view(h.state()));
|
||||
assert_eq!(h.state().canvas.view.offset, start_offset);
|
||||
assert_eq!(h.state().canvas.view.zoom, start_zoom);
|
||||
|
||||
// Normal touchpad input scrolls down cleanly after hostile events.
|
||||
h.event(wheel(MouseWheelUnit::Point, Vec2::new(0.0, -30.0), Modifiers::NONE, MouseWheelSource::Trackpad));
|
||||
h.run_steps(1);
|
||||
let scrolled_offset = h.state().canvas.view.offset;
|
||||
assert!(scrolled_offset.1 > start_offset.1, "normal wheel input scrolls down: {scrolled_offset:?} vs {start_offset:?}");
|
||||
|
||||
// Huge finite deltas in both point and line units stay finite and clamped to document bounds.
|
||||
h.event(wheel(MouseWheelUnit::Point, Vec2::new(0.0, -1e30), Modifiers::NONE, MouseWheelSource::Trackpad));
|
||||
h.run_steps(1);
|
||||
assert!(finite_view(h.state()));
|
||||
assert!(h.state().canvas.view.offset.1.abs() < 1e6, "offset stays clamped to document bounds: {:?}", h.state().canvas.view.offset);
|
||||
|
||||
h.event(wheel(MouseWheelUnit::Line, Vec2::new(0.0, 1e30), Modifiers::NONE, MouseWheelSource::Wheel));
|
||||
h.run_steps(1);
|
||||
assert!(finite_view(h.state()));
|
||||
assert!(h.state().canvas.view.offset.1.abs() < 1e6);
|
||||
|
||||
// Non-finite session zoom is clamped/recovered on the next pass without poisoning canvas state.
|
||||
h.state_mut().session.view.zoom = f32::NAN;
|
||||
h.run_steps(1);
|
||||
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());
|
||||
}
|
||||
|
||||
@@ -260,6 +260,51 @@ fn table_gridlines_skip_edges_a_border_draws() {
|
||||
);
|
||||
}
|
||||
|
||||
/// #5967: a new table has borders on every edge, so it shows no gridline at all; with its
|
||||
/// borders removed every edge shows one.
|
||||
#[test]
|
||||
fn a_bordered_table_shows_no_gridlines() {
|
||||
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
|
||||
a.run("insert.table", json!({"rows": 2, "cols": 3})).unwrap();
|
||||
assert!(a.session.view.table_gridlines, "View Gridlines is on by default");
|
||||
let segs = |a: &mut WordApp| gridline_segments(&a.session.layout().pages[0], true, None).len();
|
||||
assert_eq!(segs(&mut a), 0);
|
||||
a.run("table.borders", json!({"kind": "none"})).unwrap();
|
||||
assert_eq!(segs(&mut a), 6 * 4, "every edge of the six cells");
|
||||
}
|
||||
|
||||
/// #5967: the gridlines of a table with very many rows are found in one pass over the rules, not
|
||||
/// by re-sorting every rule on a line for each cell edge on it (a long table repainted slowly).
|
||||
#[test]
|
||||
fn table_gridlines_of_a_many_row_table_are_fast() {
|
||||
const ROWS: usize = 30_000;
|
||||
let line = wordcraft_doc::props::Border::single(0.5);
|
||||
let mut items = Vec::new();
|
||||
for i in 0..ROWS {
|
||||
let y = i as f32 * 10.0;
|
||||
items.push(Placed::Cell {
|
||||
rect: wordcraft_geom::Rect::new(0.0, y, 10.0, 10.0),
|
||||
covered: false,
|
||||
table: Default::default(),
|
||||
row: i,
|
||||
cell: 0,
|
||||
story: StoryRef::Body,
|
||||
clip: false,
|
||||
});
|
||||
// One border piece per row on each side, so both vertical lines carry a rule per row.
|
||||
for x in [0.0, 10.0] {
|
||||
items.push(Placed::Rule { x0: x, y0: y, x1: x, y1: y + 10.0, border: line });
|
||||
}
|
||||
}
|
||||
let page = Page { items, ..Default::default() };
|
||||
let start = std::time::Instant::now();
|
||||
let segs = gridline_segments(&page, true, None);
|
||||
// Both sides are covered; the top and bottom of every cell are not.
|
||||
assert_eq!(segs.len(), 2 * ROWS);
|
||||
assert!(segs.iter().all(|(a, b)| a.y == b.y));
|
||||
assert!(start.elapsed() < std::time::Duration::from_secs(5), "took {:?}", start.elapsed());
|
||||
}
|
||||
|
||||
/// The drawing grid the page shows starts at the text area's top left, stays inside it, spaces
|
||||
/// its lines by the settings the same both ways or differently across and down, and falls back
|
||||
/// to the spec's 1/8 inch for a missing spacing.
|
||||
|
||||
@@ -4,9 +4,9 @@ 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::HelpEntry;
|
||||
use craft::ui::menu::search::{HelpEntry, SearchIndex, SearchWords, Synonyms};
|
||||
use craft::ui::patterns::panels::{CommandPalette, PaletteFace};
|
||||
use craft::ui::runtime::env::{Label, WordTemplate};
|
||||
use craft::ui::runtime::env::{Env, Label, WordTemplate};
|
||||
use craft::ui::runtime::inspect;
|
||||
use egui::Ui;
|
||||
use serde_json::json;
|
||||
@@ -64,7 +64,10 @@ pub(super) fn show(app: &mut WordApp, ui: &mut Ui, compact: bool) -> egui::Rect
|
||||
}
|
||||
rect = Some(button.response.rect);
|
||||
}
|
||||
let out = CommandPalette::new(name.clone(), &entries, Bind::bound(&mut open))
|
||||
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))
|
||||
.face(if compact { PaletteFace::Dialog } else { PaletteFace::InPlace })
|
||||
.placeholder(Label::from(name.clone()))
|
||||
.suggested((Label::from(tl!("Suggested").to_string()), suggested))
|
||||
|
||||