Merge main into feat/catalog-update-source; fix catalog review findings

- resolve the check_for_update doc-comment conflict with main
- offer prereleases from the signed catalog to a prerelease build, as the GitHub path does
- accept %2B in catalog download links and return the canonical link
- validate links against the catalog entry's own repo spelling
- share the stable/prerelease pick between latest_for and latest_for_repo
- add regression tests; rustfmt
This commit is contained in:
FredApps committed 2026-11-27 09:42:41 +01:00
commit 921a720426
613 files changed
+23013 -1977

No files matched your search

+1 -2
View File
@@ -69,8 +69,7 @@ workflows:
'.github/workflows/menu.yml':
- 'actions/checkout@v7.0.1'
- 'dtolnay/rust-toolchain@stable'
'.github/workflows/nightly.yml':
- 'step-security/harden-runner@v2.22.4'
'.github/workflows/nightly.yml': []
'.github/workflows/pcraft-format.yml':
- 'actions/checkout@v7.0.1'
- 'step-security/dtolnay-rust-toolchain@v1.0.0'
+1 -1
View File
@@ -3,7 +3,7 @@ name: AI model
on:
workflow_dispatch:
push:
branches: [main, next]
branches: [main]
paths: ['crates/ai-core/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/ai-core.yml']
pull_request:
paths: ['crates/ai-core/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/ai-core.yml']
+1 -1
View File
@@ -3,7 +3,7 @@ name: Atomic file writes
on:
workflow_dispatch:
push:
branches: [main, next]
branches: [main]
paths: ['crates/atomic/**', 'crates/settings/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/atomic.yml']
pull_request:
paths: ['crates/atomic/**', 'crates/settings/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/atomic.yml']
+1 -1
View File
@@ -2,7 +2,7 @@ name: Shared audio
on:
push:
branches: [main, next]
branches: [main]
paths: ["crates/audio/**", "crates/media/**", "crates/media-testkit/**", "scripts/fetch-opus-vectors.sh", "Cargo.toml", "Cargo.lock", ".github/workflows/audio.yml"]
pull_request:
paths: ["crates/audio/**", "crates/media/**", "crates/media-testkit/**", "scripts/fetch-opus-vectors.sh", "Cargo.toml", "Cargo.lock", ".github/workflows/audio.yml"]
+1 -1
View File
@@ -3,7 +3,7 @@ name: Colour management
on:
workflow_dispatch:
push:
branches: [main, next]
branches: [main]
paths: ['crates/cms/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/cms.yml']
pull_request:
paths: ['crates/cms/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/cms.yml']
+2 -2
View File
@@ -2,7 +2,7 @@ name: Shared CRW
on:
push:
branches: [main, next]
branches: [main]
paths: ["crates/crw/**", "scripts/fetch-crw-samples.py", "Cargo.toml", "Cargo.lock", ".github/workflows/crw.yml"]
pull_request:
paths: ["crates/crw/**", "scripts/fetch-crw-samples.py", "Cargo.toml", "Cargo.lock", ".github/workflows/crw.yml"]
@@ -52,7 +52,7 @@ jobs:
- uses: step-security/dtolnay-rust-toolchain@v1.0.0
with:
toolchain: stable
# Pull requests restore the entry main or next saved and never write their own: the same
# Pull requests restore the entry main saved and never write their own: the same
# files saved once per pull request took a share of the 10 GB cache budget.
- name: Restore the CC0 sample files
id: samples
+1 -1
View File
@@ -3,7 +3,7 @@ name: Dialogs
on:
workflow_dispatch:
push:
branches: [main, next]
branches: [main]
paths: ['crates/dialogs/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/dialogs.yml']
pull_request:
paths: ['crates/dialogs/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/dialogs.yml']
+1 -1
View File
@@ -3,7 +3,7 @@ name: Craft documents
on:
workflow_dispatch:
push:
branches: [main, next]
branches: [main]
paths: ['crates/doc/**', 'crates/pcraft-format/**', 'crates/vectorcraft-format/**', 'crates/ecproj-format/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/doc.yml']
pull_request:
paths: ['crates/doc/**', 'crates/pcraft-format/**', 'crates/vectorcraft-format/**', 'crates/ecproj-format/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/doc.yml']
+1 -1
View File
@@ -6,7 +6,7 @@ name: Docs
on:
workflow_dispatch:
push:
branches: [main, next]
branches: [main]
paths: ['crates/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/docs.yml']
pull_request:
paths: ['crates/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/docs.yml']
+1 -1
View File
@@ -3,7 +3,7 @@ name: EffectCraft project format
on:
workflow_dispatch:
push:
branches: [main, next]
branches: [main]
paths: ['crates/ecproj-format/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/ecproj-format.yml']
pull_request:
paths: ['crates/ecproj-format/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/ecproj-format.yml']
+1 -1
View File
@@ -3,7 +3,7 @@ name: Font store
on:
workflow_dispatch:
push:
branches: [main, next]
branches: [main]
paths: ['crates/font-store/**', 'crates/font-catalog/**', 'crates/atomic/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/font-store.yml']
pull_request:
paths: ['crates/font-store/**', 'crates/font-catalog/**', 'crates/atomic/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/font-store.yml']
+1 -1
View File
@@ -2,7 +2,7 @@ name: Shared format crates
on:
push:
branches: [main, next]
branches: [main]
paths:
- "crates/xml/**"
- "crates/mime/**"
+3 -1
View File
@@ -32,7 +32,9 @@ jobs:
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
linux-env: WGPU_BACKEND=vulkan
windows-env: CRAFT_PRINT_REQUIRE_QUEUE=1
env: CRAFT_PRINT_REQUIRE_QUEUE=0
env: |
CRAFT_PRINT_REQUIRE_QUEUE=0
CRAFT_HOSTILE_DIVISOR=1
setup-command: bash scripts/ci-test-inputs.sh
command: |
python scripts/test-full-validation.py
+1 -1
View File
@@ -2,7 +2,7 @@ name: House rules
on:
push:
branches: [main, next]
branches: [main]
paths:
- AGENTS.md
- CLAUDE.md
+1 -1
View File
@@ -2,7 +2,7 @@ name: Shared JPEG
on:
push:
branches: [main, next]
branches: [main]
paths: ["crates/jpeg/**", "Cargo.toml", "Cargo.lock", ".github/workflows/jpeg.yml"]
pull_request:
paths: ["crates/jpeg/**", "Cargo.toml", "Cargo.lock", ".github/workflows/jpeg.yml"]
+1 -1
View File
@@ -2,7 +2,7 @@ name: Keymap
on:
push:
branches: [main, next]
branches: [main]
paths: ["crates/keymap/**", "crates/settings/**", "crates/ui/**", "crates/ui-contract/**", "crates/ui-widgets/**", "crates/ui-panels/**", "crates/ui-canvas/**", "crates/ui-patterns/**", "crates/ui-shell/**", "crates/i18n/**", "Cargo.toml", "Cargo.lock", ".github/workflows/keymap.yml"]
pull_request:
paths: ["crates/keymap/**", "crates/settings/**", "crates/ui/**", "crates/ui-contract/**", "crates/ui-widgets/**", "crates/ui-panels/**", "crates/ui-canvas/**", "crates/ui-patterns/**", "crates/ui-shell/**", "crates/i18n/**", "Cargo.toml", "Cargo.lock", ".github/workflows/keymap.yml"]
+1 -1
View File
@@ -2,7 +2,7 @@ name: Shared media
on:
push:
branches: [main, next]
branches: [main]
paths: ["crates/media/**", "crates/media-testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/media.yml"]
pull_request:
paths: ["crates/media/**", "crates/media-testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/media.yml"]
+1 -1
View File
@@ -2,7 +2,7 @@ name: Menu
on:
push:
branches: [main, next]
branches: [main]
paths: ["crates/menu/**", "crates/keymap/**", "crates/quit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/menu.yml"]
pull_request:
paths: ["crates/menu/**", "crates/keymap/**", "crates/quit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/menu.yml"]
+4 -29
View File
@@ -1,7 +1,7 @@
name: Nightly full tests
# The tests the Workspace gate shortens, in full, once a day: every hostile-input hammer and sweep
# without CRAFT_HOSTILE_DIVISOR, and every proptest at its own case count (no PROPTEST_CASES). The
# with CRAFT_HOSTILE_DIVISOR=1 (every member, no sample), and every proptest at its own case count (no PROPTEST_CASES). The
# rest of the workspace's tests run with them, on Linux, with the gate's setup.
on:
schedule:
@@ -26,37 +26,12 @@ jobs:
packages: mesa-vulkan-drivers libvulkan1
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
linux-env: WGPU_BACKEND=vulkan
env: CRAFT_PRINT_REQUIRE_QUEUE=0
env: |
CRAFT_PRINT_REQUIRE_QUEUE=0
CRAFT_HOSTILE_DIVISOR=1
setup-command: bash scripts/ci-test-inputs.sh
cache-paths: .test-inputs/photocraft/corpus
cache-key: photocraft-corpus
cache-key-files: scripts/ci-test-inputs.sh
# The gate's build (the same targets and profile overrides), with every test at its full count.
command: bash scripts/ci-workspace-tests.sh full
# The scheduled run is main's; this starts the full tests above on next too, where the gate
# runs the same fractions. It also starts one Workspace run on next a day that nothing cancels
# (pull requests run the Linux legs only, and pushes to next cancel each other's runs): next's
# macOS and Windows legs then run in full at least once a day, and its Linux leg builds from
# source and saves next's own workspace-crates cache entry, which pull requests into next
# restore. Main gets the same from workspace.yml's own scheduled runs. The only job here with
# `actions: write`; it checks out and runs nothing from the repository.
workspace-next:
name: Workspace on next
if: github.event_name == 'schedule'
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
actions: write
steps:
- name: Harden runner
uses: step-security/harden-runner@v2.22.4
with:
egress-policy: audit
- name: Start the Workspace workflow and these full tests on next
env:
GH_TOKEN: ${{ github.token }}
REPO: ${{ github.repository }}
run: |
gh workflow run workspace.yml --repo "$REPO" --ref next
gh workflow run nightly.yml --repo "$REPO" --ref next
+1 -1
View File
@@ -3,7 +3,7 @@ name: PhotoCraft format
on:
workflow_dispatch:
push:
branches: [main, next]
branches: [main]
paths: ['crates/pcraft-format/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/pcraft-format.yml']
pull_request:
paths: ['crates/pcraft-format/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/pcraft-format.yml']
+1 -1
View File
@@ -2,7 +2,7 @@ name: Shared PDF
on:
push:
branches: [main, next]
branches: [main]
paths: ["crates/pdf/**", "crates/plate-test/**", "crates/prepress/**", "crates/cms/**", "vendor/hayro*/**", "vendor/krilla/**", "vendor/linesweeper/**", "vendor/vello_common/**", "vendor/vello_cpu/**", "scripts/test-pdf-backends.sh", "scripts/*fetch-pdf-test-fonts.py", "Cargo.toml", "Cargo.lock", ".github/workflows/pdf.yml"]
pull_request:
paths: ["crates/pdf/**", "crates/plate-test/**", "crates/prepress/**", "crates/cms/**", "vendor/hayro*/**", "vendor/krilla/**", "vendor/linesweeper/**", "vendor/vello_common/**", "vendor/vello_cpu/**", "scripts/test-pdf-backends.sh", "scripts/*fetch-pdf-test-fonts.py", "Cargo.toml", "Cargo.lock", ".github/workflows/pdf.yml"]
+1 -1
View File
@@ -2,7 +2,7 @@ name: Proofing
on:
push:
branches: [main, next]
branches: [main]
paths: ["crates/proof/**", "Cargo.toml", "Cargo.lock", ".github/workflows/proof.yml"]
pull_request:
paths: ["crates/proof/**", "Cargo.toml", "Cargo.lock", ".github/workflows/proof.yml"]
+1 -1
View File
@@ -3,7 +3,7 @@ name: Suite themes
on:
workflow_dispatch:
push:
branches: [main, next]
branches: [main]
paths: ['crates/theme/**', 'crates/theme-store/**', 'crates/atomic/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/theme.yml']
pull_request:
paths: ['crates/theme/**', 'crates/theme-store/**', 'crates/atomic/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/theme.yml']
+1 -1
View File
@@ -3,7 +3,7 @@ name: App updates
on:
workflow_dispatch:
push:
branches: [main, next]
branches: [main]
paths: ['crates/update/**', 'Cargo.toml', 'Cargo.lock', 'rustfmt.toml', 'clippy.toml', '.github/workflows/update.yml']
pull_request:
paths: ['crates/update/**', 'Cargo.toml', 'Cargo.lock', 'rustfmt.toml', 'clippy.toml', '.github/workflows/update.yml']
+1 -1
View File
@@ -3,7 +3,7 @@ name: VectorCraft format
on:
workflow_dispatch:
push:
branches: [main, next]
branches: [main]
paths: ['crates/vectorcraft-format/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/vectorcraft-format.yml']
pull_request:
paths: ['crates/vectorcraft-format/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/vectorcraft-format.yml']
+1 -1
View File
@@ -2,7 +2,7 @@ name: Shared video
on:
push:
branches: [main, next]
branches: [main]
paths: ["crates/video/**", "crates/media/**", "crates/media-testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/video.yml"]
pull_request:
paths: ["crates/video/**", "crates/media/**", "crates/media-testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/video.yml"]
+1 -1
View File
@@ -3,7 +3,7 @@ name: Web API (page command API)
on:
workflow_dispatch:
push:
branches: [main, next]
branches: [main]
paths: ['crates/web-api/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/web-api.yml']
pull_request:
paths: ['crates/web-api/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/web-api.yml']
+1 -1
View File
@@ -2,7 +2,7 @@ name: Shared web host
on:
push:
branches: [main, next]
branches: [main]
paths: ["crates/web-host/**", "Cargo.toml", "Cargo.lock", ".github/workflows/web-host.yml"]
pull_request:
paths: ["crates/web-host/**", "Cargo.toml", "Cargo.lock", ".github/workflows/web-host.yml"]
+1 -1
View File
@@ -3,7 +3,7 @@ name: Window decorations
on:
workflow_dispatch:
push:
branches: [main, next]
branches: [main]
paths: ['crates/window/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/window.yml']
pull_request:
paths: ['crates/window/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/window.yml']
+21 -28
View File
@@ -2,7 +2,7 @@ name: Workspace
on:
push:
branches: [main, next]
branches: [main]
tags: ["v*"]
pull_request:
workflow_dispatch:
@@ -16,13 +16,12 @@ permissions:
contents: read
concurrency:
# A pull request, main and next each have one group, so a newer push cancels the run it
# supersedes; the newest push's run still tests everything before it. Every other run (a release
# tag, a manual run, the scheduled run, nightly.yml's run on next) gets a group of its own and is
# neither cancelled nor replaced while queued: a release run always finishes, the scheduled run
# saves the caches, and next gets one complete macOS and Windows run a day.
group: workspace-${{ (github.event_name == 'pull_request' || github.event_name == 'push' && github.ref == 'refs/heads/main' || github.event_name == 'push' && github.ref == 'refs/heads/next') && github.ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' || github.event_name == 'push' && github.ref == 'refs/heads/main' || github.event_name == 'push' && github.ref == 'refs/heads/next' }}
# A pull request and main each have one group, so a newer push cancels the run it supersedes; the
# newest push's run still tests everything before it. Every other run (a release tag, a manual
# run, the scheduled run) gets a group of its own and is neither cancelled nor replaced while
# queued: a release run always finishes, and the scheduled run saves the caches.
group: workspace-${{ (github.event_name == 'pull_request' || github.event_name == 'push' && github.ref == 'refs/heads/main') && github.ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' || github.event_name == 'push' && github.ref == 'refs/heads/main' }}
jobs:
# Whether this run needs the macOS and Windows legs, and which tests every leg runs
@@ -71,7 +70,7 @@ jobs:
# The macOS and Windows legs cache dependencies only, so `deps-profile` hashes only the
# settings that reach a dependency: `[profile.dev]` and `[profile.dev.package."*"]`. Every
# other override names a workspace crate (scripts/test-workspace-tests.py), so changing one
# keeps those entries, and next's runs restore main's.
# keeps those entries.
- uses: actions/checkout@v7.0.1
if: github.event_name != 'pull_request'
with:
@@ -104,13 +103,10 @@ jobs:
# The Linux leg keeps the compiled workspace crates between runs (`cache-workspace-crates`): each
# main run saves a rolling cache entry of its own, every run restores the newest one, and Cargo
# rebuilds only the crates a change reaches. `cache-prune` keeps the newest entry. The midnight
# scheduled run builds from source (`cold-build`) and starts the entry afresh. next has an entry
# of its own, since main's is built from different code and lockfile and a pull request into next
# rebuilt nearly everything from it (15.5 minutes): nightly.yml's daily manual run on next builds
# from source and saves it (`cache-save-on-dispatch`), and pull requests into next restore it
# before main's. The macOS and Windows legs keep a dependency-only entry: their workspace crates
# would not fit the 10 GB cache budget beside Linux's. The lint legs keep no cache
# (`lint-cache: false`) for the same reason; a cold lint leg is still shorter than its gate leg.
# scheduled run builds from source (`cold-build`) and starts the entry afresh. The macOS and
# Windows legs keep a dependency-only entry: their workspace crates would not fit the 10 GB cache
# budget beside Linux's. The lint legs keep no cache (`lint-cache: false`) for the same reason; a
# cold lint leg is still shorter than its gate leg.
native:
name: Workspace
needs: platforms
@@ -118,9 +114,8 @@ jobs:
with:
os: '["ubuntu-latest"]'
cache-workspace-crates: true
cache-save-on-dispatch: true
cache-version: &cache-version v2-${{ needs.platforms.outputs.profile }}
cold-build: ${{ github.event.schedule == '17 0 * * *' || github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/next' }}
cold-build: ${{ github.event.schedule == '17 0 * * *' }}
lint-cache: false
# The vendored crates are on the workspace `exclude` list and craft-pdf's read-only contract is a
# workspace of its own (pdf.yml tests it), so unreached-rs has no module tree for them.
@@ -182,7 +177,7 @@ jobs:
# The macOS and Windows legs, with the Linux leg's inputs. They take 1.5-2 hours against the Linux
# leg's 15-40 minutes, so a pull request does not wait for them: they run after the merge, on
# every push to main and next, on main's scheduled runs and on nightly.yml's daily run on next.
# every push to main and on main's scheduled runs.
# A pull request that needs them before it merges gets the full-ci label.
native-platforms:
name: Workspace
@@ -192,7 +187,7 @@ jobs:
with:
os: '["windows-latest","macos-latest"]'
lint-cache: false
# Named by the dependency settings alone (`deps-profile`), so next restores main's entries.
# Named by the dependency settings alone (`deps-profile`).
cache-version: v2-${{ needs.platforms.outputs.deps-profile }}
timeout-minutes: *timeout
tools: *tools
@@ -212,15 +207,14 @@ jobs:
lint-command: *lint
command: *command
# Each main run's Linux leg saves a rolling cache entry of its own (`cache-workspace-crates`), as
# does the daily manual run on next, and every run restores only the newest. This deletes the
# older ones of the run's branch as soon as the Linux leg is done, instead of leaving them to the
# 10 GB budget's eviction, which would evict other entries too. The only job with
# `actions: write`; it checks out and runs nothing from the repository.
# Each main run's Linux leg saves a rolling cache entry of its own (`cache-workspace-crates`), and
# every run restores only the newest. This deletes the older ones as soon as the Linux leg is
# done, instead of leaving them to the 10 GB budget's eviction, which would evict other entries
# too. The only job with `actions: write`; it checks out and runs nothing from the repository.
cache-prune:
name: cache prune
needs: native
if: ${{ !cancelled() && github.event_name != 'pull_request' && (github.ref == 'refs/heads/main' || github.ref == 'refs/heads/next') }}
if: ${{ !cancelled() && github.event_name != 'pull_request' && github.ref == 'refs/heads/main' }}
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
@@ -234,11 +228,10 @@ jobs:
env:
GH_TOKEN: ${{ github.token }}
REPO: ${{ github.repository }}
REF: ${{ github.ref }}
run: |
set -euo pipefail
# `<version>-rust-<profile>-<job>-crates-<os>-<arch>-<run>-<attempt>-...`, newest first.
gh cache list --repo "$REPO" --ref "$REF" --limit 100 --sort created_at --order desc --json id,key \
gh cache list --repo "$REPO" --ref refs/heads/main --limit 100 --sort created_at --order desc --json id,key \
--jq '.[] | "\(.id) \(.key)"' > "$RUNNER_TEMP/caches"
declare -A kept
while read -r id key; do
Generated
+15
View File
@@ -1909,6 +1909,7 @@ dependencies = [
"craft-scraft-format",
"craft-settings",
"craft-sf2",
"craft-shared-vec",
"craft-sheet",
"craft-shx",
"craft-silhouette-studio",
@@ -2047,6 +2048,7 @@ name = "craft-appkit"
version = "0.1.0"
dependencies = [
"block2 0.6.2",
"objc2 0.6.5",
"objc2-app-kit 0.3.2",
"objc2-foundation 0.3.2",
]
@@ -2280,6 +2282,7 @@ dependencies = [
"craft-atomic",
"craft-control-protocol",
"craft-flags",
"craft-platform",
"dirs",
"getrandom 0.3.4",
"log",
@@ -2419,6 +2422,7 @@ name = "craft-dialogs"
version = "0.1.0"
dependencies = [
"block2 0.6.2",
"craft-appkit",
"craft-atomic",
"craft-behavior",
"craft-browse",
@@ -4086,6 +4090,16 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-shared-vec"
version = "0.1.0"
dependencies = [
"craft-shared-vec",
"proptest",
"serde",
"serde_json",
]
[[package]]
name = "craft-sheet"
version = "0.1.0"
@@ -4205,6 +4219,7 @@ dependencies = [
name = "craft-suite-account"
version = "0.1.0"
dependencies = [
"craft-platform",
"dirs",
"keyring",
"keyring-core",
+1
View File
@@ -32,6 +32,7 @@ craft-ssip = { path = "crates/ssip" }
craft-ber = { path = "crates/ber" }
craft-proto = { path = "crates/proto" }
craft-render-parity = { path = "crates/render-parity" }
craft-shared-vec = { path = "crates/shared-vec" }
acadrust = "=0.6.6"
log = "0.4"
# internal: add each crate here as `craft-<name> = { path = "crates/<name>" }`
+2 -2
View File
@@ -289,8 +289,8 @@ linesweeper
linesweeper 0.5.0 (https://crates.io/crates/linesweeper/0.5.0), MIT OR Apache-2.0, is stored in
vendor/linesweeper with its upstream license files and local patches, to src/sweep/sweep_line.rs,
src/curve/transverse.rs, src/curve/mod.rs, src/curve/line.rs and docs/sweep.typ. Its manifest names
Joe Neeman as author, and its LICENSE-MIT reads "Copyright (c) 2018 Raph Levien". See
src/segments.rs, src/curve/transverse.rs, src/curve/mod.rs, src/curve/line.rs and docs/sweep.typ. Its
manifest names Joe Neeman as author, and its LICENSE-MIT reads "Copyright (c) 2018 Raph Levien". See
vendor/linesweeper/README.craft.md and vendor/linesweeper/SOURCE.json for provenance, the local
patches and the files left out.
+4 -2
View File
@@ -377,8 +377,9 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
with a password. Salvages damaged files. Bounded and panic-free on hostile input. What an item
means stays in each app.
- [`craft-quit`](crates/quit/src/lib.rs): native macOS quit, egui close handling and an optional
app menu. Unsaved-document decisions and save prompts stay in each app.
- [`craft-quit`](crates/quit/README.md): native macOS quit, a window close held for unsaved
documents, the Quit menu item id and the unsaved-changes question one document at a time
(`CloseGuard`). The prompt and the saving stay in each app.
- [`craft-rtf`](crates/rtf/README.md): Rich Text Format: a tokenizer, text decoding in the file's code pages
(`\uN`, `\'hh`, single-byte and East Asian multibyte pages), escaping and dates, and a reader and writer
for a small neutral model (paragraphs, character formatting, outline levels, tables).
@@ -388,6 +389,7 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
revisions panel, presence, voting, cursor chat and join over the app's own transport (`ui`
feature).
- [`craft-settings`](crates/settings/README.md): `config.toml` settings storage for every app: platform folders, portable mode and overrides, atomic saves while running, backup, damaged-file recovery and schema migrations, plus remembered dialog options and preset folders (also on wasm32). Policy in [docs/settings-storage.md](docs/settings-storage.md).
- [`craft-shared-vec`](crates/shared-vec/README.md): an ordered, indexed list whose clones share storage, for document trees kept in an undo history: an edit copies the blocks on its path instead of the whole list, and `bytes_not_in` counts what keeping two versions costs. Reads and writes as a plain sequence with `serde`.
- [`craft-sheet`](crates/sheet/README.md): spreadsheet vocabulary shared by `craft-xls`, `craft-xlsx` and `craft-ods`: cell positions and A1 text, cell values and error values, sheet-name quoting, Excel's built-in number formats and indexed colour palette. Not a file format; no dependencies.
- [`craft-sf2`](crates/sf2/README.md): SoundFont 2 (`.sf2`) reader: the sample pool and, per preset, the key and velocity regions a note sounds, with tuning, loop points, pan, level and volume envelope resolved from the preset and instrument zones. Bounded on hostile input. From LoopCraft.
- [`craft-silhouette-studio`](crates/silhouette-studio/src/lib.rs): bounded, fail-closed reader for Silhouette Studio `.studio` and `.studio3` documents: outlines, line colours and page size in millimetres. Protected designs are refused.
+5 -4
View File
@@ -1,6 +1,6 @@
[package]
name = "craft-appkit"
description = "The macOS menu-tracking observers that need `unsafe`, behind a safe API, so no other crate allows `unsafe`."
description = "The macOS menu-tracking observers and Save panel calls that need `unsafe`, behind a safe API, so no other crate allows `unsafe`."
version.workspace = true
edition.workspace = true
license.workspace = true
@@ -8,11 +8,12 @@ rust-version.workspace = true
repository.workspace = true
# `NSMenuDidBeginTrackingNotification` and `NSMenuDidEndTrackingNotification`, observed through
# `NSNotificationCenter` with a block.
# `NSNotificationCenter` with a block. A Save panel made with `-init`, and the target of a pop-up menu's action.
[target.'cfg(target_os = "macos")'.dependencies]
block2 = "0.6.2"
objc2-app-kit = { version = "0.3.2", default-features = false, features = ["std", "NSMenu"] }
objc2-foundation = { version = "0.3.2", default-features = false, features = ["std", "block2", "NSNotification", "NSOperation", "NSString"] }
objc2 = { version = "0.6.4", default-features = false, features = ["std"] }
objc2-app-kit = { version = "0.3.2", default-features = false, features = ["std", "NSButton", "NSControl", "NSMenu", "NSPanel", "NSPopUpButton", "NSResponder", "NSSavePanel", "NSView", "NSWindow"] }
objc2-foundation = { version = "0.3.2", default-features = false, features = ["std", "block2", "NSNotification", "NSObject", "NSOperation", "NSString"] }
# The workspace table with `unsafe_code` at `deny`: `lib.rs` allows it for this crate's FFI calls, and design-lint's
# `contract/unsafe-allow` rule names this crate's source as one of the places that may. Cargo cannot override one
+4 -2
View File
@@ -1,5 +1,5 @@
//! The AppKit calls that need `unsafe`, behind a safe API: observing when a menu starts and stops tracking. macOS
//! only; the crate is empty elsewhere.
//! The AppKit calls that need `unsafe`, behind a safe API: observing when a menu starts and stops tracking, and the
//! Save panel calls in `save_panel`. macOS only; the crate is empty elsewhere.
//!
//! This is one of the crates that may allow `unsafe`; the design-lint rule `contract/unsafe-allow` names it. Every
//! block says why it is sound.
@@ -14,6 +14,8 @@ use block2::RcBlock;
use objc2_app_kit::{NSMenuDidBeginTrackingNotification, NSMenuDidEndTrackingNotification};
use objc2_foundation::{NSNotification, NSNotificationCenter};
pub mod save_panel;
/// Calls `on_change(true)` when a menu begins tracking (`NSMenuDidBeginTrackingNotification`) and `on_change(false)`
/// when it ends (`NSMenuDidEndTrackingNotification`), from the thread that posts the notification. Observes once
/// for the process; a later call replaces nothing and does nothing.
+64
View File
@@ -0,0 +1,64 @@
//! The Save panel calls that need `unsafe`: making a panel that may be nil, and a pop-up menu's action.
use objc2::rc::Retained;
use objc2::runtime::AnyObject;
use objc2::{ClassType, DefinedClass, MainThreadMarker, MainThreadOnly, define_class, msg_send, sel};
use objc2_app_kit::{NSPopUpButton, NSSavePanel};
use objc2_foundation::{NSObject, NSObjectProtocol};
/// A new Save panel, or `None` when AppKit returns nil. `+[NSSavePanel savePanel]` returns nil on some systems
/// (storytold/vectorcraft#5980), and objc2's `NSSavePanel::savePanel` panics on it.
pub fn new_save_panel(mtm: MainThreadMarker) -> Option<Retained<NSSavePanel>> {
// SAFETY: `-init` is the initializer of a bare panel, called once on the allocation. The result is typed as
// `Option`, so nil is `None`.
let panel: Option<Retained<NSSavePanel>> = unsafe { msg_send![NSSavePanel::alloc(mtm), init] };
if panel.is_some() {
return panel;
}
// SAFETY: a class method that returns an autoreleased panel or nil, typed as `Option`.
unsafe { msg_send![NSSavePanel::class(), savePanel] }
}
/// The closure a [`PopUpChoice`] calls.
pub struct Ivars {
on_choose: Box<dyn Fn(usize)>,
}
define_class!(
// SAFETY: NSObject has no subclassing requirements, and the class implements no `Drop`.
#[unsafe(super(NSObject))]
#[thread_kind = MainThreadOnly]
#[ivars = Ivars]
#[name = "CraftPopUpChoice"]
/// The target of a pop-up menu's action; see [`on_choose`].
pub struct PopUpChoice;
// SAFETY: NSObjectProtocol has no additional requirements.
unsafe impl NSObjectProtocol for PopUpChoice {}
impl PopUpChoice {
// SAFETY: NSControl's target-action sends the pop-up button as the one object argument.
#[unsafe(method(choose:))]
fn choose(&self, sender: &NSPopUpButton) {
if let Ok(index) = usize::try_from(sender.indexOfSelectedItem()) {
(self.ivars().on_choose)(index);
}
}
}
);
/// Calls `on_choose` with the index of the item the user chooses in `popup`. A control does not retain its target,
/// so the caller keeps the returned object for as long as `popup` can send its action.
pub fn on_choose(mtm: MainThreadMarker, popup: &NSPopUpButton, on_choose: impl Fn(usize) + 'static) -> Retained<PopUpChoice> {
let this = PopUpChoice::alloc(mtm).set_ivars(Ivars { on_choose: Box::new(on_choose) });
// SAFETY: NSObject's designated initializer, called once on the allocated subclass.
let target: Retained<PopUpChoice> = unsafe { msg_send![super(this), init] };
let object: &AnyObject = &target;
// SAFETY: `choose:` takes the sender, the signature a control's action is sent with, and the caller keeps
// `target` alive while `popup` can send it (the documentation above).
unsafe {
popup.setTarget(Some(object));
popup.setAction(Some(sel!(choose:)));
}
target
}
+22 -1
View File
@@ -6,7 +6,7 @@ Extracted from the storage engine in **PhotoCraft** (refs #2, #14), it guarantee
## Core Guarantees: Atomicity vs. Durability
1. **Atomicity (All-or-Nothing Replacement)**: `atomic_write` never truncates or overwrites the destination in place. It stages content in a hidden temporary file beside the destination (`.{stem}.{pid}-{n}.craft_tmp`), guaranteeing same-volume rename semantics (`EXDEV`-free). An external reader never sees a partial write. If an error occurs during staging or rename, the destination retains its prior bytes and the staging file is unlinked in user space. An abnormal process exit (e.g. `SIGKILL`, crash, or power loss) bypasses user-space cleanup and leaves the staging file on disk; sweeping orphaned staging files is delegated to consuming application recovery routines. The destination file itself is never corrupted.
1. **Atomicity (All-or-Nothing Replacement)**: `atomic_write` never truncates or overwrites the destination in place. It stages content in a hidden temporary file beside the destination (`.{stem}.{pid}-{n}.craft_tmp`), guaranteeing same-volume rename semantics (`EXDEV`-free). An external reader never sees a partial write. If an error occurs during staging or rename, the destination retains its prior bytes and the staging file is unlinked in user space. An abnormal process exit (e.g. `SIGKILL`, crash, or power loss) bypasses user-space cleanup and leaves the staging file on disk; the application removes orphaned staging files by calling `sweep_temp_files` for the folder (see "Removing Orphaned Staging Files" below). The destination file itself is never corrupted.
2. **Durability & Ordering Boundaries**:
- **Content Flush**: Before rename, staging file bytes are flushed to physical storage media (`sync_file`, issuing `F_FULLFSYNC` on macOS/APFS with SMB `fsync` fallback).
- **Directory Flush (Unix)**: After rename, syncing the parent directory table (`sync_dir`) is attempted on a best-effort basis. If directory sync fails, the error is ignored because the rename has already committed and the destination has already been replaced.
@@ -63,6 +63,27 @@ let path = Path::new("export.png");
write_new(path, b"png bytes...").expect("exclusive write");
```
### Removing Orphaned Staging Files
```rust
use std::path::Path;
use std::time::Duration;
use craft_atomic::sweep_temp_files;
// Removes staging files in scenes/ that were last modified an hour or more ago.
// Returns how many were removed.
let removed = sweep_temp_files(Path::new("scenes"), Duration::from_secs(3600)).unwrap_or(0);
```
`sweep_temp_files` removes only regular files whose names have the staging form, never follows
a symbolic link, and does not search subfolders. A save updates its staging file's modification
time only while it writes bytes, not while it flushes or renames, and removing the staging file
makes that save fail. Choose a minimum age longer than the longest time any save into the folder,
by any process including the calling one, may go without writing, counting the final flush and
rename. On Windows, a write may not update the modification time until the staging file's handle
closes, so choose a minimum age longer than the longest whole save, from the staging file's
creation through the rename. Entries that cannot be removed are left in place.
### Document Permissions and Private Data
The free functions and `WriteOptions::default()` use `NewFilePermissions::PlatformDefault`.
+54 -3
View File
@@ -14,9 +14,9 @@
//! file retains its previous bytes, or it is replaced completely with the new contents. If an error occurs
//! during staging or rename, the target remains unmodified and the staging file is removed in user space.
//! An abnormal process termination (e.g. `SIGKILL`, crash, power loss) bypasses user-space cleanup and
//! leaves the temporary staging file on disk. Sweeping orphaned staging files is the responsibility of the
//! consuming application; the library does not perform background sweeping. The destination file itself is
//! never corrupted.
//! leaves the temporary staging file on disk. The library does not sweep in the background; the consuming
//! application calls [`sweep_temp_files`] for a folder, for example at startup, to remove orphaned staging
//! files. The destination file itself is never corrupted.
//! - **Durability & Ordering Boundaries**:
//! Data persistence across power failures involves two sync points:
//! 1. **Content Flush (`sync_file`)**: The staging file's payload is forced to non-volatile storage
@@ -818,6 +818,57 @@ pub fn temp_name(file: &str) -> String {
format!(".{stem}.{pid}-{n}.craft_tmp")
}
/// Removes staging files that interrupted writes left in `dir`, and returns how many it removed.
///
/// A file is removed when its name has the form [`temp_name`] gives, it is a regular file (a
/// symbolic link is not followed), and it was last modified at least `min_age` ago. The process
/// id in the name is not used to decide, since the system reuses process ids. A save updates its
/// staging file's modification time only while it writes bytes, not while it flushes or renames,
/// and removing the staging file makes that save fail. Pass a `min_age` longer than the longest
/// time any save into `dir`, by any process including the calling one, may go without writing,
/// counting the final flush and rename. On Windows, a write may not update the modification time
/// until the staging file's handle closes, so pass a `min_age` longer than the longest whole save,
/// from the staging file's creation through the rename. Entries that cannot be read or removed are
/// left in place. Subfolders are not searched.
/// On `wasm32` this returns an `Unsupported` error.
pub fn sweep_temp_files(dir: &Path, min_age: std::time::Duration) -> io::Result<usize> {
#[cfg(target_arch = "wasm32")]
{
let _ = (dir, min_age);
Err(io::Error::new(io::ErrorKind::Unsupported, "staging files cannot be swept on this platform"))
}
#[cfg(not(target_arch = "wasm32"))]
{
let now = std::time::SystemTime::now();
let entries = std::fs::read_dir(dir).map_err(|e| io::Error::new(e.kind(), format!("cannot read {}: {e}", dir.display())))?;
let mut removed = 0;
for entry in entries.flatten() {
if !entry.file_name().to_str().is_some_and(is_temp_name) {
continue;
}
let Ok(meta) = std::fs::symlink_metadata(entry.path()) else { continue };
let old = meta.modified().ok().and_then(|m| now.duration_since(m).ok()).is_some_and(|age| age >= min_age);
if meta.is_file() && old && std::fs::remove_file(entry.path()).is_ok() {
removed += 1;
}
}
Ok(removed)
}
}
/// Whether `name` has the form [`temp_name`] gives (`.{stem}.{pid}-{n}.craft_tmp`), with a stem
/// of at most [`TEMP_STEM_BYTES`] bytes.
#[cfg(not(target_arch = "wasm32"))]
fn is_temp_name(name: &str) -> bool {
// Decimal digits with no leading zero, as `format!` writes an integer; a lone `0` is allowed.
let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()) && (s == "0" || !s.starts_with('0'));
let Some((stem, tail)) = name.strip_prefix('.').and_then(|rest| rest.strip_suffix(".craft_tmp")).and_then(|rest| rest.rsplit_once('.')) else {
return false;
};
let Some((pid, n)) = tail.split_once('-') else { return false };
stem.len() <= TEMP_STEM_BYTES && digits(pid) && digits(n) && pid.parse::<u32>().is_ok() && n.parse::<u64>().is_ok()
}
/// The end of an error message: whether an original file was left as it was.
fn unchanged(existed: bool) -> &'static str {
if existed { "; the original file was not changed" } else { "" }
+76
View File
@@ -582,3 +582,79 @@ fn wasm_atomic_write_returns_unsupported() {
let err = atomic_write(Path::new("dummy.craft"), b"data").unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::Unsupported);
}
#[cfg(target_arch = "wasm32")]
#[test]
fn wasm_sweep_temp_files_returns_unsupported() {
let err = sweep_temp_files(Path::new("scenes"), std::time::Duration::ZERO).unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::Unsupported);
}
/// Writes the file `name` in `dir` and dates its modification time `age` in the past.
#[cfg(not(target_arch = "wasm32"))]
fn leftover(dir: &Path, name: &str, age: std::time::Duration) -> io::Result<PathBuf> {
let p = dir.join(name);
std::fs::write(&p, b"interrupted save")?;
File::options().write(true).open(&p)?.set_modified(std::time::SystemTime::now() - age)?;
Ok(p)
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn sweep_removes_only_old_staging_files() -> io::Result<()> {
let d = TempDir::new("sweep_old");
let other = std::process::id().wrapping_add(1);
let hour = std::time::Duration::from_secs(3600);
let orphan = leftover(&d.0, &format!(".scene.json.{other}-0.craft_tmp"), 2 * hour)?;
// A process id the system reused for this process does not protect an old orphan.
let same_pid = leftover(&d.0, &temp_name("scene.json"), 2 * hour)?;
let recent = leftover(&d.0, &format!(".scene.json.{other}-1.craft_tmp"), std::time::Duration::ZERO)?;
let document = leftover(&d.0, "scene.json", 2 * hour)?;
assert_eq!(sweep_temp_files(&d.0, hour)?, 2);
assert!(!orphan.exists() && !same_pid.exists());
assert!(recent.exists() && document.exists());
Ok(())
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn sweep_keeps_files_it_did_not_name_and_folders() -> io::Result<()> {
let d = TempDir::new("sweep_lookalike");
let other = std::process::id().wrapping_add(1);
let old = std::time::Duration::from_secs(7200);
let orphan = leftover(&d.0, &format!(".a.b.{other}-7.craft_tmp"), old)?;
let kept = [
leftover(&d.0, "notes.craft_tmp", old)?,
leftover(&d.0, &format!("scene.json.{other}-7.craft_tmp"), old)?,
leftover(&d.0, ".scene.json.12-x.craft_tmp", old)?,
leftover(&d.0, ".scene.json.-3.craft_tmp", old)?,
leftover(&d.0, ".12-3.craft_tmp", old)?,
leftover(&d.0, &format!(".scene.json.{other}-7.craft_tmp.bak"), old)?,
leftover(&d.0, ".scene.json.99999999999-7.craft_tmp", old)?,
// temp_name writes the process id and the counter without leading zeros.
leftover(&d.0, ".scene.json.012-0.craft_tmp", old)?,
leftover(&d.0, ".scene.json.12-03.craft_tmp", old)?,
// temp_name keeps at most TEMP_STEM_BYTES bytes of the destination's name.
leftover(&d.0, &format!(".{}.{other}-7.craft_tmp", "s".repeat(TEMP_STEM_BYTES + 1)), old)?,
];
// The longest stem temp_name writes, in ASCII and in two-byte characters.
let longest = leftover(&d.0, &temp_name(&"s".repeat(200)), old)?;
let longest_wide = leftover(&d.0, &temp_name(&"é".repeat(100)), old)?;
let folder = d.0.join(format!(".scene.json.{other}-8.craft_tmp"));
std::fs::create_dir(&folder)?;
assert_eq!(sweep_temp_files(&d.0, std::time::Duration::ZERO)?, 3);
assert!(!orphan.exists() && !longest.exists() && !longest_wide.exists());
assert!(kept.iter().all(|p| p.exists()), "a file without the staging name was removed");
assert!(folder.is_dir());
Ok(())
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn sweep_of_a_missing_folder_is_an_error() {
let d = TempDir::new("sweep_missing");
let err = sweep_temp_files(&d.0.join("absent"), std::time::Duration::ZERO).err().map(|e| e.kind());
assert_eq!(err, Some(io::ErrorKind::NotFound));
}
+1 -1
View File
@@ -14,7 +14,7 @@ Features: `ui` (the egui parts), `agents` (agents in the open window: the launch
| `security` | Tokens (`generate_token`, `validate_token`, `server_token`, `client_token`), the authentication handshake (`ServerHandshake`: the challenge handshake, which never sends the token, or the one-frame `auth {token}`), bounded line reads, connection and request limits. |
| `protocol` | The JSON-lines wire format: one `{"id", "method", "params"}` request per line, one `{"id", "ok", "result" | "error"}` reply per line; `Params` validators that name the bad parameter. |
| `control` | `ControlRequest`, `Reply`, `Dispatch` and `ControlChannel`: the UI-thread side that drains requests between frames, replies after injected input or a background job settles, and admits screenshots. The app supplies the method table. |
| `synthetic` | `Click`, `Move`, `Wheel`, `KeyPress` and `Release`: the validated parameters of `ui.click`, `ui.move`, `ui.wheel` (`unit: "points"` or `"lines"`), `ui.key` and `ui.release`, each point a screen point, a document point or a `control` target, and `input_method`'s `ui.ime` `{preedit, cursor}` and `{commit}` forms, queued through `WindowHost::inject_*` one step per pass. |
| `synthetic` | `Click`, `Move`, `Drag`, `Wheel`, `KeyPress` and `Release`: the validated parameters of `ui.click`, `ui.move`, `ui.drag` (a press, moves in even steps and the release, from one request), `ui.wheel` (`unit: "points"` or `"lines"`), `ui.key` and `ui.release`, each point a screen point, a document point or a `control` target, and `input_method`'s `ui.ime` `{preedit, cursor}` and `{commit}` forms, queued through `WindowHost::inject_*` one step per pass. |
| `access` | Named controls over the window's access tree (`ui` feature): `Target` (`{name, role?, within?, index?}`, found in reading order), `describe`, and `access_method`, which answers `ui.find` from the tree `ControlChannel::poll_input` has the host keep. |
| `server` | `listen` (bind a port) and `serve` (a listener bound earlier): the loopback TCP server that authenticates each connection and forwards requests to the channel, until its `Listening` is dropped. |
| `client` | `ControlClient`: connect, authenticate, call (a screenshot is `call("ui.screenshot", ..)`); for integration tests and CLIs. |
+52 -5
View File
@@ -16,7 +16,7 @@ use crate::security;
use crate::server::{self, Listening};
/// How long after a failed start [`AgentLink::sync`] tries again with the same settings, so
/// freeing a taken port is enough.
/// freeing a taken port is enough. A refused token file is not tried again: see [`AgentLink::sync`].
pub const RETRY: Duration = Duration::from_secs(5);
/// Why agents cannot connect, or what the app could not apply. `Display` is the English sentence
@@ -123,6 +123,10 @@ pub struct AgentLink {
applied: Option<Option<AgentSettings>>,
retry_at: Option<Instant>,
retry: Duration,
/// The token a failed start already read and checked, for its retries with the same settings;
/// cleared once a start succeeds or the settings change. On Windows the check starts `whoami` and PowerShell (`owner_only`), about 300 ms
/// on the UI thread, which every retry of a taken port would otherwise pay again.
checked_token: Option<String>,
status: AgentLinkStatus,
}
@@ -144,6 +148,7 @@ impl AgentLink {
applied: None,
retry_at: None,
retry: RETRY,
checked_token: None,
status: AgentLinkStatus::default(),
}
}
@@ -166,7 +171,12 @@ impl AgentLink {
/// Brings the server in line with `want` (`None`: agents may not connect): start it, restart it
/// on another port, stop it, or keep it while other settings change. Does nothing while `want`
/// equals the last call's and no retry of a failed start is due.
/// equals the last call's and no retry of a failed start is due. A token file refused as it is
/// (open to others, a damaged token) is replaced by a new one (`fresh_token`). One that still
/// can't be used (a folder in its place, a folder that can't be written) schedules no retry:
/// that lasts until someone changes it, and on Windows each check blocks the UI thread for
/// about 300 ms (`owner_only` starts `whoami` and PowerShell), which a retry every [`RETRY`]
/// turned into a stall every few seconds (photocraft#17006). Changing the settings tries again.
pub fn sync(&mut self, want: Option<&AgentSettings>, host: &WindowHost) -> LinkUpdate {
let mut update = LinkUpdate::default();
if self.launch.is_some() {
@@ -174,9 +184,15 @@ impl AgentLink {
}
let now = motion::now();
let retry_due = self.retry_at.is_some_and(|at| now >= at);
if self.applied.as_ref().is_some_and(|applied| applied.as_ref() == want) && !retry_due {
let unchanged = self.applied.as_ref().is_some_and(|applied| applied.as_ref() == want);
if unchanged && !retry_due {
return update;
}
// Only a retry with the same settings reuses the token its failed start checked: after a
// change (agents off and on again, another port) the file may hold another token by now.
if !unchanged {
self.checked_token = None;
}
let before = (self.status.clone(), self.applied.clone().flatten());
self.applied = Some(want.cloned());
self.retry_at = None;
@@ -218,6 +234,10 @@ impl AgentLink {
update.requests = Some(requests);
Ok(())
}
Err(problem @ LinkProblem::TokenFile(_)) => {
log::warn!("{problem}");
Err(problem)
}
Err(problem) => {
log::warn!("{problem}");
self.retry_at = Some(motion::now() + self.retry);
@@ -229,13 +249,21 @@ impl AgentLink {
/// The token from the settings folder (created `0600` when missing), the server, then the
/// connection file. Any failure leaves nothing running.
fn start(&self, dir: &Path, port: u16, port_pref: u32, host: &WindowHost) -> Result<(Running, Receiver<ControlRequest>), LinkProblem> {
/// A retry of a failed start reuses the token that start checked ([`Self::checked_token`]).
/// The token file is the link's own, so one refused as it is gets a new token (see
/// [`fresh_token`]).
fn start(&mut self, dir: &Path, port: u16, port_pref: u32, host: &WindowHost) -> Result<(Running, Receiver<ControlRequest>), LinkProblem> {
let token_file = dir.join(TOKEN_FILE);
let token = security::server_token(None, Some(&token_file)).map_err(|e| LinkProblem::TokenFile(e.to_string()))?;
let token = match self.checked_token.clone() {
Some(token) => token,
None => fresh_token(&token_file)?,
};
self.checked_token = Some(token.clone());
let (requests, server) = server::listen(port, token, host.clone()).map_err(|e| LinkProblem::Listen { port, error: e.to_string() })?;
let running = Running { server, dir: dir.to_path_buf(), port_pref };
let connection = Connection::new(running.server.addr.port(), token_file, self.app.clone());
write_connection(dir, &connection).map_err(|e| LinkProblem::Publish(e.to_string()))?;
self.checked_token = None;
Ok((running, requests))
}
@@ -250,3 +278,22 @@ impl AgentLink {
self.status.problem = Some(problem);
}
}
/// The token in `token_file`, created when missing. A regular file the check refuses (one an
/// older app wrote with its folder's access list on Windows, open to Administrators, or a damaged
/// token) is replaced with a new token, once: the token is only this link's secret, and a client
/// reads the new one from the file. Kept, its refusal would keep agents out until someone deleted
/// the file. Anything else in the way (a folder, a link) is reported, not removed.
fn fresh_token(token_file: &Path) -> Result<String, LinkProblem> {
let read = || security::server_token(None, Some(token_file)).map_err(|e| LinkProblem::TokenFile(e.to_string()));
let problem = match read() {
Ok(token) => return Ok(token),
Err(problem) => problem,
};
if !std::fs::symlink_metadata(token_file).is_ok_and(|meta| meta.is_file()) {
return Err(problem);
}
log::warn!("{problem}; writing a new token file");
std::fs::remove_file(token_file).map_err(|e| LinkProblem::TokenFile(format!("{}: {e}", token_file.display())))?;
read()
}
+72 -6
View File
@@ -5,8 +5,9 @@
//! (`engine.execute`, `ui.inspect`, `ui.set`, `ui.dialog.*`, `ui.screenshot`, …) and hands the
//! [`Reply`] to [`ControlChannel::settle`]. The channel replies at once, after the queued
//! injected input has been processed ([`Reply::AfterInput`], so a following `ui.inspect` sees
//! the effect), when a background job ends ([`Reply::AfterJob`]), or when a screenshot completes
//! ([`Reply::Screenshot`], through [`crate::screenshot::Captures`]).
//! the effect), when a background job ends ([`Reply::AfterJob`]), when the app answers a dialog's
//! held OK ([`Reply::AfterHeldOk`]), or when a screenshot completes ([`Reply::Screenshot`], through
//! [`crate::screenshot::Captures`]).
//!
//! Deadlines: a request still queued when its [`REPLY_DEADLINE`] passes is dropped before dispatch
//! and the transport replies [`expired_error`] (safe to re-send); one that was dispatched and gave
@@ -15,6 +16,7 @@
use std::sync::mpsc::{Receiver, Sender};
use craft_ui::dialog::{DialogHost, DialogId, HeldOk};
use craft_ui::runtime::motion;
use craft_ui::runtime::windows::WindowHost;
use serde_json::{Value, json};
@@ -133,6 +135,19 @@ pub enum Reply {
/// A `ui.accessTree`: hold the reply until the window's settled access tree can be read
/// ([`ControlChannel::poll_access_trees`]).
AccessTree,
/// A `ui.dialog.confirm` that filed the held OK of a dialog for the app: hold the reply until the
/// app answers it ([`ControlChannel::poll_held`]).
#[non_exhaustive]
AfterHeldOk {
/// The dialog whose OK is held.
dialog: DialogId,
/// Which open of the dialog ([`DialogHost::open_serial`]): a later open of the same dialog
/// is not the one the request confirmed.
open: u64,
/// The app's refusal of the dialog's previous OK, when this confirm filed OK again after it:
/// the earlier confirms still held for this open are answered with it.
refused: Option<String>,
},
}
impl Reply {
@@ -174,6 +189,7 @@ pub struct ControlChannel {
input_waiters: Vec<Sender<ControlResponse>>,
job_waiters: Vec<(JobId, Sender<ControlResponse>)>,
tree_waiters: Vec<Sender<ControlResponse>>,
held_waiters: Vec<(DialogId, u64, Sender<ControlResponse>)>,
/// The screenshot queue; the app calls its `issue` and `drain` from its UI and logic phases.
pub captures: Captures,
}
@@ -181,7 +197,14 @@ pub struct ControlChannel {
impl ControlChannel {
/// Attach a transport's receiver (TCP, stdin, tests).
pub fn new(rx: Receiver<ControlRequest>) -> Self {
Self { rx, input_waiters: Vec::new(), job_waiters: Vec::new(), tree_waiters: Vec::new(), captures: Captures::default() }
Self {
rx,
input_waiters: Vec::new(),
job_waiters: Vec::new(),
tree_waiters: Vec::new(),
held_waiters: Vec::new(),
captures: Captures::default(),
}
}
/// The next request to run, claimed through [`Dispatch::start`]. Expired or abandoned
@@ -200,8 +223,16 @@ impl ControlChannel {
/// Reply now, or park the reply on input, a job or a screenshot. `settle_ms` is the
/// screenshot settle delay ([`crate::screenshot::settle_ms`] of the animation time);
/// `document` the identity a screenshot is attributed to.
/// `document` the identity a screenshot is attributed to. A screenshot is admitted at
/// [`motion::now`]; [`Self::settle_at`] takes the time instead.
pub fn settle(&mut self, req: ControlRequest, outcome: Reply, document: Option<DocumentId>, settle_ms: f64) {
self.settle_at(req, outcome, document, settle_ms, motion::now());
}
/// [`Self::settle`] with a screenshot admitted at `now`: its settle delay and its
/// [`crate::screenshot::DEADLINE`] count from `now`, on the clock the app passes to
/// [`Captures::issue`] and [`Captures::drain`].
pub fn settle_at(&mut self, req: ControlRequest, outcome: Reply, document: Option<DocumentId>, settle_ms: f64, now: Instant) {
let reply = req.reply;
match outcome {
Reply::Done(v) => {
@@ -210,9 +241,21 @@ impl ControlChannel {
Reply::AfterInput => self.input_waiters.push(reply),
Reply::AfterJob(job) => self.job_waiters.push((job, reply)),
Reply::AccessTree => self.tree_waiters.push(reply),
Reply::AfterHeldOk { dialog, open, refused } => {
if let Some(reason) = refused {
self.held_waiters.retain(|(earlier, earlier_open, tx)| {
let answered = (*earlier, *earlier_open) == (dialog, open);
if answered {
let _ = tx.send(json!({"ok": false, "error": reason}));
}
!answered
});
}
self.held_waiters.push((dialog, open, reply));
}
Reply::Screenshot { token, path, region, viewport } => {
let request = ScreenshotRequest { token, path, region, viewport, reply, document, settle_ms };
if let Err((reply, e)) = self.captures.admit(request, motion::now()) {
if let Err((reply, e)) = self.captures.admit(request, now) {
let _ = reply.send(json!({"ok": false, "error": e}));
}
}
@@ -291,6 +334,29 @@ impl ControlChannel {
}
}
/// Answers the held `ui.dialog.confirm` requests ([`Reply::AfterHeldOk`]) from `host`: success
/// once the app accepted the dialog's held OK; once it refused it, an error whose text is the
/// refusal's reason, English for a reason given as a `Word`; an error once the dialog closed
/// while it waited, also when the same dialog opened again since. A request stays held while
/// the app has not answered. Call it in every pass after the app answered the held OKs it
/// answers in that pass and before the pass runs the host ([`DialogHost::run`]), which closes a
/// dialog the app accepted; calling it more than once in a pass is harmless.
pub fn poll_held(&mut self, host: &DialogHost) {
self.held_waiters.retain(|(dialog, open, reply)| {
let answer = match host.held_state(*dialog) {
_ if host.open_serial(*dialog) != Some(*open) => {
json!({"ok": false, "error": "the dialog closed while its OK waited for the app's answer"})
}
Some(HeldOk::Waiting) => return true,
Some(HeldOk::Accepted) => json!({"ok": true, "result": null}),
Some(HeldOk::Refused(reason)) => json!({"ok": false, "error": reason.as_str()}),
_ => json!({"ok": false, "error": "the app refused OK"}),
};
let _ = reply.send(answer);
false
});
}
/// Drops the host's queued input and the step in flight, and fails every
/// [`Reply::AfterInput`] waiter with `input cancelled: {reason}`, also when only waiters
/// remain (their input was already consumed). True when anything was pending or waiting.
@@ -331,6 +397,6 @@ impl ControlChannel {
/// Waiters of every kind, for `ui.inspect`'s `pending` count and tests.
pub fn waiting(&self) -> usize {
self.input_waiters.len() + self.job_waiters.len() + self.tree_waiters.len() + self.captures.pending()
self.input_waiters.len() + self.job_waiters.len() + self.tree_waiters.len() + self.held_waiters.len() + self.captures.pending()
}
}
+30 -3
View File
@@ -1,7 +1,8 @@
//! `ui.dialog.set`, `ui.dialog.confirm` and `ui.dialog.cancel` on an app's [`DialogHost`], for every dialog type.
//!
//! The app's method table hands these methods to [`dialog_method`] and lists [`inspect`] under `ui.inspect`'s
//! `dialogs`. A dialog is named by the `id` `inspect` lists, or `"top"` for the top one; its fields are its
//! The app's method table hands these methods to [`dialog_method`], or to [`dialog_reply`] for a reply that waits
//! for the app's answer to a held OK, and lists [`inspect`] under `ui.inspect`'s `dialogs`. A dialog is named by the
//! `id` `inspect` lists, or `"top"` for the top one; its fields are its
//! [`StackDialog::json_fields`](craft_ui::dialog::StackDialog::json_fields). Opening a dialog (`ui.dialog.open`) and
//! running the command its answer is for stay the app's: an answer waits for the app's `DialogHost::take` as a
//! click's would.
@@ -10,6 +11,7 @@ use craft_ui::dialog::{DialogHost, DialogId, HeldOk, StandardPrompt};
use egui::Context;
use serde_json::{Value, json};
use crate::control::Reply;
use crate::protocol::Params;
/// The most `fields` one `ui.dialog.set` call takes.
@@ -36,7 +38,8 @@ pub fn inspect(host: &DialogHost) -> Value {
/// - `ui.dialog.set {dialog, field, value}` sets one field ([`DialogHost::set_json_field`]); `{dialog, fields: [{field,
/// value?}]}` sets a list of at most [`MAX_DIALOG_FIELDS`], all or none ([`DialogHost::set_json_fields`]).
/// - `ui.dialog.confirm {dialog, choice?}` answers OK, as the default button would, after setting the `choice` field
/// when one is given (which button of a prompt). A dialog that holds its OK files it for the app, which answers it.
/// when one is given (which button of a prompt). A dialog that holds its OK files it for the app, which answers it;
/// a second confirm while that answer waits is refused.
/// - `ui.dialog.cancel {dialog}` closes the dialog as Escape would: a standard prompt with a button for its Escape
/// answer gives that answer, with its tag; any other dialog closes with its children with Cancel.
pub fn dialog_method(host: &mut DialogHost, ctx: &Context, method: &str, params: &Value) -> Option<Result<Value, String>> {
@@ -49,6 +52,26 @@ pub fn dialog_method(host: &mut DialogHost, ctx: &Context, method: &str, params:
Some(run(host, ctx, method, params, fields))
}
/// [`dialog_method`] as the [`Reply`] the app hands to [`ControlChannel::settle`](crate::ControlChannel::settle): a
/// `ui.dialog.confirm` that files a dialog's held OK for the app replies once the app answers it
/// ([`Reply::AfterHeldOk`], answered by [`ControlChannel::poll_held`](crate::ControlChannel::poll_held)), so a refusal
/// reaches the caller as the reply's error, in its reason's English text. Every other call replies at once.
pub fn dialog_reply(host: &mut DialogHost, ctx: &Context, method: &str, params: &Value) -> Option<Reply> {
// The dialog is named before the call: a confirm that closes it may leave another dialog on top.
let named = dialog_id(host, params).ok();
// A refusal this confirm replaces still answers the confirms it refused.
let refused = match named.and_then(|id| host.held_state(id)) {
Some(HeldOk::Refused(reason)) => Some(reason.as_str().to_owned()),
_ => None,
};
let result = dialog_method(host, ctx, method, params)?;
let held = named.filter(|&id| method == "ui.dialog.confirm" && result.is_ok() && host.held_state(id) == Some(HeldOk::Waiting));
Some(match held.and_then(|id| Some((id, host.open_serial(id)?))) {
Some((dialog, open)) => Reply::AfterHeldOk { dialog, open, refused },
None => Reply::from_result(result),
})
}
fn run(host: &mut DialogHost, ctx: &Context, method: &str, params: &Value, fields: &[&str]) -> Result<Value, String> {
let params = Params(params).only(None, fields)?;
let read = Params(&params);
@@ -67,6 +90,10 @@ fn run(host: &mut DialogHost, ctx: &Context, method: &str, params: &Value, field
}
},
"ui.dialog.confirm" => {
// A second OK while the first waits files nothing, as the disabled button shows.
if host.held_state(id) == Some(HeldOk::Waiting) {
return Err("the dialog's OK waits for the app's answer to an earlier OK".to_owned());
}
if let Some(choice) = params.get("choice") {
host.set_json_field(ctx, id, "choice", choice.clone())?;
}
+41 -23
View File
@@ -8,8 +8,11 @@
//! idle for [`IO_TIMEOUT`] is closed. Tokens are 64 hex characters in either case, kept
//! lower-cased by the server and compared in constant time with hex letters folded. None of this depends on the transport: the TCP server and a test channel share it.
#[cfg(not(windows))]
use std::fs::OpenOptions;
use std::io::{BufRead, Write};
use std::io::BufRead;
#[cfg(not(windows))]
use std::io::Write;
use std::path::Path;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::{Duration, Instant};
@@ -319,30 +322,34 @@ fn read_token_file(path: &Path) -> Result<String, AutomationError> {
Ok(token)
}
fn create_token_file(path: &Path, token: &str) -> Result<(), AutomationError> {
/// Create the token file `path` holding `token` and a newline. An error keeps the kind of the one
/// that caused it, with the path in its message.
fn create_token_file(path: &Path, token: &str) -> std::io::Result<()> {
let at = |p: &Path, e: std::io::Error| std::io::Error::new(e.kind(), format!("{}: {e}", p.display()));
if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
std::fs::create_dir_all(parent).map_err(|e| AutomationError::Io(format!("{}: {e}", parent.display())))?;
std::fs::create_dir_all(parent).map_err(|e| at(parent, e))?;
}
let mut options = OpenOptions::new();
options.write(true).create_new(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
let mut file = options.open(path).map_err(|e| AutomationError::Io(format!("{}: {e}", path.display())))?;
// On Windows the new file has its folder's access list: it is restricted to its user and SYSTEM before the token
// is written, and a file that cannot be restricted is removed rather than left for the token to go into later.
// On Windows the file is created with an access list of its user and SYSTEM only, so it never has its folder's
// access list, and the token is written through the handle that created it.
#[cfg(windows)]
{
use craft_platform::owner_only;
if let Err(e) = owner_only::current_user_sid().and_then(|me| owner_only::restrict_to_owner(path, &me)) {
drop(file);
let _ = std::fs::remove_file(path);
return Err(AutomationError::Io(format!("{}: cannot restrict the control token file to its owner: {e}", path.display())));
owner_only::current_user_sid()
.and_then(|me| owner_only::create_private_file(path, &me, format!("{token}\n").as_bytes()))
.map_err(|e| std::io::Error::new(e.kind(), format!("{}: cannot create the control token file for its owner only: {e}", path.display())))
}
#[cfg(not(windows))]
{
let mut options = OpenOptions::new();
options.write(true).create_new(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
let mut file = options.open(path).map_err(|e| at(path, e))?;
writeln!(file, "{token}").map_err(|e| at(path, e))
}
writeln!(file, "{token}").map_err(|e| AutomationError::Io(format!("{}: {e}", path.display())))
}
/// The server's token, lower-cased. Both given is
@@ -355,8 +362,19 @@ fn create_token_file(path: &Path, token: &str) -> Result<(), AutomationError> {
/// file can be reached by others: <why>; restrict it to its owner`), and its trimmed content is
/// validated. A missing one is created with a generated token (parent directories created,
/// `create_new`, mode 0600 on Unix, the user and SYSTEM only on Windows, the token and a
/// newline); losing that create race to another process reads the winner's file instead.
/// newline); losing that create race to another process reads the winner's file instead. On
/// Windows a create that does not finish in time fails (`I/O: <path>: cannot create the control
/// token file for its owner only: <why>`), and a file it left at the path is not read as a winner's.
pub fn server_token(supplied: Option<&str>, token_file: Option<&Path>) -> Result<String, AutomationError> {
server_token_with(supplied, token_file, create_token_file)
}
/// [`server_token`], with `create` making a missing token file.
fn server_token_with(
supplied: Option<&str>,
token_file: Option<&Path>,
create: impl FnOnce(&Path, &str) -> std::io::Result<()>,
) -> Result<String, AutomationError> {
if supplied.is_some() && token_file.is_some() {
return Err(token_conflict());
}
@@ -370,11 +388,11 @@ pub fn server_token(supplied: Option<&str>, token_file: Option<&Path>) -> Result
};
match read_token_file(path) {
Ok(existing) => Ok(existing.to_ascii_lowercase()),
Err(AutomationError::Io(_)) if !path.exists() => match create_token_file(path, &token) {
Err(AutomationError::Io(_)) if !path.exists() => match create(path, &token) {
Ok(()) => Ok(token),
// Another process won the create-new race.
Err(AutomationError::Io(_)) if path.exists() => read_token_file(path).map(|v| v.to_ascii_lowercase()),
Err(e) => Err(e),
// Another process won the create-new race. A file left by a create that ran out of time is this one's.
Err(e) if e.kind() != std::io::ErrorKind::TimedOut && path.exists() => read_token_file(path).map(|v| v.to_ascii_lowercase()),
Err(e) => Err(AutomationError::Io(e.to_string())),
},
Err(e) => Err(e),
}
+28
View File
@@ -141,6 +141,12 @@ fn server_token_sources_and_validation() {
use std::os::unix::fs::PermissionsExt;
assert_eq!(std::fs::metadata(&file).unwrap().permissions().mode() & 0o777, 0o600);
}
#[cfg(windows)]
{
use craft_platform::owner_only;
let sddl = owner_only::sddl_of(&file).unwrap();
assert_eq!(owner_only::foreign_access(&sddl, &owner_only::current_user_sid().unwrap()), None, "{sddl}");
}
assert_eq!(server_token(None, Some(&file)).unwrap(), created);
// An existing file's content is trimmed and lower-cased.
@@ -163,3 +169,25 @@ fn server_token_sources_and_validation() {
"bridge mode needs --control-token, --control-token-file, PHOTOCRAFT_CONTROL_TOKEN, or PHOTOCRAFT_CONTROL_TOKEN_FILE"
);
}
// A token file create that runs out of time fails with its own error, even when it left a file at
// the path: that file is not read as another process's. A create that another process beat to the
// path reads that process's token.
#[trial]
fn a_token_file_create_that_runs_out_of_time_is_an_error() {
let dir = scratch_dir("token-limit");
let file = dir.join("token");
let late = |p: &Path, _: &str| {
std::fs::write(p, "partial").unwrap();
Err(std::io::Error::new(std::io::ErrorKind::TimedOut, format!("{}: powershell.exe did not finish within 10 s and was ended", p.display())))
};
let err = server_token_with(None, Some(&file), late).unwrap_err().to_string();
assert!(err.starts_with("I/O: ") && err.ends_with("did not finish within 10 s and was ended"), "{err}");
std::fs::remove_file(&file).unwrap();
let beaten = |p: &Path, _: &str| {
create_token_file(p, TOKEN).unwrap();
Err(std::io::Error::new(std::io::ErrorKind::AlreadyExists, "the file already exists"))
};
assert_eq!(server_token_with(None, Some(&file), beaten).unwrap(), TOKEN);
let _ = std::fs::remove_dir_all(&dir);
}
+76 -4
View File
@@ -1,5 +1,5 @@
//! Synthetic pointer, keyboard, input-method, file-drop and access-tree input: `ui.click`, `ui.focus`, `ui.move`,
//! `ui.wheel`, `ui.key`, `ui.release`, `ui.type`, `ui.ime`, `ui.drop` and `ui.capsLock`.
//! `ui.drag`, `ui.wheel`, `ui.key`, `ui.release`, `ui.type`, `ui.ime`, `ui.drop` and `ui.capsLock`.
//!
//! This module reads and validates the protocol's parameters; the window host queues the input
//! ([`WindowHost::inject_move`], [`WindowHost::inject_click`], [`WindowHost::inject_wheel`],
@@ -12,7 +12,8 @@
//! withdraws a step queued for a document or focus that changed before the pass consumed it.
//!
//! Held input: `hold: true` on `ui.click` leaves its last press down and on `ui.key` its key, until `ui.release`; a
//! `ui.move` while a button is held drags. Each request names the modifiers held during it; a move or wheel leaves
//! `ui.move` while a button is held drags. `ui.drag` is the whole gesture in one request: a press, moves in even steps
//! and the release, queued together, so its reply waits for the release. Each request names the modifiers held during it; a move or wheel leaves
//! them held (a hover with modifiers across a screenshot), a click or key that holds nothing lets them go.
//!
//! Points are screen points (egui points), or document points with `coordinates: "document"`, which the application
@@ -22,8 +23,7 @@
//!
//! A node of the access tree (`id` or `label`, [`NodeTarget`]) is clicked or focused through the node's own action
//! instead of a point: [`crate::access::resolve`] finds it in the window's kept tree when the request arrives, so a
//! missing, ambiguous, disabled or undeclared node is refused before anything is queued. There is no `ui.drag`: a
//! drag is `ui.click {hold}`, `ui.move` and `ui.release`.
//! missing, ambiguous, disabled or undeclared node is refused before anything is queued.
use std::path::PathBuf;
@@ -43,6 +43,12 @@ pub const MAX_CLICKS: u64 = 256;
/// display, yet small enough that egui's pointer delta between two such points stays finite.
pub const MAX_SCREEN_POINT: f64 = 1e6;
/// Most moves one `ui.drag` may ask for (`steps`).
pub const MAX_DRAG_STEPS: u64 = 200;
/// The moves a `ui.drag` makes when its request names no `steps`.
pub const DRAG_STEPS: u64 = 12;
/// The longest hover rest one `ui.move` may ask for (`rest`, seconds).
pub const MAX_REST: f64 = 10.0;
@@ -302,6 +308,71 @@ impl Move {
}
}
/// A validated `ui.drag`: a press at one point, moves in even steps to another with the button down, and the release
/// there.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct Drag {
/// Where the button goes down.
pub from: At,
/// Where the button comes up.
pub to: At,
/// The button pressed.
pub button: PointerButton,
/// Moves from `from` to `to`; the last one lands on `to`.
pub steps: u64,
/// Modifiers held from the press to the release.
pub mods: Mods,
}
impl Drag {
/// `{from, to, button?, steps?, modifiers…}`, no other fields. `from` and `to` are each a point object
/// `{x?, y?, coordinates?, page?, control?}` in its own space, as `ui.click` reads its point; a missing one is
/// ``"missing `from`"``, and the errors inside one name it (``"from.x must be a finite number"``). `button`
/// defaults to `left`. `steps` is an unsigned integer from 1 to [`MAX_DRAG_STEPS`], default [`DRAG_STEPS`];
/// outside that range is ``"`steps` must be between 1 and 200 (got {steps})"``.
pub fn from_params(params: &Value) -> Result<Self, String> {
let p = Params(params).only(None, &["from", "to", "button", "steps", "modifiers", "shift", "alt", "command", "ctrl"])?;
let p = Params(&p);
let point = |name: &str| -> Result<At, String> {
let Some(point) = p.0.get(name) else { return Err(format!("missing `{name}`")) };
let point = Params(point).only(Some(name), &POINT)?;
At::from_params(&Params(&point)).map_err(|error| format!("{name}.{error}"))
};
let steps = p.uint_field("steps")?.unwrap_or(DRAG_STEPS);
if !(1..=MAX_DRAG_STEPS).contains(&steps) {
return Err(format!("`steps` must be between 1 and {MAX_DRAG_STEPS} (got {steps})"));
}
Ok(Self {
from: point("from")?,
to: point("to")?,
button: button(&p)?.unwrap_or(PointerButton::Primary),
steps,
mods: p.modifiers(&KEY_MODIFIERS)?,
})
}
/// Queues a move to `from` and a press there, `steps` moves in even steps to `to` with the button held, and the
/// release at `to`, in `viewport`; the modifiers are then let go unless other input stays held, as after a click.
/// Both points are placed before anything is queued (a control point against the access tree the host kept for
/// `viewport`), so a point that cannot be placed leaves no press down. When the host withdraws the rest of the
/// gesture after its press ran, the button stays down until `ui.release`, as any held input does.
pub fn inject(&self, host: &WindowHost, viewport: ViewportId, map: DocumentMap<'_>) -> Result<(), String> {
let (from, to) = (self.from.place(host, viewport, map)?, self.to.place(host, viewport, map)?);
let steps = u16::try_from(self.steps).unwrap_or(u16::MAX);
host.inject_click(viewport, from, self.button, 1, self.mods, true);
for step in 1..=steps {
let at = if step == steps { to } else { from.lerp(to, f32::from(step) / f32::from(steps)) };
host.inject_move(viewport, at, self.mods, 0.0);
}
host.inject_release(viewport, Some(to), Released::Button(self.button));
// A click of no presses at the pointer's place queues no event: it only lets the modifiers go when nothing
// stays held.
host.inject_click(viewport, to, self.button, 0, self.mods, false);
Ok(())
}
}
/// The most notches one `ui.wheel` turn in lines may ask for, either way.
pub const MAX_NOTCHES: f32 = 100.0;
@@ -429,6 +500,7 @@ pub fn input_method(method: &str, params: &Value, host: &WindowHost, viewport: V
"ui.focus" => Focus::from_params(params).and_then(|focus| focus.inject(host, viewport)),
"ui.drop" => drop_files(params, host, viewport, map),
"ui.move" => Move::from_params(params).and_then(|step| step.inject(host, viewport, map)),
"ui.drag" => Drag::from_params(params).and_then(|drag| drag.inject(host, viewport, map)),
"ui.wheel" => Wheel::from_params(params).and_then(|wheel| wheel.inject(host, viewport, map)),
"ui.key" => KeyPress::from_params(params).map(|key| key.inject(host, viewport)),
"ui.release" => Release::from_params(params).and_then(|release| release.inject(host, viewport, map)),
+90
View File
@@ -308,6 +308,96 @@ fn a_token_file_that_cannot_be_written_keeps_agents_out() {
TcpListener::bind(("127.0.0.1", port)).expect("the port was let go");
}
/// A refused token file is not tried again with the same settings: a retry can't succeed until someone changes the
/// file, and on Windows each check starts `whoami` and PowerShell on the UI thread, about 300 ms, which a retry every
/// few seconds turned into a stall that often (photocraft#17006). Changing the settings tries again.
#[trial]
fn a_refused_token_file_is_not_retried_until_the_settings_change() {
let dir = temp_dir("link-token-no-retry");
std::fs::create_dir(dir.path().join(TOKEN_FILE)).unwrap();
let host = host();
let mut link = AgentLink::new(Some(dir.path().to_path_buf()), "x").retry_after(Duration::ZERO);
let wanted = free_port();
assert!(link.sync(Some(&on(u32::from(wanted))), &host).requests.is_none());
assert!(matches!(link.status().problem, Some(LinkProblem::TokenFile(_))), "{:?}", link.status());
// The file is fixed, but the same settings don't look at it again.
std::fs::remove_dir(dir.path().join(TOKEN_FILE)).unwrap();
let same = link.sync(Some(&on(u32::from(wanted))), &host);
assert!(same.requests.is_none() && !same.changed, "no retry with the same settings");
assert!(matches!(link.status().problem, Some(LinkProblem::TokenFile(_))), "{:?}", link.status());
let changed = link.sync(Some(&on(0)), &host);
assert!(changed.requests.is_some(), "a settings change tries again");
assert_eq!(link.status().problem, None);
}
/// A token file the check refuses as it is (here a damaged token; on Windows also one an older app wrote with its
/// folder's access list, open to Administrators) is the link's own: it is replaced with a new token, so agents can
/// connect instead of staying out until someone deletes the file (photocraft#17006).
#[trial]
fn a_refused_token_file_is_replaced_with_a_new_token() {
let dir = temp_dir("link-token-refresh");
let file = dir.path().join(TOKEN_FILE);
std::fs::write(&file, "not a token\n").unwrap();
let host = host();
let mut link = AgentLink::new(Some(dir.path().to_path_buf()), "x");
assert!(link.sync(Some(&on(0)), &host).requests.is_some(), "{:?}", link.status());
assert_eq!(link.status().problem, None);
let token = std::fs::read_to_string(&file).unwrap();
assert_ne!(token.trim(), "not a token");
assert_eq!(token.trim().len(), 64, "a new token: {token:?}");
assert_eq!(read_connection(dir.path()).unwrap().expect("published").port, link.status().port.expect("listening"));
}
/// A retry of a taken port reuses the token its first try checked instead of reading the token file again (on Windows
/// that check is about 300 ms on the UI thread, photocraft#17006); a start that succeeded reads it afresh next time.
#[trial]
fn a_taken_port_retry_reuses_the_checked_token() {
let dir = temp_dir("link-token-reuse");
let host = host();
let mut link = AgentLink::new(Some(dir.path().to_path_buf()), "x").retry_after(Duration::ZERO);
let taken = TcpListener::bind("127.0.0.1:0").unwrap();
let port = u32::from(taken.local_addr().unwrap().port());
assert!(link.sync(Some(&on(port)), &host).requests.is_none());
assert!(matches!(link.status().problem, Some(LinkProblem::Listen { .. })), "{:?}", link.status());
// Reading the file now fails, so a retry that read it would report a token file problem.
std::fs::remove_file(dir.path().join(TOKEN_FILE)).unwrap();
std::fs::create_dir(dir.path().join(TOKEN_FILE)).unwrap();
drop(taken);
let retried = link.sync(Some(&on(port)), &host);
assert!(retried.requests.is_some(), "{:?}", link.status());
assert_eq!(link.status().problem, None);
// Once a start succeeded, the next one reads the file again.
let moved = link.sync(Some(&on(0)), &host);
assert!(moved.requests.is_none());
assert!(matches!(link.status().problem, Some(LinkProblem::TokenFile(_))), "{:?}", link.status());
}
/// The checked token is kept only for retries with the same settings: turning agents off and on again reads the token
/// file again, so a server never listens with a token the file no longer holds.
#[trial]
fn a_settings_change_reads_the_token_file_again() {
let dir = temp_dir("link-token-settings");
let host = host();
let mut link = AgentLink::new(Some(dir.path().to_path_buf()), "x").retry_after(Duration::ZERO);
let taken = TcpListener::bind("127.0.0.1:0").unwrap();
let port = u32::from(taken.local_addr().unwrap().port());
assert!(link.sync(Some(&on(port)), &host).requests.is_none());
assert!(matches!(link.status().problem, Some(LinkProblem::Listen { .. })), "{:?}", link.status());
assert!(!link.sync(None, &host).stopped, "nothing was running");
// While agents are off the token file changes; here it can't be read at all, which the next start must report.
std::fs::remove_file(dir.path().join(TOKEN_FILE)).unwrap();
std::fs::create_dir(dir.path().join(TOKEN_FILE)).unwrap();
drop(taken);
let back = link.sync(Some(&on(port)), &host);
assert!(back.requests.is_none(), "started with the token the file no longer holds");
assert!(matches!(link.status().problem, Some(LinkProblem::TokenFile(_))), "{:?}", link.status());
}
/// Dropping the link stops its server and removes its connection file.
#[trial]
fn dropping_the_link_removes_its_connection_file() {
+91 -2
View File
@@ -1,9 +1,13 @@
//! `ui.dialog.*` on typed dialogs through one generic path.
use craft_automation::dialogs::{MAX_DIALOG_FIELDS, dialog_method, inspect};
use std::sync::mpsc::{Receiver, channel};
use craft_automation::control::{ControlChannel, ControlRequest, ControlResponse};
use craft_automation::dialogs::{MAX_DIALOG_FIELDS, dialog_method, dialog_reply, inspect};
use craft_ui::contract::{Bind, SaveKey};
use craft_ui::dialog::{DialogHost, DialogResult, PromptChoice, PromptKind, StandardPrompt};
use craft_ui::dialog::{DialogHost, DialogId, DialogResult, PromptChoice, PromptKind, StandardPrompt};
use craft_ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind};
use craft_ui::runtime::env::{Label, Word};
use craft_ui::testing::trial;
use egui::Context;
use serde_json::{Value, json};
@@ -124,6 +128,91 @@ fn param_dialog_automation_follows_its_rows() {
assert_eq!((reopened.fields.number("radius"), reopened.fields.text("method")), (Some(7.0), Some("zoom")));
}
const TAKEN: Word = Word::keyed("craft_automation.nameTaken", "A preset with that name exists");
/// The open parameter dialog `id` names.
fn held(host: &mut DialogHost, id: DialogId) -> &mut HostedParamDialog {
host.get_dyn_mut(id).and_then(|dialog| dialog.downcast_mut::<HostedParamDialog>()).expect("the held dialog is open")
}
/// A `ui.dialog.confirm` that files a held OK replies with the app's answer: nothing while the app has not answered,
/// an error with the refusal's English text once it refuses, success once it accepts, and an error when the dialog
/// closes first, also when it opened again since. A second confirm while the answer waits is refused, and one after a
/// refusal no poll has read answers the earlier confirm with it. A dialog without a held OK replies at once.
#[trial]
fn a_confirm_of_a_held_ok_replies_with_the_apps_answer() {
let ctx = Context::default();
let mut host = DialogHost::new();
let (_requests, rx) = channel();
let mut control = ControlChannel::new(rx);
let dialog = |ctx: &Context, held: bool| {
let dialog = HostedParamDialog::new(ctx, "blur", DialogFields::new(), |fields| {
ParamDialog::new("blur", "Blur", Param::parse_list(r#"{"radius":0.1..1000=1}"#)).values(Bind::bound(fields))
});
if held { dialog.held_ok() } else { dialog }
};
let confirm = |host: &mut DialogHost, control: &mut ControlChannel, id: DialogId| -> Receiver<ControlResponse> {
let (request, reply) = ControlRequest::new("ui.dialog.confirm", json!({"dialog": id.value()}));
let outcome = dialog_reply(host, &ctx, &request.method, &request.params).expect("a ui.dialog method");
control.settle(request, outcome, None, 0.0);
reply
};
let id = host.open(dialog(&ctx, true));
let reply = confirm(&mut host, &mut control, id);
control.poll_held(&host);
assert!(reply.try_recv().is_err(), "the reply waits for the app's answer");
assert_eq!(control.waiting(), 1);
let again = confirm(&mut host, &mut control, id);
assert!(again.try_recv().is_ok_and(|reply| reply["ok"] == false), "a second OK while the first waits is refused");
assert_eq!(control.waiting(), 1);
assert!(held(&mut host, id).take_ok().is_some(), "OK filed the answer for the app");
held(&mut host, id).answer_ok(Err(Label::from(TAKEN)));
control.poll_held(&host);
assert_eq!(reply.try_recv(), Ok(json!({"ok": false, "error": "A preset with that name exists"})));
assert_eq!(control.waiting(), 0);
// A confirm after a refusal no poll has read yet answers the earlier confirm with that refusal.
let first = confirm(&mut host, &mut control, id);
assert!(held(&mut host, id).take_ok().is_some(), "OK files the answer again after a refusal");
held(&mut host, id).answer_ok(Err(Label::from(TAKEN)));
let reply = confirm(&mut host, &mut control, id);
assert_eq!(first.try_recv(), Ok(json!({"ok": false, "error": "A preset with that name exists"})));
assert_eq!(control.waiting(), 1);
assert!(held(&mut host, id).take_ok().is_some());
held(&mut host, id).answer_ok(Ok(()));
control.poll_held(&host);
assert_eq!(reply.try_recv(), Ok(json!({"ok": true, "result": null})));
assert!(host.confirm_by_id(&ctx, id), "the accepted dialog closes");
assert!(matches!(host.take_keyed::<HostedParamDialog>(), Some((DialogResult::Ok(_), _))));
let id = host.open(dialog(&ctx, true));
let reply = confirm(&mut host, &mut control, id);
assert!(host.cancel_by_id(&ctx, id));
control.poll_held(&host);
let closed = reply.try_recv().expect("a closed dialog answers the held confirm");
assert_eq!(closed["ok"], false);
assert!(closed["error"].as_str().is_some_and(|error| error.contains("closed")), "{closed}");
host.take_keyed::<HostedParamDialog>();
// The same dialog opened again is a new open: its answer is not the closed one's.
let id = host.open(dialog(&ctx, true));
let reply = confirm(&mut host, &mut control, id);
assert!(host.cancel_by_id(&ctx, id));
assert_eq!(host.open(dialog(&ctx, true)), id, "a reopened dialog has the same id");
assert_eq!(control.waiting(), 1);
control.poll_held(&host);
let closed = reply.try_recv().expect("the closed open's confirm is answered");
assert!(closed["error"].as_str().is_some_and(|error| error.contains("closed")), "{closed}");
assert!(host.cancel_by_id(&ctx, id));
host.take_keyed::<HostedParamDialog>();
let id = host.open(dialog(&ctx, false));
let reply = confirm(&mut host, &mut control, id);
assert_eq!(reply.try_recv(), Ok(json!({"ok": true, "result": null})), "a dialog without a held OK replies at once");
assert_eq!(control.waiting(), 0);
}
/// A `fields` list sets every field or none: a refused field in the middle leaves the dialog as it was and gives that
/// refusal; a list over the limit, an item without a string `field` and `field` beside `fields` are refused unread.
#[trial]
+28
View File
@@ -248,6 +248,34 @@ fn a_request_past_its_deadline_times_out() {
}
}
/// A screenshot settled at a given time counts its settle delay and its deadline from that time, on the clock the app
/// also passes to `issue` and `drain`, not from the wall clock.
#[trial]
fn a_screenshot_settled_at_a_time_counts_from_that_time() {
use craft_automation::control::{ControlChannel, ControlRequest, Reply};
use craft_automation::screenshot::ScreenshotParams;
use serde_json::json;
let ctx = Context::default();
// An app clock ahead of the wall clock.
let arrived = motion::now() + Duration::from_secs(60);
let (_transport, requests) = channel();
let mut control = ControlChannel::new(requests);
control.captures.note_geometry(ViewportId::ROOT, geometry(800.0, 600.0));
let (request, rx) = ControlRequest::new("ui.screenshot", json!({}));
let params = ScreenshotParams::from_params(&json!({})).expect("no params");
control.settle_at(request, Reply::screenshot(1, params, ViewportId::ROOT), None, 500.0, arrived);
assert!(rx.try_recv().is_err(), "the reply waits for the capture");
let (finished, callbacks) = settle_and_issue(&mut control.captures, &ctx, arrived + Duration::from_millis(400), None);
assert!(finished.is_empty(), "inside its deadline: {:?}", finished.iter().map(error).collect::<Vec<_>>());
assert!(callbacks.is_empty(), "not issued inside its settle delay");
assert!(control.captures.drain(arrived + DEADLINE - Duration::from_millis(1), None).is_empty(), "inside its deadline");
let finished = control.captures.drain(arrived + DEADLINE, None);
assert_eq!(finished.len(), 1);
assert!(error(&finished[0]).contains("timed out"), "{}", error(&finished[0]));
}
/// Cancelling releases the budget at once; an image that arrives afterwards is dropped.
#[trial]
fn cancellation_releases_the_budget_and_drops_a_late_image() {
+76 -3
View File
@@ -1,12 +1,12 @@
//! Synthetic input through the window host: held presses and keys, modifiers, the wheel, Caps Lock, hover rest,
//! Synthetic input through the window host: held presses and keys, drags, modifiers, the wheel, Caps Lock, hover rest,
//! document coordinates and input-method compositions, as the passes see them, and the params refused before
//! anything is queued.
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use craft_automation::access::NO_TREE;
use craft_automation::synthetic::{At, Click, Focus, MAX_CLICKS, MAX_SCREEN_POINT, NO_DOCUMENT, NOT_FINITE, input_method};
use craft_automation::access::{NO_CONTROL, NO_TREE};
use craft_automation::synthetic::{At, Click, Focus, MAX_CLICKS, MAX_DRAG_STEPS, MAX_SCREEN_POINT, NO_DOCUMENT, NOT_FINITE, input_method};
use craft_ui::contract::{Bind, Show as _};
use craft_ui::runtime::egui::injected::hook_without_pass;
use craft_ui::runtime::windows::WindowHost;
@@ -123,6 +123,52 @@ fn a_held_press_stays_down_until_its_release() {
assert!(!rig.now().primary_down, "a click without hold releases");
}
/// `ui.drag` presses at `from`, moves to `to` in `steps` even steps with the button down, releases at `to` with its
/// modifiers held throughout, then lets them go. Each point is in its own space: `to` here is a document point.
#[trial]
fn a_drag_presses_moves_in_steps_and_releases_at_its_end() {
let mut rig = Rig::new();
rig.fx.settle();
rig.take();
let to = map(0, pos2(220.0, 40.0)).expect("the test map places every point");
rig.send("ui.drag", json!({"from": {"x": 10, "y": 20}, "to": {"x": 220, "y": 40, "coordinates": "document"}, "steps": 4, "shift": true}));
let after = rig.now();
let events: Vec<Event> = rig.take().into_iter().flat_map(|pass| pass.events).collect();
let buttons: Vec<(Pos2, bool, bool)> = events
.iter()
.filter_map(|event| match event {
Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers } => Some((*pos, *pressed, modifiers.shift)),
_ => None,
})
.collect();
assert_eq!(buttons, vec![(pos2(10.0, 20.0), true, true), (to, false, true)], "one press at `from`, one release at `to`, both with Shift");
let held = events.iter().skip_while(|event| !matches!(event, Event::PointerButton { pressed: true, .. }));
let moves: Vec<Pos2> = held
.take_while(|event| !matches!(event, Event::PointerButton { pressed: false, .. }))
.filter_map(|event| match event {
Event::PointerMoved(at) => Some(*at),
_ => None,
})
.collect();
assert_eq!(moves.len(), 4, "one move per step while the button is down: {moves:?}");
assert!(moves.windows(2).all(|pair| pair[1].x > pair[0].x), "each step goes further towards `to`: {moves:?}");
assert_eq!(moves.last(), Some(&to), "the last step lands on `to`");
assert!(!after.primary_down && !after.shift, "the drag leaves no button or modifier held");
}
/// A drag keeps its modifiers held after its release while other input stays down, as a click does.
#[trial]
fn a_drag_keeps_its_modifiers_while_a_held_key_stays_down() {
let mut rig = Rig::new();
rig.send("ui.key", json!({"key": "Space", "hold": true}));
rig.send("ui.drag", json!({"from": {"x": 10, "y": 10}, "to": {"x": 60, "y": 10}, "steps": 2, "shift": true}));
let after = rig.now();
assert!(after.space_down && !after.primary_down, "the key stays down and the drag's button is up");
assert!(after.shift, "the modifiers stay with the held key");
rig.send("ui.release", json!({}));
assert!(!rig.now().space_down && !rig.now().shift, "the release lets everything go");
}
/// A move's modifiers stay held after it (a hover with modifiers); a click that holds nothing lets its own go.
#[trial]
fn a_move_keeps_its_modifiers_and_a_click_lets_them_go() {
@@ -292,6 +338,25 @@ fn document_points_need_a_canvas() {
assert_eq!(screen, Some(Ok(())));
}
/// A drag whose end cannot be placed is refused whole: its press at a screen point is not queued either. That holds
/// for a document end without a canvas and for a control end that names no control of the window.
#[trial]
fn a_drag_with_an_end_it_cannot_place_queues_no_press() {
let mut rig = Rig::new();
rig.fx.settle();
let (host, ctx) = (rig.host(), rig.fx.ctx().clone());
let none = |_: usize, _: Pos2| None;
let params = json!({"from": {"x": 1, "y": 1}, "to": {"x": 5, "y": 5, "coordinates": "document"}});
assert_eq!(input_method("ui.drag", &params, &host, ViewportId::ROOT, &none), Some(Err(NO_DOCUMENT.to_owned())));
assert!(host.injected_idle());
assert!(hook_without_pass(&ctx, ViewportId::ROOT).is_empty(), "the refused drag queued nothing");
let params = json!({"from": {"x": 1, "y": 1}, "to": {"control": {"name": "Save"}, "x": 4}});
let answer = input_method("ui.drag", &params, &host, ViewportId::ROOT, &map);
assert!(matches!(&answer, Some(Err(error)) if error.starts_with(NO_CONTROL)), "{answer:?}");
assert!(host.injected_idle());
assert!(hook_without_pass(&ctx, ViewportId::ROOT).is_empty(), "the drag to an unplaced control queued nothing");
}
/// A step handed to the input whose pass has not run is withdrawn when the focus moved, and when the application
/// withdraws the input because its document changed: the integration's preserved copy leaves the input, no key
/// stays down, and the waiters fail with `TARGET_CHANGED`.
@@ -358,6 +423,14 @@ fn bad_input_params_are_refused_before_anything_is_queued() {
("ui.move", json!({"x": 10, "y": 10, "rest": "long"})),
("ui.move", json!({"x": 10, "y": 10, "coordinates": "page"})),
("ui.move", json!({"x": 10, "y": -far})),
("ui.drag", json!({"from": {"x": 10}})),
("ui.drag", json!({"from": {"x": 10}, "to": {"x": 20, "nudge": 1}})),
("ui.drag", json!({"from": {"x": 10}, "to": [20, 20]})),
("ui.drag", json!({"from": {"x": 10}, "to": {"x": far}})),
("ui.drag", json!({"from": {"x": 10}, "to": {"x": 20}, "steps": 0})),
("ui.drag", json!({"from": {"x": 10}, "to": {"x": 20}, "steps": MAX_DRAG_STEPS + 1})),
("ui.drag", json!({"from": {"x": 10}, "to": {"x": 20}, "x": 5})),
("ui.drag", json!({"from": {"x": 10}, "to": {"control": {"name": "Save"}, "coordinates": "document"}})),
("ui.key", json!({"key": "A", "hold": true, "nudge": 1})),
("ui.key", json!({"key": 5})),
("ui.key", json!({"key": "NoSuchKey", "hold": true})),
+11 -1
View File
@@ -578,7 +578,17 @@ impl<P: Clone + Eq + Hash> Layout<P> {
moving.column.groups.iter_mut().for_each(|group| group.height = height);
}
let index = place.group_index().ok_or(DockError::InvalidPlacement)?;
let groups = &mut self.column_mut(&place).ok_or(DockError::MissingTarget)?.groups;
let column = self.column_mut(&place).ok_or(DockError::MissingTarget)?;
// Groups shown at a width of their own, in a floating window or an expanded column, keep it
// as the flyout width of the collapsed column they join.
if column.iconic
&& !moving.column.iconic
&& let Some(width) = moving.column.width
{
let flyout = (column.width != Some(width)).then_some(width);
moving.column.groups.iter_mut().for_each(|group| group.flyout_width = flyout);
}
let groups = &mut column.groups;
let index = (index + usize::from(below)).min(groups.len());
groups.splice(index..index, moving.column.groups);
Ok(())
+18 -1
View File
@@ -42,7 +42,8 @@ pub struct Workspace<P> {
#[serde(default)]
hidden: Vec<(P, Location<P>)>,
/// Floating panels, and closed panels that were floating, with the docked location each one left, so Dock Panel
/// can return it. A closed panel's record lives as long as its `hidden` record. Saved with the workspace.
/// can return it; a closed panel that floats records the place it would reopen at. A closed panel's record lives
/// as long as its `hidden` record. Saved with the workspace.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
floated: Vec<(P, Location<P>)>,
/// Counts the replacements of this live workspace. Not saved, and not part of equality.
@@ -264,6 +265,16 @@ impl<P: Clone + Eq + Hash> Workspace<P> {
Action::Open { panel, .. } if proposed.hidden.iter().any(|(p, _)| p == panel) => proposed.reopen(panel, &policy)?,
_ => false,
};
// Floating a hidden panel records the docked place it would reopen at, without reopening it there. A panel
// that would reopen in a floating window has no docked place.
let hidden_place = match &action {
Action::Float { panel, .. } if !proposed.layout.contains(panel) && proposed.hidden.iter().any(|(p, _)| p == panel) => proposed
.restored(panel, &policy)
.filter(|restored| !floats(&restored.layout, panel))
.and_then(|restored| restored.layout.location(panel).ok())
.map(|location| (panel.clone(), location)),
_ => None,
};
if !reopened {
// SetNative records where the window system has a floating window, so a lock
// does not refuse it.
@@ -278,6 +289,12 @@ impl<P: Clone + Eq + Hash> Workspace<P> {
proposed.hidden.push((panel, location));
}
proposed.track_floated(&before);
if let Some((panel, location)) = hidden_place
&& floats(&proposed.layout, &panel)
&& !proposed.floated.iter().any(|(p, _)| p == &panel)
{
proposed.floated.push((panel, location));
}
all_closed.extend(closed);
}
let visible: HashSet<P> = proposed.layout.panels().into_iter().cloned().collect();
+47 -16
View File
@@ -1,6 +1,7 @@
//! The fit rules: which tabs, bar items or titles stay in a strip and which go to an overflow menu. [`fit`] and
//! [`fit_whole`] assign tab widths (tabs shrink before they overflow, or keep their width); [`fit_items`] shortens
//! items that have a short form, then drops command items and titles from the end. All of them read no egui types.
//! items that have a short form, in the order their host ranks, and drops command items and titles from the end.
//! All of them read no egui types.
/// Tabs visible on a strip and tabs that need an overflow menu, all in original order.
#[derive(Clone, Debug, Default, PartialEq)]
@@ -230,19 +231,39 @@ pub struct FitItem {
pub keep: FitKeep,
/// The extent of the item's shorter form, if it has one.
pub short: Option<f32>,
/// The rank of the item's short form: lower ranks shorten first, and equal ranks shorten the last item first.
pub short_order: u16,
/// Whether the item keeps its full form until no more free items can leave.
pub short_late: bool,
}
impl FitItem {
/// An item `extent` long in `section`.
pub const fn new(extent: f32, section: u16, keep: FitKeep) -> Self {
FitItem { extent, section, keep, short: None }
FitItem { extent, section, keep, short: None, short_order: 0, short_late: false }
}
/// The item with a shorter form `extent` long, which it takes before any free item leaves.
/// The item with a shorter form `extent` long, which it takes before any free item leaves unless it is late.
/// An item marked [`FitItem::short_late`] takes that form only after no free item is left to leave.
pub const fn short(mut self, extent: f32) -> Self {
self.short = Some(extent);
self
}
/// The item with its short form ranked `order`: lower ranks shorten first, and the last item of a rank first.
/// Every item ranks 0 by default.
pub const fn short_order(mut self, order: u16) -> Self {
self.short_order = order;
self
}
/// The item takes its short form only after every free item that can leave has left.
/// The other items go to the overflow menu before this one shortens. A free item with a late short form leaves
/// in its turn instead.
pub const fn short_late(mut self) -> Self {
self.short_late = true;
self
}
}
/// Which items the strip shows and which go to the overflow menu, as indexes into the input, in input order.
@@ -277,11 +298,13 @@ pub fn run_extent(items: &[FitItem], shown: &[bool], gap: f64, section_gap: f64)
}
/// Decides which items stay in a strip `available` long. Everything fits and no item is `Menu`: all items show.
/// Otherwise the `Menu` items are in the menu, and the items with a [`FitItem::short`] form take it first, the last
/// one first, until the run fits (listed in [`Fit::short`]); a `Pinned` item shortens as a `Free` one does. Only then
/// does the last `Free` item leave, one at a time, until the rest and an overflow control `overflow_extent` long,
/// set off by `gap`, fit; `Pinned` items stay even when they alone are longer than `available`. Items that leave are
/// never listed as short. Negative and non-finite lengths count as zero.
/// Otherwise the `Menu` items are in the menu, and the items with a [`FitItem::short`] form take it first, lowest
/// [`FitItem::short_order`] first and the last item of a rank first, until the run fits (listed in [`Fit::short`]); a
/// `Pinned` item shortens as a `Free` one does. Only then does the last `Free` item leave, one at a time, until the
/// rest and an overflow control `overflow_extent` long, set off by `gap`, fit. When no `Free` item is left to go, the
/// items marked [`FitItem::short_late`] take their short forms in the same order; items that left do not come back.
/// `Pinned` items stay even when they alone are longer than `available`. Items that leave are never listed as short.
/// Negative and non-finite lengths count as zero.
pub fn fit_items(items: &[FitItem], available: f32, gap: f32, section_gap: f32, overflow_extent: f32) -> Fit {
let (available, gap, section_gap, overflow_extent) =
(item_extent(available), item_extent(gap), item_extent(section_gap), item_extent(overflow_extent));
@@ -302,19 +325,27 @@ pub fn fit_items(items: &[FitItem], available: f32, gap: f32, section_gap: f32,
// The shadow run holds each item at the extent it takes: shortened items at their `short` extent.
let mut run: Vec<FitItem> = items.to_vec();
let mut short = vec![false; items.len()];
while !fits(&run, &shown) {
let Some(last) = (0..items.len()).rev().find(|&at| shown[at] && !short[at] && items[at].short.is_some()) else {
break;
};
short[last] = true;
if let (Some(item), Some(extent)) = (run.get_mut(last), items[last].short) {
item.extent = extent;
// Takes the short forms of the shown items with this `late` mark, lowest rank first and the last item of a rank
// first (`min_by_key` keeps the first minimum, which is the last index in a reversed scan), until the run fits.
let shorten = |late: bool, run: &mut [FitItem], short: &mut [bool], shown: &[bool]| {
while !fits(run, shown) {
let next = (0..items.len())
.rev()
.filter(|&at| shown[at] && !short[at] && items[at].short.is_some() && items[at].short_late == late)
.min_by_key(|&at| items[at].short_order);
let Some(next) = next else { break };
short[next] = true;
if let (Some(item), Some(extent)) = (run.get_mut(next), items[next].short) {
item.extent = extent;
}
}
}
};
shorten(false, &mut run, &mut short, &shown);
while !fits(&run, &shown) {
let Some(last) = (0..items.len()).rev().find(|&at| shown[at] && items[at].keep == FitKeep::Free) else { break };
shown[last] = false;
}
shorten(true, &mut run, &mut short, &shown);
let (kept, left): (Vec<usize>, Vec<usize>) = (0..items.len()).partition(|&at| shown[at]);
let short = kept.iter().copied().filter(|&at| short[at]).collect();
Fit { shown: kept, overflow: left, short }
+80 -6
View File
@@ -85,15 +85,12 @@ pub struct GridCursor {
impl GridCursor {
/// A cursor over `columns` in `flow`'s rect, with `gap` between columns (x) and rows (y), placed by `last`. A
/// column is never narrower than its least in `last`: a `Content` column starts there, and a `Fill` column's share
/// does not go below it.
/// does not go below it. A `Fill` column raised to its least takes the difference from the other `Fill` columns.
pub fn new(flow: Flow, columns: &[ColumnWidth], gap: Vec2, last: &GridMeasure) -> Self {
let least = |i: usize| last.least.get(i).copied().unwrap_or(0.0);
let content: Vec<f32> = (0..columns.len()).map(|i| last.columns.get(i).copied().unwrap_or(0.0).max(least(i))).collect();
let widths = resolve_columns(columns, &content, flow.rect().width(), gap.x)
.into_iter()
.enumerate()
.map(|(i, width)| if matches!(columns[i], ColumnWidth::Fill { .. }) { width.max(least(i)) } else { width })
.collect();
let mut widths = resolve_columns(columns, &content, flow.rect().width(), gap.x);
keep_fill_least(columns, &mut widths, least);
let fills = columns.iter().map(|kind| matches!(kind, ColumnWidth::Fill { .. })).collect();
GridCursor {
flow,
@@ -266,6 +263,44 @@ impl GridCursor {
}
}
/// Shares the room the `Fill` columns of `widths` hold among them again so that none is narrower than its `least`: a
/// column whose share by weight is below its least takes its least, and the columns left share the rest by weight.
/// The fill columns together take more than their room only when their least widths do not fit in it.
fn keep_fill_least(columns: &[ColumnWidth], widths: &mut [f32], least: impl Fn(usize) -> f32) {
let fills: Vec<(usize, f32)> = columns
.iter()
.enumerate()
.filter_map(|(i, column)| if let ColumnWidth::Fill { weight } = column { Some((i, *weight)) } else { None })
.collect();
let room: f32 = fills.iter().map(|(i, _)| widths[*i]).sum();
if !room.is_finite() {
// Room with no bound leaves every share above its least.
for (i, _) in &fills {
widths[*i] = widths[*i].max(least(*i));
}
return;
}
let mut raised = vec![false; columns.len()];
loop {
let left = room - fills.iter().filter(|(i, _)| raised[*i]).map(|(i, _)| least(*i)).sum::<f32>();
let weights: f32 = fills.iter().filter(|(i, _)| !raised[*i]).map(|(_, weight)| weight).sum();
let share = |weight: f32| if weights > 0.0 { left.max(0.0) * weight / weights } else { 0.0 };
let mut more = false;
for (i, weight) in &fills {
if !raised[*i] && share(*weight) < least(*i) {
raised[*i] = true;
more = true;
}
}
if !more {
for (i, weight) in &fills {
widths[*i] = if raised[*i] { least(*i) } else { share(*weight).max(least(*i)) };
}
return;
}
}
}
/// `columns` with each `Fill` column as a `Content` column.
fn as_content(columns: &[ColumnWidth]) -> Vec<ColumnWidth> {
columns.iter().map(|kind| if matches!(kind, ColumnWidth::Fill { .. }) { ColumnWidth::Content } else { *kind }).collect()
@@ -288,4 +323,43 @@ mod tests {
cursor.cell(Vec2::new(150.0, 100.0));
assert_eq!(cursor.room(), Vec2::new(200.0, 100.0), "the content cell may take what the fill column holds");
}
/// The widths of one row of `columns` placed by `last`, read from the cells.
fn row_widths(columns: &[ColumnWidth], last: &GridMeasure) -> Vec<f32> {
let mut cursor = GridCursor::new(flow(false), columns, Vec2::ZERO, last);
columns.iter().map(|_| cursor.cell(Vec2::new(10.0, 10.0)).width()).collect()
}
#[test]
fn a_fill_column_raised_to_its_least_takes_the_difference_from_the_other_fill_columns() {
let columns = [ColumnWidth::fill(1.0), ColumnWidth::fill(2.0), ColumnWidth::fill(1.0), ColumnWidth::Content];
let fitting = GridMeasure::new(vec![0.0, 0.0, 0.0, 60.0], vec![10.0]);
let shares = row_widths(&columns, &fitting);
let raised = row_widths(&columns, &fitting.clone().with_least(vec![120.0, 0.0, 0.0, 0.0]));
assert!(shares[0] < 120.0, "the first column's share is below its least");
assert!(raised[0] >= 120.0, "the first column keeps its least");
assert!(raised[1] < shares[1] && raised[2] < shares[2], "the other fill columns narrow");
assert_eq!(raised[1], 2.0 * raised[2], "the other fill columns keep their weights");
assert_eq!(raised[3], shares[3], "the content column keeps its width");
assert_eq!(raised.iter().sum::<f32>(), 300.0, "the row fills the grid and no more");
}
#[test]
fn fill_columns_whose_least_widths_do_not_fit_take_their_least_widths() {
let columns = [ColumnWidth::fill(1.0), ColumnWidth::fill(1.0), ColumnWidth::fill(1.0), ColumnWidth::Content];
let last = GridMeasure::new(vec![0.0, 0.0, 0.0, 60.0], vec![10.0]).with_least(vec![200.0, 70.0, 0.0, 0.0]);
let widths = row_widths(&columns, &last);
assert!(widths[0] >= 200.0 && widths[1] >= 70.0, "each fill column keeps its least");
assert_eq!(widths[2], 0.0, "the fill column with no least gives up its room");
assert_eq!(widths.iter().sum::<f32>(), 330.0, "the row is as wide as the least widths and no wider");
}
#[test]
fn fill_columns_whose_shares_cover_their_least_widths_keep_their_shares() {
let columns = [ColumnWidth::fill(1.0), ColumnWidth::fill(1.0), ColumnWidth::fill(1.0), ColumnWidth::Content];
let last = GridMeasure::new(vec![0.0, 0.0, 0.0, 60.0], vec![10.0]);
let shares = row_widths(&columns, &last);
let kept = row_widths(&columns, &last.clone().with_least(vec![50.0, 50.0, 50.0, 0.0]));
assert_eq!(kept, shares);
}
}
+62 -14
View File
@@ -18,9 +18,10 @@ fn is_unit_char(c: char) -> bool {
}
/// Whether `spelling` can be registered with [`Reader::unit`]: letters and unit symbols only, so the reader can
/// tell it from a number or an operator.
/// tell it from a number or an operator, or one `/` followed by them (`/in`, a count per inch).
pub fn is_unit_spelling(spelling: &str) -> bool {
!spelling.is_empty() && spelling.chars().all(is_unit_char)
let letters = spelling.strip_prefix('/').unwrap_or(spelling);
!letters.is_empty() && letters.chars().all(is_unit_char)
}
/// A unit spelling and the factor that turns its quantity into the base unit.
@@ -41,7 +42,9 @@ struct Unit {
/// (`3cm*50%` is 1.5 cm), whatever `%` means elsewhere. Text that starts with `+`, `*` or `/` is relative: it
/// applies to the start value (`+5` adds 5, `*2` doubles). A leading `-` is a negative number. A unit is the longest
/// registered spelling at the start of the letters after a number, so `2inx3` is `2in` times 3 and `2px` stays a
/// quantity when `px` is registered. A group separator counts only before exactly three digits.
/// quantity when `px` is registered. A registered spelling that starts with `/` (`/in`) is a unit when the letters after
/// the `/` start it, so `40/in` is 40 of it; any other `/` divides (`80/2`). A group separator counts only before
/// exactly three digits.
#[derive(Clone, Debug, PartialEq)]
pub struct Reader {
decimal: char,
@@ -79,7 +82,8 @@ impl Reader {
self
}
/// The digit-group separator, which the reader skips between digits.
/// The digit-group separator, which the reader skips between digits. A comma or point after zero reads as a
/// decimal when it is the number's only separator and digits follow it.
#[must_use]
pub fn group(mut self, group: char) -> Self {
self.group = Some(group);
@@ -213,8 +217,9 @@ impl Parse<'_> {
}
}
/// A number and the longest registered unit spelling at the start of the letters after it. Letters that start no
/// unit stay unread: a product sign (`2x3`) takes them, and anything else leaves the text unread, which refuses it.
/// A number and the longest registered unit spelling at the start of the letters after it, or after a `/` when a
/// registered spelling starts with `/`. Letters that start no unit stay unread: a product sign (`2x3`) takes them,
/// and anything else leaves the text unread, which refuses it. A `/` that starts no unit is left to divide.
fn quantity(&mut self, scaled: bool) -> Result<f64, NotAValue> {
let number = self.number()?;
self.tag = None;
@@ -223,8 +228,11 @@ impl Parse<'_> {
return Ok(number / 100.0);
}
let reader = self.reader;
let run: Vec<char> = self.chars[self.at..].iter().copied().take_while(|c| is_unit_char(*c)).collect();
let unit = (1..=run.len()).rev().find_map(|len| {
let after = &self.chars[self.at..];
let slash = usize::from(after.first() == Some(&'/'));
let letters = after[slash..].iter().take_while(|c| is_unit_char(**c)).count();
let run = &after[..slash + letters];
let unit = (1 + slash..=run.len()).rev().find_map(|len| {
let lowered = run[..len].iter().collect::<String>().to_lowercase();
reader.units.iter().find(|unit| unit.spelling == lowered).map(|unit| (len, unit))
});
@@ -243,11 +251,6 @@ impl Parse<'_> {
}
}
/// Whether the group separator at `at` is followed by exactly three digits.
fn three_digits_after(&self, at: usize) -> bool {
self.chars[at + 1..].iter().take_while(|c| digit(**c).is_some()).count() == 3
}
fn number(&mut self) -> Result<f64, NotAValue> {
let mut text = String::new();
let mut seen_decimal = false;
@@ -257,7 +260,16 @@ impl Parse<'_> {
} else if c == self.reader.decimal && !seen_decimal {
seen_decimal = true;
text.push('.');
} else if Some(c) == self.reader.group && !seen_decimal && !text.is_empty() && self.three_digits_after(self.at) {
} else if Some(c) == self.reader.group && !seen_decimal && !text.is_empty() {
let after = &self.chars[self.at + 1..];
let digits = after.iter().take_while(|c| digit(**c).is_some()).count();
let only_mark = after.get(digits).is_none_or(|&next| next != c && next != self.reader.decimal);
if text == "0" && matches!(c, '.' | ',') && digits > 0 && only_mark {
seen_decimal = true;
text.push('.');
} else if digits != 3 {
break;
}
} else {
break;
}
@@ -274,6 +286,28 @@ impl Parse<'_> {
mod tests {
use super::*;
#[test]
fn a_single_group_mark_after_zero_reads_as_a_decimal() {
for (decimal, group) in [('.', ','), (',', '.')] {
let reader = Reader::new().decimal(decimal).group(group).unit("cm", 2.0);
for (text, want) in [
(format!("0{group}125+2"), 2.125),
(format!("2x0{group}125"), 0.25),
(format!("-0{group}25 cm"), -0.5),
(format!("٠{group}١٢٥"), 0.125),
(format!("1{group}125"), 1125.0),
(format!("1{group}234{decimal}5"), 1234.5),
(format!("0{group}123{group}456"), 123456.0),
(format!("0{group}125{decimal}5"), 125.5),
] {
assert_eq!(reader.read(&text, None), Ok(want), "{text}");
}
assert_eq!(reader.read(&format!("0{group}"), None), Err(NotAValue));
}
let swiss = Reader::new().group('\'');
assert_eq!(swiss.read("0'125", None), Ok(125.0));
}
#[test]
fn expressions_units_and_relative_input_read_through_one_grammar() {
let reader = Reader::new().decimal(',').group('.').unit("in", 72.0).unit("pt", 1.0);
@@ -326,6 +360,20 @@ mod tests {
near(&percent, "2%", 14.0);
assert_eq!(percent.read("*50%", Some(4.0)), Ok(2.0), "a relative share");
let per_inch = Reader::new().unit_tagged("/in", 1.0, 0);
assert!(is_unit_spelling("/in") && !is_unit_spelling("/") && !is_unit_spelling("in/") && !is_unit_spelling("//in"));
for text in ["40/in", "40 /in", "40/IN", "80/2", "80/2/in"] {
near(&per_inch, text, 40.0);
}
assert_eq!(per_inch.read_tagged("40/in", None), Ok((40.0, Some(0))), "the spelling names its unit");
assert_eq!(per_inch.read("*2", Some(20.0)), Ok(40.0), "a relative product");
assert_eq!(per_inch.read("/2", Some(80.0)), Ok(40.0), "a leading / still divides the start value");
for bad in ["", "/in", "40/inch", "40/"] {
assert_eq!(per_inch.read(bad, Some(1.0)), Err(NotAValue), "{bad:?} is not a value");
}
near(&lengths, "144/2in", 1.0);
assert_eq!(lengths.read("144/in", None), Err(NotAValue), "without a /in spelling, /in is a division with no number");
let german = Reader::new().decimal(',').group('.');
near(&german, "1.234,5", 1234.5);
near(&german, "1.234.567", 1_234_567.0);
+36 -2
View File
@@ -66,6 +66,15 @@ pub struct Wheel {
pub lines: Vec2,
/// Zoom factor; 1 for none.
pub zoom: f32,
/// The wheel motion that reached the share as `zoom` instead of `scroll`, in wheel lines: wheel events under the
/// zoom modifier, and the Ctrl+wheel steps the service reads as a touchpad's pinch on Windows and Linux. A line
/// event counts its lines (notches) as the device sent them, a point or page event its points over egui's line
/// scroll speed. It travels with the zoom share, so a taker can count the notches or lines of a Ctrl+wheel that
/// zooms without the zoom speed; zero for a native pinch and for a wheel without the modifier.
pub zoom_lines: Vec2,
/// The running gesture's `zoom_lines` gathered so far, this share included, for the taker that owns the gesture;
/// another taker's share gathers only itself, as with `gathered`.
pub zoom_gathered: Vec2,
/// The modifiers held.
pub mods: Mods,
/// The unit the device reported.
@@ -224,6 +233,8 @@ impl Wheel {
scroll,
lines: Vec2::ZERO,
zoom: 1.0,
zoom_lines: Vec2::ZERO,
zoom_gathered: Vec2::ZERO,
mods,
unit,
phase,
@@ -245,6 +256,13 @@ impl Wheel {
self
}
/// The same gesture with `lines` wheel lines of motion that zoom (`Wheel::zoom_lines`).
#[must_use]
pub const fn zoom_lines(mut self, lines: Vec2) -> Self {
self.zoom_lines = lines;
self
}
/// The same gesture with the two-finger touch zoom factor `zoom`.
pub const fn touch_zoom(mut self, zoom: f32) -> Self {
self.touch_zoom = zoom;
@@ -563,13 +581,28 @@ fn for_field(wheel: &Wheel) -> bool {
/// Whether `wheel` carries a pinch, a touch zoom, a rotation or a two-finger pan: the zoom share's values.
fn pinches(wheel: &Wheel) -> bool {
wheel.zoom != 1.0 || wheel.touch_zoom != 1.0 || wheel.rotation != 0.0 || wheel.touch_rotation != 0.0 || wheel.touch_pan != Vec2::ZERO
wheel.zoom != 1.0
|| wheel.zoom_lines != Vec2::ZERO
|| wheel.touch_zoom != 1.0
|| wheel.rotation != 0.0
|| wheel.touch_rotation != 0.0
|| wheel.touch_pan != Vec2::ZERO
}
/// `wheel` without the zoom share's values: a scroll share carries no pinch or rotation, so a field or a scroll region
/// never reads one.
const fn scroll_only(wheel: Wheel) -> Wheel {
Wheel { zoom: 1.0, touch_zoom: 1.0, rotation: 0.0, touch_rotation: 0.0, touch_pan: Vec2::ZERO, zooms: false, ..wheel }
Wheel {
zoom: 1.0,
zoom_lines: Vec2::ZERO,
zoom_gathered: Vec2::ZERO,
touch_zoom: 1.0,
rotation: 0.0,
touch_rotation: 0.0,
touch_pan: Vec2::ZERO,
zooms: false,
..wheel
}
}
/// The split rule. A focused field (a `WheelTaker::field` taker that holds `focus`, or an app's own text field) takes
@@ -715,6 +748,7 @@ fn split_at<O: Copy + PartialEq>(
Some((_, share)) => {
share.scroll += part.scroll;
share.zoom *= part.zoom;
share.zoom_lines += part.zoom_lines;
share.touch_zoom *= part.touch_zoom;
share.rotation += part.rotation;
share.touch_rotation += part.touch_rotation;
+68
View File
@@ -247,6 +247,35 @@ fn a_floated_panel_keeps_where_it_was_docked_until_it_docks() {
assert!(!floats(workspace.layout(), 3) && workspace.floated().is_empty(), "docking back drops the record");
}
/// A closed panel that floats by itself records the place it would reopen at, as opening it first records, and its old
/// group keeps its front tab; docking it then returns it to that group at its old index.
#[test]
fn a_closed_panel_that_floats_keeps_its_docked_place_and_its_old_group_keeps_its_front_tab() {
let float = Action::float(2, rect(10.0, 10.0, 200.0, 200.0));
let mut opened = Workspace::new(docked());
opened.apply(Action::close(2), false, allow).unwrap();
opened.apply_all([Action::open(2, None), float.clone()], false, allow).unwrap();
let mut workspace = Workspace::new(docked());
workspace.apply(Action::close(2), false, allow).unwrap();
workspace.apply(float, false, allow).unwrap();
let layout = workspace.layout();
assert!(matches!(layout.place(&2), Some(PanelPlace::Floating { .. })));
assert_eq!(group_members(layout, 3), [3]);
assert_eq!(front(layout, 3), 3, "the old group keeps its front tab");
assert_eq!(workspace.floated(), opened.floated(), "the record matches the one opening it first gives");
let [(_, location)] = workspace.floated() else { panic!("one record: {:?}", workspace.floated()) };
let back = Action::move_beside(2, location.anchor.unwrap(), location.placement.clone());
workspace.apply(back, false, allow).unwrap();
assert_eq!(end_dock(workspace.layout())[0].groups[0].panels, [2, 3], "Dock Panel returns it to its old index");
let mut workspace = Workspace::new(docked());
workspace.apply(Action::close(6), false, allow).unwrap();
workspace.apply(Action::float(6, rect(10.0, 10.0, 200.0, 200.0)), false, allow).unwrap();
assert!(workspace.floated().is_empty(), "a panel closed from a floating window has no docked place");
}
/// Canvas 1; an end dock with an expanded column [2] and a collapsed column [3], [4]; a floating window [6].
fn columns() -> Layout<u32> {
let dock = Node::dock(DockEdge::End, vec![Column::new(vec![g(&[2], 0)]), Column::new(vec![g(&[3], 0), g(&[4], 0)]).with_iconic(true)]);
@@ -290,6 +319,45 @@ fn a_floating_windows_edge_is_saved_set_by_collapsed_moves_and_floats_and_cleare
assert_eq!(floated.edge, None, "an expanded column keeps to the edge nearer its rect");
}
/// A group docked into a collapsed column keeps the width it was shown at as its flyout width: a floating window's
/// width, or an expanded column's. A width equal to the column's leaves the flyout following the column, and a group
/// moved between collapsed columns keeps its own flyout width.
#[test]
fn a_group_docked_into_a_collapsed_column_keeps_its_width_as_the_flyout_width() {
let flyout = |layout: &Layout<u32>, panel: u32| layout.group(&layout.place(&panel).unwrap()).unwrap().flyout_width;
let mut layout = columns();
layout.apply(Action::move_floating(6, rect(100.0, 100.0, 420.0, 400.0))).unwrap();
layout.apply(Action::move_group(6, Target::at(3, DockPlacement::group(true, None)))).unwrap();
assert!(!floats(&layout, 6) && column_of(&layout, 6).iconic);
assert_eq!(flyout(&layout, 6), Some(420.0), "the floating window's width");
layout.apply(Action::resize_flyout_width(6, Some(380.0))).unwrap();
layout.apply(Action::move_group(6, Target::float(rect(100.0, 100.0, 380.0, 400.0)))).unwrap();
layout.apply(Action::set_iconic(6, false)).unwrap();
layout.apply(Action::move_floating(6, rect(100.0, 100.0, 300.0, 400.0))).unwrap();
layout.apply(Action::move_group(6, Target::at(4, DockPlacement::group(false, None)))).unwrap();
assert_eq!(flyout(&layout, 6), Some(300.0), "the width the window was resized to, not the flyout width it left with");
let mut layout = columns();
layout.apply(Action::resize_column(2, 260.0)).unwrap();
layout.apply(Action::move_group(2, Target::at(3, DockPlacement::group(true, None)))).unwrap();
assert_eq!(flyout(&layout, 2), Some(260.0), "the expanded column's width");
let mut layout = columns();
layout.apply(Action::resize_column(3, 300.0)).unwrap();
layout.apply(Action::move_group(6, Target::at(3, DockPlacement::group(true, None)))).unwrap();
assert_eq!(flyout(&layout, 6), None, "a width equal to the column's follows the column");
let mut layout = columns();
let start = Node::dock(DockEdge::Start, vec![Column::new(vec![g(&[7], 0)]).with_iconic(true)]);
let Some(root) = layout.root.take() else { panic!("no root") };
layout.root = Some(Node::split(Axis::X, SplitSize::FixedFirst(48.0), start, root));
layout.apply(Action::resize_flyout_width(3, Some(350.0))).unwrap();
layout.apply(Action::move_group(3, Target::at(7, DockPlacement::group(true, None)))).unwrap();
assert_eq!(flyout(&layout, 3), Some(350.0), "a group from another collapsed column keeps its own");
}
/// Collapse to icons is a state of every column: a floating window collapses and stays floating; groups leaving a
/// column float in its state; groups joining a column, docked or floating, take that column's state.
#[test]
+31
View File
@@ -64,6 +64,37 @@ fn short_items_shorten_from_the_end_before_any_item_leaves() {
assert_eq!(squeezed.short.len(), 2, "pinned items shorten as free ones do: {squeezed:?}");
}
/// Guards the host's order of short forms: a lower `short_order` shortens first wherever its item sits, and a
/// `short_late` item keeps its full form until every free item has gone to the menu, then shortens in rank order.
#[test]
fn short_forms_follow_their_rank_and_late_ones_wait_for_the_free_items() {
let item = |extent| FitItem::new(extent, 0, FitKeep::Free);
let ranked = [item(50.0).short(20.0), item(50.0), item(50.0).short(20.0).short_order(1)];
let fit = fit_items(&ranked, 120.0, 0.0, 0.0, 10.0);
assert_eq!(fit.short, [0], "the lower rank shortens before the later item: {fit:?}");
assert!(fit.overflow.is_empty(), "{fit:?}");
// Two free items in one section, then two pinned ones that shorten only late, the first ranked before the second.
let pinned = |extent| FitItem::new(extent, 1, FitKeep::Pinned).short(20.0).short_late();
let bar = [item(40.0), item(40.0), pinned(60.0), pinned(60.0).short_order(1)];
let at = |available| fit_items(&bar, available, 0.0, 0.0, 10.0);
let roomy = at(180.0);
assert_eq!(roomy.overflow, [1], "a free item leaves before any late item shortens: {roomy:?}");
assert!(roomy.short.is_empty(), "{roomy:?}");
let tight = at(130.0);
assert_eq!(tight.overflow, [0, 1], "every free item leaves first: {tight:?}");
assert!(tight.short.is_empty(), "{tight:?}");
let narrow = at(100.0);
assert_eq!(narrow.short, [2], "then the lower-ranked late item shortens: {narrow:?}");
assert_eq!(narrow.overflow, [0, 1], "items that left stay in the menu: {narrow:?}");
let narrowest = at(50.0);
assert_eq!(narrowest.short, [2, 3], "then the next rank: {narrowest:?}");
}
#[test]
fn kept_selection_keeps_its_width_and_overflow_starts_at_the_end() {
let natural = [80.0, 90.0, 85.0, 95.0, 70.0];
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "craft-cdr"
description = "Bounded reader for .cdr drawings of versions 1 to 27 and .cmx files: WL records, RIFF index, compressed lists, ZIP packages, shapes, fills, outlines, pages and layers, and the picture a file keeps of its drawing; writer for version 15 .cdr drawings"
description = "Bounded reader for .cdr drawings of versions 1 to 27 and .cmx files: WL records, RIFF index, compressed lists, ZIP packages, shapes, fills, outlines, pages and layers, and the picture a file keeps of its drawing; writer for version 15 .cdr drawings, and a .cmx writer in the layouts it reads"
version.workspace = true
edition.workspace = true
license.workspace = true
+45 -4
View File
@@ -1,8 +1,10 @@
# Where each layout comes from
The reader relies on the record layouts below, and the writer (`src/write.rs`) lays out version 15
files by the same rows, with R64 to R73 for what only the writer needs. Code cites a row by its id
(`R1` ...), and `tests/it/provenance.rs` fails when a cited id has no row here.
files by the same rows, with R64 to R73 for what only the writer needs. The `.cmx` writer
(`src/cmx_write.rs`) writes in them, with R74 for what only it needs ("Written fields" lists each
field it sets). Code cites a row by its id (`R1` ...), and `tests/it/provenance.rs` fails when a
cited id has no row here.
Sources:
@@ -57,7 +59,10 @@ Sources:
Status: `public-spec` (K, KF, KR, Z, F, PR or G), `sample` (S), `public-notes` (a layout CN marks
confirmed that no CX file shows), `unconfirmed` (a point no source states and no sample file shows;
listed so it can be checked against a file, with what the reader does when it is wrong).
listed so it can be checked against a file, with what the reader does when it is wrong). The
"Written fields" table also uses `own` (a value the reader does not read, set as the synthetic test
files of `src/synth_cmx.rs` set it) and `the writer's choice` (a value the reader does not read and
the synthetic test files do not set, chosen by the writer).
Public specifications cover only parts of versions 1 to 4: the rows that cite K, F or PR, such as
the version 3 fill (R34) and page settings (R38). The other rows of those versions rest on the
@@ -126,7 +131,7 @@ file is committed.
| R55 | A table (`rclr`, `rpen`, `rott`, `rdot`, `rotl`) is a u16 entry count, then one field list per entry; an instruction's body is field lists too. A field is a u8 tag, a u16 length counting its 3 header bytes, and the data; 0xff ends the list. Objects name table entries from 1 | CN "Tables"; S: every one of these tables in the nine CX files with 32-bit coordinates reads its count of entries with no bytes left | sample |
| R56 | A color entry: a property list in field 10 (a u32 length, then parts laid out as R11's, the color in part 1 as R14), or in older files the model and palette bytes in field 1 and the values in field 2. Models of the older fields: 2 cyan, magenta, yellow and black in percent; 3 the same in 0 to 255; 4 cyan, magenta and yellow in 0 to 255; 5 red, green and blue in 0 to 255; 9 gray in 0 to 255, 255 white. Other models read as black with a warning | CN "Tables" (`rclr`); S: every color of the nine CX files is model 2 in the older fields | sample (model 2), public-notes (field 10), unconfirmed (models 3 and 5 of the older fields, read as the program of CN reads them, and models 4 and 9, read as R14's; a wrong reading gives a wrong color) |
| R57 | `rpen` field 1: the width as a u32 in coordinate units (then an aspect, an angle and a matrix, not read). `rott` field 1: a flags byte (1 no outline, 2 solid, 4 dashed, 8 behind the fill, 16 scaled with the object), then the caps in the low 4 bits and the join in the high 4 bits, numbered as R12. `rdot` field 1: a u16 count, then the dash and gap lengths in outline widths (u16 each). A pattern whose lengths are all 0 draws a solid line, as R48's | CN "Tables"; S: line types 0x02 and 0x22 with caps and joins 0x00, 0x01 and 0x11 in the CX files | public-notes (the flags 4, 8 and 16 and the cap and join numbering; bit 0x20, set in `balloon.cmx`, is not read) |
| R58 | `rotl` field 1: six u16, the 1-based entries of the outline's line type, screen, color, arrowhead pair, pen and dash pattern | CN "Tables"; S: every `rotl` entry of the CX files names entries that exist | sample |
| R58 | `rotl` field 1: six u16, the 1-based entries of the outline's line type, screen, color, arrowhead pair, pen and dash pattern | CN "Tables"; S: every `rotl` entry of the CX files names entries that exist; in `balloon.cmx`, `PC.CMX` and `squares.cmx`, solid outlines name `rdot` entry 1, whose field 1 is a count of 0 | sample |
| R59 | `rota`: a u16 count, then pairs of u16 (start and end arrowheads, 0 for none), not field lists | CN "Tables"; S: `rota` is `01 00 00 00 00 00` in every CX file | sample (pairs of 0), public-notes (other values) |
| R60 | A `page` chunk is a stream of instructions: a u16 size counting the whole instruction and an i16 code, or 0xFFFF, a u32 size and the code (the long form); then field lists. Codes: 9 and 10 begin and end a page, 11 and 12 a layer, 13 and 14 a group, 67 a curve; 20 and 21 a text object, 65 its drawn characters, 66 an ellipse, 68 a rectangle, 69 an image, 88 and 89 add and remove a clipping path, 111 a jump whose field 1 is the u32 file offset to go on from (the bytes jumped over hold images). Objects are drawn in file order, the first at the back | CN "page: instructions"; S: codes 9 to 14 and 67 in the CX files; in `squares.cmx` the large square comes first and the two smaller ones inside it after | sample (9 to 14, 67, the order), public-notes (the long form and the other codes) |
| R61 | Field 4 of instruction 9: the page's width and height, u32 each in coordinate units. Without it, field 1 gives the drawing's bounds: a u16 page number, a u32, then the left, top, right and bottom edges as i32 in coordinate units; the page takes the bounds' size and is centered on them (VectorCraft's own choice). Without either, the page has no size, and the importer gives it 612 × 792 pt as it does a `.cdr` page without one (VectorCraft's own size) | CN "page: instructions"; S: none of the CX files has field 4; in all nine with 32-bit coordinates, the four edges in field 1 match the extent of the file's curves | public-notes (field 4), sample (field 1) |
@@ -142,3 +147,39 @@ file is committed.
| R71 | An `outl` chunk from version 13 holds records up to the one of id 1, whose length the specification's samples give as the bytes left in the chunk less 8. In the version 15 samples the id 1 record holds 130 bytes, 8 bytes follow it, and its body holds an f64 1 at bytes 16 and 48, 45 degrees at byte 84 and 60 at byte 88; the writer writes that layout and those values. A record of id 2 holds a color property list that ends at its empty property, without the fields R66 names after a fill's list | KF L1158-L1244 (the records, type 2 a color property list, and the id 1 length in its samples); S: the 18 `outl` chunks of the LT `testset/15` files without text (each 237 bytes, the id 1 record 130 bytes long with those values and 8 bytes of 0 after it, the id 2 record 43 bytes long) | public-spec (the record types and the length), sample (the values; the reader does not use them) |
| R72 | In the version 15 samples an `mcfg` chunk starts with the tag 1300 and the length of the rest of the chunk, then 4 bytes of 0 (the 12 bytes R10 names), and each `fild` chunk sits in a `LIST filc` of its own inside `LIST filt` | S: the 15 LT `testset/15` files without text (every `mcfg` starts with 1300 and its size less 8; each of their 31 `fild` chunks is the only chunk of a `LIST filc`) | sample (the reader skips the 12 bytes and finds `fild` chunks at any depth) |
| R73 | The specification reads the id in a container's argument 8005 (R46) as the stored u32 plus 1, halved, and the `spnd` id as stored. Sample files hold the same stored u32 in both places, even ids included, which the halved reading would not match. The writer numbers containers 1, 2, 3 and so on, and writes the same number in the clipped group's `spnd` | KF L799-L807 (`powerclip_id`), L2305-L2312 (`spnd`); S: the container and `spnd` of LT `powerclipsquare_blackfill_whiterectangleinside.cdr` of `testset/12` (156091928) and `powerclipsquare_blackfill_whiterectangleinside_cdr15.cdr` (1), the eight UC files `corel_powerclip_*` of versions 7 to 13 (47834832) and TDF 114901 (515235504) | sample (the halved reading: not followed) |
| R74 | `rscr`: a u16 count, then one field list per screen entry, which a `rotl` entry names (R58). The reader does not read it; the `.cmx` writer writes one entry whose field 1 holds the 13 bytes `00 00 3c 00 00 00 00 00 40 a5 ae 02 00` | S: each of the nine CX files with 32-bit coordinates has an `rscr` of one entry with a 13-byte field 1, these bytes in seven of them (`bars.cmx` and `thatch.cmx` differ in bytes 2 and 8 to 11) | sample |
## Written fields
`src/cmx_write.rs` writes `.cmx` files in the layouts of the rows above, nothing else. The table
lists every field it sets. `own` marks a value the reader does not read, which the writer sets as
the synthetic test files of `src/synth_cmx.rs` set it. The header's offsets at bytes 84 to 95, the
index chunks (`LIST indx`), the instruction counts and file offsets that the CX files also keep in
their page, layer and group records, and the bounds they keep in layer and group records are not
written: no public source describes
them, and the reader finds every chunk by its id and walks the instructions in order.
| Field written | Rows | Status |
|---|---|---|
| The RIFF form `CMX1`, chunk ids and sizes, a pad byte after an odd body | R53 | sample |
| Chunk order: `cont`, the `page` chunks, then `rclr`, `rpen`, `rott`, `rdot`, `rotl`, `rota` and `rscr` | R53 | own (the reader finds each chunk by its id) |
| `cont`: `4` at byte 52, the unit 1e-7 m as an f64 at bytes 64 to 72 | R54 | sample |
| `cont`: `2` at bytes 48 and 54, zeros elsewhere, 180 bytes | R54 | own |
| Table counts and field lists | R55 | sample |
| `rclr` field 10: a property list with part 1, the color record (model, palette 5, 4 zero bytes, 4 values), and for a spot color part 3, its name; models 2 (CMYK in percent), 5 (blue, green, red), 9 (gray), 20 (registration) and 21 (blue, green, red at the tint, and the tint in percent) | R11, R14, R56 | public-notes (field 10), public-spec (the models) |
| `rpen` field 1: the width | R57 | public-notes |
| `rpen` field 1 after the width: an aspect of 100, an angle of 0, a matrix type of 1 | R57 | own |
| `rott` field 1: the flags 2, 4, 8 and 16, the caps and the join | R57 | public-notes |
| `rdot` field 1: a count and the lengths in whole outline widths | R57 | public-notes |
| `rdot` field 1 of a solid outline's pattern: a count of 0 | R57, R58 | sample |
| `rotl` field 1: six entries, the screen and the arrowhead pair always 1, a solid outline's dash pattern the entry with a count of 0 | R58 | sample |
| `rota`: one pair of 0 | R59 | sample |
| `rscr`: one screen entry, its field 1 as the sample files write it | R74 | sample |
| Instructions in the short form, and the long form past 65,534 bytes | R60 | sample (short form), public-notes (long form) |
| Begin page, field 1: the page number (from 1), a u32 of 0, the left, top, right and bottom edges of the page's curves (of the page around its center when it has none; all 0 for a page without a size) | R61 | sample (page number 1, the edges), own (the later numbers, the edges of a page with no curves or no size) |
| Begin page, field 4: the page's width and height | R61 | public-notes |
| Begin layer, field 1: the page number and the layer number (u16 each, from 1), then 8 zero bytes, then the name as a u16 byte count and 8-bit characters | R62 | sample (the numbers: `balloon.cmx` and `PC.CMX` number their four layers `01 00 01 00` to `01 00 04 00`; the name), own (the 8 bytes) |
| Begin layer, field 4: the name as a u32 count of UTF-16 code units and the units | R62 | public-notes |
| Begin group with field 1 of 26 zero bytes; end layer, group and page with no fields | R60 | own (the bodies are not read) |
| Curve, field 1: rendering attributes with a uniform fill (type 1, the color entry, screen entry 1) and an outline entry | R63, R74 | sample (the uniform fills of `bars.cmx`, `balloon.cmx` and `PC.CMX` name screen 1) |
| Curve, field 2: the point count, the points as i32 and a type byte each, bit 2 set on every move, line and curve end node and clear on control points, bit 3 on the first and last nodes of a closed subpath that fits in one curve; a closed subpath cut into open pieces gets a line back to its start added when its last point is elsewhere; at most 7,281 points | R16, R62 | sample (the layout), own (bit 2 on the nodes the synthetic files set it on), the writer's choice (bit 2 on a closing node, which the synthetic files leave clear) |
+32 -2
View File
@@ -97,6 +97,36 @@ arrowheads and lenses are not read; the drawing's `warnings` name each kind it h
path is left out and the objects it clips are read without it. Files in big-endian byte order and
files with 16-bit coordinates are refused.
`write_cmx` writes a drawing as a `.cmx` file with 32-bit coordinates in the layouts `read_cmx`
reads, so that `read_cmx` leaves nothing out because of the `Limits` given: pages with their
sizes, layers with their names, groups, and curves with uniform fills and outlines. What the file
holds differently from the drawing is reported, as below. Rectangles and ellipses are
written as curves, and a clipping container as a group of its fill, the objects it clips
(unclipped) and its outline. A rounded rectangle scaled differently along its two sides gets round
corners, not stretched ones. Hidden layers, groups and shapes, guide and grid layers, guidelines
and master layers are left out; opacity, blend modes, fill rules and locked states are not
written, desktop layers are written as drawing layers, and a spot color with no name opens as a
process color; every use of a named spot color takes the look of its use at the strongest tint
among the uses whose look is known.
`write_cmx` returns an error, and writes nothing, for a coordinate, page side or outline width
past the 32-bit range, a negative or NaN outline width, a page side that rounds to 0, more than
65,535 pages, layers on a page or different colors, pens, line types, dash patterns or outlines, a
dash pattern of more than 32,765 lengths, groups nested deeper than the limits allow, more chunks,
objects, coordinates or dashes than a read within the limits takes, a file longer than their input
size, and a chunk past its 32-bit size. Otherwise the returned `Written` reports paths split or cut into several curves, dashes
rounded to whole outline widths, nonzero fills that may fill differently, names that open
shortened, spot colors at a tint too low to keep their look, with no name or with no known look
(written black), uses of one ink with different looks, and what was left out or written opaque,
unclipped or unlocked.
The header's index offsets, the index chunks (`LIST indx`), the instruction counts and offsets
inside page, layer and group records, and the bounds inside layer and group records are not
written, so a reader must find the chunks by their ids and walk the instructions in order, as
`read_cmx` does. The record of a page with a size holds the edges of its curves, or of the page
when it has none. `PROVENANCE.md`'s "Written
fields" table lists every field the `.cmx` writer sets.
## Writing
`write` writes a drawing as a `.cdr` file of version 15: a ZIP package whose first member,
@@ -157,8 +187,8 @@ degree of its angle.
## Provenance
`PROVENANCE.md` lists every record layout the reader relies on, and the rows only the writer
needs, with their public sources and status.
`PROVENANCE.md` lists every record layout the reader relies on, and the rows only the writers
need, with their public sources and status.
Code cites the rows by id (`R1` ...), and `tests/it/provenance.rs` fails when a cited id has no row.
The test inputs are synthetic drawings built by `src/synth.rs` and `src/synth_cmx.rs` (the
`synth` feature); no third-party file is committed.
File diff suppressed because it is too large. Load diff
+34 -2
View File
@@ -11,7 +11,7 @@
//! panic.
//!
//! [`write()`] writes a [`Drawing`] as a `.cdr` file of version 15, laying out each record as the
//! reader reads it. Nothing here writes `.cmx` files.
//! reader reads it. [`write_cmx`] writes `.cmx` files in the layouts the reader reads.
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
@@ -20,6 +20,7 @@ use std::fmt;
mod build;
mod bytes;
mod cmx;
mod cmx_write;
mod geometry;
mod inline;
mod layout;
@@ -38,6 +39,7 @@ mod wl;
mod write;
mod zip;
pub use cmx_write::{MAX_CURVE_POINTS, Written};
pub use limits::Limits;
pub use model::{Drawing, Warning};
pub use preview::{Preview, PreviewFormat, preview};
@@ -66,7 +68,8 @@ pub enum Error {
Version(u16),
/// A container structure that doesn't parse.
Damaged(&'static str),
/// Past one of the [`Limits`].
/// Past one of the [`Limits`]; from [`write_cmx`], also past what a `.cmx` file holds, or an
/// outline width that is negative or NaN.
Limit(&'static str),
/// A file this reader doesn't open: an encrypted, ZIP64 or split package, or a RIFF file that
/// names a version before 3; a big-endian `.cmx` file or one with 16-bit coordinates; a
@@ -118,3 +121,32 @@ pub fn read_cmx(bytes: &[u8], limits: Limits) -> Result<Drawing, Error> {
let mut budget = limits::Budget::new(limits);
cmx::drawing(bytes, &mut budget)
}
/// Write `drawing` as a `.cmx` exchange file with 32-bit coordinates, in the layouts
/// [`read_cmx`] reads: its pages, layers, groups and shapes (as curves) with uniform fills and
/// outlines. [`read_cmx`] reading the file within `limits` leaves nothing out because of them;
/// what the file holds differently from the drawing, such as a name the reader shortens, is
/// reported in [`Written`].
///
/// It fails with [`Error::Limit`], and writes nothing, for:
/// - a coordinate, page side or outline width past the 32-bit range, a negative or NaN outline
/// width, or a page side that rounds to 0;
/// - more than 65,535 pages, layers on a page, or different colors, pens, line types, dash
/// patterns or outlines, or a dash pattern of more than 32,765 lengths;
/// - groups nested deeper than the depth of `limits`, or more chunks, objects, coordinates or
/// dashes than a read within `limits` takes;
/// - a file longer than the input size of `limits`, or a chunk past what its 32-bit size holds.
///
/// [`Written`] reports what the file holds differently from the drawing; its fields name each
/// case. A rounded rectangle under a scale that keeps right angles but differs along its sides is
/// written with round corners of its radii times the square root of the scales' product, not with
/// stretched corners, and is not reported.
///
/// The header's index offsets, the index chunks (`LIST indx`), the instruction counts and offsets
/// inside page, layer and group records, and the bounds inside layer and group records are not
/// written, so a reader must find the chunks by their ids and walk the instructions in order, as
/// [`read_cmx`] does. The record of a page with a size holds the edges of its curves, or of the
/// page when it has none.
pub fn write_cmx(drawing: &Drawing, limits: Limits) -> Result<Written, Error> {
cmx_write::write(drawing, limits)
}
+3 -3
View File
@@ -15,7 +15,7 @@ const MAX_SKIPPED: usize = 4;
const MAX_OUTLINE_RECORDS: usize = 16;
/// The most UTF-16 units of a library color's name kept, and the most bytes or UTF-16 units of
/// a layer's.
const MAX_NAME: usize = 256;
pub(crate) const MAX_NAME: usize = 256;
/// A header field: u16 in short files, u32 otherwise.
fn word(r: &mut Rd, p: &Profile) -> Option<usize> {
@@ -260,7 +260,7 @@ fn b_tint(b: &[u8]) -> Option<f32> {
}
/// The full-strength color behind sRGB `rgb` shown at `tint` (a tint mixes toward white).
fn untinted(rgb: [f32; 3], tint: f32) -> [f32; 3] {
pub(crate) fn untinted(rgb: [f32; 3], tint: f32) -> [f32; 3] {
if tint <= 0.0 {
return rgb;
}
@@ -486,7 +486,7 @@ fn with_hash(name: String, hash: Option<u64>) -> String {
/// The characters Windows-1252 puts at 0x80 to 0x9F (U+FFFD where it has none); the other bytes
/// are Latin-1.
const CP1252_HIGH: [char; 32] = [
pub(crate) const CP1252_HIGH: [char; 32] = [
'€', '\u{FFFD}', '‚', 'ƒ', '„', '…', '†', '‡', 'ˆ', '‰', 'Š', '‹', 'Œ', '\u{FFFD}', 'Ž', '\u{FFFD}', '\u{FFFD}', '‘', '’', '“', '”', '•', '–',
'—', '˜', '™', 'š', '›', 'œ', '\u{FFFD}', 'ž', 'Ÿ',
];
File diff suppressed because it is too large. Load diff
+1
View File
@@ -4,6 +4,7 @@
mod bench;
mod cmx;
mod cmx_write;
mod provenance;
mod read;
mod write;
@@ -282,6 +282,58 @@ fn a_late_reply_from_before_sign_out_is_dropped() {
);
}
/// File › Open calls `start` on every frame. A sign-out has no answer, so nothing orders it
/// before a request the next frame sends. A provider that still holds the session answers that
/// request with the departed account, and the window must not show that account or its files.
#[test]
fn a_page_drawn_after_sign_out_does_not_bring_the_account_back() {
let (mut app, held, _log) = two_tabs();
start(&mut app);
let (_, post) = held.take(|j| matches!(j, Job::Account)).unwrap();
post.send(Event::Account(Ok(account("Previous Person"))));
held.take(|j| matches!(j, Job::List(_))).unwrap();
drain(&mut app, &egui::Context::default());
sign_out(&mut app);
start(&mut app);
// Whatever the frame asked is answered as a provider that has not yet ended the session would.
while let Some((job, post)) = held.take(|j| matches!(j, Job::Account | Job::List(_))) {
match job {
Job::Account => post.send(Event::Account(Ok(account("Previous Person")))),
Job::List(path) => post.send(Event::Listed { path, entries: Ok(vec![entry("/Payroll 2026.note", "p1")]) }),
_ => {}
}
}
drain(&mut app, &egui::Context::default());
let r = report(&app);
assert!(
r["account"].is_null() && r["entries"].as_array().is_some_and(Vec::is_empty),
"signed out, yet account={} entries={}",
r["account"],
r["entries"]
);
sign_in(&mut app);
let (_, post) = held.take(|j| matches!(j, Job::SignIn)).unwrap();
post.send(Event::Account(Ok(account("Ada"))));
drain(&mut app, &egui::Context::default());
start(&mut app);
assert!(held.take(|j| matches!(j, Job::List(_))).is_some(), "the next sign-in lists the root folder again");
}
/// Save As while signed out has no account to land in. A provider that has not ended the session
/// yet would create the file in the account that is leaving.
#[test]
fn save_as_after_sign_out_is_refused_until_the_next_sign_in() {
let (mut app, held, _log) = two_tabs();
start(&mut app);
let (_, post) = held.take(|j| matches!(j, Job::Account)).unwrap();
post.send(Event::Account(Ok(account("Previous Person"))));
drain(&mut app, &egui::Context::default());
sign_out(&mut app);
let refused = save_as(&mut app, "", "Plan");
assert!(refused.is_err(), "signed out, yet Save As went ahead: {refused:?}");
assert!(held.take(|j| matches!(j, Job::Create { .. })).is_none(), "nothing is created while signed out");
}
/// Save as a copy, then the first click on the Save As page is refused (no name typed yet). The
/// second click, with a name, must still copy the conflicted document A, not the active tab B.
#[test]
+22 -1
View File
@@ -191,6 +191,11 @@ pub struct CloudFiles {
pub account_fault: Option<Fault>,
/// The account is asked for once per run. A frame never asks again.
asked_account: bool,
/// Set by [`sign_out`] and cleared by [`sign_in`]. While it is set, the
/// pages ask the service nothing. [`Job::SignOut`] has no answer and no
/// order against a later job, so a provider that still holds the session
/// could answer an account or listing request with the departed account.
signed_out: bool,
/// The folder being browsed. Shared by the Open and Save As pages, which
/// are never on screen together.
pub mine: Folder,
@@ -249,6 +254,7 @@ impl CloudFiles {
account: None,
account_fault: None,
asked_account: false,
signed_out: false,
mine: Folder::default(),
shared: Folder::default(),
source: Source::default(),
@@ -344,8 +350,10 @@ pub fn submit<A: CloudApp>(app: &A, job: Job) {
}
/// Asks who is signed in, once per run, and lists the root folder.
///
/// After [`sign_out`] it asks nothing until the next [`sign_in`].
pub fn start<A: CloudApp>(app: &mut A) {
if !available(app) {
if !available(app) || app.cloud().signed_out {
return;
}
if !app.cloud().asked_account {
@@ -375,6 +383,7 @@ pub fn sign_in<A: CloudApp>(app: &mut A) {
// would then be swallowed by the guard that stops a frame asking twice. A
// button that does nothing the second time reads as a broken button.
cloud.asked_account = true;
cloud.signed_out = false;
cloud.link = None;
cloud.status = Some(working);
// A new session. A job the previous one left outstanding may never
@@ -402,6 +411,10 @@ pub fn sign_out<A: CloudApp>(app: &mut A) {
cloud.account = None;
cloud.account_fault = None;
cloud.asked_account = false;
// File › Open and Save As call `start` on every frame. Without this, the
// next frame would ask who is signed in and list the root folder while
// the sign-out may still be on its way.
cloud.signed_out = true;
cloud.link = None;
cloud.mine = Folder::default();
cloud.shared = Folder::default();
@@ -413,8 +426,13 @@ pub fn sign_out<A: CloudApp>(app: &mut A) {
// that never heard back does not refuse every one after it forever.
cloud.account_generation.fetch_add(1, Ordering::Relaxed);
cloud.busy = None;
cloud.sharing_save = false;
cloud.relist_after_sign_in = false;
cloud.save_as_target = None;
// Sharing went with the account: Share is not offered on the old
// account's answer, and a sheet open on one of its documents closes. The
// next sign-in asks the provider again.
app.sharing().signed_out();
submit(app, Job::SignOut);
}
@@ -630,6 +648,9 @@ pub fn save_as<A: CloudApp>(app: &mut A, folder: &str, name: &str) -> Result<Jso
if app.cloud().relist_after_sign_in {
return Err("wait for the sign-in to finish".to_owned());
}
if app.cloud().signed_out {
return Err(app.tr("Sign in to save to the cloud"));
}
// A document that does not exist yet has no content type to read. The
// name a person just typed is the whole of what was asked for.
let bytes = app.encode(uid, Destination::new(&name))?;
+5
View File
@@ -42,6 +42,11 @@ fn header<A: CloudApp>(app: &mut A, ui: &mut Ui) {
let line = if account.display.is_empty() { app.tr("Signed in") } else { account.display.clone() };
dim(ui, &style, &line);
}
// Nothing is asked after a sign-out, so there is nothing to wait for.
(None, None) if app.cloud().signed_out => {
let signed_out = app.tr("Signed out");
dim(ui, &style, &signed_out);
}
(None, None) => {
let waiting = app.tr("Connecting to your cloud account…");
dim(ui, &style, &waiting);
+43
View File
@@ -435,6 +435,49 @@ fn signing_out_forgets_everything_this_window_knew() {
assert!(jobs.lock().unwrap().iter().any(|j| matches!(j, Job::SignOut)), "the service is told, so the saved token goes too");
}
/// A sharing service that says it can share and answers nothing else.
struct Shares;
impl crate::share::ShareBackend for Shares {
fn submit(&self, request: crate::share::Request, reply: crate::share::Replier) {
if request == crate::share::Request::Capabilities {
reply.answer(crate::share::Answer::Capabilities { capabilities: vec![Capability::Sharing], linked: true });
}
}
}
#[test]
fn signing_out_takes_sharing_with_it() {
let (mut app, _jobs, ctx) = wired();
app.share.connect(Shares);
// Enough frames for an account answer to land, the provider to be asked,
// and its answer to be read.
let frames = |app: &mut Notebook| {
for _ in 0..3 {
ctx.begin_pass(Default::default());
app.share.show(&ctx);
pump(app, &ctx);
ctx.end_pass().textures_delta.clear();
}
};
frames(&mut app);
assert!(app.share.available());
app.share.open("/Minutes.note", "Minutes");
assert!(app.share.is_open());
sign_out(&mut app);
assert!(!app.share.is_open(), "a sheet open on the old account's document closes");
assert!(!app.share.available(), "Share is not offered on the old account's answer");
// The provider is not asked again while the sign-out may still be on its
// way, so a service that still has the old account cannot offer it back.
frames(&mut app);
assert!(!app.share.available(), "nobody is signed in");
sign_in(&mut app);
frames(&mut app);
assert!(app.share.available(), "the next sign-in asks again");
}
#[test]
fn an_answer_queued_before_the_session_changed_is_dropped() {
let (mut app, _jobs, ctx) = wired();
+34 -8
View File
@@ -338,6 +338,10 @@ pub struct ShareDialog {
provider: Option<Provider>,
/// When the capability question was last asked.
asked: Option<f64>,
/// The last request number issued before the latest [`ShareDialog::refresh`]
/// or [`ShareDialog::connect`]. A capabilities answer to that request or an
/// earlier one describes the account as it was, and is ignored.
capabilities_after: u64,
open: Option<Sheet>,
/// Keyed by the URL the contact carried, so reopening the dialog does not
/// fetch the same faces again.
@@ -370,6 +374,7 @@ impl ShareDialog {
seq: 0,
provider: None,
asked: None,
capabilities_after: 0,
open: None,
avatars: HashMap::new(),
wants_save: None,
@@ -387,6 +392,7 @@ impl ShareDialog {
self.backend = Some(Box::new(backend));
self.provider = None;
self.asked = None;
self.capabilities_after = self.seq;
}
pub fn connected(&self) -> bool {
@@ -413,10 +419,25 @@ impl ShareDialog {
/// The answer is kept once it arrives, so a host that signs somebody
/// in after the first answer has to say so. Without this the dialog
/// keeps the answer it got while nobody was signed in, and Share
/// stays unavailable for the rest of the run.
/// stays unavailable for the rest of the run. An answer to a question
/// asked before the refresh is ignored when it arrives.
pub fn refresh(&mut self) {
self.provider = None;
self.asked = None;
self.capabilities_after = self.seq;
}
/// Forget sharing for an account that signed out.
///
/// Closes the sheet and offers nothing until [`ShareDialog::refresh`],
/// which the next sign-in calls. The provider is not asked again here: a
/// question asked before the sign-out reaches the service would describe
/// the account that is leaving. Answers to earlier questions are ignored.
pub fn signed_out(&mut self) {
self.close();
self.provider = Some(Provider { sharing: false, contacts: false, mail: false, links: false, key: false, key_required: false });
self.asked = None;
self.capabilities_after = self.seq;
}
pub fn available(&self) -> bool {
@@ -639,6 +660,8 @@ impl ShareDialog {
// once the open sheet is no longer borrowed.
let mut reload = None;
match answer {
// Asked before the account changed: it describes the old one.
Answer::Capabilities { .. } if seq <= self.capabilities_after => {}
Answer::Capabilities { capabilities, linked } => {
self.provider = Some(Provider {
sharing: linked && capabilities.contains(&Capability::Sharing),
@@ -717,13 +740,16 @@ impl ShareDialog {
}
}
Answer::Linked => {
// An account arrived, so the list is stale.
if let Some(sheet) = &mut self.open {
sheet.destinations = None;
}
let seq = self.issue(Request::Destinations);
if let Some(sheet) = &mut self.open {
sheet.destinations_seq = Some(seq);
// An account arrived, so the list is stale. With no sheet open
// there is no list to reload.
if self.open.is_some() {
if let Some(sheet) = &mut self.open {
sheet.destinations = None;
}
let seq = self.issue(Request::Destinations);
if let Some(sheet) = &mut self.open {
sheet.destinations_seq = Some(seq);
}
}
}
Answer::Withdrawn { share_id } => {
+27
View File
@@ -113,6 +113,24 @@ fn nothing_is_offered_until_the_service_says_sharing_exists() {
assert!(dialog.is_open());
}
#[test]
fn a_capabilities_answer_asked_before_a_refresh_is_ignored() {
let ctx = Context::default();
let backend = Silent::default();
let mut dialog = ShareDialog::new();
dialog.connect(backend.clone());
dialog.collect(&ctx);
dialog.refresh();
dialog.collect(&ctx);
assert_eq!(backend.seen(), vec![Request::Capabilities, Request::Capabilities], "the refresh asks again");
// The first question was about the account before the refresh.
dialog.receive(&ctx, 1, Ok(everything()));
assert!(!dialog.available(), "the old account's answer must not offer Share");
dialog.receive(&ctx, 2, Ok(everything()));
assert!(dialog.available());
}
#[test]
fn an_unlinked_account_cannot_share_even_where_the_provider_can() {
let ctx = Context::default();
@@ -580,6 +598,15 @@ fn a_closed_dialog_still_collects_and_reports_nothing() {
assert!(shared.is_empty() && failed.is_empty());
}
#[test]
fn a_link_answer_arriving_with_no_sheet_open_asks_for_nothing() {
let (ctx, mut dialog, backend) = ready();
dialog.signed_out();
let before = backend.seen().len();
dialog.receive(&ctx, 99, Ok(Answer::Linked));
assert_eq!(backend.seen().len(), before);
}
#[test]
fn pressing_return_takes_the_first_match_or_an_address() {
let (_ctx, mut dialog, _) = ready();
+2 -2
View File
@@ -59,7 +59,7 @@ pub enum ChosenColor {
pub struct ColorChoiceOutput {
/// The choice's response.
pub response: Response,
/// The row chosen this pass; the host stores it.
/// The row committed this pass; the host stores it. Navigating an open popup reports no choice.
pub chosen: Option<ChosenColor>,
/// "Select Custom Color…" was chosen, for this pass only: the app opens its colour picker from the request (key
/// [`ColorChoice::CUSTOM_KEY`], the custom colour) and, on OK, stores the colour and chooses
@@ -151,7 +151,7 @@ impl<'a> ColorChoice<'a> {
entries.push(Entry::separator());
entries.push(Entry::new(Row::SelectCustom, words.select_custom.as_str().to_owned()));
let shown = Select::new(self.label.clone(), Bind::given(row), &entries).enabled(self.enabled).show(ui);
let picked = shown.value().cloned();
let picked = shown.events.committed().cloned();
let mut pick_color = None;
let chosen = match picked {
Some(Row::Named(id)) => Some(ChosenColor::Named(id)),
+1 -1
View File
@@ -522,7 +522,7 @@ impl<'a> HarmonyPanel<'a> {
Variation::WarmCool => (&words.cool, &words.warm),
Variation::VividMuted => (&words.muted, &words.vivid),
};
Row::new().align(RowAlign::SpaceBetween).show(ui, |ui, _| {
Row::new().fill_width().align(RowAlign::SpaceBetween).show(ui, |ui, _| {
Text::new(left.clone()).show(ui);
Text::new(right.clone()).show(ui);
});
+2 -2
View File
@@ -15,7 +15,7 @@ use craft_cms::convert::CmykConverter;
use craft_keymap::Mods;
use craft_theme::Srgba;
use craft_ui::buttons::{Button, PopupMark};
use craft_ui::choice::{ChoiceWords, RING_SHARE, Segmented, Swatch, SwatchStyle, paint_ring};
use craft_ui::choice::{ChoiceWords, Segmented, Swatch, SwatchStyle, paint_ring, ring_band};
use craft_ui::contract::{
Access, Activation, Bind, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, Entry, Meta as _, Outcome, Overlay, OverlayUi,
Overlays as _, Pages, PaintUi, PartsCx, Pointer as _, PopupKind, Props as _, Remember as _, Role, Show as _, ShowContainer as _, WordSetCx as _,
@@ -372,7 +372,7 @@ pub(crate) fn paint_well(ui: &mut PaintUi<'_>, cx: &Cx<'_, impl craft_ui::contra
if style.ring {
let ground =
ui.with_style(cx.resolved.variant, |scope| SurfaceStyle { edge: SurfaceEdge::None, shadow: None, ..scope.surface(cx.env.surface()) });
ui.draw().surface_styled(well.shrink(well.width() * RING_SHARE), &ground);
ui.draw().surface_styled(well.shrink(ring_band(well)), &ground);
} else {
ui.draw().stroke(&shape, StrokeWidth::Thin, style.edge);
}
+10 -5
View File
@@ -440,8 +440,13 @@ impl<P: Clone + Send + Sync + 'static> Component for SwatchPair<'_, P> {
flags.set(Flags::MIXED, self.wells[i].paint.same().is_none());
flags.set(Flags::CHECKED, well == active);
let shape = if cx.style.round { HitShape::circle(at.center(), at.width() / 2.0) } else { HitShape::Rect(at) };
let part =
cx.part(WELL.at(i as u64), shape).sense(sense).priority(HitPriority::new(HitLevel::Body, u8::from(front))).flags(flags).focusable();
let part = cx
.part(WELL.at(i as u64), shape)
.sense(sense)
.priority(HitPriority::new(HitLevel::Body, u8::from(front)))
.flags(flags)
.focusable()
.tooltip(self.wells[i].label.clone());
// Focus arrives at the active well, so arriving makes no other well active.
let part = if well == active { part.selected() } else { part };
if self.popover {
@@ -449,10 +454,10 @@ impl<P: Clone + Send + Sync + 'static> Component for SwatchPair<'_, P> {
}
}
let buttons = self.button_rects(cx.style);
for (key, button, shown) in [(DEFAULT, buttons[0], self.default_button.is_some()), (SWAP, buttons[1], self.swap_button.is_some())] {
if shown {
for (key, button, name) in [(DEFAULT, buttons[0], &self.default_button), (SWAP, buttons[1], &self.swap_button)] {
if let Some(name) = name {
let at = flow.to_physical(button.translate(rect.min.to_vec2()));
cx.part(key, at).sense(Sense::CLICK).pointer_only("The host's Default Colours and Swap Colours commands");
cx.part(key, at).sense(Sense::CLICK).tooltip(name.clone()).pointer_only("The host's Default Colours and Swap Colours commands");
}
}
cx.roving(Roving::new(NavShape::Flat));
+43 -15
View File
@@ -3,15 +3,15 @@
use craft_behavior::{EditEvent, IconId, Mixed, Selection};
use craft_theme::Srgba;
use craft_ui::choice::{SwatchSpacing, SwatchTable};
use craft_ui::contract::{ActivateOn, Bind, Held, ListDrag, NoValue, Outcome, Pattern, Show as _, ShowContainer as _};
use craft_ui::choice::{SwatchSpacing, SwatchTable, SwatchTableOutput};
use craft_ui::contract::{ActivateOn, Bind, Held, LeadOnOpen, ListDrag, NoValue, Outcome, Pattern, Show as _, ShowContainer as _, SpaceAction};
use craft_ui::display::{Shade, Text};
use craft_ui::layout_components::Stack;
use craft_ui::runtime::env::Label;
use craft_ui::runtime::memory::StageAccess;
use craft_ui::runtime::requests::ColorRequest;
use craft_ui::style::TypeRole;
use egui::{Response, Ui};
use egui::{PointerButton, Response, Ui};
use std::sync::Arc;
#[cfg(feature = "suite")]
@@ -35,6 +35,9 @@ pub struct SwatchPaletteOutput {
pub pick_color: Option<ColorRequest>,
/// Every swatch click of this pass, also a click on the colour already bound, which files no `edit`.
pub picked: Option<Srgba>,
/// The picked entry's index in the palette, including a swatch with the bound colour or a duplicate colour.
/// The recent row and the Other… cell do not report a swatch index.
pub picked_swatch: Option<usize>,
}
impl Outcome for SwatchPaletteOutput {
@@ -65,6 +68,7 @@ pub struct SwatchPalette<'a> {
label: Label,
color: PaletteColor<'a>,
swatches: &'a [(Label, Srgba)],
selected_swatch: Option<usize>,
spacing: SwatchSpacing,
drag: Option<TableMap>,
/// The Other… cell: the key of its colour request and its name.
@@ -109,7 +113,7 @@ impl PaletteColor<'_> {
#[derive(Clone, Copy)]
enum Pick {
/// A swatch or a recent colour.
Color(Srgba),
Color { color: Srgba, swatch: Option<usize> },
/// The Other… cell.
Other,
}
@@ -119,6 +123,15 @@ fn cell_of(swatches: &[(Label, Srgba)], color: Option<Srgba>) -> Selection<usize
color.and_then(|color| swatches.iter().position(|(_, c)| c.to_rgba() == color.to_rgba())).map_or_else(Selection::default, Selection::single)
}
/// A completed activation, or the table's existing secondary-button pick.
fn picked_cell(table: &SwatchTableOutput, ui: &Ui) -> Option<usize> {
table.open.or_else(|| {
table.selected.filter(|_| {
ui.input(|input| input.pointer.button_pressed(PointerButton::Secondary) || input.pointer.button_released(PointerButton::Secondary))
})
})
}
impl<'a> SwatchPalette<'a> {
/// A palette named `label` of `swatches`, each a name and a colour, choosing the colour bound to `color`.
pub fn new(label: impl Into<Label>, color: Bind<'a, Srgba>, swatches: &'a [(Label, Srgba)]) -> Self {
@@ -126,6 +139,7 @@ impl<'a> SwatchPalette<'a> {
label: label.into(),
color: PaletteColor::Color(Held::new(color)),
swatches,
selected_swatch: None,
spacing: SwatchSpacing::Touching,
drag: None,
other: None,
@@ -141,6 +155,7 @@ impl<'a> SwatchPalette<'a> {
label: label.into(),
color: PaletteColor::Optional(color),
swatches,
selected_swatch: None,
spacing: SwatchSpacing::Touching,
drag: None,
other: None,
@@ -148,6 +163,13 @@ impl<'a> SwatchPalette<'a> {
}
}
/// Selects the entry at `index` when the host knows the swatch's identity. The palette uses the
/// bound colour to find a selection when the index is absent or out of range.
pub fn selected_swatch(mut self, index: Option<usize>) -> Self {
self.selected_swatch = index;
self
}
/// The gap between the cells, passed on to its `SwatchTable`.
pub fn spacing(mut self, spacing: SwatchSpacing) -> Self {
self.spacing = spacing;
@@ -179,7 +201,7 @@ impl<'a> SwatchPalette<'a> {
/// Shows the palette.
pub fn show(self, ui: &mut Ui) -> SwatchPaletteOutput {
let SwatchPalette { label, mut color, swatches, spacing, drag, other, recent } = self;
let SwatchPalette { label, mut color, swatches, selected_swatch, spacing, drag, other, recent } = self;
let recent = recent.filter(|(_, colors)| !colors.is_empty());
let recent_cells: Vec<(Label, Srgba)> =
recent.iter().flat_map(|(_, colors)| colors.iter()).map(|color| (Label::from(color.to_hex()), *color)).collect();
@@ -187,7 +209,8 @@ impl<'a> SwatchPalette<'a> {
let mut shown = Stack::new().show(ui, |ui, cx| {
let before = color.read(cx)?;
let bound = before.same().copied().flatten();
let mut current = cell_of(swatches, bound);
let preferred = selected_swatch.filter(|&index| index < swatches.len());
let mut current = preferred.map_or_else(|| cell_of(swatches, bound), Selection::single);
// A palette of recent colours alone has no grid: an empty table would be an empty list box in the tree.
let mut pick = None;
if !swatches.is_empty() || other.is_some() {
@@ -197,7 +220,11 @@ impl<'a> SwatchPalette<'a> {
.wells(true)
.spacing(spacing)
.activate(ActivateOn::Click)
.space(SpaceAction::ActivateLead)
.selection(Bind::bound(&mut current));
if let Some(index) = preferred {
table = table.rows_stamp(index as u64).lead_on_open(LeadOnOpen::Selected);
}
if let Some(map) = &drag {
table = map(table);
}
@@ -207,8 +234,8 @@ impl<'a> SwatchPalette<'a> {
let table = table.show_all(ui);
// The Other… cell is keyed `swatches.len()`, past the swatches. A click selects on its press and activates
// on its release, so only the activation files the request: one request for one click.
pick = table.selected.or(table.open).and_then(|at| match swatches.get(at) {
Some((_, picked)) => Some(Pick::Color(*picked)),
pick = picked_cell(&table, ui).and_then(|at| match swatches.get(at) {
Some((_, picked)) => Some(Pick::Color { color: *picked, swatch: Some(at) }),
None => (other.is_some() && table.open == Some(at) && at == swatches.len()).then_some(Pick::Other),
});
}
@@ -219,10 +246,11 @@ impl<'a> SwatchPalette<'a> {
.tips(true)
.wells(true)
.activate(ActivateOn::Click)
.space(SpaceAction::ActivateLead)
.selection(Bind::bound(&mut current))
.show_all(ui);
if let Some((_, picked)) = row.selected.or(row.open).and_then(|at| recent_cells.get(at)) {
pick = Some(Pick::Color(*picked));
if let Some((_, picked)) = picked_cell(&row, ui).and_then(|at| recent_cells.get(at)) {
pick = Some(Pick::Color { color: *picked, swatch: None });
}
}
Some((before, pick))
@@ -235,21 +263,21 @@ impl<'a> SwatchPalette<'a> {
match pick? {
Pick::Other => {
let key = other.as_ref().map(|(key, _)| key.clone())?;
Some((None, None, Some(ColorRequest::new(key, bound).title(name.clone()))))
Some((None, None, Some(ColorRequest::new(key, bound).title(name.clone())), None))
}
Pick::Color(after) => {
Pick::Color { color: after, swatch } => {
let unchanged = bound.is_some_and(|bound| bound.to_rgba() == after.to_rgba());
let edit = (!unchanged).then(|| {
color.write(cx, before, after, name.as_str());
let reported = bound.map_or(Mixed::Mixed, Mixed::Same);
EditEvent::set(reported, after, Arc::from(name.as_str()), None)
});
Some((Some(after), edit, None))
Some((Some(after), edit, None, swatch))
}
}
})
.flatten();
let (picked, edit, pick_color) = settled.unwrap_or((None, None, None));
SwatchPaletteOutput { response: shown.output, edit, pick_color, picked }
let (picked, edit, pick_color, picked_swatch) = settled.unwrap_or((None, None, None, None));
SwatchPaletteOutput { response: shown.output, edit, pick_color, picked, picked_swatch }
}
}
+26 -8
View File
@@ -446,9 +446,10 @@ pub struct ColorPanel<'a> {
dynamic: bool,
layout: ColorPanelLayout,
wells: Option<([PairWell; 2], Bind<'a, Well>)>,
buttons: Option<[Label; 2]>,
edited: Option<Option<PickedColor>>,
shown: Option<ColorPanelShown>,
recent: &'a [Srgba],
recent: Option<&'a [Srgba]>,
recent_setup: Option<RecentSetup>,
gamut: Option<Gamut<'a>>,
}
@@ -469,9 +470,10 @@ fn recent_setup<P: Send + Sync + 'static>(map: impl Fn(usize) -> Option<P> + Sen
#[derive(Clone, Copy)]
struct Inputs<'a> {
wells: Option<&'a [PairWell; 2]>,
buttons: Option<&'a [Label; 2]>,
edited: Option<&'a Option<PickedColor>>,
shown: &'a ColorPanelShown,
recent: &'a [Srgba],
recent: Option<&'a [Srgba]>,
recent_setup: Option<&'a RecentSetup>,
}
@@ -486,9 +488,10 @@ impl<'a> ColorPanel<'a> {
dynamic: true,
layout: ColorPanelLayout::default(),
wells: None,
buttons: None,
edited: None,
shown: None,
recent: &[],
recent: None,
recent_setup: None,
gamut: None,
}
@@ -528,6 +531,14 @@ impl<'a> ColorPanel<'a> {
self
}
/// The names of the [`ColorPanelLayout::FillStroke`] layout's swap and default buttons, which are also their
/// tooltips: a host names the keys of its own commands there ("Swap Fill and Stroke (Shift+X)"). The panel's
/// words by default.
pub fn buttons(mut self, swap: impl Into<Label>, default: impl Into<Label>) -> Self {
self.buttons = Some([swap.into(), default.into()]);
self
}
/// The colour the rows edit, with its model values; `None` disables the rows (mixed, None, a pattern). The edited
/// well's colour by default.
pub fn edited(mut self, color: Option<PickedColor>) -> Self {
@@ -541,9 +552,10 @@ impl<'a> ColorPanel<'a> {
self
}
/// The Recent Colors, a spaced `SwatchPalette` that wraps and drags.
/// The Recent Colors, a spaced `SwatchPalette` that wraps and drags. The FillStroke layout shows the captioned row
/// for a host that gives them, an empty list included; without them it shows no row.
pub fn recent(mut self, colors: &'a [Srgba]) -> Self {
self.recent = colors;
self.recent = Some(colors);
self
}
@@ -561,7 +573,7 @@ impl<'a> ColorPanel<'a> {
/// Shows the panel and returns this pass's edits and requests.
pub fn show(self, ui: &mut Ui) -> ColorPanelOutput {
let ColorPanel { state, colors, cmyk, rgb, dynamic, layout, wells, edited, shown: rows, recent, recent_setup, gamut } = self;
let ColorPanel { state, colors, cmyk, rgb, dynamic, layout, wells, buttons, edited, shown: rows, recent, recent_setup, gamut } = self;
let env = Env::of(ui);
let (words, dialog) = (env.words::<ColorPanelWords>(), env.words::<ColorPickerDialogWords>());
let mut held = Held::new(state);
@@ -597,6 +609,7 @@ impl<'a> ColorPanel<'a> {
dialog: &dialog,
inputs: Inputs {
wells: wells.as_ref(),
buttons: buttons.as_ref(),
edited: edited.as_ref(),
shown: rows.as_ref().unwrap_or(&default_rows),
recent,
@@ -981,7 +994,8 @@ impl Body<'_> {
}
/// The foreground over the background (the host's wells when it gave them): a click on the other well edits it, a
/// click on the edited one asks for the picker. `FillStroke` adds the pair's swap and default buttons.
/// click on the edited one asks for the picker. `FillStroke` adds the pair's swap and default buttons, named by the
/// host's [`ColorPanel::buttons`] when it gave them.
fn wells(&mut self, ui: &mut Ui) {
let was = self.active;
let mut active = was;
@@ -991,7 +1005,11 @@ impl Body<'_> {
let pair = SwatchPair::<()>::new(self.words.wells.clone(), wells, Bind::bound(&mut active)).popover(false).frame_active(true);
let pair = match self.layout {
ColorPanelLayout::ForegroundBackground => pair,
ColorPanelLayout::FillStroke => pair.swap_button(self.words.swap_colors.clone()).default_button(self.words.default_colors.clone()),
ColorPanelLayout::FillStroke => {
let [swap, default] =
self.inputs.buttons.cloned().unwrap_or_else(|| [self.words.swap_colors.clone(), self.words.default_colors.clone()]);
pair.swap_button(swap).default_button(default)
}
};
let pair = pair.show(ui);
self.active = active;
+13 -6
View File
@@ -6,10 +6,11 @@ use craft_behavior::{EditEvent, Mixed};
use craft_theme::Srgba;
use craft_ui::choice::{Swatch, SwatchSpacing};
use craft_ui::contract::{Bind, Gap, LabelScheme, Props as _, Scroll, Show as _, ShowContainer as _, Sizing};
use craft_ui::display::Text;
use craft_ui::display::{Shade, Text};
use craft_ui::form::{Field, FieldGroup};
use craft_ui::layout_components::{Row, Stack};
use craft_ui::runtime::env::Label;
use craft_ui::style::TypeRole;
use craft_ui::text::{HexField, TextField};
use egui::Ui;
@@ -131,8 +132,8 @@ impl Body<'_> {
}
}
/// The Spectrum ramp (grey in Grayscale) with a tooltip naming the shown mode. A Cmd or Ctrl click recolours and
/// picks nothing; a Shift click moves to the next mode.
/// The Spectrum ramp (gray in Grayscale) with a tooltip naming the shown mode, at least as tall as its square end
/// boxes. A Cmd or Ctrl click recolors and picks nothing; a Shift click moves to the next mode.
fn spectrum(&mut self, ui: &mut Ui) {
let mode = self.shown_mode();
let kind = if mode == ColorPanelMode::GrayscaleSlider { RampKind::Grayscale } else { RampKind::Spectrum };
@@ -145,6 +146,7 @@ impl Body<'_> {
.gamut(gamut)
.gamut_revision(revision)
.web_safe(self.now.web_safe_ramp)
.square_boxes(true)
.sizing(Sizing::Fill)
.show(ui);
self.ramp_events(ramp.edit.events);
@@ -154,14 +156,19 @@ impl Body<'_> {
}
}
/// The Recent Colors as a spaced palette; a pick sets the colour.
/// The Recent Colors caption over a spaced palette; a pick sets the color. The caption shows while the host's list
/// is empty, where the first applied color will go.
// PLAN: Alt on a recent colour or a warning chip should set the other colour; `SwatchPaletteOutput` and
// `ColorWarningChipOutput` report no modifiers (color-w1 for the palette, the owner of warning.rs for the chip).
fn recent(&mut self, ui: &mut Ui) {
if self.inputs.recent.is_empty() {
let Some(recent) = self.inputs.recent else {
return;
};
Text::new(self.words.recent_colors.clone()).role(TypeRole::Caption).shade(Shade::Faint).show(ui);
if recent.is_empty() {
return;
}
let swatches: Vec<(Label, Srgba)> = self.inputs.recent.iter().map(|color| (Label::from(color.to_hex()), *color)).collect();
let swatches: Vec<(Label, Srgba)> = recent.iter().map(|color| (Label::from(color.to_hex()), *color)).collect();
let mut current = self.color();
let mut palette = SwatchPalette::new(self.words.recent_colors.clone(), Bind::bound(&mut current), &swatches).spacing(SwatchSpacing::Spaced);
if let Some(setup) = self.inputs.recent_setup {
+14 -2
View File
@@ -6,8 +6,8 @@ use craft_cms::convert::CmykConverter;
use craft_theme::{Hsb, Srgba};
use craft_ui::canvas::context_click;
use craft_ui::contract::{
Access, Bind, BindMut, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, Focus as _, Input, Name, Outcome, PaintUi, PartsCx,
Pointer as _, Props as _, Remember as _, Role, WordSetCx as _,
Access, Bind, BindMut, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, Focus as _, Input, MeasureCx, Name, Outcome, PaintUi,
PartsCx, Pointer as _, Props as _, Remember as _, Role, WordSetCx as _,
};
use craft_ui::primitives::{Marker, PaintShape, StrokeWidth};
use craft_ui::runtime::commands::FireSource;
@@ -240,6 +240,11 @@ pub struct ColorRamp<'a> {
/// Whether the white and black boxes follow the bar; on by default.
#[prop]
boxes: bool,
/// Whether the ramp is at least as tall as its two end boxes stacked, each as tall as it is wide, in place of a
/// color band; off by default. A ramp that takes the room under other rows keeps this height in a host sized by
/// its content and in a short one.
#[prop]
square_boxes: bool,
/// The ramp's kind as the host names it ("RGB Spectrum"), the bar's accessible value.
#[prop(into)]
kind_name: Option<Label>,
@@ -265,6 +270,7 @@ impl<'a> ColorRamp<'a> {
web_safe: false,
recolor_clicks: false,
boxes: true,
square_boxes: false,
kind_name: None,
colors: Arc::default(),
shown_ends: ends,
@@ -416,6 +422,12 @@ impl Component for ColorRamp<'_> {
Some(Axis::X)
}
/// With [`square_boxes`](ColorRamp::square_boxes), as tall as its two end boxes stacked, each as tall as it is wide;
/// else the style's least, a color band.
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
if self.square_boxes { Vec2::new(0.0, cx.style.boxes * 2.0) } else { Vec2::ZERO }
}
fn sense(&self) -> Sense {
Sense::empty()
}
+62 -11
View File
@@ -136,11 +136,19 @@ pub(super) fn group_rename(groups: &[SwatchGroup], index: usize, text: &str) ->
(!name.is_empty() && !groups.iter().enumerate().any(|(i, g)| i != index && g.name == name)).then(|| name.to_owned())
}
/// The flat rows of the browser: each group's header, then its swatches.
/// Whether the browser shows a header row for `group`: every group but the one with an empty name, which holds the
/// swatches outside every group.
fn has_header(group: &SwatchGroup) -> bool {
!group.name.is_empty()
}
/// The flat rows of the browser: each group's header (none for the swatches outside every group), then its swatches.
fn flat<'a>(groups: impl IntoIterator<Item = &'a SwatchGroup>) -> Vec<SwatchKey> {
let mut rows = Vec::new();
for group in groups {
rows.push(SwatchKey::Group(group.name.clone()));
if has_header(group) {
rows.push(SwatchKey::Group(group.name.clone()));
}
rows.extend(group.entries.iter().map(|e| SwatchKey::Swatch(e.name.clone())));
}
rows
@@ -167,10 +175,21 @@ fn resolve_move(groups: &[SwatchGroup], names: &[&str], to: usize, parent: Optio
(group < groups.len()).then_some((group, slot))
}
/// The slot groups `names` land in when dropped at flat row `to`, counted in the groups that stay.
/// The slot groups `names` land in when dropped at flat row `to`, counted in the groups that stay: each staying group
/// whose first row (its header, or its first swatch when it has none) is above `to`. Groups never land above the
/// swatches outside every group when those come first.
fn group_slot(groups: &[SwatchGroup], names: &[&str], to: usize) -> usize {
let remaining = flat(groups.iter().filter(|g| !names.contains(&g.name.as_str())));
remaining[..to.min(remaining.len())].iter().filter(|k| matches!(k, SwatchKey::Group(_))).count()
let mut row = 0;
let mut slot = 0;
let mut staying = groups.iter().filter(|g| !names.contains(&g.name.as_str())).peekable();
let floor = usize::from(staying.peek().is_some_and(|g| !has_header(g)));
for group in staying {
if row < to {
slot += 1;
}
row += usize::from(has_header(group)) + group.entries.len();
}
slot.max(floor)
}
/// The `at` of each edit that moves `moved` (in library order) one by one within `order`, so that they end up together
@@ -352,8 +371,8 @@ impl SwatchLibrary {
}
/// Applies a reorder of the browser: swatches go into a group at a place, or groups to a place among the
/// groups. `to` counts in the flat rows (a header, then its swatches) that remain once the moved ones are
/// taken out. Anything else leaves the library as it is.
/// groups. `to` counts in the flat rows (a header, then its swatches; no header for the group with an empty
/// name) that remain once the moved ones are taken out. Anything else leaves the library as it is.
pub fn apply_reorder(&mut self, mv: &ReorderMove<SwatchKey>) -> bool {
if mv.copy {
return false;
@@ -623,7 +642,11 @@ pub(super) fn panel_source<'a>(
} else {
entries().filter_map(|e| e.color().map(|color| (e.name.as_str(), color.to_srgb(cmyk)))).collect()
};
PresetSource::new(SwatchInputs { groups, drawn, icons, host }, PresetFns::new(source_rows).thumb(paint_swatch))
let fns = PresetFns::new(source_rows).thumb(paint_swatch).accepts(|_, drag, _, _| {
let groups = matches!(drag.grabbed, SwatchKey::Group(_));
drag.keys.iter().all(|key| matches!(key, SwatchKey::Group(_)) == groups)
});
PresetSource::new(SwatchInputs { groups, drawn, icons, host }, fns)
}
fn source_rows(inputs: &SwatchInputs<'_>, env: &Env) -> Vec<PresetRow<SwatchKey>> {
@@ -641,17 +664,24 @@ fn source_rows(inputs: &SwatchInputs<'_>, env: &Env) -> Vec<PresetRow<SwatchKey>
}
/// The rows the Swatches panel lists for `groups`: each group's header, then its swatches, each named by its name and
/// colour value (the name alone for a swatch without a colour).
/// colour value (the name alone for a swatch without a colour). A group with an empty name holds the swatches outside
/// every group: its swatches show at the top level, with no header.
pub fn swatch_rows(groups: &[SwatchGroup], words: &SwatchesWords) -> Vec<PresetRow<SwatchKey>> {
let mut rows = Vec::with_capacity(groups.len() + groups.iter().map(|g| g.entries.len()).sum::<usize>());
for group in groups {
rows.push(PresetRow::group(SwatchKey::Group(group.name.clone()), group.name.as_str(), 0).count(group.entries.len()));
let header = has_header(group);
let depth = usize::from(header);
if header {
rows.push(PresetRow::group(SwatchKey::Group(group.name.clone()), group.name.as_str(), 0).count(group.entries.len()));
}
for entry in &group.entries {
let named = match entry.color() {
Some(color) => format!("{}, {}", entry.name, value_text(color, words.book_color.as_str())),
None => entry.name.clone(),
};
rows.push(PresetRow::item(SwatchKey::Swatch(entry.name.clone()), entry.name.as_str(), 1).tooltip(named.clone()).accessible_name(named));
rows.push(
PresetRow::item(SwatchKey::Swatch(entry.name.clone()), entry.name.as_str(), depth).tooltip(named.clone()).accessible_name(named),
);
}
}
rows
@@ -676,6 +706,27 @@ pub(crate) mod tests {
SwatchGroup { name: name.to_owned(), entries: entries.iter().map(|n| SwatchEntry::new((*n).to_owned(), SwatchColor::Gray(0.5))).collect() }
}
/// The swatches outside every group (the group with an empty name) have no header row, so a place below them
/// counts them as rows: a group dropped there lands after them, and a swatch dropped there joins them. A group
/// dropped above them lands after them too.
#[trial]
fn drops_below_the_ungrouped_swatches_land_after_them() {
let library = SwatchLibrary::new(vec![group("", &["A", "B"]), group("G", &["C"]), group("H", &["D"])]);
let rows: Vec<_> = swatch_rows(&library.groups, &SwatchesWords::default()).into_iter().map(|row| row.key).collect();
assert_eq!(rows, flat(&library.groups), "the reorder counts the rows the browser shows");
for to in [0, 2] {
let mut moved = library.clone();
assert!(moved.apply_reorder(&ReorderMove::new(SwatchKey::Group("H".to_owned()), vec![SwatchKey::Group("H".to_owned())], to, false)));
let order: Vec<_> = moved.groups.iter().map(|g| g.name.as_str()).collect();
assert_eq!(order, ["", "H", "G"], "H dropped at row {to} lands below the ungrouped swatches, above G");
}
let mut moved = library.clone();
assert!(moved.apply_reorder(&ReorderMove::new(SwatchKey::Swatch("C".to_owned()), vec![SwatchKey::Swatch("C".to_owned())], 2, false)));
assert_eq!(moved.find("C"), Some(SwatchAt::new(0, 2)), "C joins the ungrouped swatches, after B");
}
/// Edits that move several items down or up give the order the browser's own reorder gives.
#[trial]
fn multi_item_moves_apply_as_the_reorder_does() {
+76 -5
View File
@@ -1,6 +1,6 @@
//! `SwatchesPanel`: the panel body, its state and what it reports.
use std::collections::BTreeMap;
use std::collections::{BTreeMap, BTreeSet};
use std::rc::Rc;
use std::sync::Arc;
@@ -18,9 +18,9 @@ use craft_ui::patterns::presets::{
};
use craft_ui::primitives::IconSpec;
use craft_ui::runtime::env::{Count, Env};
use egui::{Response, Ui};
use egui::{AsIdSalt, IdSalt, Response, Ui};
use super::library::{HostThumb, find_swatch, has, panel_source};
use super::library::{HostThumb, find_swatch, group_of, has, panel_source};
use super::menu::event_edits;
use super::{SWATCH_ZOOM, SwatchAt, SwatchEdit, SwatchKey, SwatchesFileOutput, SwatchesState, SwatchesWords};
use crate::palette::{SwatchGroup, SwatchNote, SwatchReport};
@@ -40,6 +40,7 @@ pub struct SwatchesPanelOutput {
pub edits: Vec<SwatchEdit>,
/// The browser events the panel does not turn into `used` or `edits`, in the order they happened: `Activate`,
/// `Menu`, `DropAt`, `Dropped` and `Reorder`. `Reorder` is also in `edits`; a host runs one of the two.
/// When enabled by [`SwatchesPanel::report_invalid_renames`], rejected inline renames appear here as `Rename`.
pub events: Vec<PresetEvent<SwatchKey>>,
}
@@ -77,6 +78,8 @@ type PayloadAdder<'a> = Box<dyn for<'b> Fn(PresetBrowser<'b, SwatchKey>) -> Pres
/// [`search`](SwatchesPanel::search), [`row_icons`](SwatchesPanel::row_icons), [`takes_drop`](SwatchesPanel::takes_drop)
/// and [`row_items`](SwatchesPanel::row_items) pass through; the events they cause come out in
/// [`SwatchesPanelOutput::events`].
/// - [`document`](SwatchesPanel::document) keeps the browser's own state (an open rename field, the scroll position)
/// per document, so a host that shows one panel for several documents does not carry it from one to another.
/// - It fills the room it is given, and its browser scrolls the swatches: show it outside a body that scrolls.
#[must_use = "show the panel with `show`"]
#[derive(Pattern)]
@@ -87,15 +90,19 @@ pub struct SwatchesPanel<'a> {
foreground: Srgba,
thumb: Option<HostThumb<'a>>,
tools: Option<ToolsFn<'a>>,
tools_at_start: bool,
drop_zone: Option<DropZone>,
footer: Option<Option<PresetFooterOptions<'a>>>,
reveal: Option<SwatchKey>,
search: bool,
row_icons: Option<RowIconsFn<'a>>,
select: SelectMode,
report_invalid_renames: bool,
takes_drop: Option<DropMaker<'a>>,
payloads: Vec<PayloadAdder<'a>>,
row_items: Option<RowItemsFn<'a>>,
document: Option<IdSalt>,
select_groups: bool,
}
/// What the body decided; `show` stores the state and reports the rest after the real run.
@@ -117,15 +124,19 @@ impl<'a> SwatchesPanel<'a> {
foreground,
thumb: None,
tools: None,
tools_at_start: false,
drop_zone: None,
footer: None,
reveal: None,
search: true,
row_icons: None,
select: SelectMode::Single,
report_invalid_renames: false,
takes_drop: None,
payloads: Vec::new(),
row_items: None,
document: None,
select_groups: false,
}
}
@@ -150,6 +161,12 @@ impl<'a> SwatchesPanel<'a> {
self
}
/// Places the host's tools before the browser controls in the toolbar. Off by default.
pub fn tools_at_start(mut self, at_start: bool) -> Self {
self.tools_at_start = at_start;
self
}
/// Where a drop onto the panel lands.
pub fn drop_zone(mut self, zone: DropZone) -> Self {
self.drop_zone = Some(zone);
@@ -187,6 +204,13 @@ impl<'a> SwatchesPanel<'a> {
self
}
/// Reports committed inline renames rejected by the panel in [`SwatchesPanelOutput::events`], so the host can
/// explain the rejection. Accepted renames produce their usual edit. Off by default.
pub fn report_invalid_renames(mut self, enabled: bool) -> Self {
self.report_invalid_renames = enabled;
self
}
/// A host payload of type `P` can be dropped onto a swatch or between swatches at `place` where `accepts` agrees;
/// the drop comes back as `PresetEvent::Dropped`.
pub fn takes_drop<P: Send + Sync + 'static>(mut self, place: DropPlace, accepts: impl Fn(&P, &DropAt<SwatchKey>) -> bool + 'a) -> Self {
@@ -216,6 +240,20 @@ impl<'a> SwatchesPanel<'a> {
self
}
/// The document whose swatches the panel shows. The browser keeps its own state (an open rename field, the scroll
/// position) for each document, so a rename left open in one document does not open on another document's
/// swatch of the same name. Without it the browser keeps that state for the `Ui` it is shown in.
pub fn document(mut self, document: impl AsIdSalt) -> Self {
self.document = Some(IdSalt::new(document));
self
}
/// Lets panel interactions select group rows alongside swatches in both views. Off by default.
pub fn select_groups(mut self, enabled: bool) -> Self {
self.select_groups = enabled;
self
}
/// Draws the panel and returns the user's actions this pass.
pub fn show(self, ui: &mut Ui) -> SwatchesPanelOutput {
let SwatchesPanel {
@@ -225,21 +263,27 @@ impl<'a> SwatchesPanel<'a> {
foreground,
thumb,
mut tools,
tools_at_start,
drop_zone,
footer,
reveal,
search,
row_icons,
select,
report_invalid_renames,
takes_drop,
payloads,
row_items,
document,
select_groups,
} = self;
let cmyk = cmyk.unwrap_or_else(|| CmykConverter::coated());
let words = Env::of(ui).words::<SwatchesWords>();
let mut held_state = Held::new(state);
let ctx = ui.ctx().clone();
let browser_id = ui.scope_id();
// A document's browser has an id of its own; otherwise the browser takes the scope id of the `Ui` it is shown in.
let document_id = document.map(|document| ui.scope_id().with(document));
let browser_id = document_id.unwrap_or_else(|| ui.scope_id());
let icons: BTreeMap<&str, Vec<(IconSpec<'static>, String)>> = match &row_icons {
Some(icons) => {
groups.iter().flat_map(|g| g.entries.iter()).map(|e| (e.name.as_str(), icons(&SwatchKey::Swatch(e.name.clone())))).collect()
@@ -263,10 +307,15 @@ impl<'a> SwatchesPanel<'a> {
let mut browser = PresetBrowser::new(words.title.clone(), Bind::bound(&mut st.browser), &source)
.thumb_range(SWATCH_ZOOM)
.toolbar(true)
.tools_at_start(tools_at_start)
.search(search)
.select(select)
.select_groups(select_groups)
.reorder(PresetReorder::items_and_groups())
.selection(Bind::bound(&mut st.selection));
if let Some(id) = document_id {
browser = browser.browser_id(id);
}
if let Some(options) = footer_options {
browser = browser.footer(options);
}
@@ -293,7 +342,21 @@ impl<'a> SwatchesPanel<'a> {
let mut used = None;
let mut edits = Vec::new();
let mut events = Vec::new();
let deleting_groups: BTreeSet<_> = out
.events
.iter()
.filter_map(|event| match event {
PresetEvent::Delete(key @ SwatchKey::Group(_)) => group_of(groups, key),
_ => None,
})
.collect();
for event in out.events {
if !deleting_groups.is_empty()
&& let PresetEvent::Delete(key @ SwatchKey::Swatch(_)) = &event
&& group_of(groups, key).is_some_and(|group| deleting_groups.contains(&group))
{
continue;
}
if let PresetEvent::Select { key: SwatchKey::Swatch(name), mods, .. } = &event
&& let Some(at) = find_swatch(groups, name)
&& let Some(entry) = groups.get(at.group).and_then(|g| g.entries.get(at.index))
@@ -309,7 +372,15 @@ impl<'a> SwatchesPanel<'a> {
| PresetEvent::Reorder { .. }
)
.then(|| event.clone());
edits.extend(event_edits(groups, &mut st, event, foreground, &words));
// The browser has discarded empty and unchanged names. Keep a live target's attempt for diagnostics
// if translating it into an edit fails. Validation and its selection updates still run in one place.
let attempted_rename =
(report_invalid_renames && matches!(&event, PresetEvent::Rename { key, .. } if live(key))).then(|| event.clone());
let resolved = event_edits(groups, &mut st, event, foreground, &words);
if resolved.is_empty() {
events.extend(attempted_rename);
}
edits.extend(resolved);
events.extend(forwarded);
}
Some(Settled { before_state, st, used, edits, events })
+101
View File
@@ -0,0 +1,101 @@
//! A named/custom color choice reports only a committed row or custom picker request.
use std::cell::RefCell;
use std::rc::Rc;
use craft_color_ui::ui::{ChosenColor, ColorChoice, NamedColor};
use craft_theme::Srgba;
use craft_ui::runtime::requests::ColorRequest;
use craft_ui::testing::{Fixture, trial};
use egui::{Key, Modifiers, vec2};
const RED: Srgba = Srgba::rgb(0.8, 0.1, 0.2);
const BLUE: Srgba = Srgba::rgb(0.1, 0.2, 0.8);
const CUSTOM: Srgba = Srgba::rgb(0.2, 0.6, 0.4);
#[derive(Default)]
struct Reports {
chosen: Vec<ChosenColor>,
requests: Vec<ColorRequest>,
}
struct Rig {
fixture: Fixture,
value: Rc<RefCell<ChosenColor>>,
reports: Rc<RefCell<Reports>>,
}
impl Rig {
fn new(start: ChosenColor, custom: Option<Srgba>) -> Self {
let value = Rc::new(RefCell::new(start));
let reports = Rc::new(RefCell::new(Reports::default()));
let (held, reported) = (value.clone(), reports.clone());
let mut fixture = Fixture::new(move |ui| {
let value = held.borrow().clone();
let shown = ColorChoice::new("Color", &value)
.named([NamedColor::new("red", "Red", Some(RED)), NamedColor::new("blue", "Blue", Some(BLUE))])
.custom(custom)
.show(ui);
if let Some(chosen) = shown.chosen {
*held.borrow_mut() = chosen.clone();
reported.borrow_mut().chosen.push(chosen);
}
reported.borrow_mut().requests.extend(shown.pick_color);
});
fixture.room(vec2(400.0, 240.0)).settle();
Rig { fixture, value, reports }
}
fn open(&mut self) {
let field = self.fixture.by_label("Color").expect("the color choice");
self.fixture.click(&field);
}
}
/// A provisional named row never replaces the host's named or custom choice; Enter reports it once.
#[trial]
fn canceled_color_navigation_keeps_the_hosts_original_choice() {
for original in [ChosenColor::Named("red".into()), ChosenColor::Custom] {
let key = if original == ChosenColor::Custom { Key::ArrowUp } else { Key::ArrowDown };
let mut rig = Rig::new(original.clone(), Some(CUSTOM));
rig.open();
rig.fixture.key(key, Modifiers::NONE).idle(2);
assert_eq!(*rig.value.borrow(), original, "navigation alone does not replace the original color");
assert!(rig.reports.borrow().chosen.is_empty());
rig.fixture.key(Key::Escape, Modifiers::NONE).settle();
assert_eq!(*rig.value.borrow(), original);
assert!(rig.reports.borrow().chosen.is_empty());
assert!(rig.reports.borrow().requests.is_empty());
rig.open();
rig.fixture.key(key, Modifiers::NONE).key(Key::Enter, Modifiers::NONE).settle().idle(2);
assert_eq!(*rig.value.borrow(), ChosenColor::Named("blue".into()));
assert_eq!(rig.reports.borrow().chosen, [ChosenColor::Named("blue".into())]);
assert!(rig.reports.borrow().requests.is_empty());
}
}
/// Proposing Select Custom Color neither requests the picker nor changes the color; Enter requests it once.
#[trial]
fn custom_color_picker_waits_for_a_committed_row() {
for custom in [Some(CUSTOM), None] {
let original = ChosenColor::Named("blue".into());
let mut rig = Rig::new(original.clone(), custom);
rig.open();
rig.fixture.key(Key::End, Modifiers::NONE).idle(2);
assert!(rig.reports.borrow().requests.is_empty(), "a provisional custom row cannot open a picker");
rig.fixture.key(Key::Escape, Modifiers::NONE).settle();
assert_eq!(*rig.value.borrow(), original);
assert!(rig.reports.borrow().requests.is_empty());
assert!(rig.reports.borrow().chosen.is_empty());
rig.open();
rig.fixture.key(Key::End, Modifiers::NONE).key(Key::Enter, Modifiers::NONE).settle().idle(2);
assert_eq!(*rig.value.borrow(), original, "the host changes its color only after the requested picker answers");
let reports = rig.reports.borrow();
assert!(reports.chosen.is_empty());
assert_eq!(reports.requests.len(), 1);
assert_eq!(reports.requests[0].key, ColorChoice::CUSTOM_KEY);
assert_eq!(reports.requests[0].color, Some(custom.unwrap_or(BLUE)));
}
}
+44
View File
@@ -202,6 +202,50 @@ impl WheelRig {
}
}
/// The names focus takes from the hue ring of a wheel shown in an arena (a split area's body) between two buttons,
/// one per Tab in `keys` (with its modifiers).
fn arena_tab_walk(inner: WheelInner, keys: &[Modifiers]) -> Vec<Option<String>> {
let mut fixture = Fixture::new(move |ui| {
let _ = craft_ui::buttons::Button::new("Before").show(ui);
let limits = |_: &usize| craft_ui::contract::SizeLimits::default();
let rules = craft_ui::docking::tree::FrameRules::new(&limits);
let area = Rect::from_min_size(ui.max_rect().min + vec2(0.0, 40.0), vec2(400.0, 340.0));
let _ = craft_ui::docking::SplitArea::pair("Panels", craft_behavior::Axis::X, (0usize, 1usize), 0.99, rules).show_at(ui, area, |ui, _| {
let _ = ColorWheel::new("Color wheel", Bind::given(ModelValues::new("hsb", &[200.0, 50.0, 50.0]))).inner(inner).show(ui);
});
let _ = craft_ui::buttons::Button::new("After").show(ui);
});
fixture.room(vec2(420.0, 420.0));
fixture.settle();
let hue = fixture.by_label("Hue").expect("the ring");
fixture.access(AccessActionKind::Focus, &hue);
fixture.idle(2);
let focused = |fixture: &Fixture| {
let tree = fixture.tree();
tree.name_of(craft_ui::testing::access::focused_key(tree)).map(str::to_owned)
};
assert_eq!(focused(&fixture).as_deref(), Some("Hue"), "{inner:?}: the ring takes focus");
keys.iter()
.map(|mods| {
fixture.key(Key::Tab, *mods);
fixture.idle(2);
focused(&fixture)
})
.collect()
}
/// In an arena, as in a docked panel, Tab from the hue ring lands on the saturation and brightness control, also when a
/// square shows it through its own folded picker, then goes on past the wheel; Shift-Tab comes back the same way.
#[trial]
fn in_an_arena_tab_from_the_ring_reaches_the_saturation_and_brightness_control() {
let (on, back) = (Modifiers::NONE, Modifiers::SHIFT);
for inner in [WheelInner::Triangle, WheelInner::Square] {
let walk = arena_tab_walk(inner, &[on, on, back, back]);
let expected = ["Saturation and brightness", "After", "Saturation and brightness", "Hue"].map(|name| Some(name.to_owned()));
assert_eq!(walk, expected, "{inner:?}");
}
}
/// A square wheel hands a press between the square and the ring to the square; its named markers speak their colour,
/// pick on a click, and a press held on one still drags the ring; Shift snaps a ring drag to 45 degrees, in both
/// variants.
+1
View File
@@ -1,6 +1,7 @@
//! The screen tests of craft-color-ui, folded into the lib's test target.
pub(crate) mod area_gamut;
pub(crate) mod choice;
pub(crate) mod color_parts;
pub(crate) mod gradient_bar;
pub(crate) mod paint_chip;
+38 -2
View File
@@ -1,13 +1,49 @@
//! `PaintChip`'s menu mark, the arrow after the well that is part of the chip, and its swatch size.
//! `PaintChip`'s menu mark, the arrow after the well that is part of the chip, its swatch size and its ring.
use craft_color_ui::ui::{Paint, PaintChip, PaintChipSize};
use craft_color_ui::ui::{GradientPreview, Paint, PaintChip, PaintChipSize};
use craft_theme::Srgba;
use craft_ui::buttons::PopupMark;
use craft_ui::contract::{Bind, Role, Show as _};
use craft_ui::testing::{Fixture, trial};
use egui::{Rect, Shape};
use std::cell::Cell;
use std::rc::Rc;
/// Every shape of the frame, groups opened.
fn flat(shapes: Vec<Shape>) -> Vec<Shape> {
shapes.into_iter().flat_map(|shape| if let Shape::Vec(inner) = shape { flat(inner) } else { vec![shape] }).collect()
}
/// A ring chip wider than it is high keeps an open middle: the hole inside the band is at least a third of the chip's
/// height, and the band is as thick at the sides as at the top and bottom. Checked for a solid paint, drawn as a band
/// of the colour, and for a gradient, whose middle is covered by the surface the chip sits on.
#[trial]
fn a_wide_ring_chip_keeps_an_open_middle() {
let gradient = GradientPreview::new(vec![(0.0, Srgba::rgb(0.2, 0.4, 0.8)), (1.0, Srgba::WHITE)]);
for paint in [Paint::Solid(Srgba::rgb(0.2, 0.4, 0.8)), Paint::Gradient(gradient)] {
let mut fixture = Fixture::new(move |ui| {
let mut paint = paint.clone();
let _ = PaintChip::new("Stroke", Bind::bound(&mut paint), Srgba::BLACK).ring(true).show(ui);
});
fixture.settle();
let well = fixture.by_role(Role::COLOR_WELL).first().copied().expect("the chip is a colour well").rect;
assert!(well.width() > well.height(), "the chip is wider than it is high");
// The hole is the smallest rect drawn round the well's centre.
let hole = flat(fixture.frame_shapes())
.into_iter()
.filter_map(|shape| match shape {
Shape::Rect(rect) => Some(rect.rect),
_ => None,
})
.filter(|rect: &Rect| rect.center().distance(well.center()) < 0.5 && rect.width() < well.width() - 2.0)
.min_by(|a, b| a.area().total_cmp(&b.area()))
.expect("a hole inside the band");
assert!(hole.height() >= well.height() / 3.0, "the hole is {:?} in a {:?} well", hole.size(), well.size());
let (side, top) = (hole.left() - well.left(), hole.top() - well.top());
assert!((side - top).abs() < 0.5, "the band is {side} at the sides and {top} at the top");
}
}
/// A click on the menu mark, past the well, opens the chip's popover, as a click on the well does.
#[trial]
fn a_click_on_the_menu_mark_opens_the_popover() {
+31
View File
@@ -8,7 +8,9 @@ use std::rc::Rc;
use craft_behavior::Mixed;
use craft_color_ui::ui::{PairWell, SwatchPair, SwatchPairOutput, Well};
use craft_theme::{Srgba, ThemeId};
use craft_ui::contract::tooltip::DELAY;
use craft_ui::contract::{Bind, Role, Show as _, ShowContainer as _};
use craft_ui::testing::pointer::moved;
use craft_ui::testing::{Fixture, trial};
use egui::{Key, Modifiers, Rect, Ui, Vec2, vec2};
@@ -118,6 +120,35 @@ fn the_well_corner_follows_the_theme_well_shape() {
assert_eq!(clicks("craft.pro"), [Some(Well::Primary), Some(Well::Primary)], "square wells");
}
/// A rest of the pointer on a well shows the well's label, and one on the Swap or Default button shows that button's
/// label: a host that names a well "Fill (X)" shows its key there.
#[trial]
fn a_rest_on_a_well_or_a_button_shows_its_label() {
let mut fixture = Fixture::new(|ui| {
let wells = [PairWell::new("Fill (X)", Srgba::rgb(0.1, 0.3, 0.8)), PairWell::new("Stroke (X)", Srgba::rgb(1.0, 1.0, 1.0))];
SwatchPair::<()>::new("Fill and Stroke", wells, Bind::given(Well::Primary))
.swap_button("Swap (Shift+X)")
.default_button("Default (D)")
.popover(false)
.show(ui);
});
fixture.room(vec2(200.0, 200.0)).settle();
let wells = fixture.by_role(Role::RADIO_BUTTON);
let swap = fixture.by_label("Swap (Shift+X)").expect("the Swap button").rect.center();
let default = fixture.by_label("Default (D)").expect("the Default button").rect.center();
let spots =
[(in_primary(wells[0].rect), "Fill (X)"), (in_secondary(wells[1].rect), "Stroke (X)"), (swap, "Swap (Shift+X)"), (default, "Default (D)")];
for (at, tip) in spots {
fixture.frame(vec![moved(egui::pos2(199.0, 199.0))]);
fixture.settle();
assert!(!fixture.texts().iter().any(|run| run.text == tip), "no {tip:?} before the rest");
fixture.frame(vec![moved(at)]);
fixture.advance(DELAY);
fixture.settle();
assert!(fixture.texts().iter().any(|run| run.text == tip), "a rest there shows {tip:?}");
}
}
/// A popover that opens with the pair as its first stop puts the focus on the active well, as Tab into the pair does:
/// the arrival makes no other well active (a Color panel opened over the Stroke chip leaves Stroke active).
#[trial]
+315 -4
View File
@@ -7,15 +7,18 @@ use std::rc::Rc;
use craft_behavior::{EditEvent, Mixed, Selection};
use craft_color_ui::palette::{SwatchColor, SwatchGroup};
use craft_color_ui::ui::{
ColorPanel, ColorPanelLayout, ColorPanelMode, ColorPanelShown, ColorPanelState, HarmonyWheel, PanelTarget, PickedColor, SwatchEdit, SwatchKey,
SwatchLibrary, SwatchPalette, SwatchesCommand, SwatchesMenu, SwatchesPanel, SwatchesState, SwatchesWords, swatch_rows,
ColorPanel, ColorPanelLayout, ColorPanelMode, ColorPanelShown, ColorPanelState, HarmonyPanel, HarmonyPanelState, HarmonyPicked, HarmonyWheel,
PanelTarget, PickedColor, SwatchEdit, SwatchKey, SwatchLibrary, SwatchPalette, SwatchesCommand, SwatchesMenu, SwatchesPanel, SwatchesState,
SwatchesWords, swatch_rows,
};
use craft_host::target::Os;
use craft_theme::{ColorModel as _, HsbModel, Srgba};
use craft_ui::buttons::Button;
use craft_ui::choice::SwatchTable;
use craft_ui::contract::Role;
use craft_ui::contract::tooltip::DELAY;
use craft_ui::contract::{Bind, Show as _};
use craft_ui::contract::{Bind, Show as _, ShowContainer as _};
use craft_ui::layout_components::Stack;
use craft_ui::runtime::env::{Label, Scale};
use craft_ui::runtime::requests::ColorRequest;
use craft_ui::testing::focus::AccessActionKind;
@@ -215,6 +218,24 @@ fn a_fill_stroke_panels_warnings_keep_their_room_so_the_spectrum_holds_still() {
assert_eq!(clean, warned, "the spectrum with no warning and with both");
}
/// A host's names for the FillStroke layout's swap and default buttons replace the panel's words, so a host can name
/// its keys there; without them the buttons keep the words.
#[trial]
fn a_fill_stroke_panel_names_its_buttons_as_the_host_asks() {
let names = |given: bool| {
let mut fixture = Fixture::new(move |ui| {
let mut state = ColorPanelState::default();
let panel = ColorPanel::new(Bind::bound(&mut state), [RED, BLUE]).layout(ColorPanelLayout::FillStroke);
let panel = if given { panel.buttons("Swap (Shift+X)", "Default (D)") } else { panel };
let _ = panel.show(ui);
});
fixture.room(COLOR_ROOM).settle();
["Swap (Shift+X)", "Default (D)", "Swap fill and stroke", "Default fill and stroke"].map(|name| fixture.by_label(name).is_some())
};
assert_eq!(names(true), [true, true, false, false], "the host's names");
assert_eq!(names(false), [false, false, true, true], "the panel's words");
}
/// The spectrum's tooltip is the shown mode's name, and a Shift click on it moves the state to the next mode without
/// editing a paint.
#[trial]
@@ -254,6 +275,36 @@ fn the_fill_stroke_spectrums_tooltip_names_the_shown_mode_and_shift_click_cycles
assert!(edits.borrow().is_empty(), "a Shift click picks nothing: {:?}", edits.borrow());
}
/// In a host sized by its content (a floating Color panel) the FillStroke spectrum is as tall as its end boxes stacked,
/// each at least as tall as it is wide, not a thin band; in a short group it keeps that height and the body scrolls.
#[trial]
fn a_fill_stroke_spectrum_keeps_its_end_boxes_square_in_a_content_sized_host() {
for (room, content_sized) in [(COLOR_ROOM, true), (Vec2::new(280.0, 96.0), false)] {
let mut fixture = Fixture::new(move |ui| {
let mut state = ColorPanelState::default();
let show = |ui: &mut egui::Ui, state: &mut ColorPanelState| {
let _ = ColorPanel::new(Bind::bound(state), [RED, BLUE]).layout(ColorPanelLayout::FillStroke).show(ui);
};
if content_sized {
let _ = Stack::new().show(ui, |ui, _| show(ui, &mut state));
} else {
show(ui, &mut state);
}
});
fixture.room(room).settle();
let bar = fixture.by_label("Color Ramp").expect("the spectrum").rect;
let ends: Vec<_> = fixture
.by_role(Role::BUTTON)
.into_iter()
.filter(|button| button.rect.left() >= bar.right() - 0.5 && button.rect.y_range().intersects(bar.y_range()))
.collect();
assert_eq!(ends.len(), 2, "{room:?}: the white and black boxes beside the bar ({bar:?})");
for end in ends {
assert!(end.rect.height() >= end.rect.width() - 0.5, "{room:?}: an end box at least square ({:?} beside {bar:?})", end.rect);
}
}
}
const SWATCHES: [(&str, [f32; 3]); 6] = [
("Red", [0.90, 0.28, 0.30]),
("Orange", [0.97, 0.42, 0.08]),
@@ -328,6 +379,7 @@ struct PaletteReports {
edits: Vec<EditEvent<Srgba>>,
requests: Vec<ColorRequest>,
picked: Vec<Srgba>,
swatches: Vec<usize>,
}
type Reports = Rc<RefCell<PaletteReports>>;
@@ -338,6 +390,7 @@ fn collect(reports: &Reports, shown: craft_color_ui::ui::SwatchPaletteOutput) {
reports.edits.extend(shown.edit);
reports.requests.extend(shown.pick_color);
reports.picked.extend(shown.picked);
reports.swatches.extend(shown.picked_swatch);
}
fn palette_swatches() -> Vec<(Label, Srgba)> {
@@ -385,7 +438,7 @@ fn the_other_cell_files_a_request_at_the_colour_and_a_recent_pick_sets_it() {
let recent = fixture.by_label(&RECENT[0].to_hex()).expect("a recent colour is named by its hex");
fixture.click(&recent).settle();
let taken = std::mem::take(&mut *reports.borrow_mut());
assert!(taken.requests.is_empty(), "a recent pick files no request");
assert!(taken.requests.is_empty() && taken.swatches.is_empty(), "a recent pick is not a palette entry");
assert_eq!(taken.edits.len(), 1, "one edit for one recent pick");
assert!(
matches!(&taken.edits[0], EditEvent::Set { before: Mixed::Same(before), after, .. }
@@ -408,6 +461,69 @@ fn the_other_cell_files_a_request_at_the_colour_and_a_recent_pick_sets_it() {
assert_eq!(taken.picked.iter().map(|c| c.to_rgba()).collect::<Vec<_>>(), [swatch("Violet").to_rgba()], "and still reports the pick");
}
#[trial]
fn a_palette_reports_the_actual_swatch_when_its_color_matches_the_bound_color() {
let color = swatch("Green");
let swatches = [(Label::from("First green"), color), (Label::from("Second green"), color), (Label::from("Third green"), color)];
let selected = Rc::new(Cell::new(2));
let preferred = Rc::clone(&selected);
let reports = Reports::default();
let out = reports.clone();
let mut fixture = Fixture::new(move |ui| {
collect(&out, SwatchPalette::new("Swatches", Bind::given(color), &swatches).selected_swatch(Some(preferred.get())).show(ui));
let _ = Button::new("Next control").show(ui);
});
fixture.room(PALETTE_WIDE).settle();
let third = fixture.by_label("Third green").expect("the linked entry");
assert_eq!(fixture.tree().selected_of(third.node), Some(true), "the linked entry stays selected");
let second = fixture.by_label("Second green").expect("the second entry");
fixture.hold(Modifiers::SHIFT).click(&second).hold(Modifiers::NONE).settle();
let click = std::mem::take(&mut *reports.borrow_mut());
assert_eq!(click.swatches, [1]);
assert_eq!(click.picked.iter().map(|picked| picked.to_rgba()).collect::<Vec<_>>(), [color.to_rgba()]);
assert!(click.edits.is_empty(), "the color binding has not changed");
fixture.key(Key::ArrowRight, Modifiers::NONE).key(Key::Space, Modifiers::NONE).settle();
let keys = std::mem::take(&mut *reports.borrow_mut());
assert_eq!(keys.swatches, [2], "Space picks the already selected swatch");
assert!(keys.edits.is_empty());
let focused = |fixture: &Fixture| {
let tree = fixture.tree();
tree.name_of(craft_ui::testing::access::focused_key(tree)).map(str::to_owned)
};
fixture.key(Key::Tab, Modifiers::NONE).settle();
assert_eq!(focused(&fixture).as_deref(), Some("Next control"));
selected.set(0);
fixture.settle();
fixture.key(Key::Tab, Modifiers::SHIFT).settle();
assert_eq!(focused(&fixture).as_deref(), Some("First green"));
fixture.key(Key::Space, Modifiers::NONE).settle();
assert_eq!(reports.borrow().swatches, [0], "Tab returns to the host's current swatch");
}
/// The FillStroke layout shows its Recent Colors caption while the host's list is empty, as it does with colors in
/// it; a host that gives no recent colors gets no row.
#[trial]
fn a_fill_stroke_panel_shows_its_recent_colors_row_while_the_list_is_empty() {
let caption = |recent: Option<&'static [Srgba]>| {
let mut fixture = Fixture::new(move |ui| {
let mut state = ColorPanelState::default();
let panel = ColorPanel::new(Bind::bound(&mut state), [RED, BLUE]).layout(ColorPanelLayout::FillStroke);
let _ = match recent {
Some(colors) => panel.recent(colors),
None => panel,
}
.show(ui);
});
fixture.room(COLOR_ROOM).settle();
fixture.texts().iter().any(|run| run.text == "Recent Colors")
};
assert!(caption(Some(&[])), "an empty list shows the row's caption");
assert!(caption(Some(&RECENT)), "a list with a color shows it");
assert!(!caption(None), "a host with no recent colors shows no row");
}
/// A palette over a colour that may be none, bound to no colour: no swatch is selected and Tab enters on the first;
/// a click writes `Same(Some(colour))` and reports one `Set` from `Mixed`.
#[trial]
@@ -541,6 +657,78 @@ fn swatches_panel_reports_each_edit_and_leaves_the_library() {
assert_eq!(state.rename, Some(SwatchKey::Swatch("Color Swatch 2".to_owned())), "the new swatch opens for renaming");
}
#[trial]
fn a_mixed_swatches_selection_rejects_reorder_and_deletes_each_entry_once() {
use craft_ui::contract::SelectMode;
let entry = |name: &str, color| craft_color_ui::palette::SwatchEntry::new(name.to_owned(), SwatchColor::Rgb(color));
let groups = vec![
SwatchGroup { name: "Basics".to_owned(), entries: vec![entry("Red", [1.0, 0.0, 0.0])] },
SwatchGroup { name: "Other".to_owned(), entries: vec![entry("Blue", [0.0, 0.0, 1.0])] },
];
let state = Rc::new(RefCell::new(SwatchesState::default()));
let edits = Rc::new(RefCell::new(Vec::new()));
let reorders = Rc::new(Cell::new(0));
let (seen, moves, held) = (edits.clone(), reorders.clone(), state.clone());
let mut fixture = Fixture::new(move |ui| {
let out = SwatchesPanel::new(&groups, Bind::bound(&mut *held.borrow_mut()), RED).select(SelectMode::Multi).select_groups(true).show(ui);
seen.borrow_mut().extend(out.edits);
for event in out.events {
if matches!(event, craft_ui::patterns::presets::PresetEvent::Reorder(_)) {
moves.set(moves.get() + 1);
}
}
});
fixture.room(Vec2::new(320.0, 400.0)).settle();
let group = |name: &str| {
let tree = fixture.tree();
tree.with_role(Role::LIST_BOX_OPTION)
.into_iter()
.find(|&key| tree.name_of(key).is_some_and(|label| label == name || label.starts_with(&format!("{name},"))))
.and_then(|key| fixture.target(key))
.unwrap_or_else(|| panic!("the {name} group"))
};
let basics = group("Basics");
let red = fixture.by_label("Red, #ff0000").expect("the Red swatch");
let blue = fixture.by_label("Blue, #0000ff").expect("the Blue swatch");
let other = group("Other");
fixture.click(&basics).hold(Modifiers::COMMAND).click(&red).click(&blue).hold(Modifiers::NONE).settle();
let keys = [SwatchKey::Group("Basics".to_owned()), SwatchKey::Swatch("Red".to_owned()), SwatchKey::Swatch("Blue".to_owned())];
assert_eq!(state.borrow().selection.items, keys, "the group and swatch keys are selected together");
fixture.drag(&red, other.center() - red.center()).settle();
assert!(edits.borrow().is_empty());
assert_eq!(reorders.get(), 0, "the swatch source refuses a mixed reorder");
fixture.key(Key::Delete, Modifiers::NONE).settle();
let reported = edits.borrow();
assert_eq!(reported.len(), 2, "the group delete already includes Red: {reported:?}");
assert!(reported.contains(&SwatchEdit::DeleteGroup { group: "Basics".to_owned() }));
assert!(reported.contains(&SwatchEdit::delete("Blue".to_owned())));
}
/// A group with an empty name holds the swatches outside every group: they show at the top with no header, so no
/// heading or disclosure button of the panel is left without a name, and a named group keeps its header.
#[trial]
fn swatches_outside_every_group_show_without_a_header() {
let entry = |name: &str, rgb: [f32; 3]| craft_color_ui::palette::SwatchEntry::new(name.to_owned(), SwatchColor::Rgb(rgb));
let groups = vec![
SwatchGroup { name: String::new(), entries: vec![entry("Red", [1.0, 0.0, 0.0]), entry("Blue", [0.0, 0.0, 1.0])] },
SwatchGroup { name: "Other".to_owned(), entries: vec![entry("Green", [0.0, 1.0, 0.0])] },
];
let (fixture, _) = swatches_rig(groups, SwatchesState::default());
let tree = fixture.tree();
let unnamed: Vec<_> = tree
.keys()
.into_iter()
.filter(|&key| matches!(tree.role_of(key), Some(Role::HEADING | Role::BUTTON)))
.filter(|&key| tree.name_of(key).is_none_or(|name| name.is_empty() || name.starts_with(',')))
.map(|key| (tree.role_of(key), tree.name_of(key), tree.bounds_of(key)))
.collect();
assert!(unnamed.is_empty(), "every heading and button is named, starting with a label: {unnamed:?}");
assert!(fixture.by_label("Red, #ff0000").is_some(), "the ungrouped swatches show");
let headings: Vec<_> = tree.with_role(Role::HEADING).into_iter().filter_map(|key| tree.name_of(key)).collect();
assert!(headings.iter().any(|name| name.starts_with("Other")), "a named group keeps its header: {headings:?}");
}
/// Tb-8 (5): a click uses any swatch, as production applied every one: a colour swatch reports its colour, and a
/// gradient, pattern or None swatch reports where it is with no colour, for the host to apply its paint. The panel
/// reported only colour swatches.
@@ -628,6 +816,113 @@ fn a_dragged_swatch_carries_the_hosts_payload_beside_the_panels_own_move() {
assert_eq!(edits.borrow().len(), 1, "a drop outside the panel edits nothing: {:?}", edits.borrow());
}
/// A panel shown for one document after another keeps a rename left open with its document: the other document's
/// swatch of the same name opens no field, and Enter there renames nothing.
#[trial]
fn a_rename_left_open_stays_with_its_document() {
let entry = |name: &str| craft_color_ui::palette::SwatchEntry::new(name.to_owned(), SwatchColor::Rgb([1.0, 0.0, 0.0]));
let groups = vec![SwatchGroup { name: "Basics".to_owned(), entries: vec![entry("Red"), entry("Rose")] }];
let document = Rc::new(Cell::new(1_u32));
let edits = Rc::new(RefCell::new(Vec::new()));
let (shown, seen) = (Rc::clone(&document), Rc::clone(&edits));
let mut state = SwatchesState::default();
let mut fixture = Fixture::new(move |ui| {
let out = SwatchesPanel::new(&groups, Bind::bound(&mut state), RED).document(shown.get()).show(ui);
seen.borrow_mut().extend(out.edits);
});
fixture.room(Vec2::new(320.0, 400.0)).settle();
let red = fixture.by_label("Red, #ff0000").expect("the Red swatch");
fixture.click(&red).key(Key::F2, Modifiers::NONE).type_text("X").settle();
let typed = |fixture: &Fixture, text: &str| {
let tree = fixture.tree();
tree.keys().into_iter().any(|key| tree.value_of(key) == Some(text))
};
assert!(typed(&fixture, "X"), "the rename field is open in the first document");
document.set(2);
fixture.settle();
fixture.type_text("Y").key(Key::Enter, Modifiers::NONE).settle();
assert!(!edits.borrow().iter().any(|edit| matches!(edit, SwatchEdit::Rename { .. })), "nothing is renamed: {:?}", edits.borrow());
}
#[trial]
fn opt_in_reports_only_rejected_swatch_and_group_renames() {
use craft_ui::patterns::presets::{PresetEvent, PresetView};
let entry = |name: &str| craft_color_ui::palette::SwatchEntry::new(name.to_owned(), SwatchColor::Rgb([1.0, 0.0, 0.0]));
let groups = vec![
SwatchGroup { name: "Basics".to_owned(), entries: vec![entry("Red"), entry("Rose")] },
SwatchGroup { name: "Other".to_owned(), entries: Vec::new() },
];
let red = SwatchKey::Swatch("Red".to_owned());
let basics = SwatchKey::Group("Basics".to_owned());
for (opt_in, key, name, accepted) in [
(false, &red, "Rose", false),
(false, &basics, "Other", false),
(true, &red, "Rose", false),
(true, &basics, "Other", false),
(true, &red, " Red ", false),
(true, &red, "Coral", true),
(true, &basics, "Favorites", true),
] {
let mut start = SwatchesState::default();
start.browser.view = PresetView::List;
let state = Rc::new(RefCell::new(start));
let edits = Rc::new(RefCell::new(Vec::new()));
let renames = Rc::new(RefCell::new(Vec::new()));
let (held, seen_edits, seen_renames) = (Rc::clone(&state), Rc::clone(&edits), Rc::clone(&renames));
let groups = groups.clone();
let mut fixture = Fixture::new(move |ui| {
let mut current = held.borrow_mut();
let mut panel = SwatchesPanel::new(&groups, Bind::bound(&mut *current), RED);
if opt_in {
panel = panel.report_invalid_renames(true);
}
let out = panel.show(ui);
seen_edits.borrow_mut().extend(out.edits);
seen_renames.borrow_mut().extend(out.events.into_iter().filter_map(|event| match event {
PresetEvent::Rename { key, text, .. } => Some((key, text)),
_ => None,
}));
});
fixture.room(Vec2::new(320.0, 400.0)).settle();
let label = if key == &red { "Red" } else { "Basics" };
let tree = fixture.tree();
let row = tree
.with_role(Role::TREE_ITEM)
.into_iter()
.find(|&node| tree.name_of(node).is_some_and(|actual| actual == label || actual.starts_with(&format!("{label},"))))
.and_then(|node| fixture.target(node))
.unwrap_or_else(|| {
panic!("the {label} row is shown, names: {:?}", tree.keys().into_iter().filter_map(|key| tree.name_of(key)).collect::<Vec<_>>())
});
fixture.click(&row).key(Key::F2, Modifiers::NONE).type_text(name).settle();
let tree = fixture.tree();
assert!(tree.keys().into_iter().any(|key| tree.value_of(key) == Some(name)), "the rename field shows {name}");
let selection = state.borrow().selection.clone();
fixture.key(Key::Enter, Modifiers::NONE).settle();
let rejected = opt_in && matches!(name, "Rose" | "Other");
if rejected {
assert_eq!(*renames.borrow(), [(key.clone(), name.to_owned())]);
} else {
assert!(renames.borrow().is_empty(), "{name}");
}
if accepted {
let reported = edits.borrow();
assert!(
match &reported[..] {
[SwatchEdit::Rename { swatch, name: new }] => key == &SwatchKey::Swatch(swatch.clone()) && new == name,
[SwatchEdit::RenameGroup { group, name: new }] => key == &SwatchKey::Group(group.clone()) && new == name,
_ => false,
},
"{name}: {reported:?}",
);
} else {
assert!(edits.borrow().is_empty(), "{name}");
assert_eq!(state.borrow().selection, selection, "{name}");
}
}
}
fn table_entries(count: usize) -> Vec<(Label, Srgba)> {
(0..count).map(|i| (Label::from(format!("Index {i}")), Srgba::rgb(i as f32 / count as f32, 0.5, 0.25))).collect()
}
@@ -768,3 +1063,19 @@ fn a_click_on_a_harmony_wheel_marker_reports_it() {
fixture.click(&marker).idle(1);
assert_eq!(clicked.get(), Some(Some(1)), "the click names the second marker");
}
/// The Color Guide's variation end labels sit at the two sides of the grid: Shades at its left edge and Tints at its
/// right edge.
#[trial]
fn the_color_guide_end_labels_sit_at_the_two_sides_of_the_grid() {
let mut fixture = Fixture::new(|ui| {
let (mut state, mut picked) = (HarmonyPanelState::default(), HarmonyPicked::default());
let _ = HarmonyPanel::new(Bind::bound(&mut state), Bind::bound(&mut picked), RED).show(ui);
});
fixture.room(COLOR_ROOM).settle();
let grid = fixture.by_label("Variations").expect("the variations grid").rect;
let run = |text: &str| fixture.texts().iter().find(|run| run.text == text).map(|run| run.rect).unwrap_or_else(|| panic!("{text} is painted"));
let (shades, tints) = (run("Shades"), run("Tints"));
assert!(shades.left() <= grid.left() + 1.0 && shades.right() < grid.center().x, "Shades {shades:?} starts at the left edge of {grid:?}");
assert!(tints.right() >= grid.right() - 1.0 && tints.left() > grid.center().x, "Tints {tints:?} ends at the right edge of {grid:?}");
}
+4
View File
@@ -34,6 +34,10 @@ craft-flags = { workspace = true, optional = true }
dirs = { version = "7", optional = true }
log = { workspace = true, optional = true }
[target.'cfg(windows)'.dependencies]
# The token file, created with an access list of its user and SYSTEM only (MIT OR Apache-2.0, ours).
craft-platform = { workspace = true }
[dev-dependencies]
proptest = { workspace = true }
tempfile = "3"
+268 -119
View File
@@ -101,7 +101,7 @@ impl App {
/// Record `port` as the running app's, readable only by the user like the token files.
pub fn write_current_port(&self, port: u16) -> Result<PathBuf> {
let path = self.current_port_path().ok_or_else(|| Error::new(ErrorKind::NotFound, "no data folder"))?;
self.write_token_file(&path, &port.to_string())?;
self.write_private(&path, &port.to_string(), true)?;
Ok(path)
}
@@ -141,16 +141,27 @@ impl App {
}
/// Write `token` to `path`, readable and writable only by the user: the folder is made `0700`
/// and the file `0600` on Unix; on Windows the file's inherited permissions are replaced by one
/// entry for the user (`icacls`) before the token goes in; when that fails, the still empty file
/// is removed and no token is written. A file left by an earlier launch is replaced. The process
/// file beside it ([`pid_path`]) records this process, best effort.
/// and the file `0600` on Unix; on Windows the file is created with an access list of the user
/// and SYSTEM only and the token is written through the handle that created it
/// (`create_for_user`), so the file never has its folder's access list. A file left by an
/// earlier launch is replaced. The process file beside it ([`pid_path`]) records this process,
/// best effort.
pub fn write_token_file(&self, path: &Path, token: &str) -> Result<()> {
self.write_private(path, token, false)
}
/// [`App::write_token_file`]. `replace`: on Windows, a file another launch put at `path` while
/// this one was being created is replaced (the discovery file, which names the latest launch);
/// otherwise this write fails and that launch's token stays.
fn write_private(&self, path: &Path, token: &str, replace: bool) -> Result<()> {
#[cfg(windows)]
let restrict = |p: &Path| restrict_to_user(p, self.custom_control_dir().is_some());
let create = |p: &Path, contents: &[u8]| create_for_user(p, contents, self.custom_control_dir().is_some(), replace);
#[cfg(not(windows))]
let restrict = |_: &Path| Ok(());
write_token_file_with(path, token, restrict)
let create = {
let _ = replace;
create_new_file
};
write_token_file_with(path, token, create)
}
}
@@ -314,31 +325,18 @@ pub fn tokens_match(a: &str, b: &str) -> bool {
a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
}
/// [`App::write_token_file`], with `restrict` limiting the new file to the user (Windows).
fn write_token_file_with(path: &Path, token: &str, restrict: impl FnOnce(&Path) -> Result<()>) -> Result<()> {
/// [`App::write_token_file`], with `create` making the new file with its contents, readable only
/// by the user.
fn write_token_file_with(path: &Path, token: &str, create: impl FnOnce(&Path, &[u8]) -> Result<()>) -> Result<()> {
let dir = path.parent().ok_or_else(|| Error::new(ErrorKind::InvalidInput, "no folder"))?;
std::fs::create_dir_all(dir)?;
let _ = std::fs::remove_file(path);
let mut opts = std::fs::OpenOptions::new();
opts.write(true).create_new(true);
#[cfg(unix)]
{
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))?;
opts.mode(0o600);
}
let opened = opts.open(path)?;
// On a refusal the file goes with the closure, so it is closed before it is removed.
let mut f = match restrict(path).map(|()| opened) {
Ok(f) => f,
Err(e) => {
let _ = std::fs::remove_file(path);
return Err(e);
}
};
f.write_all(token.as_bytes())?;
f.write_all(b"\n")?;
f.sync_all()?;
create(path, format!("{token}\n").as_bytes())?;
let pid = std::process::id();
let line = process_start(pid).map_or_else(|| format!("{pid}\n"), |start| format!("{pid} {start}\n"));
let _ = std::fs::write(pid_path(path), line);
@@ -369,74 +367,148 @@ fn held_by_another(path: &Path, token: &str) -> bool {
read_token(path).is_some_and(|held| !tokens_match(&held, token.trim()))
}
/// How long `icacls` may take (#6145). It finishes at once; on some computers the new process
/// is left suspended (security software holding it), and waiting on it without a limit froze
/// the app.
#[cfg(windows)]
const ICACLS_LIMIT: std::time::Duration = std::time::Duration::from_secs(5);
/// How a run of `icacls` ended.
#[cfg(any(windows, test))]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum IcaclsEnd {
Succeeded,
Failed,
/// It didn't finish within [`ICACLS_LIMIT`] and was ended.
TimedOut,
/// Create `path`, which must not exist yet, holding `contents`: mode `0600` on Unix. On Windows a
/// file created this way has its folder's access list; the token file there is made by
/// `create_for_user`.
fn create_new_file(path: &Path, contents: &[u8]) -> Result<()> {
let mut opts = std::fs::OpenOptions::new();
opts.write(true).create_new(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
opts.mode(0o600);
}
let mut f = opts.open(path)?;
f.write_all(contents)?;
f.sync_all()
}
/// Whether a token may go into a file after `icacls` ended this way. `custom_folder`: the file is
/// in the folder the app's `CONTROL_DIR` names. A timeout is accepted only in the default folder,
/// the user's own local app data, which other users can't read by default; nothing is known about
/// the permissions of any other folder.
/// How long creating the token file may take on Windows (#6145). It runs `whoami` and PowerShell;
/// on some computers a new process is left suspended (security software holding it), and waiting
/// on it without a limit froze the app.
#[cfg(windows)]
const CREATE_LIMIT: std::time::Duration = std::time::Duration::from_secs(10);
/// Windows: create `path` with the current user as owner and an access list of that user and
/// SYSTEM only, given to Windows in the call that creates the file, with `contents` written
/// through that handle (`craft_platform::owner_only::create_private_file`), then named `path`.
/// Another account never gets a moment in which the file has its folder's access list and could be
/// opened. `custom_folder`: the file is in the folder the app's `CONTROL_DIR` names;
/// [`create_within`] says what it changes when the create takes longer than [`CREATE_LIMIT`], and
/// what `replace` changes.
#[cfg(windows)]
fn create_for_user(path: &Path, contents: &[u8], custom_folder: bool, replace: bool) -> Result<()> {
use craft_platform::owner_only;
/// How many creates that were not waited for are still running.
static STUCK: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
let private = |p: &Path, c: &[u8]| owner_only::current_user_sid().and_then(|me| owner_only::create_private_file(p, &me, c));
create_within(path, contents, custom_folder, replace, CREATE_LIMIT, &STUCK, private).0
}
/// What a create that wasn't waited for gives: in a folder the app's `CONTROL_DIR` names
/// (`custom_folder`) an error of kind [`ErrorKind::TimedOut`], since nothing is known about that
/// folder's permissions; in the default folder, the user's own local app data, which other users
/// can't read by default, `path` created with that folder's access list ([`create_new_file`]).
#[cfg(any(windows, test))]
fn restriction_result(end: IcaclsEnd, custom_folder: bool, path: &Path) -> Result<()> {
match end {
IcaclsEnd::Succeeded => Ok(()),
IcaclsEnd::TimedOut if !custom_folder => Ok(()),
IcaclsEnd::TimedOut => Err(Error::new(ErrorKind::TimedOut, format!("icacls did not finish in time to restrict {}", path.display()))),
IcaclsEnd::Failed => Err(Error::other(format!("icacls failed to restrict {}", path.display()))),
fn not_waited_for(path: &Path, contents: &[u8], custom_folder: bool) -> Result<()> {
if custom_folder {
Err(Error::new(ErrorKind::TimedOut, format!("creating {} for its user only did not finish in time", path.display())))
} else {
create_new_file(path, contents)
}
}
/// Windows: drop inherited entries and grant only the current user full access. An `icacls`
/// that doesn't finish in time is ended, and [`restriction_result`] decides what that means.
#[cfg(windows)]
fn restrict_to_user(path: &Path, custom_folder: bool) -> Result<()> {
use std::os::windows::process::CommandExt;
let user = std::env::var("USERNAME").map_err(|_| Error::other("USERNAME is not set"))?;
let domain = std::env::var("USERDOMAIN").ok().filter(|d| !d.is_empty());
let who = domain.map_or(user.clone(), |d| format!("{d}\\{user}"));
let child = std::process::Command::new("icacls")
.arg(path)
.args(["/inheritance:r", "/grant:r", &format!("{who}:F")])
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.creation_flags(0x0800_0000)
.spawn()?;
let end = match wait_within(child, ICACLS_LIMIT)? {
Some(status) if status.success() => IcaclsEnd::Succeeded,
Some(_) => IcaclsEnd::Failed,
None => IcaclsEnd::TimedOut,
/// Run `private`, which creates a file holding `contents` for the user alone, on a thread of its
/// own, and wait for it at most `limit`. The thread creates a file of its own beside `path`
/// (`.<name>.<process id>.<count>.tmp`), and the file takes the name `path` only once `private`
/// has finished, so `path` never holds a file that is still being written: with `replace` by a
/// rename that replaces a file another launch put there meanwhile, otherwise by [`place_new`],
/// which leaves that file and fails. When `private` fails with [`ErrorKind::TimedOut`] (a tool
/// `craft_platform::owner_only` ended after its own limit), [`not_waited_for`] gives the result.
/// When the thread hasn't finished in time, [`not_waited_for`] gives the result, the thread removes its
/// file whenever it does finish, and `stuck` counts it until then. While `stuck` counts any
/// thread, no other thread is started and [`not_waited_for`] answers at once, so a computer that
/// leaves new processes suspended holds at most the threads that were started together. The
/// thread's handle is returned for tests.
#[cfg(any(windows, test))]
fn create_within(
path: &Path,
contents: &[u8],
custom_folder: bool,
replace: bool,
limit: std::time::Duration,
stuck: &'static std::sync::atomic::AtomicUsize,
private: impl FnOnce(&Path, &[u8]) -> Result<()> + Send + 'static,
) -> (Result<()>, Option<std::thread::JoinHandle<()>>) {
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::mpsc::{RecvTimeoutError, channel};
use std::sync::{Arc, Mutex, PoisonError};
/// Numbers the thread's files within this process.
static COUNT: AtomicU64 = AtomicU64::new(0);
if stuck.load(Ordering::Acquire) > 0 {
return (not_waited_for(path, contents, custom_folder), None);
}
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let staged = path.with_file_name(format!(".{name}.{}.{}.tmp", std::process::id(), COUNT.fetch_add(1, Ordering::Relaxed)));
let (sender, receiver) = channel();
// Set under the lock when the caller stops waiting; the thread reads it under the same lock
// before it reports, so its result is either received or its file is removed.
let abandoned = Arc::new(Mutex::new(false));
let (own_file, owned_contents, flag) = (staged.clone(), contents.to_vec(), Arc::clone(&abandoned));
let spawned = std::thread::Builder::new().name("craft-control-token-file".into()).spawn(move || {
let made = private(&own_file, &owned_contents);
let abandoned = flag.lock().unwrap_or_else(PoisonError::into_inner);
if *abandoned {
let _ = std::fs::remove_file(&own_file);
stuck.fetch_sub(1, Ordering::AcqRel);
} else {
let _ = sender.send(made);
}
});
let handle = match spawned {
Ok(handle) => handle,
Err(e) => return (Err(e), None),
};
restriction_result(end, custom_folder, path)
let made = match receiver.recv_timeout(limit) {
Ok(made) => made,
Err(RecvTimeoutError::Disconnected) => Err(Error::other(format!("the thread creating {} stopped", path.display()))),
Err(RecvTimeoutError::Timeout) => {
let mut abandoned = abandoned.lock().unwrap_or_else(PoisonError::into_inner);
match receiver.try_recv() {
Ok(made) => made,
Err(_) => {
*abandoned = true;
stuck.fetch_add(1, Ordering::AcqRel);
drop(abandoned);
return (not_waited_for(path, contents, custom_folder), Some(handle));
}
}
}
};
let placed = match made {
// `owner_only` ended a tool that ran out of its own time: the same as not waiting.
Err(e) if e.kind() == ErrorKind::TimedOut => not_waited_for(path, contents, custom_folder),
made => made.and_then(|()| if replace { std::fs::rename(&staged, path) } else { place_new(&staged, path) }),
};
let _ = std::fs::remove_file(&staged);
(placed, Some(handle))
}
/// Wait for `child` at most `limit`: its exit status, or `None` (and the child ended) when it
/// hasn't finished by then.
/// Give the finished file `staged` the name `path`, which must not exist yet: a second launch
/// writing the same token file at the same time gets [`ErrorKind::AlreadyExists`], as a
/// `create_new` there would, instead of replacing the first one's token. The new name is a hard
/// link. On a volume without hard links the file is renamed once `path` is found free; there a
/// launch that puts its file at `path` between that check and the rename has it replaced, as std
/// offers no rename that refuses an existing file without `unsafe`. `staged` is left for the
/// caller to remove.
#[cfg(any(windows, test))]
fn wait_within(mut child: std::process::Child, limit: std::time::Duration) -> Result<Option<std::process::ExitStatus>> {
let start = std::time::Instant::now();
loop {
if let Some(status) = child.try_wait()? {
return Ok(Some(status));
fn place_new(staged: &Path, path: &Path) -> Result<()> {
match std::fs::hard_link(staged, path) {
Ok(()) => Ok(()),
Err(e) if e.kind() == ErrorKind::AlreadyExists || std::fs::symlink_metadata(path).is_ok() => {
Err(Error::new(ErrorKind::AlreadyExists, format!("{}: {e}", path.display())))
}
if start.elapsed() >= limit {
// Not waited for afterwards: a suspended process may not end at once.
let _ = child.kill();
return Ok(None);
}
std::thread::sleep(std::time::Duration::from_millis(20));
Err(_) => std::fs::rename(staged, path),
}
}
@@ -456,50 +528,127 @@ mod tests {
/// An app with no data folder and no environment, whose times read `t<seconds>`.
const TEST: App = App { name: "TestCraft", data_dir: || None, env: |_| None, utc: |secs| format!("t{secs}"), default_port: 27878 };
/// #6145: a child that doesn't finish in time is given up on, not waited for forever.
#[cfg(unix)]
/// #6145: a private create that doesn't finish in time doesn't hold the caller up. In a folder
/// the app's `CONTROL_DIR` names, the call fails; in the default folder, the file is created
/// anyway and holds the token. Either way the file the late create makes is removed when it
/// finishes and never takes the token file's name, even when a later write has put a file
/// there. While it runs, the next create starts no thread of its own. A create that finishes in
/// time puts its file in place unless a file already has the name, and one that fails leaves
/// nothing. A create that fails as timed out by itself is taken as one not waited for.
#[test]
fn a_slow_child_is_waited_for_only_so_long() {
use std::time::{Duration, Instant};
let start = Instant::now();
let slow = std::process::Command::new("sleep").arg("30").spawn().unwrap();
assert!(wait_within(slow, Duration::from_millis(200)).unwrap().is_none());
assert!(start.elapsed() < Duration::from_secs(5), "{:?}", start.elapsed());
let quick = std::process::Command::new("true").spawn().unwrap();
assert!(wait_within(quick, Duration::from_secs(5)).unwrap().is_some_and(|s| s.success()));
let failing = std::process::Command::new("false").spawn().unwrap();
assert!(wait_within(failing, Duration::from_secs(5)).unwrap().is_some_and(|s| !s.success()));
}
/// #6145's freeze fix stays in the default folder, the user's own; a folder picked with
/// the app's `CONTROL_DIR` gets no token unless the file was really restricted.
#[test]
fn only_the_default_folder_accepts_an_icacls_that_timed_out() {
let path = Path::new("control/7878.token");
for custom in [false, true] {
assert!(restriction_result(IcaclsEnd::Succeeded, custom, path).is_ok());
assert!(restriction_result(IcaclsEnd::Failed, custom, path).is_err());
fn a_private_create_that_does_not_finish_in_time_is_not_waited_for() {
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::mpsc::channel;
use std::time::Duration;
static STUCK: AtomicUsize = AtomicUsize::new(0);
let dir = std::env::temp_dir().join(format!("craft-control-create-limit-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let names = || {
let mut names: Vec<String> = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect();
names.sort();
names
};
for custom in [true, false] {
let path = dir.join("7878.port");
let (go, wait) = channel::<()>();
let (made, handle) = create_within(&path, b"7878\n", custom, false, Duration::ZERO, &STUCK, move |p, c| {
wait.recv().map_err(Error::other)?;
create_new_file(p, c)
});
assert_eq!(STUCK.load(Ordering::Acquire), 1);
if custom {
assert_eq!(made.unwrap_err().kind(), ErrorKind::TimedOut);
assert!(!path.exists());
let unused = |_: &Path, _: &[u8]| -> Result<()> { panic!("a second thread was started") };
let (again, none) = create_within(&path, b"7878\n", custom, false, Duration::from_secs(600), &STUCK, unused);
assert_eq!(again.unwrap_err().kind(), ErrorKind::TimedOut);
assert!(none.is_none());
// A later write of the same contents, as a retry of the same port would make.
create_new_file(&path, b"7878\n").unwrap();
} else {
made.unwrap();
}
go.send(()).unwrap();
handle.unwrap().join().unwrap();
assert_eq!(STUCK.load(Ordering::Acquire), 0);
assert_eq!(names(), ["7878.port"]);
assert_eq!(read_token(&path).as_deref(), Some("7878"));
std::fs::remove_file(&path).unwrap();
}
assert!(restriction_result(IcaclsEnd::TimedOut, false, path).is_ok());
let e = restriction_result(IcaclsEnd::TimedOut, true, path).unwrap_err();
assert_eq!(e.kind(), ErrorKind::TimedOut);
assert!(e.to_string().contains("7878.token"), "{e}");
let path = dir.join("quick.token");
let (made, handle) = create_within(&path, b"quick\n", true, false, Duration::from_secs(600), &STUCK, create_new_file);
made.unwrap();
handle.unwrap().join().unwrap();
assert_eq!(names(), ["quick.token"]);
assert_eq!(read_token(&path).as_deref(), Some("quick"));
// Another launch's file at the name is kept, as `create_new` keeps it.
let (made, handle) = create_within(&path, b"later\n", true, false, Duration::from_secs(600), &STUCK, create_new_file);
assert_eq!(made.unwrap_err().kind(), ErrorKind::AlreadyExists);
handle.unwrap().join().unwrap();
assert_eq!(names(), ["quick.token"]);
assert_eq!(read_token(&path).as_deref(), Some("quick"));
// With `replace` (the discovery file) the later launch's file takes the name.
let (made, handle) = create_within(&path, b"later\n", true, true, Duration::from_secs(600), &STUCK, create_new_file);
made.unwrap();
handle.unwrap().join().unwrap();
assert_eq!(names(), ["quick.token"]);
assert_eq!(read_token(&path).as_deref(), Some("later"));
let refused = |_: &Path, _: &[u8]| -> Result<()> { Err(Error::other("refused")) };
let (made, handle) = create_within(&dir.join("refused.token"), b"other\n", true, false, Duration::from_secs(600), &STUCK, refused);
assert!(made.is_err());
handle.unwrap().join().unwrap();
assert_eq!(names(), ["quick.token"]);
// A create whose tool was ended after its own limit, within this one, is taken as one
// that was not waited for.
let ended =
|_: &Path, _: &[u8]| -> Result<()> { Err(Error::new(ErrorKind::TimedOut, "powershell.exe did not finish within 10 s and was ended")) };
let path = dir.join("ended.token");
let (made, handle) = create_within(&path, b"ended\n", true, false, Duration::from_secs(600), &STUCK, ended);
assert_eq!(made.unwrap_err().kind(), ErrorKind::TimedOut);
handle.unwrap().join().unwrap();
assert_eq!(names(), ["quick.token"]);
let (made, handle) = create_within(&path, b"ended\n", false, false, Duration::from_secs(600), &STUCK, ended);
made.unwrap();
handle.unwrap().join().unwrap();
assert_eq!(names(), ["ended.token", "quick.token"]);
assert_eq!(read_token(&path).as_deref(), Some("ended"));
assert_eq!(STUCK.load(Ordering::Acquire), 0);
let _ = std::fs::remove_dir_all(&dir);
}
/// A file that couldn't be restricted is removed, empty and with no process file beside it, and
/// the error goes to the caller. A restricted one gets its token.
/// A file that couldn't be created leaves no process file beside it, and the error goes to the
/// caller. A created one gets the token and a newline.
#[test]
fn a_token_file_that_could_not_be_restricted_is_removed() {
let dir = std::env::temp_dir().join(format!("craft-control-restrict-{}", std::process::id()));
fn a_token_file_that_could_not_be_created_leaves_nothing() {
let dir = std::env::temp_dir().join(format!("craft-control-create-{}", std::process::id()));
let path = dir.join("7879.token");
let e = write_token_file_with(&path, "secret-token", |p| {
assert_eq!(std::fs::read(p).unwrap(), b"", "restricted before the token goes in");
restriction_result(IcaclsEnd::TimedOut, true, p)
})
.unwrap_err();
let e = write_token_file_with(&path, "secret-token", |_, _| Err(Error::new(ErrorKind::TimedOut, "refused"))).unwrap_err();
assert_eq!(e.kind(), ErrorKind::TimedOut);
assert!(!path.exists() && !pid_path(&path).exists());
write_token_file_with(&path, "secret-token", |p| restriction_result(IcaclsEnd::TimedOut, false, p)).unwrap();
write_token_file_with(&path, "secret-token", create_new_file).unwrap();
assert_eq!(std::fs::read(&path).unwrap(), b"secret-token\n");
assert!(pid_path(&path).exists());
let _ = std::fs::remove_dir_all(&dir);
}
/// On Windows the token file is its user's alone from the moment it exists: in a folder that
/// lets Users read what is created in it, the file has no entry for Users and no other
/// account's access.
#[cfg(windows)]
#[test]
fn the_token_file_is_private_from_the_start_on_windows() {
use craft_platform::owner_only;
let dir = std::env::temp_dir().join(format!("craft-control-private-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let ok = std::process::Command::new("icacls").arg(&dir).arg("/grant").arg("*S-1-5-32-545:(OI)(CI)R").output().unwrap();
assert!(ok.status.success(), "{}", String::from_utf8_lossy(&ok.stderr));
let path = dir.join("7880.token");
TEST.write_token_file(&path, "secret-token").unwrap();
let sddl = owner_only::sddl_of(&path).unwrap();
assert!(!sddl.contains(";BU)") && !sddl.contains(";S-1-5-32-545)"), "Users must not inherit read access: {sddl}");
assert_eq!(owner_only::foreign_access(&sddl, &owner_only::current_user_sid().unwrap()), None, "{sddl}");
assert_eq!(read_token(&path).as_deref(), Some("secret-token"));
let _ = std::fs::remove_dir_all(&dir);
}
+4
View File
@@ -229,6 +229,7 @@ craft-ppt-binary = { workspace = true, optional = true }
craft-sqlite = { workspace = true, optional = true }
craft-audio-dsp = { workspace = true, optional = true }
craft-sbs = { workspace = true, optional = true }
craft-shared-vec = { workspace = true, optional = true }
craft-ease = { workspace = true, optional = true }
craft-i18n-build = { workspace = true, optional = true }
craft-pbr = { workspace = true, optional = true }
@@ -819,6 +820,9 @@ settings-testing = ["settings", "craft-settings/testing"]
sf2 = ["dep:craft-sf2"]
sf2-test-support = ["sf2", "craft-sf2/test-support"]
shared-vec = ["dep:craft-shared-vec"]
shared-vec-serde = ["shared-vec", "craft-shared-vec/serde"]
sheet = ["dep:craft-sheet"]
shx = ["dep:craft-shx"]
+2
View File
@@ -339,6 +339,8 @@ pub use craft_scraft_format as scraft_format;
pub use craft_settings as settings;
#[cfg(feature = "sf2")]
pub use craft_sf2 as sf2;
#[cfg(feature = "shared-vec")]
pub use craft_shared_vec as shared_vec;
#[cfg(feature = "sheet")]
pub use craft_sheet as sheet;
#[cfg(feature = "shx")]
+1 -1
View File
@@ -6,7 +6,7 @@ use std::path::{Path, PathBuf};
/// Crates the facade leaves out, by directory, with the reason. Everything else under `crates/` is a member.
pub const NOT_IN_FACADE: &[(&str, &str)] = &[
("appkit", "the `unsafe` AppKit observers behind a safe API, used by craft-window"),
("appkit", "the `unsafe` AppKit calls behind a safe API, used by craft-window and craft-dialogs"),
("design-lint", "a lint template and checker for apps' clippy.toml, run from xtask"),
("feature-root", "a build tool: the dependency set tools/cl resolves every local build's features with; never built"),
("fonts-build", "a build-script helper; apps call it from build.rs"),
@@ -62,10 +62,18 @@ fn field_path_in(tokens: proc_macro2::TokenStream, out: &mut Vec<proc_macro2::Sp
}
fn is_cfg_test(attrs: &[Attribute]) -> bool {
attrs.iter().any(|a| {
a.path().is_ident("cfg")
&& matches!(&a.meta, syn::Meta::List(list) if list.tokens.clone().into_iter().any(|t| matches!(t, proc_macro2::TokenTree::Ident(i) if i == "test")))
})
attrs.iter().any(|a| a.path().is_ident("cfg") && a.parse_args::<syn::Meta>().is_ok_and(|m| implies_test(&m)))
}
/// Whether the cfg predicate holds only under `test`: `test` itself, or an `all(..)` with such a predicate in it.
fn implies_test(meta: &syn::Meta) -> bool {
match meta {
syn::Meta::Path(path) => path.is_ident("test"),
syn::Meta::List(list) if list.path.is_ident("all") => list
.parse_args_with(syn::punctuated::Punctuated::<syn::Meta, syn::Token![,]>::parse_terminated)
.is_ok_and(|all| all.iter().any(implies_test)),
_ => false,
}
}
fn names_fs(segments: &[String]) -> bool {
@@ -15,3 +15,10 @@ fn exists(path: &Path) -> bool {
mod tests {
static SEEN: std::sync::Mutex<u32> = std::sync::Mutex::new(0);
}
#[cfg(all(test, feature = "screen-testing"))]
mod counted {
thread_local! {
static READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
}
+5 -4
View File
@@ -31,13 +31,14 @@ serde_json = { workspace = true, optional = true }
rfd = { version = "0.17.2", default-features = false, features = ["xdg-portal"] }
# The file-dialog probe asks the session bus whether the desktop portal offers a file chooser.
# The free-standing Open and Folder panel (`beginWithCompletionHandler:`). rfd and winit already
# use these.
# The free-standing Open and Folder panel (`beginWithCompletionHandler:`), and the Save sheet with a
# Format menu (`beginSheetModalForWindow:completionHandler:`). rfd and winit already use these.
[target.'cfg(target_os = "macos")'.dependencies]
block2 = "0.6.2"
craft-appkit = { workspace = true }
objc2 = { version = "0.6.4", default-features = false, features = ["std"] }
objc2-app-kit = { version = "0.3.2", default-features = false, features = ["std", "block2", "NSApplication", "NSOpenPanel", "NSPanel", "NSResponder", "NSSavePanel", "NSView", "NSWindow"] }
objc2-foundation = { version = "0.3.2", default-features = false, features = ["std", "NSArray", "NSString", "NSURL"] }
objc2-app-kit = { version = "0.3.2", default-features = false, features = ["std", "block2", "NSAccessibilityProtocols", "NSApplication", "NSButton", "NSControl", "NSOpenPanel", "NSPanel", "NSPopUpButton", "NSResponder", "NSSavePanel", "NSText", "NSTextField", "NSView", "NSWindow", "objc2-core-foundation"] }
objc2-foundation = { version = "0.3.2", default-features = false, features = ["std", "NSArray", "NSGeometry", "NSString", "NSURL", "objc2-core-foundation"] }
# The Linux and BSD Save panel asks the desktop portal itself, which reports the file type picked.
# The versions craft-platform already builds (zbus with async-io and blocking-api), so adopting the
+8 -2
View File
@@ -44,7 +44,7 @@ pub type Override = Box<dyn FnMut(&Request) -> Answer>;
pub enum Kind { Open { multiple: bool }, Folder, Save }
pub struct FileDialog { pub kind: Kind, pub title: Option<String>, pub filters: Vec<Filter>,
pub directory: Option<PathBuf>, pub file_name: Option<String> }
pub directory: Option<PathBuf>, pub file_name: Option<String>, pub format_label: Option<String> }
pub struct Filter { pub name: String, pub extensions: Vec<String> }
pub struct Message { pub level: MessageLevel, pub title: String, pub description: String,
pub buttons: MessageButtons }
@@ -66,7 +66,7 @@ impl<T> Dialogs<T> {
```
`FileDialog` has builders: `FileDialog::open().title("Place").filter("Images", &["png", "jpg"])`,
and `open_many`, `folder`, `save`, `directory`, `file_name`.
and `open_many`, `folder`, `save`, `directory`, `file_name`, `format_label`.
In an eframe app:
@@ -127,6 +127,12 @@ they start only with a parent in a running app, and answer `Unavailable` otherwi
before the event loop starts or after it ends (startup and crash messages) stay blocking `rfd`
calls in the app.
A Save that offers two or more file types is a sheet the crate makes itself, with a Format menu
that lists each type by name, the suggested name's type chosen. Choosing a type changes the
extension in the name field, and the answer is `Saved` with the chosen type's index in `filter`.
The menu's label is `FileDialog::format_label`, set from `FilePanels::set_format_label` (English
"Format:" when unset). A Save with one type is rfd's sheet, which has no menu.
## Follow-ups
- Linux portal Save (`org.freedesktop.portal.FileChooser.SaveFile`), so the file type the user
+115
View File
@@ -0,0 +1,115 @@
//! The Format menu of a macOS Save panel with two or more file types: which types it lists, which one is chosen
//! when the panel opens, the name a choice gives the file and the extensions the panel then allows. Plain rules on
//! names and filters, so they are tested on every platform; `macos.rs` shows the menu.
use std::path::Path;
use crate::Filter;
use crate::service::normal;
/// The indices into `filters` of the file types the menu lists, in order: types with an extension other than `*`.
/// Empty when fewer than two remain: the panel then has no menu.
pub(crate) fn entries(filters: &[Filter]) -> Vec<usize> {
let listed: Vec<usize> = filters
.iter()
.enumerate()
.filter(|(_, f)| f.extensions.iter().any(|e| !normal(e).is_empty()) && !f.extensions.iter().any(|e| normal(e) == "*"))
.map(|(at, _)| at)
.collect();
if listed.len() < 2 { Vec::new() } else { listed }
}
/// The menu's item titles for `entries`, one per entry and all different: a pop-up menu keeps one item per title, so
/// a name that repeats gets its extensions after it (`Document (docx)`), and a title that still matches an earlier
/// title or another type's name gets a number after it.
pub(crate) fn titles(filters: &[Filter], entries: &[usize]) -> Vec<String> {
let names: Vec<&str> = entries.iter().map(|&at| filters.get(at).map_or("", |f| f.name.as_str())).collect();
let mut out: Vec<String> = Vec::new();
for (&at, name) in entries.iter().zip(&names) {
let mut base = (*name).to_owned();
if names.iter().filter(|n| *n == name).count() > 1 {
let extensions: Vec<String> = filters.get(at).map(|f| f.extensions.iter().map(|e| normal(e)).collect()).unwrap_or_default();
base = format!("{name} ({})", extensions.join(", "));
}
let taken = |title: &str| out.iter().any(|t| t == title) || (title != *name && names.contains(&title));
let mut title = base.clone();
let mut number = 2;
while taken(&title) {
title = format!("{base} {number}");
number += 1;
}
out.push(title);
}
out
}
/// The file type a Save answer reports, as an index into `filters`: the one chosen in the menu (menu position
/// `chosen`), unless the name the panel returned ends in an extension that only another listed type has: the user
/// typed it, and the file is saved in that type. `kept` is the name the field still showed when the last choice could
/// not rename it. A returned name equal to it that still has the extension of the name the panel opened with
/// (`opened_with`) keeps the chosen type: the save flow gives a name with the opened extension the chosen type's
/// extension (`with_chosen_type`). Any other extension stays on the name, so the type reported is the one the name has.
pub(crate) fn answered_type(
returned: &str,
kept: Option<&str>,
opened_with: Option<&str>,
filters: &[Filter],
entries: &[usize],
chosen: usize,
) -> Option<usize> {
let chosen = entries.get(chosen).copied()?;
let Some(ext) = extension(returned) else { return Some(chosen) };
let kept_opened = kept == Some(returned) && opened_with.and_then(extension).as_ref() == Some(&ext);
if filters.get(chosen).is_some_and(|f| lists(f, &ext)) || kept_opened {
return Some(chosen);
}
Some(entries.iter().copied().find(|&at| filters.get(at).is_some_and(|f| lists(f, &ext))).unwrap_or(chosen))
}
/// The menu position chosen when the panel opens: the type whose extensions include `name`'s, else the first.
pub(crate) fn initial(name: &str, filters: &[Filter], entries: &[usize]) -> usize {
let Some(ext) = extension(name) else { return 0 };
entries.iter().position(|&at| filters.get(at).is_some_and(|f| lists(f, &ext))).unwrap_or(0)
}
/// The name the panel shows once `chosen` is picked: an extension `chosen` lists stays; one that another of
/// `filters` lists becomes `chosen`'s first; any other is part of the name (`art.v2`), and `chosen`'s first extension
/// is added after it. An empty name stays empty.
pub(crate) fn renamed(name: &str, chosen: &Filter, filters: &[Filter]) -> String {
let Some(first) = chosen.extensions.iter().map(|e| normal(e)).find(|e| !e.is_empty()) else { return name.to_owned() };
if name.is_empty() {
return String::new();
}
match extension(name) {
Some(ext) if lists(chosen, &ext) => name.to_owned(),
Some(ext) if filters.iter().any(|f| lists(f, &ext)) => Path::new(name).with_extension(first).to_string_lossy().into_owned(),
_ => format!("{name}.{first}"),
}
}
/// The extensions the panel allows with menu position `selected` chosen: that type's first, so that AppKit adds it
/// to a name typed without one, then the other listed types', so that a name typed with one of theirs is kept.
pub(crate) fn allowed(filters: &[Filter], entries: &[usize], selected: usize) -> Vec<String> {
let chosen = entries.get(selected).copied();
let order = chosen.into_iter().chain(entries.iter().copied().filter(|&at| Some(at) != chosen));
let mut out: Vec<String> = Vec::new();
for ext in order.filter_map(|at| filters.get(at)).flat_map(|f| f.extensions.iter().map(|e| normal(e))) {
if !ext.is_empty() && !out.contains(&ext) {
out.push(ext);
}
}
out
}
/// `name`'s extension as compared, if it has one.
fn extension(name: &str) -> Option<String> {
Path::new(name).extension().and_then(|e| e.to_str()).map(normal)
}
/// Whether `filter` lists `ext` (already [`normal`]).
fn lists(filter: &Filter, ext: &str) -> bool {
filter.extensions.iter().any(|e| normal(e) == ext)
}
#[cfg(test)]
pub(crate) mod tests;
+110
View File
@@ -0,0 +1,110 @@
use super::*;
use craft_ui::testing::trial;
fn filters() -> Vec<Filter> {
vec![Filter::new("Document", &["doc"]), Filter::new("Drawing", &["ai"]), Filter::new("Picture", &["jpg", "jpeg"])]
}
/// The menu lists the types with an extension; "every file" types and ones without an extension stay out, and a
/// panel left with one type gets no menu.
#[trial]
fn the_menu_lists_types_with_extensions_and_needs_two() {
assert_eq!(entries(&filters()), [0, 1, 2]);
let mixed = [Filter::new("Document", &["doc"]), Filter::new("All files", &["*"]), Filter::new("Any", &[]), Filter::new("Drawing", &[".ai"])];
assert_eq!(entries(&mixed), [0, 3], "the dot is not part of the extension");
assert!(entries(&[Filter::new("Document", &["doc"]), Filter::new("All files", &["*"])]).is_empty());
assert!(entries(&[]).is_empty());
}
/// Two types with one name both stay in the menu, under different titles; other titles are the names.
#[trial]
fn types_that_share_a_name_get_different_titles() {
let twice = [Filter::new("Document", &["doc"]), Filter::new("Document", &["docx"]), Filter::new("Drawing", &["ai"])];
let listed = entries(&twice);
assert_eq!(listed, [0, 1, 2]);
let shown = titles(&twice, &listed);
assert_eq!(shown.len(), listed.len());
assert!(shown.iter().enumerate().all(|(i, t)| !shown[..i].contains(t)), "{shown:?}");
assert_eq!(shown[2], "Drawing");
for set in [
vec![Filter::new("Document", &["doc"]), Filter::new("Document", &["doc"])],
vec![Filter::new("X (x) 2", &["a"]), Filter::new("X", &["x"]), Filter::new("X", &["x"])],
vec![Filter::new("X", &["x"]), Filter::new("X", &["x"]), Filter::new("X (x) 2", &["a"]), Filter::new("X (x)", &["b"])],
] {
let shown = titles(&set, &entries(&set));
assert_eq!(shown.len(), set.len());
assert!(shown.iter().enumerate().all(|(i, t)| !shown[..i].contains(t)), "{shown:?}");
}
}
/// The answer reports the chosen type, unless the user typed another listed type's extension; a name the panel kept
/// when a choice could not rename it keeps the chosen type.
#[trial]
fn a_typed_extension_of_another_type_is_the_type_saved() {
let all = filters();
let listed = entries(&all);
let (kept, opened) = (Some("Untitled-1.doc"), Some("Untitled-1.doc"));
let answer = |returned, kept| answered_type(returned, kept, opened, &all, &listed, 1);
assert_eq!(answer("Untitled-1.ai", None), Some(1));
assert_eq!(answer("Untitled-1.doc", kept), Some(1), "the panel kept the opened name");
assert_eq!(answer("Other.doc", kept), Some(0), "the user typed a new name after that");
assert_eq!(answer("Untitled-1.doc", None), Some(0), "the user typed the first type's extension back");
assert_eq!(answer("photo.JPEG", kept), Some(2), "the user typed another type's extension");
assert_eq!(answer("Other.doc", Some("Other.doc")), Some(1), "a kept name with the opened extension");
assert_eq!(answer("Other.jpg", Some("Other.jpg")), Some(2), "a kept name with another type's extension keeps that type");
assert_eq!(answer("notes.v2", None), Some(1));
assert_eq!(answer("art", None), Some(1));
assert_eq!(answered_type("art.ai", None, opened, &all, &listed, 9), None, "a position the menu doesn't have");
}
#[trial]
fn the_suggested_name_chooses_its_type_and_any_other_the_first() {
let all = filters();
let listed = entries(&all);
for (name, at) in [("Untitled-1.doc", 0), ("art.AI", 1), ("photo.jpeg", 2), ("Untitled-1", 0), ("notes.v2", 0), ("", 0)] {
assert_eq!(initial(name, &all, &listed), at, "{name}");
}
}
/// Choosing a type replaces the extension of another listed type, keeps one of its own and adds its own after any
/// other dot in the name.
#[trial]
fn choosing_a_type_gives_the_name_its_extension() {
let all = filters();
let drawing = &all[1];
for (name, expected) in [
("Untitled-1.doc", "Untitled-1.ai"),
("Plan 1.DOC", "Plan 1.ai"),
("photo.jpeg", "photo.ai"),
("art.ai", "art.ai"),
("art.AI", "art.AI"),
("art", "art.ai"),
("art.v2", "art.v2.ai"),
("", ""),
] {
assert_eq!(renamed(name, drawing, &all), expected, "{name}");
}
assert_eq!(renamed("photo.jpeg", &all[2], &all), "photo.jpeg", "a second extension of the chosen type stays");
}
/// A sequence of choices (A to B to C) ends with C's extension, and back to A gives A's.
#[trial]
fn each_choice_follows_the_previous_one() {
let all = filters();
let mut name = "Untitled-1.doc".to_owned();
for (at, ext) in [(1, "ai"), (2, "jpg"), (0, "doc")] {
name = renamed(&name, &all[at], &all);
assert_eq!(Path::new(&name).extension().and_then(|e| e.to_str()), Some(ext));
assert_eq!(Path::new(&name).file_stem().and_then(|e| e.to_str()), Some("Untitled-1"));
}
}
/// The chosen type's extension comes first, so AppKit adds it to a bare name; the others stay allowed.
#[trial]
fn the_chosen_type_is_allowed_first() {
let all = filters();
let listed = entries(&all);
assert_eq!(allowed(&all, &listed, 0), ["doc", "ai", "jpg", "jpeg"]);
assert_eq!(allowed(&all, &listed, 1), ["ai", "doc", "jpg", "jpeg"]);
assert_eq!(allowed(&all, &listed, 2), ["jpg", "jpeg", "doc", "ai"]);
}
Loaded 100 of 613 files, more files were not shown because too many files have changed in this diff. Show more