diff --git a/.github/workflows/audio.yml b/.github/workflows/audio.yml index 5fd971c629..5b9c965a79 100644 --- a/.github/workflows/audio.yml +++ b/.github/workflows/audio.yml @@ -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: diff --git a/.github/workflows/media.yml b/.github/workflows/media.yml index f4c4e6689b..7d570980dd 100644 --- a/.github/workflows/media.yml +++ b/.github/workflows/media.yml @@ -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: diff --git a/.github/workflows/video.yml b/.github/workflows/video.yml index 20afe0d700..0db0f19f30 100644 --- a/.github/workflows/video.yml +++ b/.github/workflows/video.yml @@ -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: diff --git a/CHANGELOG.md b/CHANGELOG.md index 31364ecf95..c2e3228555 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/Cargo.lock b/Cargo.lock index 016cb16777..c319ea1631 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -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" diff --git a/Cargo.toml b/Cargo.toml index 41220a0f5a..f8bc4506d5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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 diff --git a/NOTICE b/NOTICE index baa994eb47..9e09cf4494 100644 --- a/NOTICE +++ b/NOTICE @@ -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. diff --git a/README.md b/README.md index 8169bedf9a..64698d8c48 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/crates/atomic/src/tests.rs b/crates/atomic/src/tests.rs index 132fd5a0a6..05ce79d82d 100644 --- a/crates/atomic/src/tests.rs +++ b/crates/atomic/src/tests.rs @@ -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 { diff --git a/crates/automation/src/client_tests.rs b/crates/automation/src/client_tests.rs index 8a767ddd21..8aeee2d0bb 100644 --- a/crates/automation/src/client_tests.rs +++ b/crates/automation/src/client_tests.rs @@ -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()))); diff --git a/crates/automation/src/control.rs b/crates/automation/src/control.rs index 2290c7c08f..7d31b469be 100644 --- a/crates/automation/src/control.rs +++ b/crates/automation/src/control.rs @@ -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); diff --git a/crates/automation/src/dialogs.rs b/crates/automation/src/dialogs.rs index 749626cc61..7e8a544f88 100644 --- a/crates/automation/src/dialogs.rs +++ b/crates/automation/src/dialogs.rs @@ -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), }) diff --git a/crates/automation/tests/it/control.rs b/crates/automation/tests/it/control.rs index 6e1dc700fc..69498ee521 100644 --- a/crates/automation/tests/it/control.rs +++ b/crates/automation/tests/it/control.rs @@ -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 { 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, server::Listening, Receiv fn nothing_more_dispatched(rx: &Receiver, 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) -> 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) -> 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 = 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) { 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) { 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"); diff --git a/crates/automation/tests/it/dialogs.rs b/crates/automation/tests/it/dialogs.rs index b15b926dcd..374d2b4446 100644 --- a/crates/automation/tests/it/dialogs.rs +++ b/crates/automation/tests/it/dialogs.rs @@ -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 { @@ -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> { + 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::()).expect("the held dialog is open") diff --git a/crates/behavior/src/canvas/units.rs b/crates/behavior/src/canvas/units.rs index 946e0d0aba..5bdd7b95ba 100644 --- a/crates/behavior/src/canvas/units.rs +++ b/crates/behavior/src/canvas/units.rs @@ -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 { let most = match self.ticks { Ticks::Decimal { whole: true } => 0, diff --git a/crates/behavior/src/codec.rs b/crates/behavior/src/codec.rs index cb45db81a6..12cebda239 100644 --- a/crates/behavior/src/codec.rs +++ b/crates/behavior/src/codec.rs @@ -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 Option + 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, + /// An authoritative reader for the complete, trimmed, non-empty input. + primary: Option, /// 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 + 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)); } diff --git a/crates/behavior/src/dock/edit.rs b/crates/behavior/src/dock/edit.rs index 2184f141dd..a94b3c5554 100644 --- a/crates/behavior/src/dock/edit.rs +++ b/crates/behavior/src/dock/edit.rs @@ -449,8 +449,9 @@ impl Layout

{ 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 Layout

{ 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 Layout

{ } /// 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

, to: Target

, canvas: &dyn Fn(&P) -> bool) -> Result<(), DockError> { let mut moving = moving; @@ -517,7 +519,7 @@ impl Layout

{ 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(()) diff --git a/crates/behavior/src/dock/groups.rs b/crates/behavior/src/dock/groups.rs index a05570c53e..4ff36d0f16 100644 --- a/crates/behavior/src/dock/groups.rs +++ b/crates/behavior/src/dock/groups.rs @@ -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

{ pub column: Column

, /// The id of a floating window whose last group is in transit, which a new window keeps. pub id: Option, + /// Panels stay in the column the groups left, so a new column made of them is expanded. + pub part: bool, } impl

Moving

{ @@ -344,14 +346,26 @@ impl

Moving

{ 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

, source: Column

) -> 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

, 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

{ + 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) -> Column

{ - Column { width: self.column.width.or(width), ..self.column } + Column { width: self.column.width.or(width), iconic: self.column.iconic && !self.part, ..self.column } } } diff --git a/crates/behavior/src/dock/inner.rs b/crates/behavior/src/dock/inner.rs index b213dd3177..6d652e7e71 100644 --- a/crates/behavior/src/dock/inner.rs +++ b/crates/behavior/src/dock/inner.rs @@ -49,7 +49,7 @@ impl Layout

{ 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 Layout

{ } 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 Layout

{ { 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 Layout

{ 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 Layout

{ } /// 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

{ - 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

, 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 Layout

{ pub(super) fn insert( &mut self, entry: StackEntry

, - source: Column

, + source: (Column

, bool), anchor: &P, placement: DockPlacement

, canvas: &dyn Fn(&P) -> bool, @@ -338,8 +340,7 @@ impl Layout

{ .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 diff --git a/crates/behavior/src/geometry/crop.rs b/crates/behavior/src/geometry/crop.rs index 4704686970..80e6ce7fd3 100644 --- a/crates/behavior/src/geometry/crop.rs +++ b/crates/behavior/src/geometry/crop.rs @@ -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 diff --git a/crates/behavior/src/lib.rs b/crates/behavior/src/lib.rs index 617f1f0347..9a9f8a7ef8 100644 --- a/crates/behavior/src/lib.rs +++ b/crates/behavior/src/lib.rs @@ -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)] diff --git a/crates/behavior/src/sense.rs b/crates/behavior/src/sense.rs index c64efa2fbd..99281664b3 100644 --- a/crates/behavior/src/sense.rs +++ b/crates/behavior/src/sense.rs @@ -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 { diff --git a/crates/behavior/src/value_drag.rs b/crates/behavior/src/value_drag.rs index 4a69c6a4e0..e2968b7285 100644 --- a/crates/behavior/src/value_drag.rs +++ b/crates/behavior/src/value_drag.rs @@ -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, + coarse: Option, +} + +impl DragModifiers { + /// Selects the fine and coarse bindings; `None` disables that binding. + pub const fn new(fine: Option, coarse: Option) -> 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, + 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, range: RangeInclusive) -> 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) -> 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) diff --git a/crates/behavior/src/wheel.rs b/crates/behavior/src/wheel.rs index 12c36a01e3..a5de8554a7 100644 --- a/crates/behavior/src/wheel.rs +++ b/crates/behavior/src/wheel.rs @@ -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 { /// 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 WheelTaker { vertical: false, zoom: false, gated: false, + directional: false, scrolls: false, notch: WheelNotch::DEFAULT, room: None, @@ -441,14 +455,17 @@ impl WheelTaker { /// 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 { 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 WheelTaker { 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( 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( // 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> = 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| (!taker.gated && !(fingers && taker.value)) || armed == Some(taker.owner) || focused == Some(taker.owner); + let open = |taker: &WheelTaker| { + 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> = latch - .flatten() - .and_then(|owner| takers.iter().find(|taker| taker.owner == owner && open(taker) && !(taker.field && focused == Some(taker.owner)))); + let held: Option<&WheelTaker> = 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| 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( 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], at: Pos2, wheel: Wheel, focus: Option, armed: Option) -> (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))); + } } diff --git a/crates/behavior/tests/codec_override.rs b/crates/behavior/tests/codec_override.rs new file mode 100644 index 0000000000..2f6923f0d6 --- /dev/null +++ b/crates/behavior/tests/codec_override.rs @@ -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 { + 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))); +} diff --git a/crates/behavior/tests/dock_apply.rs b/crates/behavior/tests/dock_apply.rs index be5f2b3a8b..347f7da531 100644 --- a/crates/behavior/tests/dock_apply.rs +++ b/crates/behavior/tests/dock_apply.rs @@ -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"); diff --git a/crates/behavior/tests/main.rs b/crates/behavior/tests/main.rs index c52c1045ec..d01da9d642 100644 --- a/crates/behavior/tests/main.rs +++ b/crates/behavior/tests/main.rs @@ -2,6 +2,7 @@ mod canvas_view; mod cells; +mod codec_override; mod digit_keys; mod dock; mod dock_apply; diff --git a/crates/captions/src/ttml.rs b/crates/captions/src/ttml.rs index 78db4763b3..07c2fd9cb1 100644 --- a/crates/captions/src/ttml.rs +++ b/crates/captions/src/ttml.rs @@ -113,6 +113,57 @@ fn time_expr(t: Tick, rate: Option) -> 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 = 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 { + #[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 { + 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 { + fn next(&mut self, bytes: Reader<'_>, quote: u8, from: usize) -> Option { 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 "ad" 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, "x"); } + /// `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("a 1 < 2"), "a 1 < 2"); } + + #[test] + fn many_unmatched_angle_brackets_before_one_gt_are_read_once() { + assert_linear(|n| format!("{}>", "<".repeat(n)), |n| format!("{}>", "<".repeat(n))); + } } diff --git a/crates/captions/tests/it/ttml_literal_angle.rs b/crates/captions/tests/it/ttml_literal_angle.rs index 0e48439013..f2a98abb61 100644 --- a/crates/captions/tests/it/ttml_literal_angle.rs +++ b/crates/captions/tests/it/ttml_literal_angle.rs @@ -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)))); } diff --git a/crates/cloud-ui/src/cloud/mod.rs b/crates/cloud-ui/src/cloud/mod.rs index b99ea2f612..457fb357d5 100644 --- a/crates/cloud-ui/src/cloud/mod.rs +++ b/crates/cloud-ui/src/cloud/mod.rs @@ -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. diff --git a/crates/cloud-ui/src/share/mod.rs b/crates/cloud-ui/src/share/mod.rs index 9d03472e50..91c9673e38 100644 --- a/crates/cloud-ui/src/share/mod.rs +++ b/crates/cloud-ui/src/share/mod.rs @@ -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>, destinations_seq: Option, - link_seq: Option, + /// Account links in flight, by request. More than one can be: every + /// unlinked destination stays clickable while another one links. + linking: Vec, /// Which one is selected, by id. destination: Option, /// 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; } } diff --git a/crates/cloud-ui/src/share/tests.rs b/crates/cloud-ui/src/share/tests.rs index 283ce0274b..188fcdb7fc 100644 --- a/crates/cloud-ui/src/share/tests.rs +++ b/crates/cloud-ui/src/share/tests.rs @@ -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 { diff --git a/crates/color-ui/README.md b/crates/color-ui/README.md index a38b1f9827..1e05047576 100644 --- a/crates/color-ui/README.md +++ b/crates/color-ui/README.md @@ -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. diff --git a/crates/color-ui/src/ui/eyedropper.rs b/crates/color-ui/src/ui/eyedropper.rs index 4e17c7b572..0f9d0e508a 100644 --- a/crates/color-ui/src/ui/eyedropper.rs +++ b/crates/color-ui/src/ui/eyedropper.rs @@ -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 Option + 'a>, - held: Option<(Pos2, Srgba)>, + held: Option, picked: Option, 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) -> 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 { + self.held + } + /// The newest pick, once. pub fn take(&mut self) -> Option { 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); diff --git a/crates/color-ui/src/ui/harmony.rs b/crates/color-ui/src/ui/harmony.rs index 254d30f628..f11fa9129b 100644 --- a/crates/color-ui/src/ui/harmony.rs +++ b/crates/color-ui/src/ui/harmony.rs @@ -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); diff --git a/crates/color-ui/src/ui/mod.rs b/crates/color-ui/src/ui/mod.rs index c075c29095..d620536e75 100644 --- a/crates/color-ui/src/ui/mod.rs +++ b/crates/color-ui/src/ui/mod.rs @@ -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, diff --git a/crates/color-ui/src/ui/pair.rs b/crates/color-ui/src/ui/pair.rs index 5504a5a901..e916f66603 100644 --- a/crates/color-ui/src/ui/pair.rs +++ b/crates/color-ui/src/ui/pair.rs @@ -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 Component for SwatchPair<'_, P> { Some(paint) => paint_value(&cx.words::(), paint), None => cx.words::().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); } } diff --git a/crates/color-ui/src/ui/panel.rs b/crates/color-ui/src/ui/panel.rs index d2548b1045..db257c06b0 100644 --- a/crates/color-ui/src/ui/panel.rs +++ b/crates/color-ui/src/ui/panel.rs @@ -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) { + 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 })); } } diff --git a/crates/color-ui/src/ui/panel/fill_stroke.rs b/crates/color-ui/src/ui/panel/fill_stroke.rs index 1e6dd88dd9..59c12cb674 100644 --- a/crates/color-ui/src/ui/panel/fill_stroke.rs +++ b/crates/color-ui/src/ui/panel/fill_stroke.rs @@ -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), + ); } } diff --git a/crates/color-ui/tests/it/pair.rs b/crates/color-ui/tests/it/pair.rs index a53fa2d925..21f5942f44 100644 --- a/crates/color-ui/tests/it/pair.rs +++ b/crates/color-ui/tests/it/pair.rs @@ -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> = 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"); +} diff --git a/crates/color-ui/tests/it/panels.rs b/crates/color-ui/tests/it/panels.rs index 5982f8222f..91d7c1dee5 100644 --- a/crates/color-ui/tests/it/panels.rs +++ b/crates/color-ui/tests/it/panels.rs @@ -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>, 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>, 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 = + 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:?}"); +} diff --git a/crates/color-ui/tests/it/sampling.rs b/crates/color-ui/tests/it/sampling.rs index 53ce25aa92..c0879b36dd 100644 --- a/crates/color-ui/tests/it/sampling.rs +++ b/crates/color-ui/tests/it/sampling.rs @@ -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>) -> Vec { 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. diff --git a/crates/craft/Cargo.toml b/crates/craft/Cargo.toml index e989add35f..fbaafba855 100644 --- a/crates/craft/Cargo.toml +++ b/crates/craft/Cargo.toml @@ -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"] diff --git a/crates/craft/src/egui_fork.rs b/crates/craft/src/egui_fork.rs index e10d75f9e0..bae49f9ad9 100644 --- a/crates/craft/src/egui_fork.rs +++ b/crates/craft/src/egui_fork.rs @@ -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] = &[ diff --git a/crates/craft/src/lib.rs b/crates/craft/src/lib.rs index 60863cda9a..f3865fae1d 100644 --- a/crates/craft/src/lib.rs +++ b/crates/craft/src/lib.rs @@ -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")] diff --git a/crates/draw/src/ui/brush_presets/picker.rs b/crates/draw/src/ui/brush_presets/picker.rs index 43d612ec1c..dbcbc769fb 100644 --- a/crates/draw/src/ui/brush_presets/picker.rs +++ b/crates/draw/src/ui/brush_presets/picker.rs @@ -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 { pub hardness: EditEvents, /// The angle widget: the new angle and roundness. pub tip: EditEvents, + /// 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, /// 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>> = 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, hardness: EditEvents, tip: EditEvents, + out_of_range: Option, } /// 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::(); 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()); } }); }); diff --git a/crates/draw/src/ui/brush_settings/size_field.rs b/crates/draw/src/ui/brush_settings/size_field.rs index aec36f81ae..63c7d41d13 100644 --- a/crates/draw/src/ui/brush_settings/size_field.rs +++ b/crates/draw/src/ui/brush_settings/size_field.rs @@ -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, + /// 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, } 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 } } } diff --git a/crates/draw/src/ui/crop/perspective_tool.rs b/crates/draw/src/ui/crop/perspective_tool.rs index 4e425b41b3..b5c095234d 100644 --- a/crates/draw/src/ui/crop/perspective_tool.rs +++ b/crates/draw/src/ui/crop/perspective_tool.rs @@ -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. diff --git a/crates/draw/src/ui/stroke/editor.rs b/crates/draw/src/ui/stroke/editor.rs index 2a802a2281..e43cb82827 100644 --- a/crates/draw/src/ui/stroke/editor.rs +++ b/crates/draw/src/ui/stroke/editor.rs @@ -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::(); let name: Arc = 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, } 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); diff --git a/crates/draw/tests/it/brush_presets.rs b/crates/draw/tests/it/brush_presets.rs index cbcbfe7b0b..dba1cdf527 100644 --- a/crates/draw/tests/it/brush_presets.rs +++ b/crates/draw/tests/it/brush_presets.rs @@ -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, /// The space above the field. offset: f32, + /// The range alerts the passes reported. + alerts: Vec, } const POINT: Pos2 = Pos2::new(160.0, 120.0); @@ -91,11 +94,12 @@ fn opened_rig(at_point: bool, remember: bool) -> (Fixture, Rc>) 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>) 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() diff --git a/crates/draw/tests/it/perspective_crop.rs b/crates/draw/tests/it/perspective_crop.rs index 57f95daba2..c2f6ddbaab 100644 --- a/crates/draw/tests/it/perspective_crop.rs +++ b/crates/draw/tests/it/perspective_crop.rs @@ -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) -> 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)])); + } +} diff --git a/crates/draw/tests/it/stroke_editor.rs b/crates/draw/tests/it/stroke_editor.rs index acf4e9d3e9..838a694d0a 100644 --- a/crates/draw/tests/it/stroke_editor.rs +++ b/crates/draw/tests/it/stroke_editor.rs @@ -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]); diff --git a/crates/font-manager/Cargo.toml b/crates/font-manager/Cargo.toml index dcc2db8025..367e024e95 100644 --- a/crates/font-manager/Cargo.toml +++ b/crates/font-manager/Cargo.toml @@ -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" diff --git a/crates/font-manager/src/glyphs.rs b/crates/font-manager/src/glyphs.rs index ccdab018dd..d0861d492d 100644 --- a/crates/font-manager/src/glyphs.rs +++ b/crates/font-manager/src/glyphs.rs @@ -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 = None; let mut font_changed = false; let mut menu: Option = 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> = 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; - 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 } } diff --git a/crates/font-manager/src/picker.rs b/crates/font-manager/src/picker.rs index 45ab39f1d5..2d61945957 100644 --- a/crates/font-manager/src/picker.rs +++ b/crates/font-manager/src/picker.rs @@ -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 diff --git a/crates/font-manager/src/picker/rank.rs b/crates/font-manager/src/picker/rank.rs index 5955c4c5e0..2c578ee7a8 100644 --- a/crates/font-manager/src/picker/rank.rs +++ b/crates/font-manager/src/picker/rank.rs @@ -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> { 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> { 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. diff --git a/crates/font-manager/src/picker/rows.rs b/crates/font-manager/src/picker/rows.rs index 3c54d291f4..b58599e1a2 100644 --- a/crates/font-manager/src/picker/rows.rs +++ b/crates/font-manager/src/picker/rows.rs @@ -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(), } } diff --git a/crates/font-manager/src/picker/stories.rs b/crates/font-manager/src/picker/stories.rs index a7ed553a42..b29c67e378 100644 --- a/crates/font-manager/src/picker/stories.rs +++ b/crates/font-manager/src/picker/stories.rs @@ -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) diff --git a/crates/font-manager/tests/it/glyphs.rs b/crates/font-manager/tests/it/glyphs.rs index 0ce58b6479..25ec2dc96a 100644 --- a/crates/font-manager/tests/it/glyphs.rs +++ b/crates/font-manager/tests/it/glyphs.rs @@ -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"; diff --git a/crates/font-manager/tests/it/picker.rs b/crates/font-manager/tests/it/picker.rs index 9f830a4b4a..31e7c20ab6 100644 --- a/crates/font-manager/tests/it/picker.rs +++ b/crates/font-manager/tests/it/picker.rs @@ -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 { + 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 = ('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(); diff --git a/crates/fonts-build/README.md b/crates/fonts-build/README.md index 4d72f41aad..f987b9ca9e 100644 --- a/crates/fonts-build/README.md +++ b/crates/fonts-build/README.md @@ -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 diff --git a/crates/fonts-build/src/lib.rs b/crates/fonts-build/src/lib.rs index e2d7ed3868..b453ac8b97 100644 --- a/crates/fonts-build/src/lib.rs +++ b/crates/fonts-build/src/lib.rs @@ -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 } + } + /// `"