Merge main into ci/pbr-feature-tests

This commit is contained in:
dotCooCoo committed 2026-11-26 19:46:50 -08:00
commit 9b681ebd3e
349 files changed
+11130 -1144

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/pbr.yml': []
'.github/workflows/pcraft-format.yml':
- 'actions/checkout@v7.0.1'
+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/**"
+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"]
-27
View File
@@ -33,30 +33,3 @@ jobs:
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",
@@ -4085,6 +4089,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"
@@ -4204,6 +4218,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>" }`
+1
View File
@@ -388,6 +388,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
}
+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})),
+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);
}
}
+28 -7
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,
@@ -213,8 +216,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 +227,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))
});
@@ -326,6 +333,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);
+29
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)]);
+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
@@ -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);
}
+6 -5
View File
@@ -448,7 +448,7 @@ pub struct ColorPanel<'a> {
wells: Option<([PairWell; 2], Bind<'a, Well>)>,
edited: Option<Option<PickedColor>>,
shown: Option<ColorPanelShown>,
recent: &'a [Srgba],
recent: Option<&'a [Srgba]>,
recent_setup: Option<RecentSetup>,
gamut: Option<Gamut<'a>>,
}
@@ -471,7 +471,7 @@ struct Inputs<'a> {
wells: Option<&'a [PairWell; 2]>,
edited: Option<&'a Option<PickedColor>>,
shown: &'a ColorPanelShown,
recent: &'a [Srgba],
recent: Option<&'a [Srgba]>,
recent_setup: Option<&'a RecentSetup>,
}
@@ -488,7 +488,7 @@ impl<'a> ColorPanel<'a> {
wells: None,
edited: None,
shown: None,
recent: &[],
recent: None,
recent_setup: None,
gamut: None,
}
@@ -541,9 +541,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
}
+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()
}
+57 -10
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;
@@ -641,17 +660,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 +702,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() {
+20 -2
View File
@@ -18,7 +18,7 @@ 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::menu::event_edits;
@@ -77,6 +77,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)]
@@ -96,6 +98,7 @@ pub struct SwatchesPanel<'a> {
takes_drop: Option<DropMaker<'a>>,
payloads: Vec<PayloadAdder<'a>>,
row_items: Option<RowItemsFn<'a>>,
document: Option<IdSalt>,
}
/// What the body decided; `show` stores the state and reports the rest after the real run.
@@ -126,6 +129,7 @@ impl<'a> SwatchesPanel<'a> {
takes_drop: None,
payloads: Vec::new(),
row_items: None,
document: None,
}
}
@@ -216,6 +220,14 @@ 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
}
/// Draws the panel and returns the user's actions this pass.
pub fn show(self, ui: &mut Ui) -> SwatchesPanelOutput {
let SwatchesPanel {
@@ -234,12 +246,15 @@ impl<'a> SwatchesPanel<'a> {
takes_drop,
payloads,
row_items,
document,
} = 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()
@@ -267,6 +282,9 @@ impl<'a> SwatchesPanel<'a> {
.select(select)
.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);
}
+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.
+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() {
+125 -3
View File
@@ -7,15 +7,17 @@ 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::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;
@@ -254,6 +256,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]),
@@ -408,6 +440,28 @@ 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");
}
/// 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 +595,30 @@ 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");
}
/// 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 +706,34 @@ 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());
}
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 +874,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"]);
}
+16 -2
View File
@@ -20,6 +20,8 @@
#![warn(missing_docs)]
mod filter;
#[cfg(any(target_os = "macos", test))]
mod format_menu;
mod native;
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
pub(crate) mod portal;
@@ -92,12 +94,18 @@ pub struct FileDialog {
pub directory: Option<PathBuf>,
/// The file name a Save dialog suggests.
pub file_name: Option<String>,
/// The label of the file type menu a macOS Save panel with two or more file types shows; `None` shows
/// [`FORMAT_LABEL`]. Other platforms' dialogs label their menu themselves.
pub format_label: Option<String>,
}
/// The English label of the macOS Save panel's file type menu.
pub const FORMAT_LABEL: &str = "Format:";
impl FileDialog {
/// A dialog of `kind` with nothing else set.
pub fn new(kind: Kind) -> Self {
Self { kind, title: None, filters: Vec::new(), directory: None, file_name: None }
Self { kind, title: None, filters: Vec::new(), directory: None, file_name: None, format_label: None }
}
/// Choose one existing file.
@@ -143,6 +151,12 @@ impl FileDialog {
self.file_name = Some(file_name.into());
self
}
/// Sets the label of the macOS Save panel's file type menu, in the app's language.
pub fn format_label(mut self, label: impl Into<String>) -> Self {
self.format_label = Some(label.into());
self
}
}
/// The icon a message box shows.
@@ -223,7 +237,7 @@ pub enum Answer {
/// The chosen files or folder.
Paths(Vec<PathBuf>),
/// A Save panel's answer: the name as typed and the file type picked, when the panel reports it (the portal's
/// current filter; rfd reports `None`).
/// current filter, or the macOS panel's Format menu; rfd reports `None`).
Saved {
/// The name as typed.
path: PathBuf,
+142 -8
View File
@@ -6,22 +6,29 @@
//! rfd can't show this panel: its async dialogs always begin a sheet, on the main or first window
//! when no parent is given (rfd 0.17.2 `backend/macos/modal_future.rs:71-102`).
//!
//! Save and message boxes are sheets on the parent window through rfd, as native apps show them.
//! rfd falls back to the blocking `runModal` when the app isn't running or has no window
//! (`modal_future.rs:79-118`), so [`sheet_parent`] lets a sheet start only with a parent in a
//! Save and message boxes are sheets on the parent window, as native apps show them. A Save that
//! offers two or more file types is a sheet made here ([`show_save_sheet`]), with a Format menu:
//! rfd's Save panel lists the extensions of every type and has no menu to choose one
//! (rfd 0.17.2 `backend/macos/file_dialog/panel_ffi.rs:107-120`). Other Saves and message boxes
//! are rfd's sheets. rfd falls back to the blocking `runModal` when the app isn't running or has no
//! window (`modal_future.rs:79-118`), so [`sheet_parent`] lets a sheet start only with a parent in a
//! running app.
use std::cell::Cell;
use std::cell::{Cell, RefCell};
use std::ffi::c_void;
use std::rc::Rc;
use block2::RcBlock;
use objc2::MainThreadMarker;
use objc2::rc::Retained;
use objc2_app_kit::{NSApplication, NSModalResponse, NSModalResponseOK, NSOpenPanel, NSView};
use objc2_foundation::{NSArray, NSString, NSURL};
use objc2::MainThreadOnly;
use objc2::rc::{Retained, Weak};
use objc2_app_kit::{
NSAccessibility, NSApplication, NSModalResponse, NSModalResponseOK, NSOpenPanel, NSPopUpButton, NSSavePanel, NSTextField, NSView, NSWindow,
};
use objc2_foundation::{NSArray, NSPoint, NSRect, NSSize, NSString, NSURL};
use raw_window_handle::{HasWindowHandle, RawWindowHandle};
use crate::{Answer, FileDialog, Kind, Reply};
use crate::{Answer, FORMAT_LABEL, FileDialog, Filter, Kind, Reply, format_menu};
const NOT_MAIN: &str = "dialogs show from the main thread only";
const NOT_RUNNING: &str = "the app isn't running yet, so the dialog can't be shown";
@@ -62,6 +69,133 @@ fn contains(root: &NSView, view: *const c_void) -> bool {
std::ptr::eq((root as *const NSView).cast(), view) || root.subviews().iter().any(|child| contains(&child, view))
}
/// The app's window that `parent`'s view is in.
fn window_of<W: HasWindowHandle>(mtm: MainThreadMarker, parent: &W) -> Option<Retained<NSWindow>> {
let view = match parent.window_handle().map(|h| h.as_raw()) {
Ok(RawWindowHandle::AppKit(h)) => h.ns_view.as_ptr().cast_const(),
_ => return None,
};
NSApplication::sharedApplication(mtm).windows().iter().find(|window| window.contentView().is_some_and(|content| contains(&content, view)))
}
/// The Format menu's height and the room around and between its label and menu, in points.
const ACCESSORY_HEIGHT: f64 = 38.0;
const MARGIN: f64 = 12.0;
const GAP: f64 = 8.0;
/// The Format menu's size, in points.
const MENU: NSSize = NSSize::new(260.0, 26.0);
/// Shows a Save sheet with a Format menu on `parent` (a [`sheet_parent`]) when `d` offers two or more file types
/// ([`format_menu::entries`]), and answers through `reply` with the type chosen in the menu. Choosing a type puts the
/// type's extensions first in the allowed types, which AppKit adds to a name typed without one, and sets the name
/// field to [`format_menu::renamed`]. The SDK's `NSSavePanel.h` says the name field can only be set while the panel is
/// configured; macOS 27.2 shows the new name. Where a system keeps the suggested name, the answer's `filter` still names the chosen
/// type, so the save flow settles the extension (`ExtensionPolicy::picked_type`, or the app's own rule) and asks
/// before replacing a file the panel did not ask about; a kept name with another extension reports that extension's
/// type ([`format_menu::answered_type`]). Gives `reply` back when `d` offers fewer types, for rfd's panel.
///
/// The menu is the panel's accessory view, set before `beginSheetModalForWindow:completionHandler:` shows the sheet:
/// an accessory set after the sheet began made macOS dismiss the sheet at once (storytold/vectorcraft#1800). The
/// completion handler holds the panel, the menu and the menu's target until the sheet closes; the target holds the
/// panel weakly.
pub(crate) fn show_save_sheet<W: HasWindowHandle>(d: &FileDialog, parent: &W, reply: Reply) -> Result<(), Reply> {
let entries = format_menu::entries(&d.filters);
if entries.is_empty() {
return Err(reply);
}
let Some(mtm) = MainThreadMarker::new() else { return Err(reply) };
let Some(window) = window_of(mtm, parent) else { return Err(reply) };
let Some(panel) = craft_appkit::save_panel::new_save_panel(mtm) else {
reply.send(Answer::Unavailable("macOS returned no Save panel".into()));
return Ok(());
};
let name = d.file_name.clone().unwrap_or_default();
let selected = format_menu::initial(&name, &d.filters, &entries);
set_allowed_types(&panel, &d.filters, &entries, selected);
if let Some(title) = &d.title {
panel.setMessage(Some(&NSString::from_str(title)));
}
if let Some(directory) = d.directory.as_deref().and_then(NSURL::from_directory_path) {
panel.setDirectoryURL(Some(&directory));
}
panel.setExtensionHidden(false);
if !name.is_empty() {
panel.setNameFieldStringValue(&NSString::from_str(&name));
}
let label = d.format_label.as_deref().unwrap_or(FORMAT_LABEL);
let (accessory, popup) = accessory(mtm, label, &d.filters, &entries, selected);
panel.setAccessoryView(Some(&accessory));
// The name the field kept when the last choice could not rename it.
let kept: Rc<RefCell<Option<String>>> = Rc::default();
let (filters, listed, weak, kept_by_choice) = (d.filters.clone(), entries.clone(), Weak::new(&*panel), kept.clone());
let choice = craft_appkit::save_panel::on_choose(mtm, &popup, move |at| {
let (Some(panel), Some(chosen)) = (weak.load(), listed.get(at).and_then(|&i| filters.get(i))) else { return };
set_allowed_types(&panel, &filters, &listed, at);
let name = panel.nameFieldStringValue().to_string();
let new_name = format_menu::renamed(&name, chosen, &filters);
panel.setNameFieldStringValue(&NSString::from_str(&new_name));
let shown = panel.nameFieldStringValue().to_string();
*kept_by_choice.borrow_mut() = (shown != new_name).then_some(shown);
});
let reply = Cell::new(Some(reply));
let answered = panel.clone();
let (filters, opened_with) = (d.filters.clone(), d.file_name.clone());
let handler = RcBlock::new(move |response: NSModalResponse| {
// The menu sends its action to `choice` while the sheet is open; the handler keeps it until then.
let _target = &choice;
let Some(reply) = reply.take() else { return };
if response != NSModalResponseOK {
return reply.send(Answer::Cancelled);
}
let Some(path) = answered.URL().and_then(|url| url.to_file_path()) else { return reply.send(Answer::Cancelled) };
let returned = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let filter = usize::try_from(popup.indexOfSelectedItem())
.ok()
.and_then(|at| format_menu::answered_type(&returned, kept.borrow().as_deref(), opened_with.as_deref(), &filters, &entries, at));
reply.send(Answer::Saved { path, filter });
});
panel.beginSheetModalForWindow_completionHandler(&window, &handler);
Ok(())
}
/// Sets `panel`'s allowed file types to [`format_menu::allowed`].
fn set_allowed_types(panel: &NSSavePanel, filters: &[Filter], entries: &[usize], selected: usize) {
let types: Vec<Retained<NSString>> = format_menu::allowed(filters, entries, selected).iter().map(|e| NSString::from_str(e)).collect();
// As rfd does, and as `show_panel` does for Open.
#[allow(deprecated)]
panel.setAllowedFileTypes(Some(&NSArray::from_retained_slice(&types)));
}
/// The label and the Format menu of `filters`' `entries`, `selected` chosen, in a view for the panel's accessory.
fn accessory(
mtm: MainThreadMarker,
text: &str,
filters: &[Filter],
entries: &[usize],
selected: usize,
) -> (Retained<NSView>, Retained<NSPopUpButton>) {
let label = NSTextField::labelWithString(&NSString::from_str(text), mtm);
label.sizeToFit();
let size = label.frame().size;
label.setFrameOrigin(NSPoint::new(MARGIN, (ACCESSORY_HEIGHT - size.height) / 2.0));
let x = MARGIN + size.width + GAP;
let frame = NSRect::new(NSPoint::new(x, (ACCESSORY_HEIGHT - MENU.height) / 2.0), MENU);
let popup = NSPopUpButton::initWithFrame_pullsDown(NSPopUpButton::alloc(mtm), frame, false);
// The label beside the menu is not tied to it for VoiceOver, so the menu carries the label's words as its name.
popup.setAccessibilityLabel(Some(&NSString::from_str(text.trim_end_matches([':', ':']))));
for title in format_menu::titles(filters, entries) {
popup.addItemWithTitle(&NSString::from_str(&title));
}
if let Ok(index) = isize::try_from(selected) {
popup.selectItemAtIndex(index);
}
let view = NSView::initWithFrame(NSView::alloc(mtm), NSRect::new(NSPoint::ZERO, NSSize::new(x + MENU.width + MARGIN, ACCESSORY_HEIGHT)));
view.addSubview(&label);
view.addSubview(&popup);
(view, popup)
}
/// Shows an Open or Folder panel that doesn't block the window and answers through `reply` when
/// it closes. AppKit calls the completion handler on the main thread.
pub(crate) fn show_panel(d: &FileDialog, reply: Reply) -> Option<Panel> {
+5 -2
View File
@@ -63,10 +63,13 @@ pub(crate) fn show<W: HasWindowHandle + HasDisplayHandle>(request: Request, pare
fn show_file<W: HasWindowHandle + HasDisplayHandle>(d: FileDialog, parent: Option<&W>, reply: Reply) -> Shown {
#[cfg(target_os = "macos")]
let parent = match d.kind {
let (parent, reply) = match d.kind {
Kind::Open { .. } | Kind::Folder => return Shown { panel: crate::macos::show_panel(&d, reply) },
Kind::Save => match crate::macos::sheet_parent(parent) {
Ok(parent) => Some(parent),
Ok(parent) => match crate::macos::show_save_sheet(&d, parent, reply) {
Ok(()) => return Shown::default(),
Err(reply) => (Some(parent), reply),
},
Err(why) => {
reply.send(Answer::Unavailable(why));
return Shown::default();
+13 -4
View File
@@ -190,10 +190,7 @@ fn saved(results: &HashMap<String, OwnedValue>) -> Result<Saved, String> {
.map_err(|e: zbus::zvariant::Error| e.to_string())?;
let uri = uris.first().ok_or("no file in the portal's answer")?;
let path = file_uri_path(uri).ok_or_else(|| format!("not a local file: {uri}"))?;
let filter = results.get("current_filter").and_then(|v| {
let (label, _globs): (String, Vec<(u32, String)>) = v.try_clone().ok()?.try_into().ok()?;
Some(label)
});
let filter = results.get("current_filter").and_then(|v| filter_label(v));
Ok(Saved { path, filter })
}
@@ -309,6 +306,18 @@ fn options<'a>(req: &'a SaveRequest, token: &'a str) -> HashMap<&'static str, Va
o
}
/// The label of a file type as the portal sends it, a `(sa(us))` structure; `None` for a value of
/// another shape.
fn filter_label(value: &Value<'_>) -> Option<String> {
match value {
Value::Structure(s) => match s.fields() {
[Value::Str(label), Value::Array(globs)] if globs.element_signature() == "(us)" => Some(label.to_string()),
_ => None,
},
_ => None,
}
}
/// `file:///home/me/A%20b.psd` → `/home/me/A b.psd`; `None` for other schemes.
// pc: apps/photocraft/src/portal_save.rs:134 file_uri_path
fn file_uri_path(uri: &str) -> Option<PathBuf> {
+42
View File
@@ -27,3 +27,45 @@ fn file_uris_become_local_paths() {
assert_eq!(file_uri_path("sftp://host/x.png"), None);
assert_eq!(file_uri_path("file://host/x.png"), None);
}
/// A `current_filter` of another shape than `(sa(us))` (a structure with fewer, other or more fields, a string)
/// gives the path alone; `uris` of another shape is an error.
#[trial]
fn an_answer_of_another_shape_is_not_read() {
let answer_with = |uris: Value<'_>, filter: Option<Value<'_>>| {
let mut r = HashMap::new();
r.insert("uris".to_string(), OwnedValue::try_from(uris).unwrap());
if let Some(filter) = filter {
r.insert("current_filter".to_string(), OwnedValue::try_from(filter).unwrap());
}
saved(&r)
};
let card = || Value::from(vec!["file:///tmp/card".to_string()]);
let malformed = [
Value::from(("PNG".to_string(),)),
Value::from(("PNG".to_string(), vec![(0u32,)])),
Value::from(("PNG".to_string(), vec![("*.png".to_string(), 0u32)])),
Value::from((1u32, vec![(0u32, "*.png".to_string())])),
Value::from(("PNG".to_string(), vec![(0u32, "*.png".to_string())], 1u32)),
Value::from("PNG"),
];
for filter in malformed {
let shape = filter.value_signature().to_string();
assert_eq!(answer_with(card(), Some(filter)), Ok(Saved { path: "/tmp/card".into(), filter: None }), "{shape}");
}
// The shape the portal defines is still read, and so is the one `options` sends.
let png = Value::from(("PNG".to_string(), vec![(0u32, "*.png".to_string())]));
assert_eq!(answer_with(card(), Some(png)), Ok(Saved { path: "/tmp/card".into(), filter: Some("PNG".into()) }));
let sent = Value::from(wire(&Filter::new("Photoshop", &["psd", "psb"])));
assert_eq!(filter_label(&sent), Some("Photoshop".into()));
let malformed = [
Value::from(vec![1u32]),
Value::from(vec![("file:///tmp/card".to_string(),)]),
Value::from(Vec::<String>::new()),
Value::from("file:///tmp/card"),
];
for uris in malformed {
let shape = uris.value_signature().to_string();
assert!(answer_with(uris, None).is_err(), "{shape}");
}
}
+10
View File
@@ -276,6 +276,8 @@ pub struct FilePanels {
extension_policy: ExtensionPolicy,
replace_guard: ReplaceGuard,
replace_words: ReplaceWords,
/// The label of the macOS Save panel's file type menu; `None` shows [`crate::FORMAT_LABEL`].
format_label: Option<String>,
/// Why no file dialog can open on this system, when the probe knows.
backend_problem: fn() -> Option<String>,
/// The replace questions [`pump_with`](FilePanels::pump_with) put on the app's dialog host.
@@ -325,6 +327,7 @@ impl FileService {
extension_policy: ExtensionPolicy::default(),
replace_guard: ReplaceGuard::default(),
replace_words: ReplaceWords::default(),
format_label: None,
backend_problem: probe::known_problem,
#[cfg(feature = "ui")]
prompts: Vec::new(),
@@ -393,6 +396,12 @@ impl FilePanels {
self.replace_words = words;
}
/// The label of the file type menu on a macOS Save panel that offers two or more types ("Format:" in English);
/// the app sets it again when the language changes.
pub fn set_format_label(&mut self, label: impl Into<String>) {
self.format_label = Some(label.into());
}
/// [`extension_policy`](FilePanels::extension_policy) on panels the app already keeps, for a
/// preference that changes while the app runs.
pub fn set_extension_policy(&mut self, policy: ExtensionPolicy) {
@@ -647,6 +656,7 @@ impl FilePanels {
if request.kind == PickKind::Save {
let adds_extension = cfg!(windows) && !request.filters.is_empty();
dialog.file_name = request.file_name.as_deref().and_then(|name| dialog_file_name(name, adds_extension));
dialog.format_label = self.format_label.clone();
}
dialog
}
+47 -20
View File
@@ -4,6 +4,7 @@ use craft_behavior::CanvasView;
use egui::Pos2;
use kurbo::{Affine, CubicBez, ParamCurveNearest as _, Point};
use super::model::SelectedAnchors;
use super::{BezierHit, BezierOverlay, EditPath, HandleSide, HandlesShown, KnotRef, MAX_ANCHORS, PathSelection};
/// A shown direction handle: its path's index, its knot, side and screen end.
@@ -46,15 +47,34 @@ impl BezierOverlay<'_> {
reach: f32,
) -> Option<BezierHit> {
// pc: crates/vector/src/edit.rs:337 `hit` (handles, anchors, segments; nearest per kind).
let shown = shown_handles(paths, selection, handles, view);
let shown = shown_handles(paths, selection, &SelectedAnchors::of(selection), handles, view);
let anchors = paths.iter().map(EditPath::anchor_count).sum::<usize>() <= MAX_ANCHORS;
hit_in(paths, &shown, anchors, view, at, reach)
}
}
/// The handles to show, in path order, in then out, leaving out retracted ones and those of subpaths the selection
/// does not show.
pub(super) fn shown_handles(paths: &[EditPath], sel: &PathSelection, handles: HandlesShown, view: &CanvasView) -> Vec<Shown> {
/// does not show. `anchors` holds the anchors `sel` selects.
pub(super) fn shown_handles(
paths: &[EditPath],
sel: &PathSelection,
anchors: &SelectedAnchors,
handles: HandlesShown,
view: &CanvasView,
) -> Vec<Shown> {
shown_handles_of(paths, sel, |path, knot| anchors.has_anchor(path, knot), sel.selected_len(), handles, view)
}
/// [`shown_handles`] with `has_anchor` answering whether a knot of a path is a selected anchor, and `selected` as the
/// number of selected anchors that `OneAnchor` counts.
fn shown_handles_of(
paths: &[EditPath],
sel: &PathSelection,
has_anchor: impl Fn(u64, KnotRef) -> bool,
selected: usize,
handles: HandlesShown,
view: &CanvasView,
) -> Vec<Shown> {
let mut shown = Vec::new();
for (index, path) in paths.iter().enumerate() {
let segment_ends = sel.segment.filter(|_| sel.path == Some(path.key)).and_then(|s| {
@@ -65,13 +85,13 @@ pub(super) fn shown_handles(paths: &[EditPath], sel: &PathSelection, handles: Ha
let Some(knot) = path.knot(knot_ref) else { continue };
for side in [HandleSide::In, HandleSide::Out] {
let of_selection = || {
sel.has_anchor(path.key, knot_ref)
|| next_to_selected_anchor(path, sel, knot_ref, side)
has_anchor(path.key, knot_ref)
|| next_to_selected_anchor(path, &has_anchor, knot_ref, side)
|| segment_ends.is_some_and(|(a, b)| (side == HandleSide::Out && a == knot_ref) || (side == HandleSide::In && b == knot_ref))
};
let wanted = match handles {
HandlesShown::All => true,
HandlesShown::OneAnchor => sel.selected_len() == 1 && of_selection(),
HandlesShown::OneAnchor => selected == 1 && of_selection(),
HandlesShown::Selected => of_selection(),
};
if wanted && !knot.retracted(side) {
@@ -85,31 +105,38 @@ pub(super) fn shown_handles(paths: &[EditPath], sel: &PathSelection, handles: Ha
/// The handles to draw for the anchors `sel` lists for the path at index `at` of `paths`, which the overlay does not
/// edit: [`shown_handles`]' rule applied with that path as the selection's, the other selected anchors still counted.
/// Empty for `All`, whose handles the scene already holds. The index of each is `at`.
pub(super) fn other_handles(paths: &[EditPath], at: usize, sel: &PathSelection, handles: HandlesShown, view: &CanvasView) -> Vec<Shown> {
/// Empty for `All`, whose handles the scene already holds. The index of each is `at`. The overlay calls it once per
/// path, so it reads the listed anchors and their count from `anchors`, the anchors `sel` selects, and copies none.
pub(super) fn other_handles(
paths: &[EditPath],
at: usize,
sel: &PathSelection,
anchors: &SelectedAnchors,
handles: HandlesShown,
view: &CanvasView,
) -> Vec<Shown> {
let Some(path) = paths.get(at) else { return Vec::new() };
let listed = sel.others.iter().find(|(key, _)| *key == path.key).filter(|_| sel.path != Some(path.key));
let (Some((_, anchors)), false) = (listed, handles == HandlesShown::All) else { return Vec::new() };
let mut own = PathSelection::new(Some(path.key), anchors.clone(), None);
for (key, rest) in sel.others.iter().filter(|(key, _)| *key != path.key) {
own = own.also(*key, rest.clone());
if sel.path == Some(path.key) || handles == HandlesShown::All || !anchors.lists(path.key) {
return Vec::new();
}
if let Some(edited) = sel.path.filter(|edited| *edited != path.key) {
own = own.also(edited, sel.anchors.clone());
}
shown_handles(std::slice::from_ref(path), &own, handles, view).into_iter().map(|shown| Shown { path: at, ..shown }).collect()
let edited = sel.path.map_or(0, |_| sel.anchors.len());
let own = PathSelection::new(Some(path.key), Vec::new(), None);
shown_handles_of(std::slice::from_ref(path), &own, |key, knot| anchors.listed_anchor(key, knot), anchors.others_len() + edited, handles, view)
.into_iter()
.map(|shown| Shown { path: at, ..shown })
.collect()
}
/// Whether `side` of `knot` is the handle of a segment that a selected anchor ends: the previous anchor's out
/// handle or the next anchor's in handle, across a closed subpath's seam too.
fn next_to_selected_anchor(path: &EditPath, sel: &PathSelection, knot: KnotRef, side: HandleSide) -> bool {
fn next_to_selected_anchor(path: &EditPath, has_anchor: &impl Fn(u64, KnotRef) -> bool, knot: KnotRef, side: HandleSide) -> bool {
let Some(sub) = path.subpaths.get(knot.subpath) else { return false };
let count = sub.knots.len();
match side {
HandleSide::Out => sub.segment_ends(knot.knot).is_some_and(|(_, next)| sel.has_anchor(path.key, KnotRef::new(knot.subpath, next))),
HandleSide::Out => sub.segment_ends(knot.knot).is_some_and(|(_, next)| has_anchor(path.key, KnotRef::new(knot.subpath, next))),
HandleSide::In => {
let previous = (knot.knot + count.saturating_sub(1)) % count.max(1);
sub.segment_ends(previous).is_some_and(|(previous, _)| sel.has_anchor(path.key, KnotRef::new(knot.subpath, previous)))
sub.segment_ends(previous).is_some_and(|(previous, _)| has_anchor(path.key, KnotRef::new(knot.subpath, previous)))
}
}
}
+13 -6
View File
@@ -37,6 +37,9 @@ use hit_test::{Shown, nearest_on_screen, other_handles, shown_handles};
pub(crate) use mark::paint_mark;
pub use mark::{AnchorsShown, HitMark, SegmentMark};
use mark::{Fill, paint_handle, segment_path, stroke};
use model::SelectedAnchors;
#[cfg(all(test, feature = "screen-testing"))]
pub(crate) use model::reads;
pub use model::{AnchorDelete, EditPath, EditSubpath, HandleSide, Knot, KnotRef, PathEdit, PathSelection};
pub use style::BezierStyle;
pub use words::BezierWords;
@@ -381,6 +384,8 @@ struct Scene {
items: Vec<Item>,
/// Over [`MAX_ANCHORS`] or hidden: outlines only.
limited: bool,
/// The anchors the selection selects (none when `limited`).
selected: SelectedAnchors,
}
/// Paths with anchors and direction handles over a canvas, edited by the pointer and the keyboard as PhotoCraft's
@@ -470,10 +475,12 @@ impl<'a> BezierOverlay<'a> {
let limited = self.anchors == AnchorsShown::Hidden || paths.iter().map(EditPath::anchor_count).sum::<usize>() > MAX_ANCHORS;
let mut items = Vec::new();
if limited {
return Scene { items, limited };
return Scene { items, limited, selected: SelectedAnchors::default() };
}
let selected = SelectedAnchors::of(self.selection);
let near = rect.expand(reach);
let shown = if self.anchors == AnchorsShown::Curvature { Vec::new() } else { shown_handles(paths, self.selection, self.handles, view) };
let shown =
if self.anchors == AnchorsShown::Curvature { Vec::new() } else { shown_handles(paths, self.selection, &selected, self.handles, view) };
let mut handles = shown.iter().peekable();
for (at, path) in paths.iter().enumerate() {
let count = path.anchor_count();
@@ -551,7 +558,7 @@ impl<'a> BezierOverlay<'a> {
}
}
}
Scene { items, limited }
Scene { items, limited, selected }
}
/// Whether the press on `item` is the tool's.
@@ -1308,7 +1315,7 @@ impl Component for BezierOverlay<'_> {
for item in &scene.items {
let press = self.takes(item);
let keyboard = item.kind != Kind::Segment && item.shown && focusable;
let selected = item.kind == Kind::Anchor && self.selection.has_anchor(item.key, item.knot);
let selected = item.kind == Kind::Anchor && scene.selected.has_anchor(item.key, item.knot);
let part = cx.part(item.part(), item.shape.clone()).priority(item.priority());
let part = if press { part.sense(PRESS) } else { part };
let part = if keyboard {
@@ -1416,7 +1423,7 @@ impl Component for BezierOverlay<'_> {
draw_end(path, item.knot, item.at, fill);
}
Kind::Anchor if item.shown => {
let fill = if self.selection.draws_selected(path.key, item.knot) {
let fill = if scene.selected.draws_selected(path.key, item.knot) {
Fill::Path(style.line)
} else {
Fill::Style(if cx.part_if_declared(item.part()).is_some() {
@@ -1433,7 +1440,7 @@ impl Component for BezierOverlay<'_> {
// The handles of anchors selected in paths the overlay does not edit: drawn, never parts.
if !circles {
for (at, path) in paths.iter().enumerate() {
for shown in other_handles(paths, at, self.selection, self.handles, &view) {
for shown in other_handles(paths, at, self.selection, &scene.selected, self.handles, &view) {
draw_end(path, shown.knot, shown.at, Fill::Style(cx.resolve(handle_fill)));
}
}
+79
View File
@@ -2,6 +2,8 @@
//! the overlays report. The host converts its own path type to these each frame and applies the
//! edits to its own.
use std::collections::HashSet;
use craft_theme::Srgba;
use kurbo::{BezPath, CubicBez, Point, Vec2};
@@ -235,6 +237,8 @@ impl PathSelection {
/// Whether `knot` of `path` draws selected: a selected anchor of the path being edited, or one listed in `others`.
pub fn draws_selected(&self, path: u64, knot: KnotRef) -> bool {
#[cfg(all(test, feature = "screen-testing"))]
reads::add(self.others.iter().map(|(key, anchors)| if *key == path { 1 + anchors.len() } else { 1 }).sum());
self.has_anchor(path, knot) || self.others.iter().any(|(key, anchors)| *key == path && anchors.contains(&knot))
}
@@ -245,6 +249,8 @@ impl PathSelection {
/// Whether `knot` of `path` is a selected anchor.
pub fn has_anchor(&self, path: u64, knot: KnotRef) -> bool {
#[cfg(all(test, feature = "screen-testing"))]
reads::add(if self.path == Some(path) { self.anchors.len() } else { 0 });
self.path == Some(path) && self.anchors.contains(&knot)
}
@@ -268,6 +274,79 @@ impl PathSelection {
}
}
/// The anchors a [`PathSelection`] selects, gathered into sets once so that the overlay asks about each knot it lays
/// out or draws without searching the selection's lists. A path that `others` lists more than once is treated as one
/// path holding every anchor listed for it.
#[derive(Default)]
pub(super) struct SelectedAnchors {
path: Option<u64>,
anchors: HashSet<KnotRef>,
others: HashSet<(u64, KnotRef)>,
listed: HashSet<u64>,
others_len: usize,
}
impl SelectedAnchors {
/// The anchors `sel` selects.
pub(super) fn of(sel: &PathSelection) -> Self {
let others_len = sel.others.iter().map(|(_, anchors)| anchors.len()).sum();
#[cfg(all(test, feature = "screen-testing"))]
reads::add(sel.anchors.len() + others_len);
Self {
path: sel.path,
anchors: sel.anchors.iter().copied().collect(),
others: sel.others.iter().flat_map(|(key, anchors)| anchors.iter().map(|knot| (*key, *knot))).collect(),
listed: sel.others.iter().map(|(key, _)| *key).collect(),
others_len,
}
}
/// Whether `knot` of `path` is a selected anchor of the path being edited ([`PathSelection::has_anchor`]).
pub(super) fn has_anchor(&self, path: u64, knot: KnotRef) -> bool {
self.path == Some(path) && self.anchors.contains(&knot)
}
/// Whether `knot` of `path` draws selected ([`PathSelection::draws_selected`]).
pub(super) fn draws_selected(&self, path: u64, knot: KnotRef) -> bool {
self.has_anchor(path, knot) || self.others.contains(&(path, knot))
}
/// Whether `knot` is one of the anchors `others` lists for `path`.
pub(super) fn listed_anchor(&self, path: u64, knot: KnotRef) -> bool {
self.others.contains(&(path, knot))
}
/// Whether `others` lists `path`, with or without anchors.
pub(super) fn lists(&self, path: u64) -> bool {
self.listed.contains(&path)
}
/// The number of anchors `others` lists over every path.
pub(super) fn others_len(&self) -> usize {
self.others_len
}
}
/// The number of entries of selection anchor lists read on this thread, for trials that count the overlay's work.
#[cfg(all(test, feature = "screen-testing"))]
pub(crate) mod reads {
use std::cell::Cell;
thread_local! {
static READS: Cell<usize> = const { Cell::new(0) };
}
/// Counts `n` entries read.
pub(crate) fn add(n: usize) {
READS.with(|reads| reads.set(reads.get() + n));
}
/// The entries read since the last call, and starts the count again.
pub(crate) fn take() -> usize {
READS.with(|reads| reads.replace(0))
}
}
/// Which of a knot's two direction handles.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
+12 -9
View File
@@ -6,7 +6,7 @@ use craft_behavior::Value;
use craft_color_ui::ui::{ChosenColor, ColorChoice, NamedColor};
use craft_theme::Srgba;
use craft_ui::choice::{Checkbox, Radio, RadioGroup};
use craft_ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _};
use craft_ui::contract::{Bind, Entry, FieldLabelRole, Props as _, Show as _, ShowContainer as _, SideLabel};
use craft_ui::dialog::{DialogId, DialogResult, DialogStack, StackDialog, dialog_id};
use craft_ui::display::{Shade, Text};
use craft_ui::form::{Field, FieldGroup};
@@ -549,31 +549,34 @@ impl DivideSlicesDialog {
}
}
/// One axis: its check box, then (while it is on) what the value counts and the value.
/// One axis: its check box, then (while it is on) what the value counts and the value. Both axes show the same Divide
/// By and value labels, so those rows describe their controls, and each control is named by its label and the axis's
/// caption.
fn axis_rows(ui: &mut Ui, axis: &mut AxisState, caption: &Label, words: &SliceWords, lengths: LengthUnits) {
Field::new(caption.clone()).show(ui, |ui, _| {
Checkbox::new(Bind::bound(&mut axis.on)).label(caption.clone()).show(ui);
});
let in_axis = |control: &Label| Label::from(words.axis_control.fill(&[("control", control.as_str()), ("axis", caption.as_str())]));
let unit = if axis.by_size { words.size.clone() } else { words.count.clone() };
Field::new(words.divide_by.clone()).enabled(axis.on).show(ui, |ui, _| {
RadioGroup::new(words.divide_by.clone(), Bind::bound(&mut axis.by_size)).show(ui, |ui, _| {
let describes = || SideLabel::new().role(FieldLabelRole::Describes);
Field::new(words.divide_by.clone()).side(describes()).enabled(axis.on).show(ui, |ui, _| {
RadioGroup::new(in_axis(&words.divide_by), Bind::bound(&mut axis.by_size)).show(ui, |ui, _| {
Row::new().show(ui, |ui, _| {
Radio::new(false).label(words.count.clone()).show(ui);
Radio::new(true).label(words.size.clone()).show(ui);
});
});
});
Field::new(unit).enabled(axis.on).show(ui, |ui, _| {
let value_name = in_axis(&unit);
Field::new(unit).side(describes()).enabled(axis.on).show(ui, |ui, _| {
if axis.by_size {
let field =
NumberField::length(words.divide_value.clone(), Bind::given(Some(axis.size)), lengths).range(1.0..=AxisState::MAX_SIZE).show(ui);
let field = NumberField::length(value_name.clone(), Bind::given(Some(axis.size)), lengths).range(1.0..=AxisState::MAX_SIZE).show(ui);
if let Some(Some(size)) = field.value().copied() {
axis.size = AxisState::size_of(size, axis.size);
}
} else {
let max = f64::from(AxisState::MAX_COUNT);
let field =
NumberField::new(words.divide_value.clone(), Bind::given(Some(f64::from(axis.count)))).range(1.0..=max).commit_decimals(0).show(ui);
let field = NumberField::new(value_name.clone(), Bind::given(Some(f64::from(axis.count)))).range(1.0..=max).commit_decimals(0).show(ui);
if let Some(Some(count)) = field.value().copied() {
axis.count = count.round().clamp(1.0, max) as u32;
}
+3
View File
@@ -72,5 +72,8 @@ craft_ui::words! {
count: "slice.count" = "slices, evenly spaced";
size: "slice.size" = "per slice";
divide_value: "slice.divideValue" = "Value";
/// The name a screen reader reads for one axis's Divide By group and value field: `{control}` the row's
/// visible label, `{axis}` the axis's caption.
axis_control: template "slice.axisControl" = "{control}, {axis}";
}
}
+16 -6
View File
@@ -71,7 +71,7 @@ impl Outcome for StrokeEditorOutput {
/// with a line sample drawn at opacity 1; the row matching [`StrokeStyle::line_style`] is selected, none for Custom.
/// Picking one applies [`StrokeStyle::with_line_style`].
/// - Rows: Alignment (Inside, Center, Outside; enabled only when [`closed`](Self::closed)); Caps (Butt / Flat, Round,
/// Square; disabled for a solid closed path); Corners (Miter, Round, Bevel; enabled only with
/// Square; disabled for a solid closed path unless [`caps_on_closed`](Self::caps_on_closed)); Corners (Miter, Round, Bevel; enabled only with
/// [`corners`](Self::corners)); the app's [`rows`](Self::rows); Miter limit (1–500, `×`; enabled only for Miter
/// corners); Opacity ([`StrokeSections::OPACITY`], 0–100 %, stored 0..=1). Choices are selects, or segmented icon
/// buttons with [`StrokeSections::ICONS`]. Under the rows of an open path: "Open paths use centered strokes".
@@ -96,6 +96,7 @@ pub struct StrokeEditor<'a> {
value: Bind<'a, StrokeStyle>,
sections: StrokeSections,
closed: bool,
caps_on_closed: bool,
corners: bool,
mixed: StrokeMixed,
rows: &'a [StrokeChoiceRow<'a>],
@@ -109,6 +110,7 @@ impl<'a> StrokeEditor<'a> {
value,
sections: StrokeSections::default(),
closed: true,
caps_on_closed: false,
corners: true,
mixed: StrokeMixed::default(),
rows: &[],
@@ -121,13 +123,20 @@ impl<'a> StrokeEditor<'a> {
self
}
/// Whether the stroked path is closed: alignment applies and caps need dashes.
/// True by default.
/// Whether the stroked path is closed: alignment applies and caps need dashes, unless
/// [`caps_on_closed`](Self::caps_on_closed) is set. True by default.
pub fn closed(mut self, closed: bool) -> Self {
self.closed = closed;
self
}
/// Whether the Caps row stays enabled on a closed path without dashes. False by default: the row is then disabled
/// for a solid closed path and enabled for an open or dashed one.
pub fn caps_on_closed(mut self, enabled: bool) -> Self {
self.caps_on_closed = enabled;
self
}
/// Whether the path has corners for the Corners and Miter limit rows (an ellipse has none). True by default.
pub fn corners(mut self, corners: bool) -> Self {
self.corners = corners;
@@ -148,7 +157,7 @@ impl<'a> StrokeEditor<'a> {
/// Shows the editor.
pub fn show(self, ui: &mut Ui) -> StrokeEditorOutput {
let StrokeEditor { label, mut value, sections, closed, corners, mixed, rows } = self;
let StrokeEditor { label, mut value, sections, closed, caps_on_closed, corners, mixed, rows } = self;
let env = Env::of(ui);
let words = env.words::<StrokeWords>();
let name: Arc<str> = label.as_str().into();
@@ -164,7 +173,7 @@ impl<'a> StrokeEditor<'a> {
Some((base, draft)) if base == held => draft,
_ => held.clone(),
};
let body = Body { words: &words, style: &style, sections, closed, corners, mixed, rows, name: name.clone() };
let body = Body { words: &words, style: &style, sections, closed, caps_on_closed, corners, mixed, rows, name: name.clone() };
body.show(ui, &mut found);
if !found.events.is_empty() {
for event in &found.events {
@@ -251,6 +260,7 @@ struct Body<'a> {
style: &'a StrokeStyle,
sections: StrokeSections,
closed: bool,
caps_on_closed: bool,
corners: bool,
mixed: StrokeMixed,
rows: &'a [StrokeChoiceRow<'a>],
@@ -325,7 +335,7 @@ impl Body<'_> {
fn grid(&self, ui: &mut Ui, found: &mut Found) {
let (style, mixed, words) = (self.style, self.mixed, self.words);
let solid_closed = self.closed && style.dashes.is_empty() && !mixed.dashes;
let solid_closed = self.closed && !self.caps_on_closed && style.dashes.is_empty() && !mixed.dashes;
let icons = self.sections.contains(StrokeSections::ICONS);
FieldGroup::new(words.title.clone()).show(ui, |ui, _| {
let align = [
+48
View File
@@ -465,6 +465,54 @@ fn one_anchor_shows_handles_only_while_one_anchor_is_selected_over_all_paths() {
assert!(!matches!(none, Some(BezierHit::Handle { .. })), "{none:?}");
}
// Under `OneAnchor` the handles of an anchor listed in `others` draw while it is the only selected anchor over all
// paths, as `Selected` draws them; with an anchor of a third path listed too, neither path's handles draw.
#[trial]
fn one_anchor_draws_other_paths_handles_only_while_one_anchor_is_selected_over_all_paths() {
let painted_with = |selection: PathSelection, handles: HandlesShown| {
let mut other = path_b();
other.subpaths[0].knots[0] = Knot::smooth(p(60.0, 200.0), p(90.0, 170.0));
let third =
EditPath::new(3, vec![EditSubpath::new(vec![Knot::smooth(p(300.0, 220.0), p(330.0, 190.0)), Knot::corner(p(360.0, 260.0))], false)]);
let mut h = harness(vec![path_a(), other, third]);
h.update(|st| (st.selection, st.handles) = (selection, handles));
format!("{:?}", h.fixture.frame_shapes())
};
let one = || sel(1, &[]).also(2, vec![kr(0)]);
assert_eq!(painted_with(one(), HandlesShown::OneAnchor), painted_with(one(), HandlesShown::Selected));
let two = || sel(1, &[]).also(2, vec![kr(0)]).also(3, vec![kr(0)]);
assert_ne!(painted_with(two(), HandlesShown::OneAnchor), painted_with(two(), HandlesShown::Selected));
assert_eq!(
painted_with(two(), HandlesShown::OneAnchor),
painted_with(sel(1, &[]).also(2, vec![kr(0)]).also(3, vec![kr(0)]), HandlesShown::OneAnchor),
"painting is the same from frame to frame"
);
}
// A frame reads the selection's anchor lists a number of times that grows with the selection, not with its square:
// doubling the selected anchors of the edited path and the number of other paths listed at most doubles the entries
// read (a search of the lists for each anchor laid out or drawn quadruples them).
#[trial]
fn a_frame_reads_the_selections_anchor_lists_in_proportion_to_the_selection() {
let reads_for = |n: usize| {
let knot = |i: usize| Knot::smooth(p(20.0 + (i % 40) as f64 * 12.0, 20.0 + (i / 40) as f64 * 12.0), p(26.0 + (i % 40) as f64 * 12.0, 20.0));
let edited = EditPath::new(1, vec![EditSubpath::new((0..n).map(knot).collect(), false)]);
let others: Vec<EditPath> =
(0..n).map(|i| EditPath::new(2 + i as u64, vec![EditSubpath::new((0..4).map(|k| knot(i * 4 + k)).collect(), true)])).collect();
let mut selection = PathSelection::new(Some(1), (0..n).map(kr).collect(), None);
for other in &others {
selection = selection.also(other.key, (0..4).map(kr).collect());
}
let mut h = harness(std::iter::once(edited).chain(others).collect());
craft_draw::ui::pen::bezier::reads::take();
h.update(|st| st.selection = selection);
craft_draw::ui::pen::bezier::reads::take()
};
let (small, large) = (reads_for(60), reads_for(120));
assert!(small > 0, "the frame reads the selection");
assert!(large < small * 3, "{small} entries read for 60 selected paths, {large} for 120");
}
// Hovering a segment under Add reports the segment with its parameter, which the preview anchor stands at.
// `AnchorsShown::Hidden` draws outlines only: no anchor, no handle, no part, no AccessKit object.
+41 -3
View File
@@ -4,11 +4,15 @@
use craft_behavior::geometry::Constraint;
use craft_behavior::kurbo::{Point, Rect};
use craft_behavior::{CanvasView, EditEvent};
use craft_draw::ui::slice::{SliceCommand, SliceEvent, SliceItem, SliceMode, SliceOrigin, SliceOverlay, SliceRefusal, SliceTool, SliceToolSettings};
use craft_ui::contract::{CommandSet, Show as _};
use craft_draw::ui::slice::{
DivideBy, DivideSlices, DivideSlicesDialog, SliceCommand, SliceEvent, SliceItem, SliceMode, SliceOrigin, SliceOverlay, SliceRefusal, SliceTool,
SliceToolSettings,
};
use craft_ui::contract::{CommandSet, Role, Show as _};
use craft_ui::dialog::DialogHost;
use craft_ui::runtime::commands::CommandRef;
use craft_ui::runtime::frame::take_output;
use craft_ui::testing::{ToolFixture, trial};
use craft_ui::testing::{Fixture, ToolFixture, access, trial};
use egui::{Key, Modifiers, Pos2, Vec2};
use std::cell::RefCell;
use std::rc::Rc;
@@ -203,3 +207,37 @@ fn delete_takes_the_key_for_the_selected_slice() {
}
}
}
/// The names a screen reader reads for the nodes of `role` in the shown Divide Slice dialog, in tree order.
fn divide_names(divide: DivideSlices, role: Role) -> Vec<String> {
let host = Rc::new(RefCell::new(DialogHost::new()));
let shown = Rc::clone(&host);
let mut fixture = Fixture::new(move |ui| shown.borrow_mut().run(ui));
fixture.room(Vec2::new(900.0, 700.0));
host.borrow_mut().open(DivideSlicesDialog::new(divide));
fixture.idle(10);
let tree = fixture.tree();
fixture.by_role(role).iter().map(|target| access::name(tree, target.node).unwrap_or_default().to_owned()).collect()
}
/// Divide Slice's two axes show the same Divide By choice and value rows; each axis's radio group and value field
/// name their axis by its caption after their visible label, so a screen reader tells the rows from the columns.
#[trial]
fn divide_slice_names_each_axis_control_by_its_axis() {
let by_count = DivideSlices::new(Some(DivideBy::Count(2)), Some(DivideBy::Count(3)));
let by_size = DivideSlices::new(Some(DivideBy::Size(72.0)), Some(DivideBy::Size(36.0)));
let cases = [
("the Divide By groups", by_count, Role::RADIO_GROUP, "Divide By"),
("the count fields", by_count, Role::SPIN_BUTTON, "slices, evenly spaced"),
("the size fields", by_size, Role::SPIN_BUTTON, "per slice"),
];
for (what, divide, role, label) in cases {
let names = divide_names(divide, role);
let [rows, columns] = names.as_slice() else { panic!("{what}: one for each axis, got {names:?}") };
assert_ne!(rows, columns, "{what} have different names");
for (name, axis) in [(rows, "Divide Horizontally Into"), (columns, "Divide Vertically Into")] {
assert!(name.starts_with(label), "{what}: {name:?} starts with the visible label {label:?}");
assert!(name.contains(axis), "{what}: {name:?} names its axis {axis:?}");
}
}
}
+36 -2
View File
@@ -1,7 +1,8 @@
//! The stroke editor's dash fields: typing in the blank after the pattern adds an entry, clearing a later field ends
//! the pattern there, and the first field never clears.
//! the pattern there, and the first field never clears. Its Caps row on a solid closed path: disabled by default,
//! enabled with `caps_on_closed`.
use craft_draw::ui::stroke::{StrokeEditor, StrokeSections, StrokeStyle};
use craft_draw::ui::stroke::{LineCap, StrokeEditor, StrokeSections, StrokeStyle};
use craft_ui::contract::Bind;
use craft_ui::testing::{Fixture, trial};
use egui::{Key, Modifiers};
@@ -34,6 +35,39 @@ fn type_into(fixture: &mut Fixture, label: &str, text: &str) {
fixture.idle(3);
}
/// The panel editor over a solid closed path, with `caps_on_closed` as given, and the style it writes through to.
fn closed_editor(caps_on_closed: bool) -> (Fixture, Rc<RefCell<StrokeStyle>>) {
let style = Rc::new(RefCell::new(StrokeStyle::default()));
let shown = Rc::clone(&style);
let mut fixture = Fixture::new(move |ui| {
let mut style = shown.borrow_mut();
let _ = StrokeEditor::new("Stroke", Bind::bound(&mut *style))
.sections(StrokeSections::PANEL)
.closed(true)
.caps_on_closed(caps_on_closed)
.show(ui);
});
fixture.settle();
(fixture, style)
}
#[trial]
fn caps_on_closed_keeps_the_cap_buttons_enabled_on_a_solid_closed_path() {
let (mut fixture, style) = closed_editor(false);
let square = fixture.by_label("Square").expect("the editor shows Square");
assert!(fixture.tree().is_disabled_key(square.node), "by default Caps is disabled for a solid closed path");
fixture.click(&square);
fixture.idle(3);
assert_ne!(style.borrow().cap, LineCap::Square, "a disabled cap button does not change the cap");
let (mut fixture, style) = closed_editor(true);
let square = fixture.by_label("Square").expect("the editor shows Square");
assert!(!fixture.tree().is_disabled_key(square.node), "with caps_on_closed Caps is enabled");
fixture.click(&square);
fixture.idle(3);
assert_eq!(style.borrow().cap, LineCap::Square, "the cap button sets the cap");
}
#[trial]
fn dash_fields_add_after_the_pattern_and_a_cleared_field_ends_it() {
let (mut fixture, style) = editor(vec![4.0, 2.0]);
+6 -2
View File
@@ -95,13 +95,17 @@ below), and `Embed::documents(&["Noto Sans", …])` only the families it names (
- `embedded_elsewhere(&["Noto Sans Math", …])` names families another table of the app embeds,
so `check_text` and the catalog check count their characters as covered.
- `dir(path)` and `required(bool)` override the two environment variables.
- `tab_face()` also embeds Noto Sans Condensed SemiBold from `fonts/latin-manifest.txt`, with the
role `tab`. `scripts` and `filter` do not apply to it. A checkout without that manifest or its
row embeds the other faces and prints a warning, even with `CRAFT_FONTS_REQUIRED=1`.
`write` returns the embedded `ManifestEntry`s, for build-time checks such as "the interface face
is present". The generated file is a slice expression of `EmbeddedFace { family, style, scripts,
index, bytes, role }` literals; any struct with those fields and that name in scope works too.
`role` is the manifest line's ninth field: `Some("ui")`, `Some("mono")`, `Some("signature")` or
`None`; craft-ui's font stack leads the Monospace family with the `mono` face and the signature
family (`FontRef::signature()`) with the `signature` face. `EmbeddedFace` itself has `name()`,
`None`, or `Some("tab")` on the face `tab_face()` adds; craft-ui's font stack leads the Monospace
family with the `mono` face, the signature family (`FontRef::signature()`) with the `signature`
face and the tab-title family with the `tab` face. `EmbeddedFace` itself has `name()`,
`has_script(tag)`, `is_cjk()` and `weight()`.
## Document fonts
+94 -28
View File
@@ -9,7 +9,7 @@ use std::io;
use std::path::{Component, Path, PathBuf};
use crate::cmap::Cmap;
use crate::manifest::{ManifestEntry, ParseError, parse_manifest, script_matches};
use crate::manifest::{ManifestEntry, ParseError, TAB_FACE, TAB_ROLE, parse_manifest, script_matches};
const DIR_VAR: &str = "CRAFT_FONTS_DIR";
const REQUIRED_VAR: &str = "CRAFT_FONTS_REQUIRED";
@@ -55,6 +55,35 @@ fn rerun_if_changed(cargo: &mut Vec<String>, path: &Path) -> Result<(), Error> {
Ok(())
}
/// `entry` of `manifest` as a face to embed, once its font file resolves to a file inside the checkout `root` and its
/// licence file, if it exists, does too.
fn checked_face(manifest: &Path, dir: &Path, root: &Path, entry: ManifestEntry, cut: bool, cargo: &mut Vec<String>) -> Result<Face, Error> {
let manifest = manifest.to_path_buf();
// A manifest path names a file in the checkout, and is served under the same name.
for file in [&entry.file, &entry.licence_file] {
if !file.is_empty() && !is_checkout_relative(file) {
return Err(Error::OutsideCheckout { manifest, file: file.clone() });
}
}
let file = dir.join(&entry.file);
// `include_bytes!` resolves relative paths from the including source file.
let path = file.canonicalize().map_err(|source| Error::Read { path: file, source })?;
// A symlink in the checkout must not pull a file from elsewhere on the build host. A
// missing licence is only warned about when serving; one that exists must be inside.
if !path.starts_with(root) {
return Err(Error::OutsideCheckout { manifest, file: entry.file });
}
if !entry.licence_file.is_empty() && dir.join(&entry.licence_file).canonicalize().is_ok_and(|licence| !licence.starts_with(root)) {
return Err(Error::OutsideCheckout { manifest, file: entry.licence_file });
}
if !path.is_file() {
return Err(Error::OutsideCheckout { manifest, file: entry.file });
}
rerun_if_changed(cargo, &path)?;
let (index, sha256) = (entry.index, entry.sha256.clone());
Ok(Face { entry, path, index, cut, sha256 })
}
/// Whether the build script is building for wasm32 (web builds usually embed fewer faces).
pub fn target_is_wasm() -> bool {
std::env::var("CARGO_CFG_TARGET_ARCH").is_ok_and(|arch| arch == "wasm32")
@@ -75,6 +104,7 @@ pub struct Embed {
families: Option<Vec<String>>,
elsewhere: Vec<String>,
serve: Option<Serve>,
tab: bool,
}
/// Where [`Embed::serve`] copies the faces, and the URL prefix they are served under.
@@ -174,6 +204,18 @@ impl Embed {
self
}
/// Also embed the tab-title face, Noto Sans Condensed SemiBold ([`TAB_FACE`]), from the checkout's
/// `fonts/latin-manifest.txt`, with the `tab` role ([`TAB_ROLE`]); craft-ui's font stack leads its tab-title family
/// with it. [`Embed::scripts`] and [`Embed::filter`] do not apply to it. A checkout without that manifest, or a
/// manifest without the face's row, embeds the other faces and prints a `cargo::warning`, required or not. A
/// manifest that does not parse, or a row whose file is missing or outside the checkout, is an [`Error`] when
/// required and a `cargo::warning` otherwise; the other faces are embedded either way when not required. A
/// [`Embed::serve`] table carries no roles, so it leaves the face out and prints a `cargo::warning`.
pub fn tab_face(mut self) -> Self {
self.tab = true;
self
}
/// Read this checkout instead of `CRAFT_FONTS_DIR`.
pub fn dir(mut self, dir: impl Into<PathBuf>) -> Self {
self.dir = Some(dir.into());
@@ -239,7 +281,7 @@ impl Embed {
let selected = match &dir {
None => Err(Error::NotSet),
Some(dir) => self.select(dir, cargo).and_then(|faces| if required { self.check_required(dir, faces) } else { Ok(faces) }),
Some(dir) => self.select(dir, required, cargo).and_then(|faces| if required { self.check_required(dir, faces) } else { Ok(faces) }),
};
let mut selected = selected;
if let Ok(faces) = &mut selected {
@@ -278,8 +320,39 @@ impl Embed {
Ok(faces)
}
/// The tab-title face of `fonts/latin-manifest.txt` ([`TAB_FACE`]), with the [`TAB_ROLE`] role. A checkout without
/// that manifest, or a manifest without the face's row, gives `None` and a `cargo::warning`.
fn select_tab_face(&self, dir: &Path, root: &Path, cargo: &mut Vec<String>) -> Result<Option<Face>, Error> {
let manifest = dir.join("fonts/latin-manifest.txt");
let text = match read_text_bounded(&manifest, MAX_MANIFEST_BYTES) {
Ok(text) => text,
Err(source) if source.kind() == io::ErrorKind::NotFound => {
// Cargo treats a missing watched file as changed, so the build watches the folder the manifest would be in.
rerun_if_changed(cargo, &dir.join("fonts"))?;
cargo.push(format!("cargo::warning=craft-fonts: not embedding the tab-title face: {} does not exist", manifest.display()));
return Ok(None);
}
Err(source) => return Err(Error::Read { path: manifest, source }),
};
rerun_if_changed(cargo, &manifest)?;
let entries = parse_manifest(&text).map_err(|error| Error::Parse { manifest: manifest.clone(), error })?;
let (family, style) = TAB_FACE;
let Some(mut entry) = entries.into_iter().find(|entry| entry.family == family && entry.style == style) else {
cargo.push(format!("cargo::warning=craft-fonts: not embedding the tab-title face: {} has no {family} {style} row", manifest.display()));
return Ok(None);
};
entry.role = Some(TAB_ROLE.to_owned());
let file = dir.join(&entry.file);
if !file.exists() {
// Cargo treats a missing watched file as changed, so the build watches the nearest folder that exists.
let folder = file.ancestors().skip(1).find(|folder| folder.is_dir()).unwrap_or(dir);
rerun_if_changed(cargo, folder)?;
}
checked_face(&manifest, dir, root, entry, false, cargo).map(Some)
}
/// The wanted manifest entries with their canonical file paths.
fn select(&self, dir: &Path, cargo: &mut Vec<String>) -> Result<Vec<Face>, Error> {
fn select(&self, dir: &Path, required: bool, cargo: &mut Vec<String>) -> Result<Vec<Face>, Error> {
let manifest = dir.join("fonts/manifest.txt");
let text = read_text_bounded(&manifest, MAX_MANIFEST_BYTES).map_err(|source| Error::Read { path: manifest.clone(), source })?;
// Cargo treats a missing watched file as changed, which would rerun the build every time.
@@ -325,29 +398,17 @@ impl Embed {
uncut.push(format!("{} {}", entry.family, entry.style));
continue;
}
// A manifest path names a file in the checkout, and is served under the same name.
for file in [&entry.file, &entry.licence_file] {
if !file.is_empty() && !is_checkout_relative(file) {
return Err(Error::OutsideCheckout { manifest, file: file.clone() });
}
faces.push(checked_face(&manifest, dir, &root, entry, cut, cargo)?);
}
if self.tab && self.serve.is_some() {
cargo.push("cargo::warning=craft-fonts: not serving the tab-title face: a served table carries no roles".to_owned());
} else if self.tab {
match self.select_tab_face(dir, &root, cargo) {
Ok(Some(face)) => faces.push(face),
Ok(None) => {}
Err(e) if required => return Err(e),
Err(e) => cargo.push(format!("cargo::warning=craft-fonts: not embedding the tab-title face: {e}")),
}
let file = dir.join(&entry.file);
// `include_bytes!` resolves relative paths from the including source file.
let path = file.canonicalize().map_err(|source| Error::Read { path: file, source })?;
// A symlink in the checkout must not pull a file from elsewhere on the build host. A
// missing licence is only warned about when serving; one that exists must be inside.
if !path.starts_with(&root) {
return Err(Error::OutsideCheckout { manifest, file: entry.file });
}
if !entry.licence_file.is_empty() && dir.join(&entry.licence_file).canonicalize().is_ok_and(|licence| !licence.starts_with(&root)) {
return Err(Error::OutsideCheckout { manifest, file: entry.licence_file });
}
if !path.is_file() {
return Err(Error::OutsideCheckout { manifest, file: entry.file });
}
rerun_if_changed(cargo, &path)?;
let (index, sha256) = (entry.index, entry.sha256.clone());
faces.push(Face { entry, path, index, cut, sha256 });
}
if !uncut.is_empty() {
let why = if self.catalogs.is_some() { "Embed::subset_to was given no translation catalogs" } else { "no translation catalogs" };
@@ -451,7 +512,8 @@ impl Embed {
}
/// Warn about each catalog's and [`Embed::check_text`] file's characters that neither an
/// embedded face nor an [`Embed::embedded_elsewhere`] face covers.
/// embedded face nor an [`Embed::embedded_elsewhere`] face covers. The tab-title face, which draws only tab titles,
/// covers none of them.
fn check_coverage(&self, faces: &[Face], dir: &Path, cargo: &mut Vec<String>) {
let files = self.checked_files();
if files.is_empty() {
@@ -460,6 +522,7 @@ impl Embed {
let elsewhere = self.elsewhere(dir, cargo);
let fonts: Vec<(&ManifestEntry, u32, Option<Vec<u8>>)> = faces
.iter()
.filter(|face| face.entry.role.as_deref() != Some(TAB_ROLE))
.map(|face| (&face.entry, face.index, read_bounded(&face.path, MAX_FILE_BYTES).ok()))
.chain(elsewhere.iter().map(|entry| (entry, entry.index, read_bounded(&dir.join(&entry.file), MAX_FILE_BYTES).ok())))
.collect();
@@ -496,16 +559,19 @@ impl Embed {
}
}
/// `faces` when `fonts/manifest.txt` gave at least one, covering every script of [`Embed::scripts`]; the tab-title
/// face, which neither selection applies to, counts for neither.
fn check_required(&self, dir: &Path, faces: Vec<Face>) -> Result<Vec<Face>, Error> {
let manifest = dir.join("fonts/manifest.txt");
if faces.is_empty() {
let selected = || faces.iter().filter(|face| face.entry.role.as_deref() != Some(TAB_ROLE));
if selected().next().is_none() {
return Err(Error::NoFaces { manifest });
}
let missing: Vec<String> = self
.scripts
.iter()
.flatten()
.filter(|tag| !faces.iter().any(|face| face.entry.scripts.iter().any(|s| script_matches(s, tag))))
.filter(|tag| !selected().any(|face| face.entry.scripts.iter().any(|s| script_matches(s, tag))))
.cloned()
.collect();
if missing.is_empty() { Ok(faces) } else { Err(Error::MissingScripts { manifest, scripts: missing }) }
+3 -3
View File
@@ -62,7 +62,7 @@ mod sha256;
mod tests;
pub use embed::{Embed, Error, target_is_wasm};
pub use manifest::{CJK_SCRIPTS, MONO_ROLE, ManifestEntry, ParseError, SIGNATURE_ROLE, UI_ROLE, parse_manifest};
pub use manifest::{CJK_SCRIPTS, MONO_ROLE, ManifestEntry, ParseError, SIGNATURE_ROLE, TAB_FACE, TAB_ROLE, UI_ROLE, parse_manifest};
/// A craft-fonts face embedded by [`Embed`]: one line of `fonts/manifest.txt`.
///
@@ -81,8 +81,8 @@ pub struct EmbeddedFace {
/// The font file's bytes, from `include_bytes!`.
pub bytes: &'static [u8],
/// The manifest line's `role`: `Some("ui")` for an interface face ([`UI_ROLE`]), `Some("mono")` for the
/// monospace face ([`MONO_ROLE`]), `Some("signature")` for the signature face ([`SIGNATURE_ROLE`]), `None` for a
/// line without one.
/// monospace face ([`MONO_ROLE`]), `Some("signature")` for the signature face ([`SIGNATURE_ROLE`]), `Some("tab")`
/// for the tab-title face [`Embed::tab_face`] adds ([`TAB_ROLE`]), `None` for a line without one.
pub role: Option<&'static str>,
}
+10
View File
@@ -11,6 +11,8 @@
//! translation catalogs; `mono` for the monospace face, which leads an app's Monospace family; or
//! `signature` for the handwriting face, which leads the signature family.
//! Fields after the ninth are ignored, so a manifest that gains a field still embeds.
//! `fonts/latin-manifest.txt` has the same format; [`Embed::tab_face`](crate::Embed::tab_face)
//! reads one row of it and gives that face the `tab` role.
use std::fmt;
@@ -37,6 +39,7 @@ pub struct ManifestEntry {
pub source: String,
/// The optional ninth field: `Some("ui")` for an interface face, `Some("mono")` for the
/// monospace face, `Some("signature")` for the signature face, `None` when the line has no role.
/// [`Embed::tab_face`](crate::Embed::tab_face) sets `Some("tab")` on the face it adds.
pub role: Option<String>,
}
@@ -72,6 +75,13 @@ pub const MONO_ROLE: &str = "mono";
/// The `role` of a signature face: `FontRef::signature()` selects the embedded faces that have it.
pub const SIGNATURE_ROLE: &str = "signature";
/// The `role` [`Embed::tab_face`](crate::Embed::tab_face) gives the tab-title face it embeds from
/// `fonts/latin-manifest.txt`: the tab-title family leads with the embedded face that has it.
pub const TAB_ROLE: &str = "tab";
/// The family and style of the tab-title face in `fonts/latin-manifest.txt`.
pub const TAB_FACE: (&str, &str) = ("Noto Sans", "Condensed SemiBold");
/// Script tags of the CJK faces, which craft-fonts also ships as interface faces. `Hant` covers
/// `Hant-HK`.
pub const CJK_SCRIPTS: &[&str] = &["Hans", "Hant", "Jpan", "Kore", "Hani"];
+72
View File
@@ -368,3 +368,75 @@ fn an_oversized_manifest_and_a_directory_face_are_errors() {
let r = run(Embed::new(), Some(&dir), None);
assert!(r.result.is_ok() && warnings(&r).iter().any(|w| w.contains("larger than")), "{:?}", r.cargo);
}
/// `Embed::tab_face` adds only the Noto Sans Condensed SemiBold row of `fonts/latin-manifest.txt`, with the `tab` role.
/// A checkout without that manifest or row keeps its other faces, required or not; a broken manifest or row is an
/// error only when required. The face counts for none of the scripts a required build asks for and covers none of the
/// characters of a checked text, and a served table leaves it out.
#[test]
fn the_tab_face_comes_from_the_latin_manifest_with_the_tab_role() {
let scratch = Scratch::new("tab-face");
let dir = checkout(&scratch, &[("Noto Sans Arabic", "Arab", "", tiny_font(&[(0x627, 0x627, None)], &[]))]);
std::fs::write(dir.join("fonts/OFL.txt"), b"licence").unwrap();
std::fs::write(dir.join("fonts/condensed.ttf"), tiny_font(&[(0x41, 0x5A, None)], &[])).unwrap();
std::fs::write(dir.join("fonts/inter.ttf"), tiny_font(&[(0x41, 0x5A, None)], &[])).unwrap();
let latin = dir.join("fonts/latin-manifest.txt");
let row = |family: &str, style: &str, file: &str| format!("{family} | {style} | {file} | Latn | OFL-1.1 | fonts/OFL.txt | 00 | src\n");
let both = row("Inter", "SemiBold", "fonts/inter.ttf") + &row("Noto Sans", "Condensed SemiBold", "fonts/condensed.ttf");
std::fs::write(&latin, &both).unwrap();
let r = run(Embed::new().tab_face(), Some(&dir), Some("1"));
assert_eq!(r.result.as_ref().unwrap(), &["Noto Sans Arabic Regular", "Noto Sans Condensed SemiBold"]);
assert!(r.table.contains(r#"family: "Noto Sans", style: "Condensed SemiBold""#) && r.table.contains(r#"role: Some("tab")"#), "{}", r.table);
assert!(!r.table.contains("Inter"), "{}", r.table);
assert!(r.cargo.iter().any(|l| l == &format!("cargo::rerun-if-changed={}", latin.display())), "{:?}", r.cargo);
// Scripts and the filter narrow only the main manifest's faces.
let r = run(Embed::new().scripts(&["Arab"]).filter(|f| f.has_script("Arab")).tab_face(), Some(&dir), Some("1"));
assert_eq!(r.result.as_ref().unwrap(), &["Noto Sans Arabic Regular", "Noto Sans Condensed SemiBold"]);
// The tab-title face does not stand in for a required script the main manifest lacks.
let r = run(Embed::new().scripts(&["Latn"]).tab_face(), Some(&dir), Some("1"));
assert!(matches!(&r.result, Err(Error::NoFaces { .. })), "{:?}", r.result);
let r = run(Embed::new().scripts(&["Arab", "Latn"]).tab_face(), Some(&dir), Some("1"));
assert!(matches!(&r.result, Err(Error::MissingScripts { scripts, .. }) if scripts == &["Latn"]), "{:?}", r.result);
let r = run(Embed::new(), Some(&dir), Some("1"));
assert_eq!(r.result.as_ref().unwrap(), &["Noto Sans Arabic Regular"]);
// A served table carries no roles, so it leaves the face out.
let r = run(Embed::new().tab_face().serve(scratch.0.join("served"), "fonts/"), Some(&dir), Some("1"));
assert_eq!(r.result.as_ref().unwrap(), &["Noto Sans Arabic Regular"]);
assert!(warnings(&r).iter().any(|w| w.contains("not serving the tab-title face")), "{:?}", r.cargo);
// Only tab titles draw in the face, so it covers none of the characters of a checked text.
std::fs::write(dir.join("fonts/condensed.ttf"), tiny_font(&[(0x41, 0x5A, None), (0x4E00, 0x4E00, None)], &[])).unwrap();
let text = scratch.0.join("text.ftl");
std::fs::write(&text, "x = \u{4E00}\n").unwrap();
let r = run(Embed::new().tab_face().check_text([&text]), Some(&dir), Some("1"));
assert_eq!(r.result.as_ref().unwrap(), &["Noto Sans Arabic Regular", "Noto Sans Condensed SemiBold"]);
assert!(warnings(&r).iter().any(|w| w.contains("1 character no embedded face covers (\u{4E00})")), "{:?}", r.cargo);
// No row for the face, or no latin manifest at all: the other faces and a warning, even when required.
std::fs::write(&latin, row("Inter", "SemiBold", "fonts/inter.ttf")).unwrap();
for required in [None, Some("1")] {
let r = run(Embed::new().tab_face(), Some(&dir), required);
assert_eq!(r.result.as_ref().unwrap(), &["Noto Sans Arabic Regular"]);
assert!(warnings(&r).iter().any(|w| w.contains("has no Noto Sans Condensed SemiBold row")), "{:?}", r.cargo);
}
std::fs::remove_file(&latin).unwrap();
for required in [None, Some("1")] {
let r = run(Embed::new().tab_face(), Some(&dir), required);
assert_eq!(r.result.as_ref().unwrap(), &["Noto Sans Arabic Regular"]);
assert!(warnings(&r).iter().any(|w| w.contains("latin-manifest.txt does not exist")), "{:?}", r.cargo);
assert!(r.cargo.iter().any(|l| l == &format!("cargo::rerun-if-changed={}", dir.join("fonts").display())), "{:?}", r.cargo);
}
// A manifest line that does not parse, or a row whose file is missing.
for broken in ["Noto Sans | Condensed SemiBold | fonts/condensed.ttf\n".to_owned(), row("Noto Sans", "Condensed SemiBold", "fonts/gone.ttf")] {
std::fs::write(&latin, &broken).unwrap();
let r = run(Embed::new().tab_face(), Some(&dir), None);
assert_eq!(r.result.as_ref().unwrap(), &["Noto Sans Arabic Regular"], "{broken}");
assert!(warnings(&r).iter().any(|w| w.contains("not embedding the tab-title face")), "{broken}: {:?}", r.cargo);
let r = run(Embed::new().tab_face(), Some(&dir), Some("1"));
assert!(matches!(r.result, Err(Error::Parse { .. } | Error::Read { .. })), "{broken}: {:?}", r.result);
}
// The build reruns when the missing file is added: it watches the folder the file would be in.
let r = run(Embed::new().tab_face(), Some(&dir), None);
assert!(r.cargo.iter().any(|l| l == &format!("cargo::rerun-if-changed={}", dir.join("fonts").display())), "{:?}", r.cargo);
}
+7 -2
View File
@@ -19,6 +19,8 @@
use std::cmp::Reverse;
use std::collections::VecDeque;
use std::hash::Hash;
#[cfg(not(target_arch = "wasm32"))]
use std::sync::OnceLock;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Condvar, Mutex, MutexGuard};
use std::thread::{self, ThreadId};
@@ -94,14 +96,17 @@ pub enum QueueOrder {
impl QueueOptions {
/// Lanes for this machine: the number of cores less one, at least 2 and at most 8 (4 when
/// the core count is unknown); 0 on wasm32.
/// the core count is unknown); 0 on wasm32. The core count is read once per process.
// lightcraft: crates/preview/src/pool.rs:104 `default_threads` (cores − 1 clamped to 2..=8;
// ours is 0 on wasm32 instead of 1, because wasm runs jobs only through `run_inline`).
pub fn default_lanes() -> usize {
#[cfg(target_arch = "wasm32")]
return 0;
#[cfg(not(target_arch = "wasm32"))]
thread::available_parallelism().map_or(4, |n| n.get().saturating_sub(1).clamp(2, 8))
{
static LANES: OnceLock<usize> = OnceLock::new();
*LANES.get_or_init(|| thread::available_parallelism().map_or(4, |n| n.get().saturating_sub(1).clamp(2, 8)))
}
}
}
+2 -1
View File
@@ -310,7 +310,8 @@ impl Component for Histogram<'_> {
let accent = super::data::color32(colors.data.selection);
let warn = cx.tone(craft_theme::variant::Tone::Warn);
HistogramStyle {
metrics: Metrics::new().min_size(Vec2::new(cx.tokens.size.plot.width, tall)),
// The width's floor is `measure`'s (`picture_width`), which a narrow room may take below the plot width.
metrics: Metrics::new().min_size(Vec2::new(0.0, tall)),
focus: cx.focus_look(),
caption: TextLook::new(TypeRole::Caption, Stateful::new(cx.color(colors.text.normal))),
stale: IconLook::new(cx.tokens.size.icon.sm, Stateful::new(warn)),
+26 -5
View File
@@ -26,7 +26,9 @@ pub(crate) use row::FX_BADGE;
use std::cell::RefCell;
use craft_ui::contract::{Bind, CommandSet as _, Commands as _, NoValue, Outcome, Show, ShowContainer as _, Tracked};
use craft_ui::contract::{
Bind, CommandSet as _, Commands as _, Entry, MemoProps, MemoView, NoValue, Outbox, Outcome, Show, ShowContainer as _, Tracked,
};
use craft_ui::layout_components::Stack;
use craft_ui::list::ListWords;
use craft_ui::menu::MenuRow;
@@ -43,9 +45,9 @@ use std::marker::PhantomData;
use super::filter::{FilterBy, LayerFilter, LayerFilterBar};
use super::options::LayersSettings;
use super::rows::BlendRows;
use super::rows::{BlendRows, LayerPropertyEdit};
use super::thumbs::LayerThumb;
use super::tree::{LayerInfo, LayerRowKey, LayerTree};
use super::tree::{LayerInfo, LayerProperties, LayerRowKey, LayerTree};
craft_ui::words! {
/// The words of the Layers panel's rows, footer and menus. Patterns with `{row}`, `{layer}` and
@@ -503,8 +505,10 @@ impl<'a, T: LayerTree> LayersPanel<'a, T> {
let properties = tree.properties();
let modes =
tree.blend_modes(properties.as_ref().is_some_and(|p| p.group), properties.as_ref().map_or("normal", |p| &p.blend_key));
let out = BlendRows::new(properties.as_ref(), &modes).show(ui);
events.borrow_mut().extend(out.events.into_iter().map(LayersEvent::Properties));
let mut edits = Vec::new();
let props = BlendProps { properties: properties.as_ref(), modes: &modes, edits: Outbox::new(&mut edits) };
let _ = MemoView::new("layers-blend-rows", props, show_blend_rows).show(ui);
events.borrow_mut().extend(edits.into_iter().map(LayersEvent::Properties));
}
})
.footer(|ui, _| match host_footer.as_mut() {
@@ -539,3 +543,20 @@ impl<'a, T: LayerTree> LayersPanel<'a, T> {
LayersOutput { events, drop_preview, hovered, focused, response: shown.output }
}
}
/// The header's blend, Opacity, Fill and lock rows as a memoized view: they show the active layer's properties and
/// the modes it offers, so a frame whose pointer is over the rows or elsewhere replays them instead of running every
/// control. They were about half of the panel's time in such a frame (photocraft#17131). Input that reaches them (a
/// press, a scrub, the open blend list) runs them.
#[derive(MemoProps)]
struct BlendProps<'a> {
properties: Option<&'a LayerProperties>,
modes: &'a [Entry<String>],
edits: Outbox<'a, LayerPropertyEdit>,
}
fn show_blend_rows(props: &mut BlendProps<'_>, ui: &mut Ui) {
for edit in BlendRows::new(props.properties, props.modes).show(ui).events {
props.edits.send(edit);
}
}
+2 -2
View File
@@ -360,7 +360,7 @@ pub struct MaskInfo {
}
/// A layer's locks. Start from `LayerLocks::default()` (nothing locked) and set the fields that are on.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PlainData)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PlainData, craft_ui::contract::MemoProps)]
#[non_exhaustive]
pub struct LayerLocks {
/// Lock transparent pixels.
@@ -536,7 +536,7 @@ impl SubRow {
}
/// The active layer's properties, for [`BlendRows`](super::rows::BlendRows).
#[derive(Clone, Debug, PartialEq)]
#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps)]
#[non_exhaustive]
pub struct LayerProperties {
/// The blend mode's key.
+35
View File
@@ -66,6 +66,13 @@ impl Rig {
(count(MemoRun::Ran), count(MemoRun::Replayed))
}
/// The runs and replays in the last frame of the memoized views whose type name holds `name`.
fn view_runs(&self, name: &str) -> (u32, u32) {
let runs = last_frame_memo_runs(self.fixture.ctx());
let count = |wanted: MemoRun| runs.iter().filter(|(ty, _, run)| ty.contains(name) && *run == wanted).count() as u32;
(count(MemoRun::Ran), count(MemoRun::Replayed))
}
/// One frame with no input, after the edit of the trial.
fn frame(&mut self) -> &mut Self {
self.fixture.frame(Vec::new());
@@ -164,3 +171,31 @@ fn a_pointer_move_beside_the_panel_replays_it_and_a_modifier_runs_it() {
fixture.frame(Vec::new());
assert_eq!(runs(&fixture), (0, 1), "and it replays while Alt stays held");
}
/// The pointer moving over the rows runs the panel but replays its blend, Opacity, Fill and lock rows: they show only the
/// active layer's properties, and running them was about half of the panel's time in such a frame (photocraft#17131).
#[trial]
fn a_pointer_over_the_rows_replays_the_blend_rows() {
let mut rig = rig(FakeLayers::fifty());
for step in 0..3 {
rig.fixture.frame(vec![pointer::moved(egui::Pos2::new(100.0, 300.0 + step as f32))]);
assert_eq!(rig.host_runs().0, 1, "step {step}: the pointer runs the panel");
assert_eq!(rig.view_runs("BlendProps"), (0, 1), "step {step}: the blend rows replay");
}
}
/// A new blend mode on the active layer runs the blend rows, so they never show a stale value.
#[trial]
fn the_active_layers_blend_mode_runs_the_blend_rows() {
let mut rig = rig(FakeLayers::fifty());
{
let mut tree = rig.tree.borrow_mut();
let active = tree.selection.active.expect("the sample has an active layer");
let layer = tree.layers.iter_mut().find(|layer| layer.id == active).expect("the active layer is listed");
layer.info.blend_key = String::from("multiply");
}
rig.frame();
assert_eq!(rig.view_runs("BlendProps").0, 1, "the edit runs the blend rows");
rig.frame();
assert_eq!(rig.host_runs(), (0, 1), "and the panel replays after it");
}
+5 -2
View File
@@ -137,7 +137,9 @@ app translates. The dialog never opens a file dialog or touches the file system.
## Windows, Linux and web: the in-window bar
`MenuBarUi` draws a laid-out bar and returns the titles' rect (`MenuBarOutput`). Show it inside a
`MenuBarUi` draws a laid-out bar and returns the titles' rect and the width every title takes side by
side (`MenuBarOutput`). A host that puts controls after the titles on the same row compares that
width with the room it leaves the bar. Show it inside a
`Stack` (a top panel's body) or the title bar's row: there the titles that don't fit its room fold
into "…".
Each item is a command row: its enabled state, check mark and chord follow the command in the
@@ -227,7 +229,8 @@ While a menu is open, a click or Escape in the window closes it and does not rea
canvas gesture, no tool action); pointer moves pass through. Only one click is kept this way
until the menu reports closed, so a menu wrongly reported open costs one click. Menu updates wait
until the menu closes; the end of tracking wakes egui, and that frame applies them. A rebuild that
fails keeps the menus as they were.
fails keeps the menus as they were, and the same menus are tried once more a second later, with no
input needed (`RebuildRetry`). When that fails too, the next change to the menus tries again.
AppKit's `NSMenuDidBeginTracking` and `NSMenuDidEndTracking` notifications say whether a menu is
open (`craft_window::native_menu::menu_tracking()`, safe from any thread). Each begin comes back
+8 -5
View File
@@ -48,11 +48,11 @@ pub(crate) fn keymap_platform(target: Target, os: Platform) -> Platform {
/// A replay at another place moves the titles' rect with the bar.
impl craft_ui::runtime::Shift for MenuBarOutput {
fn shifted(&self, by: &egui::RecordShift) -> Self {
MenuBarOutput { titles: by.rect(self.titles), opened: self.opened }
MenuBarOutput { titles: by.rect(self.titles), natural: self.natural, opened: self.opened }
}
fn snapped(&self, to: &Self, within: f32) -> Self {
MenuBarOutput { titles: craft_ui::runtime::Shift::snapped(&self.titles, &to.titles, within), opened: self.opened }
MenuBarOutput { titles: craft_ui::runtime::Shift::snapped(&self.titles, &to.titles, within), natural: self.natural, opened: self.opened }
}
}
@@ -63,6 +63,9 @@ pub struct MenuBarOutput {
/// The menu titles alone, without the room the bar leaves after them
/// ([`craft_ui::menu::MenuBarOutput::titles`]).
pub titles: Rect,
/// The width every title takes side by side with none in "…", whatever room the bar had
/// ([`craft_ui::menu::MenuBarOutput::natural`]). Zero when the bar shows nothing.
pub natural: f32,
/// True in the one pass where a menu of the bar opened while none was open
/// ([`craft_ui::menu::MenuBarOutput::opened`]).
pub opened: bool,
@@ -167,7 +170,7 @@ impl<'a> MenuBarUi<'a> {
icons: self.icons,
compact: self.compact,
};
MemoView::new("menu-bar", props, show_bar).show(ui).unwrap_or(MenuBarOutput { titles: Rect::NOTHING, opened: false })
MemoView::new("menu-bar", props, show_bar).show(ui).unwrap_or(MenuBarOutput { titles: Rect::NOTHING, natural: 0.0, opened: false })
}
}
@@ -214,8 +217,8 @@ fn show_bar(props: &mut BarProps<'_>, ui: &mut Ui) -> MenuBarOutput {
if let Some(menu) = props.help {
bar = bar.help(MenuHelp::new(menu, &entries));
}
let out = bar.show(ui);
MenuBarOutput { titles: out.titles, opened: out.opened }
let shown = bar.show(ui);
MenuBarOutput { titles: shown.titles, natural: shown.natural, opened: shown.opened }
}
/// What the kept text of a bar is made of: the model, the platform that names its shortcuts, the preferred mnemonics,
Loaded 100 of 349 files, more files were not shown because too many files have changed in this diff. Show more