mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-30 18:27:00 +01:00
Merge remote-tracking branch 'origin/main' into fix-1428
# Conflicts: # crates/testkit/Cargo.toml
This commit is contained in:
commit
780bfa081e
377 files changed
+33998
-3582
No files matched your search
@@ -3,9 +3,9 @@ name: Shared audio
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths: ["crates/audio/**", "crates/media/**", "crates/media-testkit/**", "scripts/fetch-opus-vectors.sh", "Cargo.toml", "Cargo.lock", ".github/workflows/audio.yml"]
|
||||
paths: ["crates/audio/**", "crates/media/**", "crates/media-testkit/**", "crates/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"]
|
||||
paths: ["crates/audio/**", "crates/media/**", "crates/media-testkit/**", "crates/testkit/**", "scripts/fetch-opus-vectors.sh", "Cargo.toml", "Cargo.lock", ".github/workflows/audio.yml"]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
|
||||
@@ -3,9 +3,9 @@ name: Shared media
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths: ["crates/media/**", "crates/media-testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/media.yml"]
|
||||
paths: ["crates/media/**", "crates/media-testkit/**", "crates/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"]
|
||||
paths: ["crates/media/**", "crates/media-testkit/**", "crates/testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/media.yml"]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
|
||||
@@ -3,9 +3,9 @@ name: Shared video
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths: ["crates/video/**", "crates/media/**", "crates/media-testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/video.yml"]
|
||||
paths: ["crates/video/**", "crates/media/**", "crates/media-testkit/**", "crates/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"]
|
||||
paths: ["crates/video/**", "crates/media/**", "crates/media-testkit/**", "crates/testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/video.yml"]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
|
||||
@@ -2,6 +2,17 @@
|
||||
|
||||
All crates share the workspace version. See [the versioning policy](docs/versioning.md).
|
||||
|
||||
## Unreleased
|
||||
|
||||
### StencilCraft document model
|
||||
|
||||
- Geometry is stored once in `Document.shapes`. Organizational layers reference shape IDs
|
||||
through `Layer.members`, and the independent, ordered `Document.operations` hold production
|
||||
passes with their own `OperationSettings` and shape memberships. Guide operations are non-output.
|
||||
- The native header now uses format version 2. This pre-release format supersedes the earlier
|
||||
schema: readers reject version 1 and other unsupported versions. Builds predating this change
|
||||
cannot open version 2 files.
|
||||
|
||||
## v0.1.0 — 2026-10-12
|
||||
|
||||
First coordinated Git release of craft-libs. Applications can pin a named baseline instead of
|
||||
|
||||
Generated
+56
-14
@@ -1870,6 +1870,7 @@ dependencies = [
|
||||
"craft-metafile",
|
||||
"craft-midi",
|
||||
"craft-mime",
|
||||
"craft-nightly",
|
||||
"craft-odf",
|
||||
"craft-ods",
|
||||
"craft-offcrypto",
|
||||
@@ -1904,6 +1905,7 @@ dependencies = [
|
||||
"craft-pst",
|
||||
"craft-quit",
|
||||
"craft-raster-codecs",
|
||||
"craft-raster3d",
|
||||
"craft-raw",
|
||||
"craft-review",
|
||||
"craft-rtf",
|
||||
@@ -2798,6 +2800,7 @@ dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"skrifa 0.47.0",
|
||||
"write-fonts 0.54.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2957,6 +2960,7 @@ name = "craft-gpu-wgpu"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"craft-gpu",
|
||||
"craft-gpu-device",
|
||||
"craft-gpu-providers",
|
||||
"pollster 0.4.0",
|
||||
"wgpu",
|
||||
@@ -3252,9 +3256,11 @@ dependencies = [
|
||||
"craft-ui-macros",
|
||||
"craft-xml",
|
||||
"egui",
|
||||
"global-hotkey",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
"x11rb",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3503,6 +3509,14 @@ dependencies = [
|
||||
"proptest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-nightly"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"uds_windows",
|
||||
"winsafe",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-odf"
|
||||
version = "0.1.0"
|
||||
@@ -3794,6 +3808,7 @@ dependencies = [
|
||||
"craft-docpath",
|
||||
"craft-host",
|
||||
"craft-i18n",
|
||||
"craft-testkit",
|
||||
"craft-theme",
|
||||
"fmv-macos-events",
|
||||
"futures-lite",
|
||||
@@ -4008,6 +4023,14 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-raster3d"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"rayon",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-raw"
|
||||
version = "0.1.0"
|
||||
@@ -4345,6 +4368,7 @@ name = "craft-testkit"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"log",
|
||||
"png 0.18.1",
|
||||
"proptest",
|
||||
"rustix 1.1.6",
|
||||
@@ -4739,6 +4763,7 @@ dependencies = [
|
||||
"base64 0.22.1",
|
||||
"chrono",
|
||||
"craft-host",
|
||||
"craft-testkit",
|
||||
"craft-theme",
|
||||
"craft-ui",
|
||||
"dunce",
|
||||
@@ -5726,7 +5751,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "ecolor"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"emath",
|
||||
@@ -5782,7 +5807,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "eframe"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytemuck",
|
||||
@@ -5817,7 +5842,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443"
|
||||
dependencies = [
|
||||
"accesskit",
|
||||
"ahash",
|
||||
@@ -5836,7 +5861,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui-wgpu"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytemuck",
|
||||
@@ -5855,7 +5880,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui-winit"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443"
|
||||
dependencies = [
|
||||
"block2 0.6.2",
|
||||
"bytemuck",
|
||||
@@ -5875,7 +5900,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui_glow"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"egui",
|
||||
@@ -5888,7 +5913,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui_kittest"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443"
|
||||
dependencies = [
|
||||
"eframe",
|
||||
"egui",
|
||||
@@ -5965,7 +5990,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "emath"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
]
|
||||
@@ -6038,7 +6063,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "epaint"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytemuck",
|
||||
@@ -6064,7 +6089,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "epaint_default_fonts"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443"
|
||||
|
||||
[[package]]
|
||||
name = "equator"
|
||||
@@ -6935,6 +6960,23 @@ version = "0.3.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b"
|
||||
|
||||
[[package]]
|
||||
name = "global-hotkey"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "adda8c76a5139df3bae0eb0413c2cd746f66594e0bb66231a4daa0be3172da70"
|
||||
dependencies = [
|
||||
"crossbeam-channel",
|
||||
"keyboard-types",
|
||||
"objc2 0.6.5",
|
||||
"objc2-app-kit 0.3.2",
|
||||
"once_cell",
|
||||
"thiserror 2.0.21",
|
||||
"windows-sys 0.59.0",
|
||||
"x11rb",
|
||||
"xkeysym",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "glow"
|
||||
version = "0.17.0"
|
||||
@@ -15412,19 +15454,19 @@ dependencies = [
|
||||
[[patch.unused]]
|
||||
name = "egui_demo_lib"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443"
|
||||
|
||||
[[patch.unused]]
|
||||
name = "egui_extras"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443"
|
||||
|
||||
[[patch.unused]]
|
||||
name = "egui_inspection"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443"
|
||||
|
||||
[[patch.unused]]
|
||||
name = "egui_system_font_provider"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443"
|
||||
+16
-14
@@ -183,6 +183,7 @@ craft-media-testkit = { path = "crates/media-testkit" }
|
||||
craft-midi = { path = "crates/midi" }
|
||||
craft-sf2 = { path = "crates/sf2" }
|
||||
craft-mime = { path = "crates/mime" }
|
||||
craft-nightly = { path = "crates/nightly" }
|
||||
craft-odf = { path = "crates/odf" }
|
||||
craft-ods = { path = "crates/ods" }
|
||||
craft-prc = { path = "crates/prc" }
|
||||
@@ -235,6 +236,7 @@ craft-text = { path = "crates/text" }
|
||||
craft-tcraft = { path = "crates/tcraft" }
|
||||
craft-texture = { path = "crates/texture" }
|
||||
craft-pbr = { path = "crates/pbr" }
|
||||
craft-raster3d = { path = "crates/raster3d" }
|
||||
craft-tga = { path = "crates/tga" }
|
||||
craft-timeline = { path = "crates/timeline" }
|
||||
craft-tiff = { path = "crates/tiff" }
|
||||
@@ -326,20 +328,20 @@ linesweeper = { path = "vendor/linesweeper" }
|
||||
vello_common = { path = "vendor/vello_common" }
|
||||
vello_cpu = { path = "vendor/vello_cpu" }
|
||||
kurbo = { path = "vendor/kurbo" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
|
||||
|
||||
# symphonia's FLAC decoder restores LPC samples as `residual + (prediction as i32)`. In a valid
|
||||
|
||||
@@ -486,3 +486,11 @@ The Y4M range-backed source in crates/media-source/src/y4m.rs adapts FilmCraft's
|
||||
original implementation (3f137a7ed420cac79b32145f5243b7f98b31f71c), licensed
|
||||
MIT OR Apache-2.0. Source notice retained:
|
||||
Copyright (c) 2026 ArtCraft Team and the FilmCraft contributors.
|
||||
|
||||
The CPU renderer in crates/raster3d (rasterizer, shading, shadow maps, resolve and encoding) and
|
||||
the copy of it in crates/raster3d/tests/it/reference/ are moved from:
|
||||
- EffectCraft, crates/render/src/three_d/adv.rs, adv/raster.rs, adv/shade.rs and adv/scene.rs,
|
||||
revision 2f16feb12f4d5ef601b35b2858f9c9a87077f61e, licensed under the MIT License or the Apache
|
||||
License, Version 2.0, at your option.
|
||||
https://github.com/storytold/effectcraft
|
||||
Copyright (c) 2026 ArtCraft Team and the EffectCraft contributors.
|
||||
@@ -394,6 +394,11 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
|
||||
- [`craft-quit`](crates/quit/README.md): native macOS quit, a window close held for unsaved
|
||||
documents, the Quit menu item id and the unsaved-changes question one document at a time
|
||||
(`CloseGuard`). The prompt and the saving stay in each app.
|
||||
- [`craft-raster3d`](crates/raster3d/README.md): a CPU renderer for a prepared 3D scene, from
|
||||
EffectCraft: clipping, rasterization with a top-left fill rule, physically based shading,
|
||||
shadow maps, a box resolve of supersampled output and sRGB encoding. Scenes and sizes are
|
||||
checked before the target is allocated. `Limits` bounds sizes and coverage work. Preparation can
|
||||
allocate clipping and triangle buffers before a work-limit error. Building the scene stays in each app.
|
||||
- [`craft-rtf`](crates/rtf/README.md): Rich Text Format: a tokenizer, text decoding in the file's code pages
|
||||
(`\uN`, `\'hh`, single-byte and East Asian multibyte pages), escaping and dates, and a reader and writer
|
||||
for a small neutral model (paragraphs, character formatting, outline levels, tables).
|
||||
@@ -436,7 +441,8 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
|
||||
test when the variable the caller names is `1`. Any other value of that variable except empty fails
|
||||
the test as a configuration error. Its `corpus` module (the `corpus` feature) checks a corpus folder
|
||||
against a pinned SHA-256 list. Its `fixtures` module (native targets only) generates test fixtures
|
||||
under `target/fixtures` and publishes each one under a lock. Not published.
|
||||
under `target/fixtures` and publishes each one under a lock. Its `temp` module makes a new test folder, private to the user on
|
||||
Unix, that is removed with its contents when dropped (best effort). Not published.
|
||||
- [`craft-text`](crates/text/README.md): text processing below the composer. Its `hyphen` module finds
|
||||
hyphenation points, with a bundled US English dictionary and patterns and optional hypher patterns
|
||||
for 47 more languages (one cargo feature each). With `ui`, the canvas text editor, Character and
|
||||
|
||||
@@ -241,6 +241,35 @@ fn temp_name_format_is_valid() {
|
||||
assert!(name.ends_with(".craft_tmp"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn temp_name_keeps_long_non_latin_names_under_the_name_limit() {
|
||||
// 62 four-byte characters plus ".json" is a valid 253-byte name.
|
||||
let file = format!("{}.json", "\u{1F600}".repeat(62));
|
||||
assert_eq!(file.len(), 253);
|
||||
let name = temp_name(&file);
|
||||
assert!(name.len() <= 255, "{} bytes", name.len());
|
||||
assert!(name.starts_with(&format!(".{}.", "\u{1F600}".repeat(TEMP_STEM_BYTES / 4))));
|
||||
assert!(name.ends_with(".craft_tmp"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn temp_name_cuts_at_a_character_boundary() {
|
||||
// TEMP_STEM_BYTES - 1 ASCII bytes, then a two-byte character that would end one byte past the limit.
|
||||
let file = format!("{}\u{e9}tail", "a".repeat(TEMP_STEM_BYTES - 1));
|
||||
let name = temp_name(&file);
|
||||
assert!(name.starts_with(&format!(".{}.", "a".repeat(TEMP_STEM_BYTES - 1))));
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn saves_a_long_non_latin_name() {
|
||||
let d = TempDir::new("long-name");
|
||||
let p = d.0.join(format!("{}.json", "\u{1F600}".repeat(62)));
|
||||
assert!(atomic_write(&p, b"saved").is_ok());
|
||||
assert_eq!(std::fs::read(&p).ok(), Some(b"saved".to_vec()));
|
||||
assert_no_temp(&d.0);
|
||||
}
|
||||
|
||||
/// What a [`Planting`] filesystem puts at a stage name just before the stage is created there.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum Obstacle {
|
||||
|
||||
@@ -128,7 +128,9 @@ fn a_refusal_waiting_at_sign_in_is_the_reason_connect_gives() {
|
||||
reader.read_line(&mut line).ok().filter(|&read| read > 0).map(|_| line)
|
||||
});
|
||||
let stream = std::net::TcpStream::connect(addr).unwrap();
|
||||
stream.set_read_timeout(Some(std::time::Duration::from_secs(5))).unwrap();
|
||||
// A hang guard only: the server thread writes the refusal without waiting on a timer, so a run that works never
|
||||
// reaches the limit.
|
||||
stream.set_read_timeout(Some(std::time::Duration::from_secs(60))).unwrap();
|
||||
assert!(stream.peek(&mut [0]).unwrap() > 0, "the refusal is waiting before the sign-in");
|
||||
let signed = ControlClient::over(stream).unwrap().sign_in(TOKEN);
|
||||
assert_eq!(signed.err(), Some(ConnectError::Refused("connection limit reached".into())));
|
||||
|
||||
@@ -141,8 +141,8 @@ pub enum Reply {
|
||||
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.
|
||||
/// Which open of the dialog the request confirmed ([`DialogHost::held_state_with_open_serial`]):
|
||||
/// a later open of the same dialog, or another dialog with its ID, is not that one.
|
||||
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.
|
||||
@@ -343,13 +343,12 @@ impl ControlChannel {
|
||||
/// 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()}),
|
||||
let current = host.held_state_with_open_serial(*dialog).filter(|(serial, _)| serial == open);
|
||||
let answer = match current {
|
||||
None => json!({"ok": false, "error": "the dialog closed while its OK waited for the app's answer"}),
|
||||
Some((_, Some(HeldOk::Waiting))) => return true,
|
||||
Some((_, Some(HeldOk::Accepted))) => json!({"ok": true, "result": null}),
|
||||
Some((_, Some(HeldOk::Refused(reason)))) => json!({"ok": false, "error": reason.as_str()}),
|
||||
_ => json!({"ok": false, "error": "the app refused OK"}),
|
||||
};
|
||||
let _ = reply.send(answer);
|
||||
|
||||
@@ -65,8 +65,11 @@ pub fn dialog_reply(host: &mut DialogHost, ctx: &Context, method: &str, params:
|
||||
_ => 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)?))) {
|
||||
let held = named.filter(|_| method == "ui.dialog.confirm" && result.is_ok()).and_then(|id| {
|
||||
let (open, state) = host.held_state_with_open_serial(id)?;
|
||||
matches!(state, Some(HeldOk::Waiting)).then_some((id, open))
|
||||
});
|
||||
Some(match held {
|
||||
Some((dialog, open)) => Reply::AfterHeldOk { dialog, open, refused },
|
||||
None => Reply::from_result(result),
|
||||
})
|
||||
|
||||
@@ -89,6 +89,10 @@ fn a_finished_job_answers_only_its_own_waiters() {
|
||||
|
||||
const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
|
||||
|
||||
/// How long a test waits for a reply, a close or a request before it fails as hung. A server that works sends each
|
||||
/// one without waiting on a timer, so the result does not depend on this limit or on how fast the machine runs.
|
||||
const HANG: Duration = Duration::from_secs(60);
|
||||
|
||||
fn read_json(reader: &mut impl BufRead) -> Option<Value> {
|
||||
let mut line = String::new();
|
||||
(reader.read_line(&mut line).ok()? > 0).then(|| serde_json::from_str(&line).expect("a JSON line"))
|
||||
@@ -116,9 +120,9 @@ fn an_unauthenticated_connection_is_closed_at_the_deadline_whatever_it_sends() {
|
||||
let options = ServeOptions { auth_deadline: Duration::from_secs(10), clock, ended: Some(ended) };
|
||||
let (rx, server) = server::serve_with(TcpListener::bind("127.0.0.1:0").expect("bound"), TOKEN.into(), host(), options).expect("started");
|
||||
let mut stream = TcpStream::connect(server.addr).expect("connected");
|
||||
stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout");
|
||||
stream.set_read_timeout(Some(HANG)).expect("timeout");
|
||||
let mut reader = BufReader::new(stream.try_clone().expect("cloned"));
|
||||
clock_read.recv_timeout(Duration::from_secs(5)).expect("the connection set its deadline");
|
||||
clock_read.recv_timeout(HANG).expect("the connection set its deadline");
|
||||
// Blank lines and the start of a line, sent while the deadline is ahead: none is a frame the handshake refuses.
|
||||
stream.write_all(b"\n \n ").expect("written");
|
||||
*at.lock().expect("the clock") = start + Duration::from_secs(10);
|
||||
@@ -176,9 +180,9 @@ fn serve_counting_ends() -> (Receiver<ControlRequest>, server::Listening, Receiv
|
||||
fn nothing_more_dispatched(rx: &Receiver<ControlRequest>, server: server::Listening, ended: &Receiver<()>, connections: usize) -> bool {
|
||||
drop(server);
|
||||
for _ in 0..connections {
|
||||
ended.recv_timeout(Duration::from_secs(5)).expect("a connection ended");
|
||||
ended.recv_timeout(HANG).expect("a connection ended");
|
||||
}
|
||||
rx.recv_timeout(Duration::from_secs(5)).err() == Some(RecvTimeoutError::Disconnected)
|
||||
rx.recv_timeout(HANG).err() == Some(RecvTimeoutError::Disconnected)
|
||||
}
|
||||
|
||||
/// With `MAX_CONNECTIONS` connections open, the next one is told `connection limit reached` and closed; once one of
|
||||
@@ -188,7 +192,7 @@ fn connections_past_the_limit_are_refused_with_the_reason() {
|
||||
let (rx, server, ended) = serve_counting_ends();
|
||||
let connect = || {
|
||||
let stream = TcpStream::connect(server.addr).expect("connected");
|
||||
stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout");
|
||||
stream.set_read_timeout(Some(HANG)).expect("timeout");
|
||||
let reader = BufReader::new(stream.try_clone().expect("cloned"));
|
||||
(stream, reader)
|
||||
};
|
||||
@@ -202,7 +206,7 @@ fn connections_past_the_limit_are_refused_with_the_reason() {
|
||||
|
||||
drop(open.pop());
|
||||
// The server frees the place when it reads the close; a new connection is served once it has.
|
||||
ended.recv_timeout(Duration::from_secs(5)).expect("the closed connection ended");
|
||||
ended.recv_timeout(HANG).expect("the closed connection ended");
|
||||
let (mut stream, mut reader) = connect();
|
||||
writeln!(stream, "{}", json!({"id": 1, "method": "auth", "params": {"token": TOKEN}})).expect("written");
|
||||
let served = read_json(&mut reader).expect("a reply");
|
||||
@@ -222,7 +226,7 @@ fn a_refused_first_frame_closes_the_connection() {
|
||||
for (first, id) in [("not json".to_owned(), Value::Null), (json!({"id": 4, "method": "auth", "params": {"token": wrong}}).to_string(), json!(4))]
|
||||
{
|
||||
let mut stream = TcpStream::connect(server.addr).expect("connected");
|
||||
stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout");
|
||||
stream.set_read_timeout(Some(HANG)).expect("timeout");
|
||||
let mut reader = BufReader::new(stream.try_clone().expect("cloned"));
|
||||
writeln!(stream, "{first}").expect("written");
|
||||
assert_eq!(read_json(&mut reader).expect("a refusal"), json!({"id": id, "ok": false, "error": "authentication required"}), "{first}");
|
||||
@@ -240,7 +244,7 @@ fn a_browser_post_never_reaches_the_app() {
|
||||
// The server's clock stands still, so the close comes from the refusal, not the deadline.
|
||||
let (rx, server, ended) = serve_counting_ends();
|
||||
let mut stream = TcpStream::connect(server.addr).expect("connected");
|
||||
stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout");
|
||||
stream.set_read_timeout(Some(HANG)).expect("timeout");
|
||||
let mut reader = BufReader::new(stream.try_clone().expect("cloned"));
|
||||
let body = format!("{}\n{}\n", json!({"id": 1, "method": "auth", "params": {"token": TOKEN}}), json!({"id": 2, "method": "test.ping"}));
|
||||
write!(stream, "POST / HTTP/1.1\r\n").expect("written");
|
||||
@@ -265,7 +269,7 @@ fn a_browser_post_never_reaches_the_app() {
|
||||
fn an_over_long_request_is_refused_and_closes_the_connection() {
|
||||
let (rx, server) = server::listen(0, TOKEN.into(), host()).expect("started");
|
||||
let mut stream = TcpStream::connect(server.addr).expect("connected");
|
||||
stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout");
|
||||
stream.set_read_timeout(Some(HANG)).expect("timeout");
|
||||
let mut reader = BufReader::new(stream.try_clone().expect("cloned"));
|
||||
writeln!(stream, "{}", json!({"id": 1, "method": "auth", "params": {"token": TOKEN}})).expect("written");
|
||||
assert_eq!(read_json(&mut reader).expect("a reply")["ok"], true);
|
||||
@@ -281,7 +285,7 @@ fn an_over_long_request_is_refused_and_closes_the_connection() {
|
||||
/// Answers the next request, which must be `test.ping`, with `pong`.
|
||||
fn answer_one_ping(rx: Receiver<ControlRequest>) -> std::thread::JoinHandle<()> {
|
||||
std::thread::spawn(move || {
|
||||
let req = rx.recv_timeout(Duration::from_secs(5)).expect("a request");
|
||||
let req = rx.recv_timeout(HANG).expect("a request");
|
||||
assert_eq!(req.method, "test.ping");
|
||||
let pong: ControlResponse = json!({"ok": true, "result": "pong"});
|
||||
req.reply.send(pong).expect("replied");
|
||||
@@ -291,7 +295,7 @@ fn answer_one_ping(rx: Receiver<ControlRequest>) -> std::thread::JoinHandle<()>
|
||||
/// Authenticates with the one-frame token, sends `test.ping` and returns its reply.
|
||||
fn ping(addr: SocketAddr) -> Value {
|
||||
let mut stream = TcpStream::connect(addr).expect("connected");
|
||||
stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout");
|
||||
stream.set_read_timeout(Some(HANG)).expect("timeout");
|
||||
let mut reader = BufReader::new(stream.try_clone().expect("cloned"));
|
||||
writeln!(stream, "{}", json!({"id": 1, "method": "auth", "params": {"token": TOKEN}})).expect("written");
|
||||
assert_eq!(read_json(&mut reader).expect("a reply")["ok"], true);
|
||||
@@ -326,7 +330,7 @@ fn a_challenge_authenticated_connection_is_served() {
|
||||
let (rx, server) = server::listen(0, TOKEN.into(), host()).expect("started");
|
||||
let handler = answer_one_ping(rx);
|
||||
let mut stream = TcpStream::connect(server.addr).expect("connected");
|
||||
stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout");
|
||||
stream.set_read_timeout(Some(HANG)).expect("timeout");
|
||||
let mut reader = BufReader::new(stream.try_clone().expect("cloned"));
|
||||
let client_nonce = generate_nonce().expect("a nonce");
|
||||
writeln!(stream, "{}", json!({"id": 1, "method": CHALLENGE_METHOD, "params": {"clientNonce": client_nonce}})).expect("written");
|
||||
@@ -376,7 +380,7 @@ fn the_documented_capture_client_sends_setup_steps_and_capture() {
|
||||
let mut channel = ControlChannel::new(forwarded);
|
||||
let mut seen: Vec<String> = Vec::new();
|
||||
while seen.len() < 4 {
|
||||
forward.send(requests.recv_timeout(Duration::from_secs(10)).expect("a request")).expect("forwarded");
|
||||
forward.send(requests.recv_timeout(HANG).expect("a request")).expect("forwarded");
|
||||
let req = channel.next_request().expect("the forwarded request is dispatched");
|
||||
seen.push(format!("{} {}", req.method, req.params));
|
||||
let reply = match req.method.as_str() {
|
||||
@@ -401,7 +405,7 @@ fn the_documented_capture_client_sends_setup_steps_and_capture() {
|
||||
/// Connects and authenticates with the one-frame token.
|
||||
fn authenticated(addr: SocketAddr) -> (TcpStream, BufReader<TcpStream>) {
|
||||
let mut stream = TcpStream::connect(addr).expect("connected");
|
||||
stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout");
|
||||
stream.set_read_timeout(Some(HANG)).expect("timeout");
|
||||
let mut reader = BufReader::new(stream.try_clone().expect("cloned"));
|
||||
writeln!(stream, "{}", json!({"id": "auth", "method": "auth", "params": {"token": TOKEN}})).expect("written");
|
||||
assert_eq!(read_json(&mut reader).expect("a reply")["ok"], true);
|
||||
@@ -414,11 +418,11 @@ fn authenticated(addr: SocketAddr) -> (TcpStream, BufReader<TcpStream>) {
|
||||
fn an_oversized_reply_keeps_its_framing_and_id_and_the_connection_serves_on() {
|
||||
let (rx, server) = server::listen(0, TOKEN.into(), host()).expect("started");
|
||||
let handler = std::thread::spawn(move || {
|
||||
let first = rx.recv_timeout(Duration::from_secs(5)).expect("a request");
|
||||
let first = rx.recv_timeout(HANG).expect("a request");
|
||||
assert_eq!(first.method, "test.large");
|
||||
assert!(first.deadline.is_some_and(|d| d > motion::now()), "native requests carry their reply deadline");
|
||||
first.reply.send(json!({"ok": true, "result": "x".repeat(MAX_RESPONSE_BYTES)})).expect("replied");
|
||||
let second = rx.recv_timeout(Duration::from_secs(5)).expect("a request");
|
||||
let second = rx.recv_timeout(HANG).expect("a request");
|
||||
assert_eq!(second.method, "test.small");
|
||||
second.reply.send(json!({"ok": true, "result": "still serving"})).expect("replied");
|
||||
});
|
||||
@@ -441,7 +445,7 @@ fn an_oversized_reply_keeps_its_framing_and_id_and_the_connection_serves_on() {
|
||||
fn a_bad_json_request_gets_a_null_id_and_the_connection_serves_on() {
|
||||
let (rx, server) = server::listen(0, TOKEN.into(), host()).expect("started");
|
||||
let handler = std::thread::spawn(move || {
|
||||
let req = rx.recv_timeout(Duration::from_secs(5)).expect("a request");
|
||||
let req = rx.recv_timeout(HANG).expect("a request");
|
||||
assert_eq!(req.method, "test.after");
|
||||
req.reply.send(json!({"ok": true, "result": "still serving"})).expect("replied");
|
||||
});
|
||||
@@ -465,7 +469,7 @@ fn a_bad_json_request_gets_a_null_id_and_the_connection_serves_on() {
|
||||
fn a_repeated_auth_is_answered_already_authenticated_without_dispatching() {
|
||||
let (rx, server) = server::listen(0, TOKEN.into(), host()).expect("started");
|
||||
let handler = std::thread::spawn(move || {
|
||||
let req = rx.recv_timeout(Duration::from_secs(5)).expect("a request");
|
||||
let req = rx.recv_timeout(HANG).expect("a request");
|
||||
assert_eq!(req.method, "test.after", "a repeated auth must not reach the app");
|
||||
req.reply.send(json!({"ok": true, "result": "still serving"})).expect("replied");
|
||||
});
|
||||
@@ -488,7 +492,7 @@ fn a_repeated_auth_is_answered_already_authenticated_without_dispatching() {
|
||||
fn a_complete_json_request_at_eof_can_reach_the_app() {
|
||||
let (rx, server, ended) = serve_counting_ends();
|
||||
let handler = std::thread::spawn(move || {
|
||||
let req = rx.recv_timeout(Duration::from_secs(5)).expect("the request reached the app");
|
||||
let req = rx.recv_timeout(HANG).expect("the request reached the app");
|
||||
assert_eq!(req.method, "test.once");
|
||||
req.reply.send(json!({"ok": true, "result": "once"})).expect("replied");
|
||||
rx
|
||||
@@ -515,7 +519,7 @@ fn idle_unauthenticated_connections_are_limited() {
|
||||
// Admission is counted by the accept thread: it is done once the next connection is answered.
|
||||
let refused = |addr| {
|
||||
let stream = TcpStream::connect(addr).expect("connected");
|
||||
stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout");
|
||||
stream.set_read_timeout(Some(HANG)).expect("timeout");
|
||||
read_json(&mut BufReader::new(stream))
|
||||
};
|
||||
let reply = refused(server.addr).expect("a refusal");
|
||||
@@ -524,10 +528,10 @@ fn idle_unauthenticated_connections_are_limited() {
|
||||
drop(idle);
|
||||
// The freed slots go back as the closed connections are noticed.
|
||||
for _ in 0..MAX_CONNECTIONS {
|
||||
ended.recv_timeout(Duration::from_secs(5)).expect("a closed connection ended");
|
||||
ended.recv_timeout(HANG).expect("a closed connection ended");
|
||||
}
|
||||
let mut stream = TcpStream::connect(server.addr).expect("connected");
|
||||
stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout");
|
||||
stream.set_read_timeout(Some(HANG)).expect("timeout");
|
||||
let mut reader = BufReader::new(stream.try_clone().expect("cloned"));
|
||||
writeln!(stream, "{}", json!({"id": "auth", "method": "auth", "params": {"token": TOKEN}})).expect("written");
|
||||
assert_eq!(read_json(&mut reader).expect("a reply")["ok"], true, "a freed slot is admitted again");
|
||||
|
||||
@@ -5,11 +5,11 @@ 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, DialogId, DialogResult, PromptChoice, PromptKind, StandardPrompt};
|
||||
use craft_ui::dialog::{DialogHost, DialogId, DialogResult, DialogStack, PromptChoice, PromptKind, StackDialog, 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 egui::{Context, Ui};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn call(host: &mut DialogHost, ctx: &Context, method: &str, params: Value) -> Result<Value, String> {
|
||||
@@ -130,6 +130,56 @@ fn param_dialog_automation_follows_its_rows() {
|
||||
|
||||
const TAKEN: Word = Word::keyed("craft_automation.nameTaken", "A preset with that name exists");
|
||||
|
||||
struct OtherDialog(DialogId);
|
||||
|
||||
impl StackDialog for OtherDialog {
|
||||
type Result = ();
|
||||
|
||||
fn id(&self) -> DialogId {
|
||||
self.0
|
||||
}
|
||||
|
||||
fn show(&mut self, _: &mut Ui, _: &DialogStack) -> Option<DialogResult<Self::Result>> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Another type open under the same stable ID, before or after the confirm, doesn't answer the confirm whose OK
|
||||
/// is waiting.
|
||||
#[trial]
|
||||
fn a_new_dialog_with_the_same_id_does_not_answer_a_pending_confirm() {
|
||||
let ctx = Context::default();
|
||||
for other_was_open in [false, true] {
|
||||
let mut host = DialogHost::new();
|
||||
let (_requests, rx) = channel();
|
||||
let mut control = ControlChannel::new(rx);
|
||||
let id = host.open(
|
||||
HostedParamDialog::new(&ctx, "blur", DialogFields::new(), |fields| {
|
||||
ParamDialog::new("blur", "Blur", Param::parse_list(r#"{"radius":0.1..1000=1}"#)).values(Bind::bound(fields))
|
||||
})
|
||||
.held_ok(),
|
||||
);
|
||||
if other_was_open {
|
||||
host.open(OtherDialog(id));
|
||||
}
|
||||
let (request, reply) = ControlRequest::new("ui.dialog.confirm", json!({"dialog": id.value()}));
|
||||
let outcome = dialog_reply(&mut host, &ctx, &request.method, &request.params).expect("the confirm command");
|
||||
control.settle(request, outcome, None, 0.0);
|
||||
if !other_was_open {
|
||||
host.open(OtherDialog(id));
|
||||
}
|
||||
assert_eq!(host.open_dialogs().len(), 2);
|
||||
control.poll_held(&host);
|
||||
assert_eq!(control.waiting(), 1, "the dialog that got the confirm is still waiting for the app (other open first: {other_was_open})");
|
||||
assert_eq!(reply.try_recv(), Err(std::sync::mpsc::TryRecvError::Empty));
|
||||
|
||||
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})));
|
||||
}
|
||||
}
|
||||
|
||||
/// 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")
|
||||
|
||||
@@ -101,10 +101,12 @@ impl RulerUnits {
|
||||
(position - zero) * self.per_doc
|
||||
}
|
||||
|
||||
/// The least and most decimals a ruler writes a tick of labelled step `step` with. Whole ticks are whole numbers;
|
||||
/// a step of at least 1 takes the decimals it has (none for 5, one for 2.5). Under [`TickLabels::Distance`] a
|
||||
/// smaller step takes at least two (PhotoCraft's `0.50`), more when it has them (0.025), and every tick takes them
|
||||
/// all; under [`TickLabels::Signed`] a tick drops the trailing zeros (`1` on a sixteenth-inch ruler).
|
||||
/// The least and most decimals a ruler writes a tick of labelled step `step` with.
|
||||
///
|
||||
/// Whole ticks are whole numbers; a step of at least 1 takes the decimals it has (none for 5, one for 2.5). Under
|
||||
/// [`TickLabels::Distance`] a smaller step takes at least two (PhotoCraft's `0.50`), more when it has them
|
||||
/// (0.025), and every tick takes them all; under [`TickLabels::Signed`] a tick drops the trailing zeros (`1` on a
|
||||
/// sixteenth-inch ruler).
|
||||
pub fn label_decimals(&self, step: f64) -> RangeInclusive<usize> {
|
||||
let most = match self.ticks {
|
||||
Ticks::Decimal { whole: true } => 0,
|
||||
|
||||
@@ -154,10 +154,10 @@ impl Codec for PlainText {
|
||||
}
|
||||
}
|
||||
|
||||
/// A reader a caller adds for words that stand for numbers.
|
||||
/// A caller's text-to-number reader.
|
||||
type Custom = Arc<dyn Fn(&str) -> Option<f64> + Send + Sync>;
|
||||
|
||||
/// An optional number: empty text is `None`; anything else reads through a [`Reader`].
|
||||
/// An optional number: empty text is `None`; anything else reads through a [`Reader`] unless overridden with [`NumberCodec::parse_with`].
|
||||
#[derive(Clone)]
|
||||
pub struct NumberCodec {
|
||||
reader: Reader,
|
||||
@@ -165,6 +165,8 @@ pub struct NumberCodec {
|
||||
/// Every decimal place is written, trailing zeros included.
|
||||
fixed: bool,
|
||||
custom: Option<Custom>,
|
||||
/// An authoritative reader for the complete, trimmed, non-empty input.
|
||||
primary: Option<Custom>,
|
||||
/// Typing rules of a zoom field ([`NumberCodec::zoom_typing`]).
|
||||
zoom: bool,
|
||||
/// A lone percentage is that share of the start value ([`NumberCodec::share_of_start`]).
|
||||
@@ -182,6 +184,7 @@ impl fmt::Debug for NumberCodec {
|
||||
.field("share", &self.share)
|
||||
.field("signed_zoom", &self.signed_zoom)
|
||||
.field("custom", &self.custom.is_some())
|
||||
.field("primary", &self.primary.is_some())
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
@@ -193,6 +196,11 @@ impl PartialEq for NumberCodec {
|
||||
(Some(a), Some(b)) => Arc::ptr_eq(a, b),
|
||||
_ => false,
|
||||
};
|
||||
let same_primary = match (&self.primary, &other.primary) {
|
||||
(None, None) => true,
|
||||
(Some(a), Some(b)) => Arc::ptr_eq(a, b),
|
||||
_ => false,
|
||||
};
|
||||
self.reader == other.reader
|
||||
&& self.decimals == other.decimals
|
||||
&& self.fixed == other.fixed
|
||||
@@ -200,6 +208,7 @@ impl PartialEq for NumberCodec {
|
||||
&& self.share == other.share
|
||||
&& self.signed_zoom == other.signed_zoom
|
||||
&& same_custom
|
||||
&& same_primary
|
||||
}
|
||||
}
|
||||
|
||||
@@ -233,7 +242,7 @@ const NUMBER_SAMPLE: &str = "0000.00";
|
||||
impl NumberCodec {
|
||||
/// A codec reading with `reader` and writing at most `decimals` decimal places.
|
||||
pub fn new(reader: Reader, decimals: usize) -> Self {
|
||||
NumberCodec { reader, decimals, fixed: false, custom: None, zoom: false, share: false, signed_zoom: false }
|
||||
NumberCodec { reader, decimals, fixed: false, custom: None, primary: None, zoom: false, share: false, signed_zoom: false }
|
||||
}
|
||||
|
||||
/// The same codec writing every decimal place, trailing zeros included ("1.00"), as a field of a quantity shown
|
||||
@@ -303,6 +312,16 @@ impl NumberCodec {
|
||||
self
|
||||
}
|
||||
|
||||
/// The same codec with an authoritative reader for the complete, trimmed, non-empty input. It replaces the
|
||||
/// reader's expressions/relative input, zoom parsing and `or_parse`: `None` or a non-finite result rejects the
|
||||
/// input without fallback. Empty text still means `None`. Formatting and the character filter are unchanged.
|
||||
///
|
||||
/// Use this when a domain's existing grammar must own the whole value, rather than adding a word with `or_parse`.
|
||||
pub fn parse_with(mut self, parse: impl Fn(&str) -> Option<f64> + Send + Sync + 'static) -> Self {
|
||||
self.primary = Some(Arc::new(parse));
|
||||
self
|
||||
}
|
||||
|
||||
/// The widest text the codec writes for a number in `range`: the longest of each end and the number one place of
|
||||
/// the last decimal inside it ("100" and "99.9" over 0 to 100 at one decimal), so a field over the range is sized
|
||||
/// for any value it shows in it.
|
||||
@@ -367,6 +386,9 @@ impl Codec for NumberCodec {
|
||||
if trimmed.is_empty() {
|
||||
return Ok((None, ParseNote::default()));
|
||||
}
|
||||
if let Some(parse) = &self.primary {
|
||||
return parse(trimmed).filter(|number| number.is_finite()).map(|number| (Some(number), ParseNote::default())).ok_or(NotAValue);
|
||||
}
|
||||
if self.zoom {
|
||||
return self.read_zoom(trimmed).map(|(number, note)| (Some(number), note));
|
||||
}
|
||||
|
||||
@@ -449,8 +449,9 @@ impl<P: Clone + Eq + Hash> Layout<P> {
|
||||
return Err(DockError::MissingPanel);
|
||||
}
|
||||
let taken = column.groups.remove(group);
|
||||
let part = !column.groups.is_empty();
|
||||
let id = self.drop_if_empty(&place);
|
||||
return Ok(Moving { id, ..Moving::taken(taken, source) });
|
||||
return Ok(Moving { id, part, ..Moving::taken(taken, source) });
|
||||
};
|
||||
if let Some(Node::Stack { entries }) = self.node_of_mut(&place)
|
||||
&& entries.len() > 1
|
||||
@@ -478,14 +479,14 @@ impl<P: Clone + Eq + Hash> Layout<P> {
|
||||
if columns.is_empty() {
|
||||
self.take_node(&path);
|
||||
}
|
||||
Ok(Moving { column: taken, id: None })
|
||||
Ok(Moving { column: taken, id: None, part: false })
|
||||
}
|
||||
Some(PanelPlace::Floating { window, .. }) => {
|
||||
if window >= self.floating.len() {
|
||||
return Err(DockError::MissingPanel);
|
||||
}
|
||||
let taken = self.floating.remove(window);
|
||||
Ok(Moving { column: Column { width: Some(taken.rect.width()), ..taken.column }, id: Some(taken.id) })
|
||||
Ok(Moving { column: Column { width: Some(taken.rect.width()), ..taken.column }, id: Some(taken.id), part: false })
|
||||
}
|
||||
Some(PanelPlace::Node(_)) | None => Err(DockError::InvalidPlacement),
|
||||
}
|
||||
@@ -500,7 +501,8 @@ impl<P: Clone + Eq + Hash> Layout<P> {
|
||||
}
|
||||
|
||||
/// Insert groups taken by [`Self::take_unit`] (or a new single-panel group). A new column, docked or floating,
|
||||
/// keeps the moving column's state; groups that join a column take that column's.
|
||||
/// keeps the moving column's state, expanded when they are part of a collapsed column; groups that join a column
|
||||
/// take that column's.
|
||||
/// `canvas` is the protected-panel test an outer edge drop narrows by ([`Self::edge_path`]).
|
||||
pub(super) fn insert_moving(&mut self, moving: Moving<P>, to: Target<P>, canvas: &dyn Fn(&P) -> bool) -> Result<(), DockError> {
|
||||
let mut moving = moving;
|
||||
@@ -517,7 +519,7 @@ impl<P: Clone + Eq + Hash> Layout<P> {
|
||||
Some(id) => id,
|
||||
None => self.fresh_window_id(),
|
||||
};
|
||||
let window = Floating::new(id, Column { width: None, ..moving.column }, rect);
|
||||
let window = Floating::new(id, moving.into_window_column(), rect);
|
||||
let edge = edge.filter(|_| window.column.iconic);
|
||||
self.floating.push(Floating { edge, ..window });
|
||||
Ok(())
|
||||
|
||||
@@ -330,12 +330,14 @@ pub(super) enum Unit {
|
||||
}
|
||||
|
||||
/// Groups in transit, in a column that carries the state of the column they came from: a new column, docked or
|
||||
/// floating, keeps that state (an icon group taken out of a collapsed column stays icons), and a column they
|
||||
/// join keeps its own.
|
||||
/// floating, keeps that state, except that part of a collapsed column makes an expanded one (the last group of a
|
||||
/// collapsed column stays icons); a column they join keeps its own.
|
||||
pub(super) struct Moving<P> {
|
||||
pub column: Column<P>,
|
||||
/// The id of a floating window whose last group is in transit, which a new window keeps.
|
||||
pub id: Option<u64>,
|
||||
/// Panels stay in the column the groups left, so a new column made of them is expanded.
|
||||
pub part: bool,
|
||||
}
|
||||
|
||||
impl<P> Moving<P> {
|
||||
@@ -344,14 +346,26 @@ impl<P> Moving<P> {
|
||||
Self::taken(group, Column::new(Vec::new()))
|
||||
}
|
||||
|
||||
/// `group` taken out of a column whose state is `source` ([`Column::emptied`]).
|
||||
/// `group` taken out of a column whose state is `source` ([`Column::emptied`]), as all of that column.
|
||||
pub(super) fn taken(group: Group<P>, source: Column<P>) -> Self {
|
||||
Self { column: Column { groups: vec![group], ..source }, id: None }
|
||||
Self { column: Column { groups: vec![group], ..source }, id: None, part: false }
|
||||
}
|
||||
|
||||
/// The column a new dock column gets: the moving column, `width` points wide unless it brings a width.
|
||||
/// `panel` alone, taken out of a column whose state is `source`, with whether other panels stay in it.
|
||||
pub(super) fn panel(panel: P, source: (Column<P>, bool)) -> Self {
|
||||
let (column, part) = source;
|
||||
Self { part, ..Self::taken(Group::new(vec![panel], 0), column) }
|
||||
}
|
||||
|
||||
/// The column a new floating window gets: the moving column, expanded when it is part of a collapsed one.
|
||||
pub(super) fn into_window_column(self) -> Column<P> {
|
||||
Column { width: None, iconic: self.column.iconic && !self.part, ..self.column }
|
||||
}
|
||||
|
||||
/// The column a new dock column gets: the moving column, `width` points wide unless it brings a width, and
|
||||
/// expanded when it is part of a collapsed one.
|
||||
pub(super) fn into_column(self, width: Option<f32>) -> Column<P> {
|
||||
Column { width: self.column.width.or(width), ..self.column }
|
||||
Column { width: self.column.width.or(width), iconic: self.column.iconic && !self.part, ..self.column }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -49,7 +49,7 @@ impl<P: Clone + Eq + Hash> Layout<P> {
|
||||
let source = self.source_of(&panel);
|
||||
// A panel the layout does not hold opens in the new window.
|
||||
let entry = self.take(&panel).unwrap_or(StackEntry { panel: panel.clone(), open: true, height: None });
|
||||
let moving = Moving { id: lone, ..Moving::taken(Group::new(vec![entry.panel], 0), source) };
|
||||
let moving = Moving { id: lone, ..Moving::panel(entry.panel, source) };
|
||||
self.insert_moving(moving, Target::Float { rect, edge: None }, canvas)
|
||||
}
|
||||
Action::Close { panel } => self.take(&panel).map(|_| ()).ok_or(DockError::MissingPanel),
|
||||
@@ -72,7 +72,7 @@ impl<P: Clone + Eq + Hash> Layout<P> {
|
||||
}
|
||||
let entry = StackEntry { panel, open: true, height: None };
|
||||
if let Some(anchor) = anchor {
|
||||
self.insert(entry, Column::new(Vec::new()), &anchor, DockPlacement::Tab { before: None }, canvas)
|
||||
self.insert(entry, (Column::new(Vec::new()), false), &anchor, DockPlacement::Tab { before: None }, canvas)
|
||||
} else if self.root.is_none() {
|
||||
self.root = Some(Node::Tabs { panels: vec![entry.panel], active: 0 });
|
||||
Ok(())
|
||||
@@ -89,7 +89,7 @@ impl<P: Clone + Eq + Hash> Layout<P> {
|
||||
{
|
||||
return Err(DockError::MissingTarget);
|
||||
}
|
||||
self.insert(StackEntry { panel, open: true, height: None }, Column::new(Vec::new()), &anchor, placement, canvas)
|
||||
self.insert(StackEntry { panel, open: true, height: None }, (Column::new(Vec::new()), false), &anchor, placement, canvas)
|
||||
}
|
||||
Action::MoveFloating { panel, rect, edge } => {
|
||||
if !valid_rect(rect) {
|
||||
@@ -142,7 +142,7 @@ impl<P: Clone + Eq + Hash> Layout<P> {
|
||||
to => {
|
||||
let source = self.source_of(&panel);
|
||||
let entry = self.take(&panel).ok_or(DockError::MissingPanel)?;
|
||||
self.insert_moving(Moving::taken(Group::new(vec![entry.panel], 0), source), to, canvas)
|
||||
self.insert_moving(Moving::panel(entry.panel, source), to, canvas)
|
||||
}
|
||||
},
|
||||
Action::Restore { panel, location } => {
|
||||
@@ -256,9 +256,11 @@ impl<P: Clone + Eq + Hash> Layout<P> {
|
||||
}
|
||||
|
||||
/// The state a new column made of `panel` keeps: its column's ([`Self::source_column`]), or none for a panel
|
||||
/// outside a column or absent.
|
||||
pub(super) fn source_of(&self, panel: &P) -> Column<P> {
|
||||
self.place(panel).map_or_else(|| Column::new(Vec::new()), |place| self.source_column(&place))
|
||||
/// outside a column or absent; and whether other panels stay in that column ([`Moving::part`]).
|
||||
pub(super) fn source_of(&self, panel: &P) -> (Column<P>, bool) {
|
||||
let Some(place) = self.place(panel) else { return (Column::new(Vec::new()), false) };
|
||||
let part = self.column(&place).is_some_and(|column| column.panels().any(|other| other != panel));
|
||||
(self.source_column(&place), part)
|
||||
}
|
||||
|
||||
/// The accordion entry of `panel` in the docked tree.
|
||||
@@ -327,7 +329,7 @@ impl<P: Clone + Eq + Hash> Layout<P> {
|
||||
pub(super) fn insert(
|
||||
&mut self,
|
||||
entry: StackEntry<P>,
|
||||
source: Column<P>,
|
||||
source: (Column<P>, bool),
|
||||
anchor: &P,
|
||||
placement: DockPlacement<P>,
|
||||
canvas: &dyn Fn(&P) -> bool,
|
||||
@@ -338,8 +340,7 @@ impl<P: Clone + Eq + Hash> Layout<P> {
|
||||
.filter(|_| !matches!(placement, DockPlacement::Group { .. } | DockPlacement::Column { .. } | DockPlacement::Edge(_)))
|
||||
.map(<[bool]>::to_vec)
|
||||
else {
|
||||
let moving = Moving::taken(Group::new(vec![entry.panel], 0), source);
|
||||
return self.insert_moving(moving, Target::At { anchor: anchor.clone(), placement }, canvas);
|
||||
return self.insert_moving(Moving::panel(entry.panel, source), Target::At { anchor: anchor.clone(), placement }, canvas);
|
||||
};
|
||||
let root = self.root.as_mut().ok_or(DockError::MissingTarget)?;
|
||||
if let DockPlacement::Split(zone) = placement
|
||||
|
||||
@@ -148,8 +148,9 @@ impl CropBox {
|
||||
(w.is_finite() && h.is_finite()).then(|| (w.round().max(1.0), h.round().max(1.0)))
|
||||
}
|
||||
|
||||
/// Whether both sides are at least `min`, and never under one document unit whatever `min` says (a `min` that is
|
||||
/// not a number counts as one unit).
|
||||
/// Whether both sides are at least `min`, and never under one document unit whatever `min` says.
|
||||
///
|
||||
/// A `min` that is not a number counts as one unit.
|
||||
pub fn size_ok(&self, min: f64) -> bool {
|
||||
let min = min.max(MIN_FRAME);
|
||||
self.rect.width() >= min && self.rect.height() >= min
|
||||
|
||||
@@ -120,7 +120,7 @@ pub use value::{
|
||||
Applied, CancelReason, EditEvent, EditEvents, EditPolicy, Gesture, GestureId, GestureNote, GesturePhase, Mixed, Preview, Validity, Value,
|
||||
same_in_f32, same_in_f32_at,
|
||||
};
|
||||
pub use value_drag::{DragWarp, ValueDrag, wrap_value};
|
||||
pub use value_drag::{DragModifier, DragModifiers, DragWarp, ValueDrag, wrap_value};
|
||||
pub use wheel::{GESTURE_GAP, Wheel, WheelEase, WheelFocus, WheelGesture, WheelNotch, WheelPhase, WheelRoom, WheelSource, WheelTaker, WheelUnit};
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -55,6 +55,11 @@ bitflags! {
|
||||
/// it that senses a drag, with its start. Released within slop it is the shape's click. Declared with `CLICK`,
|
||||
/// without `DRAG`.
|
||||
const PASSES_DRAG = 131072;
|
||||
/// The vertical wheel share, taken only while the component holds key focus or a press armed it, in any wheel
|
||||
/// scope: a control whose wheel steps what focus picks rather than what the pointer is over (the focused thumb
|
||||
/// of a range). Every other wheel bit the shape senses waits for focus with it. A control that senses no wheel
|
||||
/// bit takes no wheel at all, so the wheel over it scrolls the region around it.
|
||||
const WHEEL_Y_FOCUSED = 262144;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -63,7 +68,12 @@ impl Sense {
|
||||
pub const PRESS: Sense = Sense::CLICK.union(Sense::DRAG);
|
||||
|
||||
/// The bits that make a shape register a wheel taker.
|
||||
pub const WHEELS: Sense = Sense::WHEEL.union(Sense::WHEEL_X).union(Sense::WHEEL_Y).union(Sense::WHEEL_ZOOM).union(Sense::WHEEL_ZOOMS_VIEW);
|
||||
pub const WHEELS: Sense = Sense::WHEEL
|
||||
.union(Sense::WHEEL_X)
|
||||
.union(Sense::WHEEL_Y)
|
||||
.union(Sense::WHEEL_ZOOM)
|
||||
.union(Sense::WHEEL_ZOOMS_VIEW)
|
||||
.union(Sense::WHEEL_Y_FOCUSED);
|
||||
|
||||
/// Whether a press can start on a shape with this sense.
|
||||
pub const fn takes_press(self) -> bool {
|
||||
|
||||
@@ -5,6 +5,52 @@ use crate::press::{PressPhase, PressState};
|
||||
use emath::{Pos2, Rect, Vec2};
|
||||
use std::ops::{Range, RangeInclusive};
|
||||
|
||||
/// A modifier that changes continuous pointer-drag sensitivity. It does not remap input or keys.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum DragModifier {
|
||||
/// Alt (Option).
|
||||
Alt,
|
||||
/// Shift.
|
||||
Shift,
|
||||
/// Control.
|
||||
Control,
|
||||
/// The platform's command modifier.
|
||||
Command,
|
||||
}
|
||||
|
||||
impl DragModifier {
|
||||
fn held(self, press: &PressState) -> bool {
|
||||
match self {
|
||||
Self::Alt => press.mods.alt,
|
||||
Self::Shift => press.mods.shift,
|
||||
Self::Control => press.mods.ctrl,
|
||||
Self::Command => press.mods.cmd,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The pointer-only fine/coarse bindings of a continuous drag. Fine wins when both bindings match.
|
||||
/// Unbound modifiers leave travel normal. Defaults retain Alt fine, Shift coarse.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct DragModifiers {
|
||||
fine: Option<DragModifier>,
|
||||
coarse: Option<DragModifier>,
|
||||
}
|
||||
|
||||
impl DragModifiers {
|
||||
/// Selects the fine and coarse bindings; `None` disables that binding.
|
||||
pub const fn new(fine: Option<DragModifier>, coarse: Option<DragModifier>) -> Self {
|
||||
Self { fine, coarse }
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for DragModifiers {
|
||||
fn default() -> Self {
|
||||
Self::new(Some(DragModifier::Alt), Some(DragModifier::Shift))
|
||||
}
|
||||
}
|
||||
|
||||
/// How the pointer's position along the axis becomes a value.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
enum Mapping {
|
||||
@@ -24,6 +70,7 @@ pub struct ValueDrag {
|
||||
hide_cursor: bool,
|
||||
fine: f64,
|
||||
coarse: Option<f64>,
|
||||
modifiers: DragModifiers,
|
||||
}
|
||||
|
||||
/// The factor Alt (Option) applies to travel when a drag sets none.
|
||||
@@ -40,12 +87,30 @@ impl ValueDrag {
|
||||
/// A track whose `start` lies after its `end` runs backwards, as a vertical slider's does, and a range whose start
|
||||
/// exceeds its end maps the track the other way; the value stays within the range either way.
|
||||
pub fn absolute(track: Range<f32>, range: RangeInclusive<f64>) -> Self {
|
||||
ValueDrag { mapping: Mapping::Absolute { track }, axis: Axis::X, range, warp: false, hide_cursor: false, fine: FINE, coarse: None }
|
||||
ValueDrag {
|
||||
mapping: Mapping::Absolute { track },
|
||||
axis: Axis::X,
|
||||
range,
|
||||
warp: false,
|
||||
hide_cursor: false,
|
||||
fine: FINE,
|
||||
coarse: None,
|
||||
modifiers: DragModifiers::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The value changes by `rate` units per point of travel from the press. Vertical travel upwards increases it.
|
||||
pub fn relative(rate: f64, range: RangeInclusive<f64>) -> Self {
|
||||
ValueDrag { mapping: Mapping::Relative { rate }, axis: Axis::X, range, warp: false, hide_cursor: false, fine: FINE, coarse: None }
|
||||
ValueDrag {
|
||||
mapping: Mapping::Relative { rate },
|
||||
axis: Axis::X,
|
||||
range,
|
||||
warp: false,
|
||||
hide_cursor: false,
|
||||
fine: FINE,
|
||||
coarse: None,
|
||||
modifiers: DragModifiers::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The axis the pointer travels on; the default is horizontal.
|
||||
@@ -67,6 +132,12 @@ impl ValueDrag {
|
||||
self
|
||||
}
|
||||
|
||||
/// Selects pointer fine/coarse bindings without changing keyboard or wheel behavior.
|
||||
pub const fn modifiers(mut self, modifiers: DragModifiers) -> Self {
|
||||
self.modifiers = modifiers;
|
||||
self
|
||||
}
|
||||
|
||||
/// Warps the pointer to the other side of the window when the drag reaches an edge, so the drag has no end
|
||||
/// ([`ValueDrag::warp_by`], [`DragWarp`]). It sets no wrap of the value.
|
||||
pub const fn warp(mut self, on: bool) -> Self {
|
||||
@@ -129,9 +200,9 @@ impl ValueDrag {
|
||||
_ => return None,
|
||||
};
|
||||
let pos = pos - shift;
|
||||
let fine = if press.mods.alt {
|
||||
let fine = if self.modifiers.fine.is_some_and(|binding| binding.held(press)) {
|
||||
self.fine
|
||||
} else if press.mods.shift {
|
||||
} else if self.modifiers.coarse.is_some_and(|binding| binding.held(press)) {
|
||||
self.coarse.unwrap_or(1.0)
|
||||
} else {
|
||||
1.0
|
||||
@@ -236,6 +307,38 @@ mod tests {
|
||||
use craft_keymap::Mods;
|
||||
use emath::{Vec2, pos2};
|
||||
|
||||
#[test]
|
||||
fn pointer_modifier_policy_preserves_defaults_and_raw_modifiers() {
|
||||
let base = ValueDrag::relative(1.0, -1000.0..=1000.0).coarse(10.0);
|
||||
let mut both = Mods::ALT;
|
||||
both.shift = true;
|
||||
for (mods, expected) in [(Mods::NONE, 20.0), (Mods::SHIFT, 200.0), (Mods::ALT, 2.0), (both, 2.0)] {
|
||||
let press = drag(pos2(0.0, 0.0), pos2(20.0, 0.0), mods);
|
||||
assert_eq!(base.value(0.0, &press, false), Some(expected));
|
||||
assert_eq!(press.mods, mods);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pointer_modifier_policy_selects_shift_fine_and_alt_normal() {
|
||||
let base = ValueDrag::relative(1.0, -1000.0..=1000.0).coarse(10.0).modifiers(DragModifiers::new(Some(DragModifier::Shift), None));
|
||||
let mut both = Mods::ALT;
|
||||
both.shift = true;
|
||||
for (mods, expected) in [(Mods::NONE, 20.0), (Mods::SHIFT, 2.0), (Mods::ALT, 20.0), (both, 2.0)] {
|
||||
let press = drag(pos2(0.0, 0.0), pos2(20.0, 0.0), mods);
|
||||
assert_eq!(base.value(0.0, &press, false), Some(expected));
|
||||
assert_eq!(press.mods, mods);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pointer_modifier_policy_unbound_and_overlapping_bindings_are_explicit() {
|
||||
let base = ValueDrag::relative(1.0, -1000.0..=1000.0).coarse(10.0);
|
||||
let shift = drag(pos2(0.0, 0.0), pos2(20.0, 0.0), Mods::SHIFT);
|
||||
assert_eq!(base.clone().modifiers(DragModifiers::new(None, None)).value(0.0, &shift, false), Some(20.0));
|
||||
assert_eq!(base.modifiers(DragModifiers::new(Some(DragModifier::Shift), Some(DragModifier::Shift))).value(0.0, &shift, false), Some(2.0));
|
||||
}
|
||||
|
||||
fn drag(from: Pos2, to: Pos2, mods: Mods) -> PressState {
|
||||
let start = PressStart::new(from, PointerButton::Primary, 0.0, 1);
|
||||
PressState::new(PressPhase::Drag { start, pos: to, delta: Vec2::ZERO }).mods(mods)
|
||||
|
||||
@@ -101,6 +101,13 @@ pub struct Wheel {
|
||||
pub gathered: Vec2,
|
||||
/// Whether the owner marked the running gesture moved (`Pointer::mark_wheel_moved`).
|
||||
pub moved: bool,
|
||||
/// The modifiers held at any point of the running gesture so far, this share's included: those of its wheel events
|
||||
/// and of the key events between them, so a key tapped between two events counts until the gesture ends. For the
|
||||
/// taker that owns the gesture; another taker's share holds its own `mods`.
|
||||
pub held: Mods,
|
||||
/// A wheel event of the running gesture, or one less than [`GESTURE_GAP`] seconds before it began, arrived while a
|
||||
/// modal layer held the wheel: the turn began or went on under the modal, and it stays marked until it ends.
|
||||
pub modal: bool,
|
||||
}
|
||||
|
||||
/// The eased motion of a canvas's line wheel: notches gather into owed motion that later passes pay out.
|
||||
@@ -247,6 +254,8 @@ impl Wheel {
|
||||
touch_pan: Vec2::ZERO,
|
||||
gathered: Vec2::ZERO,
|
||||
moved: false,
|
||||
held: mods,
|
||||
modal: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -362,6 +371,10 @@ pub struct WheelTaker<O> {
|
||||
/// It takes any axis (scroll or zoom) only while focused or armed: a value control, unless its scope frees it,
|
||||
/// or any taker inside a gated scope.
|
||||
pub gated: bool,
|
||||
/// Directional value editing: dominant horizontal (or Shift) scroll edits under the pointer;
|
||||
/// vertical scroll requires explicit arming, not keyboard focus. The existing arming lifecycle
|
||||
/// disarms on leaving the control, without changing keyboard focus.
|
||||
pub directional: bool,
|
||||
/// A scroll region (a scrolling body or collection): Shift turns the vertical wheel sideways over it.
|
||||
pub scrolls: bool,
|
||||
/// The distance of one wheel line.
|
||||
@@ -430,6 +443,7 @@ impl<O> WheelTaker<O> {
|
||||
vertical: false,
|
||||
zoom: false,
|
||||
gated: false,
|
||||
directional: false,
|
||||
scrolls: false,
|
||||
notch: WheelNotch::DEFAULT,
|
||||
room: None,
|
||||
@@ -441,14 +455,17 @@ impl<O> WheelTaker<O> {
|
||||
|
||||
/// The taker a shape with `sense` registers, `None` when `sense` has no wheel bit: `WHEEL` takes both scroll
|
||||
/// axes and zoom; `WHEEL_X`, `WHEEL_Y` and `WHEEL_ZOOM` take one share each and combine; `WHEEL_ZOOMS_VIEW`
|
||||
/// makes a zoom zone.
|
||||
/// makes a zoom zone; `WHEEL_Y_FOCUSED` takes the vertical share and makes the taker gated, so every axis it takes
|
||||
/// waits for focus or arming.
|
||||
pub fn for_sense(owner: O, rect: Rect, sense: Sense) -> Option<Self> {
|
||||
let all = sense.contains(Sense::WHEEL);
|
||||
let focused = sense.contains(Sense::WHEEL_Y_FOCUSED);
|
||||
let taker = WheelTaker::new(owner, rect)
|
||||
.horizontal(all || sense.contains(Sense::WHEEL_X))
|
||||
.vertical(all || sense.contains(Sense::WHEEL_Y))
|
||||
.vertical(all || focused || sense.contains(Sense::WHEEL_Y))
|
||||
.zoom(all || sense.contains(Sense::WHEEL_ZOOM))
|
||||
.zooms_view(sense.contains(Sense::WHEEL_ZOOMS_VIEW));
|
||||
.zooms_view(sense.contains(Sense::WHEEL_ZOOMS_VIEW))
|
||||
.gated(focused);
|
||||
(taker.horizontal || taker.vertical || taker.zoom || taker.zooms_view).then_some(taker)
|
||||
}
|
||||
|
||||
@@ -497,6 +514,14 @@ impl<O> WheelTaker<O> {
|
||||
self
|
||||
}
|
||||
|
||||
/// Opts a value control into directional editing, without changing the default focus gate.
|
||||
/// The caller registers both scroll axes and keeps the taker gated so presses can arm it.
|
||||
#[must_use]
|
||||
pub const fn directional(mut self, on: bool) -> Self {
|
||||
self.directional = on;
|
||||
self
|
||||
}
|
||||
|
||||
/// The distance of one wheel line.
|
||||
pub const fn notch(mut self, notch: WheelNotch) -> Self {
|
||||
self.notch = notch;
|
||||
@@ -637,7 +662,8 @@ pub fn split<O: Copy + PartialEq>(
|
||||
if !running {
|
||||
*gesture = WheelGesture::default();
|
||||
}
|
||||
let field = focus.taker.filter(|focused| !focus.by_position && takers.iter().any(|taker| taker.field && taker.owner == *focused));
|
||||
let field =
|
||||
focus.taker.filter(|focused| !focus.by_position && takers.iter().any(|taker| taker.field && !taker.directional && taker.owner == *focused));
|
||||
let app_field = focus.app_field && !focus.by_position;
|
||||
// A value control keeps its gesture only while the pointer is over it: once the pointer leaves, the gesture goes
|
||||
// on by position as a running one (value controls excluded) and the control hears its end now, so its edit run
|
||||
@@ -696,17 +722,43 @@ fn split_at<O: Copy + PartialEq>(
|
||||
// Takers register outer first, so among equal areas the later one is the deeper (or the upper) and goes first.
|
||||
let mut under: Vec<&WheelTaker<O>> = takers.iter().rev().filter(|taker| taker.rect.contains(at)).collect();
|
||||
under.sort_by(|a, b| a.rect.area().total_cmp(&b.rect.area()));
|
||||
// A trackpad steps a value control only while it is focused or armed: over anything else it scrolls the panel.
|
||||
// Read intent without changing anyone's input: a running panel gesture can cross a
|
||||
// directional control without that control becoming an eligible recipient.
|
||||
// A dominant horizontal swipe, or a Shift-wheel whatever its vertical component; the edit distance is the axis
|
||||
// that intent names, so a Shift-wheel with a little sideways drift still edits by its vertical share.
|
||||
let horizontal = wheel.scroll.x.abs() > wheel.scroll.y.abs();
|
||||
let sideways = horizontal || (wheel.mods.shift && wheel.scroll.y != 0.0);
|
||||
// A trackpad otherwise steps a value control only while it is focused or armed.
|
||||
let fingers = wheel.source.fingers();
|
||||
let open = |taker: &WheelTaker<O>| (!taker.gated && !(fingers && taker.value)) || armed == Some(taker.owner) || focused == Some(taker.owner);
|
||||
let open = |taker: &WheelTaker<O>| {
|
||||
if taker.directional {
|
||||
!(wheel.mods.alt || wheel.mods.cmd || wheel.mods.ctrl) && (sideways || armed == Some(taker.owner))
|
||||
} else {
|
||||
(!taker.gated && !(fingers && taker.value)) || armed == Some(taker.owner) || focused == Some(taker.owner)
|
||||
}
|
||||
};
|
||||
// The running gesture's owner, while it is registered and open; it takes its axes wherever the pointer is. A
|
||||
// focused field holds the wheel by the field rule alone, so a wheel with Alt or Cmd/Ctrl still reaches the view.
|
||||
let held: Option<&WheelTaker<O>> = latch
|
||||
.flatten()
|
||||
.and_then(|owner| takers.iter().find(|taker| taker.owner == owner && open(taker) && !(taker.field && focused == Some(taker.owner))));
|
||||
let held: Option<&WheelTaker<O>> = latch.flatten().and_then(|owner| {
|
||||
// A focused field holds the wheel by the field rule alone, not a directional control: that one took the
|
||||
// gesture by position and keeps it while it runs.
|
||||
takers.iter().find(|taker| taker.owner == owner && open(taker) && !(taker.field && !taker.directional && focused == Some(taker.owner)))
|
||||
});
|
||||
// Who takes a scroll axis by position: any open taker for a new gesture; during a running one no value control,
|
||||
// so a control the pointer passes over does not take the scroll over.
|
||||
let free = |taker: &WheelTaker<O>| open(taker) && (latch.is_none() || !taker.value);
|
||||
let horizontal_recipient = held
|
||||
.filter(|taker| taker.horizontal)
|
||||
.or_else(|| under.iter().copied().find(|taker| taker.horizontal && free(taker) && taker.has_room(false, wheel.scroll.x)));
|
||||
let wheel = if sideways && horizontal_recipient.is_some_and(|taker| taker.directional) {
|
||||
// Only the selected directional recipient reads a normalized dominant-axis share.
|
||||
// Another owner, including a latched panel or a command-chord recipient, keeps the
|
||||
// device's original components unchanged.
|
||||
let (along, lines) = if horizontal { (wheel.scroll.x, wheel.lines.x) } else { (wheel.scroll.y, wheel.lines.y) };
|
||||
Wheel { scroll: Vec2::new(along, 0.0), lines: Vec2::new(lines, 0.0), ..wheel }
|
||||
} else {
|
||||
wheel
|
||||
};
|
||||
let zone = (wheel.scroll.y != 0.0).then(|| under.iter().position(|t| (t.vertical || t.zooms_view) && open(t))).flatten();
|
||||
let zone_view = zone.filter(|&at| !under[at].vertical).and_then(|at| under[at + 1..].iter().find(|t| t.zoom && open(t))).map(|t| t.owner);
|
||||
// A running gesture zooms a view by the zone only when it is that view's gesture.
|
||||
@@ -758,6 +810,13 @@ fn split_at<O: Copy + PartialEq>(
|
||||
None => shares.push((owner, part)),
|
||||
}
|
||||
}
|
||||
// A directional value control reads a plain notch: Shift reached it as the request for the sideways wheel (the
|
||||
// rule above), never as a multiplier of its step. Another taker keeps its modifiers.
|
||||
for (owner, share) in &mut shares {
|
||||
if takers.iter().any(|taker| taker.directional && taker.owner == *owner) {
|
||||
share.mods = Mods { shift: false, ..share.mods };
|
||||
}
|
||||
}
|
||||
shares
|
||||
}
|
||||
|
||||
@@ -770,6 +829,12 @@ mod tests {
|
||||
Wheel::new(Vec2::new(x, y), Mods::NONE, WheelUnit::Point, WheelPhase::Move)
|
||||
}
|
||||
|
||||
/// The first share of a split at `at` with nothing armed or latched.
|
||||
fn share_of(takers: &[WheelTaker<u8>], at: Pos2, wheel: Wheel, focus: Option<u8>, armed: Option<u8>) -> (u8, Wheel) {
|
||||
let mut gesture = WheelGesture::default();
|
||||
split(takers, at, wheel, WheelFocus::new(focus), armed, &mut gesture, 0.0)[0]
|
||||
}
|
||||
|
||||
fn rect(size: f32) -> Rect {
|
||||
Rect::from_min_size(pos2(0.0, 0.0), Vec2::splat(size))
|
||||
}
|
||||
@@ -856,4 +921,70 @@ mod tests {
|
||||
assert!(notch(&mut ease, -NOTCH, 2.0 + 11.0 * 0.02) < -NOTCH - 1.0, "precondition: the run is fast again");
|
||||
assert!(near(notch(&mut ease, -NOTCH, 5.0), -NOTCH), "an idle gap starts again at one notch");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn directional_value_wheel_keeps_plain_defaults_and_requires_arming_only_for_vertical() {
|
||||
let panel = WheelTaker::new(1u8, rect(300.0)).horizontal(true).vertical(true).scrolls(true);
|
||||
let control = WheelTaker::new(2u8, rect(100.0)).horizontal(true).vertical(true).value(true).gated(true);
|
||||
let at = pos2(10.0, 10.0);
|
||||
let shares =
|
||||
|control, wheel, focus, armed| split(&[panel, control], at, wheel, WheelFocus::new(focus), armed, &mut WheelGesture::default(), 0.0);
|
||||
assert_eq!(shares(control, wheel(0.0, 6.0), Some(2), None)[0].0, 2, "default focus gate is unchanged");
|
||||
assert_eq!(shares(control, wheel(6.0, 0.0), None, None)[0].0, 1, "default unfocused sideways scroll stays with the panel");
|
||||
let directional = control.directional(true);
|
||||
assert_eq!(shares(directional, wheel(0.0, 6.0), Some(2), None)[0].0, 1, "focus alone does not rearm vertical editing");
|
||||
assert_eq!(shares(directional, wheel(0.0, 6.0), Some(2), Some(2))[0].0, 2, "an explicit press arms vertical editing");
|
||||
let horizontal = shares(directional, wheel(6.0, 0.0).source(WheelSource::Trackpad), None, None);
|
||||
assert_eq!((horizontal[0].0, horizontal[0].1.scroll), (2, Vec2::new(6.0, 0.0)), "an unselected horizontal trackpad swipe edits");
|
||||
let diagonal_right = shares(directional, wheel(12.0, -3.0), None, None);
|
||||
assert_eq!((diagonal_right[0].0, diagonal_right[0].1.scroll), (2, Vec2::new(12.0, 0.0)), "horizontal-dominant intent keeps its sign");
|
||||
let shifted = shares(directional, Wheel { mods: Mods::SHIFT, ..wheel(0.0, 6.0) }, None, None);
|
||||
assert_eq!((shifted[0].0, shifted[0].1.scroll), (2, Vec2::new(6.0, 0.0)), "Shift-wheel is explicitly sideways");
|
||||
assert!(!shifted[0].1.mods.shift, "the directional share carries one plain notch, not Shift's ten");
|
||||
let diagonal = shares(directional, wheel(3.0, -12.0), Some(2), None);
|
||||
assert!(diagonal.iter().all(|(owner, _)| *owner == 1), "a vertical-dominant swipe stays with the panel despite focus");
|
||||
assert_eq!(diagonal[0].1.scroll.y, -12.0, "vertical scrolling remains available");
|
||||
for mods in [Mods::CTRL, Mods::ALT, Mods::CMD, Mods { shift: true, ..Mods::CTRL }] {
|
||||
let chord = shares(directional, Wheel { mods, ..wheel(12.0, -3.0) }, None, None);
|
||||
assert_eq!((chord[0].0, chord[0].1.scroll), (1, Vec2::new(12.0, -3.0)), "command chords keep both original panel components: {mods:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn directional_shift_wheel_with_both_axes_edits_by_its_vertical_share() {
|
||||
let panel = WheelTaker::new(1u8, rect(300.0)).horizontal(true).vertical(true).scrolls(true);
|
||||
let directional = WheelTaker::new(2u8, rect(100.0)).horizontal(true).vertical(true).value(true).gated(true).directional(true);
|
||||
let at = pos2(10.0, 10.0);
|
||||
let mixed = share_of(&[panel, directional], at, Wheel { mods: Mods::SHIFT, ..wheel(3.0, -12.0) }, None, None);
|
||||
assert_eq!(mixed.0, 2, "Shift-wheel with mixed axes reaches the directional control");
|
||||
assert_eq!(mixed.1.scroll, Vec2::new(-12.0, 0.0), "and edits by its vertical share");
|
||||
assert!(!mixed.1.mods.shift, "one plain notch");
|
||||
let plain = share_of(&[panel, directional], at, wheel(3.0, -12.0), None, None);
|
||||
assert_eq!(plain.0, 1, "without Shift a vertical-dominant swipe is the panel's");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_focused_directional_field_keeps_its_running_gesture() {
|
||||
let panel = WheelTaker::new(1u8, rect(300.0)).horizontal(true).vertical(true).scrolls(true);
|
||||
let field = WheelTaker::new(2u8, rect(100.0)).horizontal(true).vertical(true).value(true).gated(true).directional(true).field(true);
|
||||
let at = pos2(10.0, 10.0);
|
||||
let mut gesture = WheelGesture::default();
|
||||
let first = split(&[panel, field], at, wheel(6.0, -3.0), WheelFocus::new(Some(2)), None, &mut gesture, 0.0);
|
||||
assert_eq!(first[0].0, 2, "the focused directional field takes the first sideways event");
|
||||
let second = split(&[panel, field], at, wheel(6.0, -3.0), WheelFocus::new(Some(2)), None, &mut gesture, 0.05);
|
||||
assert_eq!(second[0].0, 2, "and the next event of the same gesture, though it is a focused field");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn directional_control_under_a_running_panel_scroll_must_not_strip_its_vertical_share() {
|
||||
let panel = WheelTaker::new(1u8, rect(300.0)).horizontal(true).vertical(true).scrolls(true);
|
||||
let directional = WheelTaker::new(2u8, rect(100.0)).horizontal(true).vertical(true).value(true).gated(true).directional(true);
|
||||
let mut gesture = WheelGesture::default();
|
||||
let first = split(&[panel, directional], pos2(200.0, 200.0), wheel(12.0, -3.0), WheelFocus::new(None), None, &mut gesture, 0.0);
|
||||
assert_eq!((first[0].0, first[0].1.scroll), (1, Vec2::new(12.0, -3.0)));
|
||||
// The existing panel-owned gesture crosses an opted-in slider. Values are excluded while
|
||||
// another owner holds the gesture, so the untouched panel must retain BOTH scroll axes.
|
||||
let crossing = split(&[panel, directional], pos2(10.0, 10.0), wheel(12.0, -3.0), WheelFocus::new(None), None, &mut gesture, 0.001);
|
||||
assert_eq!((crossing[0].0, crossing[0].1.scroll), (1, Vec2::new(12.0, -3.0)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
//! An opt-in primary numeric grammar never falls through to expression, relative or fallback parsing.
|
||||
|
||||
use craft_behavior::{Codec, NotAValue, NumberCodec, ParseNote, Reader};
|
||||
|
||||
fn absolute(text: &str) -> Option<f64> {
|
||||
text.parse().ok()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codec_override_reads_complete_trimmed_values_absolutely() {
|
||||
let codec = NumberCodec::default().parse_with(|text| {
|
||||
assert_eq!(text, text.trim());
|
||||
absolute(text)
|
||||
});
|
||||
assert_eq!(codec.parse(" +12 ", &Some(50.0)), Ok(Some(12.0)));
|
||||
assert_eq!(codec.parse("-12", &Some(50.0)), Ok(Some(-12.0)));
|
||||
assert_eq!(codec.parse(" ", &Some(50.0)), Ok(None), "the existing empty-value convention stays intact");
|
||||
assert_eq!(codec.parse_tagged("12", &Some(50.0)), Ok((Some(12.0), ParseNote::default())));
|
||||
for text in ["1+2", "*2", "1.2.3", "12 widgets", "1 2", "1,2.3"] {
|
||||
assert_eq!(codec.parse(text, &Some(50.0)), Err(NotAValue), "reject the entire input {text:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codec_override_rejection_never_falls_through_to_other_readers() {
|
||||
let codec = NumberCodec::new(Reader::new().unit("widgets", 2.0), 2).or_parse(|_| Some(999.0)).zoom_typing().parse_with(absolute);
|
||||
for text in ["1+2", "8/4", "2 widgets", "Auto", "1.2.3"] {
|
||||
assert_eq!(codec.parse(text, &Some(50.0)), Err(NotAValue), "no secondary reader may accept {text:?}");
|
||||
}
|
||||
assert_eq!(codec.parse("+12", &Some(50.0)), Ok(Some(12.0)));
|
||||
// Setter order does not silently replace the authoritative reader with the fallback reader.
|
||||
let codec = NumberCodec::default().parse_with(absolute).or_parse(|_| Some(999.0));
|
||||
assert_eq!(codec.parse("Auto", &None), Err(NotAValue));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codec_override_rejects_nonfinite_callback_results() {
|
||||
let codec = NumberCodec::default().parse_with(absolute);
|
||||
for text in ["NaN", "inf", "-inf", "1e9999"] {
|
||||
assert_eq!(codec.parse(text, &None), Err(NotAValue), "non-finite {text:?}");
|
||||
}
|
||||
for value in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
|
||||
let codec = NumberCodec::default().parse_with(move |_| Some(value));
|
||||
assert_eq!(codec.parse("anything", &None), Err(NotAValue));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codec_override_preserves_formatting_filter_equality_and_all_default_grammars() {
|
||||
let original = NumberCodec::new(Reader::new().decimal(','), 2).fixed().zoom_typing();
|
||||
let custom = original.clone().parse_with(absolute);
|
||||
assert_eq!(original.format(&Some(12.5)), custom.format(&Some(12.5)));
|
||||
assert_eq!(custom.format(&Some(12.5)), "12,50");
|
||||
for c in ['1', ',', '/', '+', '-', '*', 'w'] {
|
||||
assert_eq!(original.filter(c), custom.filter(c), "filter {c}");
|
||||
}
|
||||
assert_eq!(custom, custom.clone());
|
||||
assert_ne!(original, custom);
|
||||
let default = NumberCodec::default();
|
||||
assert_eq!(default.parse("+12", &Some(50.0)), Ok(Some(62.0)));
|
||||
assert_eq!(default.parse("1+2", &Some(50.0)), Ok(Some(3.0)));
|
||||
assert_eq!(default.clone().or_parse(|text| (text == "Auto").then_some(99.0)).parse("Auto", &None), Ok(Some(99.0)));
|
||||
assert_eq!(default.zoom_typing().parse("8/4", &None), Ok(Some(200.0)));
|
||||
}
|
||||
@@ -310,7 +310,7 @@ fn a_floating_windows_edge_is_saved_set_by_collapsed_moves_and_floats_and_cleare
|
||||
assert_eq!(layout.floating[0].edge, None, "collapsing hangs the strip from the edge nearer the window");
|
||||
|
||||
let mut moved = columns();
|
||||
moved.apply(Action::move_group(3, Target::float_with_edge(window(), Some(DockEdge::End)))).unwrap();
|
||||
moved.apply(Action::move_column(3, Target::float_with_edge(window(), Some(DockEdge::End)))).unwrap();
|
||||
let floated = moved.floating.iter().find(|window| window.contains(&3)).unwrap();
|
||||
assert_eq!(floated.edge, Some(DockEdge::End), "a collapsed column floats at the edge its strip was dropped near");
|
||||
let mut moved = columns();
|
||||
@@ -356,10 +356,21 @@ fn a_group_docked_into_a_collapsed_column_keeps_its_width_as_the_flyout_width()
|
||||
layout.apply(Action::resize_flyout_width(3, Some(350.0))).unwrap();
|
||||
layout.apply(Action::move_group(3, Target::at(7, DockPlacement::group(true, None)))).unwrap();
|
||||
assert_eq!(flyout(&layout, 3), Some(350.0), "a group from another collapsed column keeps its own");
|
||||
|
||||
let source = Column::new(vec![g(&[3], 0), g(&[4], 0)]).with_width(300.0).with_iconic(true);
|
||||
let target = Column::new(vec![g(&[7], 0)]).with_iconic(true);
|
||||
let mut layout = Layout::new(
|
||||
Some(Node::split(Axis::X, SplitSize::Ratio(0.5), Node::dock(DockEdge::Start, vec![target]), Node::dock(DockEdge::End, vec![source]))),
|
||||
vec![],
|
||||
);
|
||||
layout.apply(Action::resize_flyout_width(3, Some(350.0))).unwrap();
|
||||
layout.apply(Action::move_group(3, Target::at(7, DockPlacement::group(true, None)))).unwrap();
|
||||
assert_eq!(flyout(&layout, 3), Some(350.0), "a group from a collapsed column of its own width keeps its flyout width");
|
||||
}
|
||||
|
||||
/// Collapse to icons is a state of every column: a floating window collapses and stays floating; groups leaving a
|
||||
/// column float in its state; groups joining a column, docked or floating, take that column's state.
|
||||
/// Collapse to icons is a state of every column: a floating window collapses and stays floating; a whole column
|
||||
/// leaving floats in its state, and part of a collapsed column floats expanded; groups joining a column, docked or
|
||||
/// floating, take that column's state.
|
||||
#[test]
|
||||
fn a_column_keeps_its_collapsed_state_when_it_floats_and_a_joined_column_decides() {
|
||||
let mut layout = columns();
|
||||
@@ -369,15 +380,24 @@ fn a_column_keeps_its_collapsed_state_when_it_floats_and_a_joined_column_decides
|
||||
layout.apply(Action::set_iconic(6, false)).unwrap();
|
||||
assert_eq!(layout.panel_state(&6), PanelState::Front);
|
||||
|
||||
for action in [
|
||||
Action::move_column(3, Target::float(window())),
|
||||
Action::move_group(3, Target::float(window())),
|
||||
Action::move_panel(3, Target::float(window())),
|
||||
] {
|
||||
let mut moved = columns();
|
||||
moved.apply(Action::move_column(3, Target::float(window()))).unwrap();
|
||||
assert!(floats(&moved, 3) && column_of(&moved, 3).iconic, "the whole collapsed column floats as icons");
|
||||
for action in [Action::move_group(3, Target::float(window())), Action::move_panel(3, Target::float(window()))] {
|
||||
let mut moved = columns();
|
||||
moved.apply(action.clone()).unwrap();
|
||||
assert!(floats(&moved, 3) && column_of(&moved, 3).iconic, "{action:?} floats as icons");
|
||||
assert!(floats(&moved, 3) && !column_of(&moved, 3).iconic, "{action:?} out of a column with another group floats expanded");
|
||||
assert!(column_of(&moved, 4).iconic, "the column it left stays collapsed");
|
||||
moved.apply(Action::move_group(4, Target::float(window()))).unwrap();
|
||||
assert!(floats(&moved, 4) && column_of(&moved, 4).iconic, "the column's last group floats as icons");
|
||||
}
|
||||
let mut tabbed = Layout::new(None, vec![Floating::new(102, Column::new(vec![g(&[3, 4, 5], 0)]).with_iconic(true), window())]);
|
||||
tabbed.apply(Action::move_panel(3, Target::float(window()))).unwrap();
|
||||
assert!(!column_of(&tabbed, 3).iconic, "a tab out of a collapsed column's only group floats expanded");
|
||||
tabbed.apply(Action::move_panel(5, Target::new_dock(DockEdge::End))).unwrap();
|
||||
assert!(!column_of(&tabbed, 5).iconic, "a tab out of a collapsed column docks expanded");
|
||||
tabbed.apply(Action::move_panel(4, Target::new_dock(DockEdge::Start))).unwrap();
|
||||
assert!(column_of(&tabbed, 4).iconic, "the column's last panel docks as icons");
|
||||
let mut moved = columns();
|
||||
moved.apply(Action::move_group(2, Target::float(window()))).unwrap();
|
||||
assert!(floats(&moved, 2) && !column_of(&moved, 2).iconic, "out of an expanded column it floats expanded");
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
mod canvas_view;
|
||||
mod cells;
|
||||
mod codec_override;
|
||||
mod digit_keys;
|
||||
mod dock;
|
||||
mod dock_apply;
|
||||
|
||||
+91
-20
@@ -113,6 +113,57 @@ fn time_expr(t: Tick, rate: Option<FrameRate>) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// The caption text as the tag parser sees it: one byte at a time, counted in tests.
|
||||
mod reader {
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// Calls to [`Reader::byte`] on this thread (tests: the tag parser's work is linear in the text).
|
||||
pub(super) static READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// The bytes of a caption text, read only through [`Reader::byte`].
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct Reader<'a> {
|
||||
bytes: &'a [u8],
|
||||
}
|
||||
|
||||
impl<'a> Reader<'a> {
|
||||
pub(super) fn new(bytes: &'a [u8]) -> Self {
|
||||
Self { bytes }
|
||||
}
|
||||
|
||||
/// The byte at `index`, or `None` past the end.
|
||||
pub(super) fn byte(self, index: usize) -> Option<u8> {
|
||||
#[cfg(test)]
|
||||
READS.with(|r| r.set(r.get().saturating_add(1)));
|
||||
self.bytes.get(index).copied()
|
||||
}
|
||||
|
||||
/// The bytes from `start` to the end, each read through [`Reader::byte`].
|
||||
pub(super) fn suffix(self, start: usize) -> Suffix<'a> {
|
||||
Suffix { reader: self, next: start }
|
||||
}
|
||||
}
|
||||
|
||||
/// Iterator returned by [`Reader::suffix`].
|
||||
pub(super) struct Suffix<'a> {
|
||||
reader: Reader<'a>,
|
||||
next: usize,
|
||||
}
|
||||
|
||||
impl Iterator for Suffix<'_> {
|
||||
type Item = u8;
|
||||
|
||||
fn next(&mut self) -> Option<u8> {
|
||||
let c = self.reader.byte(self.next)?;
|
||||
self.next = self.next.saturating_add(1);
|
||||
Some(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
use reader::Reader;
|
||||
|
||||
/// Memoised "next occurrence of a quote byte" searches, so unterminated quotes are not rescanned.
|
||||
#[derive(Default)]
|
||||
struct QuoteCache {
|
||||
@@ -121,7 +172,7 @@ struct QuoteCache {
|
||||
|
||||
impl QuoteCache {
|
||||
/// Index of the next `quote` byte at or after `from`.
|
||||
fn next(&mut self, bytes: &[u8], quote: u8, from: usize) -> Option<usize> {
|
||||
fn next(&mut self, bytes: Reader<'_>, quote: u8, from: usize) -> Option<usize> {
|
||||
let slot = usize::from(quote == b'\'');
|
||||
if let Some((searched, result)) = self.found[slot]
|
||||
&& searched <= from
|
||||
@@ -129,7 +180,7 @@ impl QuoteCache {
|
||||
{
|
||||
return result;
|
||||
}
|
||||
let result = bytes.get(from..).and_then(|t| t.iter().position(|&c| c == quote)).map(|i| from + i);
|
||||
let result = bytes.suffix(from).position(|c| c == quote).map(|i| from + i);
|
||||
self.found[slot] = Some((from, result));
|
||||
result
|
||||
}
|
||||
@@ -139,42 +190,42 @@ impl QuoteCache {
|
||||
/// letters/digits starting with a letter immediately after, then whitespace-separated
|
||||
/// `name="value"` / `name='value'` attributes, optional `/` before `>`. A `>` inside a quoted
|
||||
/// value does not end the tag. Returns `(index after '>', closing, lowercase name)`; the name is empty for a self-closing tag.
|
||||
fn parse_tag(bytes: &[u8], start: usize, cache: &mut QuoteCache) -> Option<(usize, bool, String)> {
|
||||
fn parse_tag(bytes: Reader<'_>, start: usize, cache: &mut QuoteCache) -> Option<(usize, bool, String)> {
|
||||
let mut i = start + 1;
|
||||
let closing = bytes.get(i) == Some(&b'/');
|
||||
let closing = bytes.byte(i) == Some(b'/');
|
||||
if closing {
|
||||
i += 1;
|
||||
}
|
||||
let name_start = i;
|
||||
if !bytes.get(i)?.is_ascii_alphabetic() {
|
||||
if !bytes.byte(i)?.is_ascii_alphabetic() {
|
||||
return None;
|
||||
}
|
||||
while bytes.get(i).is_some_and(u8::is_ascii_alphanumeric) {
|
||||
let mut name = String::new();
|
||||
while let Some(c) = bytes.byte(i).filter(u8::is_ascii_alphanumeric) {
|
||||
name.push(char::from(c.to_ascii_lowercase()));
|
||||
i += 1;
|
||||
}
|
||||
let name = String::from_utf8_lossy(bytes.get(name_start..i)?).to_ascii_lowercase();
|
||||
loop {
|
||||
let ws_start = i;
|
||||
while bytes.get(i).is_some_and(u8::is_ascii_whitespace) {
|
||||
while bytes.byte(i).is_some_and(|c| c.is_ascii_whitespace()) {
|
||||
i += 1;
|
||||
}
|
||||
match bytes.get(i)? {
|
||||
match bytes.byte(i)? {
|
||||
b'>' => return Some((i + 1, closing, name)),
|
||||
// self-closing: no markup
|
||||
b'/' if !closing && bytes.get(i + 1) == Some(&b'>') => return Some((i + 2, closing, String::new())),
|
||||
b'/' if !closing && bytes.byte(i + 1) == Some(b'>') => return Some((i + 2, closing, String::new())),
|
||||
_ => {}
|
||||
}
|
||||
if i == ws_start {
|
||||
return None;
|
||||
}
|
||||
let key_start = i;
|
||||
while bytes.get(i).is_some_and(|c| c.is_ascii_alphanumeric() || matches!(c, b'-' | b':' | b'_')) {
|
||||
while bytes.byte(i).is_some_and(|c| c.is_ascii_alphanumeric() || matches!(c, b'-' | b':' | b'_')) {
|
||||
i += 1;
|
||||
}
|
||||
if i == key_start || bytes.get(i) != Some(&b'=') {
|
||||
if i == key_start || bytes.byte(i) != Some(b'=') {
|
||||
return None;
|
||||
}
|
||||
let quote = *bytes.get(i + 1)?;
|
||||
let quote = bytes.byte(i + 1)?;
|
||||
if quote != b'"' && quote != b'\'' {
|
||||
return None;
|
||||
}
|
||||
@@ -204,10 +255,11 @@ fn inline(text: &str) -> String {
|
||||
};
|
||||
let mut rest = text;
|
||||
let mut cache = QuoteCache::default();
|
||||
let bytes = Reader::new(text.as_bytes());
|
||||
while !rest.is_empty() {
|
||||
// Only a well-formed tag is markup; "1 < 2 and 3 > 2" and "a<b and c>d" are text.
|
||||
if rest.starts_with('<')
|
||||
&& let Some((end, closing, name)) = parse_tag(text.as_bytes(), text.len() - rest.len(), &mut cache)
|
||||
&& let Some((end, closing, name)) = parse_tag(bytes, text.len() - rest.len(), &mut cache)
|
||||
{
|
||||
let attr = match name.as_str() {
|
||||
"i" => Some("tts:fontStyle=\"italic\""),
|
||||
@@ -1171,15 +1223,34 @@ mod tests {
|
||||
assert_eq!(out, "<span tts:fontStyle=\"italic\">x</span>");
|
||||
}
|
||||
|
||||
/// `inline(text)` and the number of bytes the tag parser read for it.
|
||||
fn inline_cost(text: &str) -> (String, usize) {
|
||||
reader::READS.with(|r| r.set(0));
|
||||
let out = inline(text);
|
||||
(out, reader::READS.with(std::cell::Cell::get))
|
||||
}
|
||||
|
||||
/// The tag parser reads each byte of `text` a bounded number of times, and twice the text costs about twice the work.
|
||||
fn assert_linear(make: impl Fn(usize) -> String, escaped: impl Fn(usize) -> String) {
|
||||
let (out, small) = inline_cost(&make(50_000));
|
||||
assert_eq!(out, escaped(50_000));
|
||||
let text = make(100_000);
|
||||
let (out, large) = inline_cost(&text);
|
||||
assert_eq!(out, escaped(100_000));
|
||||
assert!(large <= 3 * text.len(), "{large} byte reads in a text of {}", text.len());
|
||||
assert!(large < 3 * small, "twice the text, {small} then {large} byte reads");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unclosed_angle_brackets_are_escaped_in_one_pass() {
|
||||
// Every `<` used to search the rest of the text for a `>`, which made this quadratic.
|
||||
let text = "<".repeat(200_000);
|
||||
let started = std::time::Instant::now();
|
||||
let out = inline(&text);
|
||||
assert_eq!(out, "<".repeat(200_000));
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(5), "{:?}", started.elapsed());
|
||||
assert_linear(|n| "<".repeat(n), |n| "<".repeat(n));
|
||||
// A tag before the unclosed tail is still markup; the tail stays literal text.
|
||||
assert_eq!(inline("<i>a</i> 1 < 2"), "<span tts:fontStyle=\"italic\">a</span> 1 < 2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn many_unmatched_angle_brackets_before_one_gt_are_read_once() {
|
||||
assert_linear(|n| format!("{}>", "<".repeat(n)), |n| format!("{}>", "<".repeat(n)));
|
||||
}
|
||||
}
|
||||
@@ -66,11 +66,10 @@ fn whitespace_after_lt_is_literal_text() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The work for this text is checked in `ttml.rs`'s `many_unmatched_angle_brackets_before_one_gt_are_read_once`.
|
||||
#[test]
|
||||
fn many_unmatched_lt_is_fast() {
|
||||
fn many_unmatched_lt_stay_text() {
|
||||
let input = format!("{}>", "<".repeat(256_000));
|
||||
let start = std::time::Instant::now();
|
||||
let text = export(&input, Format::Ttml);
|
||||
assert!(start.elapsed() < std::time::Duration::from_secs(2), "took {:?}", start.elapsed());
|
||||
assert!(text.contains(&format!("{}>", "<".repeat(256_000))));
|
||||
}
|
||||
@@ -6,7 +6,7 @@
|
||||
//! that says whose storage this is, a Save As page that picks a folder and
|
||||
//! names a file, and a save that refuses to overwrite somebody else's work.
|
||||
//!
|
||||
//! Three things shape the implementation.
|
||||
//! Four things shape the implementation.
|
||||
//!
|
||||
//! Nothing here opens a socket. Every call goes through [`CloudBackend`]. A
|
||||
//! host writes that half. This module never learns what it reaches. That keeps
|
||||
@@ -21,6 +21,12 @@
|
||||
//! list under a heading reads to a user as a broken window. A feature the
|
||||
//! provider does not have is therefore absent, heading and all.
|
||||
//!
|
||||
//! Nothing here acts on a stale answer. Every answer carries the account
|
||||
//! generation its job was issued in, and [`pump`] drops one whose generation
|
||||
//! is no longer current, so a reply that arrives after a sign-out or a new
|
||||
//! sign-in is not applied to the session that replaced its own. A new kind of
|
||||
//! answer follows the same rule.
|
||||
//!
|
||||
//! The application supplies [`CloudApp`]. That is what it alone can answer.
|
||||
//! What its documents are, how bytes become one and back, and the words it
|
||||
//! shows them in.
|
||||
|
||||
@@ -5,12 +5,11 @@
|
||||
//! look or change, add a note, decide whether an email goes out, and see who
|
||||
//! already has access so one of them can be taken away again.
|
||||
//!
|
||||
//! Three things shape the implementation.
|
||||
//! Four things shape the implementation.
|
||||
//!
|
||||
//! Nothing here opens a socket. Every call goes through [`ShareBackend`], and
|
||||
//! nothing here reaches the network. A host writes the backend, and this
|
||||
//! module never learns what it talks to.
|
||||
//! this file.
|
||||
//!
|
||||
//! Nothing here blocks. Answers arrive on a channel and are read once per
|
||||
//! frame. Autocomplete waits [`DEBOUNCE`] after the last keystroke before it
|
||||
@@ -21,6 +20,17 @@
|
||||
//! false until the service says sharing exists, and an app hides its Share
|
||||
//! control rather than offering a button that fails. Contacts and mail are
|
||||
//! reported separately and are hidden the same way.
|
||||
//!
|
||||
//! Nothing here acts on a stale answer. Every request carries a sequence
|
||||
//! number, and its answer comes back with it. An answer is applied only while
|
||||
//! the request it answers still stands: an answer to a query the
|
||||
//! user has typed past, a link granted or an account linked for a sheet that
|
||||
//! has since closed or moved to another document, and a capabilities answer
|
||||
//! to a question asked before [`ShareDialog::refresh`],
|
||||
//! [`ShareDialog::connect`] or [`ShareDialog::signed_out`] are dropped. A
|
||||
//! withdrawal is the one answer applied by share id instead: the share is gone
|
||||
//! on the service, so it leaves every list that still shows it. A new kind of
|
||||
//! answer follows the sequence rule.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::mpsc::{Receiver, Sender};
|
||||
@@ -226,7 +236,9 @@ struct Sheet {
|
||||
/// Where it could be saved. `None` until the answer arrives.
|
||||
destinations: Option<Vec<Destination>>,
|
||||
destinations_seq: Option<u64>,
|
||||
link_seq: Option<u64>,
|
||||
/// Account links in flight, by request. More than one can be: every
|
||||
/// unlinked destination stays clickable while another one links.
|
||||
linking: Vec<u64>,
|
||||
/// Which one is selected, by id.
|
||||
destination: Option<String>,
|
||||
/// The name typed while the document still has nowhere to live.
|
||||
@@ -248,7 +260,7 @@ impl Sheet {
|
||||
Sheet {
|
||||
destinations: None,
|
||||
destinations_seq: None,
|
||||
link_seq: None,
|
||||
linking: Vec::new(),
|
||||
destination: None,
|
||||
save_as: title.clone(),
|
||||
saving: None,
|
||||
@@ -740,16 +752,16 @@ impl ShareDialog {
|
||||
}
|
||||
}
|
||||
Answer::Linked => {
|
||||
// An account arrived, so the list is stale. With no sheet open
|
||||
// there is no list to reload.
|
||||
if self.open.is_some() {
|
||||
if let Some(sheet) = &mut self.open {
|
||||
sheet.destinations = None;
|
||||
}
|
||||
let seq = self.issue(Request::Destinations);
|
||||
if let Some(sheet) = &mut self.open {
|
||||
sheet.destinations_seq = Some(seq);
|
||||
}
|
||||
// Only for the sheet that asked: after the sheet closed, moved
|
||||
// to another document or the account signed out, a late
|
||||
// answer asks the service for nothing.
|
||||
let Some(sheet) = self.open.as_mut().filter(|sheet| sheet.linking.contains(&seq)) else { return };
|
||||
// An account arrived, so the list is stale.
|
||||
sheet.linking.retain(|s| *s != seq);
|
||||
sheet.destinations = None;
|
||||
let seq = self.issue(Request::Destinations);
|
||||
if let Some(sheet) = &mut self.open {
|
||||
sheet.destinations_seq = Some(seq);
|
||||
}
|
||||
}
|
||||
Answer::Withdrawn { share_id } => {
|
||||
@@ -802,8 +814,8 @@ impl ShareDialog {
|
||||
sheet.destinations_seq = None;
|
||||
sheet.destinations = Some(Vec::new());
|
||||
sheet.save_error = Some(reason);
|
||||
} else if sheet.link_seq == Some(seq) {
|
||||
sheet.link_seq = None;
|
||||
} else if sheet.linking.contains(&seq) {
|
||||
sheet.linking.retain(|s| *s != seq);
|
||||
sheet.save_error = Some(reason);
|
||||
}
|
||||
}
|
||||
@@ -845,7 +857,7 @@ impl ShareDialog {
|
||||
// application's business and not this crate's.
|
||||
let seq = self.issue(Request::Link { destination });
|
||||
if let Some(sheet) = &mut self.open {
|
||||
sheet.link_seq = Some(seq);
|
||||
sheet.linking.push(seq);
|
||||
sheet.error = None;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -307,6 +307,49 @@ fn a_link_granted_after_the_sheet_moved_on_is_not_copied() {
|
||||
assert!(copied(&ctx).is_empty(), "nor after the sheet closed");
|
||||
}
|
||||
|
||||
fn destinations_asked(backend: &Silent) -> usize {
|
||||
backend.seen().iter().filter(|r| **r == Request::Destinations).count()
|
||||
}
|
||||
|
||||
fn last_link(dialog: &ShareDialog) -> u64 {
|
||||
dialog.open.as_ref().and_then(|s| s.linking.last().copied()).expect("asked")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_account_linked_for_a_sheet_that_moved_on_asks_for_nothing() {
|
||||
let (ctx, mut dialog, _) = ready();
|
||||
dialog.apply(&ctx, vec![Act::Link("drive".into())]);
|
||||
let first = last_link(&dialog);
|
||||
// A second destination is clicked before the first one answers.
|
||||
dialog.apply(&ctx, vec![Act::Link("mail".into())]);
|
||||
let second = last_link(&dialog);
|
||||
dialog.receive(&ctx, first, Ok(Answer::Linked));
|
||||
let sheet = dialog.open.as_ref().expect("open");
|
||||
assert!(sheet.destinations_seq.is_some(), "the sheet that asked fetches its destinations again");
|
||||
assert_eq!(sheet.linking, [second], "the later link is still in flight");
|
||||
dialog.receive(&ctx, second, Err("no account".into()));
|
||||
let sheet = dialog.open.as_ref().expect("open");
|
||||
assert!(sheet.linking.is_empty());
|
||||
assert_eq!(sheet.save_error.as_deref(), Some("no account"));
|
||||
|
||||
let (ctx, mut dialog, backend) = ready();
|
||||
dialog.apply(&ctx, vec![Act::Link("drive".into())]);
|
||||
let linking = last_link(&dialog);
|
||||
dialog.close();
|
||||
dialog.open("files/plan.docx", "Plan");
|
||||
let before = destinations_asked(&backend);
|
||||
dialog.receive(&ctx, linking, Ok(Answer::Linked));
|
||||
assert_eq!(destinations_asked(&backend), before, "the budget's link answer must not ask anything for the plan");
|
||||
|
||||
let (ctx, mut dialog, backend) = ready();
|
||||
dialog.apply(&ctx, vec![Act::Link("drive".into())]);
|
||||
let linking = last_link(&dialog);
|
||||
dialog.signed_out();
|
||||
let before = destinations_asked(&backend);
|
||||
dialog.receive(&ctx, linking, Ok(Answer::Linked));
|
||||
assert_eq!(destinations_asked(&backend), before, "nothing is asked for an account that signed out");
|
||||
}
|
||||
|
||||
/// Whether one frame of the sheet offers "Get a link" as a button that can
|
||||
/// be pressed, read off the accessibility tree.
|
||||
fn link_button_enabled(dialog: &mut ShareDialog) -> Option<bool> {
|
||||
|
||||
@@ -10,5 +10,7 @@ The colour model and conversions are in `craft-theme`; profiles and transforms i
|
||||
|
||||
`ColorPanel::edited` can supply a colour's native components. Editing one channel preserves the other components,
|
||||
even when the host renders the colour through a different working-space transform. Current host components take
|
||||
precedence over the panel's remembered values. Canceling a channel gesture restores the host's complete opening
|
||||
colour, including its display colour, alpha and native components.
|
||||
precedence over the panel's remembered values. Canceling a channel or ramp gesture restores the host's complete opening
|
||||
color, including its display color, alpha and native components. The `before` of an edit from the channels, the ramp,
|
||||
a hex field, the readout, the out-of-gamut chip, the Black and White wells or a Recent Colors chip is that complete
|
||||
color, so Undo returns to it.
|
||||
@@ -260,6 +260,16 @@ pub struct EyedropperPick {
|
||||
pub background: bool,
|
||||
}
|
||||
|
||||
/// The sampling ring while the button is held: its centre on screen and the sampled colour it shows.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub struct EyedropperRing {
|
||||
/// The pointer at the sample, on screen.
|
||||
pub center: Pos2,
|
||||
/// The sampled colour: the upper half of the ring.
|
||||
pub color: Srgba,
|
||||
}
|
||||
|
||||
/// The pipette icon's tip, in the icon's own 24-unit box.
|
||||
pub(super) const HOTSPOT: [f32; 2] = [2.0, 22.0];
|
||||
/// The ring's outer radius in points.
|
||||
@@ -274,7 +284,7 @@ const RING_SEGMENTS: usize = 48;
|
||||
pub struct EyedropperTool<'a> {
|
||||
options: EyedropperOptions,
|
||||
sample: Box<dyn FnMut([f64; 2], SampleSize, SampleSource) -> Option<Srgba> + 'a>,
|
||||
held: Option<(Pos2, Srgba)>,
|
||||
held: Option<EyedropperRing>,
|
||||
picked: Option<EyedropperPick>,
|
||||
foreground: Srgba,
|
||||
}
|
||||
@@ -293,6 +303,19 @@ impl<'a> EyedropperTool<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
/// The ring a previous tool held: an app that builds the tool anew each pass hands back what
|
||||
/// [`ring`](Self::ring) gave the last pass, so a pass with no pointer input still paints the ring.
|
||||
#[must_use]
|
||||
pub fn held(mut self, ring: Option<EyedropperRing>) -> Self {
|
||||
self.held = ring;
|
||||
self
|
||||
}
|
||||
|
||||
/// The ring while the button is held over the document; `None` once it is up or the gesture is cancelled.
|
||||
pub fn ring(&self) -> Option<EyedropperRing> {
|
||||
self.held
|
||||
}
|
||||
|
||||
/// The newest pick, once.
|
||||
pub fn take(&mut self) -> Option<EyedropperPick> {
|
||||
self.picked.take()
|
||||
@@ -303,7 +326,7 @@ impl<'a> EyedropperTool<'a> {
|
||||
let Point { x, y } = space.view.to_doc(pointer.pos);
|
||||
match (self.sample)([x, y], self.options.size, self.options.source) {
|
||||
Some(color) => {
|
||||
self.held = Some((pointer.pos, color));
|
||||
self.held = Some(EyedropperRing { center: pointer.pos, color });
|
||||
self.picked = Some(EyedropperPick { color, background: pointer.mods.alt });
|
||||
}
|
||||
None => self.held = None,
|
||||
@@ -351,7 +374,7 @@ impl CanvasTool for EyedropperTool<'_> {
|
||||
}
|
||||
|
||||
fn paint(&self, draw: &Draw<'_>, cx: &ToolContext<'_>) {
|
||||
let (true, Some((center, new)), Some(style)) = (self.options.show_ring, self.held, cx.style()) else { return };
|
||||
let (true, Some(EyedropperRing { center, color: new }), Some(style)) = (self.options.show_ring, self.held, cx.style()) else { return };
|
||||
let tokens = style.tokens;
|
||||
let inner = RING_OUTER_RADIUS - 2.0 * RING_BAND;
|
||||
band(draw, center, (inner, inner + RING_BAND), (PI, TAU), new);
|
||||
|
||||
@@ -19,7 +19,7 @@ use std::sync::Arc;
|
||||
use super::picker::{ChannelRow, ChannelRule};
|
||||
use super::{ColorDisc, DiscHit, DiscLook, DiscRadius};
|
||||
use crate::harmony::{Guide, GuideOptions, Harmony, Variation};
|
||||
use craft_ui::choice::{CellMarks, SwatchTable, SwatchTableOutput};
|
||||
use craft_ui::choice::{CellMarks, SwatchSpacing, SwatchTable, SwatchTableOutput};
|
||||
|
||||
#[cfg(feature = "suite")]
|
||||
pub(crate) mod stories;
|
||||
@@ -503,6 +503,7 @@ impl<'a> HarmonyPanel<'a> {
|
||||
.multiple(true)
|
||||
.per_row(columns)
|
||||
.span(true)
|
||||
.spacing(SwatchSpacing::Spaced)
|
||||
.marks(move |&at| CellMarks::default().edge(at % columns == centre))
|
||||
.selection(Bind::bound(&mut selection));
|
||||
let SwatchTableOutput { selected, chosen: clicked, .. } = dragging(table, payload.as_ref(), &grid_cells).show_all(ui);
|
||||
|
||||
@@ -53,7 +53,7 @@ pub use compare::{CompareSwatch, CompareSwatchOutput, CompareSwatchStyle};
|
||||
pub use disc::{ColorDisc, ColorDiscOutput, ColorDiscStyle, ColorDiscWords, DiscHit, DiscLook, DiscMove, DiscRadius, patch_at};
|
||||
pub use droppers::{DropperButton, DropperButtonOutput, DropperKind, DropperTool};
|
||||
pub use eyedropper::{
|
||||
EyedropperBar, EyedropperBarOutput, EyedropperOptions, EyedropperPick, EyedropperTool, EyedropperWords, SampleSize, SampleSource,
|
||||
EyedropperBar, EyedropperBarOutput, EyedropperOptions, EyedropperPick, EyedropperRing, EyedropperTool, EyedropperWords, SampleSize, SampleSource,
|
||||
};
|
||||
pub use harmony::{
|
||||
GuideCell, GuideCellAt, HarmonyCommand, HarmonyMenu, HarmonyMenuAction, HarmonyPanel, HarmonyPanelOutput, HarmonyPanelState, HarmonyPicked,
|
||||
|
||||
@@ -6,7 +6,7 @@ use craft_ui::buttons::IconButton;
|
||||
use craft_ui::choice::{ChoiceWords, Swatch, SwatchMetrics, SwatchStyle};
|
||||
use craft_ui::contract::{
|
||||
Access, Bind, BindMut, Common, Component, Cx, DragPreview, DropMark, DropOperation, DropTarget, Edit as _, EditResponse, Focus as _, MeasureCx,
|
||||
Meta as _, Outcome, Overlay, OverlayUi, Overlays as _, PaintUi, PartsCx, Pointer as _, Props as _, Remember as _, Role, WordSetCx as _,
|
||||
Meta as _, Name, Outcome, Overlay, OverlayUi, Overlays as _, PaintUi, PartsCx, Pointer as _, Props as _, Remember as _, Role, WordSetCx as _,
|
||||
};
|
||||
use craft_ui::primitives::{Glyph, IconSpec, PaintShape, StrokeWidth, WellFill};
|
||||
use craft_ui::runtime::commands::FireSource;
|
||||
@@ -571,8 +571,11 @@ impl<P: Clone + Send + Sync + 'static> Component for SwatchPair<'_, P> {
|
||||
Some(paint) => paint_value(&cx.words::<PaintWords>(), paint),
|
||||
None => cx.words::<ChoiceWords>().swatch_mixed.as_str().to_owned(),
|
||||
};
|
||||
// The two wells are a choice of the active colour: radios, the front one checked, with the colour as value.
|
||||
access.node(WELL.at(i as u64), Role::RADIO_BUTTON).value(value);
|
||||
// The two wells are a choice of the active colour: radios, the front one checked, with the colour as value,
|
||||
// each named by its own label ("Fill", "Stroke"), not the pair's.
|
||||
let node = access.node(WELL.at(i as u64), Role::RADIO_BUTTON);
|
||||
node.name = Name::Text(cx.env.resolve(&well.label).as_str().to_owned());
|
||||
node.value(value);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -417,6 +417,8 @@ struct Kept {
|
||||
dragging: bool,
|
||||
/// The host's complete colour before a model gesture, independent of the panel's transform.
|
||||
opening: Option<(GestureId, PanelTarget, PickedColor)>,
|
||||
/// Both colors, complete, before a gesture of the ramp, a hex field or the readout.
|
||||
colors_opening: Option<(GestureId, [PickedColor; 2])>,
|
||||
/// The ramp gesture in progress picks for the colour not edited.
|
||||
other: bool,
|
||||
}
|
||||
@@ -977,6 +979,42 @@ impl Body<'_> {
|
||||
self.inputs.edited.and_then(Option::as_ref)
|
||||
}
|
||||
|
||||
/// The complete color of `target`: the host's `edited` color with its model values for the edited well, else
|
||||
/// the well's color.
|
||||
fn complete(&self, target: PanelTarget) -> PickedColor {
|
||||
match self.picked() {
|
||||
Some(picked) if target == self.target => *picked,
|
||||
_ => PickedColor { color: self.colors[target.index()], model: None },
|
||||
}
|
||||
}
|
||||
|
||||
/// Pushes `event` for `target` with the complete color it started from as its `before`: the color when its
|
||||
/// gesture began, kept through the host's live updates, or the current color for a `Set`.
|
||||
fn push_from_complete(&mut self, target: PanelTarget, mut event: EditEvent<PickedColor>) {
|
||||
if let EditEvent::Begin { id, .. } = &event {
|
||||
self.kept.colors_opening = Some((*id, [self.complete(PanelTarget::Foreground), self.complete(PanelTarget::Background)]));
|
||||
}
|
||||
let opening = self.kept.colors_opening.filter(|(id, _)| Some(*id) == event.id()).map(|(_, colors)| colors[target.index()]);
|
||||
match &mut event {
|
||||
EditEvent::Begin { before, .. } | EditEvent::Commit { before, .. } => {
|
||||
if let Some(picked) = opening {
|
||||
*before = Mixed::Same(picked);
|
||||
}
|
||||
}
|
||||
EditEvent::Cancel { before, .. } => {
|
||||
if let Some(picked) = opening {
|
||||
*before = Some(Mixed::Same(picked));
|
||||
}
|
||||
}
|
||||
EditEvent::Set { before, .. } => *before = Mixed::Same(self.complete(target)),
|
||||
_ => {}
|
||||
}
|
||||
if matches!(event.phase(), Some(GesturePhase::Commit | GesturePhase::Cancel) | None) {
|
||||
self.kept.colors_opening = None;
|
||||
}
|
||||
self.push(target, event);
|
||||
}
|
||||
|
||||
/// Whether the rows edit anything: the host gave no `edited(None)`.
|
||||
fn enabled(&self) -> bool {
|
||||
self.inputs.edited.is_none_or(Option::is_some)
|
||||
@@ -1090,7 +1128,7 @@ impl Body<'_> {
|
||||
if ColorWarningChip::new(&warning).arrangement(ColorWarningArrangement::Beside).show(ui).clicked {
|
||||
let picked = PickedColor { color: warning.nearest().with_alpha(color.a), model: None };
|
||||
let name = self.words.title.as_str();
|
||||
self.push(self.target, EditEvent::set(Mixed::Same(PickedColor { color, model: None }), picked, name.into(), None));
|
||||
self.push_from_complete(self.target, EditEvent::set(Mixed::Same(PickedColor { color, model: None }), picked, name.into(), None));
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -1271,7 +1309,7 @@ impl Body<'_> {
|
||||
let color = self.color();
|
||||
let edit = ColorReadout::new(self.words.hex_color.clone(), Bind::given(color.to_rgba())).show(ui);
|
||||
for event in edit.events {
|
||||
self.push(self.target, event.map(|rgba| PickedColor { color: Srgba::from(rgba).with_alpha(color.a), model: None }));
|
||||
self.push_from_complete(self.target, event.map(|rgba| PickedColor { color: Srgba::from(rgba).with_alpha(color.a), model: None }));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1309,7 +1347,7 @@ impl Body<'_> {
|
||||
}
|
||||
let target = if self.kept.other { self.target.other() } else { self.target };
|
||||
let alpha = self.colors[target.index()].a;
|
||||
self.push(target, event.map(|pick| PickedColor { color: pick.color.with_alpha(alpha), model: None }));
|
||||
self.push_from_complete(target, event.map(|pick| PickedColor { color: pick.color.with_alpha(alpha), model: None }));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -128,7 +128,7 @@ impl Body<'_> {
|
||||
.show(ui, |ui, _| TextField::hex(words.hex_color.clone(), Bind::given(color.to_rgba())).show(ui))
|
||||
.inner;
|
||||
for event in edit.into_iter().flat_map(|edit| edit.events) {
|
||||
self.push(self.target, event.map(|rgba| PickedColor::rgb(Srgba::from(rgba).with_alpha(color.a))));
|
||||
self.push_from_complete(self.target, event.map(|rgba| PickedColor::rgb(Srgba::from(rgba).with_alpha(color.a))));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -206,6 +206,9 @@ impl Body<'_> {
|
||||
fn set_color(&mut self, target: PanelTarget, color: Srgba) {
|
||||
let before = self.colors[target.index()];
|
||||
let name = self.words.title.as_str();
|
||||
self.push(target, EditEvent::set(Mixed::Same(PickedColor::rgb(before)), PickedColor::rgb(color.with_alpha(before.a)), name.into(), None));
|
||||
self.push_from_complete(
|
||||
target,
|
||||
EditEvent::set(Mixed::Same(PickedColor::rgb(before)), PickedColor::rgb(color.with_alpha(before.a)), name.into(), None),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -203,3 +203,20 @@ fn the_host_activates_the_other_well_while_one_keeps_the_focus_and_an_arrow_acti
|
||||
fixture.key(Key::ArrowRight, Modifiers::NONE).key(Key::ArrowLeft, Modifiers::NONE).settle();
|
||||
assert_eq!(active.get(), Well::Primary, "the arrow onto Fill makes it active");
|
||||
}
|
||||
|
||||
/// Each well is named by its own label, not the pair's: a screen reader, and a test, tells the two apart.
|
||||
#[trial]
|
||||
fn each_well_is_named_by_its_own_label() {
|
||||
let mut fixture = Fixture::new(|ui| {
|
||||
let wells = [PairWell::new("Fill", Srgba::rgb(0.1, 0.3, 0.8)), PairWell::new("Stroke", Srgba::rgb(1.0, 1.0, 1.0))];
|
||||
SwatchPair::<()>::new("Fill and Stroke", wells, Bind::given(Well::Primary)).popover(false).show(ui);
|
||||
});
|
||||
fixture.room(vec2(200.0, 200.0)).settle();
|
||||
let wells = fixture.by_role(Role::RADIO_BUTTON);
|
||||
let names: Vec<Option<&str>> = wells.iter().map(|well| fixture.tree().name_of(well.node)).collect();
|
||||
assert_eq!(names, vec![Some("Fill"), Some("Stroke")], "the two wells are radio buttons named by their own labels, the primary first");
|
||||
let fill = fixture.by_label("Fill").expect("a node is named Fill");
|
||||
let stroke = fixture.by_label("Stroke").expect("a node is named Stroke");
|
||||
assert_eq!(fill.node, wells[0].node, "Fill names the primary well's radio button");
|
||||
assert_eq!(stroke.node, wells[1].node, "Stroke names the secondary well's radio button");
|
||||
}
|
||||
@@ -343,16 +343,21 @@ fn a_disabled_fill_stroke_rgb_row_does_not_switch_its_units() {
|
||||
|
||||
/// A Color panel whose host supplies authoritative native CMYK components.
|
||||
fn native_cmyk_panel(picked: PickedColor) -> (Fixture, Rc<RefCell<PickedColor>>, Edits) {
|
||||
native_panel_in(picked, ColorPanelLayout::FillStroke, ColorPanelMode::CmykSliders)
|
||||
}
|
||||
|
||||
/// A Color panel in `layout` and `mode` whose host supplies authoritative native CMYK components.
|
||||
fn native_panel_in(picked: PickedColor, layout: ColorPanelLayout, mode: ColorPanelMode) -> (Fixture, Rc<RefCell<PickedColor>>, Edits) {
|
||||
let host = Rc::new(RefCell::new(picked));
|
||||
let edits: Edits = Default::default();
|
||||
let (color, output) = (host.clone(), edits.clone());
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let picked = *color.borrow();
|
||||
let mut state = ColorPanelState { mode: ColorPanelMode::CmykSliders, ..Default::default() };
|
||||
let mut state = ColorPanelState { mode, ..Default::default() };
|
||||
let shown = ColorPanel::new(Bind::bound(&mut state), [picked.color; 2])
|
||||
.layout(ColorPanelLayout::FillStroke)
|
||||
.layout(layout)
|
||||
.edited(Some(picked))
|
||||
.shown(ColorPanelShown::Mode(ColorPanelMode::CmykSliders))
|
||||
.shown(ColorPanelShown::Mode(mode))
|
||||
.show(ui);
|
||||
for (_, event) in &shown.edits {
|
||||
if let Some(picked) = event.landed() {
|
||||
@@ -433,6 +438,127 @@ fn a_canceled_native_channel_drag_restores_the_hosts_original_color() {
|
||||
assert_eq!(*host.borrow(), picked, "release after Cancel cannot reapply the preview");
|
||||
}
|
||||
|
||||
/// The color the last finished edit reports it started from: the `before` of its Commit or Set.
|
||||
fn last_before(edits: &Edits) -> PickedColor {
|
||||
edits
|
||||
.borrow()
|
||||
.iter()
|
||||
.rev()
|
||||
.find_map(|(_, event)| match event {
|
||||
EditEvent::Commit { before: Mixed::Same(before), .. } | EditEvent::Set { before: Mixed::Same(before), .. } => Some(*before),
|
||||
_ => None,
|
||||
})
|
||||
.expect("a finished edit")
|
||||
}
|
||||
|
||||
/// A ramp drag starts from the host's complete color: Cancel restores the native inks and Undo of a committed drag
|
||||
/// returns to them, even after the host applies the drag's live updates.
|
||||
#[trial]
|
||||
fn a_ramp_drag_restores_and_undoes_to_the_hosts_native_color() {
|
||||
let native = ModelValues::new("cmyk", &[12.345, 45.678, 78.912, 23.456]);
|
||||
let picked = PickedColor::in_model(Srgba::new(0.2, 0.4, 0.6, 0.7), native);
|
||||
let (mut fixture, host, edits) = native_cmyk_panel(picked);
|
||||
let ramp = fixture.by_label("Color Ramp").expect("the ramp");
|
||||
let from = ramp.rect.left_center() + Vec2::new(10.0, 0.0);
|
||||
fixture.drag_hold_at(from, Vec2::new(60.0, 0.0)).settle();
|
||||
assert_ne!(*host.borrow(), picked, "the host applies the live ramp preview");
|
||||
fixture.key(Key::Escape, Modifiers::NONE).settle();
|
||||
let canceled = edits
|
||||
.borrow()
|
||||
.iter()
|
||||
.rev()
|
||||
.find_map(|(_, event)| match event {
|
||||
EditEvent::Cancel { before: Some(Mixed::Same(before)), .. } => Some(*before),
|
||||
_ => None,
|
||||
})
|
||||
.expect("the ramp drag cancels");
|
||||
assert_eq!(canceled, picked, "Cancel carries the host's exact opening color and model");
|
||||
assert_eq!(*host.borrow(), picked, "the host restores the complete opening color");
|
||||
fixture.release_at(from + Vec2::new(60.0, 0.0)).settle();
|
||||
fixture.drag_at(from, Vec2::new(60.0, 0.0)).settle();
|
||||
assert_ne!(*host.borrow(), picked, "the ramp drag lands a new color");
|
||||
assert_eq!(last_before(&edits), picked, "the committed drag undoes to the host's color and model");
|
||||
}
|
||||
|
||||
/// Without an `edited` color, a canceled ramp drag restores the well's color from before the drag, after the host
|
||||
/// applies the drag's live updates to its wells.
|
||||
#[trial]
|
||||
fn a_canceled_ramp_drag_restores_the_wells_color() {
|
||||
let start = Srgba::new(0.2, 0.4, 0.6, 0.7);
|
||||
let wells = Rc::new(Cell::new([start, BLUE]));
|
||||
let edits: Edits = Default::default();
|
||||
let (colors, output) = (wells.clone(), edits.clone());
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut state = ColorPanelState { mode: ColorPanelMode::CmykSliders, ..Default::default() };
|
||||
let shown = ColorPanel::new(Bind::bound(&mut state), colors.get()).show(ui);
|
||||
for (target, event) in &shown.edits {
|
||||
if let Some(picked) = event.landed() {
|
||||
let mut now = colors.get();
|
||||
now[usize::from(*target == PanelTarget::Background)] = picked.color;
|
||||
colors.set(now);
|
||||
}
|
||||
}
|
||||
output.borrow_mut().extend(shown.edits);
|
||||
});
|
||||
fixture.room(COLOR_ROOM).settle();
|
||||
let ramp = fixture.by_label("Color Ramp").expect("the ramp");
|
||||
let from = ramp.rect.left_center() + Vec2::new(10.0, 0.0);
|
||||
fixture.drag_hold_at(from, Vec2::new(60.0, 0.0)).settle();
|
||||
assert_ne!(wells.get()[0], start, "the host applies the live ramp preview");
|
||||
fixture.key(Key::Escape, Modifiers::NONE).settle();
|
||||
let canceled = edits.borrow().iter().rev().find_map(|(_, event)| match event {
|
||||
EditEvent::Cancel { before, .. } => Some(*before),
|
||||
_ => None,
|
||||
});
|
||||
assert_eq!(canceled, Some(Some(Mixed::Same(PickedColor { color: start, model: None }))), "Cancel carries the well's color");
|
||||
assert_eq!(wells.get(), [start, BLUE], "the host restores the well's color");
|
||||
}
|
||||
|
||||
/// A hex entry, in the cubes' readout and in the FillStroke layout's hex field, undoes to the host's complete color,
|
||||
/// its native inks included.
|
||||
#[trial]
|
||||
fn a_hex_entry_undoes_to_the_hosts_native_color() {
|
||||
let native = ModelValues::new("cmyk", &[12.345, 45.678, 78.912, 23.456]);
|
||||
let picked = PickedColor::in_model(Srgba::new(0.2, 0.4, 0.6, 0.7), native);
|
||||
for (layout, mode) in
|
||||
[(ColorPanelLayout::ForegroundBackground, ColorPanelMode::HueCube), (ColorPanelLayout::FillStroke, ColorPanelMode::CmykSliders)]
|
||||
{
|
||||
let (mut fixture, host, edits) = native_panel_in(picked, layout, mode);
|
||||
let hex = fixture.by_label("Hex color").expect("the hex field");
|
||||
fixture.click(&hex);
|
||||
fixture.key(Key::A, Modifiers::COMMAND);
|
||||
fixture.type_text("996633");
|
||||
fixture.key(Key::Enter, Modifiers::NONE);
|
||||
fixture.settle();
|
||||
assert_ne!(*host.borrow(), picked, "{layout:?}: the hex entry lands a new color");
|
||||
assert_eq!(last_before(&edits), picked, "{layout:?}: the hex entry undoes to the host's color and model");
|
||||
}
|
||||
}
|
||||
|
||||
/// A click on the FillStroke layout's White well undoes to the host's complete color, its native inks included.
|
||||
#[trial]
|
||||
fn a_white_well_pick_undoes_to_the_hosts_native_color() {
|
||||
let native = ModelValues::new("cmyk", &[12.345, 45.678, 78.912, 23.456]);
|
||||
let picked = PickedColor::in_model(Srgba::new(0.2, 0.4, 0.6, 0.7), native);
|
||||
let (mut fixture, host, edits) = native_cmyk_panel(picked);
|
||||
let white = fixture.by_label("White").expect("the White well");
|
||||
fixture.click(&white).settle();
|
||||
assert_ne!(*host.borrow(), picked, "the White well lands white");
|
||||
assert_eq!(last_before(&edits), picked, "the White well's pick undoes to the host's color and model");
|
||||
}
|
||||
|
||||
/// A click on the out-of-gamut chip undoes to the host's complete color, its native inks included.
|
||||
#[trial]
|
||||
fn a_gamut_chip_pick_undoes_to_the_hosts_native_color() {
|
||||
let native = ModelValues::new("cmyk", &[12.345, 45.678, 78.912, 23.456]);
|
||||
let picked = PickedColor::in_model(Srgba::rgb(0.0, 0.0, 1.0), native);
|
||||
let (mut fixture, host, edits) = native_cmyk_panel(picked);
|
||||
let chip = fixture.by_label("Out of gamut for printing: click for the nearest printable color").expect("the out-of-gamut chip");
|
||||
fixture.click(&chip).settle();
|
||||
assert_ne!(*host.borrow(), picked, "the chip lands the nearest printable color");
|
||||
assert_eq!(last_before(&edits), picked, "the chip's pick undoes to the host's color and model");
|
||||
}
|
||||
|
||||
/// The rect of the FillStroke spectrum in Web Color for a foreground of `color`.
|
||||
fn spectrum_rect(color: Srgba) -> egui::Rect {
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
@@ -1451,3 +1577,23 @@ fn the_color_guide_end_labels_sit_at_the_two_sides_of_the_grid() {
|
||||
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:?}");
|
||||
}
|
||||
|
||||
/// The Color Guide's variation cells stand apart: each cell's left edge lies right of the cell before it on its row,
|
||||
/// and each row's top lies below the row above it.
|
||||
#[trial]
|
||||
fn the_color_guide_variation_cells_stand_apart() {
|
||||
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");
|
||||
let cells: Vec<egui::Rect> =
|
||||
fixture.tree().children_of(grid.node).into_iter().filter_map(|key| fixture.target(key)).map(|cell| cell.rect).collect();
|
||||
assert!(cells.len() >= 4, "the grid holds its cells: {cells:?}");
|
||||
let (first, next) = (cells[0], cells[1]);
|
||||
assert!((first.center().y - next.center().y).abs() < 0.5, "the first two cells share a row: {cells:?}");
|
||||
assert!(next.left() >= first.right() + 1.0, "a gap lies between two cells of a row: {first:?}, {next:?}");
|
||||
let below = cells.iter().find(|cell| cell.top() > first.center().y).expect("a second row of cells");
|
||||
assert!(below.top() >= first.bottom() + 1.0, "a gap lies between two rows: {first:?}, {below:?}");
|
||||
}
|
||||
@@ -8,8 +8,9 @@ use craft_behavior::CanvasView;
|
||||
use craft_behavior::kurbo::Point;
|
||||
use craft_cms::convert::CmykConverter;
|
||||
use craft_color_ui::ui::{
|
||||
CaptureResult, CaptureSource, ColorPicker, ColorPickerLayout, ColorSamplerPass, ColorSamplerTool, ColorSamplers, MAX_SAMPLERS, PickedColor,
|
||||
SamplerCache, SamplerEvent, SamplerReadouts, ScreenColorPicker, ScreenPick, ScreenPickerWords, StillCapture,
|
||||
CaptureResult, CaptureSource, ColorPicker, ColorPickerLayout, ColorSamplerPass, ColorSamplerTool, ColorSamplers, EyedropperOptions,
|
||||
EyedropperTool, MAX_SAMPLERS, PickedColor, SamplerCache, SamplerEvent, SamplerReadouts, ScreenColorPicker, ScreenPick, ScreenPickerWords,
|
||||
StillCapture,
|
||||
};
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::contract::Bind;
|
||||
@@ -74,6 +75,25 @@ fn events(tool: &ToolFixture<ColorSamplerPass<'static>>) -> Vec<SamplerEvent> {
|
||||
tool.tool_mut().take_events()
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn the_held_sampling_ring_carries_over_to_the_next_pass_tool() {
|
||||
// An app whose sample closure borrows its state builds the tool anew each pass: the ring the press held must reach
|
||||
// the next pass's tool, which gets no pointer input to sample again, or the ring flickers (photocraft#17931).
|
||||
let red = Srgba::rgb(1.0, 0.0, 0.0);
|
||||
let tool = EyedropperTool::new(EyedropperOptions::default(), move |_, _, _| Some(red));
|
||||
let mut tool = ToolFixture::with_view("Eyedropper", tool, sampler_view, |_, _| {});
|
||||
tool.fixture().room(vec2(800.0, 600.0));
|
||||
tool.fixture().settle();
|
||||
let at = tool.canvas().rect.min + vec2(40.0, 30.0);
|
||||
tool.press_at(at);
|
||||
let ring = tool.tool().ring().expect("the held button shows the ring");
|
||||
assert_eq!((ring.center, ring.color), (at, red));
|
||||
let next = EyedropperTool::new(EyedropperOptions::default(), |_, _, _| None).held(Some(ring));
|
||||
assert_eq!(next.ring(), Some(ring));
|
||||
tool.release_at(at);
|
||||
assert_eq!(tool.tool().ring(), None, "the release ends the ring");
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_new_point_lands_at_the_release_and_a_dragged_point_moves_on_release() {
|
||||
// A new point: nothing at the press, an Add at the release; off the canvas or on Escape, nothing.
|
||||
|
||||
@@ -119,6 +119,7 @@ craft-metadata = { workspace = true, optional = true }
|
||||
craft-metafile = { workspace = true, optional = true }
|
||||
craft-midi = { workspace = true, optional = true }
|
||||
craft-mime = { workspace = true, optional = true }
|
||||
craft-nightly = { workspace = true, optional = true }
|
||||
craft-odf = { workspace = true, optional = true }
|
||||
craft-ods = { workspace = true, optional = true }
|
||||
craft-offcrypto = { workspace = true, optional = true }
|
||||
@@ -237,6 +238,7 @@ 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 }
|
||||
craft-raster3d = { workspace = true, optional = true }
|
||||
|
||||
[features]
|
||||
ui = [
|
||||
@@ -621,6 +623,7 @@ jxl-encode = ["jxl", "craft-jxl/encode"]
|
||||
|
||||
keymap = ["dep:craft-keymap"]
|
||||
keymap-egui = ["keymap", "craft-keymap/egui"]
|
||||
keymap-global = ["keymap", "craft-keymap/global"]
|
||||
|
||||
kiwi = ["dep:craft-kiwi"]
|
||||
|
||||
@@ -689,6 +692,8 @@ midi-serde = ["midi", "craft-midi/serde"]
|
||||
mime = ["dep:craft-mime"]
|
||||
mime-detect = ["mime", "craft-mime/detect"]
|
||||
|
||||
nightly = ["dep:craft-nightly"]
|
||||
|
||||
odf = ["dep:craft-odf"]
|
||||
odf-text = ["odf", "craft-odf/text"]
|
||||
|
||||
@@ -798,6 +803,8 @@ quit = ["dep:craft-quit"]
|
||||
|
||||
raster-codecs = ["dep:craft-raster-codecs"]
|
||||
|
||||
raster3d = ["dep:craft-raster3d"]
|
||||
|
||||
raw = ["dep:craft-raw"]
|
||||
raw-arw = ["raw", "craft-raw/arw"]
|
||||
raw-cr2 = ["raw", "craft-raw/cr2"]
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
/// The egui fork the library is built and tested with. Apps patch egui to exactly this.
|
||||
pub const GIT: &str = "https://github.com/storytold/egui.git";
|
||||
/// The commit of [`GIT`].
|
||||
pub const REV: &str = "932a73b28560acb1a695533307b2cd0d66a42081";
|
||||
pub const REV: &str = "14c39fed181756be6f357c284354e0ab55b64443";
|
||||
|
||||
/// The packages the workspace patches to the fork (the `[patch.crates-io]` entries that name [`GIT`]).
|
||||
pub const PACKAGES: &[&str] = &[
|
||||
|
||||
@@ -261,6 +261,8 @@ pub use craft_metafile as metafile;
|
||||
pub use craft_midi as midi;
|
||||
#[cfg(feature = "mime")]
|
||||
pub use craft_mime as mime;
|
||||
#[cfg(feature = "nightly")]
|
||||
pub use craft_nightly as nightly;
|
||||
#[cfg(feature = "odf")]
|
||||
pub use craft_odf as odf;
|
||||
#[cfg(feature = "ods")]
|
||||
@@ -329,6 +331,8 @@ pub use craft_pst as pst;
|
||||
pub use craft_quit as quit;
|
||||
#[cfg(feature = "raster-codecs")]
|
||||
pub use craft_raster_codecs as raster_codecs;
|
||||
#[cfg(feature = "raster3d")]
|
||||
pub use craft_raster3d as raster3d;
|
||||
#[cfg(feature = "raw")]
|
||||
pub use craft_raw as raw;
|
||||
#[cfg(feature = "review")]
|
||||
|
||||
@@ -20,6 +20,7 @@ use craft_ui::patterns::presets::{
|
||||
use craft_ui::primitives::{FacePaint, IconSpec};
|
||||
use craft_ui::runtime::env::{Env, Label, UnitKind};
|
||||
use craft_ui::runtime::overlay::CloseReason;
|
||||
use craft_ui::text::RangeAlert;
|
||||
use egui::{Pos2, Response, Ui};
|
||||
|
||||
use super::panel::{BRUSH_THUMBS, picks_of};
|
||||
@@ -156,6 +157,9 @@ pub struct BrushPresetPickerOutput<K> {
|
||||
pub hardness: EditEvents<f64>,
|
||||
/// The angle widget: the new angle and roundness.
|
||||
pub tip: EditEvents<TipAngle>,
|
||||
/// A value typed into Size or Hardness outside its range and clamped, in the pass it committed; never for a drag or
|
||||
/// a step. The host shows the range alert; the picker stays open.
|
||||
pub out_of_range: Option<RangeAlert>,
|
||||
/// Escape closed the picker: the values to set back, each the one it had when the picker opened (or a preset
|
||||
/// picked since brought) while it still holds the value the picker's head last set; a value changed from
|
||||
/// elsewhere since keeps that change. `None` when nothing goes back.
|
||||
@@ -355,13 +359,14 @@ impl<'a, K: Value + Eq + Hash + MemoProps> BrushPresetPicker<'a, K> {
|
||||
let next_search = Cell::new(before.search);
|
||||
let tool_picks: RefCell<Vec<BrushPick<K>>> = RefCell::new(Vec::new());
|
||||
let (mut diameter, mut hardness, mut tip) = (EditEvents::new(), EditEvents::new(), EditEvents::new());
|
||||
let mut out_of_range = None;
|
||||
let browser_id = ui.scope_id().with("browser");
|
||||
let head = |ui: &mut Ui, _: &mut BodyCx<'_>| {
|
||||
let mut sent = Vec::new();
|
||||
let props = HeadProps { values, max_diameter, sent: Outbox::new(&mut sent) };
|
||||
let _ = MemoView::new("head", props, head_view).show(ui);
|
||||
for edits in sent {
|
||||
(diameter, hardness, tip) = (edits.diameter, edits.hardness, edits.tip);
|
||||
(diameter, hardness, tip, out_of_range) = (edits.diameter, edits.hardness, edits.tip, edits.out_of_range);
|
||||
}
|
||||
if let Some(rows) = app_rows.take() {
|
||||
rows(ui);
|
||||
@@ -431,6 +436,7 @@ impl<'a, K: Value + Eq + Hash + MemoProps> BrushPresetPicker<'a, K> {
|
||||
diameter,
|
||||
hardness,
|
||||
tip,
|
||||
out_of_range,
|
||||
reverted,
|
||||
open: out.open,
|
||||
picks,
|
||||
@@ -445,6 +451,7 @@ impl<'a, K: Value + Eq + Hash + MemoProps> BrushPresetPicker<'a, K> {
|
||||
diameter: EditEvents::new(),
|
||||
hardness: EditEvents::new(),
|
||||
tip: EditEvents::new(),
|
||||
out_of_range: None,
|
||||
reverted: None,
|
||||
open: false,
|
||||
picks: Vec::new(),
|
||||
@@ -462,11 +469,12 @@ struct HeadProps<'a> {
|
||||
sent: Outbox<'a, HeadEdits>,
|
||||
}
|
||||
|
||||
/// What a run of the head reports: the Size, Hardness and angle widget edits.
|
||||
/// What a run of the head reports: the Size, Hardness and angle widget edits, and a value typed out of range.
|
||||
struct HeadEdits {
|
||||
diameter: EditEvents<f64>,
|
||||
hardness: EditEvents<f64>,
|
||||
tip: EditEvents<TipAngle>,
|
||||
out_of_range: Option<RangeAlert>,
|
||||
}
|
||||
|
||||
/// The head: the angle widget, Size and Hardness, then a divider. A memoized view, so a drag of its Size runs it
|
||||
@@ -474,17 +482,20 @@ struct HeadEdits {
|
||||
fn head_view(props: &mut HeadProps<'_>, ui: &mut Ui) {
|
||||
let words = Env::of(ui).words::<BrushPresetWords>();
|
||||
let (values, max_diameter) = (props.values, props.max_diameter);
|
||||
let mut edits = HeadEdits { diameter: EditEvents::new(), hardness: EditEvents::new(), tip: EditEvents::new() };
|
||||
let mut edits = HeadEdits { diameter: EditEvents::new(), hardness: EditEvents::new(), tip: EditEvents::new(), out_of_range: None };
|
||||
Row::new().show(ui, |ui, _| {
|
||||
if let Some(angle) = values.tip {
|
||||
edits.tip = TipEllipse::new(words.tip.clone(), Bind::given(angle)).show(ui).events;
|
||||
}
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
edits.diameter = BrushSizeField::new(words.size.clone(), Bind::given(values.diameter), max_diameter).show(ui).edit.events;
|
||||
let size = BrushSizeField::new(words.size.clone(), Bind::given(values.diameter), max_diameter).show(ui);
|
||||
edits.diameter = size.edit.events;
|
||||
edits.out_of_range = size.out_of_range;
|
||||
if let Some(value) = values.hardness {
|
||||
let field =
|
||||
SliderField::new(words.hardness.clone(), Bind::given(value * 100.0), 0.0..=100.0).step(1.0).unit_kind(UnitKind::Percent).show(ui);
|
||||
edits.hardness = field.edit.events.map(|percent| (percent / 100.0).clamp(0.0, 1.0));
|
||||
edits.out_of_range = field.out_of_range.or(edits.out_of_range.take());
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
use craft_ui::contract::{Bind, EditResponse, Outcome, Props as _, Show as _};
|
||||
use craft_ui::form::SliderField;
|
||||
use craft_ui::runtime::env::{Label, UnitKind};
|
||||
use craft_ui::text::RangeAlert;
|
||||
use craft_ui::value_drag::SliderScale;
|
||||
use egui::{Response, Ui};
|
||||
|
||||
@@ -15,6 +16,9 @@ pub struct BrushSizeOutput {
|
||||
pub response: Response,
|
||||
/// The slider field's edit.
|
||||
pub edit: EditResponse<f64>,
|
||||
/// A value typed into the field outside 1 to the maximum and clamped, in the pass it committed; never for a slider
|
||||
/// drag or a step. The host shows the range alert.
|
||||
pub out_of_range: Option<RangeAlert>,
|
||||
}
|
||||
|
||||
impl Outcome for BrushSizeOutput {
|
||||
@@ -62,13 +66,8 @@ impl<'a> BrushSizeField<'a> {
|
||||
Some(original) => diameter.reset(original.clamp(1.0, max)),
|
||||
None => diameter,
|
||||
};
|
||||
let edit = SliderField::new(label, diameter, 1.0..=max)
|
||||
.scale(SliderScale::Log)
|
||||
.step(1.0)
|
||||
.unit_kind(UnitKind::Pixels)
|
||||
.enabled(max > 1.0)
|
||||
.show(ui)
|
||||
.edit;
|
||||
BrushSizeOutput { response: edit.response.clone(), edit }
|
||||
let shown =
|
||||
SliderField::new(label, diameter, 1.0..=max).scale(SliderScale::Log).step(1.0).unit_kind(UnitKind::Pixels).enabled(max > 1.0).show(ui);
|
||||
BrushSizeOutput { response: shown.edit.response.clone(), edit: shown.edit, out_of_range: shown.out_of_range }
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,7 @@
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft_behavior::geometry::Constraint;
|
||||
use craft_behavior::geometry::{Constraint, SnapKind, SnapKinds};
|
||||
use craft_behavior::kurbo::Point;
|
||||
use craft_behavior::{CancelReason, Cursor, CursorIcon, EditEvent, GestureId, IconId, Mixed, PaintedCursor, PointerGlyph};
|
||||
use craft_theme::variant::Tone;
|
||||
@@ -130,6 +130,27 @@ fn boxed(anchor: Point, to: Point) -> PerspectiveQuad {
|
||||
(x1 > x0 && y1 > y0).then_some([Point::new(x0, y0), Point::new(x1, y0), Point::new(x1, y1), Point::new(x0, y1)])
|
||||
}
|
||||
|
||||
/// Where a box drag pressed at `press` starts. While the canvas snaps to the document bounds
|
||||
/// ([`ToolContext::snaps_to_document_bounds`]), a press beyond a document corner (outside on both axes) starts at that
|
||||
/// corner, and one within the snap distance of an edge starts on the nearest edge ([`ToolContext::snap_of`]). Any other
|
||||
/// press, and every press on a document whose size is negative or not finite, starts where it was. Clicked corners
|
||||
/// don't come here: they keep their place.
|
||||
fn drag_start(press: Point, cx: &ToolContext<'_>) -> Point {
|
||||
let size = cx.space().and_then(|space| space.document());
|
||||
// A size that is negative or not finite has no bounds to start on (and would make `clamp` panic): no snap at all.
|
||||
if size.is_some_and(|size| !(size.width.is_finite() && size.height.is_finite() && size.width >= 0.0 && size.height >= 0.0)) {
|
||||
return press;
|
||||
}
|
||||
if let Some(size) = size
|
||||
&& cx.snaps_to_document_bounds()
|
||||
&& !(0.0..=size.width).contains(&press.x)
|
||||
&& !(0.0..=size.height).contains(&press.y)
|
||||
{
|
||||
return Point::new(press.x.clamp(0.0, size.width), press.y.clamp(0.0, size.height));
|
||||
}
|
||||
cx.snap_of(press, SnapKinds::only(SnapKind::Bounds))
|
||||
}
|
||||
|
||||
/// What the host hands the perspective crop pass each frame.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
#[non_exhaustive]
|
||||
@@ -206,7 +227,8 @@ impl CanvasTool for PerspectiveCropPass<'_> {
|
||||
self.tool.events.push(PerspectiveCropEvent::Edit(EditEvent::begin(press.id, Mixed::Same(press.before), label, None)));
|
||||
}
|
||||
if press.began {
|
||||
let (a, b) = Constraint::Free.corners(press.anchor, space.view.to_doc(pointer.pos), pointer.mods.shift, pointer.mods.alt);
|
||||
// The snapped start shapes the box from its first move, so the drag shows where its release puts it.
|
||||
let (a, b) = Constraint::Free.corners(drag_start(press.anchor, cx), space.view.to_doc(pointer.pos), pointer.mods.shift, pointer.mods.alt);
|
||||
self.tool.quad = boxed(a, b);
|
||||
if self.tool.quad.is_some() {
|
||||
// A drag that makes no box keeps the corners clicked so far.
|
||||
|
||||
@@ -85,6 +85,8 @@ impl Outcome for StrokeEditorOutput {
|
||||
/// - While the style fails [`StrokeStyle::validate`], the invalid word shows at the end and nothing is reported.
|
||||
/// - [`mixed`](Self::mixed): a mixed field shows the mixed state and lights no button or preset; the first edit sets it
|
||||
/// for all.
|
||||
/// - [`host_labels`](Self::host_labels): shown in a host's [`FieldGroup`], the labeled rows read that group's label
|
||||
/// column, so their controls start where the controls of the host's rows start.
|
||||
///
|
||||
/// ```ignore
|
||||
/// let out = StrokeEditor::new("Stroke", Bind::bound(&mut style)).sections(StrokeSections::PANEL).show(ui);
|
||||
@@ -100,6 +102,7 @@ pub struct StrokeEditor<'a> {
|
||||
corners: bool,
|
||||
mixed: StrokeMixed,
|
||||
rows: &'a [StrokeChoiceRow<'a>],
|
||||
host_labels: bool,
|
||||
}
|
||||
|
||||
impl<'a> StrokeEditor<'a> {
|
||||
@@ -114,6 +117,7 @@ impl<'a> StrokeEditor<'a> {
|
||||
corners: true,
|
||||
mixed: StrokeMixed::default(),
|
||||
rows: &[],
|
||||
host_labels: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -155,9 +159,17 @@ impl<'a> StrokeEditor<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
/// Whether the editor's labeled rows read the label column of the [`FieldGroup`] the host shows the editor in, so
|
||||
/// their controls start where the controls of the host's rows in that group start. False by default: the rows
|
||||
/// then share a label column of their own.
|
||||
pub fn host_labels(mut self, on: bool) -> Self {
|
||||
self.host_labels = on;
|
||||
self
|
||||
}
|
||||
|
||||
/// Shows the editor.
|
||||
pub fn show(self, ui: &mut Ui) -> StrokeEditorOutput {
|
||||
let StrokeEditor { label, mut value, sections, closed, caps_on_closed, corners, mixed, rows } = self;
|
||||
let StrokeEditor { label, mut value, sections, closed, caps_on_closed, corners, mixed, rows, host_labels } = self;
|
||||
let env = Env::of(ui);
|
||||
let words = env.words::<StrokeWords>();
|
||||
let name: Arc<str> = label.as_str().into();
|
||||
@@ -173,7 +185,7 @@ impl<'a> StrokeEditor<'a> {
|
||||
Some((base, draft)) if base == held => draft,
|
||||
_ => held.clone(),
|
||||
};
|
||||
let body = Body { words: &words, style: &style, sections, closed, caps_on_closed, corners, mixed, rows, name: name.clone() };
|
||||
let body = Body { words: &words, style: &style, sections, closed, caps_on_closed, corners, mixed, rows, host_labels, name: name.clone() };
|
||||
body.show(ui, &mut found);
|
||||
if !found.events.is_empty() {
|
||||
for event in &found.events {
|
||||
@@ -264,11 +276,33 @@ struct Body<'a> {
|
||||
corners: bool,
|
||||
mixed: StrokeMixed,
|
||||
rows: &'a [StrokeChoiceRow<'a>],
|
||||
/// The labeled rows read the label column of the group around the editor.
|
||||
host_labels: bool,
|
||||
/// The name of the edits, for the host's undo.
|
||||
name: Arc<str>,
|
||||
}
|
||||
|
||||
impl Body<'_> {
|
||||
/// Shows `body`'s labeled rows as a group named `label`: a [`FieldGroup`] with a label column of its own, or with
|
||||
/// `host_labels` a stack as wide, whose rows read the label column of the group around the editor.
|
||||
fn group(&self, ui: &mut Ui, label: &Label, salt: Option<&'static str>, mut body: impl FnMut(&mut Ui)) {
|
||||
if self.host_labels {
|
||||
let stack = Stack::new().label(label.clone()).sizing(Sizing::FillWidth);
|
||||
match salt {
|
||||
Some(salt) => stack.id_salt(salt),
|
||||
None => stack,
|
||||
}
|
||||
.show(ui, |ui, _| body(ui));
|
||||
} else {
|
||||
let group = FieldGroup::new(label.clone());
|
||||
match salt {
|
||||
Some(salt) => group.id_salt(salt),
|
||||
None => group,
|
||||
}
|
||||
.show(ui, |ui, _| body(ui));
|
||||
}
|
||||
}
|
||||
|
||||
/// Reports the one-step change to `next`.
|
||||
fn set(&self, found: &mut Found, field: StrokeField, next: StrokeStyle) {
|
||||
let event = EditEvent::set(Mixed::Same(self.style.clone()), next, self.name.clone(), None);
|
||||
@@ -337,7 +371,7 @@ impl Body<'_> {
|
||||
let (style, mixed, words) = (self.style, self.mixed, self.words);
|
||||
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, _| {
|
||||
self.group(ui, &words.title, None, |ui| {
|
||||
let align = [
|
||||
(StrokeAlign::Inside, "stroke_align_inside", &words.inside),
|
||||
(StrokeAlign::Center, "stroke_align_center", &words.center),
|
||||
@@ -453,7 +487,7 @@ impl Body<'_> {
|
||||
}
|
||||
});
|
||||
}
|
||||
FieldGroup::new(words.dash_offset.clone()).id_salt("offset").show(ui, |ui, _| {
|
||||
self.group(ui, &words.dash_offset, Some("offset"), |ui| {
|
||||
let range = -f64::from(StrokeStyle::DASH_OFFSET_MAX)..=f64::from(StrokeStyle::DASH_OFFSET_MAX);
|
||||
let event =
|
||||
number(ui, &words.dash_offset, "dash-offset", f64::from(style.dash_offset), self.mixed.dash_offset, range, self.dash_unit(), true);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! The Brush Preset picker: Rename Brush… in the gear opens the browser's name field on the current preset; the app
|
||||
//! opens the picker at a point without its field; a resized picker keeps its size; the head edits angle and
|
||||
//! roundness; Escape reverts the head's edits.
|
||||
//! roundness; Escape reverts the head's edits; a Size or Hardness typed out of range reports the range alert.
|
||||
|
||||
use craft_draw::ui::brush_presets::{BrushCardParts, BrushPick, BrushPickerState, BrushPickerValues, BrushPresetPicker, BrushRowPaint, brush_row};
|
||||
use craft_draw::ui::brush_settings::TipAngle;
|
||||
@@ -10,6 +10,7 @@ use craft_ui::primitives::FacePaint;
|
||||
use craft_ui::runtime::env::Env;
|
||||
use craft_ui::testing::pointer::{moved, press, release};
|
||||
use craft_ui::testing::{Fixture, MemoRun, last_frame_memo_runs, trial};
|
||||
use craft_ui::text::RangeAlert;
|
||||
use egui::{Key, Modifiers, Pos2, Rect, Vec2};
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
@@ -74,6 +75,8 @@ struct Opened {
|
||||
at: Option<Pos2>,
|
||||
/// The space above the field.
|
||||
offset: f32,
|
||||
/// The range alerts the passes reported.
|
||||
alerts: Vec<RangeAlert>,
|
||||
}
|
||||
|
||||
const POINT: Pos2 = Pos2::new(160.0, 120.0);
|
||||
@@ -91,11 +94,12 @@ fn opened_rig(at_point: bool, remember: bool) -> (Fixture, Rc<RefCell<Opened>>)
|
||||
tip_edits: 0,
|
||||
at,
|
||||
offset: 0.0,
|
||||
alerts: Vec::new(),
|
||||
}));
|
||||
let shown = Rc::clone(&host);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut host = shown.borrow_mut();
|
||||
let Opened { current, state, values, open, tip_edits, at, offset } = &mut *host;
|
||||
let Opened { current, state, values, open, tip_edits, at, offset, alerts } = &mut *host;
|
||||
ui.add_space(*offset);
|
||||
let rows = PresetSource::new(state.parts, PresetFns::new(two_rows));
|
||||
let mut picker = BrushPresetPicker::new("Brush Preset picker", Bind::bound(current), &rows, Bind::bound(state), *values);
|
||||
@@ -116,6 +120,7 @@ fn opened_rig(at_point: bool, remember: bool) -> (Fixture, Rc<RefCell<Opened>>)
|
||||
values.tip = Some(*tip);
|
||||
}
|
||||
*tip_edits += out.tip.len();
|
||||
alerts.extend(out.out_of_range);
|
||||
if let Some(back) = out.reverted {
|
||||
*values = back;
|
||||
}
|
||||
@@ -226,6 +231,50 @@ fn escape_reverts_size_hardness_angle_and_roundness() {
|
||||
assert_eq!(host.borrow().values, OPENED, "Escape puts all four back");
|
||||
}
|
||||
|
||||
/// Types `text` into the head's number field named `label` and commits it with Enter.
|
||||
fn type_into(fixture: &mut Fixture, label: &str, text: &str) {
|
||||
let field = fixture.by_role(Role::SPIN_BUTTON).into_iter().find(|target| fixture.tree().name_of(target.node) == Some(label));
|
||||
let field = field.unwrap_or_else(|| panic!("the {label} field shows"));
|
||||
fixture.click(&field);
|
||||
fixture.key(Key::A, Modifiers::COMMAND);
|
||||
fixture.type_text(text);
|
||||
fixture.key(Key::Enter, Modifiers::NONE);
|
||||
fixture.idle(3);
|
||||
}
|
||||
|
||||
/// Size and Hardness typed past their ranges keep the closest value and report the range alert once each, with the
|
||||
/// picker still open; a typed value in range and a slider press report none.
|
||||
#[trial]
|
||||
fn size_and_hardness_typed_out_of_range_report_the_range_alert() {
|
||||
let (mut fixture, host) = opened_rig(true, false);
|
||||
type_into(&mut fixture, "Size", "9999");
|
||||
{
|
||||
let host = host.borrow();
|
||||
assert_eq!(host.values.diameter, 5000.0, "Size keeps the largest diameter");
|
||||
let [alert] = host.alerts.as_slice() else { panic!("one alert for Size: {:?}", host.alerts) };
|
||||
assert_eq!((alert.typed, alert.kept, alert.range.clone()), (9999.0, 5000.0, 1.0..=5000.0));
|
||||
assert!(host.open, "the picker stays open");
|
||||
}
|
||||
type_into(&mut fixture, "Size", "0");
|
||||
assert_eq!(host.borrow().values.diameter, 1.0, "Size keeps the smallest diameter");
|
||||
assert_eq!(host.borrow().alerts.len(), 2, "a typed 0 is out of range too");
|
||||
type_into(&mut fixture, "Hardness", "150");
|
||||
{
|
||||
let host = host.borrow();
|
||||
assert_eq!(host.values.hardness, Some(1.0), "Hardness keeps 100 %");
|
||||
let alert = host.alerts.last().expect("an alert for Hardness");
|
||||
assert_eq!((host.alerts.len(), alert.typed, alert.kept, alert.range.clone()), (3, 150.0, 100.0, 0.0..=100.0));
|
||||
}
|
||||
type_into(&mut fixture, "Size", "40");
|
||||
let slider = fixture.by_role(Role::SLIDER).into_iter().find(|target| fixture.tree().name_of(target.node) == Some("Hardness"));
|
||||
let slider = slider.expect("the Hardness slider shows").rect;
|
||||
fixture.click_at(slider.left_center() + Vec2::new(slider.width() * 0.8, 0.0));
|
||||
fixture.idle(3);
|
||||
let host = host.borrow();
|
||||
assert_eq!(host.values.diameter, 40.0);
|
||||
assert_eq!(host.alerts.len(), 3, "a value in range and a slider press alert nothing: {:?}", host.alerts);
|
||||
}
|
||||
|
||||
/// The memoized views of `props` that ran in the last frame.
|
||||
fn views_ran(fixture: &Fixture, props: &str) -> usize {
|
||||
last_frame_memo_runs(fixture.ctx()).into_iter().filter(|(name, _, run)| name.contains(props) && *run == MemoRun::Ran).count()
|
||||
|
||||
@@ -3,14 +3,15 @@
|
||||
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft_behavior::CanvasView;
|
||||
use craft_behavior::geometry::Constraint;
|
||||
use craft_behavior::geometry::{Constraint, SnapOptions, SnapTargets};
|
||||
use craft_behavior::kurbo::{Point, Rect as DocRect, Size};
|
||||
use craft_draw::ui::crop::{
|
||||
CropDocKey, PerspectiveCropEvent, PerspectiveCropQuad, PerspectiveCropTool, PerspectiveInput, grid_lines, grid_steps, is_valid,
|
||||
};
|
||||
use craft_ui::canvas::{Canvas, ToolHost, tool_pass};
|
||||
use craft_ui::canvas::{Canvas, Snap, ToolHost, tool_pass};
|
||||
use craft_ui::contract::{Bind, Show as _, ShowContainer as _};
|
||||
use craft_ui::runtime::access::Role;
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
@@ -62,6 +63,17 @@ struct Rig {
|
||||
|
||||
impl Rig {
|
||||
fn new() -> Self {
|
||||
Self::snapping(None)
|
||||
}
|
||||
|
||||
/// A rig whose canvas snaps with `options` to its document's bounds (the targets an app builds for View > Snap To),
|
||||
/// in a room with a pasteboard of 100 points around the document.
|
||||
fn snapping(options: Option<SnapOptions>) -> Self {
|
||||
let snap = options.map(|options| {
|
||||
let bounds = DocRect::from_origin_size(Point::ZERO, SIZE);
|
||||
Snap::new(Arc::new(SnapTargets::new().with_document(&options, bounds, std::iter::empty(), None)), options)
|
||||
});
|
||||
let pasteboard = snap.is_some();
|
||||
let tool = Rc::new(RefCell::new(PerspectiveCropTool::new()));
|
||||
let document = Rc::new(Cell::new(None));
|
||||
let apply = Rc::new(Cell::new(false));
|
||||
@@ -72,7 +84,11 @@ impl Rig {
|
||||
let view = CanvasView::new(room, Point::new(200.0, 150.0), 1.0);
|
||||
let input = PerspectiveInput { document: active.get(), ..Default::default() };
|
||||
let mut pass = tool.pass(input);
|
||||
let _ = Canvas::new("Document").document(SIZE).view(view).show(ui, |ui, body| {
|
||||
let mut canvas = Canvas::new("Document").document(SIZE).view(view);
|
||||
if let Some(snap) = snap.clone() {
|
||||
canvas = canvas.snap(snap);
|
||||
}
|
||||
let _ = canvas.show(ui, |ui, body| {
|
||||
let output = pass.show_quad(ui, body.rect);
|
||||
applied.set(applied.get() || output.apply);
|
||||
if let Some(canvas) = tool_pass(&body.env) {
|
||||
@@ -80,6 +96,9 @@ impl Rig {
|
||||
}
|
||||
});
|
||||
});
|
||||
if pasteboard {
|
||||
fixture.room(Vec2::new(SIZE.width as f32 + 200.0, SIZE.height as f32 + 200.0));
|
||||
}
|
||||
fixture.settle();
|
||||
Rig { fixture, tool, document, apply }
|
||||
}
|
||||
@@ -366,3 +385,52 @@ fn a_session_starts_once_and_a_document_switch_discards_it() {
|
||||
rig.fixture.frame(Vec::new());
|
||||
assert!(rig.tool.borrow_mut().take_events().is_empty(), "the same document keeps its quad");
|
||||
}
|
||||
|
||||
/// photocraft#11803: with Snap To Document Bounds on, a box drag started on the pasteboard starts on the document.
|
||||
#[test]
|
||||
fn a_box_drag_starts_on_the_document_bounds_the_canvas_snaps_to() {
|
||||
let box_from = |rig: &mut Rig, press: (f64, f64), to: (f64, f64)| {
|
||||
rig.tool.borrow_mut().clear();
|
||||
rig.drag(press, to, Modifiers::NONE);
|
||||
rig.quad()
|
||||
};
|
||||
let mut rig = Rig::snapping(Some(SnapOptions::default()));
|
||||
|
||||
// Beyond a corner (outside on both axes) the box starts at that corner, from the drag's first move.
|
||||
rig.tool.borrow_mut().clear();
|
||||
let (from, to) = (rig.at(-50.0, -40.0), rig.at(100.0, 100.0));
|
||||
rig.fixture.frame(vec![Event::PointerMoved(from)]);
|
||||
rig.button(from, true, Modifiers::NONE);
|
||||
rig.fixture.frame(vec![Event::PointerMoved(from + (to - from) * 0.5)]);
|
||||
let shown = rig.quad().map(|q| q[0]);
|
||||
assert!(shown.is_some_and(|p| p.x.abs() < 1e-3 && p.y.abs() < 1e-3), "the drag shows the snapped start: {shown:?}");
|
||||
rig.fixture.frame(vec![Event::PointerMoved(to)]);
|
||||
rig.button(to, false, Modifiers::NONE);
|
||||
rig.fixture.frame(Vec::new());
|
||||
assert!(near(rig.quad(), [(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)]), "{:?}", rig.quad());
|
||||
assert!(near(box_from(&mut rig, (450.0, 340.0), (300.0, 200.0)), [(300.0, 200.0), (400.0, 200.0), (400.0, 300.0), (300.0, 300.0)]));
|
||||
// Within the snap distance of an edge the start moves onto it, on that axis only.
|
||||
assert!(near(box_from(&mut rig, (3.0, 4.0), (100.0, 100.0)), [(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)]));
|
||||
assert!(near(box_from(&mut rig, (395.0, 150.0), (300.0, 250.0)), [(300.0, 150.0), (400.0, 150.0), (400.0, 250.0), (300.0, 250.0)]));
|
||||
// Outside on one axis only, beyond the snap distance, and inside away from the edges: the start stays.
|
||||
assert!(near(box_from(&mut rig, (-50.0, 100.0), (100.0, 200.0)), [(-50.0, 100.0), (100.0, 100.0), (100.0, 200.0), (-50.0, 200.0)]));
|
||||
assert!(near(box_from(&mut rig, (100.0, 150.0), (200.0, 250.0)), [(100.0, 150.0), (200.0, 150.0), (200.0, 250.0), (100.0, 250.0)]));
|
||||
|
||||
// Clicked corners keep their place, also beyond a corner and near an edge.
|
||||
rig.tool.borrow_mut().clear();
|
||||
for click in [(-30.0, -30.0), (200.0, 3.0), (300.0, 200.0), (3.0, 200.0)] {
|
||||
rig.click(click);
|
||||
}
|
||||
assert!(near(rig.quad(), [(-30.0, -30.0), (200.0, 3.0), (300.0, 200.0), (3.0, 200.0)]), "{:?}", rig.quad());
|
||||
|
||||
// With Document Bounds off, or snapping off, the press beyond a corner and the one near an edge start where they were.
|
||||
let mut bounds_off = SnapOptions::default();
|
||||
bounds_off.document_bounds = false;
|
||||
let mut snap_off = SnapOptions::default();
|
||||
snap_off.on = false;
|
||||
for options in [bounds_off, snap_off] {
|
||||
let mut rig = Rig::snapping(Some(options));
|
||||
assert!(near(box_from(&mut rig, (-50.0, -40.0), (100.0, 100.0)), [(-50.0, -40.0), (100.0, -40.0), (100.0, 100.0), (-50.0, 100.0)]));
|
||||
assert!(near(box_from(&mut rig, (3.0, 4.0), (100.0, 100.0)), [(3.0, 4.0), (100.0, 4.0), (100.0, 100.0), (3.0, 100.0)]));
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,13 @@
|
||||
//! 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. Its Caps row on a solid closed path: disabled by default,
|
||||
//! enabled with `caps_on_closed`.
|
||||
//! enabled with `caps_on_closed`. Its labeled rows in a host's group: a label column of their own by default, the
|
||||
//! host group's with `host_labels`.
|
||||
|
||||
use craft_draw::ui::stroke::{LineCap, StrokeEditor, StrokeSections, StrokeStyle};
|
||||
use craft_ui::contract::Bind;
|
||||
use craft_ui::contract::{Bind, Show as _, ShowContainer as _};
|
||||
use craft_ui::form::{Field, FieldGroup};
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use craft_ui::text::NumberField;
|
||||
use egui::{Key, Modifiers};
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
@@ -68,6 +71,58 @@ fn caps_on_closed_keeps_the_cap_buttons_enabled_on_a_solid_closed_path() {
|
||||
assert_eq!(style.borrow().cap, LineCap::Square, "the cap button sets the cap");
|
||||
}
|
||||
|
||||
/// The label of the host group's own row: longer than every label of the editor.
|
||||
const HOST_ROW: &str = "Arrowheads and profile";
|
||||
|
||||
/// A host group with one long-labeled row, [`HOST_ROW`], over the editor with `sections` and `host_labels` as given,
|
||||
/// on a dashed path.
|
||||
fn hosted_editor(sections: StrokeSections, host_labels: bool) -> Fixture {
|
||||
let style = Rc::new(RefCell::new(StrokeStyle { dashes: vec![4.0, 2.0], ..StrokeStyle::default() }));
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut style = style.borrow_mut();
|
||||
FieldGroup::new("Host").show(ui, |ui, _| {
|
||||
Field::new(HOST_ROW).show(ui, |ui, _| {
|
||||
NumberField::new(HOST_ROW, Bind::given(Some(1.0))).show(ui);
|
||||
});
|
||||
let _ = StrokeEditor::new("Stroke", Bind::bound(&mut *style)).sections(sections).host_labels(host_labels).show(ui);
|
||||
});
|
||||
});
|
||||
fixture.settle();
|
||||
fixture
|
||||
}
|
||||
|
||||
/// The x where the control named `label` starts.
|
||||
fn control_start(fixture: &Fixture, label: &str) -> f32 {
|
||||
fixture.by_label(label).unwrap_or_else(|| panic!("{label:?} names its control")).rect.min.x
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn host_labels_start_the_editor_rows_at_the_host_groups_control_edge() {
|
||||
/// How far two edges may differ and still line up, in points.
|
||||
const SLACK: f32 = 0.5;
|
||||
let selects = StrokeSections::DASHES | StrokeSections::DASH_ALIGN | StrokeSections::OPACITY;
|
||||
let fixture = hosted_editor(selects, true);
|
||||
let edge = control_start(&fixture, HOST_ROW);
|
||||
for name in ["Alignment", "Caps", "Corners", "Miter limit", "Opacity", "Dash offset", "Align dashes"] {
|
||||
let at = control_start(&fixture, name);
|
||||
assert!((at - edge).abs() <= SLACK, "{name:?} starts at the host group's control edge: {at} {edge}");
|
||||
}
|
||||
|
||||
let fixture = hosted_editor(StrokeSections::PANEL, true);
|
||||
let edge = control_start(&fixture, HOST_ROW);
|
||||
for name in ["Miter limit", "Dash offset"] {
|
||||
let at = control_start(&fixture, name);
|
||||
assert!((at - edge).abs() <= SLACK, "{name:?} starts at the host group's control edge with icon rows: {at} {edge}");
|
||||
}
|
||||
|
||||
let fixture = hosted_editor(selects, false);
|
||||
let edge = control_start(&fixture, HOST_ROW);
|
||||
for name in ["Alignment", "Caps", "Corners", "Miter limit", "Opacity", "Dash offset"] {
|
||||
let at = control_start(&fixture, name);
|
||||
assert!(at < edge - SLACK, "by default {name:?} keeps the editor's own label column: {at} {edge}");
|
||||
}
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn dash_fields_add_after_the_pattern_and_a_cleared_field_ends_it() {
|
||||
let (mut fixture, style) = editor(vec![4.0, 2.0]);
|
||||
|
||||
@@ -57,6 +57,8 @@ craft-fonts-build = { workspace = true }
|
||||
craft-font-manager = { path = ".", features = ["suite"] }
|
||||
# The shared preview test vectors.
|
||||
serde_json = { workspace = true }
|
||||
# Test faces built for the script filter (a script no shipped test font covers).
|
||||
write-fonts = "0.54"
|
||||
|
||||
[[test]]
|
||||
name = "it"
|
||||
|
||||
@@ -7,12 +7,13 @@
|
||||
#[cfg(feature = "suite")]
|
||||
pub(crate) mod stories;
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft_behavior::{IconId, Selection};
|
||||
use craft_host::Section;
|
||||
use craft_ui::contract::{
|
||||
ActivateOn, Bind, CollectionEvent, CommandSet, Entry, NoValue, Outcome, Pad, Pattern, Props, Remember as _, SelectMode, Show as _,
|
||||
ActivateOn, Bind, BodyCx, CollectionEvent, CommandSet, Entry, NoValue, Outcome, Pad, Pattern, Props, Remember as _, SelectMode, Show as _,
|
||||
ShowCollection as _, ShowContainer as _, Sizing,
|
||||
};
|
||||
use craft_ui::display::{Shade, Spinner, Text};
|
||||
@@ -508,7 +509,7 @@ impl<'a> GlyphsPanel<'a> {
|
||||
source,
|
||||
mut family,
|
||||
mut style,
|
||||
mut settings,
|
||||
settings,
|
||||
families,
|
||||
styles,
|
||||
can_insert,
|
||||
@@ -533,9 +534,31 @@ impl<'a> GlyphsPanel<'a> {
|
||||
let mut picked: Option<AlternatePick> = None;
|
||||
let mut font_changed = false;
|
||||
let mut menu: Option<GlyphCellMenu> = None;
|
||||
let shown = Stack::new().label(label).command_scope(GlyphsCommand::SCOPE).show(ui, |ui, cx| {
|
||||
let settings = RefCell::new(settings);
|
||||
// The body hands the footer the pass's settings and its selection text: the footer is drawn after the body,
|
||||
// in the room under the grid.
|
||||
let pass: RefCell<Option<(GlyphsPanelSettings, String)>> = RefCell::new(None);
|
||||
let footer = |ui: &mut Ui, cx: &mut BodyCx<'_>| {
|
||||
let Some((mut state, info)) = pass.borrow_mut().take() else {
|
||||
return;
|
||||
};
|
||||
let mut zoom_value = f64::from(state.zoom);
|
||||
Row::new().show(ui, |ui, _| {
|
||||
Text::new(info.clone()).show(ui);
|
||||
ThumbnailSlider::new(words.zoom.clone(), Bind::bound(&mut zoom_value), ZOOM).show(ui);
|
||||
});
|
||||
if !can_insert {
|
||||
Text::new(words.no_text.clone()).show(ui);
|
||||
}
|
||||
state.zoom = zoom_value as f32;
|
||||
let mut settings = settings.borrow_mut();
|
||||
if read_bind(&mut settings, cx).is_none_or(|held| held != state) {
|
||||
write_bind(&mut settings, cx, state, "Glyphs panel");
|
||||
}
|
||||
};
|
||||
let shown = Stack::new().label(label).command_scope(GlyphsCommand::SCOPE).footer(footer).show(ui, |ui, cx| {
|
||||
cx.publish(GlyphsCommand::Alternates, CommandState::new());
|
||||
let mut state = read_bind(&mut settings, cx).unwrap_or_default();
|
||||
let mut state = read_bind(&mut settings.borrow_mut(), cx).unwrap_or_default();
|
||||
if state.category.is_empty() {
|
||||
state.category = CATEGORIES[0].to_owned();
|
||||
}
|
||||
@@ -545,7 +568,6 @@ impl<'a> GlyphsPanel<'a> {
|
||||
} else {
|
||||
ZOOM.default_value()
|
||||
};
|
||||
let mut zoom_value = size;
|
||||
let (held_family, held_style) = (read_bind(&mut family, cx).unwrap_or_default(), read_bind(&mut style, cx).unwrap_or_default());
|
||||
let (mut face_family, mut face_style) = (held_family.clone(), held_style.clone());
|
||||
|
||||
@@ -756,15 +778,8 @@ impl<'a> GlyphsPanel<'a> {
|
||||
None => count,
|
||||
};
|
||||
*cx.memory::<Marked>() = marked;
|
||||
Row::new().show(ui, |ui, _| {
|
||||
Text::new(info.clone()).show(ui);
|
||||
ThumbnailSlider::new(words.zoom.clone(), Bind::bound(&mut zoom_value), ZOOM).show(ui);
|
||||
});
|
||||
if !can_insert {
|
||||
Text::new(words.no_text.clone()).show(ui);
|
||||
}
|
||||
|
||||
state.zoom = zoom_value as f32;
|
||||
state.zoom = size as f32;
|
||||
if let Some(cell) = activated
|
||||
&& can_insert
|
||||
{
|
||||
@@ -776,9 +791,7 @@ impl<'a> GlyphsPanel<'a> {
|
||||
}
|
||||
activated_out = Some(cell);
|
||||
}
|
||||
if read_bind(&mut settings, cx).is_none_or(|held| held != state) {
|
||||
write_bind(&mut settings, cx, state, "Glyphs panel");
|
||||
}
|
||||
*pass.borrow_mut() = Some((state, info));
|
||||
});
|
||||
GlyphsPanelOutput { response: shown.output, activated: activated_out, alternate: picked, font_changed, menu }
|
||||
}
|
||||
|
||||
@@ -86,6 +86,15 @@ craft_ui::words! {
|
||||
script_east_asian: "fontPicker.scriptEastAsian" = "East Asian";
|
||||
script_japanese: "fontPicker.scriptJapanese" = "Japanese";
|
||||
script_thai: "fontPicker.scriptThai" = "Thai";
|
||||
script_devanagari: "fontPicker.scriptDevanagari" = "Devanagari";
|
||||
script_bengali: "fontPicker.scriptBengali" = "Bengali";
|
||||
script_gurmukhi: "fontPicker.scriptGurmukhi" = "Gurmukhi";
|
||||
script_gujarati: "fontPicker.scriptGujarati" = "Gujarati";
|
||||
script_odia: "fontPicker.scriptOdia" = "Odia";
|
||||
script_tamil: "fontPicker.scriptTamil" = "Tamil";
|
||||
script_telugu: "fontPicker.scriptTelugu" = "Telugu";
|
||||
script_kannada: "fontPicker.scriptKannada" = "Kannada";
|
||||
script_malayalam: "fontPicker.scriptMalayalam" = "Malayalam";
|
||||
any_kind: "fontPicker.anyKind" = "Any Kind";
|
||||
font_technology: "fontPicker.fontTechnology" = "Font Technology";
|
||||
preview_size: "fontPicker.previewSize" = "Font Preview Size";
|
||||
@@ -206,7 +215,7 @@ fn chosen_sample<'s, 'a>(texts: &'s [SampleText<'a>], settings: Option<&FontPick
|
||||
/// Coverage from the face: Latin, the basic Latin letters in the cmap; East Asian, the CJK Windows code pages
|
||||
/// (JIS, Simplified/Traditional Chinese, Wansung, Johab) or CJK ideographs/kana/Hangul when no code pages are declared;
|
||||
/// Japanese, the OS/2 kana or CJK unicode-range bits or the JIS code page bit, or a Japanese family name; Thai, U+0E01
|
||||
/// and U+0E32 in the cmap. Read lazily like the class.
|
||||
/// and U+0E32 in the cmap; an Indic script, its letter KA and vowel sign AA in the cmap. Read lazily like the class.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
#[non_exhaustive]
|
||||
pub enum FontScript {
|
||||
@@ -218,11 +227,43 @@ pub enum FontScript {
|
||||
Japanese,
|
||||
/// Thai.
|
||||
Thai,
|
||||
/// Devanagari.
|
||||
Devanagari,
|
||||
/// Bengali.
|
||||
Bengali,
|
||||
/// Gurmukhi.
|
||||
Gurmukhi,
|
||||
/// Gujarati.
|
||||
Gujarati,
|
||||
/// Odia.
|
||||
Odia,
|
||||
/// Tamil.
|
||||
Tamil,
|
||||
/// Telugu.
|
||||
Telugu,
|
||||
/// Kannada.
|
||||
Kannada,
|
||||
/// Malayalam.
|
||||
Malayalam,
|
||||
}
|
||||
|
||||
impl FontScript {
|
||||
/// Every script the script row can offer, in order.
|
||||
pub const ALL: [FontScript; 4] = [FontScript::Latin, FontScript::EastAsian, FontScript::Japanese, FontScript::Thai];
|
||||
pub const ALL: [FontScript; 13] = [
|
||||
FontScript::Latin,
|
||||
FontScript::EastAsian,
|
||||
FontScript::Japanese,
|
||||
FontScript::Thai,
|
||||
FontScript::Devanagari,
|
||||
FontScript::Bengali,
|
||||
FontScript::Gurmukhi,
|
||||
FontScript::Gujarati,
|
||||
FontScript::Odia,
|
||||
FontScript::Tamil,
|
||||
FontScript::Telugu,
|
||||
FontScript::Kannada,
|
||||
FontScript::Malayalam,
|
||||
];
|
||||
}
|
||||
|
||||
/// A family set the host gives (VectorCraft: Document, Recently Added), one filter toggle each. An `ordered` set that
|
||||
|
||||
@@ -200,9 +200,26 @@ const JAPANESE_RANGES: u32 = (1 << (49 - 32)) | (1 << (50 - 32)) | (1 << (59 - 3
|
||||
/// Hangul Syllables (56) plus [`JAPANESE_RANGES`].
|
||||
const EAST_ASIAN_RANGES: u32 = JAPANESE_RANGES | (1 << (56 - 32));
|
||||
|
||||
/// The Indic scripts and the first code point of their Unicode block. Every block has its letter KA and vowel sign AA
|
||||
/// at the same offsets.
|
||||
const INDIC_BLOCKS: [(FontScript, u32); 9] = [
|
||||
(FontScript::Devanagari, 0x0900),
|
||||
(FontScript::Bengali, 0x0980),
|
||||
(FontScript::Gurmukhi, 0x0A00),
|
||||
(FontScript::Gujarati, 0x0A80),
|
||||
(FontScript::Odia, 0x0B00),
|
||||
(FontScript::Tamil, 0x0B80),
|
||||
(FontScript::Telugu, 0x0C00),
|
||||
(FontScript::Kannada, 0x0C80),
|
||||
(FontScript::Malayalam, 0x0D00),
|
||||
];
|
||||
const INDIC_KA: u32 = 0x15;
|
||||
const INDIC_AA: u32 = 0x3E;
|
||||
|
||||
/// The scripts a face covers: Latin, the basic Latin letters in its `cmap`; East Asian, its East Asian Windows code
|
||||
/// pages, CJK/kana/Hangul Unicode ranges, CJK ideographs in `cmap`, or a CJK localized name; Japanese, the JIS code
|
||||
/// page, the kana or CJK Unicode ranges of its `OS/2` table, or a Japanese family name; Thai, ก and า in its `cmap`.
|
||||
/// page, the kana or CJK Unicode ranges of its `OS/2` table, or a Japanese family name; Thai, ก and า in its `cmap`;
|
||||
/// an Indic script, its letter KA and vowel sign AA in its `cmap` (no code page covers these scripts).
|
||||
fn read_scripts(catalog: &Catalog, face: &FaceInfo) -> Option<Vec<FontScript>> {
|
||||
let data = catalog.load(face).ok()?;
|
||||
let font = FontRef::from_index(&data.bytes, face.index).ok()?;
|
||||
@@ -217,7 +234,11 @@ fn read_scripts(catalog: &Catalog, face: &FaceInfo) -> Option<Vec<FontScript>> {
|
||||
let japanese = face.code_pages[0] & JIS_CODE_PAGE != 0 || ranges & JAPANESE_RANGES != 0 || japanese_name(face);
|
||||
let thai = ['\u{0E01}', '\u{0E32}'].into_iter().all(&mapped);
|
||||
let scripts = [(FontScript::Latin, latin), (FontScript::EastAsian, east_asian), (FontScript::Japanese, japanese), (FontScript::Thai, thai)];
|
||||
Some(scripts.into_iter().filter_map(|(script, covered)| covered.then_some(script)).collect())
|
||||
let indic = INDIC_BLOCKS.into_iter().map(|(script, block)| {
|
||||
let at = |offset: u32| char::from_u32(block + offset).is_some_and(&mapped);
|
||||
(script, at(INDIC_KA) && at(INDIC_AA))
|
||||
});
|
||||
Some(scripts.into_iter().chain(indic).filter_map(|(script, covered)| covered.then_some(script)).collect())
|
||||
}
|
||||
|
||||
/// The class of a family from its regular face, `None` when the catalog lacks it.
|
||||
|
||||
@@ -350,6 +350,15 @@ fn script_label(script: FontScript, words: &FontPickerWords) -> Label {
|
||||
FontScript::EastAsian => words.script_east_asian.clone(),
|
||||
FontScript::Japanese => words.script_japanese.clone(),
|
||||
FontScript::Thai => words.script_thai.clone(),
|
||||
FontScript::Devanagari => words.script_devanagari.clone(),
|
||||
FontScript::Bengali => words.script_bengali.clone(),
|
||||
FontScript::Gurmukhi => words.script_gurmukhi.clone(),
|
||||
FontScript::Gujarati => words.script_gujarati.clone(),
|
||||
FontScript::Odia => words.script_odia.clone(),
|
||||
FontScript::Tamil => words.script_tamil.clone(),
|
||||
FontScript::Telugu => words.script_telugu.clone(),
|
||||
FontScript::Kannada => words.script_kannada.clone(),
|
||||
FontScript::Malayalam => words.script_malayalam.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -232,7 +232,7 @@ fn font_picker_filter_chips(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
FamilySet::new("document", "Document", &document),
|
||||
FamilySet::new("added", "Recently Added", &added).ordered().enabled(false).hint("No fonts were added recently"),
|
||||
];
|
||||
let scripts = [FontScript::Latin, FontScript::Japanese, FontScript::Thai];
|
||||
let scripts = [FontScript::Latin, FontScript::Japanese, FontScript::Thai, FontScript::Devanagari, FontScript::Gujarati];
|
||||
let filters = FontFilters { sets: vec!["document".to_owned()], ..FontFilters::default() };
|
||||
let extras = Extras { sets: &sets, scripts: &scripts, layout: FilterLayout::Chips, ..Extras::default() };
|
||||
show_with(ui, data, demo("Hack", FontPickerSettings::default(), filters), &catalog(), &extras)
|
||||
|
||||
@@ -7,7 +7,7 @@ use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
|
||||
use craft_font_manager::glyphs::{CellInfo, GlyphCell, GlyphSource, GlyphsPanel, GlyphsPanelSettings};
|
||||
use craft_ui::contract::{Bind, Show as _, ShowContainer as _};
|
||||
use craft_ui::contract::{Bind, Role, Show as _, ShowContainer as _};
|
||||
use craft_ui::menu::{Menu, MenuItem};
|
||||
use craft_ui::testing::pointer;
|
||||
use craft_ui::testing::{Fixture, Room, trial};
|
||||
@@ -336,6 +336,45 @@ fn glyphs_panel_alternates() {
|
||||
}
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn the_footer_stays_inside_the_panel_under_a_grid_that_fills_it() {
|
||||
let (mut family, mut style, mut settings) = ("Plain".to_owned(), "Regular".to_owned(), GlyphsPanelSettings::default());
|
||||
let mut fx = Fixture::new(move |ui| {
|
||||
GlyphsPanel::new("Glyphs", &Plain, Bind::bound(&mut family), Bind::bound(&mut style), Bind::bound(&mut settings)).show(ui);
|
||||
});
|
||||
let room = egui::vec2(320.0, 420.0);
|
||||
fx.room(room).settle();
|
||||
for label in ["300 glyphs", "Zoom", "Edit text to insert glyphs"] {
|
||||
let target = fx.by_label(label).unwrap_or_else(|| panic!("missing {label}"));
|
||||
assert!(target.rect.bottom() <= room.y, "{label} ends at {} below the panel's bottom edge {}", target.rect.bottom(), room.y);
|
||||
assert!(fx.visible(&target).is_some(), "{label} is in view");
|
||||
}
|
||||
let zoom = fx.by_label("Zoom").expect("the zoom slider");
|
||||
let first = fx.by_label(&name(FIRST)).expect("the first cell");
|
||||
assert!(first.rect.bottom() <= zoom.rect.top(), "the first cell ends above the footer");
|
||||
// The recent strip and the glyph grid are both list boxes; the glyph grid is the lower one.
|
||||
let grid = fx.by_role(Role::LIST_BOX).into_iter().map(|list| list.rect.bottom()).fold(f32::NEG_INFINITY, f32::max);
|
||||
assert!(grid.is_finite(), "the panel shows the glyph grid");
|
||||
assert!(grid <= zoom.rect.top(), "the glyph grid ends at {grid}, below the footer's top {}", zoom.rect.top());
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn the_zoom_slider_in_the_footer_writes_the_settings() {
|
||||
let settings = Rc::new(RefCell::new(GlyphsPanelSettings::default()));
|
||||
let held = Rc::clone(&settings);
|
||||
let (mut family, mut style) = ("Plain".to_owned(), "Regular".to_owned());
|
||||
let mut fx = Fixture::new(move |ui| {
|
||||
let mut settings = held.borrow_mut();
|
||||
GlyphsPanel::new("Glyphs", &Plain, Bind::bound(&mut family), Bind::bound(&mut style), Bind::bound(&mut *settings)).show(ui);
|
||||
});
|
||||
fx.room(egui::vec2(320.0, 420.0)).settle();
|
||||
let before = settings.borrow().zoom;
|
||||
let zoom = fx.by_label("Zoom").expect("the zoom slider");
|
||||
fx.access(craft_ui::testing::focus::AccessActionKind::Increment, &zoom).settle();
|
||||
let after = settings.borrow().zoom;
|
||||
assert!(after > before, "a step on the footer's slider is written to the settings: {before} then {after}");
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn the_font_style_and_category_pickers_fit_in_a_narrow_glyphs_panel() {
|
||||
let expected_family = "A particularly long font family name";
|
||||
|
||||
@@ -385,6 +385,54 @@ fn a_thai_and_a_cjk_face_each_pass_their_own_scripts_filter() {
|
||||
assert!(!thai.iter().chain(&japanese).any(|family| family.contains("Inter")), "Inter covers neither");
|
||||
}
|
||||
|
||||
/// A face named `family` whose `cmap` maps the basic Latin letters and `extra`: only the tables the catalog and the
|
||||
/// coverage read, with an empty `glyf` so it counts as drawable.
|
||||
fn face_mapping(family: &str, extra: &[char]) -> Vec<u8> {
|
||||
use write_fonts::FontBuilder;
|
||||
use write_fonts::tables::cmap::Cmap;
|
||||
use write_fonts::tables::maxp::Maxp;
|
||||
use write_fonts::tables::name::{Name, NameRecord};
|
||||
use write_fonts::tables::os2::Os2;
|
||||
use write_fonts::types::{GlyphId, NameId, Tag};
|
||||
|
||||
let chars: Vec<char> = ('A'..='Z').chain('a'..='z').chain(extra.iter().copied()).collect();
|
||||
let cmap = Cmap::from_mappings(chars.iter().zip(1u32..).map(|(&c, g)| (c, GlyphId::new(g)))).expect("a cmap");
|
||||
let mut records = vec![
|
||||
NameRecord::new(3, 1, 0x409, NameId::new(1), family.to_owned().into()),
|
||||
NameRecord::new(3, 1, 0x409, NameId::new(2), "Regular".to_owned().into()),
|
||||
NameRecord::new(3, 1, 0x409, NameId::new(4), format!("{family} Regular").into()),
|
||||
NameRecord::new(3, 1, 0x409, NameId::new(6), format!("{}-Regular", family.replace(' ', "")).into()),
|
||||
];
|
||||
records.sort_by_key(|r| r.name_id);
|
||||
let mut builder = FontBuilder::new();
|
||||
builder.add_table(&Name::new(records)).expect("name");
|
||||
builder.add_table(&Os2 { us_weight_class: 400, us_width_class: 5, ..Default::default() }).expect("OS/2");
|
||||
builder.add_table(&cmap).expect("cmap");
|
||||
builder.add_table(&Maxp::new(u16::try_from(chars.len() + 1).expect("few glyphs"))).expect("maxp");
|
||||
builder.add_raw(Tag::new(b"glyf"), vec![0u8; 4]);
|
||||
builder.build()
|
||||
}
|
||||
|
||||
/// An Indic script is read from the face's `cmap` (KA and vowel sign AA); no code page marks it. A face with
|
||||
/// Devanagari passes the Devanagari filter, not the Gujarati one, and Latin-only and Thai faces pass neither.
|
||||
#[trial]
|
||||
fn an_indic_face_passes_its_own_scripts_filter() {
|
||||
const THAI: &[u8] = include_bytes!("../../../font-subset/tests/data/sarabun/Sarabun-Regular.ttf");
|
||||
let deva = face_mapping("Test Devanagari", &['\u{0915}', '\u{093E}']);
|
||||
// A lone KA, as a symbol font might carry, is not coverage.
|
||||
let ka_only = face_mapping("Test Lone Ka", &['\u{0A95}']);
|
||||
let catalog = catalog_of(&[INTER_REGULAR, THAI, &deva, &ka_only]);
|
||||
let with = |script: FontScript| {
|
||||
let mut filters = FontFilters::default();
|
||||
filters.script = Some(script);
|
||||
listed(&catalog, &filters, &[])
|
||||
};
|
||||
let devanagari = with(FontScript::Devanagari);
|
||||
assert!(devanagari.iter().any(|family| family.contains("Test Devanagari")), "Devanagari: {devanagari:?}");
|
||||
assert!(!devanagari.iter().any(|family| family.contains("Inter") || family.contains("Sarabun")), "Devanagari: {devanagari:?}");
|
||||
assert!(with(FontScript::Gujarati).is_empty(), "nothing covers Gujarati: {:?}", with(FontScript::Gujarati));
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_host_set_keeps_only_its_families_and_an_ordered_one_lists_them_in_its_order() {
|
||||
let catalog = three_faces();
|
||||
|
||||
@@ -106,7 +106,10 @@ index, bytes, role }` literals; any struct with those fields and that name in sc
|
||||
`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()`.
|
||||
`has_script(tag)`, `is_cjk()` and `weight()`. Tests and tables written by hand build a face with
|
||||
`EmbeddedFace::new(family, style, scripts, bytes)`, which sets no `role`, plus `.with_index(n)`
|
||||
for a face in a collection; both are `const fn`. Code that uses `new` keeps compiling when a
|
||||
field with a default is added; a struct literal does not.
|
||||
|
||||
## Document fonts
|
||||
|
||||
|
||||
@@ -87,6 +87,26 @@ pub struct EmbeddedFace {
|
||||
}
|
||||
|
||||
impl EmbeddedFace {
|
||||
/// A face at index 0 of `bytes` with no `role`, for tests and for tables written by hand. Code
|
||||
/// that builds faces with `new` keeps compiling when a field with a default is added; a struct
|
||||
/// literal does not.
|
||||
///
|
||||
/// ```
|
||||
/// use craft_fonts_build::EmbeddedFace;
|
||||
///
|
||||
/// static FACE: EmbeddedFace = EmbeddedFace::new("Sans", "Bold", &["Latn"], b"").with_index(2);
|
||||
/// assert_eq!((FACE.name().as_str(), FACE.index), ("Sans Bold", 2));
|
||||
/// ```
|
||||
pub const fn new(family: &'static str, style: &'static str, scripts: &'static [&'static str], bytes: &'static [u8]) -> Self {
|
||||
Self { family, style, scripts, index: 0, bytes, role: None }
|
||||
}
|
||||
|
||||
/// The same face at `index` in a font collection (`.ttc`).
|
||||
#[must_use]
|
||||
pub const fn with_index(self, index: u32) -> Self {
|
||||
Self { index, ..self }
|
||||
}
|
||||
|
||||
/// `"<family> <style>"`, e.g. `"Noto Sans Arabic Regular"`.
|
||||
pub fn name(&self) -> String {
|
||||
format!("{} {}", self.family, self.style)
|
||||
|
||||
@@ -4,7 +4,7 @@ use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
use crate::cmap::Cmap;
|
||||
use crate::embed::Env;
|
||||
use crate::{Embed, Error};
|
||||
use crate::{Embed, EmbeddedFace, Error};
|
||||
|
||||
fn fixture() -> PathBuf {
|
||||
Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixture/craft-fonts")
|
||||
@@ -46,6 +46,20 @@ fn run(embed: Embed, dir: Option<&Path>, required: Option<&str>) -> Run {
|
||||
Run { result: result.map(|faces| faces.iter().map(|f| format!("{} {}", f.family, f.style)).collect()), cargo, table }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn embedded_face_new_starts_at_index_zero() {
|
||||
const SCRIPTS: &[&str] = &["Jpan", "Latn"];
|
||||
const FACE: EmbeddedFace = EmbeddedFace::new("Sans JP", "Bold", SCRIPTS, b"font");
|
||||
assert_eq!((FACE.family, FACE.style, FACE.scripts, FACE.index, FACE.bytes), ("Sans JP", "Bold", SCRIPTS, 0, &b"font"[..]));
|
||||
assert_eq!(FACE.role, None);
|
||||
let in_collection = FACE.with_index(3);
|
||||
assert_eq!(in_collection.index, 3);
|
||||
assert_eq!(
|
||||
(in_collection.family, in_collection.style, in_collection.bytes, in_collection.role),
|
||||
(FACE.family, FACE.style, FACE.bytes, FACE.role)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serve_replaces_a_stale_copy_of_the_same_size() {
|
||||
let scratch = Scratch::new("serve-stale");
|
||||
|
||||
@@ -16,6 +16,9 @@ The `gpu-device` feature of `craft` exports this crate as `craft::gpu_device`.
|
||||
settings for flags and backend options when that instance is first created. `native_descriptor`
|
||||
reads those settings on every call.
|
||||
|
||||
`native_instance` returns `Result<wgpu::Instance, OpenError>`. It returns `OpenError::NoAdapter`
|
||||
when no wgpu backend is compiled for the target.
|
||||
|
||||
Licensed under MIT OR Apache-2.0.
|
||||
|
||||
## Contents
|
||||
@@ -24,7 +27,7 @@ Licensed under MIT OR Apache-2.0.
|
||||
|---|---|
|
||||
| `Candidate` | one listed adapter as plain data: name, backend, device type, PCI vendor, device and bus, driver, feature count, and whether it can draw to the window's surface |
|
||||
| `list(instance, surface)` | every adapter the instance lists, as `wgpu::Adapter`s and as `Candidate`s |
|
||||
| `native_instance`, `native_descriptor` | a wgpu instance over Vulkan, Metal and DirectX 12, plus OpenGL except on Windows; wgpu's `WGPU_*` flag variables apply |
|
||||
| `native_instance`, `native_descriptor` | a wgpu instance over Vulkan, Metal and DirectX 12, plus OpenGL; OpenGL is excluded on Windows unless it is the only compiled native backend; wgpu's `WGPU_*` flag variables apply |
|
||||
| `choose(candidates, power)` | wgpu's own adapter rule with two corrections: the newest version of a driver that lists one GPU twice, and DirectX 12 instead of Vulkan on Intel Gen 9 to Gen 11 integrated GPUs (`intel_gen9_to_gen11`) |
|
||||
| `Preference` | `Auto` (high performance), `LowPower`, `Adapter(AdapterKey)` or `Software`; serde form `{"kind":"auto"}`, `{"kind":"adapter","name":…,"backend":…,"vendor":…,"device":…,"pciBusId":…,"driver":…}` |
|
||||
| `AdapterKey` | what identifies an adapter across runs: backend, PCI vendor, device and bus, the Vulkan driver's name, and the name when the backend reports no PCI ids |
|
||||
@@ -80,7 +83,8 @@ Licensed under MIT OR Apache-2.0.
|
||||
`Device::poll` raises on a lost device and record the loss.
|
||||
- wgpu keeps one device-lost callback per device, and a later `set_device_lost_callback`
|
||||
replaces the one `DeviceHealth::watch` set. A `craft-gpu` context on a watched device reads
|
||||
`DeviceHealth::device_status` instead of setting its own callback.
|
||||
`DeviceHealth::device_status` instead of setting its own callback, as `craft-gpu-wgpu`'s
|
||||
`WgpuContext` does.
|
||||
- After an out-of-memory error, polls and waits keep running, so staging memory is reclaimed.
|
||||
The app reads `DeviceHealth::out_of_memory_count` when it handles the error, frees memory, and
|
||||
passes the count to `DeviceHealth::clear_out_of_memory`. The device is then healthy again,
|
||||
|
||||
@@ -133,21 +133,30 @@ pub(crate) fn wgpu_choice(candidates: &[Candidate], power: PowerPreference) -> O
|
||||
}
|
||||
|
||||
/// A wgpu instance over the native backends (Vulkan, Metal, DirectX 12), and OpenGL except on
|
||||
/// Windows. On Windows, OpenGL starts a WGL context thread inside the vendor driver (NVIDIA's
|
||||
/// `nvoglv64` is both its OpenGL driver and its Vulkan driver), and instances created and devices
|
||||
/// dropped at the same time can then deadlock in that driver.
|
||||
/// Windows, unless OpenGL is the only compiled native backend. On Windows, OpenGL starts a WGL
|
||||
/// context thread inside the vendor driver (NVIDIA's `nvoglv64` is both its OpenGL driver and its
|
||||
/// Vulkan driver), and instances created and devices dropped at the same time can then deadlock
|
||||
/// in that driver.
|
||||
///
|
||||
/// On native targets, the first call creates one shared instance and reads wgpu's environment
|
||||
/// settings for flags and backend options. Later calls return clones of that instance.
|
||||
pub fn native_instance() -> wgpu::Instance {
|
||||
/// Returns [`crate::OpenError::NoAdapter`] when no wgpu backend is compiled for this target.
|
||||
pub fn native_instance() -> Result<wgpu::Instance, crate::OpenError> {
|
||||
native_instance_with_backends(wgpu::Instance::enabled_backend_features())
|
||||
}
|
||||
|
||||
fn native_instance_with_backends(backends: wgpu::Backends) -> Result<wgpu::Instance, crate::OpenError> {
|
||||
if backends.is_empty() {
|
||||
return Err(crate::OpenError::NoAdapter);
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
static SHARED: std::sync::OnceLock<wgpu::Instance> = std::sync::OnceLock::new();
|
||||
SHARED.get_or_init(|| wgpu::Instance::new(native_descriptor())).clone()
|
||||
Ok(SHARED.get_or_init(|| wgpu::Instance::new(native_descriptor())).clone())
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
wgpu::Instance::new(native_descriptor())
|
||||
Ok(wgpu::Instance::new(native_descriptor()))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -162,8 +171,15 @@ pub fn native_instance() -> wgpu::Instance {
|
||||
/// or pass the descriptor to egui-wgpu as `WgpuSetupCreateNew::instance_descriptor`, where eframe
|
||||
/// fills in the window's display handle.
|
||||
pub fn native_descriptor() -> wgpu::InstanceDescriptor {
|
||||
native_descriptor_with_backends(wgpu::Instance::enabled_backend_features())
|
||||
}
|
||||
|
||||
fn native_descriptor_with_backends(backends: wgpu::Backends) -> wgpu::InstanceDescriptor {
|
||||
let mut desc = wgpu::InstanceDescriptor::new_without_display_handle();
|
||||
desc.backends = if cfg!(windows) { wgpu::Backends::PRIMARY } else { wgpu::Backends::PRIMARY | wgpu::Backends::GL };
|
||||
if backends.contains(wgpu::Backends::GL) && !backends.intersects(wgpu::Backends::PRIMARY) {
|
||||
desc.backends |= wgpu::Backends::GL;
|
||||
}
|
||||
desc.flags = desc.flags.with_env();
|
||||
desc.backend_options = desc.backend_options.with_env();
|
||||
desc
|
||||
@@ -245,13 +261,14 @@ pub fn intel_gen9_to_gen11(device: u32) -> bool {
|
||||
|
||||
/// Whether `c` is an Intel Gen 9 to Gen 11 integrated GPU listed through Intel's Windows Vulkan
|
||||
/// driver ([`intel_gen9_to_gen11`]). Mesa's Vulkan driver for the same GPUs on Linux reports a
|
||||
/// driver name with "Mesa" in it and is not included.
|
||||
/// driver name or driver information with "Mesa" in it and is not included.
|
||||
pub(crate) fn intel_vulkan_crashes(c: &Candidate) -> bool {
|
||||
c.backend == Backend::Vulkan
|
||||
&& c.device_type == DeviceType::IntegratedGpu
|
||||
&& c.vendor == INTEL
|
||||
&& intel_gen9_to_gen11(c.device)
|
||||
&& !c.driver.to_ascii_lowercase().contains("mesa")
|
||||
&& !c.driver_info.to_ascii_lowercase().contains("mesa")
|
||||
}
|
||||
|
||||
/// For an Intel Gen 9 to Gen 11 integrated GPU listed through Intel's Windows Vulkan driver, the
|
||||
@@ -505,6 +522,16 @@ pub(crate) mod tests {
|
||||
assert_eq!(choose(&discrete, HighPerformance), Some(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mesa_driver_info_keeps_dozen_eligible() {
|
||||
let adapters = vec![gpu("Intel(R) UHD Graphics 630", Vulkan, IntegratedGpu, INTEL, 0x3e91, "", "Dozen", "Mesa 26.1.0", 44)];
|
||||
for power in POWERS {
|
||||
assert_eq!(choose(&adapters, power), Some(0));
|
||||
}
|
||||
assert!(!intel_vulkan_crashes(&adapters[0]));
|
||||
assert!(intel_vulkan_crashes(&uhd_630()[0]), "the Intel Windows driver remains excluded");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gen9_to_gen11_ids() {
|
||||
for id in [0x1916, 0x0a84, 0x5a85, 0x3184, 0x5917, 0x87c0, 0x3e91, 0x3ea0, 0x9b41, 0x5a52, 0x8a5a, 0x4571, 0x4e61] {
|
||||
@@ -576,19 +603,37 @@ pub(crate) mod tests {
|
||||
std::thread::scope(|scope| {
|
||||
let first = scope.spawn(|| {
|
||||
gate.wait();
|
||||
native_instance()
|
||||
native_instance().unwrap()
|
||||
});
|
||||
let second = scope.spawn(|| {
|
||||
gate.wait();
|
||||
native_instance()
|
||||
native_instance().unwrap()
|
||||
});
|
||||
gate.wait();
|
||||
let first = first.join().unwrap();
|
||||
assert_eq!(first, second.join().unwrap());
|
||||
assert_eq!(first, native_instance());
|
||||
assert_eq!(first, native_instance().unwrap());
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_compiled_backend_returns_an_error() {
|
||||
assert_eq!(native_instance_with_backends(wgpu::Backends::empty()), Err(crate::OpenError::NoAdapter));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gles_is_selected_when_it_is_the_only_compiled_native_backend() {
|
||||
let desc = native_descriptor_with_backends(wgpu::Backends::GL | wgpu::Backends::NOOP);
|
||||
assert!(desc.backends.contains(wgpu::Backends::GL));
|
||||
if cfg!(windows) {
|
||||
for other in [wgpu::Backends::DX12, wgpu::Backends::VULKAN, wgpu::Backends::METAL] {
|
||||
let desc = native_descriptor_with_backends(wgpu::Backends::GL | other);
|
||||
assert!(!desc.backends.contains(wgpu::Backends::GL));
|
||||
}
|
||||
assert!(!native_descriptor_with_backends(wgpu::Backends::NOOP).backends.contains(wgpu::Backends::GL));
|
||||
}
|
||||
}
|
||||
|
||||
/// The instance reads wgpu's flag variables and keeps its own backends whatever `WGPU_BACKEND`
|
||||
/// says. Runs in a child process, which has them set.
|
||||
#[test]
|
||||
@@ -608,7 +653,11 @@ pub(crate) mod tests {
|
||||
}
|
||||
let desc = native_descriptor();
|
||||
assert!(desc.flags.contains(wgpu::InstanceFlags::ALLOW_UNDERLYING_NONCOMPLIANT_ADAPTER), "{:?}", desc.flags);
|
||||
let backends = if cfg!(windows) { wgpu::Backends::PRIMARY } else { wgpu::Backends::PRIMARY | wgpu::Backends::GL };
|
||||
let mut backends = if cfg!(windows) { wgpu::Backends::PRIMARY } else { wgpu::Backends::PRIMARY | wgpu::Backends::GL };
|
||||
let compiled = wgpu::Instance::enabled_backend_features();
|
||||
if compiled.contains(wgpu::Backends::GL) && !compiled.intersects(wgpu::Backends::PRIMARY) {
|
||||
backends |= wgpu::Backends::GL;
|
||||
}
|
||||
assert_eq!(desc.backends, backends);
|
||||
}
|
||||
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
//!
|
||||
//! wgpu's default uncaptured-error handler panics, and `Device::poll` panics on a lost device
|
||||
//! whatever the handler. [`DeviceHealth::watch`] replaces the handler with one that records the
|
||||
//! fault and registers the device-lost callback, and the polls here run only while the device is
|
||||
//! healthy, catching the poll's panic as a last resort. Every GPU entry point checks
|
||||
//! fault and registers the device-lost callback. [`DeviceHealth::probe`] keeps polling until
|
||||
//! that callback runs or a poll panics. Every GPU entry point checks
|
||||
//! [`DeviceHealth::fault`] first.
|
||||
//!
|
||||
//! Builds for the web too: the callbacks only touch atomics and a mutex.
|
||||
@@ -101,8 +101,10 @@ struct Inner {
|
||||
/// The first other error.
|
||||
error: OnceLock<String>,
|
||||
errors: AtomicU64,
|
||||
/// wgpu itself reported the device lost (see [`DeviceHealth::device_lost`]).
|
||||
/// A device loss was confirmed (see [`DeviceHealth::device_lost`]).
|
||||
device_lost: AtomicBool,
|
||||
/// The device-lost callback ran or a poll panicked.
|
||||
polling_stopped: AtomicBool,
|
||||
}
|
||||
|
||||
/// Shared health flag of one wgpu device. Cheap to clone; every clone sees the same state.
|
||||
@@ -137,8 +139,8 @@ impl DeviceHealth {
|
||||
};
|
||||
log::error!("wgpu device lost ({reason:?}): {detail}");
|
||||
// The loss first: a caller that sees `device_lost` then also sees the fault.
|
||||
lost.mark(Fault::Lost(detail));
|
||||
lost.0.device_lost.store(true, Ordering::Release);
|
||||
lost.confirm_device_lost(detail);
|
||||
lost.0.polling_stopped.store(true, Ordering::Release);
|
||||
});
|
||||
let errors = health.clone();
|
||||
device.on_uncaptured_error(Arc::new(move |e: wgpu::Error| errors.uncaptured(&e)));
|
||||
@@ -236,6 +238,11 @@ impl DeviceHealth {
|
||||
self.0.error.get().map(|text| Fault::Error(text.clone()))
|
||||
}
|
||||
|
||||
/// A recorded device loss or error other than out of memory that stops polls and waits.
|
||||
pub fn polling_fault(&self) -> Option<Fault> {
|
||||
self.0.lost.get().map(|text| Fault::Lost(text.clone())).or_else(|| self.0.error.get().map(|text| Fault::Error(text.clone())))
|
||||
}
|
||||
|
||||
/// The device loss in the form of `craft_gpu::GpuContext::device_status`:
|
||||
/// [`GpuFault::DeviceLost`](craft_gpu::GpuFault::DeviceLost) once a loss is recorded,
|
||||
/// otherwise `Ok`. Other errors are reported by [`fault`](Self::fault). wgpu keeps one
|
||||
@@ -253,8 +260,10 @@ impl DeviceHealth {
|
||||
self.0.errors.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Whether wgpu itself reported the device lost: its device-lost callback ran, or polling it
|
||||
/// panicked. A fault recorded with [`mark`](Self::mark) is not one. After a real loss nothing
|
||||
/// Whether a device loss was confirmed: its device-lost callback ran, polling it panicked,
|
||||
/// or [`confirm_device_lost`](Self::confirm_device_lost) or
|
||||
/// [`record_device_loss`](Self::record_device_loss) was called. A fault recorded with
|
||||
/// [`mark`](Self::mark) is not one. After a real loss nothing
|
||||
/// drawn with the device reaches the screen, the window's own frames included.
|
||||
pub fn device_lost(&self) -> bool {
|
||||
self.0.device_lost.load(Ordering::Acquire)
|
||||
@@ -262,9 +271,10 @@ impl DeviceHealth {
|
||||
|
||||
/// Non-blocking poll that runs even after a fault was recorded, so a device that is lost
|
||||
/// later (a driver reset while the app sat idle, or the PC slept) is noticed before the next
|
||||
/// frame is drawn with it. Skipped once [`device_lost`](Self::device_lost).
|
||||
/// frame is drawn with it. Polling stops only after the device-lost callback ran or a poll
|
||||
/// panicked, including when a caller already confirmed the loss.
|
||||
pub fn probe(&self, device: &wgpu::Device) {
|
||||
if self.device_lost() {
|
||||
if self.0.polling_stopped.load(Ordering::Acquire) {
|
||||
return;
|
||||
}
|
||||
if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| device.poll(wgpu::PollType::Poll))).is_err() {
|
||||
@@ -274,7 +284,19 @@ impl DeviceHealth {
|
||||
|
||||
/// `Device::poll` panicked: wgpu found the device lost.
|
||||
fn lost_by_poll(&self) {
|
||||
self.mark(Fault::Lost("the device stopped responding".into()));
|
||||
self.record_device_loss("the device stopped responding".into());
|
||||
self.0.polling_stopped.store(true, Ordering::Release);
|
||||
}
|
||||
|
||||
/// Record a confirmed device loss even when wgpu has deferred its device-lost callback.
|
||||
/// [`probe`](Self::probe) continues polling until that callback runs or a poll panics.
|
||||
pub fn record_device_loss(&self, detail: String) {
|
||||
self.confirm_device_lost(detail);
|
||||
}
|
||||
|
||||
/// Record a caller-confirmed device loss without stopping [`probe`](Self::probe).
|
||||
pub fn confirm_device_lost(&self, detail: String) {
|
||||
self.mark(Fault::Lost(detail));
|
||||
self.0.device_lost.store(true, Ordering::Release);
|
||||
}
|
||||
|
||||
@@ -506,6 +528,15 @@ fn one_line(s: &str) -> String {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn confirming_device_loss_keeps_probe_polling() {
|
||||
let h = DeviceHealth::new();
|
||||
h.clone().confirm_device_lost("destroyed".into());
|
||||
assert!(h.device_lost());
|
||||
assert_eq!(h.fault(), Some(Fault::Lost("destroyed".into())));
|
||||
assert!(!h.0.polling_stopped.load(Ordering::Acquire));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_fault_wins_but_loss_replaces_an_error() {
|
||||
let h = DeviceHealth::new();
|
||||
|
||||
@@ -12,20 +12,20 @@ workspace = true
|
||||
[dependencies]
|
||||
craft-gpu = { workspace = true }
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
||||
wgpu = { workspace = true, features = ["webgpu"] }
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
# Chooses and opens the device, and watches it for a loss (`adapter-probe`).
|
||||
craft-gpu-device = { workspace = true, optional = true }
|
||||
pollster = { workspace = true, optional = true }
|
||||
wgpu = { workspace = true }
|
||||
# Native code uses wgpu only with `adapter-probe`.
|
||||
wgpu = { workspace = true, optional = true }
|
||||
|
||||
[features]
|
||||
default = []
|
||||
adapter-probe = ["dep:pollster"]
|
||||
native-vulkan = ["wgpu/vulkan"]
|
||||
native-dx12 = ["wgpu/dx12"]
|
||||
native-metal = ["wgpu/metal"]
|
||||
native-gles = ["wgpu/gles"]
|
||||
adapter-probe = ["dep:pollster", "dep:craft-gpu-device", "dep:wgpu"]
|
||||
native-vulkan = ["wgpu?/vulkan"]
|
||||
native-dx12 = ["wgpu?/dx12"]
|
||||
native-metal = ["wgpu?/metal"]
|
||||
native-gles = ["wgpu?/gles"]
|
||||
|
||||
[dev-dependencies]
|
||||
pollster = { workspace = true }
|
||||
@@ -33,3 +33,7 @@ pollster = { workspace = true }
|
||||
# providers against a real WgpuContext, not just craft-gpu-null, per RFC-0022 acceptance
|
||||
# requirement 2. Dev-only: no cycle (craft-gpu-providers never depends on craft-gpu-wgpu).
|
||||
craft-gpu-providers = { workspace = true }
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies]
|
||||
# The noop backend opens devices without a GPU in the tests.
|
||||
wgpu = { workspace = true, features = ["noop"] }
|
||||
+284
-106
@@ -1,10 +1,14 @@
|
||||
//! wgpu-backed [`GpuContext`].
|
||||
//!
|
||||
//! WebGPU on `wasm32`; native APIs when backend features are enabled. With the `adapter-probe`
|
||||
//! feature (native only, pollster) and at least one `native-*` backend feature,
|
||||
//! [`WgpuContext::new`] requests a real device and builds [`DeviceCaps`] from what that device
|
||||
//! actually enabled (`Device::limits()` / `Device::features()`), never from the adapter's
|
||||
//! advertised maximum. Without a usable adapter (the features above are off, no GPU is present,
|
||||
//! feature (native only), [`WgpuContext::new`] opens a real device through `craft-gpu-device`
|
||||
//! (its adapter choice for `Preference::Auto`, its driver corrections and its fallback order) and
|
||||
//! builds [`DeviceCaps`] from what that device actually enabled (`Device::limits()` /
|
||||
//! `Device::features()`), never from the adapter's advertised maximum.
|
||||
//! With the native `adapter-probe` feature, `WgpuContext::from_opened` and `WgpuContext::with_device`
|
||||
//! take a device the caller opened.
|
||||
//! A loss is read from the device's `craft_gpu_device::DeviceHealth`, which owns the device's
|
||||
//! device-lost callback. Without a usable adapter (`adapter-probe` is off, no GPU is present,
|
||||
//! or on `wasm32` where real device creation needs the async worker-init path noted in
|
||||
//! `docs/gpu-backends.md`), the context degrades to the same in-memory staging behavior as
|
||||
//! `craft_gpu_null::NullContext` (not a dependency of this crate; named here only for context);
|
||||
@@ -32,29 +36,17 @@ fn probe_fallback(backend_name: &str, device_name: &str) -> DeviceCaps {
|
||||
|
||||
#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))]
|
||||
fn probe_caps_native() -> DeviceCaps {
|
||||
let instance = native::instance();
|
||||
let adapter = match pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())) {
|
||||
Ok(adapter) => adapter,
|
||||
Err(_) => return probe_fallback("wgpu", "no-adapter"),
|
||||
};
|
||||
let info = adapter.get_info();
|
||||
let limits = adapter.limits();
|
||||
DeviceCaps {
|
||||
backend_name: format!("{:?}", info.backend),
|
||||
device_name: info.name,
|
||||
max_storage_buffer_binding_size: limits.max_storage_buffer_binding_size,
|
||||
max_buffer_size: limits.max_buffer_size,
|
||||
max_texture_dimension_2d: limits.max_texture_dimension_2d,
|
||||
features: Vec::new(),
|
||||
vendor_id: info.vendor,
|
||||
software: info.device_type == wgpu::DeviceType::Cpu,
|
||||
}
|
||||
native::instance().as_ref().map(native::probe_caps_on).unwrap_or_else(|| probe_fallback("wgpu", "no-adapter"))
|
||||
}
|
||||
|
||||
/// Adapter-advertised limits, when an adapter is available; otherwise conservative defaults. This
|
||||
/// is the quick, device-free probe for UI surfaces that want a number before any context exists
|
||||
/// (Settings). It is advisory only: these are the adapter's maximums, not a device's granted
|
||||
/// ones. [`WgpuContext::caps`] is the authoritative, device-truth source once a context exists.
|
||||
/// ones. With `adapter-probe` it reports the adapter `craft_gpu_device::pick` chooses for
|
||||
/// `Preference::Auto` without opening a device on it; when a device then fails to open there,
|
||||
/// [`WgpuContext::new`] opens the next adapter in `craft_gpu_device::ranked` order, or a software
|
||||
/// one, which this probe does not report. [`WgpuContext::caps`] is the authoritative, device-truth
|
||||
/// source once a context exists.
|
||||
pub fn probe_caps() -> DeviceCaps {
|
||||
#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))]
|
||||
{
|
||||
@@ -74,11 +66,10 @@ pub fn probe_caps() -> DeviceCaps {
|
||||
|
||||
#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))]
|
||||
mod native {
|
||||
use std::sync::{Arc, Mutex};
|
||||
use craft_gpu::DeviceCaps;
|
||||
use craft_gpu_device::{Capabilities, DeviceHealth, Opened, Preference, Request};
|
||||
|
||||
use craft_gpu::{DeviceCaps, GpuFault};
|
||||
|
||||
use crate::{Backing, DeviceBacking};
|
||||
use crate::{Backing, DeviceBacking, probe_fallback};
|
||||
|
||||
/// Features this context asks a device for. No provider dispatches a real WGSL job on wgpu
|
||||
/// yet (`craft-gpu-providers` ships CPU stand-ins, by design, until that lands); extend this
|
||||
@@ -86,71 +77,77 @@ mod native {
|
||||
/// [`create_device`].
|
||||
const DESIRED_FEATURES: wgpu::Features = wgpu::Features::empty();
|
||||
|
||||
/// An instance over whichever native backends were compiled in (`native-vulkan`,
|
||||
/// `native-dx12`, `native-metal`, `native-gles`), honoring `WGPU_BACKEND` when set, so the
|
||||
/// An instance over `craft_gpu_device::native_descriptor`'s backends (Vulkan, Metal and
|
||||
/// DirectX 12, plus OpenGL except on Windows). OpenGL is also used on Windows when it is
|
||||
/// the only compiled native backend. The instance honors `WGPU_BACKEND` when set, so the
|
||||
/// same build can be pointed at a software Vulkan adapter (lavapipe/llvmpipe) in a local container run or a CI lane.
|
||||
/// `new_without_display_handle` because this context never has a window (no surface is ever
|
||||
/// requested); FilmCraft's own off-screen export device uses the same constructor for the
|
||||
/// same reason (`filmcraft-gpu`'s `export_renderer.rs`, see `docs/gpu-backends.md`).
|
||||
/// The descriptor has no display handle because this context never has a window (no surface
|
||||
/// is ever requested); FilmCraft's own off-screen export device uses the same constructor for
|
||||
/// the same reason (`filmcraft-gpu`'s `export_renderer.rs`, see `docs/gpu-backends.md`).
|
||||
///
|
||||
/// The process holds one instance, made on the first call and returned by every later one,
|
||||
/// so `WGPU_BACKEND` is read once. Every context and every probe requests its adapter from
|
||||
/// it. An instance per context loads and unloads every installed Vulkan driver each time, and
|
||||
/// on Linux with Ubuntu's `mesa-vulkan-drivers` installed, contexts opened that way from
|
||||
/// several threads at once crash with SIGSEGV while a lavapipe device is in use.
|
||||
pub(crate) fn instance() -> wgpu::Instance {
|
||||
static SHARED: std::sync::OnceLock<wgpu::Instance> = std::sync::OnceLock::new();
|
||||
SHARED
|
||||
.get_or_init(|| {
|
||||
let mut desc = wgpu::InstanceDescriptor::new_without_display_handle();
|
||||
if let Some(backends) = wgpu::Backends::from_env() {
|
||||
desc.backends = backends;
|
||||
}
|
||||
wgpu::Instance::new(desc)
|
||||
})
|
||||
.clone()
|
||||
pub(crate) fn instance() -> Option<wgpu::Instance> {
|
||||
instance_with_backends(wgpu::Instance::enabled_backend_features())
|
||||
}
|
||||
|
||||
/// Request a real device. `None` on the defined no-adapter path (no usable adapter): the
|
||||
/// caller degrades to the staging backing, identical in shape to `craft-gpu-null`.
|
||||
pub(crate) fn instance_with_backends(backends: wgpu::Backends) -> Option<wgpu::Instance> {
|
||||
if backends.is_empty() {
|
||||
return None;
|
||||
}
|
||||
static SHARED: std::sync::OnceLock<wgpu::Instance> = std::sync::OnceLock::new();
|
||||
Some(
|
||||
SHARED
|
||||
.get_or_init(|| {
|
||||
let mut desc = craft_gpu_device::native_descriptor();
|
||||
if let Some(backends) = wgpu::Backends::from_env() {
|
||||
desc.backends = backends;
|
||||
}
|
||||
wgpu::Instance::new(desc)
|
||||
})
|
||||
.clone(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Open a real device on `instance` with `craft-gpu-device`'s choice for
|
||||
/// `Preference::Auto`. `None` on the defined no-adapter path (no usable adapter): the caller
|
||||
/// degrades to the staging backing, identical in shape to `craft-gpu-null`.
|
||||
///
|
||||
/// Never panics: `required_features` is intersected with what the adapter actually
|
||||
/// advertises, and `required_limits` is set to the adapter's own limits (never more), so
|
||||
/// Never panics: `craft_gpu_device::open` asks only for the features from
|
||||
/// [`DESIRED_FEATURES`] the adapter has, and for the adapter's own limits (never more), so
|
||||
/// `request_device`'s documented panics ("features/limits not supported by this adapter")
|
||||
/// cannot trigger here.
|
||||
pub(crate) fn create_device_on(instance: &wgpu::Instance) -> Option<(DeviceCaps, Backing)> {
|
||||
let request = Request { label: Some("craft-gpu-wgpu"), optional_features: DESIRED_FEATURES, ..Default::default() };
|
||||
let opened = craft_gpu_device::open(instance, None, &Preference::Auto, &request).ok()?;
|
||||
Some(backing_of(&opened))
|
||||
}
|
||||
|
||||
pub(crate) fn create_device() -> Option<(DeviceCaps, Backing)> {
|
||||
let instance = instance();
|
||||
let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())).ok()?;
|
||||
let features = DESIRED_FEATURES & adapter.features();
|
||||
let limits = adapter.limits();
|
||||
let desc =
|
||||
wgpu::DeviceDescriptor { label: Some("craft-gpu-wgpu"), required_features: features, required_limits: limits, ..Default::default() };
|
||||
let (device, queue) = pollster::block_on(adapter.request_device(&desc)).ok()?;
|
||||
create_device_on(&instance()?)
|
||||
}
|
||||
|
||||
let lost = Arc::new(Mutex::new(None));
|
||||
{
|
||||
let lost = Arc::clone(&lost);
|
||||
device.set_device_lost_callback(move |reason, message| {
|
||||
if let Ok(mut slot) = lost.lock() {
|
||||
*slot = Some(GpuFault::DeviceLost(format!("{reason:?}: {message}")));
|
||||
}
|
||||
});
|
||||
pub(crate) fn backing_of(opened: &Opened) -> (DeviceCaps, Backing) {
|
||||
backing_with(opened.device.clone(), opened.queue.clone(), opened.health.clone())
|
||||
}
|
||||
|
||||
/// The device's own caps, and a backing that reads the loss from `health`.
|
||||
pub(crate) fn backing_with(device: wgpu::Device, queue: wgpu::Queue, health: DeviceHealth) -> (DeviceCaps, Backing) {
|
||||
let caps = craft_gpu_device::device_caps(&device);
|
||||
(caps, Backing::Device(DeviceBacking { device, queue, buffers: Vec::new(), health, pending: Vec::new() }))
|
||||
}
|
||||
|
||||
/// The adapter `craft-gpu-device` would open for `Preference::Auto`, with its advertised
|
||||
/// limits and no features (no device was opened to grant any).
|
||||
pub(crate) fn probe_caps_on(instance: &wgpu::Instance) -> DeviceCaps {
|
||||
let (adapters, _) = craft_gpu_device::list(instance, None);
|
||||
match craft_gpu_device::pick(&adapters, None, &Preference::Auto) {
|
||||
Ok((adapter, _)) => DeviceCaps { features: Vec::new(), ..Capabilities::of_adapter(&adapter).into_device_caps() },
|
||||
Err(_) => probe_fallback("wgpu", "no-adapter"),
|
||||
}
|
||||
|
||||
let info = device.adapter_info();
|
||||
let device_limits = device.limits();
|
||||
let caps = DeviceCaps {
|
||||
backend_name: format!("{:?}", info.backend),
|
||||
device_name: info.name,
|
||||
max_storage_buffer_binding_size: device_limits.max_storage_buffer_binding_size,
|
||||
max_buffer_size: device_limits.max_buffer_size,
|
||||
max_texture_dimension_2d: device_limits.max_texture_dimension_2d,
|
||||
features: device.features().iter_names().map(|(name, _)| name.to_string()).collect(),
|
||||
vendor_id: info.vendor,
|
||||
software: info.device_type == wgpu::DeviceType::Cpu,
|
||||
};
|
||||
let backing = Backing::Device(DeviceBacking { device, queue, buffers: Vec::new(), lost, pending: Vec::new() });
|
||||
Some((caps, backing))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -180,12 +177,72 @@ struct DeviceBacking {
|
||||
/// matching the staging path and `craft-gpu-null` exactly, with no padding visible. `None`
|
||||
/// once freed: see the `Backing::Staging` doc for why the slot stays rather than shifting.
|
||||
buffers: Vec<Option<(wgpu::Buffer, u64)>>,
|
||||
/// Set by the device-lost callback registered in [`native::create_device`]; checked before
|
||||
/// every call that would otherwise touch the (now invalid) device.
|
||||
lost: std::sync::Arc<std::sync::Mutex<Option<GpuFault>>>,
|
||||
/// The device's health from `craft-gpu-device`, which holds its device-lost callback; its
|
||||
/// loss is checked before every call that would otherwise touch the (now invalid) device.
|
||||
health: craft_gpu_device::DeviceHealth,
|
||||
pending: Vec<PendingRead>,
|
||||
}
|
||||
|
||||
#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))]
|
||||
impl DeviceBacking {
|
||||
fn allocation_fault(&self, error: wgpu::Error, operation: &str) -> GpuFault {
|
||||
self.health.caught(&self.device, &error);
|
||||
if let Err(fault) = self.health.device_status() {
|
||||
return fault;
|
||||
}
|
||||
self.prefer_device_loss(GpuFault::Operation(format!("{operation}: {error}")))
|
||||
}
|
||||
|
||||
fn prefer_device_loss(&self, fault: GpuFault) -> GpuFault {
|
||||
if !matches!(fault, GpuFault::DeviceLost(_))
|
||||
&& let Err(loss @ GpuFault::DeviceLost(_)) = self.check_device_valid()
|
||||
{
|
||||
return loss;
|
||||
}
|
||||
fault
|
||||
}
|
||||
|
||||
fn submit_read_copy(&self, commands: wgpu::CommandBuffer, scope: wgpu::ErrorScopeGuard) -> Result<wgpu::SubmissionIndex, GpuFault> {
|
||||
let submission = self.queue.submit(Some(commands));
|
||||
if let Some(error) = pollster::block_on(scope.pop()) {
|
||||
return Err(self.allocation_fault(error, "request_read: device reported an allocation error copying the buffer"));
|
||||
}
|
||||
self.check_device_valid()?;
|
||||
Ok(submission)
|
||||
}
|
||||
|
||||
fn check_device_valid(&self) -> Result<(), GpuFault> {
|
||||
// wgpu-core 30.0.1 checks device validity before rejecting empty buffer usage.
|
||||
// A valid device produces a scoped validation error; device loss bypasses the scope.
|
||||
// Both paths return before HAL allocation or fence waits.
|
||||
// Device owners must synchronize concurrent destroy calls with uploads.
|
||||
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
||||
let scope = self.device.push_error_scope(wgpu::ErrorFilter::Validation);
|
||||
drop(self.device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: None,
|
||||
size: 0,
|
||||
usage: wgpu::BufferUsages::empty(),
|
||||
mapped_at_creation: false,
|
||||
}));
|
||||
pollster::block_on(scope.pop())
|
||||
}));
|
||||
self.health.probe(&self.device);
|
||||
self.health.device_status()?;
|
||||
match result {
|
||||
Ok(None) => {
|
||||
self.health.confirm_device_lost("the device was destroyed or lost".into());
|
||||
}
|
||||
Err(_) => self.health.record_device_loss("the device stopped responding".into()),
|
||||
Ok(Some(_)) => {}
|
||||
}
|
||||
self.health.device_status()?;
|
||||
if let Some(fault) = self.health.polling_fault() {
|
||||
return Err(fault.into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// wgpu's `COPY_BUFFER_ALIGNMENT`: every buffer with copy usage, and every `write_buffer` /
|
||||
/// `copy_buffer_to_buffer` size, must be a multiple of this (4 bytes). Uploading or reading back
|
||||
/// a buffer length that doesn't land on this boundary (`b"xy"`, two bytes) is a validation error
|
||||
@@ -200,6 +257,7 @@ struct PendingRead {
|
||||
request: ReadRequest,
|
||||
handle: HandleId,
|
||||
staging: wgpu::Buffer,
|
||||
submission: wgpu::SubmissionIndex,
|
||||
/// True length to truncate the mapped (padded) bytes back down to.
|
||||
true_len: u64,
|
||||
state: std::sync::Arc<std::sync::Mutex<Option<Result<(), String>>>>,
|
||||
@@ -207,7 +265,7 @@ struct PendingRead {
|
||||
|
||||
#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))]
|
||||
fn resolve_pending(pending: PendingRead) -> ReadOutcome {
|
||||
let PendingRead { request, handle, staging, true_len, state } = pending;
|
||||
let PendingRead { request, handle, staging, true_len, state, .. } = pending;
|
||||
let result = match state.lock() {
|
||||
Ok(mut guard) => match guard.take() {
|
||||
Some(Ok(())) => match staging.get_mapped_range(0..true_len.next_multiple_of(COPY_ALIGN)) {
|
||||
@@ -262,6 +320,38 @@ impl WgpuContext {
|
||||
Self { caps, worker_kind, backing: Backing::Staging(Vec::new()), next_request: 0, ready: Vec::new() }
|
||||
}
|
||||
|
||||
/// A context on a device `craft_gpu_device::open` (or `open_async`) opened, sharing its
|
||||
/// device, queue and [`DeviceHealth`](craft_gpu_device::DeviceHealth). The caps are the
|
||||
/// device's own (`Opened::device_caps`). A loss the health records, from the device-lost
|
||||
/// callback it set or from any other user of the device, is this context's
|
||||
/// `GpuFault::DeviceLost`.
|
||||
#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))]
|
||||
pub fn from_opened(worker_kind: WorkerKind, opened: &craft_gpu_device::Opened) -> Self {
|
||||
let (caps, backing) = native::backing_of(opened);
|
||||
Self { caps, worker_kind, backing, next_request: 0, ready: Vec::new() }
|
||||
}
|
||||
|
||||
/// A context on a device the caller opened, such as the one egui-wgpu's render state holds.
|
||||
/// `queue` must be the queue opened with `device`.
|
||||
/// `health` is the device's [`DeviceHealth::watch`](craft_gpu_device::DeviceHealth::watch);
|
||||
/// wgpu keeps one device-lost callback per device, so this context sets none of its own. The
|
||||
/// caps are the device's own: the features and limits it was opened with, whatever they are.
|
||||
#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))]
|
||||
pub fn with_device(worker_kind: WorkerKind, device: wgpu::Device, queue: wgpu::Queue, health: craft_gpu_device::DeviceHealth) -> Self {
|
||||
let (caps, backing) = native::backing_with(device, queue, health);
|
||||
Self { caps, worker_kind, backing, next_request: 0, ready: Vec::new() }
|
||||
}
|
||||
|
||||
/// The health of this context's device, when it has one: share it with the rest of the app,
|
||||
/// and with `craft_gpu_device::Recovery` after a loss.
|
||||
#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))]
|
||||
pub fn health(&self) -> Option<&craft_gpu_device::DeviceHealth> {
|
||||
match &self.backing {
|
||||
Backing::Device(d) => Some(&d.health),
|
||||
Backing::Staging(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// True when this context holds a real device (`request_device` succeeded), false on the
|
||||
/// staging/no-adapter path. Settings UI can use this to show "no GPU" honestly instead of
|
||||
/// implying a device that was never created; tests use it to skip rather than fail when the
|
||||
@@ -283,7 +373,7 @@ impl WgpuContext {
|
||||
pub fn is_device_lost(&self) -> bool {
|
||||
#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))]
|
||||
if let Backing::Device(d) = &self.backing {
|
||||
return d.lost.lock().map(|g| g.is_some()).unwrap_or(false);
|
||||
return d.health.device_status().is_err();
|
||||
}
|
||||
false
|
||||
}
|
||||
@@ -291,7 +381,52 @@ impl WgpuContext {
|
||||
fn take_lost_fault(&self) -> Option<GpuFault> {
|
||||
#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))]
|
||||
if let Backing::Device(d) = &self.backing {
|
||||
return d.lost.lock().ok().and_then(|g| g.clone());
|
||||
return d.health.device_status().err();
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// `read_buffer` waits for the requested read's copy submission between polls.
|
||||
/// `DeviceHealth::wait` does not wait once the device reported an error other than out of
|
||||
/// memory, stops after its current 100 ms slice when another user of the device records
|
||||
/// such an error, and fails when its poll fails. Then the read of `request` is dropped and
|
||||
/// fails with that error, instead of polling in a loop until a map that may never complete;
|
||||
/// a loss is left to the next `poll_reads`, which fails every pending read with it.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[cfg_attr(not(feature = "adapter-probe"), allow(unused_variables, clippy::unused_self))]
|
||||
fn wait_between_reads(&mut self, request: ReadRequest) -> Option<GpuFault> {
|
||||
#[cfg(feature = "adapter-probe")]
|
||||
if let Backing::Device(d) = &mut self.backing
|
||||
&& (d.health.polling_fault().is_some()
|
||||
|| d.pending.iter().find(|p| p.request == request).is_some_and(|p| !d.health.wait(&d.device, p.submission.clone())))
|
||||
{
|
||||
d.health.probe(&d.device);
|
||||
if d.health.device_status().is_err() {
|
||||
return None;
|
||||
}
|
||||
let fault = d.prefer_device_loss(
|
||||
d.health
|
||||
.polling_fault()
|
||||
.or_else(|| d.health.fault())
|
||||
.map(GpuFault::from)
|
||||
.unwrap_or_else(|| GpuFault::Operation("read_buffer: waiting for the device failed".into())),
|
||||
);
|
||||
if matches!(fault, GpuFault::DeviceLost(_)) {
|
||||
return None;
|
||||
}
|
||||
d.pending.retain(|p| p.request != request);
|
||||
return Some(fault);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Why no new work may go to the device: a loss as `GpuFault::DeviceLost`, and any other
|
||||
/// fault its health recorded (an uncaptured error, or an out-of-memory error the app has not
|
||||
/// cleared with `DeviceHealth::clear_out_of_memory`) as `GpuFault::Operation`.
|
||||
fn take_work_fault(&self) -> Option<GpuFault> {
|
||||
#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))]
|
||||
if let Backing::Device(d) = &self.backing {
|
||||
return d.health.fault().map(GpuFault::from);
|
||||
}
|
||||
None
|
||||
}
|
||||
@@ -308,8 +443,15 @@ impl GpuContext for WgpuContext {
|
||||
|
||||
#[cfg_attr(not(all(not(target_arch = "wasm32"), feature = "adapter-probe")), allow(unused_variables))]
|
||||
fn upload_buffer(&mut self, label: &str, bytes: &[u8]) -> Result<HandleId, GpuFault> {
|
||||
if let Some(fault) = self.take_lost_fault() {
|
||||
return Err(fault);
|
||||
if let Some(fault) = self.take_work_fault() {
|
||||
#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))]
|
||||
if !matches!(fault, GpuFault::DeviceLost(_))
|
||||
&& let Backing::Device(d) = &self.backing
|
||||
&& let Err(loss @ GpuFault::DeviceLost(_)) = d.check_device_valid()
|
||||
{
|
||||
return Err(loss);
|
||||
}
|
||||
return Err(self.take_work_fault().unwrap_or(fault));
|
||||
}
|
||||
match &mut self.backing {
|
||||
Backing::Staging(buffers) => {
|
||||
@@ -322,10 +464,10 @@ impl GpuContext for WgpuContext {
|
||||
let true_len = bytes.len() as u64;
|
||||
let padded_len = true_len.next_multiple_of(COPY_ALIGN);
|
||||
if padded_len > self.caps.max_buffer_size {
|
||||
return Err(GpuFault::InvalidJob(format!(
|
||||
return Err(d.prefer_device_loss(GpuFault::InvalidJob(format!(
|
||||
"upload_buffer: {true_len} bytes (padded to {padded_len}) exceeds the device's max_buffer_size {}",
|
||||
self.caps.max_buffer_size
|
||||
)));
|
||||
))));
|
||||
}
|
||||
// The size check above only catches a request past the device's advertised
|
||||
// maximum; it proves nothing about whether the device can actually allocate
|
||||
@@ -345,7 +487,8 @@ impl GpuContext for WgpuContext {
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
if let Some(err) = pollster::block_on(create_scope.pop()) {
|
||||
return Err(GpuFault::Operation(format!("upload_buffer: device reported an allocation error creating the buffer: {err}")));
|
||||
// The scope kept it from the device's health; every user of the device sees it.
|
||||
return Err(d.allocation_fault(err, "upload_buffer: device reported an allocation error creating the buffer"));
|
||||
}
|
||||
// write_buffer makes its own staging allocation to carry `bytes` to the device, a
|
||||
// second allocation that can also run out of memory; it gets its own scope rather
|
||||
@@ -367,8 +510,10 @@ impl GpuContext for WgpuContext {
|
||||
// is still a submission as far as that flush is concerned, so it is enough.
|
||||
d.queue.submit(std::iter::empty());
|
||||
if let Some(err) = pollster::block_on(write_scope.pop()) {
|
||||
return Err(GpuFault::Operation(format!("upload_buffer: device reported an allocation error writing the buffer: {err}")));
|
||||
return Err(d.allocation_fault(err, "upload_buffer: device reported an allocation error writing the buffer"));
|
||||
}
|
||||
// Loss bypasses error scopes and its callback can wait for pending queue work.
|
||||
d.check_device_valid()?;
|
||||
let id = u32::try_from(d.buffers.len()).map_err(|_| GpuFault::Operation("too many buffers".into()))?;
|
||||
d.buffers.push(Some((buffer, true_len)));
|
||||
Ok(HandleId(id))
|
||||
@@ -394,8 +539,26 @@ impl GpuContext for WgpuContext {
|
||||
}
|
||||
|
||||
fn request_read(&mut self, handle: HandleId) -> Result<ReadRequest, GpuFault> {
|
||||
if let Some(fault) = self.take_lost_fault() {
|
||||
return Err(fault);
|
||||
if let Some(fault) = self.take_work_fault() {
|
||||
#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))]
|
||||
if !matches!(fault, GpuFault::DeviceLost(_))
|
||||
&& let Backing::Device(d) = &self.backing
|
||||
&& let Err(loss @ GpuFault::DeviceLost(_)) = d.check_device_valid()
|
||||
{
|
||||
return Err(loss);
|
||||
}
|
||||
return Err(self.take_work_fault().unwrap_or(fault));
|
||||
}
|
||||
#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))]
|
||||
if let Backing::Device(d) = &self.backing {
|
||||
d.buffers
|
||||
.get(handle.0 as usize)
|
||||
.and_then(Option::as_ref)
|
||||
.ok_or_else(|| d.prefer_device_loss(GpuFault::InvalidJob("bad handle".into())))?;
|
||||
d.check_device_valid()?;
|
||||
if let Some(fault) = self.take_work_fault() {
|
||||
return Err(fault);
|
||||
}
|
||||
}
|
||||
match &mut self.backing {
|
||||
Backing::Staging(buffers) => {
|
||||
@@ -409,8 +572,11 @@ impl GpuContext for WgpuContext {
|
||||
}
|
||||
#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))]
|
||||
Backing::Device(d) => {
|
||||
let (buffer, true_len) =
|
||||
d.buffers.get(handle.0 as usize).and_then(Option::as_ref).ok_or_else(|| GpuFault::InvalidJob("bad handle".into()))?;
|
||||
let (buffer, true_len) = d
|
||||
.buffers
|
||||
.get(handle.0 as usize)
|
||||
.and_then(Option::as_ref)
|
||||
.ok_or_else(|| d.prefer_device_loss(GpuFault::InvalidJob("bad handle".into())))?;
|
||||
let true_len = *true_len;
|
||||
if true_len == 0 {
|
||||
// An empty buffer has nothing to copy or map (wgpu refuses an empty map
|
||||
@@ -443,17 +609,14 @@ impl GpuContext for WgpuContext {
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
if let Some(err) = pollster::block_on(create_scope.pop()) {
|
||||
return Err(GpuFault::Operation(format!("request_read: device reported an allocation error creating the staging buffer: {err}")));
|
||||
return Err(d.allocation_fault(err, "request_read: device reported an allocation error creating the staging buffer"));
|
||||
}
|
||||
// The copy and its submission get their own scope rather than reusing the one
|
||||
// already closed above, same split as upload_buffer's create vs. write.
|
||||
let copy_scope = d.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory);
|
||||
let mut encoder = d.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("craft-gpu-wgpu.read-copy") });
|
||||
encoder.copy_buffer_to_buffer(buffer, 0, &staging, 0, copy_len);
|
||||
d.queue.submit(Some(encoder.finish()));
|
||||
if let Some(err) = pollster::block_on(copy_scope.pop()) {
|
||||
return Err(GpuFault::Operation(format!("request_read: device reported an allocation error copying the buffer: {err}")));
|
||||
}
|
||||
let submission = d.submit_read_copy(encoder.finish(), copy_scope)?;
|
||||
let state = std::sync::Arc::new(std::sync::Mutex::new(None));
|
||||
{
|
||||
let state = std::sync::Arc::clone(&state);
|
||||
@@ -466,7 +629,7 @@ impl GpuContext for WgpuContext {
|
||||
let id = self.next_request;
|
||||
self.next_request = self.next_request.wrapping_add(1);
|
||||
let request = ReadRequest(id);
|
||||
d.pending.push(PendingRead { request, handle, staging, true_len, state });
|
||||
d.pending.push(PendingRead { request, handle, staging, submission, true_len, state });
|
||||
Ok(request)
|
||||
}
|
||||
}
|
||||
@@ -506,16 +669,32 @@ impl GpuContext for WgpuContext {
|
||||
let mut outcomes = std::mem::take(&mut self.ready);
|
||||
#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))]
|
||||
if let Backing::Device(d) = &mut self.backing {
|
||||
if let Some(fault) = d.lost.lock().ok().and_then(|g| g.clone()) {
|
||||
// A non-blocking poll that also runs after an error other than a loss was recorded,
|
||||
// and records a loss instead of panicking when the device is gone.
|
||||
d.health.probe(&d.device);
|
||||
let fault = d.health.polling_fault().map(GpuFault::from);
|
||||
if let Some(fault) = fault {
|
||||
let fault = d.prefer_device_loss(fault);
|
||||
outcomes.extend(d.pending.drain(..).map(|p| ReadOutcome { request: p.request, handle: p.handle, result: Err(fault.clone()) }));
|
||||
return outcomes;
|
||||
}
|
||||
let _ = d.device.poll(wgpu::PollType::Poll);
|
||||
let mut remaining = Vec::with_capacity(d.pending.len());
|
||||
for pending in d.pending.drain(..) {
|
||||
let mut remaining: Vec<PendingRead> = Vec::with_capacity(d.pending.len());
|
||||
let mut pending_reads = std::mem::take(&mut d.pending).into_iter();
|
||||
while let Some(pending) = pending_reads.next() {
|
||||
let is_ready = pending.state.lock().map(|g| g.is_some()).unwrap_or(false);
|
||||
if is_ready {
|
||||
outcomes.push(resolve_pending(pending));
|
||||
let mut outcome = resolve_pending(pending);
|
||||
outcome.result = outcome.result.map_err(|fault| d.prefer_device_loss(fault));
|
||||
if let Err(fault @ GpuFault::DeviceLost(_)) = &outcome.result {
|
||||
outcomes.extend(remaining.into_iter().chain(pending_reads).map(|p| ReadOutcome {
|
||||
request: p.request,
|
||||
handle: p.handle,
|
||||
result: Err(fault.clone()),
|
||||
}));
|
||||
outcomes.push(outcome);
|
||||
return outcomes;
|
||||
}
|
||||
outcomes.push(outcome);
|
||||
} else {
|
||||
remaining.push(pending);
|
||||
}
|
||||
@@ -547,9 +726,8 @@ impl GpuContext for WgpuContext {
|
||||
// Block on the GPU between polls instead of busy-spinning the CPU. A no-op when
|
||||
// `backing` is `Staging` (nothing to wait for; the request already resolved above)
|
||||
// or when wgpu is itself WebGPU under the hood, which self-polls.
|
||||
#[cfg(feature = "adapter-probe")]
|
||||
if let Backing::Device(d) = &self.backing {
|
||||
let _ = d.device.poll(wgpu::PollType::wait_indefinitely());
|
||||
if let Some(fault) = self.wait_between_reads(request) {
|
||||
return Err(fault);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -341,10 +341,16 @@ fn device_status_surfaces_loss_even_with_nothing_pending() {
|
||||
#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))]
|
||||
#[test]
|
||||
fn every_context_and_probe_shares_one_wgpu_instance() {
|
||||
let first = crate::native::instance();
|
||||
let again = std::thread::spawn(crate::native::instance).join().expect("instance() on another thread");
|
||||
let first = crate::native::instance().expect("the noop backend is compiled");
|
||||
let again = std::thread::spawn(crate::native::instance).join().expect("instance() on another thread").expect("the noop backend is compiled");
|
||||
assert_eq!(first, again, "a second call, from another thread, must return the same instance");
|
||||
assert_eq!(first, crate::native::instance(), "a later call must return the same instance");
|
||||
assert_eq!(Some(first), crate::native::instance(), "a later call must return the same instance");
|
||||
}
|
||||
|
||||
#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))]
|
||||
#[test]
|
||||
fn no_compiled_backend_returns_no_instance() {
|
||||
assert!(crate::native::instance_with_backends(wgpu::Backends::empty()).is_none());
|
||||
}
|
||||
|
||||
/// Same two guarantees on a real device: empty buffers round-trip (the readback resolves without
|
||||
@@ -377,3 +383,557 @@ fn real_device_empty_buffer_and_interleaved_read_buffer_behave_like_staging() {
|
||||
}
|
||||
assert!(seen_a, "a's completion must still arrive through poll_reads after b's read_buffer");
|
||||
}
|
||||
|
||||
/// Devices from `craft-gpu-device`, on wgpu's noop backend, so these run without a GPU.
|
||||
#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))]
|
||||
mod device_from_craft_gpu_device {
|
||||
use craft_gpu::{GpuContext, GpuFault, WorkerKind};
|
||||
use craft_gpu_device::{DeviceHealth, Fault, Preference, Request};
|
||||
|
||||
use crate::{Backing, WgpuContext, native};
|
||||
|
||||
/// An instance whose only adapter is wgpu's noop one, which wgpu 30 lists as a software
|
||||
/// adapter.
|
||||
fn noop() -> wgpu::Instance {
|
||||
let mut desc = wgpu::InstanceDescriptor::new_without_display_handle();
|
||||
desc.backends = wgpu::Backends::NOOP;
|
||||
desc.backend_options.noop = wgpu::NoopBackendOptions { enable: true, ..Default::default() };
|
||||
wgpu::Instance::new(desc)
|
||||
}
|
||||
|
||||
fn opened() -> craft_gpu_device::Opened {
|
||||
craft_gpu_device::open(&noop(), None, &Preference::Software, &Request::default()).expect("the noop adapter opens")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_read_copy_rejected_after_device_destruction_reports_loss() {
|
||||
let opened = opened();
|
||||
let ctx = WgpuContext::from_opened(WorkerKind::Main, &opened);
|
||||
let Backing::Device(d) = &ctx.backing else { panic!("a device backing") };
|
||||
d.check_device_valid().expect("a valid device");
|
||||
let scope = opened.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory);
|
||||
let commands = opened.device.create_command_encoder(&wgpu::CommandEncoderDescriptor::default()).finish();
|
||||
opened.device.set_device_lost_callback(|_, _| {});
|
||||
opened.device.destroy();
|
||||
assert_eq!(opened.health.device_status(), Ok(()));
|
||||
|
||||
assert!(matches!(d.submit_read_copy(commands, scope), Err(GpuFault::DeviceLost(_))));
|
||||
assert!(opened.health.device_lost());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_allocation_fault_returns_loss_discovered_by_caught() {
|
||||
for destroyed in [false, true] {
|
||||
let opened = opened();
|
||||
let ctx = WgpuContext::from_opened(WorkerKind::Main, &opened);
|
||||
let Backing::Device(d) = &ctx.backing else { panic!("a device backing") };
|
||||
if destroyed {
|
||||
opened.device.destroy();
|
||||
}
|
||||
assert_eq!(opened.health.device_status(), Ok(()));
|
||||
let error = wgpu::Error::OutOfMemory { source: Box::new(std::io::Error::other("allocation failed")) };
|
||||
let fault = d.allocation_fault(error, "allocation");
|
||||
if destroyed {
|
||||
assert!(matches!(fault, GpuFault::DeviceLost(_)), "{fault:?}");
|
||||
assert!(opened.health.device_lost());
|
||||
} else {
|
||||
assert!(matches!(fault, GpuFault::Operation(_)), "{fault:?}");
|
||||
assert!(opened.health.fault().is_some_and(|fault| fault.is_out_of_memory()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_allocation_fault_detects_loss_before_callback_delivery() {
|
||||
for validation in [false, true] {
|
||||
let opened = opened();
|
||||
let ctx = WgpuContext::from_opened(WorkerKind::Main, &opened);
|
||||
let Backing::Device(d) = &ctx.backing else { panic!("a device backing") };
|
||||
if validation {
|
||||
opened.health.mark(Fault::Error("Validation Error".into()));
|
||||
}
|
||||
opened.device.set_device_lost_callback(|_, _| {});
|
||||
opened.device.destroy();
|
||||
assert_eq!(opened.health.device_status(), Ok(()));
|
||||
let error = wgpu::Error::OutOfMemory { source: Box::new(std::io::Error::other("allocation failed")) };
|
||||
|
||||
let fault = d.allocation_fault(error, "allocation");
|
||||
assert!(matches!(fault, GpuFault::DeviceLost(_)), "{fault:?}");
|
||||
assert!(opened.health.device_lost());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_default_device_is_the_one_craft_gpu_device_opens() {
|
||||
let (caps, backing) = native::create_device_on(&noop()).expect("the noop adapter opens");
|
||||
let Backing::Device(d) = &backing else { panic!("a device backing") };
|
||||
assert_eq!(caps, craft_gpu_device::device_caps(&d.device));
|
||||
assert!(caps.software, "{caps:?}");
|
||||
assert!(d.health.is_ok() && d.health.device_status().is_ok());
|
||||
// no adapter at all: the staging path
|
||||
let mut desc = wgpu::InstanceDescriptor::new_without_display_handle();
|
||||
desc.backends = wgpu::Backends::NOOP;
|
||||
assert!(native::create_device_on(&wgpu::Instance::new(desc)).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_probe_reports_the_adapter_craft_gpu_device_picks() {
|
||||
let opened = opened();
|
||||
let caps = native::probe_caps_on(&noop());
|
||||
assert_eq!(caps.device_name, opened.candidate.name);
|
||||
assert!(caps.software && caps.features.is_empty(), "{caps:?}");
|
||||
let mut desc = wgpu::InstanceDescriptor::new_without_display_handle();
|
||||
desc.backends = wgpu::Backends::NOOP;
|
||||
assert_eq!(native::probe_caps_on(&wgpu::Instance::new(desc)).device_name, "no-adapter");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_context_on_an_opened_device_reads_the_loss_from_its_health() {
|
||||
let opened = opened();
|
||||
let mut ctx = WgpuContext::from_opened(WorkerKind::Main, &opened);
|
||||
assert!(ctx.has_device());
|
||||
assert_eq!(ctx.caps(), opened.device_caps());
|
||||
assert_eq!(ctx.device_status(), Ok(()));
|
||||
// a loss another user of the device records is this context's loss too
|
||||
opened.health.mark(Fault::Lost("the driver reset the GPU".into()));
|
||||
assert!(ctx.health().is_some_and(|h| h.device_status().is_err()));
|
||||
assert_eq!(ctx.device_status(), Err(GpuFault::DeviceLost("the driver reset the GPU".into())));
|
||||
assert!(ctx.is_device_lost());
|
||||
assert!(matches!(ctx.upload_buffer("after-loss", b"x"), Err(GpuFault::DeviceLost(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_destroyed_device_is_lost_through_the_health_that_watches_it() {
|
||||
let opened = opened();
|
||||
let health = DeviceHealth::watch(&opened.device);
|
||||
let mut ctx = WgpuContext::with_device(WorkerKind::DedicatedWorker, opened.device.clone(), opened.queue.clone(), health.clone());
|
||||
assert_eq!(ctx.caps(), opened.device_caps());
|
||||
opened.device.destroy();
|
||||
let _ = ctx.poll_reads();
|
||||
assert!(health.device_status().is_err(), "{health:?}");
|
||||
assert!(matches!(ctx.device_status(), Err(GpuFault::DeviceLost(_))));
|
||||
assert!(matches!(ctx.request_read(craft_gpu::HandleId(0)), Err(GpuFault::DeviceLost(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_upload_to_a_destroyed_shared_device_fails_without_a_poll_first() {
|
||||
let opened = opened();
|
||||
let mut ctx = WgpuContext::from_opened(WorkerKind::Main, &opened);
|
||||
opened.device.destroy();
|
||||
assert!(matches!(ctx.upload_buffer("after-destroy", b"abcd"), Err(GpuFault::DeviceLost(_))));
|
||||
let Backing::Device(d) = &ctx.backing else { panic!("a device backing") };
|
||||
assert!(d.buffers.is_empty(), "no handle is kept for the failed upload");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_read_detects_loss_before_the_callback_updates_health() {
|
||||
let opened = opened();
|
||||
let mut ctx = WgpuContext::from_opened(WorkerKind::Main, &opened);
|
||||
let handle = ctx.upload_buffer("empty", b"").expect("upload");
|
||||
opened.device.set_device_lost_callback(|_, _| {});
|
||||
opened.device.destroy();
|
||||
assert_eq!(opened.health.device_status(), Ok(()));
|
||||
let next_request = ctx.next_request;
|
||||
assert!(matches!(ctx.request_read(handle), Err(GpuFault::DeviceLost(_))));
|
||||
assert_eq!(ctx.next_request, next_request);
|
||||
assert!(ctx.ready.is_empty());
|
||||
assert!(opened.health.device_lost());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_nonempty_read_detects_loss_before_the_callback_updates_health() {
|
||||
let opened = opened();
|
||||
let mut ctx = WgpuContext::from_opened(WorkerKind::Main, &opened);
|
||||
let handle = ctx.upload_buffer("nonempty", b"abcd").expect("upload");
|
||||
opened.device.set_device_lost_callback(|_, _| {});
|
||||
opened.device.destroy();
|
||||
assert_eq!(opened.health.device_status(), Ok(()));
|
||||
let next_request = ctx.next_request;
|
||||
assert!(matches!(ctx.request_read(handle), Err(GpuFault::DeviceLost(_))));
|
||||
assert_eq!(ctx.next_request, next_request);
|
||||
assert!(ctx.ready.is_empty());
|
||||
assert!(opened.health.device_lost());
|
||||
let Backing::Device(d) = &ctx.backing else { panic!("a device backing") };
|
||||
assert!(d.pending.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_upload_to_a_destroyed_device_fails_when_the_loss_waits_for_pending_work() {
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
let opened = opened();
|
||||
let mut ctx = WgpuContext::from_opened(WorkerKind::Main, &opened);
|
||||
let work_pending = Arc::new(AtomicBool::new(true));
|
||||
let delivered = Arc::new(AtomicBool::new(false));
|
||||
let loss_pending = Arc::new(AtomicBool::new(false));
|
||||
let flag = Arc::clone(&loss_pending);
|
||||
// The noop queue finishes immediately. This gate emulates work that stays pending
|
||||
// through every upload poll, with loss delivery controlled by the test.
|
||||
opened.device.set_device_lost_callback(move |_, _| {
|
||||
flag.store(true, Ordering::Release);
|
||||
});
|
||||
let deliver_loss = || {
|
||||
if !work_pending.load(Ordering::Acquire) && loss_pending.swap(false, Ordering::AcqRel) {
|
||||
let health = opened.health.clone();
|
||||
let delivered = Arc::clone(&delivered);
|
||||
opened.queue.on_submitted_work_done(move || {
|
||||
health.mark(Fault::Lost("destroyed".into()));
|
||||
delivered.store(true, Ordering::Release);
|
||||
});
|
||||
}
|
||||
};
|
||||
opened.queue.submit([]);
|
||||
opened.device.destroy();
|
||||
assert!(!delivered.load(Ordering::Acquire));
|
||||
deliver_loss();
|
||||
assert_eq!(ctx.device_status(), Ok(()));
|
||||
assert!(matches!(ctx.upload_buffer("after-destroy", b"abcd"), Err(GpuFault::DeviceLost(_))));
|
||||
assert!(opened.health.device_lost());
|
||||
assert!(work_pending.load(Ordering::Acquire));
|
||||
assert!(!delivered.load(Ordering::Acquire), "the upload must detect loss before callback delivery");
|
||||
let Backing::Device(d) = &ctx.backing else { panic!("a device backing") };
|
||||
assert!(d.buffers.is_empty(), "no handle is kept for the failed upload");
|
||||
work_pending.store(false, Ordering::Release);
|
||||
assert!(loss_pending.load(Ordering::Acquire), "the device-lost callback must run");
|
||||
deliver_loss();
|
||||
assert!(!delivered.load(Ordering::Acquire));
|
||||
ctx.poll_reads();
|
||||
assert!(delivered.load(Ordering::Acquire));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn device_loss_overrides_an_earlier_work_fault_before_callback_delivery() {
|
||||
for message in [craft_gpu_device::OUT_OF_MEMORY, "Validation Error"] {
|
||||
for upload in [false, true] {
|
||||
let opened = opened();
|
||||
let mut ctx = WgpuContext::from_opened(WorkerKind::Main, &opened);
|
||||
let handle = ctx.upload_buffer("pending", b"abcd").expect("upload");
|
||||
let request = ctx.request_read(handle).expect("request_read");
|
||||
opened.health.mark(Fault::Error(message.into()));
|
||||
// The noop queue completes immediately. The test defers the callback's health update until after the call.
|
||||
opened.device.set_device_lost_callback(|_, _| {});
|
||||
opened.device.destroy();
|
||||
assert_eq!(opened.health.fault(), Some(Fault::Error(message.into())));
|
||||
let next_request = ctx.next_request;
|
||||
let result = if upload { ctx.upload_buffer("after-destroy", b"abcd").map(|_| ()) } else { ctx.request_read(handle).map(|_| ()) };
|
||||
assert!(matches!(result, Err(GpuFault::DeviceLost(_))), "{result:?}");
|
||||
assert!(opened.health.device_lost());
|
||||
assert_eq!(ctx.next_request, next_request);
|
||||
let Backing::Device(d) = &ctx.backing else { panic!("a device backing") };
|
||||
assert_eq!(d.buffers.len(), 1);
|
||||
assert_eq!(d.pending.len(), 1);
|
||||
assert_eq!(d.pending[0].request, request);
|
||||
assert!(ctx.ready.is_empty());
|
||||
opened.health.mark(Fault::Lost("destroyed".into()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_read_rechecks_out_of_memory_reported_during_the_validity_probe() {
|
||||
let opened = opened();
|
||||
let mut ctx = WgpuContext::from_opened(WorkerKind::Main, &opened);
|
||||
let handle = ctx.upload_buffer("before", b"abcd").expect("upload");
|
||||
let health = opened.health.clone();
|
||||
opened.queue.on_submitted_work_done(move || {
|
||||
health.mark(Fault::Error(craft_gpu_device::OUT_OF_MEMORY.into()));
|
||||
});
|
||||
assert_eq!(opened.health.fault(), None);
|
||||
let next_request = ctx.next_request;
|
||||
|
||||
assert_eq!(ctx.request_read(handle), Err(GpuFault::Operation(craft_gpu_device::OUT_OF_MEMORY.into())));
|
||||
assert!(opened.health.fault().is_some_and(|fault| fault.is_out_of_memory()));
|
||||
assert_eq!(ctx.next_request, next_request);
|
||||
assert!(ctx.ready.is_empty());
|
||||
let Backing::Device(d) = &ctx.backing else { panic!("a device backing") };
|
||||
assert!(d.pending.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_work_preserves_out_of_memory_precedence_over_validation_errors() {
|
||||
for oom_first in [true, false] {
|
||||
let opened = opened();
|
||||
let mut ctx = WgpuContext::from_opened(WorkerKind::Main, &opened);
|
||||
let handle = ctx.upload_buffer("before", b"abcd").expect("upload");
|
||||
let faults = [Fault::Error(craft_gpu_device::OUT_OF_MEMORY.into()), Fault::Error("Validation Error".into())];
|
||||
for index in if oom_first { [0, 1] } else { [1, 0] } {
|
||||
opened.health.mark(faults[index].clone());
|
||||
}
|
||||
assert_eq!(ctx.upload_buffer("oom", b"x"), Err(GpuFault::Operation(craft_gpu_device::OUT_OF_MEMORY.into())));
|
||||
assert_eq!(ctx.request_read(handle), Err(GpuFault::Operation(craft_gpu_device::OUT_OF_MEMORY.into())));
|
||||
assert_eq!(ctx.device_status(), Ok(()));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_work_goes_to_a_device_whose_health_recorded_an_error() {
|
||||
let opened = opened();
|
||||
let mut ctx = WgpuContext::from_opened(WorkerKind::Main, &opened);
|
||||
let handle = ctx.upload_buffer("before", b"abcd").expect("upload on a healthy device");
|
||||
// an out-of-memory error stops new work until the app clears it
|
||||
opened.health.mark(Fault::Error(craft_gpu_device::OUT_OF_MEMORY.into()));
|
||||
assert!(matches!(ctx.upload_buffer("oom", b"x"), Err(GpuFault::Operation(_))));
|
||||
assert!(matches!(ctx.request_read(handle), Err(GpuFault::Operation(_))));
|
||||
assert_eq!(ctx.device_status(), Ok(()), "only a loss is a device_status fault");
|
||||
ctx.free_buffer(handle);
|
||||
opened.health.clear_out_of_memory(opened.health.out_of_memory_count());
|
||||
let handle = ctx.upload_buffer("after", b"abcd").expect("upload once the error is cleared");
|
||||
assert_eq!(ctx.buffer_len(handle), Ok(4));
|
||||
// another error stops it for good
|
||||
opened.health.mark(Fault::Error("Validation Error".into()));
|
||||
assert_eq!(ctx.upload_buffer("validation", b"x"), Err(GpuFault::Operation("Validation Error".into())));
|
||||
assert_eq!(ctx.device_status(), Ok(()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_read_waiting_when_the_device_reports_an_error_fails_instead_of_polling_forever() {
|
||||
let opened = opened();
|
||||
let mut ctx = WgpuContext::from_opened(WorkerKind::Main, &opened);
|
||||
let handle = ctx.upload_buffer("pending", b"abcd").expect("upload");
|
||||
let request = ctx.request_read(handle).expect("request_read");
|
||||
opened.health.mark(Fault::Error("Validation Error".into()));
|
||||
assert_eq!(ctx.wait_between_reads(request), Some(GpuFault::Operation("Validation Error".into())));
|
||||
let Backing::Device(d) = &ctx.backing else { panic!("a device backing") };
|
||||
assert!(d.pending.iter().all(|p| p.request != request), "the failed read is dropped");
|
||||
// a loss is left to poll_reads, which fails every pending read with it
|
||||
let other = ctx.request_read(handle);
|
||||
assert!(other.is_err());
|
||||
opened.health.mark(Fault::Lost("gone".into()));
|
||||
assert_eq!(ctx.wait_between_reads(request), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn waiting_for_a_read_does_not_submit_more_queue_work() {
|
||||
let opened = opened();
|
||||
let mut ctx = WgpuContext::from_opened(WorkerKind::Main, &opened);
|
||||
let handle = ctx.upload_buffer("pending", b"abcd").expect("upload");
|
||||
let request = ctx.request_read(handle).expect("read");
|
||||
opened.queue.submit([]);
|
||||
|
||||
let probe = craft_gpu_device::open(&noop(), None, &Preference::Software, &Request::default()).expect("the noop adapter opens");
|
||||
// The probe supplies an index just beyond this device's submitted work.
|
||||
let next_index = loop {
|
||||
let index = probe.queue.submit([]);
|
||||
match opened.device.poll(wgpu::PollType::Wait { submission_index: Some(index.clone()), timeout: Some(std::time::Duration::ZERO) }) {
|
||||
Err(wgpu::PollError::WrongSubmissionIndex(..)) => break index,
|
||||
Ok(_) => {}
|
||||
Err(err) => panic!("unexpected poll error: {err}"),
|
||||
}
|
||||
};
|
||||
|
||||
assert_eq!(ctx.wait_between_reads(request), None);
|
||||
// An extra submission would make the probe index valid.
|
||||
assert!(matches!(
|
||||
opened.device.poll(wgpu::PollType::Wait { submission_index: Some(next_index), timeout: Some(std::time::Duration::ZERO) }),
|
||||
Err(wgpu::PollError::WrongSubmissionIndex(..))
|
||||
));
|
||||
let outcomes = ctx.poll_reads();
|
||||
assert_eq!(outcomes.len(), 1);
|
||||
assert_eq!(outcomes[0].request, request);
|
||||
assert_eq!(outcomes[0].result, Ok(b"abcd".to_vec()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_read_waits_for_its_copy_after_out_of_memory() {
|
||||
let opened = opened();
|
||||
let mut ctx = WgpuContext::from_opened(WorkerKind::Main, &opened);
|
||||
let handle = ctx.upload_buffer("pending", b"abcd").expect("upload");
|
||||
let request = ctx.request_read(handle).expect("read");
|
||||
opened.health.mark(Fault::Error(craft_gpu_device::OUT_OF_MEMORY.into()));
|
||||
|
||||
assert_eq!(ctx.wait_between_reads(request), None);
|
||||
let Backing::Device(d) = &ctx.backing else { panic!("a device backing") };
|
||||
let pending = d.pending.iter().find(|p| p.request == request).expect("pending read");
|
||||
assert!(matches!(*pending.state.lock().expect("map state"), Some(Ok(()))), "the wait completes the map despite out of memory");
|
||||
assert_eq!(opened.health.device_status(), Ok(()));
|
||||
let outcomes = ctx.poll_reads();
|
||||
assert_eq!(outcomes.len(), 1);
|
||||
assert_eq!(outcomes[0].request, request);
|
||||
assert_eq!(outcomes[0].result, Ok(b"abcd".to_vec()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rejected_read_submission_detects_loss_before_callback_delivery() {
|
||||
let opened = opened();
|
||||
let mut ctx = WgpuContext::from_opened(WorkerKind::Main, &opened);
|
||||
let handle = ctx.upload_buffer("pending", b"abcd").expect("upload");
|
||||
let request = ctx.request_read(handle).expect("read");
|
||||
opened.device.set_device_lost_callback(|_, _| {});
|
||||
opened.device.destroy();
|
||||
let rejected = opened.queue.submit([]);
|
||||
let Backing::Device(d) = &mut ctx.backing else { panic!("a device backing") };
|
||||
d.pending.iter_mut().find(|p| p.request == request).expect("pending read").submission = rejected;
|
||||
|
||||
assert_eq!(ctx.wait_between_reads(request), None);
|
||||
assert!(opened.health.device_lost());
|
||||
let Backing::Device(d) = &ctx.backing else { panic!("a device backing") };
|
||||
assert!(d.pending.iter().any(|p| p.request == request));
|
||||
let outcomes = ctx.poll_reads();
|
||||
assert_eq!(outcomes.len(), 1);
|
||||
assert_eq!(outcomes[0].request, request);
|
||||
assert!(matches!(outcomes[0].result, Err(GpuFault::DeviceLost(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_read_waiting_with_out_of_memory_and_a_validation_error_fails_with_the_validation_error() {
|
||||
for oom_first in [true, false] {
|
||||
let opened = opened();
|
||||
let mut ctx = WgpuContext::from_opened(WorkerKind::Main, &opened);
|
||||
let handle = ctx.upload_buffer("pending", b"abcd").expect("upload");
|
||||
let request = ctx.request_read(handle).expect("request_read");
|
||||
let faults = [Fault::Error(craft_gpu_device::OUT_OF_MEMORY.into()), Fault::Error("Validation Error".into())];
|
||||
for index in if oom_first { [0, 1] } else { [1, 0] } {
|
||||
opened.health.mark(faults[index].clone());
|
||||
}
|
||||
assert_eq!(ctx.wait_between_reads(request), Some(GpuFault::Operation("Validation Error".into())));
|
||||
let Backing::Device(d) = &ctx.backing else { panic!("a device backing") };
|
||||
assert!(d.pending.iter().all(|p| p.request != request), "the failed read is dropped");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_staging_context_has_no_health() {
|
||||
let ctx = WgpuContext::with_caps(WorkerKind::Main, craft_gpu::DeviceCaps::default());
|
||||
assert!(ctx.health().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pending_read_fails_when_validation_and_out_of_memory_coexist() {
|
||||
for oom_first in [true, false] {
|
||||
let device = opened();
|
||||
let mut ctx = WgpuContext::from_opened(WorkerKind::Main, &device);
|
||||
let handle = ctx.upload_buffer("pending", b"abcd").expect("upload");
|
||||
let request = ctx.request_read(handle).expect("read");
|
||||
let faults = [Fault::Error(craft_gpu_device::OUT_OF_MEMORY.into()), Fault::Error("Validation Error".into())];
|
||||
for index in if oom_first { [0, 1] } else { [1, 0] } {
|
||||
device.health.mark(faults[index].clone());
|
||||
}
|
||||
let outcomes = ctx.poll_reads();
|
||||
assert_eq!(outcomes.len(), 1);
|
||||
assert_eq!(outcomes[0].request, request);
|
||||
assert_eq!(outcomes[0].result, Err(GpuFault::Operation("Validation Error".into())));
|
||||
assert!(ctx.poll_reads().is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn polling_pending_reads_prefers_loss_before_callback_delivery() {
|
||||
let opened = opened();
|
||||
let mut ctx = WgpuContext::from_opened(WorkerKind::Main, &opened);
|
||||
let handle = ctx.upload_buffer("pending", b"abcd").expect("upload");
|
||||
let first = ctx.request_read(handle).expect("first read");
|
||||
let second = ctx.request_read(handle).expect("second read");
|
||||
opened.health.mark(Fault::Error("Validation Error".into()));
|
||||
opened.device.set_device_lost_callback(|_, _| {});
|
||||
opened.device.destroy();
|
||||
assert_eq!(opened.health.device_status(), Ok(()));
|
||||
|
||||
let outcomes = ctx.poll_reads();
|
||||
assert_eq!(outcomes.len(), 2);
|
||||
assert!(outcomes.iter().any(|outcome| outcome.request == first));
|
||||
assert!(outcomes.iter().any(|outcome| outcome.request == second));
|
||||
for outcome in outcomes {
|
||||
assert_eq!(outcome.handle, handle);
|
||||
assert!(matches!(outcome.result, Err(GpuFault::DeviceLost(_))));
|
||||
}
|
||||
assert!(opened.health.device_lost());
|
||||
assert!(ctx.poll_reads().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn device_errors_prefer_loss_before_callback_delivery() {
|
||||
for operation in 0..4 {
|
||||
let opened = opened();
|
||||
let mut ctx = WgpuContext::from_opened(WorkerKind::Main, &opened);
|
||||
let handle = ctx.upload_buffer("pending", b"abcd").expect("upload");
|
||||
let request = ctx.request_read(handle).expect("read");
|
||||
let Backing::Device(d) = &mut ctx.backing else { panic!("a device backing") };
|
||||
d.pending[0].state = std::sync::Arc::new(std::sync::Mutex::new(Some(Err("mapping failed".into()))));
|
||||
opened.device.set_device_lost_callback(|_, _| {});
|
||||
opened.device.destroy();
|
||||
assert_eq!(opened.health.device_status(), Ok(()));
|
||||
|
||||
let result = match operation {
|
||||
0 => {
|
||||
ctx.caps.max_buffer_size = 0;
|
||||
ctx.upload_buffer("oversized", b"abcd").map(|_| ())
|
||||
}
|
||||
1 => ctx.buffer_len(craft_gpu::HandleId(u32::MAX)).map(|_| ()),
|
||||
2 => ctx.request_read(craft_gpu::HandleId(u32::MAX)).map(|_| ()),
|
||||
_ => {
|
||||
let outcomes = ctx.poll_reads();
|
||||
assert_eq!(outcomes.len(), 1);
|
||||
assert_eq!(outcomes[0].request, request);
|
||||
outcomes.into_iter().next().expect("read outcome").result.map(|_| ())
|
||||
}
|
||||
};
|
||||
if operation == 1 {
|
||||
assert_eq!(result, Err(GpuFault::InvalidJob("bad handle".into())));
|
||||
assert!(!opened.health.device_lost());
|
||||
} else {
|
||||
assert!(matches!(result, Err(GpuFault::DeviceLost(_))), "{result:?}");
|
||||
assert!(opened.health.device_lost());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_map_error_revealing_loss_completes_all_pending_reads_once() {
|
||||
let opened = opened();
|
||||
let mut ctx = WgpuContext::from_opened(WorkerKind::Main, &opened);
|
||||
let handle = ctx.upload_buffer("pending", b"abcd").expect("upload");
|
||||
let first = ctx.request_read(handle).expect("first read");
|
||||
let second = ctx.request_read(handle).expect("second read");
|
||||
let third = ctx.request_read(handle).expect("third read");
|
||||
let Backing::Device(d) = &mut ctx.backing else { panic!("a device backing") };
|
||||
for pending in &mut d.pending {
|
||||
pending.state = std::sync::Arc::new(std::sync::Mutex::new(None));
|
||||
}
|
||||
*d.pending[1].state.lock().expect("map state") = Some(Err("mapping failed".into()));
|
||||
opened.device.set_device_lost_callback(|_, _| {});
|
||||
opened.device.destroy();
|
||||
assert_eq!(opened.health.device_status(), Ok(()));
|
||||
|
||||
let outcomes = ctx.poll_reads();
|
||||
assert_eq!(outcomes.len(), 3);
|
||||
let loss = opened.health.device_status().expect_err("device loss");
|
||||
assert!(matches!(loss, GpuFault::DeviceLost(_)));
|
||||
for request in [first, second, third] {
|
||||
let outcome = outcomes.iter().find(|outcome| outcome.request == request).expect("read outcome");
|
||||
assert_eq!(outcome.handle, handle);
|
||||
assert_eq!(outcome.result, Err(loss.clone()));
|
||||
}
|
||||
let Backing::Device(d) = &ctx.backing else { panic!("a device backing") };
|
||||
assert!(d.pending.is_empty());
|
||||
assert!(ctx.poll_reads().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn polling_faults_complete_all_pending_reads_once() {
|
||||
let device = opened();
|
||||
let mut ctx = WgpuContext::from_opened(WorkerKind::Main, &device);
|
||||
let handle = ctx.upload_buffer("pending", b"abcd").expect("upload");
|
||||
let first = ctx.request_read(handle).expect("first read");
|
||||
let second = ctx.request_read(handle).expect("second read");
|
||||
device.health.mark(Fault::Error("Validation Error".into()));
|
||||
let outcomes = ctx.poll_reads();
|
||||
assert_eq!(outcomes.len(), 2);
|
||||
assert!(outcomes.iter().any(|outcome| outcome.request == first));
|
||||
assert!(outcomes.iter().any(|outcome| outcome.request == second));
|
||||
for outcome in outcomes {
|
||||
assert_eq!(outcome.handle, handle);
|
||||
assert_eq!(outcome.result, Err(GpuFault::Operation("Validation Error".into())));
|
||||
}
|
||||
assert!(ctx.poll_reads().is_empty(), "failed requests complete only once");
|
||||
|
||||
let device = opened();
|
||||
let mut ctx = WgpuContext::from_opened(WorkerKind::Main, &device);
|
||||
let handle = ctx.upload_buffer("oom", b"abcd").expect("upload");
|
||||
let request = ctx.request_read(handle).expect("read");
|
||||
device.health.mark(Fault::Error(craft_gpu_device::OUT_OF_MEMORY.into()));
|
||||
let outcomes = ctx.poll_reads();
|
||||
assert!(outcomes.iter().all(|outcome| outcome.request == request && outcome.result.is_ok()));
|
||||
let Backing::Device(backing) = &ctx.backing else { panic!("device backing") };
|
||||
assert_eq!(outcomes.len() + backing.pending.len(), 1, "out of memory does not discard or fail the read");
|
||||
}
|
||||
}
|
||||
+23
-3
@@ -226,6 +226,19 @@ fn prefix_links(n: &[u8]) -> Vec<usize> {
|
||||
links
|
||||
}
|
||||
|
||||
// Each step of `Folded::matches` through the haystack on this thread: one per byte read and one
|
||||
// per failure link followed.
|
||||
#[cfg(test)]
|
||||
std::thread_local! {
|
||||
static SEARCH_STEPS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn count_search_step() {
|
||||
#[cfg(test)]
|
||||
SEARCH_STEPS.with(|steps| steps.set(steps.get().saturating_add(1)));
|
||||
}
|
||||
|
||||
/// Folded text and where each part came from.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Folded {
|
||||
@@ -296,7 +309,9 @@ impl Folded {
|
||||
return Some(0..0);
|
||||
}
|
||||
while let Some(&b) = hay.get(at) {
|
||||
count_search_step();
|
||||
while k > 0 && n[k] != b {
|
||||
count_search_step();
|
||||
k = links[k - 1];
|
||||
}
|
||||
if n[k] == b {
|
||||
@@ -330,10 +345,15 @@ mod tests {
|
||||
let haystack = format!("{}a", "a\u{301}".repeat(100_000));
|
||||
let needle = format!("{}a", "a\u{301}".repeat(50_000));
|
||||
let folded = f.fold(&haystack);
|
||||
let start = std::time::Instant::now();
|
||||
let found = folded.find(&f.fold(&needle));
|
||||
let folded_needle = f.fold(&needle);
|
||||
SEARCH_STEPS.with(|steps| steps.set(0));
|
||||
let found = folded.find(&folded_needle);
|
||||
assert_eq!(found, Some(haystack.len() - needle.len()..haystack.len()));
|
||||
assert!(start.elapsed() < std::time::Duration::from_secs(5), "{:?}", start.elapsed());
|
||||
// One pass reads each haystack byte once and follows at most as many links as it read
|
||||
// bytes; searching again from each turned-down occurrence rereads the needle each time.
|
||||
let steps = SEARCH_STEPS.with(std::cell::Cell::get);
|
||||
let bound = 2 * folded.as_str().len();
|
||||
assert!(steps <= bound, "{steps} search steps for a {}-byte haystack", folded.as_str().len());
|
||||
}
|
||||
#[test]
|
||||
fn source_ranges_round_trip() {
|
||||
|
||||
@@ -79,18 +79,28 @@ pub(super) fn split_extra_samples(
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The smallest piece of a buffer one worker zeroes. Without a floor, rayon splits a byte
|
||||
/// iterator down to single bytes when workers steal from each other, and on a pool with a hundred
|
||||
/// or more workers the nested splits overflow a worker's 2 MiB stack.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const ZERO_PIECE: usize = 1 << 20;
|
||||
|
||||
/// Appends `len` zero bytes to `v` on all cores, in pieces of at least [`ZERO_PIECE`] bytes.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn extend_zeros(v: &mut Vec<u8>, len: usize) {
|
||||
use rayon::prelude::*;
|
||||
v.par_extend(rayon::iter::repeat_n(0u8, len).with_min_len(ZERO_PIECE));
|
||||
}
|
||||
|
||||
/// A zero-filled buffer, allocated fallibly. On native targets the zeroing (and the first
|
||||
/// touch of every page, which dominates on a fresh multi-hundred-megabyte buffer) is spread over
|
||||
/// all cores.
|
||||
pub(super) fn zeroed(len: usize) -> Result<Vec<u8>, CodecError> {
|
||||
let mut v = Vec::new();
|
||||
v.try_reserve_exact(len).map_err(|_| CodecError::LimitExceeded(format!("cannot allocate {len} bytes for the image")))?;
|
||||
// The capacity is already there: this only writes the zeros.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
use rayon::prelude::*;
|
||||
// The capacity is already there: this only writes the zeros.
|
||||
v.par_extend(rayon::iter::repeat_n(0u8, len));
|
||||
}
|
||||
extend_zeros(&mut v, len);
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
v.resize(len, 0);
|
||||
Ok(v)
|
||||
@@ -104,10 +114,7 @@ pub(super) fn refill_zeroed(mut v: Vec<u8>, len: usize) -> Result<Vec<u8>, Codec
|
||||
}
|
||||
v.clear();
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
use rayon::prelude::*;
|
||||
v.par_extend(rayon::iter::repeat_n(0u8, len));
|
||||
}
|
||||
extend_zeros(&mut v, len);
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
v.resize(len, 0);
|
||||
Ok(v)
|
||||
@@ -507,3 +514,21 @@ fn finish_band(lay: &Layout, band: &mut [u8]) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
mod zeroing_tests {
|
||||
use super::{refill_zeroed, zeroed};
|
||||
|
||||
/// Zeroing a large buffer on a pool with many workers and small stacks: the work is split
|
||||
/// into a bounded number of pieces, so no worker's stack fills up with nested splits.
|
||||
#[test]
|
||||
fn zeroing_on_a_wide_pool_with_small_stacks_completes() {
|
||||
let pool = rayon::ThreadPoolBuilder::new().num_threads(256).stack_size(256 << 10).build().unwrap();
|
||||
let v = pool.install(|| zeroed(64 << 20)).unwrap();
|
||||
assert!(v.len() == 64 << 20 && v.iter().all(|&b| b == 0));
|
||||
let mut v = v;
|
||||
v.fill(7);
|
||||
let v = pool.install(|| refill_zeroed(v, 48 << 20)).unwrap();
|
||||
assert!(v.len() == 48 << 20 && v.iter().all(|&b| b == 0));
|
||||
}
|
||||
}
|
||||
@@ -141,8 +141,8 @@ impl EffectSpec {
|
||||
/// field that the drag on the image moves.
|
||||
/// - Pattern Overlay: blend; opacity; pattern Pattern; angle; scale Scale 1..1000 %; link Link
|
||||
/// with Layer. Defaults: Normal, 100, "", 0, 100, true.
|
||||
/// - Bevel & Emboss: style Style (inner Inner Bevel, outer Outer Bevel, emboss Emboss, pillow
|
||||
/// Pillow Emboss); technique Technique (smooth Smooth, chiselHard Chisel Hard, chiselSoft
|
||||
/// - Bevel & Emboss: style Style (outer Outer Bevel, inner Inner Bevel, emboss Emboss, pillow
|
||||
/// Pillow Emboss, stroke Stroke Emboss); technique Technique (smooth Smooth, chiselHard Chisel Hard, chiselSoft
|
||||
/// Chisel Soft); depth Depth 1..1000 %; direction Direction (up Up, down Down); size 0..250
|
||||
/// px; soften Soften 0..16 px; angle; useGlobalLight; altitude Altitude 0..90 °;
|
||||
/// glossContour Gloss Contour (anti-alias `glossAntiAlias`); highlightBlend Highlight Mode;
|
||||
@@ -360,7 +360,13 @@ impl EffectSpec {
|
||||
field(
|
||||
"style",
|
||||
"Style",
|
||||
choice(&[("inner", "Inner Bevel"), ("outer", "Outer Bevel"), ("emboss", "Emboss"), ("pillow", "Pillow Emboss")]),
|
||||
choice(&[
|
||||
("outer", "Outer Bevel"),
|
||||
("inner", "Inner Bevel"),
|
||||
("emboss", "Emboss"),
|
||||
("pillow", "Pillow Emboss"),
|
||||
("stroke", "Stroke Emboss"),
|
||||
]),
|
||||
),
|
||||
field("technique", "Technique", choice(&[("smooth", "Smooth"), ("chiselHard", "Chisel Hard"), ("chiselSoft", "Chisel Soft")])),
|
||||
field("depth", "Depth", slider(1.0, 1000.0, Percent)),
|
||||
|
||||
@@ -90,6 +90,7 @@ craft_ui::words! {
|
||||
outer_bevel: "layerStyle.choiceOuter" = "Outer Bevel";
|
||||
emboss: "layerStyle.choiceEmboss" = "Emboss";
|
||||
pillow_emboss: "layerStyle.choicePillow" = "Pillow Emboss";
|
||||
stroke_emboss: "layerStyle.choiceStrokeEmboss" = "Stroke Emboss";
|
||||
smooth: "layerStyle.choiceSmooth" = "Smooth";
|
||||
chisel_hard: "layerStyle.choiceChiselHard" = "Chisel Hard";
|
||||
chisel_soft: "layerStyle.choiceChiselSoft" = "Chisel Soft";
|
||||
@@ -202,6 +203,7 @@ impl LayerStyleWords {
|
||||
"outer" => &self.outer_bevel,
|
||||
"emboss" => &self.emboss,
|
||||
"pillow" => &self.pillow_emboss,
|
||||
"stroke" => &self.stroke_emboss,
|
||||
"smooth" => &self.smooth,
|
||||
"chiselHard" => &self.chisel_hard,
|
||||
"chiselSoft" => &self.chisel_soft,
|
||||
|
||||
@@ -161,6 +161,25 @@ fn page_rig(kind: EffectKind, params: Option<StyleParams>) -> (Fixture, Rc<RefCe
|
||||
rig_of(host(draft, vec![spec]))
|
||||
}
|
||||
|
||||
/// Bevel & Emboss offers the five styles in the reference application's menu order, and a stored Stroke Emboss shows
|
||||
/// by name rather than as a blank.
|
||||
#[trial]
|
||||
fn bevel_style_offers_stroke_emboss_in_menu_order() {
|
||||
let spec = EffectSpec::photoshop(EffectKind::BevelEmboss);
|
||||
let Some(FieldKind::Choice(choices)) = spec.fields.iter().find(|field| field.key == "style").map(|field| &field.kind) else {
|
||||
panic!("Bevel & Emboss has a Style choice")
|
||||
};
|
||||
let values: Vec<&str> = choices.iter().map(|choice| choice.value.as_ref()).collect();
|
||||
assert_eq!(values, ["outer", "inner", "emboss", "pillow", "stroke"]);
|
||||
assert_eq!(spec.defaults.get("style"), Some(&StyleValue::Text("inner".into())), "Inner Bevel stays the default");
|
||||
|
||||
let mut params = spec.defaults.clone();
|
||||
params.set("style", StyleValue::Text("stroke".into()));
|
||||
let (fixture, _host) = page_rig(EffectKind::BevelEmboss, Some(params));
|
||||
let style = one(&fixture, Role::COMBO_BOX, "Style");
|
||||
assert_eq!(fixture.tree().value_of(style.node), Some("Stroke Emboss"));
|
||||
}
|
||||
|
||||
/// A page shows the spec's defaults for keys the instance lacks without writing them; editing one field writes only
|
||||
/// that key.
|
||||
#[trial]
|
||||
|
||||
@@ -23,6 +23,13 @@ craft-host = { workspace = true }
|
||||
craft-tracked = { workspace = true }
|
||||
craft-ui-macros = { workspace = true }
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
global-hotkey = { version = "0.9", optional = true }
|
||||
|
||||
# The systems where global-hotkey grabs keys through X11.
|
||||
[target.'cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd"))'.dependencies]
|
||||
x11rb = { version = "0.13.1", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
# `serde` for setting `RawInput` fields only the suite's egui fork has.
|
||||
egui = { workspace = true }
|
||||
@@ -32,3 +39,5 @@ tempfile = "3"
|
||||
[features]
|
||||
# The egui key conversions.
|
||||
egui = ["dep:egui", "craft-host/ui"]
|
||||
# System-wide hotkeys (the `global` module); not built for wasm32.
|
||||
global = ["dep:global-hotkey", "dep:x11rb"]
|
||||
+73
-1
@@ -18,7 +18,7 @@ supplies its command catalog, its file-format readers and its UI.
|
||||
`Keymap::with_reserved`, e.g. `reserved::system(platform)` for the operating system's window
|
||||
switching and closing chords. A reserved chord cannot be assigned or bound.
|
||||
- Dependencies: `serde`, `serde_json` and `roxmltree`; `craft-i18n` and `craft-host`; `egui` with the
|
||||
`egui` feature.
|
||||
`egui` feature; `global-hotkey`, and `x11rb` on Linux and the BSDs, with the `global` feature.
|
||||
|
||||
## A catalog and dispatch
|
||||
|
||||
@@ -364,3 +364,75 @@ The Keyboard Shortcuts dialog is `craft_menu::shortcuts`.
|
||||
- `egui`: the egui side. Conversions to and from egui keys and modifiers; `KeyInput::from_egui`;
|
||||
`egui::matches`, which accepts the shifted key egui reports for a Shift binding (`Shift+;`
|
||||
matches `:`).
|
||||
- `global`: `global::GlobalHotkeys`, chords that run a command while another application has the
|
||||
keyboard, such as a record toggle pressed during a full-screen game. It registers them with
|
||||
`RegisterHotKey` on Windows, a Carbon hotkey on macOS and a key grab on the X11 root window
|
||||
on Linux and the BSDs. Not built for wasm32; on other systems (Android, iOS) `new` fails with
|
||||
`GlobalError::Unsupported`.
|
||||
|
||||
```rust,ignore
|
||||
let mut hotkeys = GlobalHotkeys::new()?;
|
||||
hotkeys.set_waker(move || ctx.request_repaint());
|
||||
let refused = hotkeys.replace(bindings); // (CommandRef, Chord) pairs
|
||||
// Once a frame:
|
||||
for event in hotkeys.poll() {
|
||||
app.key(&event.command, event.state); // KeyState::Pressed or KeyState::Released
|
||||
}
|
||||
```
|
||||
|
||||
- One set is open per process at a time (`GlobalError::AlreadyOpen`). Create it on the UI
|
||||
thread: on Windows that thread receives the hotkey messages, and on macOS it must be the main
|
||||
thread.
|
||||
- A chord needs Cmd, Ctrl or Alt unless its key is F1 to F35 (`GlobalError::TypingKey`). Keys
|
||||
typed with Shift (`+`, `:`, `?`) have no key of their own (`GlobalError::Unbindable`). Off
|
||||
macOS, `Cmd+K` and `Ctrl+K` are one hotkey (`GlobalError::Duplicate`). A chord another
|
||||
application holds is `GlobalError::Taken`. Windows registers F1 to F24 and macOS F1 to F20.
|
||||
On X11 the ISO key between left Shift and Z and `\` are one hotkey (`GlobalError::Duplicate`),
|
||||
and `'` cannot be grabbed (`GlobalError::Unbindable`). On Windows a chord with Ctrl and Alt on
|
||||
a letter, digit, symbol or Space key is refused (`GlobalError::AltGr`), since Windows reports AltGr
|
||||
as Ctrl+Alt.
|
||||
- On X11 a symbol chord is grabbed at the key that types the symbol in the current layout. A
|
||||
symbol the layout types only with AltGr is refused (`GlobalError::Unbindable`): with German,
|
||||
`Ctrl+[` would grab Ctrl+8. A symbol typed with Shift is written without Shift, as the keymap
|
||||
matches punctuation: with AZERTY, `Ctrl+.` grabs Ctrl+Shift on the key that types `.`, and
|
||||
`Ctrl+Shift+.` is refused (`GlobalError::Unbindable`). The Latin letters of a second layout
|
||||
group count as that layout's own keys when the key types no letter, digit or symbol in the
|
||||
first group, so with Russian and US `Ctrl+A` grabs the key that types A. With US and French,
|
||||
`Ctrl+A` is refused (`GlobalError::Unbindable`), since the grab would go to the US Q key.
|
||||
Symbols of a second group are refused like AltGr ones.
|
||||
Two chords that land on one key and modifier set are one hotkey (`GlobalError::Duplicate`):
|
||||
with AZERTY, `Ctrl+-` and `Ctrl+6`. So are two chords registered as the same hotkey on
|
||||
different keys: `Ctrl+.` registered with AZERTY, then `Ctrl+Shift+.` after a switch to US.
|
||||
- On X11, when a layout change moves a chord's key, `replace`, `unregister` and `clear`
|
||||
release the key that was grabbed. A grab that no key of the current layout leads to stays
|
||||
until a later change can release it, and its chord is refused meanwhile (`GlobalError::Taken`).
|
||||
When the layout changes while a grab is released, a binding whose grab that release removed
|
||||
is grabbed again, or leaves the set when it cannot be grabbed again.
|
||||
When the keyboard mapping cannot be read, `replace` refuses every binding and keeps the set
|
||||
as it is, except that an empty `replace` still clears the set. The grabs of the chords that
|
||||
leave the set then stay until a later change can release them, and `unregister` returns the
|
||||
error.
|
||||
- On Windows and X11 a letter chord is grabbed at the key that types the letter, as the keymap
|
||||
matches letters on a Latin layout. On macOS it is grabbed at the letter's position on a US
|
||||
keyboard: with AZERTY, `Cmd+A` is the key that types Q.
|
||||
- A held chord gives one `Pressed` and one `Released`. `replace` leaves a binding whose chord
|
||||
and command do not change registered, so a held chord stays held. Unregistering a held chord,
|
||||
or replacing its binding, gives its `Released` at the next `poll`; events the system sent
|
||||
before the change go to the command the chord ran then. On Windows and macOS a press that
|
||||
waits in the app's event queue while the bindings change goes to the new command. On Windows
|
||||
the release of a chord unregistered while held is dropped when it arrives, so it does not end
|
||||
a later hold of the same chord.
|
||||
- At most 256 system events wait between polls (`MAX_QUEUED`); beyond that the oldest are
|
||||
dropped, and after such a loss every chord that was down is released. When more than 256
|
||||
events wait for `poll`, the oldest press whose release also waits is dropped with that
|
||||
release, so every press the app gets has its release. Past 512 waiting events
|
||||
(`MAX_PENDING`) the oldest press is dropped; a release is never dropped. At most 128 chords
|
||||
are registered (`MAX_GLOBAL`).
|
||||
- On X11 each `register` and `unregister` waits for the key-grab thread, which takes one
|
||||
request every 50 ms. `replace` sends the chords it removes in one request and those it adds
|
||||
in another, and adds them one at a time when the system refuses one of them; `clear` sends
|
||||
one request. `new` fails with
|
||||
`GlobalError::Os` when that thread has stopped (a display without the XKEYBOARD extension).
|
||||
- A Wayland session is refused with `GlobalError::Wayland`, since an X11 grab there sees only
|
||||
keys typed into X11 windows. Without an X11 display, `new` fails with
|
||||
`GlobalError::NoDisplay`.
|
||||
File diff suppressed because it is too large.
Load diff
@@ -13,7 +13,9 @@
|
||||
//! user's keyboard layout, for matching, recording and labels. [`editor`] is the model of a
|
||||
//! shortcut editor: undo, a chord recorder, conflict queries and search. With the `egui` feature,
|
||||
//! the `egui` module
|
||||
//! converts to and from egui keys and matches key presses against bindings.
|
||||
//! converts to and from egui keys and matches key presses against bindings. With the `global`
|
||||
//! feature, the `global` module registers chords with the operating system so that they run
|
||||
//! commands while another application has the keyboard.
|
||||
//!
|
||||
//! ```
|
||||
//! use craft_keymap::{Chord, Platform};
|
||||
@@ -143,6 +145,8 @@ mod commands;
|
||||
pub mod editor;
|
||||
#[cfg(feature = "egui")]
|
||||
pub mod egui;
|
||||
#[cfg(all(feature = "global", not(target_arch = "wasm32")))]
|
||||
pub mod global;
|
||||
pub mod import;
|
||||
pub mod keymap;
|
||||
pub mod layout;
|
||||
|
||||
@@ -208,6 +208,15 @@ Hide Others, Show All and Quit, where Quit asks the app first.
|
||||
craft_menu::mac::install_app_menu(&cc.egui_ctx, "WordCraft")?;
|
||||
```
|
||||
|
||||
Its labels are English. `mac::install_app_menu_with` takes a `LayoutOptions` instead, and its
|
||||
`label` translates `About {app}`, `Services`, `Hide {app}`, `Hide Others`, `Show All` and
|
||||
`Quit {app}`, the keys `mac_layout` uses for the same items.
|
||||
|
||||
```rust
|
||||
#[cfg(target_os = "macos")]
|
||||
craft_menu::mac::install_app_menu_with(&cc.egui_ctx, &LayoutOptions::new("WordCraft").label(&translate))?;
|
||||
```
|
||||
|
||||
craft-menu owns the process's menu event handler (muda keeps the first one set, in craft-window), so the
|
||||
crate sets it once and both `mac::install` and `mac::install_app_menu` use it; a later
|
||||
`mac::install` replaces the minimal app menu, and a second `mac::install` returns `None`.
|
||||
|
||||
@@ -99,7 +99,7 @@ impl<'a> LayoutOptions<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
fn text(&self, english: &'static str) -> String {
|
||||
pub(crate) fn text(&self, english: &'static str) -> String {
|
||||
(self.label)(english).replace("{app}", self.app_name)
|
||||
}
|
||||
|
||||
|
||||
@@ -64,7 +64,8 @@
|
||||
//! [`LanguageMenu`] does for languages.
|
||||
//!
|
||||
//! The labels the layout writes itself are English unless the app passes its translations in
|
||||
//! [`LayoutOptions::label`].
|
||||
//! [`LayoutOptions::label`]. `mac::install_app_menu_with` takes the same translations for the
|
||||
//! minimal app menu.
|
||||
//!
|
||||
//! **Keys stay with egui.** AppKit runs a menu's key equivalents before the window sees the key,
|
||||
//! which would skip the app's own key rules (a focused text field keeps ⌘C, ⌘V and ⌘Z, dialogs
|
||||
|
||||
+27
-2
@@ -39,6 +39,7 @@ use craft_ui::menu::Alternate;
|
||||
use craft_ui::runtime::{frame, motion};
|
||||
use craft_window::native_menu as native;
|
||||
|
||||
use crate::LayoutOptions;
|
||||
use crate::driver::{Attempt, Backend, Dispatch, Event, NativeMenu, RebuildRetry, native_ok};
|
||||
use crate::model::{Builtin, Item, ItemKind, Menu, MenuBar, MenuRole, Node, Standard, label_or_system, native_id, structure_key, window_key};
|
||||
|
||||
@@ -95,7 +96,8 @@ pub fn install_with(ctx: &egui::Context, bar: &MenuBar, options: MacOptions) ->
|
||||
|
||||
/// Replace winit's default macOS app menu with a minimal one whose Quit (⌘Q) asks the app first,
|
||||
/// for an app without a [`MenuBar`] of its own: About, Services, Hide, Hide Others, Show All and
|
||||
/// Quit, labelled in English with `app_name` ("Quit WordCraft").
|
||||
/// Quit, labeled in English with `app_name` ("Quit WordCraft"). [`install_app_menu_with`] takes
|
||||
/// the app's translations.
|
||||
///
|
||||
/// winit's Quit ends the process without asking, so unsaved work is lost. This Quit has the id
|
||||
/// [`craft_quit::QUIT_MENU_ID`] and runs [`craft_quit::on_menu_event`]: it asks the root window to
|
||||
@@ -106,13 +108,36 @@ pub fn install_with(ctx: &egui::Context, bar: &MenuBar, options: MacOptions) ->
|
||||
/// platforms without an application menu bar. On error winit's menu stays: the app still runs, but
|
||||
/// ⌘Q quits without asking.
|
||||
pub fn install_app_menu(ctx: &egui::Context, app_name: &str) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
install_app_menu_with(ctx, &LayoutOptions::new(app_name))
|
||||
}
|
||||
|
||||
/// [`install_app_menu`] with the app's translations: the titles [`app_menu`] gives.
|
||||
pub fn install_app_menu_with(ctx: &egui::Context, options: &LayoutOptions) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
let ctx = ctx.clone();
|
||||
let handler = Arc::new(move |id: &str, _: native::Chosen| {
|
||||
craft_quit::on_menu_event(&ctx, id);
|
||||
// Choosing an item is not window input, so nothing else wakes egui.
|
||||
ctx.request_repaint();
|
||||
});
|
||||
native::install_app_menu(app_name, craft_quit::QUIT_MENU_ID, handler)
|
||||
native::install_app_menu_with(&app_menu(options), craft_quit::QUIT_MENU_ID, handler)
|
||||
}
|
||||
|
||||
/// The titles of the minimal app menu ([`install_app_menu_with`]). [`LayoutOptions::label`] names
|
||||
/// the items through the keys [`crate::mac_layout`] uses for its app menu: `About {app}`,
|
||||
/// `Services`, `Hide {app}`, `Hide Others`, `Show All` and `Quit {app}`, with `{app}` replaced by
|
||||
/// [`LayoutOptions::app_name`], which also titles the menu. Services, Hide Others and Show All take
|
||||
/// the system's localized titles when the app supplies no translation, as in [`crate::mac_layout`].
|
||||
/// [`LayoutOptions::keys`] is not used.
|
||||
pub fn app_menu(options: &LayoutOptions) -> native::AppMenu {
|
||||
let mut menu = native::AppMenu::english(options.app_name);
|
||||
let system = |english: &'static str| label_or_system(&options.text(english), english, native::system_title);
|
||||
menu.about = options.text("About {app}");
|
||||
menu.services = system(Standard::Services.english());
|
||||
menu.hide = options.text("Hide {app}");
|
||||
menu.hide_others = system("Hide Others");
|
||||
menu.show_all = system(Standard::ShowAll.english());
|
||||
menu.quit = options.text("Quit {app}");
|
||||
menu
|
||||
}
|
||||
|
||||
/// What each native item runs, by native id, for the handler.
|
||||
|
||||
@@ -4,19 +4,21 @@
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft_behavior::ColumnWidth;
|
||||
use craft_behavior::nav::NavShape;
|
||||
use craft_behavior::{Metrics, PartKey, Roving, Sense};
|
||||
use craft_keymap::{Binding, Chord, CommandRef, Holder, Key, Keymap, Mods, Overrides, Platform, Scope, Trigger};
|
||||
use craft_theme::variant::Tone;
|
||||
use craft_theme::Variant;
|
||||
use craft_theme::variant::{Emphasis, Tone};
|
||||
use craft_ui::buttons::{Button, ToggleButton};
|
||||
use craft_ui::contract::{
|
||||
Access, Bind, BodyCx, Component, Cx, Input, MeasureCx, Name, NoValue, Outcome, PaintUi, PartsCx, Pointer as _, Props as _, Role, Show as _,
|
||||
ShowContainer as _, clicked,
|
||||
ShowContainer as _, Sizing, clicked,
|
||||
};
|
||||
use craft_ui::display::Text;
|
||||
use craft_ui::layout_components::{Row, Stack};
|
||||
use craft_ui::display::{Badge, Text};
|
||||
use craft_ui::layout_components::{Grid, Row, Stack};
|
||||
use craft_ui::primitives::{PaintShape, StrokeWidth, TextRun, Wrap};
|
||||
use craft_ui::style::{ComponentStyle, FocusLook, StyleColor, StyleCx, TextLook, TypeRole};
|
||||
use craft_ui::style::{ComponentStyle, FocusLook, StyleColor, StyleCx, SurfaceKind, TextLook, TypeRole};
|
||||
use egui::{CornerRadius, Rect, Response, Ui, Vec2, vec2};
|
||||
|
||||
use super::state::{DialogState, Env};
|
||||
@@ -31,6 +33,11 @@ const ROW_GAP: f32 = 0.25;
|
||||
/// Where the navigation cluster starts, in key units.
|
||||
const NAV_AT: f32 = 15.5;
|
||||
|
||||
/// The share of the pane's width the keys take beside the clicked key's shortcuts, and the share those take.
|
||||
const CAPS_SHARE: f32 = 0.7;
|
||||
const LIST_SHARE: f32 = 0.3;
|
||||
const COLUMNS: [ColumnWidth; 2] = [ColumnWidth::fill(CAPS_SHARE), ColumnWidth::fill(LIST_SHARE)];
|
||||
|
||||
const KEY: PartKey = PartKey::new("key");
|
||||
const MODIFIER: PartKey = PartKey::new("modifier");
|
||||
|
||||
@@ -328,6 +335,8 @@ pub(crate) struct PaneStyle {
|
||||
/// Cap fills by class, and the ink that reads on each: free, application, panel or context, both.
|
||||
fills: [StyleColor; 4],
|
||||
inks: [StyleColor; 4],
|
||||
/// The thin edge of every cap, so a cap whose fill is the dialog's own still reads as a key.
|
||||
edge: StyleColor,
|
||||
/// A modifier cap that is on.
|
||||
on_fill: StyleColor,
|
||||
on_ink: StyleColor,
|
||||
@@ -379,22 +388,36 @@ impl Component for KeyCaps {
|
||||
|
||||
fn style(cx: &StyleCx<'_>, _: Self::StyleKey) -> PaneStyle {
|
||||
let classes = [Class::Free, Class::App, Class::Scoped, Class::Both];
|
||||
// The solid look of a tone: its fill and the ink that reads on it.
|
||||
let solid = |tone: Tone| {
|
||||
let look = cx.with_variant(Variant::look(Emphasis::Solid, tone)).variant_look();
|
||||
(look.fill.off.rest, look.text.off.rest)
|
||||
};
|
||||
PaneStyle {
|
||||
metrics: Metrics::new(),
|
||||
focus: cx.focus_look(),
|
||||
text: TextLook::new(TypeRole::Caption, craft_theme::Stateful::new(cx.ink(craft_ui::style::Ink::OnPanel))),
|
||||
step: cx.control().height,
|
||||
radius: cx.surface(craft_ui::style::SurfaceKind::Raised).radius,
|
||||
fills: classes.map(|c| cx.tone_fill(c.tone())),
|
||||
inks: classes.map(|c| if c == Class::Free { cx.ink(craft_ui::style::Ink::OnPanel) } else { cx.tone(c.tone()) }),
|
||||
on_fill: cx.tone_fill(Tone::Info),
|
||||
on_ink: cx.tone(Tone::Info),
|
||||
// A free key is a raised cap (the neutral tone's soft fill is the sunken surface, which a dialog may share); a
|
||||
// held key is the solid fill of its tone, so the classes read at a glance.
|
||||
fills: classes.map(|c| if c == Class::Free { StyleColor(cx.surface(SurfaceKind::Raised).fill) } else { solid(c.tone()).0 }),
|
||||
inks: classes.map(|c| if c == Class::Free { cx.ink(craft_ui::style::Ink::OnPanel) } else { solid(c.tone()).1 }),
|
||||
edge: cx.color(cx.tokens.color.line.border),
|
||||
on_fill: solid(Tone::Info).0,
|
||||
on_ink: solid(Tone::Info).1,
|
||||
}
|
||||
}
|
||||
|
||||
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
|
||||
// The caps keep their proportions: 18.5 units go across the pane and 6.25 down it, so the pane is as tall as
|
||||
// the width it is given makes the keys, and a wider pane draws bigger keys rather than the same keys one
|
||||
// control high. Measured at its least, the pane is 18.5 controls wide, so a key is one control; a pane given
|
||||
// less room than that takes the room it is given (down to the plot's least height), so its keys can come out
|
||||
// smaller than a control. A pane measured in a column that offers it no room still learns the height it shows
|
||||
// at, as `picture_size` has the column sweep again with the width the pane settles on.
|
||||
let step = cx.style.step;
|
||||
vec2(UNITS_W * step, UNITS_H * step)
|
||||
cx.picture_size(UNITS_W * step, 2.0 * UNITS_W * step, |width| width / UNITS_W * UNITS_H)
|
||||
}
|
||||
|
||||
fn sense(&self) -> Sense {
|
||||
@@ -448,13 +471,16 @@ impl Component for KeyCaps {
|
||||
};
|
||||
let shape = PaintShape::Rect(cell, style.radius);
|
||||
draw.fill(&shape, fill);
|
||||
draw.stroke(&shape, StrokeWidth::Thin, style.edge);
|
||||
if Self::interactive(view) && cx.part(Self::part(at, view)).hovered {
|
||||
draw.stroke(&shape, StrokeWidth::Medium, ink);
|
||||
}
|
||||
if view.marked && matches!(view.cap, Cap::Key(_)) {
|
||||
draw.stroke(&shape, StrokeWidth::Thick, ink);
|
||||
}
|
||||
let (top, bottom) = cell.split_top_bottom_at_fraction(0.5);
|
||||
// The names stand off the cap's edges, so a long one is cut before it touches the next key.
|
||||
let pad = (unit * 0.1).clamp(2.0, 4.0);
|
||||
let (top, bottom) = cell.shrink2(vec2(pad, pad * 0.5)).split_top_bottom_at_fraction(0.5);
|
||||
if let Some(title) = &view.title {
|
||||
draw.text(top, &TextRun::new(title.as_str()).role(style.text.role).color(ink).wrap(Wrap::Elide));
|
||||
}
|
||||
@@ -621,7 +647,7 @@ pub(crate) fn show(ui: &mut Ui, _cx: &mut BodyCx<'_>, env: &mut Env<'_>, state:
|
||||
let mut assign = false;
|
||||
let mods = state.keyboard.mods;
|
||||
let index = state.keyboard.index(env.keymap);
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
Stack::new().fill_width().show(ui, |ui, _| {
|
||||
Row::new().show(ui, |ui, _| {
|
||||
let layout = if mac { &words.keyboard_us_macos } else { &words.keyboard_us };
|
||||
Text::new(layout.clone()).show(ui);
|
||||
@@ -632,26 +658,30 @@ pub(crate) fn show(ui: &mut Ui, _cx: &mut BodyCx<'_>, env: &mut Env<'_>, state:
|
||||
toggled = Some(m);
|
||||
}
|
||||
}
|
||||
// The legend: each word on the solid fill its keys take.
|
||||
for (tone, word) in [
|
||||
(Tone::Accent, &words.application),
|
||||
(Tone::Warn, &words.panel_or_context),
|
||||
(Tone::Bad, &words.both),
|
||||
(Tone::Info, &words.modifier_on),
|
||||
] {
|
||||
Text::new(word.clone()).tone(tone).show(ui);
|
||||
Badge::new(word.clone()).variant(Variant::look(Emphasis::Solid, tone)).id_salt(("shortcuts.legend", word.as_str())).show(ui);
|
||||
}
|
||||
});
|
||||
Row::new().show(ui, |ui, _| {
|
||||
let caps = KeyCaps {
|
||||
common: craft_ui::contract::Common::new(),
|
||||
caps: cap_views(env, &state.keyboard, &index.1, mods),
|
||||
key: None,
|
||||
toggled: None,
|
||||
};
|
||||
let pane = caps.id_salt("shortcuts.keyboardCaps").show(ui);
|
||||
picked_key = pane.key;
|
||||
toggled = toggled.or(pane.toggled);
|
||||
Stack::new().show(ui, |ui, _| key_list(ui, env, state, &index.1, mods, &mut go, &mut assign));
|
||||
// The keys take most of the width; the clicked key's shortcuts the rest, under the keys' own height.
|
||||
Grid::new(&COLUMNS).fill_width().show(ui, |ui, _| {
|
||||
Stack::new().fill_width().show(ui, |ui, _| {
|
||||
let caps = KeyCaps {
|
||||
common: craft_ui::contract::Common::new(),
|
||||
caps: cap_views(env, &state.keyboard, &index.1, mods),
|
||||
key: None,
|
||||
toggled: None,
|
||||
};
|
||||
let pane = caps.id_salt("shortcuts.keyboardCaps").sizing(Sizing::FillWidth).show(ui);
|
||||
picked_key = pane.key;
|
||||
toggled = toggled.or(pane.toggled);
|
||||
});
|
||||
Stack::new().fill_width().show(ui, |ui, _| key_list(ui, env, state, &index.1, mods, &mut go, &mut assign));
|
||||
});
|
||||
});
|
||||
if let Some(m) = toggled {
|
||||
@@ -680,7 +710,7 @@ fn key_list(ui: &mut Ui, env: &Env<'_>, state: &DialogState, index: &Index, mods
|
||||
let words = say.words();
|
||||
let platform = env.keymap.platform();
|
||||
let Some(key) = state.keyboard.key else {
|
||||
Text::new(words.click_a_key_to_see_its.clone()).shade(craft_ui::display::Shade::Muted).show(ui);
|
||||
Text::new(words.click_a_key_to_see_its.clone()).shade(craft_ui::display::Shade::Muted).sizing(Sizing::FillWidth).show(ui);
|
||||
return;
|
||||
};
|
||||
Text::new(words.key_key.fill(&[("key", say.key_word(key, platform).as_str())])).show(ui);
|
||||
|
||||
@@ -73,8 +73,10 @@
|
||||
//!
|
||||
//! [`Options`] sets the conflict mode, double-press recording, area tabs, the on-screen keyboard,
|
||||
//! read-only rows for keys outside the catalog, the app's import and export formats, an `accept`
|
||||
//! rule for which keys a command may get, and a `visible` rule for which catalog entries the table
|
||||
//! lists (hidden entries keep their keys and still count in conflicts).
|
||||
//! rule for which keys a command may get, a `visible` rule for which catalog entries the table
|
||||
//! lists (hidden entries keep their keys and still count in conflicts), and whether the footer
|
||||
//! offers Undo and Redo over the dialog's history or one button that steps the last change
|
||||
//! ([`UndoButtons`]).
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::collections::BTreeMap;
|
||||
@@ -199,6 +201,19 @@ pub enum ConflictMode {
|
||||
Keep,
|
||||
}
|
||||
|
||||
/// How the footer offers undo in [`Layout::Table`].
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum UndoButtons {
|
||||
/// Undo and Redo, side by side, over the whole history of the dialog's edits.
|
||||
#[default]
|
||||
History,
|
||||
/// One button that steps the last change only: Undo reverts it and the button becomes Redo, which applies it
|
||||
/// again and turns back into Undo. Starting to record a shortcut disables it until the next change. The undo
|
||||
/// and redo keys step the same change.
|
||||
Toggle,
|
||||
}
|
||||
|
||||
/// An app's own Show entry.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
#[non_exhaustive]
|
||||
@@ -335,6 +350,8 @@ pub struct Options {
|
||||
/// [`Layout::Table`]: how the body is arranged. The keymap, the `accept` rule, the conflict mode
|
||||
/// and undo are the same in every layout.
|
||||
pub layout: Layout,
|
||||
/// [`UndoButtons::History`]: how the footer offers undo.
|
||||
pub undo: UndoButtons,
|
||||
}
|
||||
|
||||
impl Default for Options {
|
||||
@@ -361,6 +378,7 @@ impl Default for Options {
|
||||
summary: true,
|
||||
accept: None,
|
||||
layout: Layout::Table,
|
||||
undo: UndoButtons::History,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -451,7 +469,9 @@ impl<'a> ShortcutsDialog<'a> {
|
||||
/// hold shortcuts in the Hold column. In [`ConflictMode::Ask`], a conflict leaves the old binding in place
|
||||
/// until the user confirms. Hosts can use [`ConflictMode::Steal`] or [`ConflictMode::Keep`] for immediate
|
||||
/// handling. Replacing a shortcut with an equivalent trigger leaves it alone. A replacement that changes
|
||||
/// the shortcut can be undone in one step. `Err` says why the field was refused.
|
||||
/// the shortcut can be undone in one step. `pressed`, `assign`, `remove` and `replace` are refused when the
|
||||
/// user could not edit a shortcut: in a read-only dialog, while a prompt, review or recording is open, or on an
|
||||
/// app tab. `Err` says why the field was refused.
|
||||
pub fn set_json_field(self, ui: &Ui, state: &mut DialogState, field: &str, value: &serde_json::Value) -> Result<(), String> {
|
||||
use craft_ui::dialog::FieldRefusal;
|
||||
let rejects = || FieldRefusal::Rejects(value).message(field);
|
||||
@@ -470,13 +490,16 @@ impl<'a> ShortcutsDialog<'a> {
|
||||
state.select_row(&command.ok_or_else(rejects)?);
|
||||
}
|
||||
"pressed" => {
|
||||
if !state.can_edit(env) {
|
||||
return Err(inactive());
|
||||
}
|
||||
let trigger = Trigger::parse(value.as_str().ok_or_else(rejects)?).map_err(|_| rejects())?;
|
||||
let command = state.selected.clone().ok_or_else(inactive)?;
|
||||
state.set_field(env, command, trigger);
|
||||
}
|
||||
"assign" => match value {
|
||||
serde_json::Value::Bool(true) => {
|
||||
if state.field.is_none() {
|
||||
if !state.can_edit(env) || state.field.is_none() {
|
||||
return Err(inactive());
|
||||
}
|
||||
state.assign_field(env);
|
||||
@@ -486,6 +509,9 @@ impl<'a> ShortcutsDialog<'a> {
|
||||
_ => return Err(rejects()),
|
||||
},
|
||||
"remove" => {
|
||||
if !state.can_edit(env) {
|
||||
return Err(inactive());
|
||||
}
|
||||
let wanted = Binding::parse(value.as_str().ok_or_else(rejects)?).map_err(|_| rejects())?;
|
||||
let command = state.selected.clone().ok_or_else(inactive)?;
|
||||
if !env.keymap.bindings(&command).contains(&wanted) {
|
||||
@@ -495,7 +521,7 @@ impl<'a> ShortcutsDialog<'a> {
|
||||
state.edit_result()?;
|
||||
}
|
||||
"replace" => {
|
||||
if !env.options.editable || !state.is_showing() || state.modal() || state.is_recording() || env.has_app_tab(state.tab) {
|
||||
if !state.can_edit(env) {
|
||||
return Err(inactive());
|
||||
}
|
||||
let command = state.selected.clone().ok_or_else(inactive)?;
|
||||
@@ -598,6 +624,11 @@ const READ_ONLY_HEIGHT: f32 = 480.0;
|
||||
enum Act {
|
||||
Undo,
|
||||
Redo,
|
||||
/// [`UndoButtons::Toggle`]'s one button, reading Redo when `redoes`, else Undo. A footer label is fixed for its
|
||||
/// pass, so the button acts only while the last change still steps the way it reads.
|
||||
Toggle {
|
||||
redoes: bool,
|
||||
},
|
||||
ResetAll,
|
||||
Summarize,
|
||||
Ok,
|
||||
@@ -607,7 +638,7 @@ enum Act {
|
||||
}
|
||||
|
||||
/// The footer's buttons and what each one does. Their enabled state is set after the body has run.
|
||||
fn footer(env: &Env<'_>) -> (Vec<FooterButton>, Vec<Act>) {
|
||||
fn footer(env: &Env<'_>, state: &DialogState) -> (Vec<FooterButton>, Vec<Act>) {
|
||||
let mut buttons = Vec::new();
|
||||
let mut acts = Vec::new();
|
||||
let mut add = |act: Act, label: String, role: DialogRole, stays_open: bool| {
|
||||
@@ -623,8 +654,14 @@ fn footer(env: &Env<'_>) -> (Vec<FooterButton>, Vec<Act>) {
|
||||
return (buttons, acts);
|
||||
}
|
||||
if editable {
|
||||
add(Act::Undo, word!(env, undo), DialogRole::Other, true);
|
||||
add(Act::Redo, word!(env, redo), DialogRole::Other, true);
|
||||
match env.options.undo {
|
||||
UndoButtons::Toggle if state.toggle_redoes() => add(Act::Toggle { redoes: true }, word!(env, redo), DialogRole::Other, true),
|
||||
UndoButtons::Toggle => add(Act::Toggle { redoes: false }, word!(env, undo), DialogRole::Other, true),
|
||||
UndoButtons::History => {
|
||||
add(Act::Undo, word!(env, undo), DialogRole::Other, true);
|
||||
add(Act::Redo, word!(env, redo), DialogRole::Other, true);
|
||||
}
|
||||
}
|
||||
add(Act::ResetAll, word!(env, reset_all_more), DialogRole::Other, true);
|
||||
}
|
||||
// With sets, Summarize… is in the set row, which a read-only dialog does not show.
|
||||
@@ -652,7 +689,7 @@ fn frame(ui: &mut Ui, env: &mut Env<'_>, state: &mut DialogState) -> ShortcutsOu
|
||||
if !state.is_showing() {
|
||||
return ShortcutsOutput { response: ui.response(), outcome: state.finish() };
|
||||
}
|
||||
let (buttons, acts) = footer(env);
|
||||
let (buttons, acts) = footer(env, state);
|
||||
let enter = env.options.enter_is_ok && !state.modal() && !state.is_recording();
|
||||
let title = env.title();
|
||||
let mut open = true;
|
||||
@@ -681,6 +718,7 @@ fn frame(ui: &mut Ui, env: &mut Env<'_>, state: &mut DialogState) -> ShortcutsOu
|
||||
button.set_enabled(match act {
|
||||
Act::Undo => idle && state.can_undo(),
|
||||
Act::Redo => idle && state.can_redo(),
|
||||
Act::Toggle { redoes } => idle && state.can_toggle() && state.toggle_redoes() == *redoes,
|
||||
Act::ResetAll => idle && !env.keymap.overrides().is_empty(),
|
||||
Act::Ok | Act::Close => idle,
|
||||
Act::Cancel => idle,
|
||||
@@ -696,13 +734,26 @@ fn frame(ui: &mut Ui, env: &mut Env<'_>, state: &mut DialogState) -> ShortcutsOu
|
||||
.show(ui, |ui, cx| {
|
||||
let mut guard = session.borrow_mut();
|
||||
let Session { env, state } = &mut *guard;
|
||||
while let Some(step) = cx.take_step(!state.modal() && state.can_undo(), !state.modal() && state.can_redo()) {
|
||||
let redoes = state.toggle_redoes();
|
||||
loop {
|
||||
// Each step can change what the next may do: in Toggle mode an undo turns the next step into a redo.
|
||||
let (undo, redo) = match env.options.undo {
|
||||
UndoButtons::Toggle => (state.can_toggle() && !state.toggle_redoes(), state.can_toggle() && state.toggle_redoes()),
|
||||
UndoButtons::History => (state.can_undo(), state.can_redo()),
|
||||
};
|
||||
let (undo, redo) = (!state.modal() && undo, !state.modal() && redo);
|
||||
let Some(step) = cx.take_step(undo, redo) else { break };
|
||||
// A step queued before the last one ran is still handed over: drop it when it is no longer allowed.
|
||||
match step {
|
||||
Step::Undo => state.undo(env),
|
||||
Step::Redo => state.redo(env),
|
||||
Step::Undo if undo => state.undo(env),
|
||||
Step::Redo if redo => state.redo(env),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
// The toggling button's label was fixed before the keys flipped it: show the new one on the next pass.
|
||||
if state.toggle_redoes() != redoes {
|
||||
cx.wake_at(cx.now());
|
||||
}
|
||||
view::body(ui, cx, env, state);
|
||||
if state.change_pending() {
|
||||
cx.wake_at(cx.now());
|
||||
@@ -713,6 +764,8 @@ fn frame(ui: &mut Ui, env: &mut Env<'_>, state: &mut DialogState) -> ShortcutsOu
|
||||
match picked.and_then(|at| acts.get(at)) {
|
||||
Some(Act::Undo) => state.undo(env),
|
||||
Some(Act::Redo) => state.redo(env),
|
||||
Some(Act::Toggle { redoes }) if state.toggle_redoes() == *redoes => state.toggle(env),
|
||||
Some(Act::Toggle { .. }) => {}
|
||||
Some(Act::ResetAll) => state.ask_reset_all(),
|
||||
Some(Act::Summarize) => state.summarize(env),
|
||||
Some(Act::Ok | Act::Close) => state.ok(env),
|
||||
|
||||
@@ -129,7 +129,7 @@ fn publish(cx: &mut BodyCx<'_>, env: &Env<'_>, idle: bool, builtin: bool, modifi
|
||||
|
||||
/// The strip's items. An app that writes other formats gets its own Export menu in place of the Export item.
|
||||
fn items(env: &Env<'_>, formats: bool) -> Vec<BarItem> {
|
||||
let item = |command: SetCommand| BarItem::new(command).display(ItemDisplay::Text);
|
||||
let item = |command: SetCommand| BarItem::new(command).display(ItemDisplay::Button);
|
||||
let mut items = vec![item(SetCommand::New), item(SetCommand::Rename), item(SetCommand::Delete), item(SetCommand::Save), item(SetCommand::Revert)];
|
||||
if !formats {
|
||||
items.push(item(SetCommand::Export));
|
||||
|
||||
@@ -277,6 +277,13 @@ struct Opened {
|
||||
holds: Option<HoldSetting>,
|
||||
}
|
||||
|
||||
/// Which way [`UndoButtons::Toggle`](super::UndoButtons::Toggle)'s button steps the last change.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Toggle {
|
||||
Undo,
|
||||
Redo,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Phase {
|
||||
New,
|
||||
@@ -311,6 +318,9 @@ pub struct DialogState {
|
||||
rows: RowCache,
|
||||
changed: bool,
|
||||
outcome: Option<Outcome>,
|
||||
/// [`UndoButtons::Toggle`](super::UndoButtons::Toggle): which way its button steps the last change, `None` while
|
||||
/// there is no change it may step.
|
||||
last_change: Option<Toggle>,
|
||||
// ---- The view's own state ----
|
||||
/// The chip of the selected row that Enter and Delete act on.
|
||||
pub(crate) chip: usize,
|
||||
@@ -363,6 +373,7 @@ impl DialogState {
|
||||
rows: RowCache::default(),
|
||||
changed: false,
|
||||
outcome: None,
|
||||
last_change: None,
|
||||
chip: 0,
|
||||
keys_pick: None,
|
||||
typing: None,
|
||||
@@ -567,6 +578,8 @@ impl DialogState {
|
||||
self.message = None;
|
||||
self.recorder.reset();
|
||||
if let Some(command) = target.command() {
|
||||
// A new edit begins: the toggling undo button no longer reaches the change before it.
|
||||
self.last_change = None;
|
||||
self.select_row(command);
|
||||
}
|
||||
self.recording = Some(Recording { target, waiting: None, started: false });
|
||||
@@ -925,6 +938,7 @@ impl DialogState {
|
||||
/// After any edit: drop the conflict bar, refresh the field's holders, report Changed.
|
||||
fn edited(&mut self, env: &Env) {
|
||||
self.changed = true;
|
||||
self.last_change = Some(Toggle::Undo);
|
||||
// The picked row is a position among the command's keys, which the edit may have moved.
|
||||
self.keys_pick = None;
|
||||
self.conflict = None;
|
||||
@@ -993,11 +1007,38 @@ impl DialogState {
|
||||
}
|
||||
|
||||
pub(crate) fn undo(&mut self, env: &mut Env) {
|
||||
self.edit(env, |s, km| s.undo(km));
|
||||
if self.edit(env, |s, km| s.undo(km)) {
|
||||
self.last_change = Some(Toggle::Redo);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn redo(&mut self, env: &mut Env) {
|
||||
self.edit(env, |s, km| s.redo(km));
|
||||
if self.edit(env, |s, km| s.redo(km)) {
|
||||
self.last_change = Some(Toggle::Undo);
|
||||
}
|
||||
}
|
||||
|
||||
/// [`UndoButtons::Toggle`](super::UndoButtons::Toggle)'s button: undoes the last change, or redoes it after that.
|
||||
pub(crate) fn toggle(&mut self, env: &mut Env) {
|
||||
match self.last_change {
|
||||
Some(Toggle::Undo) => self.undo(env),
|
||||
Some(Toggle::Redo) => self.redo(env),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the toggling button has a change to step.
|
||||
pub(crate) fn can_toggle(&self) -> bool {
|
||||
match self.last_change {
|
||||
Some(Toggle::Undo) => self.can_undo(),
|
||||
Some(Toggle::Redo) => self.can_redo(),
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the toggling button reads Redo: its last step undid the change.
|
||||
pub(crate) fn toggle_redoes(&self) -> bool {
|
||||
self.last_change == Some(Toggle::Redo)
|
||||
}
|
||||
|
||||
pub(crate) fn can_undo(&self) -> bool {
|
||||
@@ -1153,6 +1194,7 @@ impl DialogState {
|
||||
env.keymap.set_overrides(p.active_overrides(b).clone());
|
||||
}
|
||||
self.session = Some(EditSession::begin(env.keymap));
|
||||
self.last_change = None;
|
||||
self.recording = None;
|
||||
self.conflict = None;
|
||||
self.field = None;
|
||||
@@ -1165,6 +1207,12 @@ impl DialogState {
|
||||
self.prompt.is_some() || self.review.is_some()
|
||||
}
|
||||
|
||||
/// Whether the user could edit a shortcut now: the dialog is editable and shown, no prompt, review or
|
||||
/// recording is open, and the shortcuts page is on screen rather than an app tab.
|
||||
pub(crate) fn can_edit(&self, env: &Env) -> bool {
|
||||
env.options.editable && self.is_showing() && !self.modal() && !self.is_recording() && !env.has_app_tab(self.tab)
|
||||
}
|
||||
|
||||
fn report(&mut self, env: &Env, result: Result<(), ProfileError>) {
|
||||
match result {
|
||||
Ok(()) => self.message = None,
|
||||
|
||||
@@ -428,7 +428,10 @@ impl Component for CommandRow<'_> {
|
||||
Line::Row(line) => {
|
||||
let mut cell = self.measure_chips(cx, line, false);
|
||||
if line.chips.is_empty() {
|
||||
cell += cx.child(("chip", "none"), &mut ChordChip::new(self.env.words.none.as_str().to_owned()), Proposal::Ideal).x + gap;
|
||||
let none = self.env.words.none.as_str().to_owned();
|
||||
let width = cx.child(("chip", "none"), &mut ChordChip::new(none.clone()), Proposal::Ideal).x;
|
||||
self.widths.insert((Shown::Chip, none), width);
|
||||
cell += width + gap;
|
||||
}
|
||||
for text in &line.unparsed {
|
||||
let width = cx.child(("unparsed", text), &mut unparsed_note(text, String::new()), Proposal::Ideal).x;
|
||||
@@ -578,14 +581,15 @@ impl CommandRow<'_> {
|
||||
}
|
||||
}
|
||||
if cells.is_empty() && !hold {
|
||||
let rect = band(&flow, cell, 0.0, chips_end.max(height));
|
||||
let none = words.none.as_str();
|
||||
let width = width_of(Shown::Chip, none).min(chips_end.max(0.0));
|
||||
let rect = band(&flow, cell, 0.0, width);
|
||||
let name = words.label_chord.fill(&[("label", &line.label), ("chord", none)]);
|
||||
let chip = ChordChip::new(none.to_owned()).label(name).id_salt(("chip", line.key.as_str(), 0)).enabled(editable);
|
||||
if ui.child(("chip", line.key.as_str(), 0), rect, chip).pressed {
|
||||
act = Some(RowAct::Record(None));
|
||||
}
|
||||
at = chips_end.max(height) + gap;
|
||||
at = width + gap;
|
||||
}
|
||||
let unparsed: &[String] = if hold { &[] } else { &line.unparsed };
|
||||
for (n, text) in unparsed.iter().enumerate() {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! The Mac layout, its shortcut clashes, and the keys that decide rebuild against update in place.
|
||||
|
||||
use craft_menu::{Builtin, Document, Item, ItemKind, LayoutOptions, MenuBar, MenuRole, Node, mac_layout, structure_key, window_key};
|
||||
use craft_menu::{Builtin, Document, Item, ItemKind, LayoutOptions, MenuBar, MenuRole, Node, mac, mac_layout, structure_key, window_key};
|
||||
use craft_ui::testing::trial;
|
||||
|
||||
use crate::sample::{chord, cmd, ids, sample, titled};
|
||||
@@ -41,6 +41,30 @@ fn the_app_menu_is_laid_out_the_mac_way() {
|
||||
);
|
||||
}
|
||||
|
||||
/// The minimal app menu names the app by default and takes the app's translations through the keys
|
||||
/// the Mac layout uses for the same items.
|
||||
#[trial]
|
||||
fn the_minimal_app_menu_takes_the_apps_translations() {
|
||||
let english = mac::app_menu(&LayoutOptions::new("Sample"));
|
||||
assert_eq!(english.title, "Sample");
|
||||
for label in [&english.about, &english.hide, &english.quit] {
|
||||
assert!(label.contains("Sample"), "{label:?} names the app");
|
||||
}
|
||||
|
||||
let german = |s: &'static str| match s {
|
||||
"About {app}" => "Über {app}".to_string(),
|
||||
"Services" => "Dienste".into(),
|
||||
"Hide {app}" => "{app} ausblenden".into(),
|
||||
"Hide Others" => "Andere ausblenden".into(),
|
||||
"Show All" => "Alle einblenden".into(),
|
||||
"Quit {app}" => "{app} beenden".into(),
|
||||
other => panic!("no app menu label {other:?}"),
|
||||
};
|
||||
let m = mac::app_menu(&LayoutOptions::new("Sample").label(&german));
|
||||
let got: [&str; 7] = [&m.title, &m.about, &m.services, &m.hide, &m.hide_others, &m.show_all, &m.quit];
|
||||
assert_eq!(got, ["Sample", "Über Sample", "Dienste", "Sample ausblenden", "Andere ausblenden", "Alle einblenden", "Sample beenden"]);
|
||||
}
|
||||
|
||||
/// App commands keep ⌘H, ⌘M, ⌘W and ⌘,: the system items give way, and each clash is reported.
|
||||
#[trial]
|
||||
fn clashes_are_resolved_in_the_apps_favour() {
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
//! The keyboard pane, the set row's buttons and the shortcut column keep the look the dialog had before the port: readable keys
|
||||
//! beside the clicked key's shortcuts, filled keys and a legend in the same fills, framed set buttons, and the add button right
|
||||
//! after the chips of every row.
|
||||
|
||||
use craft_keymap::{Platform, Profiles};
|
||||
use craft_ui::contract::Role;
|
||||
use craft_ui::testing::{Target, trial};
|
||||
use egui::Shape;
|
||||
|
||||
use super::fixture::Rig;
|
||||
|
||||
/// The pane as an app opens it: a size of its own in the rig's 1000 by 700 point window. The pane takes the height its
|
||||
/// width gives the keys.
|
||||
fn pane_like_an_app(options: &mut craft_menu::shortcuts::Options) {
|
||||
options.keyboard = true;
|
||||
options.size = Some(egui::vec2(900.0, 620.0));
|
||||
}
|
||||
|
||||
/// The key named `name` on the pane (its node is a button of that name).
|
||||
fn cap(rig: &Rig, name: &str) -> Target {
|
||||
rig.named(name, Role::BUTTON)
|
||||
}
|
||||
|
||||
/// The pane `width` points wide, with the height of one control and a key's rect: the footer's OK is a control.
|
||||
fn pane(width: f32) -> (f32, egui::Rect) {
|
||||
let rig = Rig::tuned(Platform::Windows, |options| {
|
||||
options.keyboard = true;
|
||||
options.size = Some(egui::vec2(width, 620.0));
|
||||
});
|
||||
(rig.named("OK", Role::BUTTON).rect.height(), cap(&rig, "Q").rect)
|
||||
}
|
||||
|
||||
/// The rects of the painted rectangles that have a fill.
|
||||
fn filled(shapes: &[Shape]) -> Vec<(egui::Rect, egui::Color32)> {
|
||||
shapes
|
||||
.iter()
|
||||
.filter_map(|shape| match shape {
|
||||
Shape::Rect(rect) if rect.fill.a() > 0 => Some((rect.visual_bounding_rect(), rect.fill)),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// With the keyboard pane on, a key is readable (at least a control tall and wide) and the clicked key's shortcuts stand
|
||||
/// beside the whole block of keys, not between them.
|
||||
#[trial]
|
||||
fn the_keyboard_keeps_readable_keys_beside_the_key_list() {
|
||||
let rig = Rig::tuned(Platform::Windows, pane_like_an_app);
|
||||
let q = cap(&rig, "Q").rect;
|
||||
assert!(q.width() >= 24.0 && q.height() >= 24.0, "a key stays readable: {q:?}");
|
||||
let hint = rig.fixture.texts().iter().find(|text| text.text.starts_with("Click a key")).expect("the hint").rect;
|
||||
// Q starts 1.5 units in and the block is 18.5 units wide, so the block ends 17 key widths past Q's left edge.
|
||||
assert!(hint.left() > q.left() + 17.0 * q.width(), "the hint stands beside the whole block of keys (a key is {q:?}): {hint:?}");
|
||||
}
|
||||
|
||||
/// The keys keep their proportions in the room the app gives the pane: a wider pane is taller, so its keys stand above one
|
||||
/// control's height rather than staying one control high however wide the dialog is.
|
||||
///
|
||||
/// Both dialogs keep the pane's two columns beside each other, so the keys take the same share of the room in each and
|
||||
/// the wider one draws the taller keys. A `Grid` stacks its columns only when their least widths do not fit: the caps
|
||||
/// ask for 18.5 control heights (444 points at the compact preset's 24 point control) and the shortcut column for its
|
||||
/// hint's readable least, which a 700 point dialog's 684 points of room (its two 8 point pads taken off) leaves well
|
||||
/// inside. A stacked grid would give the caps the whole width instead, and they would come out wider, and so taller,
|
||||
/// in the narrower dialog.
|
||||
#[trial]
|
||||
fn a_wider_pane_is_taller_and_its_keys_stand_above_a_control() {
|
||||
let (control, narrow) = pane(700.0);
|
||||
let (_, wide) = pane(950.0);
|
||||
assert!(wide.height() > narrow.height(), "a wider pane draws taller keys: {:?} against {:?}", wide, narrow);
|
||||
assert!(wide.height() > control, "the keys stand above one control's height: {:?} against {control}", wide);
|
||||
}
|
||||
|
||||
/// Keys are painted with a fill of their own, and the legend words stand on fills too.
|
||||
#[trial]
|
||||
fn keys_and_the_legend_are_filled() {
|
||||
let mut rig = Rig::tuned(Platform::Windows, pane_like_an_app);
|
||||
let q = cap(&rig, "Q").rect;
|
||||
let legend = rig.fixture.texts().iter().find(|text| text.text == "Application").expect("the legend word Application").rect;
|
||||
let fills = filled(&rig.fixture.frame_shapes());
|
||||
assert!(fills.iter().any(|(rect, _)| (rect.center() - q.center()).length() < 2.0 && rect.width() > 20.0), "the key Q has a fill: {q:?}");
|
||||
assert!(fills.iter().any(|(rect, _)| rect.contains_rect(legend)), "the legend word stands on a fill: {legend:?}");
|
||||
}
|
||||
|
||||
/// The set row's actions are framed buttons.
|
||||
#[trial]
|
||||
fn the_set_row_buttons_are_framed() {
|
||||
let mut rig = Rig::mac_with_sets(Profiles::default());
|
||||
let new = rig.find("New Set\u{2026}").rect;
|
||||
let shapes = rig.fixture.frame_shapes();
|
||||
let framed = shapes.iter().any(|shape| match shape {
|
||||
Shape::Rect(rect) => {
|
||||
let r = rect.visual_bounding_rect();
|
||||
(r.center() - new.center()).length() < 3.0 && r.width() >= new.width() - 3.0 && (rect.fill.a() > 0 || !rect.stroke.is_empty())
|
||||
}
|
||||
_ => false,
|
||||
});
|
||||
assert!(framed, "New Set\u{2026} is drawn as a framed button: {new:?}");
|
||||
}
|
||||
|
||||
/// A shortcut is one keycap per key (`Ctrl`, `S`), the framework's look for a chord.
|
||||
#[trial]
|
||||
fn a_shortcut_is_one_keycap_per_key() {
|
||||
let rig = Rig::tuned(Platform::Windows, |_| {});
|
||||
let texts: Vec<&str> = rig.fixture.texts().iter().map(|text| text.text.as_str()).collect();
|
||||
assert!(texts.contains(&"Ctrl") && texts.contains(&"S"), "Save's shortcut shows a keycap for Ctrl and one for S: {texts:?}");
|
||||
assert!(!texts.contains(&"Ctrl+S"), "not one text for the chord: {texts:?}");
|
||||
}
|
||||
|
||||
/// The add button stands right after the last text of its row's shortcut cell, whether the cell holds a chord or None.
|
||||
#[trial]
|
||||
fn the_add_button_follows_the_chips_of_every_row() {
|
||||
let rig = Rig::tuned(Platform::Windows, |_| {});
|
||||
let adds: Vec<Target> = rig
|
||||
.fixture
|
||||
.by_role(Role::BUTTON)
|
||||
.into_iter()
|
||||
.filter(|node| rig.fixture.tree().name_of(node.node).is_some_and(|name| name.starts_with("Add a shortcut to")))
|
||||
.collect();
|
||||
assert!(adds.len() >= 3, "rows with an add button: {}", adds.len());
|
||||
for add in adds {
|
||||
let before = rig
|
||||
.fixture
|
||||
.texts()
|
||||
.iter()
|
||||
.filter(|text| (text.rect.center().y - add.rect.center().y).abs() < 6.0 && text.rect.right() <= add.rect.left() + 1.0)
|
||||
.map(|text| text.rect.right())
|
||||
.fold(f32::MIN, f32::max);
|
||||
assert!(add.rect.left() - before < 24.0, "the add button {:?} follows its chips ({before})", add.rect);
|
||||
}
|
||||
}
|
||||
@@ -2,12 +2,14 @@
|
||||
mod fixture;
|
||||
pub(crate) mod hold;
|
||||
pub(crate) mod import_offer;
|
||||
pub(crate) mod keyboard;
|
||||
pub(crate) mod lists;
|
||||
pub(crate) mod recorder;
|
||||
pub(crate) mod review;
|
||||
pub(crate) mod rows;
|
||||
pub(crate) mod sets;
|
||||
pub(crate) mod tabs;
|
||||
pub(crate) mod undo_toggle;
|
||||
|
||||
use std::cell::Cell;
|
||||
use std::rc::Rc;
|
||||
@@ -246,6 +248,49 @@ fn automation_does_not_replace_a_binding_while_the_recorder_owns_it() {
|
||||
assert!(!rig.shared.borrow().state.is_recording());
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn automation_cannot_edit_shortcuts_in_a_read_only_dialog() {
|
||||
let mut rig = Rig::mac();
|
||||
rig.set_json_field("command", json!("file.save")).unwrap();
|
||||
rig.set_json_field("pressed", json!("Cmd+K")).unwrap();
|
||||
rig.shared.borrow_mut().options.editable = false;
|
||||
rig.pass();
|
||||
|
||||
assert!(rig.set_json_field("assign", json!(true)).is_err(), "assign");
|
||||
assert!(rig.set_json_field("remove", json!("Cmd+S")).is_err(), "remove");
|
||||
assert!(rig.set_json_field("pressed", json!("Cmd+J")).is_err(), "pressed");
|
||||
assert_eq!(rig.bindings("file.save"), ["Cmd+S"]);
|
||||
let shared = rig.shared.borrow();
|
||||
assert!(!shared.state.snapshot(&shared.km).unwrap().can_undo);
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn automation_cannot_edit_shortcuts_while_reset_confirmation_is_open() {
|
||||
let mut rig = Rig::mac();
|
||||
rig.set_json_field("command", json!("file.save")).unwrap();
|
||||
rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Cmd+K"})).unwrap();
|
||||
rig.set_json_field("pressed", json!("Cmd+J")).unwrap();
|
||||
rig.click("Reset All…");
|
||||
|
||||
assert!(rig.set_json_field("assign", json!(true)).is_err(), "assign");
|
||||
assert!(rig.set_json_field("remove", json!("Cmd+K")).is_err(), "remove");
|
||||
assert!(rig.set_json_field("pressed", json!("Cmd+L")).is_err(), "pressed");
|
||||
assert_eq!(rig.bindings("file.save"), ["Cmd+K"]);
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn automation_cannot_edit_a_shortcut_while_the_recorder_owns_it() {
|
||||
let mut rig = Rig::mac();
|
||||
rig.set_json_field("command", json!("file.save")).unwrap();
|
||||
rig.click("Save: ⌘S");
|
||||
assert!(rig.shared.borrow().state.is_recording());
|
||||
|
||||
assert!(rig.set_json_field("remove", json!("Cmd+S")).is_err(), "remove");
|
||||
assert!(rig.set_json_field("pressed", json!("Cmd+J")).is_err(), "pressed");
|
||||
assert_eq!(rig.bindings("file.save"), ["Cmd+S"]);
|
||||
assert!(rig.shared.borrow().state.is_recording());
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn automation_rejects_oversize_replacements_but_can_replace_an_oversize_default() {
|
||||
let scope = "Text".repeat(16);
|
||||
|
||||
@@ -17,7 +17,22 @@ use super::fixture;
|
||||
|
||||
#[trial]
|
||||
fn shortcut_replacement_is_unavailable_on_an_app_tab() {
|
||||
shortcut_edit_is_unavailable_on_an_app_tab("replace", json!({"old": "Cmd+S", "new": "Cmd+E"}));
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn shortcut_removal_is_unavailable_on_an_app_tab() {
|
||||
shortcut_edit_is_unavailable_on_an_app_tab("remove", json!("Cmd+S"));
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_new_shortcut_cannot_be_pressed_on_an_app_tab() {
|
||||
shortcut_edit_is_unavailable_on_an_app_tab("pressed", json!("Cmd+E"));
|
||||
}
|
||||
|
||||
fn shortcut_edit_is_unavailable_on_an_app_tab(field: &'static str, value: serde_json::Value) {
|
||||
for (tab, app_tab) in [("menus", true), ("unknown", false)] {
|
||||
let value = value.clone();
|
||||
let result = Rc::new(RefCell::new(None));
|
||||
let observed = result.clone();
|
||||
let drawn = Rc::new(Cell::new(false));
|
||||
@@ -31,19 +46,14 @@ fn shortcut_replacement_is_unavailable_on_an_app_tab() {
|
||||
})];
|
||||
if observed.borrow().is_none() {
|
||||
ShortcutsDialog::new(&mut keys).tabs(&mut tabs).set_json_field(ui, &mut state, "command", &json!("file.save")).unwrap();
|
||||
let answer = ShortcutsDialog::new(&mut keys).tabs(&mut tabs).set_json_field(
|
||||
ui,
|
||||
&mut state,
|
||||
"replace",
|
||||
&json!({"old": "Cmd+S", "new": "Cmd+E"}),
|
||||
);
|
||||
let answer = ShortcutsDialog::new(&mut keys).tabs(&mut tabs).set_json_field(ui, &mut state, field, &value);
|
||||
*observed.borrow_mut() = Some(answer);
|
||||
}
|
||||
ShortcutsDialog::new(&mut keys).tabs(&mut tabs).show(ui, &mut state);
|
||||
});
|
||||
fixture.settle();
|
||||
assert_eq!(drawn.get(), app_tab);
|
||||
assert_eq!(result.borrow().as_ref().unwrap().is_err(), app_tab);
|
||||
assert_eq!(result.borrow().as_ref().unwrap().is_err(), app_tab, "{field} on {tab}");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
//! `UndoButtons::Toggle`: one footer button that steps the last change back and forth.
|
||||
|
||||
use craft_keymap::{CommandRef, Platform};
|
||||
use craft_menu::shortcuts::UndoButtons;
|
||||
use craft_ui::contract::Role;
|
||||
use craft_ui::testing::trial;
|
||||
use egui::{Key, Modifiers};
|
||||
|
||||
use super::fixture::Rig;
|
||||
|
||||
fn rig() -> Rig {
|
||||
Rig::tuned(Platform::Windows, |options| options.undo = UndoButtons::Toggle)
|
||||
}
|
||||
|
||||
/// Whether the footer button `label` can be clicked.
|
||||
fn enabled(rig: &Rig, label: &str) -> bool {
|
||||
let button = rig.named(label, Role::BUTTON);
|
||||
!rig.fixture.tree().is_disabled_key(button.node)
|
||||
}
|
||||
|
||||
/// Records `key` over the selected command's `old` key in the detail pane.
|
||||
fn replace(rig: &mut Rig, id: &str, control: &str, key: Key) {
|
||||
rig.shared.borrow_mut().state.select(&CommandRef::from(id));
|
||||
rig.pass();
|
||||
rig.click(control);
|
||||
rig.press(Modifiers::NONE, key);
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn the_button_undoes_the_last_change_then_redoes_it() {
|
||||
let mut rig = rig();
|
||||
assert!(!rig.has("Redo"), "one button, not Undo and Redo side by side");
|
||||
assert!(!enabled(&rig, "Undo"), "nothing to undo when the dialog opens");
|
||||
let original = rig.bindings("file.save");
|
||||
|
||||
replace(&mut rig, "file.save", "Replace Ctrl+S for Save", Key::F11);
|
||||
assert_eq!(rig.bindings("file.save"), ["F11"]);
|
||||
assert!(enabled(&rig, "Undo"));
|
||||
|
||||
rig.click("Undo");
|
||||
assert_eq!(rig.bindings("file.save"), original);
|
||||
assert!(!rig.has("Undo") && enabled(&rig, "Redo"), "after Undo the button reads Redo");
|
||||
|
||||
rig.click("Redo");
|
||||
assert_eq!(rig.bindings("file.save"), ["F11"]);
|
||||
assert!(!rig.has("Redo") && enabled(&rig, "Undo"), "after Redo the button reads Undo again");
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn the_button_reaches_only_the_last_change() {
|
||||
let mut rig = rig();
|
||||
let export = rig.bindings("file.export");
|
||||
replace(&mut rig, "file.save", "Replace Ctrl+S for Save", Key::F11);
|
||||
replace(&mut rig, "file.export", "Replace Ctrl+E for Export…", Key::F9);
|
||||
|
||||
rig.click("Undo");
|
||||
assert_eq!(rig.bindings("file.export"), export);
|
||||
assert_eq!(rig.bindings("file.save"), ["F11"], "the change before the last one stays");
|
||||
assert!(!rig.has("Undo"), "a second Undo is not offered");
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn starting_to_record_disables_the_button() {
|
||||
let mut rig = rig();
|
||||
replace(&mut rig, "file.save", "Replace Ctrl+S for Save", Key::F11);
|
||||
assert!(enabled(&rig, "Undo"));
|
||||
|
||||
rig.click("Replace F11 for Save");
|
||||
assert!(!enabled(&rig, "Undo"), "a new edit has begun");
|
||||
rig.press(Modifiers::NONE, Key::Escape);
|
||||
assert_eq!(rig.bindings("file.save"), ["F11"]);
|
||||
assert!(!enabled(&rig, "Undo"), "a cancelled recording does not bring the earlier change back");
|
||||
}
|
||||
@@ -11,7 +11,11 @@ crate has no UI, does no file or network I/O and has no `unsafe` code. File form
|
||||
glTF 2.0 recommends for meshes without tangents
|
||||
(<https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html>): `w` holds the bitangent sign.
|
||||
- **UV unwrapping.** `unwrap::auto_unwrap` makes a non-overlapping layout per material, splitting
|
||||
vertices where charts meet.
|
||||
vertices where charts meet. It checks the mesh against its size limits and its attribute data
|
||||
first and returns an error without changing the mesh when a check fails. Charts are projected
|
||||
and packed in `f64`. Padding uses the
|
||||
requested resolution, with a minimum resolution of 16. A layout that cannot fit returns an
|
||||
error without changing the mesh. Missing normals use area-weighted `f64` accumulation and normalization.
|
||||
- **UV G-buffer.** `UvGBuffer` records, for each texel of one material's UV space, the triangle
|
||||
and barycentrics under the texel center; `surface_at` turns them into a position, normal and
|
||||
tangent frame. `UvGBuffer::new` returns an error for a side of 0 or above `MAX_SIDE` (16,384),
|
||||
@@ -22,6 +26,9 @@ crate has no UI, does no file or network I/O and has no `unsafe` code. File form
|
||||
return `Result<Mesh>`. They reject non-finite or nonpositive dimensions and dimensions whose
|
||||
doubled half extents overflow. A box bevel must be finite and between zero and 95% of its
|
||||
smallest half extent; an invalid bevel returns `GeomError::Invalid`.
|
||||
Sphere and torus seam endpoints have identical positions and retain distinct UV endpoints.
|
||||
Cylinder caps share exact rim positions with the side, and rounded-box faces share exact boundary positions.
|
||||
Lathe profile lengths and direction normalization use `f64` before the UVs and normals are stored as `f32`.
|
||||
- **BVH.** `Bvh` is a binned SAH tree on all three axes with a median split when no split beats a
|
||||
leaf. It answers closest-hit, any-hit and filtered ray casts, nearest-point queries and box
|
||||
queries.
|
||||
|
||||
@@ -15,7 +15,11 @@ struct Node {
|
||||
count: u32,
|
||||
}
|
||||
|
||||
/// A ray hit: distance, triangle and barycentrics (weights of vertices 1 and 2).
|
||||
/// A hit: `t`, triangle and barycentrics (weights of vertices 1 and 2).
|
||||
///
|
||||
/// From [`Bvh::closest`] and [`Bvh::closest_filtered`], `t` is the ray parameter: the hit point
|
||||
/// is `o + t·d`, so `t` is a distance only when `d` has unit length. From [`Bvh::nearest`], `t` is
|
||||
/// the distance from the query point.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Hit {
|
||||
pub t: f32,
|
||||
@@ -35,7 +39,7 @@ pub struct Bvh {
|
||||
|
||||
const LEAF: usize = 4;
|
||||
|
||||
/// Traversal stack of (node, entry distance): inline for typical depths (no allocation per
|
||||
/// Traversal stack of (node, ray parameter at entry): inline for typical depths (no allocation per
|
||||
/// ray), spilling to the heap for degenerate trees.
|
||||
struct Stack {
|
||||
inline: [(u32, f32); 64],
|
||||
@@ -286,7 +290,7 @@ impl Bvh {
|
||||
let mut best = None;
|
||||
let mut stack = Stack::default();
|
||||
stack.push((0, Self::slab(root.lo, root.hi, oa, inv, tmax)?));
|
||||
// Entries carry their entry distance: nodes behind a closer hit are skipped unopened.
|
||||
// Entries carry their ray parameter at entry: nodes behind a closer hit are skipped unopened.
|
||||
while let Some((ni, tn)) = stack.pop() {
|
||||
let Some(n) = self.nodes.get(ni as usize).filter(|_| tn <= tmax) else { continue };
|
||||
if n.count > 0 {
|
||||
@@ -675,4 +679,25 @@ mod tests {
|
||||
assert_eq!(hit.tri, 500);
|
||||
assert_eq!(hit.t, 10.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ray_hit_t_is_the_parameter_of_the_direction_given() {
|
||||
let m = Mesh {
|
||||
positions: vec![Vec3::new(-1.0, -1.0, 0.0), Vec3::new(1.0, -1.0, 0.0), Vec3::new(0.0, 1.0, 0.0)],
|
||||
indices: vec![0, 1, 2],
|
||||
..Default::default()
|
||||
};
|
||||
let bvh = Bvh::new(&m);
|
||||
let o = Vec3::new(0.0, 0.0, 1.0);
|
||||
// The triangle is 1 unit away; a direction of length 2 reaches it at t = 0.5.
|
||||
let d = Vec3::new(0.0, 0.0, -2.0);
|
||||
assert_eq!(bvh.closest(o, d, 10.0).map(|h| h.t), Some(0.5));
|
||||
assert_eq!(bvh.closest_filtered(o, d, 10.0, &|_| true).map(|h| h.t), Some(0.5));
|
||||
assert_eq!(o + d * 0.5, Vec3::ZERO);
|
||||
// `tmax` is in the same units: the hit at t = 0.5 lies beyond 0.4 and before 0.6.
|
||||
assert!(!bvh.occluded(o, d, 0.4));
|
||||
assert!(bvh.occluded(o, d, 0.6));
|
||||
// `nearest` reports the distance itself.
|
||||
assert_eq!(bvh.nearest(o, 10.0, &|_| true).map(|h| h.t), Some(1.0));
|
||||
}
|
||||
}
|
||||
+73
-11
@@ -110,34 +110,69 @@ impl Mesh {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Edges where the UV layout splits: two triangles meet there in 3D but not in UV space, per material in `0..materials.len().max(1)`
|
||||
/// Edges where the UV layout splits: two triangles meet there in 3D but not in UV space, per material in `0..materials.len().max(1)`.
|
||||
/// An edge between two vertices at one position is not listed, and a triangle with two corners at one position
|
||||
/// connects its two other edges in UV space, as the corners of a pole row do.
|
||||
pub fn uv_seam_edges(&self) -> Vec<Vec<(u32, u32)>> {
|
||||
// Signed zero denotes the same position on either side of an imported seam
|
||||
let bits = |position: Vec3| position.to_array().map(|coordinate| if coordinate == 0.0 { 0 } else { coordinate.to_bits() });
|
||||
let mut seams = vec![Vec::new(); self.materials.len().max(1)];
|
||||
// Match across materials before grouping the lines for texture-set visibility
|
||||
let mut sides: std::collections::HashMap<EdgePositions, Vec<(u32, u32, usize)>> = std::collections::HashMap::new();
|
||||
// A triangle with two corners at one position joins its two edges to the third corner in UV space
|
||||
let mut joins: std::collections::HashMap<EdgePositions, Vec<[(u32, u32); 2]>> = std::collections::HashMap::new();
|
||||
let canonical = |from: u32, to: u32, from_bits: [u32; 3], to_bits: [u32; 3]| {
|
||||
if from_bits <= to_bits { ((from_bits, to_bits), (from, to)) } else { ((to_bits, from_bits), (to, from)) }
|
||||
};
|
||||
for material in 0..seams.len() {
|
||||
for triangle in self.triangles_of(material) {
|
||||
let Some(corners) = self.indices.get(triangle * 3..triangle * 3 + 3) else { continue };
|
||||
let Some(corner_bits) =
|
||||
corners.iter().map(|&corner| self.positions.get(corner as usize).map(|p| bits(*p))).collect::<Option<Vec<_>>>()
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
|
||||
for (from, to) in [(corners[0], corners[1]), (corners[1], corners[2]), (corners[2], corners[0])] {
|
||||
let (Some(from_position), Some(to_position)) = (self.positions.get(from as usize), self.positions.get(to as usize)) else {
|
||||
for (a, b) in [(0, 1), (1, 2), (2, 0)] {
|
||||
// An edge between two vertices at one position has no length to draw
|
||||
if corner_bits[a] == corner_bits[b] {
|
||||
let c = 3 - a - b;
|
||||
if corner_bits[c] != corner_bits[a] {
|
||||
let (edge, first) = canonical(corners[a], corners[c], corner_bits[a], corner_bits[c]);
|
||||
let (_, second) = canonical(corners[b], corners[c], corner_bits[b], corner_bits[c]);
|
||||
joins.entry(edge).or_default().push([first, second]);
|
||||
}
|
||||
continue;
|
||||
};
|
||||
|
||||
let (from_bits, to_bits) = (bits(*from_position), bits(*to_position));
|
||||
let (edge, pair) = if from_bits <= to_bits { ((from_bits, to_bits), (from, to)) } else { ((to_bits, from_bits), (to, from)) };
|
||||
}
|
||||
let (edge, pair) = canonical(corners[a], corners[b], corner_bits[a], corner_bits[b]);
|
||||
sides.entry(edge).or_default().push((pair.0, pair.1, material));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let uv = |index: u32| self.uvs.get(index as usize).copied();
|
||||
for pairs in sides.into_values() {
|
||||
let Some(&(first_from, first_to, _)) = pairs.first() else { continue };
|
||||
for (edge, pairs) in sides {
|
||||
// Group the UV layouts of this edge, joining the layouts a collapsed triangle connects
|
||||
let mut layouts = Vec::new();
|
||||
for &(from, to, _) in &pairs {
|
||||
if !layouts.contains(&(uv(from), uv(to))) {
|
||||
layouts.push((uv(from), uv(to)));
|
||||
}
|
||||
}
|
||||
let mut group: Vec<usize> = (0..layouts.len()).collect();
|
||||
for [first, second] in joins.get(&edge).into_iter().flatten() {
|
||||
let find = |(from, to): (u32, u32)| layouts.iter().position(|layout| *layout == (uv(from), uv(to)));
|
||||
if let (Some(first), Some(second)) = (find(*first), find(*second)) {
|
||||
let (kept, merged) = (group[first], group[second]);
|
||||
for g in &mut group {
|
||||
if *g == merged {
|
||||
*g = kept;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if pairs.iter().any(|&(from, to, _)| (uv(from), uv(to)) != (uv(first_from), uv(first_to))) {
|
||||
if group.iter().any(|&g| g != group[0]) {
|
||||
for (from, to, material) in pairs {
|
||||
if let Some(edges) = seams.get_mut(material) {
|
||||
edges.push((from.min(to), from.max(to)));
|
||||
@@ -401,14 +436,22 @@ impl Mesh {
|
||||
(m.positions.len() - 1) as u32
|
||||
})
|
||||
};
|
||||
for t in self.indices.as_chunks::<3>().0 {
|
||||
// Each child keeps the hidden bits of the halves of the parent's edges it has; the edges
|
||||
// inside the parent are real.
|
||||
let mut diagonals = Vec::with_capacity(if self.diagonals.is_empty() { 0 } else { self.diagonals.len().saturating_mul(4) });
|
||||
for (k, t) in self.indices.as_chunks::<3>().0.iter().enumerate() {
|
||||
if t.iter().any(|&i| i as usize >= self.positions.len()) {
|
||||
continue;
|
||||
}
|
||||
let (a, b, c) = (t[0], t[1], t[2]);
|
||||
let (ab, bc, ca) = (mid(&mut m, a, b), mid(&mut m, b, c), mid(&mut m, c, a));
|
||||
m.indices.extend_from_slice(&[a, ab, ca, ab, b, bc, ca, bc, c, ab, bc, ca]);
|
||||
if !self.diagonals.is_empty() {
|
||||
let h = self.diagonals.get(k).copied().unwrap_or(0);
|
||||
diagonals.extend_from_slice(&[h & 0b101, h & 0b011, h & 0b110, 0]);
|
||||
}
|
||||
}
|
||||
m.diagonals = diagonals;
|
||||
for s in &mut m.submeshes {
|
||||
s.start *= 4;
|
||||
s.count *= 4;
|
||||
@@ -530,6 +573,12 @@ mod tests {
|
||||
a.append(&m);
|
||||
assert_eq!(a.diagonals, vec![0, 0b100, 0b001]);
|
||||
assert_eq!(crate::primitives::plane(1.0, 2).wire_edges()[0].len(), 12, "a 2×2 grid of quads has 12 edges");
|
||||
// Subdividing hides both halves of the diagonal and nothing else: 16 edges less 2.
|
||||
let sub = m.subdivided();
|
||||
assert_eq!(sub.diagonals.len(), sub.triangle_count());
|
||||
let edges = &sub.wire_edges()[0];
|
||||
assert_eq!(edges.len(), 14);
|
||||
assert!(edges.iter().all(|&(a, b)| !matches!((a, b), (0, 6) | (2, 6))), "diagonal halves {edges:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -564,6 +613,19 @@ mod tests {
|
||||
assert_eq!(mesh.uv_seam_edges(), vec![vec![(0, 2), (2, 4)]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uv_seams_skip_edges_between_vertices_at_one_position() {
|
||||
let (segments, rings) = (3, 2);
|
||||
let mesh = crate::primitives::sphere(1.0, segments, rings);
|
||||
let seams = mesh.uv_seam_edges();
|
||||
assert!(
|
||||
seams[0].iter().all(|&(from, to)| mesh.positions[from as usize] != mesh.positions[to as usize]),
|
||||
"zero-length seam edges at a pole: {seams:?}"
|
||||
);
|
||||
// Only the meridian where u = 0 meets u = 1 is a seam: columns 0 and 3, with the collapsed pole triangles
|
||||
assert_eq!(seams, vec![vec![(0, 4), (2, 7), (3, 7), (4, 8), (4, 9), (7, 11)]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uv_seams_between_materials_belong_to_both_materials() {
|
||||
let mut mesh = quad();
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
use std::f32::consts::{PI, TAU};
|
||||
|
||||
use glam::{Vec2, Vec3};
|
||||
use glam::{DVec2, Vec2, Vec3};
|
||||
|
||||
use crate::mesh::{Mesh, SubMesh};
|
||||
use crate::{GeomError, Result};
|
||||
@@ -88,7 +88,8 @@ impl Builder {
|
||||
}
|
||||
}
|
||||
|
||||
/// UV sphere of `radius` centred at `center`.
|
||||
/// A UV sphere of `radius` centered at the origin. The seam endpoints have identical positions
|
||||
/// at each ring. Vertices at each pole share one position.
|
||||
pub fn sphere(radius: f32, segments: usize, rings: usize) -> Mesh {
|
||||
let mut b = Builder::default();
|
||||
sphere_into(&mut b, Vec3::ZERO, radius, segments.max(3), rings.max(2), UvRect::FULL);
|
||||
@@ -98,8 +99,14 @@ pub fn sphere(radius: f32, segments: usize, rings: usize) -> Mesh {
|
||||
fn sphere_into(b: &mut Builder, center: Vec3, radius: f32, segs: usize, rings: usize, r: UvRect) {
|
||||
b.grid(rings, segs, |i, j| {
|
||||
let (u, v) = (j as f32 / segs as f32, i as f32 / rings as f32);
|
||||
let (theta, phi) = (v * PI, u * TAU + PI * 1.5);
|
||||
let n = Vec3::new(theta.sin() * phi.cos(), theta.cos(), -theta.sin() * phi.sin());
|
||||
let (theta, phi) = (v * PI, if j == segs { PI * 1.5 } else { u * TAU + PI * 1.5 });
|
||||
let n = if i == 0 {
|
||||
Vec3::Y
|
||||
} else if i == rings {
|
||||
-Vec3::Y
|
||||
} else {
|
||||
Vec3::new(theta.sin() * phi.cos(), theta.cos(), -theta.sin() * phi.sin())
|
||||
};
|
||||
(center + n * radius, n, r.map(u, v))
|
||||
});
|
||||
}
|
||||
@@ -153,7 +160,10 @@ fn rounded_box_into(b: &mut Builder, center: Vec3, half: Vec3, bevel: f32, r: Uv
|
||||
v.push(inner * (2.0 * (i as f32 / kc as f32) - 1.0));
|
||||
}
|
||||
for i in 1..=kb {
|
||||
v.push(inner + bevel * (i as f32 / kb as f32));
|
||||
v.push(if i == kb { h } else { inner + bevel * (i as f32 / kb as f32) });
|
||||
}
|
||||
for i in 0..v.len() / 2 {
|
||||
v[i] = -v[v.len() - 1 - i];
|
||||
}
|
||||
v
|
||||
};
|
||||
@@ -167,7 +177,7 @@ fn rounded_box_into(b: &mut Builder, center: Vec3, half: Vec3, bevel: f32, r: Uv
|
||||
let (a, c) = (cu[j], cv[i]);
|
||||
let q = *n * hn + *u * a + *v * c;
|
||||
let clamped = q.clamp(-inner, inner);
|
||||
let dir = (q - clamped).try_normalize().unwrap_or(*n);
|
||||
let dir = (q - clamped).as_dvec3().try_normalize().map(|v| v.as_vec3()).unwrap_or(*n);
|
||||
let p = if bevel > 0.0 { clamped + dir * bevel } else { q };
|
||||
let nn = if bevel > 0.0 { dir } else { *n };
|
||||
(center + p, nn, cell.map((a + hu) / (2.0 * hu), (c + hv) / (2.0 * hv)))
|
||||
@@ -181,26 +191,28 @@ fn lathe_into(b: &mut Builder, center: Vec3, profile: &[(f32, f32)], segs: usize
|
||||
if profile.len() < 2 {
|
||||
return;
|
||||
}
|
||||
let mut len = vec![0.0f32];
|
||||
let mut len = vec![0.0f64];
|
||||
for w in profile.windows(2) {
|
||||
let d = Vec2::new(w[1].0 - w[0].0, w[1].1 - w[0].1).length();
|
||||
let d = DVec2::new(f64::from(w[1].0) - f64::from(w[0].0), f64::from(w[1].1) - f64::from(w[0].1)).length();
|
||||
len.push(len.last().copied().unwrap_or(0.0) + d);
|
||||
}
|
||||
let total = len.last().copied().unwrap_or(1.0).max(1e-6);
|
||||
let total = len.last().copied().filter(|total| *total > 0.0).unwrap_or(1.0);
|
||||
let rows = profile.len() - 1;
|
||||
b.grid(rows, segs, |i, j| {
|
||||
let (rad, y) = profile[i];
|
||||
// Profile tangent (downwards) → outward normal in the (r, y) plane.
|
||||
let prev = profile[i.saturating_sub(1)];
|
||||
let next = profile[(i + 1).min(rows)];
|
||||
let t = Vec2::new(next.0 - prev.0, next.1 - prev.1).try_normalize().unwrap_or(Vec2::NEG_Y);
|
||||
let t = DVec2::new(f64::from(next.0) - f64::from(prev.0), f64::from(next.1) - f64::from(prev.1))
|
||||
.try_normalize()
|
||||
.map(|t| t.as_vec2())
|
||||
.unwrap_or(Vec2::NEG_Y);
|
||||
let n2 = Vec2::new(-t.y, t.x);
|
||||
let u = j as f32 / segs as f32;
|
||||
let phi = u * TAU + PI * 1.5;
|
||||
let dir = Vec3::new(phi.cos(), 0.0, -phi.sin());
|
||||
let dir = circle_sample(j, segs);
|
||||
let p = center + dir * rad + Vec3::Y * y;
|
||||
let n = dir * n2.x + Vec3::Y * n2.y;
|
||||
(p, n, r.map(u, len[i] / total))
|
||||
(p, n, r.map(u, (len[i] / total) as f32))
|
||||
});
|
||||
}
|
||||
|
||||
@@ -331,14 +343,19 @@ fn preview_orb_radius(d: Vec3) -> f32 {
|
||||
radius + relief
|
||||
}
|
||||
|
||||
fn circle_sample(column: usize, segments: usize) -> Vec3 {
|
||||
let angle = if column == segments { PI * 1.5 } else { column as f32 / segments as f32 * TAU + PI * 1.5 };
|
||||
Vec3::new(angle.cos(), 0.0, -angle.sin())
|
||||
}
|
||||
|
||||
/// A flat disk facing up (+Y) or down, with planar UVs inside `r`.
|
||||
fn disk_into(b: &mut Builder, center: Vec3, radius: f32, up: bool, segs: usize, r: UvRect) {
|
||||
let n = if up { Vec3::Y } else { Vec3::NEG_Y };
|
||||
let c = b.vert(center, n, r.map(0.5, 0.5));
|
||||
let first = b.p.len() as u32;
|
||||
for j in 0..segs {
|
||||
let a = j as f32 / segs as f32 * TAU;
|
||||
let (x, z) = (a.cos(), a.sin());
|
||||
let sample = circle_sample(j, segs);
|
||||
let (x, z) = (sample.x, sample.z);
|
||||
// Top view: +X right, +Z down the texture; bottom view mirrors X.
|
||||
let uv = if up { r.map(0.5 + x * 0.5, 0.5 + z * 0.5) } else { r.map(0.5 + x * 0.5, 0.5 - z * 0.5) };
|
||||
b.vert(center + Vec3::new(x, 0.0, z) * radius, n, uv);
|
||||
@@ -346,9 +363,9 @@ fn disk_into(b: &mut Builder, center: Vec3, radius: f32, up: bool, segs: usize,
|
||||
for j in 0..segs as u32 {
|
||||
let (a, bb) = (first + j, first + (j + 1) % segs as u32);
|
||||
if up {
|
||||
b.idx.extend_from_slice(&[c, bb, a]);
|
||||
} else {
|
||||
b.idx.extend_from_slice(&[c, a, bb]);
|
||||
} else {
|
||||
b.idx.extend_from_slice(&[c, bb, a]);
|
||||
}
|
||||
b.diag.push(0);
|
||||
}
|
||||
@@ -370,8 +387,8 @@ pub fn torus(major: f32, minor: f32, segs: usize, sides: usize) -> Mesh {
|
||||
let (segs, sides) = (segs.max(3), sides.max(3));
|
||||
b.grid(sides, segs, |i, j| {
|
||||
let (u, v) = (j as f32 / segs as f32, i as f32 / sides as f32);
|
||||
let phi = u * TAU + PI * 1.5;
|
||||
let theta = v * TAU;
|
||||
let phi = if j == segs { PI * 1.5 } else { u * TAU + PI * 1.5 };
|
||||
let theta = if i == sides { 0.0 } else { v * TAU };
|
||||
let dir = Vec3::new(phi.cos(), 0.0, -phi.sin());
|
||||
let n = dir * theta.cos() - Vec3::Y * theta.sin();
|
||||
(dir * major + n * minor, n, Vec2::new(u, v))
|
||||
@@ -503,6 +520,145 @@ pub const BUILTINS: [(&str, &str); 9] = [
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn lathe_profile_uvs_are_independent_of_height() {
|
||||
let side_range = |mesh: &Mesh| {
|
||||
mesh.uvs
|
||||
.iter()
|
||||
.zip(&mesh.normals)
|
||||
.filter(|(_, normal)| normal.y.abs() < 0.5)
|
||||
.fold((f32::INFINITY, f32::NEG_INFINITY), |(lo, hi), (uv, _)| (lo.min(uv.y), hi.max(uv.y)))
|
||||
};
|
||||
let expected = side_range(&cylinder(1.0, 1.0, 16));
|
||||
let actual = side_range(&cylinder(1.0, 1e-20, 16));
|
||||
assert!((actual.0 - expected.0).abs() < 1e-6 && (actual.1 - expected.1).abs() < 1e-6, "{actual:?} {expected:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tall_cylinders_keep_finite_profile_uvs_and_unit_normals() {
|
||||
let mesh = cylinder(1.0, 1e20, 16);
|
||||
mesh.validate().unwrap();
|
||||
assert!(mesh.uvs.iter().all(|uv| uv.is_finite() && uv.min_element() >= 0.0 && uv.max_element() <= 1.0));
|
||||
assert!(mesh.normals.iter().all(|normal| normal.is_finite() && (normal.length_squared() - 1.0).abs() < 1e-5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepted_small_box_dimensions_are_preserved() {
|
||||
let cube = cube(1e-7).unwrap();
|
||||
let (lo, hi) = cube.bounds();
|
||||
assert_eq!(hi - lo, Vec3::splat(1e-7));
|
||||
let half = Vec3::new(5e-8, 2e-7, 3e-7);
|
||||
let mesh = rounded_box(half, 0.0).unwrap();
|
||||
let (lo, hi) = mesh.bounds();
|
||||
assert_eq!((lo, hi), (-half, half));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rounded_box_face_boundaries_share_exact_positions() {
|
||||
for (half, bevel) in [(1.038, 0.037), (1e21, 1e20)] {
|
||||
let mut builder = Builder::default();
|
||||
rounded_box_into(&mut builder, Vec3::ZERO, Vec3::splat(half), bevel, UvRect::FULL);
|
||||
assert!(builder.n[0].abs().min_element() > 0.5, "rounded corner normal {:?}, half={half}", builder.n[0]);
|
||||
let key = |p: Vec3| p.to_array().map(|v| if v == 0.0 { 0 } else { v.to_bits() });
|
||||
let mut counts = std::collections::HashMap::new();
|
||||
for &position in &builder.p {
|
||||
*counts.entry(key(position)).or_insert(0usize) += 1;
|
||||
}
|
||||
let side = 23;
|
||||
for face in 0..6 {
|
||||
for row in 0..side {
|
||||
for column in 0..side {
|
||||
if row == 0 || column == 0 || row == side - 1 || column == side - 1 {
|
||||
let position = builder.p[face * side * side + row * side + column];
|
||||
assert!(counts[&key(position)] >= 2, "unmatched boundary {position:?}, half={half}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cylinder_caps_match_the_wall_at_every_segment_count() {
|
||||
for segments in [3, 6, 7, 32] {
|
||||
let mesh = cylinder(1.0, 2.0, segments);
|
||||
for row in 0..=1 {
|
||||
let (first, last) = (row * (segments + 1), row * (segments + 1) + segments);
|
||||
assert_eq!(mesh.positions[first], mesh.positions[last]);
|
||||
assert_eq!(mesh.normals[first], mesh.normals[last]);
|
||||
assert!(mesh.uvs[first].x < mesh.uvs[last].x);
|
||||
}
|
||||
for y in [-1.0, 1.0] {
|
||||
let wall: Vec<_> = mesh
|
||||
.positions
|
||||
.iter()
|
||||
.zip(&mesh.normals)
|
||||
.filter_map(|(position, normal)| (position.y == y && normal.y == 0.0).then_some(*position))
|
||||
.collect();
|
||||
let rim: Vec<_> = mesh
|
||||
.positions
|
||||
.iter()
|
||||
.zip(&mesh.normals)
|
||||
.filter_map(|(position, normal)| {
|
||||
(position.y == y && normal.y != 0.0 && position.x * position.x + position.z * position.z > 0.5).then_some(*position)
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(rim.len(), segments);
|
||||
assert!(rim.iter().all(|position| wall.contains(position)), "{segments} segments at height {y}: {rim:?} vs {wall:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sphere_poles_use_identical_endpoint_positions() {
|
||||
for segments in [3, 7, 32] {
|
||||
let rings = 8;
|
||||
let mesh = sphere(1.0, segments, rings);
|
||||
for (row, expected) in [(0, Vec3::Y), (rings, -Vec3::Y)] {
|
||||
for column in 0..=segments {
|
||||
let index = row * (segments + 1) + column;
|
||||
assert_eq!(mesh.positions[index], expected);
|
||||
assert_eq!(mesh.normals[index], expected);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sphere_geometry_closes_its_longitudinal_uv_seam_exactly() {
|
||||
for segments in [3, 7, 32] {
|
||||
let rings = 8;
|
||||
let mesh = sphere(1.0, segments, rings);
|
||||
let width = segments + 1;
|
||||
for row in 0..=rings {
|
||||
let (a, b) = (row * width, row * width + segments);
|
||||
assert_eq!(mesh.positions[a], mesh.positions[b], "seam row {row}");
|
||||
assert_eq!(mesh.normals[a], mesh.normals[b], "seam normal row {row}");
|
||||
assert_eq!((mesh.uvs[a].x, mesh.uvs[b].x), (0.0, 1.0));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn torus_geometry_closes_both_uv_seams_exactly() {
|
||||
for (segs, sides) in [(3, 3), (7, 5), (32, 12)] {
|
||||
let mesh = torus(1.0, 0.35, segs, sides);
|
||||
let width = segs + 1;
|
||||
for row in 0..=sides {
|
||||
let (a, b) = (row * width, row * width + segs);
|
||||
assert_eq!(mesh.positions[a], mesh.positions[b], "u seam row {row}");
|
||||
assert_eq!(mesh.normals[a], mesh.normals[b], "u seam normal row {row}");
|
||||
assert_eq!((mesh.uvs[a].x, mesh.uvs[b].x), (0.0, 1.0));
|
||||
}
|
||||
for col in 0..=segs {
|
||||
let (a, b) = (col, sides * width + col);
|
||||
assert_eq!(mesh.positions[a], mesh.positions[b], "v seam column {col}");
|
||||
assert_eq!(mesh.normals[a], mesh.normals[b], "v seam normal column {col}");
|
||||
assert_eq!((mesh.uvs[a].y, mesh.uvs[b].y), (0.0, 1.0));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
@@ -595,6 +751,42 @@ mod tests {
|
||||
assert!(dome > ORB_CUT && valley < ORB_CUT - 0.05, "dome {dome}, valley {valley}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cylinder_caps_share_the_side_rim_samples() {
|
||||
let bits = |p: Vec3| p.to_array().map(f32::to_bits);
|
||||
for segs in [3, 5, 6, 7, 8, 11, 13, 17, 31, 64, 100, 257] {
|
||||
let m = cylinder(1.0, 2.0, segs);
|
||||
let side: Vec<Vec3> = (0..m.positions.len()).filter(|&i| m.normals[i].y.abs() < 1e-4).map(|i| m.positions[i]).collect();
|
||||
let rim = (0..m.positions.len()).filter(|&i| m.normals[i].y.abs() > 0.99 && Vec2::new(m.positions[i].x, m.positions[i].z).length() > 0.5);
|
||||
for i in rim {
|
||||
let p = m.positions[i];
|
||||
assert!(side.iter().any(|&s| bits(s) == bits(p)), "segs {segs}: cap rim vertex {p:?} is not bit-identical to a side rim sample");
|
||||
}
|
||||
// Every side edge along a rim has a cap edge with the same end positions.
|
||||
let edges = |cap: bool| {
|
||||
let mut out = std::collections::HashSet::new();
|
||||
for t in m.indices.as_chunks::<3>().0 {
|
||||
let is_cap = m.normals[t[0] as usize].y.abs() > 0.99;
|
||||
if is_cap != cap {
|
||||
continue;
|
||||
}
|
||||
for (a, b) in [(t[0], t[1]), (t[1], t[2]), (t[2], t[0])] {
|
||||
let (pa, pb) = (m.positions[a as usize], m.positions[b as usize]);
|
||||
let on_rim = |p: Vec3| p.y.abs() == 1.0 && Vec2::new(p.x, p.z).length() > 0.5;
|
||||
if on_rim(pa) && on_rim(pb) && pa.y == pb.y {
|
||||
let (ka, kb) = (bits(pa), bits(pb));
|
||||
out.insert(if ka < kb { (ka, kb) } else { (kb, ka) });
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
};
|
||||
let (side_edges, cap_edges) = (edges(false), edges(true));
|
||||
assert_eq!(side_edges.len(), 2 * segs, "segs {segs}: side rim edges");
|
||||
assert!(side_edges.is_subset(&cap_edges), "segs {segs}: a side rim edge has no cap edge with the same end positions");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn material_ball_has_two_materials() {
|
||||
let m = material_ball();
|
||||
|
||||
+403
-125
@@ -1,32 +1,36 @@
|
||||
//! Automatic UV unwrapping for meshes imported without texture coordinates.
|
||||
//!
|
||||
//! Triangles are grouped into charts by flood fill across shared (welded) edges while each face
|
||||
//! normal stays within 60° of the chart's seed face, so every chart is a height field over its
|
||||
//! seed plane and projects onto it without flipping. Charts are rotated to their principal axes
|
||||
//! and shelf-packed per material into 0..1 with one uniform scale, so texel density is the same
|
||||
//! normal stays within 60° of the chart's seed face. Charts are rotated to their principal axes
|
||||
//! and shelf-packed per material into 0..1 with one uniform scale. Texel density is the same
|
||||
//! everywhere within a material.
|
||||
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
|
||||
use glam::{Vec2, Vec3};
|
||||
use glam::{DVec2, DVec3, Vec2, Vec3};
|
||||
|
||||
use crate::{GeomError, Mesh, Result};
|
||||
|
||||
/// Vertices an unwrap accepts, and the most it produces.
|
||||
const MAX_UNWRAP_VERTICES: usize = 20_000_000;
|
||||
/// Triangles an unwrap accepts, counting a triangle once for each submesh that lists it.
|
||||
const MAX_UNWRAP_TRIANGLES: usize = 4_000_000;
|
||||
|
||||
/// Faces of a chart stay within this angle of the seed face normal (cos 60°).
|
||||
const CHART_COS: f32 = 0.5;
|
||||
/// Packing never goes beyond this virtual resolution (texels per side).
|
||||
const MAX_PACK_RES: f32 = 65_536.0;
|
||||
|
||||
/// Welded vertex id per vertex: vertices at the same position (snapped to a grid of 1e-6 of
|
||||
/// the bounding diagonal) share an id. Ids are dense, in order of first appearance.
|
||||
pub fn weld_ids(positions: &[Vec3]) -> Vec<u32> {
|
||||
let (lo, hi) = positions.iter().fold((Vec3::splat(f32::MAX), Vec3::splat(f32::MIN)), |(lo, hi), p| (lo.min(*p), hi.max(*p)));
|
||||
let cell = ((hi - lo).length() * 1e-6).max(1e-12);
|
||||
let (lo, hi) =
|
||||
positions.iter().map(|p| p.as_dvec3()).fold((DVec3::splat(f64::MAX), DVec3::splat(f64::MIN)), |(lo, hi), p| (lo.min(p), hi.max(p)));
|
||||
let diagonal = (hi - lo).length();
|
||||
let cell = if diagonal > 0.0 && diagonal.is_finite() { diagonal * 1e-6 } else { 1.0 };
|
||||
let mut map: HashMap<[i64; 3], u32> = HashMap::with_capacity(positions.len());
|
||||
positions
|
||||
.iter()
|
||||
.map(|p| {
|
||||
let q = ((*p - lo) / cell).round();
|
||||
let q = ((p.as_dvec3() - lo) / cell).round();
|
||||
let next = map.len() as u32;
|
||||
*map.entry([q.x as i64, q.y as i64, q.z as i64]).or_insert(next)
|
||||
})
|
||||
@@ -44,62 +48,163 @@ pub fn all_triangles_degenerate(mesh: &Mesh) -> bool {
|
||||
})
|
||||
}
|
||||
|
||||
fn face_has_area(positions: [Vec3; 3]) -> bool {
|
||||
(0..3).any(|axis| {
|
||||
let next = (axis + 1) % 3;
|
||||
let [a, b, c] = positions.map(|position| [f64::from(position[axis]), f64::from(position[next])]);
|
||||
let products = [a[0] * b[1], b[0] * c[1], c[0] * a[1], -a[1] * b[0], -b[1] * c[0], -c[1] * a[0]];
|
||||
let (mut expansion, mut len) = ([0.0; 6], 0);
|
||||
for mut value in products {
|
||||
let mut kept = 0;
|
||||
for index in 0..len {
|
||||
let part = expansion[index];
|
||||
let sum = value + part;
|
||||
let part_virtual = sum - value;
|
||||
let value_virtual = sum - part_virtual;
|
||||
let error = (value - value_virtual) + (part - part_virtual);
|
||||
if error != 0.0 {
|
||||
expansion[kept] = error;
|
||||
kept += 1;
|
||||
}
|
||||
value = sum;
|
||||
}
|
||||
expansion[kept] = value;
|
||||
len = kept + 1;
|
||||
}
|
||||
expansion[..len].iter().any(|part| *part != 0.0)
|
||||
})
|
||||
}
|
||||
|
||||
struct Chart {
|
||||
material: usize,
|
||||
/// The seed face's first corner. Projections are taken relative to it, in `f64`, so they
|
||||
/// keep the chart's own detail wherever the chart lies.
|
||||
origin: DVec3,
|
||||
/// Projection basis (right-handed with the seed normal).
|
||||
t: Vec3,
|
||||
b: Vec3,
|
||||
t: DVec3,
|
||||
b: DVec3,
|
||||
/// Rotation to the chart's principal axes (cos, sin).
|
||||
rot: Vec2,
|
||||
lo: Vec2,
|
||||
hi: Vec2,
|
||||
/// Texel offset of the chart's packed rectangle and the material's scale and resolution.
|
||||
offset: Vec2,
|
||||
rot: DVec2,
|
||||
/// Bounds of the rotated chart. Charts are measured and packed in `f64`, where the extent of
|
||||
/// any chart of finite `f32` positions and the scale that packs it neither overflow nor
|
||||
/// round to zero.
|
||||
lo: DVec2,
|
||||
hi: DVec2,
|
||||
/// Texel offset of the chart's packed rectangle.
|
||||
offset: DVec2,
|
||||
}
|
||||
|
||||
impl Chart {
|
||||
fn local(&self, p: Vec3) -> Vec2 {
|
||||
let q = Vec2::new(p.dot(self.t), p.dot(self.b));
|
||||
Vec2::new(q.x * self.rot.x - q.y * self.rot.y, q.x * self.rot.y + q.y * self.rot.x)
|
||||
fn local(&self, p: Vec3) -> DVec2 {
|
||||
let d = p.as_dvec3() - self.origin;
|
||||
let q = DVec2::new(d.dot(self.t), d.dot(self.b));
|
||||
DVec2::new(q.x * self.rot.x - q.y * self.rot.y, q.x * self.rot.y + q.y * self.rot.x)
|
||||
}
|
||||
fn size(&self) -> Vec2 {
|
||||
(self.hi - self.lo).max(Vec2::ZERO)
|
||||
fn size(&self) -> DVec2 {
|
||||
(self.hi - self.lo).max(DVec2::ZERO)
|
||||
}
|
||||
}
|
||||
|
||||
/// The material each triangle is unwrapped for; triangles in no submesh count as material 0. Returns an error when submeshes of two
|
||||
/// materials share a triangle.
|
||||
fn triangle_materials(mesh: &Mesh) -> Result<Vec<usize>> {
|
||||
let mut material = vec![None; mesh.triangle_count()];
|
||||
for s in &mesh.submeshes {
|
||||
for t in (s.start / 3) as usize..((s.start as usize + s.count as usize) / 3) {
|
||||
if let Some(m) = material.get_mut(t) {
|
||||
if let Some(other) = *m
|
||||
&& other != s.material
|
||||
{
|
||||
return Err(GeomError::Invalid(format!("triangle {t} is in submeshes of materials {other} and {}", s.material)));
|
||||
}
|
||||
*m = Some(s.material);
|
||||
/// Area-weighted smooth normals over the index buffer, as [`Mesh::compute_normals`] computes
|
||||
/// them, returned instead of stored.
|
||||
fn smooth_normals(mesh: &Mesh) -> Vec<Vec3> {
|
||||
let mut normals = vec![DVec3::ZERO; mesh.positions.len()];
|
||||
for &[a, b, c] in mesh.indices.as_chunks::<3>().0 {
|
||||
let (a, b, c) = (a as usize, b as usize, c as usize);
|
||||
let (Some(pa), Some(pb), Some(pc)) = (mesh.positions.get(a), mesh.positions.get(b), mesh.positions.get(c)) else { continue };
|
||||
let face = (pb.as_dvec3() - pa.as_dvec3()).cross(pc.as_dvec3() - pa.as_dvec3());
|
||||
for v in [a, b, c] {
|
||||
if let Some(x) = normals.get_mut(v) {
|
||||
*x += face;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(material.into_iter().map(|m| m.unwrap_or(0)).collect())
|
||||
normals.into_iter().map(|v| v.try_normalize().map(|normal| normal.as_vec3()).unwrap_or(Vec3::Y)).collect()
|
||||
}
|
||||
|
||||
/// Replace the UVs of `mesh` with an automatic non-overlapping layout: each material gets its
|
||||
/// own 0..1 space with charts at least `padding_texels` (minimum 1) away from each other and
|
||||
/// the borders at `resolution`. Vertices are split at chart borders; tangents are recomputed.
|
||||
/// Returns the number of charts, or an error, before any change to the mesh, when submeshes of
|
||||
/// two materials share a triangle.
|
||||
pub fn auto_unwrap(mesh: &mut Mesh, padding_texels: f32, resolution: u32) -> Result<usize> {
|
||||
/// The checks [`auto_unwrap`] makes before it changes anything. The size limits come first.
|
||||
fn check_input(mesh: &Mesh) -> Result<()> {
|
||||
if mesh.positions.len() > MAX_UNWRAP_VERTICES {
|
||||
return Err(GeomError::Invalid(format!("mesh has {} vertices; unwrapping accepts at most {MAX_UNWRAP_VERTICES}", mesh.positions.len())));
|
||||
}
|
||||
if mesh.triangle_count() > MAX_UNWRAP_TRIANGLES {
|
||||
return Err(GeomError::Invalid(format!("mesh has {} triangles; unwrapping accepts at most {MAX_UNWRAP_TRIANGLES}", mesh.triangle_count())));
|
||||
}
|
||||
let listed = mesh.submeshes.iter().fold(0u64, |sum, s| sum.saturating_add(u64::from(s.count / 3)));
|
||||
if listed > MAX_UNWRAP_TRIANGLES as u64 {
|
||||
return Err(GeomError::Invalid(format!("submeshes list {listed} triangles; unwrapping accepts at most {MAX_UNWRAP_TRIANGLES}")));
|
||||
}
|
||||
mesh.validate_indices()?;
|
||||
for s in &mesh.submeshes {
|
||||
if !s.start.is_multiple_of(3) || !s.count.is_multiple_of(3) {
|
||||
return Err(GeomError::Invalid(format!("submesh {} is not triangle-aligned", s.name)));
|
||||
}
|
||||
if u64::from(s.start) + u64::from(s.count) > mesh.indices.len() as u64 || s.material >= mesh.materials.len().max(1) {
|
||||
return Err(GeomError::Invalid(format!("submesh {} is out of range", s.name)));
|
||||
}
|
||||
}
|
||||
if mesh.positions.iter().any(|p| !p.is_finite()) {
|
||||
return Err(GeomError::Invalid("mesh has non-finite positions".into()));
|
||||
}
|
||||
if mesh.normals.len() == mesh.positions.len() && mesh.normals.iter().any(|v| !v.is_finite()) {
|
||||
return Err(GeomError::Invalid("mesh has non-finite normals".into()));
|
||||
}
|
||||
if !mesh.colors.is_empty() && (mesh.colors.len() != mesh.positions.len() || mesh.colors.iter().any(|c| !c.is_finite())) {
|
||||
return Err(GeomError::Invalid("mesh colors are not one finite color per vertex".into()));
|
||||
}
|
||||
if all_triangles_degenerate(mesh) {
|
||||
return Err(GeomError::Invalid("every triangle of the mesh is degenerate".into()));
|
||||
}
|
||||
let material = triangle_materials(mesh)?;
|
||||
if mesh.normals.len() != mesh.positions.len() {
|
||||
mesh.compute_normals();
|
||||
if !mesh.indices.is_empty()
|
||||
&& mesh.indices.as_chunks::<3>().0.iter().all(|vertices| !face_has_area(vertices.map(|vertex| mesh.positions[vertex as usize])))
|
||||
{
|
||||
return Err(GeomError::Invalid("every triangle of the mesh is degenerate".into()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The material of every triangle. Each material is packed into its own 0..1 square, so a
|
||||
/// triangle that submeshes of two materials list would be laid out over another chart of one of
|
||||
/// them, and is an error. Every triangle must be listed by a submesh.
|
||||
fn face_materials(mesh: &Mesh) -> Result<Vec<usize>> {
|
||||
let n = mesh.triangle_count();
|
||||
let mut material = vec![usize::MAX; n];
|
||||
for s in &mesh.submeshes {
|
||||
let end = (u64::from(s.start) + u64::from(s.count)) / 3;
|
||||
for t in (s.start / 3) as usize..(end as usize).min(n) {
|
||||
if let Some(m) = material.get_mut(t) {
|
||||
if *m != usize::MAX && *m != s.material {
|
||||
return Err(GeomError::Invalid(format!("triangle {t} is in submeshes of materials {} and {}", *m, s.material)));
|
||||
}
|
||||
*m = s.material;
|
||||
}
|
||||
}
|
||||
}
|
||||
if material.contains(&usize::MAX) {
|
||||
return Err(GeomError::Invalid("submeshes do not cover every triangle".into()));
|
||||
}
|
||||
Ok(material)
|
||||
}
|
||||
|
||||
/// Replace the UVs of `mesh` with an automatic non-overlapping layout: each material gets its
|
||||
/// own 0..1 space with charts at least `padding_texels` (minimum 1, which a NaN counts as) away
|
||||
/// from each other and the borders at `resolution`. Vertices are split at chart borders;
|
||||
/// tangents are recomputed. Returns the number of charts.
|
||||
/// The effective resolution is at least 16. A layout that cannot fit with the requested
|
||||
/// padding returns an error without changing the mesh.
|
||||
///
|
||||
/// A mesh that fails a check is returned unchanged: indices, triangle-aligned submesh ranges
|
||||
/// that cover every triangle, materials, no
|
||||
/// triangle listed by submeshes of two materials, finite positions, finite normals and colors
|
||||
/// when it has them, at least one triangle that is not degenerate, and the size limits (20
|
||||
/// million vertices; 4 million triangles, counting a triangle once for each submesh that lists
|
||||
/// it). The limits are checked before any other work. More than 20 million new vertices is an
|
||||
/// error as well.
|
||||
pub fn auto_unwrap(mesh: &mut Mesh, padding_texels: f32, resolution: u32) -> Result<usize> {
|
||||
check_input(mesh)?;
|
||||
// Kept apart from the mesh until the layout is packed, so an error leaves the mesh as it was.
|
||||
let computed_normals = if mesh.normals.len() != mesh.positions.len() { Some(smooth_normals(mesh)) } else { None };
|
||||
let old_normals = computed_normals.as_deref().unwrap_or(&mesh.normals);
|
||||
let n = mesh.triangle_count();
|
||||
let weld = weld_ids(&mesh.positions);
|
||||
let pos = |v: usize| mesh.positions.get(v).copied().unwrap_or_default();
|
||||
@@ -109,11 +214,12 @@ pub fn auto_unwrap(mesh: &mut Mesh, padding_texels: f32, resolution: u32) -> Res
|
||||
let mut normal: Vec<Option<Vec3>> = Vec::with_capacity(n);
|
||||
let mut area = Vec::with_capacity(n);
|
||||
for t in 0..n {
|
||||
let [a, b, c] = mesh.tri(t).unwrap_or([0; 3]);
|
||||
let cr = (pos(b) - pos(a)).cross(pos(c) - pos(a));
|
||||
let [a, b, c] = mesh.tri(t).unwrap_or([0; 3]).map(|v| pos(v).as_dvec3());
|
||||
let cr = (b - a).cross(c - a);
|
||||
area.push(cr.length() * 0.5);
|
||||
normal.push(cr.try_normalize());
|
||||
normal.push(cr.try_normalize().map(|n| n.as_vec3()));
|
||||
}
|
||||
let material = face_materials(mesh)?;
|
||||
|
||||
// Manifold edge adjacency over welded vertices: edge → (face, face, count).
|
||||
let mut edges: HashMap<(u32, u32), (u32, u32, u8)> = HashMap::with_capacity(n * 2);
|
||||
@@ -151,7 +257,20 @@ pub fn auto_unwrap(mesh: &mut Mesh, padding_texels: f32, resolution: u32) -> Res
|
||||
let id = charts.len() as u32;
|
||||
let sn = normal[seed].unwrap_or(Vec3::Z);
|
||||
let t = sn.any_orthonormal_vector();
|
||||
charts.push(Chart { material: material[seed], t, b: sn.cross(t), rot: Vec2::X, lo: Vec2::ZERO, hi: Vec2::ZERO, offset: Vec2::ZERO });
|
||||
let b = sn.cross(t);
|
||||
// Relative to the seed's first corner, so the rounding of a projection follows the
|
||||
// chart's size rather than its distance from the origin.
|
||||
let origin = pos(mesh.tri(seed).unwrap_or([0; 3])[0]).as_dvec3();
|
||||
charts.push(Chart {
|
||||
material: material[seed],
|
||||
origin,
|
||||
t: t.as_dvec3(),
|
||||
b: b.as_dvec3(),
|
||||
rot: DVec2::X,
|
||||
lo: DVec2::ZERO,
|
||||
hi: DVec2::ZERO,
|
||||
offset: DVec2::ZERO,
|
||||
});
|
||||
chart_of[seed] = id;
|
||||
queue.push_back(seed);
|
||||
while let Some(f) = queue.pop_front() {
|
||||
@@ -167,30 +286,30 @@ pub fn auto_unwrap(mesh: &mut Mesh, padding_texels: f32, resolution: u32) -> Res
|
||||
}
|
||||
}
|
||||
|
||||
// Principal axes and bounds of every chart.
|
||||
let mut cov = vec![(Vec2::ZERO, [0.0f64; 3], 0usize); charts.len()];
|
||||
// Principal axes and bounds of every chart, in f64 from the positions as given.
|
||||
let mut cov = vec![(DVec2::ZERO, [0.0f64; 3], 0usize); charts.len()];
|
||||
for (t, &c) in chart_of.iter().enumerate() {
|
||||
let c = c as usize;
|
||||
for v in mesh.tri(t).unwrap_or([0; 3]) {
|
||||
if let (Some(ch), Some(acc)) = (charts.get(c), cov.get_mut(c)) {
|
||||
let q = ch.local(pos(v));
|
||||
acc.0 += q;
|
||||
acc.1[0] += (q.x * q.x) as f64;
|
||||
acc.1[1] += (q.y * q.y) as f64;
|
||||
acc.1[2] += (q.x * q.y) as f64;
|
||||
acc.1[0] += q.x * q.x;
|
||||
acc.1[1] += q.y * q.y;
|
||||
acc.1[2] += q.x * q.y;
|
||||
acc.2 += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (ch, (sum, m, k)) in charts.iter_mut().zip(&cov) {
|
||||
let k = (*k).max(1) as f64;
|
||||
let (mx, my) = (sum.x as f64 / k, sum.y as f64 / k);
|
||||
let (mx, my) = (sum.x / k, sum.y / k);
|
||||
let (cxx, cyy, cxy) = (m[0] / k - mx * mx, m[1] / k - my * my, m[2] / k - mx * my);
|
||||
let angle = 0.5 * (2.0 * cxy).atan2(cxx - cyy);
|
||||
// Rotate so the principal axis lies along x.
|
||||
ch.rot = Vec2::new((-angle).cos() as f32, (-angle).sin() as f32);
|
||||
ch.lo = Vec2::splat(f32::MAX);
|
||||
ch.hi = Vec2::splat(f32::MIN);
|
||||
ch.rot = DVec2::new((-angle).cos(), (-angle).sin());
|
||||
ch.lo = DVec2::splat(f64::MAX);
|
||||
ch.hi = DVec2::splat(f64::MIN);
|
||||
}
|
||||
for (t, &c) in chart_of.iter().enumerate() {
|
||||
let c = c as usize;
|
||||
@@ -205,20 +324,22 @@ pub fn auto_unwrap(mesh: &mut Mesh, padding_texels: f32, resolution: u32) -> Res
|
||||
for ch in &mut charts {
|
||||
if ch.size().y > ch.size().x {
|
||||
// Quarter turn (x, y) → (y, −x) so shelves stay low.
|
||||
ch.rot = Vec2::new(ch.rot.y, -ch.rot.x);
|
||||
ch.rot = DVec2::new(ch.rot.y, -ch.rot.x);
|
||||
let (lo, hi) = (ch.lo, ch.hi);
|
||||
ch.lo = Vec2::new(lo.y, -hi.x);
|
||||
ch.hi = Vec2::new(hi.y, -lo.x);
|
||||
ch.lo = DVec2::new(lo.y, -hi.x);
|
||||
ch.hi = DVec2::new(hi.y, -lo.x);
|
||||
}
|
||||
}
|
||||
|
||||
// Pack each material's charts into its own 0..1 square.
|
||||
let pad = padding_texels.max(1.0);
|
||||
let mut scale = HashMap::new();
|
||||
let mats: std::collections::BTreeSet<usize> = charts.iter().map(|c| c.material).collect();
|
||||
for m in mats {
|
||||
let ids: Vec<usize> = (0..charts.len()).filter(|i| charts[*i].material == m).collect();
|
||||
let sizes: Vec<Vec2> = ids.iter().map(|i| charts[*i].size()).collect();
|
||||
let mut by_material: std::collections::BTreeMap<usize, Vec<usize>> = std::collections::BTreeMap::new();
|
||||
for (id, chart) in charts.iter().enumerate() {
|
||||
by_material.entry(chart.material).or_default().push(id);
|
||||
}
|
||||
for (m, ids) in by_material {
|
||||
let sizes: Vec<DVec2> = ids.iter().map(|i| charts[*i].size()).collect();
|
||||
let (s, res, offsets) = pack(&sizes, resolution.max(16) as f32, pad)?;
|
||||
for (i, o) in ids.iter().zip(offsets) {
|
||||
charts[*i].offset = o;
|
||||
@@ -227,52 +348,67 @@ pub fn auto_unwrap(mesh: &mut Mesh, padding_texels: f32, resolution: u32) -> Res
|
||||
}
|
||||
|
||||
// Rebuild vertices: one per (vertex, chart).
|
||||
let mut remap: HashMap<(u32, u32), u32> = HashMap::with_capacity(mesh.positions.len() * 2);
|
||||
let mut remap: HashMap<(u32, u32), u32> = HashMap::with_capacity(mesh.positions.len().saturating_mul(2).min(mesh.indices.len()));
|
||||
let (mut positions, mut normals, mut uvs, mut colors) = (Vec::new(), Vec::new(), Vec::new(), Vec::new());
|
||||
let mut indices = Vec::with_capacity(mesh.indices.len());
|
||||
for (t, &c) in chart_of.iter().enumerate() {
|
||||
let Some(ch) = charts.get(c as usize) else { continue };
|
||||
let (s, res) = scale.get(&ch.material).copied().unwrap_or((0.0, 1.0));
|
||||
let (s, res) = scale.get(&ch.material).copied().unwrap_or((0.0, 1.0f32));
|
||||
for v in mesh.tri(t).unwrap_or([0; 3]) {
|
||||
let idx = *remap.entry((v as u32, c)).or_insert_with(|| {
|
||||
let q = ch.local(pos(v));
|
||||
// Chart y points up; UV v points down the image.
|
||||
let texel = ch.offset + Vec2::splat(pad) + Vec2::new(q.x - ch.lo.x, ch.hi.y - q.y) * s;
|
||||
let texel = ch.offset + DVec2::splat(f64::from(pad)) + DVec2::new(q.x - ch.lo.x, ch.hi.y - q.y) * s;
|
||||
positions.push(pos(v));
|
||||
normals.push(mesh.normals.get(v).copied().unwrap_or(Vec3::Y));
|
||||
normals.push(old_normals.get(v).copied().unwrap_or(Vec3::Y));
|
||||
if let Some(c) = mesh.colors.get(v) {
|
||||
colors.push(*c);
|
||||
}
|
||||
uvs.push((texel / res).clamp(Vec2::ZERO, Vec2::ONE));
|
||||
uvs.push((texel / f64::from(res)).as_vec2().clamp(Vec2::ZERO, Vec2::ONE));
|
||||
(positions.len() - 1) as u32
|
||||
});
|
||||
indices.push(idx);
|
||||
}
|
||||
if positions.len() > MAX_UNWRAP_VERTICES {
|
||||
return Err(GeomError::Invalid(format!("unwrapping would produce more than {MAX_UNWRAP_VERTICES} vertices")));
|
||||
}
|
||||
}
|
||||
mesh.positions = positions;
|
||||
mesh.normals = normals;
|
||||
mesh.uvs = uvs;
|
||||
mesh.colors = colors;
|
||||
mesh.indices = indices;
|
||||
let charts = charts.len();
|
||||
// The new arrays replace the mesh's only once the tangents and the final check have passed.
|
||||
let old = (
|
||||
std::mem::replace(&mut mesh.positions, positions),
|
||||
std::mem::replace(&mut mesh.normals, normals),
|
||||
std::mem::replace(&mut mesh.uvs, uvs),
|
||||
std::mem::replace(&mut mesh.colors, colors),
|
||||
std::mem::replace(&mut mesh.indices, indices),
|
||||
std::mem::take(&mut mesh.tangents),
|
||||
);
|
||||
mesh.compute_tangents();
|
||||
mesh.validate()?;
|
||||
Ok(charts.len())
|
||||
if let Err(e) = mesh.validate() {
|
||||
(mesh.positions, mesh.normals, mesh.uvs, mesh.colors, mesh.indices, mesh.tangents) = old;
|
||||
return Err(e);
|
||||
}
|
||||
Ok(charts)
|
||||
}
|
||||
|
||||
/// Shelf-pack rectangles of world `sizes` (each grown by `pad` texels per side) into a square of
|
||||
/// `res` texels with the largest uniform scale that fits. Returns (texels per world unit,
|
||||
/// resolution used, texel offset per rectangle). The resolution doubles when the padding alone
|
||||
/// cannot fit (very many charts), so the result always fits in 0..1.
|
||||
fn pack(sizes: &[Vec2], mut res: f32, pad: f32) -> Result<(f32, f32, Vec<Vec2>)> {
|
||||
/// resolution used, texel offset per rectangle). A layout without room for a positive scale
|
||||
/// returns an error. The sizes and the scale are in
|
||||
/// `f64`, where the scale of any chart of finite `f32` positions is finite and above zero.
|
||||
fn pack(sizes: &[DVec2], res: f32, pad: f32) -> Result<(f64, f32, Vec<DVec2>)> {
|
||||
let mut order: Vec<usize> = (0..sizes.len()).collect();
|
||||
order.sort_by(|a, b| sizes[*b].y.total_cmp(&sizes[*a].y));
|
||||
let place = |s: f32, res: f32| -> Option<Vec<Vec2>> {
|
||||
let mut out = vec![Vec2::ZERO; sizes.len()];
|
||||
let (mut x, mut y, mut shelf) = (0.0f32, 0.0f32, 0.0f32);
|
||||
let mut out = vec![DVec2::ZERO; sizes.len()];
|
||||
let pad = f64::from(pad);
|
||||
// Shelf-place every rectangle at scale `s` into `out`; false when they do not fit.
|
||||
let place = |s: f64, res: f32, out: &mut [DVec2]| -> bool {
|
||||
let res = f64::from(res);
|
||||
let (mut x, mut y, mut shelf) = (0.0f64, 0.0f64, 0.0f64);
|
||||
for &i in &order {
|
||||
let r = sizes[i] * s + Vec2::splat(2.0 * pad);
|
||||
let r = sizes[i] * s + DVec2::splat(2.0 * pad);
|
||||
if r.x > res {
|
||||
return None;
|
||||
return false;
|
||||
}
|
||||
if x + r.x > res {
|
||||
y += shelf;
|
||||
@@ -280,36 +416,44 @@ fn pack(sizes: &[Vec2], mut res: f32, pad: f32) -> Result<(f32, f32, Vec<Vec2>)>
|
||||
shelf = 0.0;
|
||||
}
|
||||
if y + r.y > res {
|
||||
return None;
|
||||
return false;
|
||||
}
|
||||
if let Some(o) = out.get_mut(i) {
|
||||
*o = DVec2::new(x, y);
|
||||
}
|
||||
out[i] = Vec2::new(x, y);
|
||||
x += r.x;
|
||||
shelf = shelf.max(r.y);
|
||||
}
|
||||
Some(out)
|
||||
true
|
||||
};
|
||||
while place(0.0, res).is_none() {
|
||||
res *= 2.0;
|
||||
if res > MAX_PACK_RES {
|
||||
return Err(GeomError::Invalid("too many UV charts to pack".into()));
|
||||
let largest = sizes.iter().map(|s| s.max_element()).fold(0.0f64, f64::max);
|
||||
if place(0.0, res, &mut out) {
|
||||
if largest <= 0.0 {
|
||||
return Ok((0.0, res, out));
|
||||
}
|
||||
let (mut lo, mut hi) = (0.0f64, (f64::from(res) - 2.0 * pad).max(0.0) / largest);
|
||||
// Halve the upper bound until a positive scale fits, so the refinement below starts
|
||||
// from a feasible lower bound however far below the first guess the answer lies.
|
||||
while hi > 0.0 {
|
||||
if place(hi, res, &mut out) {
|
||||
lo = hi;
|
||||
break;
|
||||
}
|
||||
hi *= 0.5;
|
||||
}
|
||||
hi = if lo > 0.0 { (2.0 * lo).min((f64::from(res) - 2.0 * pad).max(0.0) / largest) } else { hi };
|
||||
for _ in 0..40 {
|
||||
if hi - lo <= lo * 1e-4 {
|
||||
break;
|
||||
}
|
||||
let mid = 0.5 * (lo + hi);
|
||||
if place(mid, res, &mut out) { lo = mid } else { hi = mid }
|
||||
}
|
||||
if lo > 0.0 && place(lo, res, &mut out) {
|
||||
return Ok((lo, res, out));
|
||||
}
|
||||
}
|
||||
let largest = sizes.iter().map(|s| s.max_element()).fold(0.0f32, f32::max);
|
||||
if largest <= 0.0 {
|
||||
return Ok((0.0, res, place(0.0, res).unwrap_or_default()));
|
||||
}
|
||||
let (mut lo, mut hi) = (0.0f32, (res - 2.0 * pad).max(0.0) / largest);
|
||||
if place(hi, res).is_some() {
|
||||
lo = hi;
|
||||
}
|
||||
for _ in 0..40 {
|
||||
if hi - lo <= lo * 1e-4 {
|
||||
break;
|
||||
}
|
||||
let mid = 0.5 * (lo + hi);
|
||||
if place(mid, res).is_some() { lo = mid } else { hi = mid }
|
||||
}
|
||||
Ok((lo, res, place(lo, res).unwrap_or_default()))
|
||||
Err(GeomError::Invalid("UV charts cannot fit with the requested padding and resolution".into()))
|
||||
}
|
||||
|
||||
impl Mesh {
|
||||
@@ -328,6 +472,81 @@ impl Mesh {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn tiny_quads_keep_their_shared_chart_edge() {
|
||||
let mut mesh = quad();
|
||||
for position in &mut mesh.positions {
|
||||
*position *= 2.0_f32.powi(-42);
|
||||
}
|
||||
assert_eq!(auto_unwrap(&mut mesh, 4.0, 16).unwrap(), 1);
|
||||
assert_eq!(weld_ids(&[Vec3::ONE; 4]), vec![0; 4]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nonempty_all_collinear_meshes_are_rejected_unchanged() {
|
||||
for positions in [vec![Vec3::ZERO, Vec3::X, Vec3::X * 2.0], {
|
||||
let d = Vec3::new(1.0, 17.0, 0.0);
|
||||
vec![Vec3::ZERO, d * (3.0 * 2.0_f32.powi(-49)), d]
|
||||
}] {
|
||||
let mut mesh = Mesh::from_parts(positions, Some(vec![Vec3::Z; 3]), Vec::new(), vec![0, 1, 2], "m").unwrap();
|
||||
let before = mesh.clone();
|
||||
assert!(auto_unwrap(&mut mesh, 4.0, 256).is_err());
|
||||
assert_eq!(mesh, before);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_normals_keep_tiny_and_large_face_directions() {
|
||||
for scale in [1e-25, 1e25] {
|
||||
let mesh = Mesh { positions: vec![Vec3::ZERO, Vec3::Y * scale, Vec3::Z * scale], indices: vec![0, 1, 2], ..Mesh::default() };
|
||||
assert_eq!(smooth_normals(&mesh), vec![Vec3::X; 3], "scale={scale}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn incomplete_or_unaligned_submeshes_leave_the_layout_unchanged() {
|
||||
let original = primitives::cube(1.0).unwrap();
|
||||
for variant in 0..3 {
|
||||
let mut mesh = original.clone();
|
||||
match variant {
|
||||
0 => mesh.submeshes.clear(),
|
||||
1 => mesh.submeshes[0].count -= 3,
|
||||
_ => {
|
||||
mesh.submeshes[0].start = 1;
|
||||
mesh.submeshes[0].count = 3;
|
||||
}
|
||||
}
|
||||
let before = mesh.clone();
|
||||
assert!(auto_unwrap(&mut mesh, 4.0, 256).is_err(), "variant {variant}");
|
||||
assert_eq!(mesh, before);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packing_preserves_the_requested_resolution_and_border() {
|
||||
assert!(pack(&[DVec2::ONE; 2000], 128.0, 4.0).is_err());
|
||||
assert!(pack(&[DVec2::ONE], 16.0, 8.0).is_err());
|
||||
let (_, resolution, offsets) = pack(&[DVec2::ONE; 2], 128.0, 4.0).unwrap();
|
||||
assert_eq!(resolution, 128.0);
|
||||
assert_eq!((offsets[0].x + 4.0) / f64::from(resolution) * 128.0, 4.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packing_finds_a_small_scale_far_below_the_first_guess() {
|
||||
let pad = 1.0 + 262_657.0 / 8_388_608.0;
|
||||
let (scale, _, _) = pack(&vec![DVec2::ONE; 511 * 511], 1054.0, pad as f32).unwrap();
|
||||
assert!(scale > 0.0);
|
||||
assert!(pack(&vec![DVec2::ONE; 600 * 600], 1054.0, pad as f32).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn weld_grid_keeps_distinct_extreme_positions() {
|
||||
let positions = [Vec3::splat(-f32::MAX), Vec3::ZERO, Vec3::splat(f32::MAX)];
|
||||
assert_eq!(weld_ids(&positions), vec![0, 1, 2]);
|
||||
}
|
||||
|
||||
use glam::Vec4;
|
||||
|
||||
use super::*;
|
||||
use crate::{UvGBuffer, primitives};
|
||||
|
||||
@@ -367,23 +586,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn triangles_in_two_materials_are_rejected_unchanged() {
|
||||
// Two congruent triangles in material 0; material 1 also lists the first.
|
||||
let p = vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::Z * 5.0, Vec3::Z * 5.0 + Vec3::X, Vec3::Z * 5.0 + Vec3::Y];
|
||||
let mut m = Mesh::from_parts(p, None, Vec::new(), vec![0, 1, 2, 3, 4, 5], "a").unwrap();
|
||||
m.materials.push("b".into());
|
||||
m.submeshes.push(crate::SubMesh { name: "b".into(), material: 1, start: 0, count: 3 });
|
||||
let before = m.clone();
|
||||
assert!(auto_unwrap(&mut m, 2.0, 64).is_err());
|
||||
assert_eq!(m, before);
|
||||
// The same material listed twice is not a conflict.
|
||||
m.submeshes[1].material = 0;
|
||||
assert_eq!(auto_unwrap(&mut m, 2.0, 64).unwrap(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn many_tiny_charts_still_fit() {
|
||||
// 2000 disconnected triangles: the packer grows its virtual resolution.
|
||||
fn many_tiny_charts_require_room_at_the_requested_resolution() {
|
||||
let mut p = Vec::new();
|
||||
let mut idx = Vec::new();
|
||||
for i in 0..2000u32 {
|
||||
@@ -392,7 +595,10 @@ mod tests {
|
||||
idx.extend([i * 3, i * 3 + 1, i * 3 + 2]);
|
||||
}
|
||||
let mut m = Mesh::from_parts(p, None, Vec::new(), idx, "m").unwrap();
|
||||
auto_unwrap(&mut m, 4.0, 128).unwrap();
|
||||
let before = m.clone();
|
||||
assert!(auto_unwrap(&mut m, 4.0, 128).is_err());
|
||||
assert_eq!(m, before);
|
||||
auto_unwrap(&mut m, 4.0, 512).unwrap();
|
||||
assert!(m.uvs.iter().all(|uv| (0.0..=1.0).contains(&uv.x) && (0.0..=1.0).contains(&uv.y)));
|
||||
}
|
||||
|
||||
@@ -409,4 +615,76 @@ mod tests {
|
||||
assert!(all_triangles_degenerate(&point));
|
||||
assert!(auto_unwrap(&mut point, 4.0, 256).is_err());
|
||||
}
|
||||
|
||||
fn quad() -> Mesh {
|
||||
let p = vec![Vec3::ZERO, Vec3::X, Vec3::new(1.0, 1.0, 0.0), Vec3::Y];
|
||||
Mesh::from_parts(p, None, Vec::new(), vec![0, 1, 2, 0, 2, 3], "m").unwrap()
|
||||
}
|
||||
|
||||
fn submesh(material: usize, start: u32, count: u32) -> crate::SubMesh {
|
||||
crate::SubMesh { name: "s".into(), material, start, count }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejected_meshes_are_left_unchanged() {
|
||||
let mut two_materials = quad();
|
||||
two_materials.materials = vec!["a".into(), "b".into()];
|
||||
two_materials.submeshes = vec![submesh(0, 0, 6), submesh(1, 3, 3)];
|
||||
let mut nan_normal = quad();
|
||||
nan_normal.normals = vec![Vec3::INFINITY; 4];
|
||||
let mut short_colors = quad();
|
||||
short_colors.colors = vec![Vec4::ONE; 2];
|
||||
let mut range = quad();
|
||||
range.submeshes = vec![submesh(0, 6, 3)];
|
||||
let mut nan_position = quad();
|
||||
nan_position.positions[2] = Vec3::INFINITY;
|
||||
for (name, mut m) in [
|
||||
("two materials", two_materials),
|
||||
("infinite normal", nan_normal),
|
||||
("short colors", short_colors),
|
||||
("range", range),
|
||||
("infinite position", nan_position),
|
||||
] {
|
||||
m.uvs.clear();
|
||||
let before = m.clone();
|
||||
assert!(auto_unwrap(&mut m, 4.0, 256).is_err(), "{name}");
|
||||
assert_eq!(m, before, "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn size_limits_are_checked_before_anything_else() {
|
||||
// Indices out of range as well: the limit is the error reported.
|
||||
let mut m = quad();
|
||||
m.indices = vec![0, 1, 9];
|
||||
m.submeshes = vec![submesh(0, 0, u32::MAX)];
|
||||
let before = m.clone();
|
||||
let message = auto_unwrap(&mut m, 4.0, 256).unwrap_err().to_string();
|
||||
assert!(message.contains("accepts at most"), "{message}");
|
||||
assert_eq!(m, before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn small_charts_far_from_the_origin_keep_their_shape() {
|
||||
// A right triangle with 16-unit legs at 1e8, where an f32 position is 8 units apart.
|
||||
let o = Vec3::splat(1e8);
|
||||
let p = vec![o, o + Vec3::X * 16.0, o + Vec3::Y * 16.0];
|
||||
let mut m = Mesh::from_parts(p, None, Vec::new(), vec![0, 1, 2], "m").unwrap();
|
||||
auto_unwrap(&mut m, 4.0, 256).unwrap();
|
||||
let (a, b, c) = (m.uvs[m.indices[0] as usize], m.uvs[m.indices[1] as usize], m.uvs[m.indices[2] as usize]);
|
||||
let (e1, e2) = (b - a, c - a);
|
||||
assert!(e1.length() > 0.1 && (e1.length() - e2.length()).abs() < 1e-3, "legs {e1} and {e2}");
|
||||
assert!(e1.dot(e2).abs() < 1e-3, "legs {e1} and {e2} are not at a right angle");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn padding_that_fills_the_square_does_not_replace_the_mesh() {
|
||||
let mut m = Mesh::from_parts(vec![Vec3::ZERO, Vec3::X, Vec3::Y], None, Vec::new(), vec![0, 1, 2], "m").unwrap();
|
||||
let before = m.clone();
|
||||
assert!(auto_unwrap(&mut m, 128.0, 256).is_err());
|
||||
assert_eq!(m, before);
|
||||
auto_unwrap(&mut m, 128.0, 512).unwrap();
|
||||
let (a, b, c) = (m.uvs[m.indices[0] as usize], m.uvs[m.indices[1] as usize], m.uvs[m.indices[2] as usize]);
|
||||
assert!((b - a).length() > 1e-4 && (c - a).length() > 1e-4, "uvs {a} {b} {c}");
|
||||
}
|
||||
}
|
||||
@@ -419,6 +419,7 @@ fn xmp_values(xmp: &str, key: &str) -> Vec<(usize, usize)> {
|
||||
let mut out = Vec::new();
|
||||
let mut from = 0;
|
||||
while let Some(k) = xmp.get(from..).and_then(|s| s.find(key)).map(|k| k + from) {
|
||||
searched(k + key.len() - from);
|
||||
from = k + key.len();
|
||||
// An attribute or an opening tag of exactly this name (not `</key>`, not `xkey`).
|
||||
if !xmp.get(..k).and_then(|h| h.chars().next_back()).is_some_and(|c| c == '<' || c.is_ascii_whitespace()) {
|
||||
@@ -443,13 +444,34 @@ fn xmp_values(xmp: &str, key: &str) -> Vec<(usize, usize)> {
|
||||
// attribute re-ran this full-suffix `find(close)` for every occurrence, which is
|
||||
// quadratic in the packet size. A missing close means the value is unterminated, so
|
||||
// no later value can parse either; stop scanning in that case.
|
||||
let Some(len) = value.find(close) else { break };
|
||||
let Some(len) = value.find(close) else {
|
||||
// the search read the rest of the packet, and no key search follows
|
||||
searched(value.len());
|
||||
from = xmp.len();
|
||||
break;
|
||||
};
|
||||
searched(len + close.len_utf8());
|
||||
out.push((start, start + len));
|
||||
from = start + len + close.len_utf8();
|
||||
}
|
||||
searched(xmp.len().saturating_sub(from));
|
||||
out
|
||||
}
|
||||
|
||||
// The bytes of the packet `xmp_values` searches for a key or a closing quote, on this thread.
|
||||
#[cfg(test)]
|
||||
std::thread_local! {
|
||||
static SEARCHED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn searched(count: usize) {
|
||||
#[cfg(test)]
|
||||
SEARCHED.with(|searched| searched.set(searched.get().saturating_add(count)));
|
||||
#[cfg(not(test))]
|
||||
let _ = count;
|
||||
}
|
||||
|
||||
/// An XMP rational (`300/1`) or plain number.
|
||||
fn xmp_number(s: &str) -> Option<f64> {
|
||||
let s = s.trim();
|
||||
@@ -780,3 +802,22 @@ pub fn resolution(exif: Option<&[u8]>, xmp: Option<&str>) -> Option<(f32, f32)>
|
||||
|
||||
#[cfg(test)]
|
||||
mod complexity_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod xmp_scan_tests {
|
||||
use super::*;
|
||||
|
||||
/// Property-like text repeated through a packet is searched once: each property's values are
|
||||
/// found in one pass, not a search of the rest of the packet from every occurrence.
|
||||
#[test]
|
||||
fn repeated_property_text_is_searched_once_for_each_property() {
|
||||
let decoys = " tiff:ResolutionUnit>".repeat(50_000);
|
||||
for key in [XMP_X, XMP_Y, XMP_UNIT] {
|
||||
SEARCHED.with(|searched| searched.set(0));
|
||||
let _ = xmp_values(&decoys, key);
|
||||
let read = SEARCHED.with(std::cell::Cell::get);
|
||||
assert!(read <= decoys.len(), "{key}: {read} bytes searched in {}", decoys.len());
|
||||
}
|
||||
assert_eq!(xmp_resolution(&decoys), None);
|
||||
}
|
||||
}
|
||||
+38
-14
@@ -567,7 +567,7 @@ fn collect_description(d: &Node, prefix: &str, props: &mut BTreeMap<String, Vec<
|
||||
*truncated = true;
|
||||
continue;
|
||||
}
|
||||
let key = format!("{prefix}{k}");
|
||||
let key = build_path(format!("{prefix}{k}"));
|
||||
if take_key_bytes(&key, budget, truncated) {
|
||||
props.entry(key).or_default().push(v.clone());
|
||||
}
|
||||
@@ -577,6 +577,20 @@ fn collect_description(d: &Node, prefix: &str, props: &mut BTreeMap<String, Vec<
|
||||
}
|
||||
}
|
||||
|
||||
// The bytes of every property path `collect_description` and `collect_property` build, on this
|
||||
// thread.
|
||||
#[cfg(test)]
|
||||
std::thread_local! {
|
||||
static PATH_BYTES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn build_path(path: String) -> String {
|
||||
#[cfg(test)]
|
||||
PATH_BYTES.with(|bytes| bytes.set(bytes.get().saturating_add(path.len())));
|
||||
path
|
||||
}
|
||||
|
||||
/// Charge one flattened key's length to the key budget; `false` when the budget is spent (the
|
||||
/// property is then left out, like other elements a limit has cut) and the map is marked partial.
|
||||
fn take_key_bytes(key: &str, budget: &mut usize, dropped: &mut bool) -> bool {
|
||||
@@ -596,8 +610,11 @@ fn collect_property(p: &Node, prefix: &str, props: &mut BTreeMap<String, Vec<Str
|
||||
*truncated = true;
|
||||
return;
|
||||
}
|
||||
let key = format!("{prefix}{}", p.name);
|
||||
// Every path built below is charged to the budget, a struct's prefix with its key: a path
|
||||
// built and then refused would be copied again for each sibling while the budget stays put.
|
||||
let path = || build_path(format!("{prefix}{}", p.name));
|
||||
if let Some(arr) = p.children.iter().find(|c| matches!(c.name.as_str(), "rdf:Seq" | "rdf:Bag" | "rdf:Alt")) {
|
||||
let key = path();
|
||||
let mut items: Vec<(bool, String)> = arr
|
||||
.children
|
||||
.iter()
|
||||
@@ -614,32 +631,39 @@ fn collect_property(p: &Node, prefix: &str, props: &mut BTreeMap<String, Vec<Str
|
||||
}
|
||||
return;
|
||||
}
|
||||
let struct_prefix = format!("{key}/");
|
||||
// a struct's path is charged like a key before its fields copy it: that work too is bounded
|
||||
// by the budget, kept fields or not
|
||||
let is_struct = p.attr("rdf:parseType") == Some("Resource") || p.children.iter().any(|c| c.name == "rdf:Description");
|
||||
if is_struct && !take_key_bytes(&key, budget, truncated) {
|
||||
return;
|
||||
}
|
||||
if p.attr("rdf:parseType") == Some("Resource") {
|
||||
// a Resource struct carries fields as attributes as well as child elements, like a nested Description
|
||||
collect_description(p, &struct_prefix, props, budget, truncated);
|
||||
return;
|
||||
}
|
||||
if let Some(d) = p.children.iter().find(|c| c.name == "rdf:Description") {
|
||||
collect_description(d, &struct_prefix, props, budget, truncated);
|
||||
if is_struct {
|
||||
let key = path();
|
||||
if !take_key_bytes(&key, budget, truncated) {
|
||||
return;
|
||||
}
|
||||
let struct_prefix = build_path(format!("{key}/"));
|
||||
if p.attr("rdf:parseType") == Some("Resource") {
|
||||
// a Resource struct carries fields as attributes as well as child elements, like a nested Description
|
||||
collect_description(p, &struct_prefix, props, budget, truncated);
|
||||
} else if let Some(d) = p.children.iter().find(|c| c.name == "rdf:Description") {
|
||||
collect_description(d, &struct_prefix, props, budget, truncated);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let field_attrs: Vec<&(String, String)> = p.attrs.iter().filter(|(k, _)| !is_rdf_meta_attr(k)).collect();
|
||||
if !field_attrs.is_empty() && p.children.is_empty() && p.text.trim().is_empty() {
|
||||
for (k, v) in field_attrs {
|
||||
let full = format!("{struct_prefix}{k}");
|
||||
// the budget is checked before the path is built, as for a description's attributes
|
||||
if *budget < prefix.len().saturating_add(p.name.len()).saturating_add(1).saturating_add(k.len()) {
|
||||
*truncated = true;
|
||||
continue;
|
||||
}
|
||||
let full = build_path(format!("{prefix}{}/{k}", p.name));
|
||||
if take_key_bytes(&full, budget, truncated) {
|
||||
props.entry(full).or_default().push(v.clone());
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
let key = path();
|
||||
let v = p.attr("rdf:resource").map(str::to_string).unwrap_or_else(|| p.text.trim().to_string());
|
||||
if take_key_bytes(&key, budget, truncated) {
|
||||
props.entry(key).or_default().push(v);
|
||||
|
||||
@@ -886,9 +886,39 @@ fn paths_are_not_built_past_the_key_budget() {
|
||||
doc.push_str(&format!("</lc:{level}>"));
|
||||
}
|
||||
doc.push_str("</rdf:Description></rdf:RDF></x:xmpmeta>");
|
||||
let t = std::time::Instant::now();
|
||||
PATH_BYTES.with(|bytes| bytes.set(0));
|
||||
let _ = parse_xmp(&doc);
|
||||
assert!(t.elapsed().as_secs() < 10, "took {:?}", t.elapsed());
|
||||
// Each path built is charged to the budget, or is a charged struct path and its "/".
|
||||
let built = PATH_BYTES.with(std::cell::Cell::get);
|
||||
let structs = 100_004;
|
||||
assert!(built <= 2 * MAX_KEY_BYTES + structs, "{built} bytes of paths built");
|
||||
}
|
||||
|
||||
/// A field attribute whose path no longer fits the budget, while its element's own path still
|
||||
/// does, left the budget as it was: each of its siblings then copied the long ancestor path again.
|
||||
#[test]
|
||||
fn field_paths_past_the_key_budget_are_not_built_for_each_sibling() {
|
||||
// One struct of n letters, then a field that spends the budget down to n + 10 bytes: room for
|
||||
// the path of `lc:e` under the struct (n + 8 bytes) but not for that of its field `lc:f`
|
||||
// (n + 13).
|
||||
let n = 200_000;
|
||||
let level = "n".repeat(n);
|
||||
let drain = "a".repeat(MAX_KEY_BYTES - 3 * n - 25);
|
||||
let mut doc = format!(
|
||||
"<x:xmpmeta xmlns:x=\"adobe:ns:meta/\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" xmlns:lc=\"{}\"><rdf:RDF><rdf:Description><lc:{level} rdf:parseType=\"Resource\"><lc:d lc:{drain}=\"1\"/>",
|
||||
LC.uri
|
||||
);
|
||||
for _ in 0..20_000 {
|
||||
doc.push_str("<lc:e lc:f=\"1\"/>");
|
||||
}
|
||||
doc.push_str(&format!("</lc:{level}></rdf:Description></rdf:RDF></x:xmpmeta>"));
|
||||
PATH_BYTES.with(|bytes| bytes.set(0));
|
||||
let data = parse_xmp(&doc).unwrap_or_else(|e| panic!("{e}"));
|
||||
assert!(data.properties_truncated);
|
||||
assert!(data.properties.contains_key(&format!("lc:{level}/lc:d/lc:{drain}")));
|
||||
assert!(!data.properties.contains_key(&format!("lc:{level}/lc:e/lc:f")));
|
||||
let built = PATH_BYTES.with(std::cell::Cell::get);
|
||||
assert!(built <= 2 * MAX_KEY_BYTES, "{built} bytes of paths built");
|
||||
}
|
||||
|
||||
/// The caller's namespace is declared where the read-only `crs` sits in the table, is known to the
|
||||
|
||||
Loaded 100 of 377 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user