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/Cargo.lock b/Cargo.lock index 85b87db49c..a95046e3a5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -835,12 +835,6 @@ dependencies = [ "cpufeatures 0.3.1", ] -[[package]] -name = "block" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d8c1fef690941d3e7788d328517591fecc684c084084702d6ff1641e993699a" - [[package]] name = "block-buffer" version = "0.10.4" @@ -1685,19 +1679,6 @@ dependencies = [ "libc", ] -[[package]] -name = "core-graphics2" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b65858d95344d2711161cd92196732f67d6c5fea238cf12f994584828731a5c" -dependencies = [ - "bitflags 2.13.2", - "block", - "cfg-if", - "core-foundation 0.10.1", - "libc", -] - [[package]] name = "core_detect" version = "1.0.0" @@ -1905,6 +1886,7 @@ dependencies = [ "craft-pst", "craft-quit", "craft-raster-codecs", + "craft-raster3d", "craft-raw", "craft-review", "craft-rtf", @@ -2055,6 +2037,8 @@ dependencies = [ "block2 0.6.2", "objc2 0.6.5", "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-core-graphics", "objc2-foundation 0.3.2", ] @@ -2800,6 +2784,7 @@ dependencies = [ "serde", "serde_json", "skrifa 0.47.0", + "write-fonts 0.54.1", ] [[package]] @@ -2959,6 +2944,7 @@ name = "craft-gpu-wgpu" version = "0.1.0" dependencies = [ "craft-gpu", + "craft-gpu-device", "craft-gpu-providers", "pollster 0.4.0", "wgpu", @@ -3049,6 +3035,8 @@ version = "0.1.0" name = "craft-i18n" version = "0.1.0" dependencies = [ + "brotli 9.1.1", + "brotli-decompressor 6.3.1", "chrono", "fixed_decimal", "icu_calendar", @@ -3254,9 +3242,11 @@ dependencies = [ "craft-ui-macros", "craft-xml", "egui", + "global-hotkey", "serde", "serde_json", "tempfile", + "x11rb", ] [[package]] @@ -3509,6 +3499,7 @@ dependencies = [ name = "craft-nightly" version = "0.1.0" dependencies = [ + "uds_windows", "winsafe", ] @@ -3798,17 +3789,20 @@ dependencies = [ "async-process", "clipboard-win", "core-graphics", - "core-graphics2", + "craft-appkit", "craft-atomic", "craft-docpath", "craft-host", "craft-i18n", + "craft-testkit", "craft-theme", "fmv-macos-events", "futures-lite", "js-sys", "log", "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-core-graphics", "objc2-foundation 0.3.2", "rfd", "serde", @@ -4017,6 +4011,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" @@ -4354,7 +4356,9 @@ name = "craft-testkit" version = "0.1.0" dependencies = [ "libc", + "log", "png 0.18.1", + "proptest", "rustix 1.1.6", "serde_json", "sha2 0.10.9", @@ -4748,6 +4752,7 @@ dependencies = [ "base64 0.22.1", "chrono", "craft-host", + "craft-testkit", "craft-theme", "craft-ui", "dunce", @@ -6944,6 +6949,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" @@ -14678,7 +14700,7 @@ checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" [[package]] name = "winit" version = "0.30.13" -source = "git+https://github.com/storytold/winit.git?rev=a517b3846ee8457d84ee4975110bfda6797c44dc#a517b3846ee8457d84ee4975110bfda6797c44dc" +source = "git+https://github.com/storytold/winit.git?rev=0dfcec0eb62fda5904137a63a6dd0c3d83295f45#0dfcec0eb62fda5904137a63a6dd0c3d83295f45" dependencies = [ "android-activity", "atomic-waker", diff --git a/Cargo.toml b/Cargo.toml index 817f5c1065..e664d72fdd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -236,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" } @@ -291,7 +292,7 @@ smallvec = "1" serde = { version = "1", features = ["derive"] } serde_json = "1" typeid = "1" -proptest = "1" +proptest = "1.7" # Character sets of the WHATWG Encoding Standard (craft-mime). (Apache-2.0 OR MIT) AND BSD-3-Clause. encoding_rs = "0.8" # All date/time conversion goes through chrono (no hand-rolled calendar code beyond the 400-year range extension; AGENTS.md). @@ -341,7 +342,7 @@ egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev 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" } +winit = { git = "https://github.com/storytold/winit.git", rev = "0dfcec0eb62fda5904137a63a6dd0c3d83295f45" } # symphonia's FLAC decoder restores LPC samples as `residual + (prediction as i32)`. In a valid # 32-bit stream the prediction can leave the i32 range while the sum does not, so a debug build 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/appkit/Cargo.toml b/crates/appkit/Cargo.toml index 5d451b3975..12f94f2e01 100644 --- a/crates/appkit/Cargo.toml +++ b/crates/appkit/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "craft-appkit" -description = "The macOS menu-tracking observers and Save panel calls that need `unsafe`, behind a safe API, so no other crate allows `unsafe`." +description = "The macOS menu-tracking observers, Save panel calls and Core Graphics display calls that need `unsafe`, behind a safe API, so no other crate allows `unsafe`." version.workspace = true edition.workspace = true license.workspace = true @@ -9,12 +9,19 @@ repository.workspace = true # `NSMenuDidBeginTrackingNotification` and `NSMenuDidEndTrackingNotification`, observed through # `NSNotificationCenter` with a block. A Save panel made with `-init`, and the target of a pop-up menu's action. +# The active display list and an image's pixel bytes from Core Graphics. [target.'cfg(target_os = "macos")'.dependencies] block2 = "0.6.2" objc2 = { version = "0.6.4", default-features = false, features = ["std"] } objc2-app-kit = { version = "0.3.2", default-features = false, features = ["std", "NSButton", "NSControl", "NSMenu", "NSPanel", "NSPopUpButton", "NSResponder", "NSSavePanel", "NSView", "NSWindow"] } +objc2-core-graphics = { version = "0.3.2", default-features = false, features = ["std", "CGDataProvider", "CGDirectDisplay", "CGError", "CGImage"] } objc2-foundation = { version = "0.3.2", default-features = false, features = ["std", "block2", "NSNotification", "NSObject", "NSOperation", "NSString"] } +# A test image made from known bytes. +[target.'cfg(target_os = "macos")'.dev-dependencies] +objc2-core-foundation = { version = "0.3.2", default-features = false, features = ["std", "CFData"] } +objc2-core-graphics = { version = "0.3.2", default-features = false, features = ["std", "CGColorSpace", "CGDataProvider", "CGImage"] } + # The workspace table with `unsafe_code` at `deny`: `lib.rs` allows it for this crate's FFI calls, and design-lint's # `contract/unsafe-allow` rule names this crate's source as one of the places that may. Cargo cannot override one # workspace lint. diff --git a/crates/appkit/src/display.rs b/crates/appkit/src/display.rs new file mode 100644 index 0000000000..39aa0da9b4 --- /dev/null +++ b/crates/appkit/src/display.rs @@ -0,0 +1,83 @@ +//! The Core Graphics display calls that need `unsafe`: listing the active displays, and reading an image's pixels +//! without copying them a second time. + +use objc2_core_graphics::{CGDataProvider, CGDirectDisplayID, CGError, CGGetActiveDisplayList, CGImage}; + +/// The largest `max` that [`active_displays`] accepts. +pub const MAX_DISPLAYS: usize = 1024; + +/// The IDs of the active displays, at most `max` of them, or `None` when `max` is above [`MAX_DISPLAYS`] or Core +/// Graphics reports an error. +pub fn active_displays(max: usize) -> Option> { + if max > MAX_DISPLAYS { + return None; + } + let capacity = u32::try_from(max).ok()?; + let mut ids: Vec = vec![0; max]; + let mut count = 0u32; + // SAFETY: `ids` holds `capacity` writable IDs and `count` is a writable `u32`. Core Graphics writes at most + // `capacity` IDs and the number it wrote. + let result = unsafe { CGGetActiveDisplayList(capacity, ids.as_mut_ptr(), &mut count) }; + if result != CGError::Success { + return None; + } + ids.truncate(usize::try_from(count).ok()?.min(max)); + Some(ids) +} + +/// Calls `read` with the bytes of `image`'s pixels, or returns `None` when the image has no data provider or the +/// provider gives no data. +pub fn with_image_bytes(image: &CGImage, read: impl FnOnce(&[u8]) -> R) -> Option { + let data = CGDataProvider::data(CGImage::data_provider(Some(image)).as_deref())?; + // SAFETY: `CGDataProviderCopyData` returns a new immutable `CFData` that this function holds until `read` + // returns, so nothing changes its bytes while the slice is borrowed. + Some(read(unsafe { data.as_bytes_unchecked() })) +} + +#[cfg(test)] +mod tests { + use objc2_core_foundation::CFData; + use objc2_core_graphics::{CGBitmapInfo, CGColorRenderingIntent, CGColorSpace, CGImageAlphaInfo, CGMainDisplayID}; + + use super::*; + + /// The list holds the main display and no more IDs than asked for; a `max` above the limit is refused. + #[test] + fn active_displays_lists_the_main_display_within_max() { + let all = active_displays(MAX_DISPLAYS).unwrap_or_default(); + assert!(all.contains(&CGMainDisplayID()), "{all:?}"); + // 0 is `kCGNullDirectDisplay`: an ID Core Graphics did not write. + assert!(!all.contains(&0), "{all:?}"); + assert_eq!(active_displays(0), Some(Vec::new())); + assert_eq!(active_displays(1).map(|ids| ids.len()), Some(1)); + assert_eq!(active_displays(MAX_DISPLAYS + 1), None); + assert_eq!(active_displays(usize::MAX), None); + } + + /// The bytes passed on are the image's own pixel rows, row padding included. + #[test] + fn image_bytes_are_the_pixels_of_the_image() { + let pixels: Vec = (0u8..24).collect(); + let provider = CGDataProvider::with_cf_data(Some(&CFData::from_bytes(&pixels))).unwrap_or_else(|| panic!("no provider")); + let space = CGColorSpace::new_device_rgb().unwrap_or_else(|| panic!("no color space")); + // SAFETY: two rows of two RGBA pixels with 4 bytes of padding (12 bytes a row), 24 bytes in the provider, and a + // null decode array. + let image = unsafe { + CGImage::new( + 2, + 2, + 8, + 32, + 12, + Some(&space), + CGBitmapInfo(CGImageAlphaInfo::PremultipliedLast.0), + Some(&provider), + std::ptr::null(), + false, + CGColorRenderingIntent::RenderingIntentDefault, + ) + } + .unwrap_or_else(|| panic!("no image")); + assert_eq!(with_image_bytes(&image, <[u8]>::to_vec), Some(pixels)); + } +} diff --git a/crates/appkit/src/lib.rs b/crates/appkit/src/lib.rs index 70ed01f92d..23f548724d 100644 --- a/crates/appkit/src/lib.rs +++ b/crates/appkit/src/lib.rs @@ -1,5 +1,6 @@ -//! The AppKit calls that need `unsafe`, behind a safe API: observing when a menu starts and stops tracking, and the -//! Save panel calls in `save_panel`. macOS only; the crate is empty elsewhere. +//! The AppKit calls that need `unsafe`, behind a safe API: observing when a menu starts and stops tracking, the +//! Save panel calls in `save_panel`, and the Core Graphics display calls in `display`. macOS only; the crate is empty +//! elsewhere. //! //! This is one of the crates that may allow `unsafe`; the design-lint rule `contract/unsafe-allow` names it. Every //! block says why it is sound. @@ -14,6 +15,7 @@ use block2::RcBlock; use objc2_app_kit::{NSMenuDidBeginTrackingNotification, NSMenuDidEndTrackingNotification}; use objc2_foundation::{NSNotification, NSNotificationCenter}; +pub mod display; pub mod save_panel; /// Calls `on_change(true)` when a menu begins tracking (`NSMenuDidBeginTrackingNotification`) and `on_change(false)` 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/behavior/src/codec.rs b/crates/behavior/src/codec.rs index 12cebda239..4953bffcf1 100644 --- a/crates/behavior/src/codec.rs +++ b/crates/behavior/src/codec.rs @@ -172,6 +172,8 @@ pub struct NumberCodec { /// A lone percentage is that share of the start value ([`NumberCodec::share_of_start`]). share: bool, signed_zoom: bool, + /// A positive value is written with its `+` ([`NumberCodec::explicit_plus`]). + plus: bool, } impl fmt::Debug for NumberCodec { @@ -183,6 +185,7 @@ impl fmt::Debug for NumberCodec { .field("zoom", &self.zoom) .field("share", &self.share) .field("signed_zoom", &self.signed_zoom) + .field("plus", &self.plus) .field("custom", &self.custom.is_some()) .field("primary", &self.primary.is_some()) .finish() @@ -207,6 +210,7 @@ impl PartialEq for NumberCodec { && self.zoom == other.zoom && self.share == other.share && self.signed_zoom == other.signed_zoom + && self.plus == other.plus && same_custom && same_primary } @@ -242,7 +246,17 @@ 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, primary: None, zoom: false, share: false, signed_zoom: false } + NumberCodec { reader, decimals, fixed: false, custom: None, primary: None, zoom: false, share: false, signed_zoom: false, plus: false } + } + + /// The same codec writing a positive value with its sign ("+2.50"), as an angle or an offset from a neutral value + /// reads; a value that rounds to zero at the codec's decimals stays unsigned ("0.00"). A leading `+` in typed text + /// is then the number's sign, as the field writes it, not the relative `+` of a plain field (which adds to the + /// value the edit started from). An authoritative [`parse_with`](Self::parse_with) reader still receives the whole + /// input, including the sign. + pub fn explicit_plus(mut self) -> Self { + self.plus = true; + self } /// The same codec writing every decimal place, trailing zeros included ("1.00"), as a field of a quantity shown @@ -322,6 +336,25 @@ impl NumberCodec { self } + fn parse_builtin(&self, trimmed: &str, start: Option) -> Result<(Option, ParseNote), NotAValue> { + if self.zoom { + return self.read_zoom(trimmed).map(|(number, note)| (Some(number), note)); + } + // Without an edit-start operand the reader already treats a leading `+` as a unary sign. Take that + // path directly rather than retrying each shorter suffix, and leave signed shares as absolute amounts. + let absolute_plus = self.plus && trimmed.starts_with('+'); + if self.share + && !absolute_plus + && let Some(share_of_start) = self.reader.share(trimmed) + { + return start.map(|start| (Some(start * share_of_start), ParseNote::default())).ok_or(NotAValue); + } + match self.reader.read_tagged(trimmed, if absolute_plus { None } else { start }) { + Ok((number, tag)) => Ok((Some(number), ParseNote { unit: tag, ..ParseNote::default() })), + Err(rejected) => self.custom.as_ref().and_then(|parse| parse(trimmed)).map(|number| (Some(number), ParseNote::default())).ok_or(rejected), + } + } + /// 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. @@ -346,6 +379,12 @@ impl NumberCodec { pub fn reader(&self) -> &Reader { &self.reader } + + /// Whether the codec writes a positive value with its `+` ([`NumberCodec::explicit_plus`]): its own text then + /// starts with a sign that is the number's, not a relative edit. + pub fn writes_sign(&self) -> bool { + self.plus + } } impl Default for NumberCodec { @@ -372,7 +411,9 @@ impl Codec for NumberCodec { } else { fixed }; - trimmed.replace('.', &self.reader.decimal_separator().to_string()) + let shown = trimmed.replace('.', &self.reader.decimal_separator().to_string()); + let zero = trimmed.bytes().all(|byte| matches!(byte, b'0' | b'.')); + if self.plus && !trimmed.starts_with('-') && !zero { format!("+{shown}") } else { shown } } fn parse(&self, text: &str, start: &Option) -> Result, NotAValue> { @@ -389,20 +430,7 @@ impl Codec for NumberCodec { 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)); - } - if self.share - && let Some(share) = self.reader.share(trimmed) - { - return start.map(|start| (Some(start * share), ParseNote::default())).ok_or(NotAValue); - } - match self.reader.read_tagged(text, *start) { - Ok((number, tag)) => Ok((Some(number), ParseNote { unit: tag, ..ParseNote::default() })), - Err(rejected) => { - self.custom.as_ref().and_then(|parse| parse(text.trim())).map(|number| (Some(number), ParseNote::default())).ok_or(rejected) - } - } + self.parse_builtin(trimmed, *start) } /// Zoom typing takes ASCII digits, `/` and the decimal separator, with an optional minus; other fields take every character. @@ -427,4 +455,83 @@ mod tests { assert_eq!(one.format(&Some(-0.06)), "-0.1"); assert_eq!(NumberCodec::new(Reader::new(), 1).fixed().format(&Some(-0.04)), "0.0"); } + + #[test] + fn an_explicit_plus_codec_writes_the_sign_of_a_positive_value() { + let angle = NumberCodec::new(Reader::new(), 2).fixed().explicit_plus(); + assert_eq!(angle.format(&Some(2.5)), "+2.50"); + assert_eq!(angle.format(&Some(-3.25)), "-3.25"); + assert_eq!(angle.format(&Some(0.0)), "0.00", "zero is unsigned"); + assert_eq!(angle.format(&Some(0.004)), "0.00", "a value that rounds to zero is unsigned"); + assert_eq!(angle.format(&Some(-0.004)), "0.00"); + assert_eq!(angle.format(&None), ""); + assert_eq!(NumberCodec::new(Reader::new(), 2).explicit_plus().format(&Some(1.5)), "+1.5", "trimmed decimals keep the sign"); + assert_eq!(NumberCodec::new(Reader::new(), 2).fixed().format(&Some(2.5)), "2.50", "without it a positive value has no sign"); + } + + #[test] + fn an_explicit_plus_codec_reads_a_leading_plus_as_the_sign() { + let angle = NumberCodec::new(Reader::new(), 2).fixed().explicit_plus(); + assert_eq!(angle.parse("+2.50", &Some(10.0)).ok(), Some(Some(2.5)), "the written text reads back as itself, not added to the start"); + assert_eq!(angle.parse(&angle.format(&Some(7.25)), &Some(-1.0)).ok(), Some(Some(7.25))); + assert_eq!(angle.parse("-3.25", &Some(10.0)).ok(), Some(Some(-3.25))); + assert_eq!(angle.parse("4", &None).ok(), Some(Some(4.0))); + assert!(angle.parse("+", &Some(1.0)).is_err(), "a lone plus is no number"); + let plain = NumberCodec::new(Reader::new(), 2); + assert_eq!(plain.parse("+2", &Some(10.0)).ok(), Some(Some(12.0)), "a plain field's leading plus still adds to the start"); + } +} + +#[cfg(test)] +mod review_tests { + use super::*; + + /// The `+` a field writes may be typed back with a space after it: "+ 2.50" is the number 2.5, not the relative + /// "+ 2.50" added to the start value. + #[test] + fn an_explicit_plus_codec_reads_the_space_after_the_sign() { + let angle = NumberCodec::new(Reader::new(), 2).fixed().explicit_plus(); + assert_eq!(angle.parse("+ 2.50", &Some(10.0)).ok(), Some(Some(2.5)), "a space after the sign keeps it the number's own"); + assert_eq!(angle.parse("+\t7", &Some(10.0)).ok(), Some(Some(7.0))); + assert!(angle.parse("+", &Some(10.0)).is_err(), "a lone plus stays no number"); + let plain = NumberCodec::new(Reader::new(), 2); + assert_eq!(plain.parse("+ 2", &Some(10.0)).ok(), Some(Some(12.0)), "a plain field's plus still adds to the start"); + // The digit after the sign may be written in any script the reader reads: Arabic-Indic ٣ is 3. + assert_eq!(angle.parse("+\u{663}", &Some(10.0)).ok(), Some(Some(3.0)), "a sign before an Arabic-Indic digit is still the number's"); + // The signed text is absolute for every lead the reader accepts, an expression too: "+(2+3)" is 5, not 15. + assert_eq!(angle.parse("+(2+3)", &Some(10.0)).ok(), Some(Some(5.0)), "a signed expression is the number, not added to the start"); + assert_eq!(angle.parse("+2+3", &Some(10.0)).ok(), Some(Some(5.0)), "and a signed sum reads the same as without the sign"); + assert_eq!(angle.parse("-(2+3)", &Some(10.0)).ok(), Some(Some(-5.0)), "a minus stays absolute, as it was"); + assert_eq!(plain.parse("+(2+3)", &Some(10.0)).ok(), Some(Some(15.0)), "a plain field still adds a leading plus to the start"); + // A word the field's own parser stands for is given the text as it was typed, `+` and all. + let named = NumberCodec::new(Reader::new(), 2).explicit_plus().or_parse(|text| (text == "+Auto").then_some(42.0)); + assert_eq!(named.parse("+Auto", &Some(10.0)).ok(), Some(Some(42.0)), "a custom parser still sees the signed text"); + assert_eq!(named.parse("+2", &Some(10.0)).ok(), Some(Some(2.0)), "while a number after the sign stays absolute"); + assert_eq!(angle.parse("\u{663}", &Some(10.0)).ok(), Some(Some(3.0)), "and the reader reads that digit as before"); + assert_eq!(plain.parse("+\u{663}", &Some(10.0)).ok(), Some(Some(13.0)), "a plain field still adds it to the start"); + } + + /// A share field's signed percentage is that number, not a share of the start value again. + #[test] + fn an_explicit_plus_share_codec_reads_a_signed_percentage_as_the_number() { + let share = NumberCodec::new(Reader::new().unit("%", 1.0), 0).share_of_start().explicit_plus(); + assert_eq!(share.parse("+50%", &Some(10.0)).ok(), Some(Some(50.0)), "a signed percentage is absolute"); + assert_eq!(share.parse("50%", &Some(10.0)).ok(), Some(Some(5.0)), "an unsigned one is the share of the start"); + assert_eq!(share.parse("+50", &Some(10.0)).ok(), Some(Some(50.0)), "and a signed number is absolute too"); + } + #[test] + fn explicit_plus_still_gives_the_authoritative_reader_the_whole_signed_input() { + let codec = NumberCodec::default().parse_with(|text| (text == "+12").then_some(17.0)).explicit_plus(); + assert_eq!(codec.parse(" +12 ", &Some(50.0)), Ok(Some(17.0))); + assert_eq!(codec.parse("+(2+3)", &Some(50.0)), Err(NotAValue), "rejects instead of falling back to the expression reader"); + assert_eq!(codec.format(&Some(17.0)), "+17"); + } + + #[test] + fn an_explicit_plus_codec_reads_a_long_run_of_unary_signs_without_recursing() { + let codec = NumberCodec::default().explicit_plus(); + let long = "+ ".repeat(32_768); + assert_eq!(codec.parse(&format!("{long}--(2+3)"), &Some(10.0)), Ok(Some(5.0))); + assert_eq!(codec.parse(&long, &Some(10.0)), Err(NotAValue)); + } } diff --git a/crates/behavior/src/press.rs b/crates/behavior/src/press.rs index 227098fa3f..d1765008c6 100644 --- a/crates/behavior/src/press.rs +++ b/crates/behavior/src/press.rs @@ -584,6 +584,23 @@ impl Open { !self.reported || (self.dragging && !self.drag_reported) || self.passing.is_some() } + /// The pointer reached `at`, by a move or by the button going up there: once past `slop` from the press, a target + /// that senses a drag starts one, one that clicks and passes its drag waits for its hand-over, and any other loses + /// its click. A release with no move before it (the pointer jumped) is judged where it went up, so only a release + /// within slop clicks. + fn reach(&mut self, at: Pos2, slop: f32) { + if self.released_at.is_none() && !self.dragging && !self.abandoned && self.passing.is_none() && at.distance(self.start.origin) > slop { + if self.sense.contains(Sense::DRAG) { + self.dragging = true; + self.silent = false; + } else if self.sense.contains(Sense::CLICK | Sense::PASSES_DRAG) { + self.passing = Some(at); + } else { + self.abandoned = true; + } + } + } + /// A release now is a click. fn clicks(&self) -> bool { !self.dragging && !self.abandoned && !self.left && self.passing.is_none() && self.sense.contains(Sense::CLICK) @@ -693,21 +710,8 @@ impl PressMachine { match *event { PointerEvent::Moved { at, .. } => { pos = at; - if let Some(open) = &mut self.open - && open.released_at.is_none() - && !open.dragging - && !open.abandoned - && open.passing.is_none() - && at.distance(open.start.origin) > input.slop - { - if open.sense.contains(Sense::DRAG) { - open.dragging = true; - open.silent = false; - } else if open.sense.contains(Sense::CLICK | Sense::PASSES_DRAG) { - open.passing = Some(at); - } else { - open.abandoned = true; - } + if let Some(open) = &mut self.open { + open.reach(at, input.slop); } } PointerEvent::Gone => { @@ -717,11 +721,14 @@ impl PressMachine { } PointerEvent::Pressed { button, pos: at, time, clicks } => { pos = at; - // A release held for the next pass gives way to a new press; it ends in this pass. + // A release held for the next pass gives way to a new press; it ends in this pass. A drag whose + // start that pass still owed was never reported, so the release is no drag either: every part reads + // `Down`, a `Release`, or `DragStart` then `Drag`, never a drag's end that never began. The press's + // target hears where the button went up in `Release::pos`, and no click is at that distance. if let Some(open) = self.open && let Some((up, click)) = open.released_at { - released = Some((open.target, open.start, up, open.dragging, click, open.silent)); + released = Some((open.target, open.start, up, open.drag_reported, click, open.silent)); self.open = None; } // A secondary press during an open primary press goes beside it, to the context target `pick` gives @@ -788,6 +795,9 @@ impl PressMachine { if self.open.is_some_and(|open| open.start.button != button || open.released_at.is_some()) { continue; } + if let Some(open) = &mut self.open { + open.reach(at, input.slop); + } if let Some(open) = &mut self.open && open.owes_phase() { @@ -1114,4 +1124,136 @@ mod tests { assert!(matches!(end.phase, Some(PressPhase::Release { click: false, .. })), "{:?}", end.phase); assert_eq!(end.activated, None); } + + /// A release past slop with no move before it (the pointer jumped while the button was down) reads as a move there + /// and a release: it does what a move past slop and a release in one pass do, for every sense. A target that drags + /// starts its drag and ends it, with no click. + #[test] + fn a_jump_release_past_slop_starts_and_ends_a_drag() { + let sense = Sense::CLICK | Sense::DRAG; + let (far, near) = (SLOP * 4.0, SLOP / 2.0); + let jumped = phases(&[&[press(0.0, 1.0)], &[up(far)], &[]], sense); + assert_eq!(jumped, phases(&[&[press(0.0, 1.0)], &[moved(far), up(far)], &[]], sense), "a jump is a move and a release"); + assert_eq!(jumped, "D S R", "the drag starts where the button went up, then ends with no click"); + assert_eq!(phases(&[&[press(0.0, 1.0)], &[up(near)]], sense), "D R!", "a jump within slop still clicks"); + + let mut machine = PressMachine::new(); + pass(&mut machine, &[press(0.0, 1.0)], sense); + let start = pass(&mut machine, &[up(far)], sense); + assert!(matches!(start.phase, Some(PressPhase::DragStart { pos, .. }) if pos == pos2(far, 0.0)), "{:?}", start.phase); + assert!(machine.release_held(), "the release waits for the owed DragStart"); + let end = pass(&mut machine, &[], sense); + assert!(matches!(end.phase, Some(PressPhase::Release { pos, click: false, .. }) if pos == pos2(far, 0.0)), "{:?}", end.phase); + assert!(end.dragging, "the release ends a drag"); + assert_eq!(end.activated, None, "a jump release past slop is no click"); + } + + /// A jump release past slop on a target that clicks and passes its drag passes the press as a move past slop does: + /// the pass reports it in `passes`, a shape below that takes it drags and releases with no click, and a press no + /// shape takes is abandoned with no click. + #[test] + fn a_jump_release_past_slop_on_a_part_that_passes_its_drag_passes_the_press() { + let far = SLOP * 4.0; + let origin = pos2(0.0, 0.0); + for events in [&[up(far)][..], &[moved(far), up(far)][..]] { + // No shape takes the press: the next pass abandons it, and its release is no click. + let mut machine = PressMachine::new(); + passing_pass(&mut machine, &[press(0.0, 1.0)]); + let passed = passing_pass(&mut machine, events); + assert_eq!(passed.passes.map(|start| start.origin), Some(origin), "{events:?}: {passed:?}"); + assert!(matches!(passed.phase, Some(PressPhase::Held { .. })) && passed.activated.is_none(), "{events:?}: {passed:?}"); + let end = passing_pass(&mut machine, &[]); + assert_eq!(end.target, Some(1)); + assert!(matches!(end.phase, Some(PressPhase::Release { click: false, .. })), "{events:?}: {:?}", end.phase); + assert_eq!(end.activated, None, "{events:?}: a passed press no shape took is no click"); + + // The shape below takes it: it starts the drag where the button went up and ends it with no click. + let mut machine = PressMachine::new(); + passing_pass(&mut machine, &[press(0.0, 1.0)]); + assert!(passing_pass(&mut machine, events).passes.is_some(), "{events:?}"); + let handed = machine.hand_over(2, Sense::DRAG).expect("the shape below takes the drag"); + assert_eq!(handed.target, Some(2)); + assert!( + matches!(handed.phase, Some(PressPhase::DragStart { start, pos }) if start.origin == origin && pos == pos2(far, 0.0)), + "{events:?}: {:?}", + handed.phase + ); + let end = passing_pass(&mut machine, &[]); + assert_eq!(end.target, Some(2)); + assert!(matches!(end.phase, Some(PressPhase::Release { click: false, .. })), "{events:?}: {:?}", end.phase); + assert_eq!(end.activated, None, "{events:?}: a passed press is no click"); + } + assert_eq!(phases(&[&[press(0.0, 1.0)], &[up(SLOP / 2.0)]], PASSES), "D R!", "a jump within slop is the shape's click"); + } + + /// A press whose button jumped far and came up in a batch that also pressed again: the release ends the press in + /// that pass, so the `DragStart` the jump owed never comes. The release is then no drag either, and the parts read + /// `Down` then a `Release` with no drag between them: a drag's end that never began would leave a part that tracks + /// a drag holding a press forever. The new press reports its `Down` in the next pass. + #[test] + fn a_jump_release_that_gives_way_to_a_new_press_reports_no_drag() { + let sense = Sense::CLICK | Sense::DRAG; + let far = SLOP * 4.0; + let jumped = [up(far), press(far, 1.1)]; + assert_eq!(phases(&[&[press(0.0, 1.0)], &jumped[..], &[]], sense), "D R D", "the release ends the press with no drag of its own"); + + let mut machine = PressMachine::new(); + pass(&mut machine, &[press(0.0, 1.0)], sense); + let end = pass(&mut machine, &jumped, sense); + assert!( + matches!(end.phase, Some(PressPhase::Release { start, pos, click: false }) if start.origin == pos2(0.0, 0.0) && pos == pos2(far, 0.0)), + "{:?}", + end.phase + ); + assert!(!end.dragging, "the press never reported its drag's start, so its release claims none"); + assert_eq!(end.activated, None, "a jump release past slop is no click"); + assert!(!machine.dragging(), "the new press is no drag either"); + pass(&mut machine, &[], sense); + let next = machine.open.map(|open| open.start.origin); + assert!(matches!(next, Some(place) if place == pos2(far, 0.0)), "the new press is open from where it went down"); + + // A press that did report its drag's start keeps its drag's end, whatever gives way to it. + let mut machine = PressMachine::new(); + pass(&mut machine, &[press(0.0, 1.0)], sense); + assert!(matches!(pass(&mut machine, &[up(far)], sense).phase, Some(PressPhase::DragStart { .. })), "the jump starts the drag"); + let end = pass(&mut machine, &[up(far), press(far, 1.3)], sense); + assert!(matches!(end.phase, Some(PressPhase::Release { click: false, .. })), "{:?}", end.phase); + assert!(end.dragging, "the release ends the drag the part saw start"); + } + + /// A jump release past slop on a part that clicks and passes its drag reads the same when a new press shares its + /// batch: the release ends the press before the move ever passes the drag on, so it reports no drag, and the new + /// press opens from where it went down. + #[test] + fn a_passed_jump_release_that_gives_way_to_a_new_press_reports_no_drag() { + let far = SLOP * 4.0; + let mut machine = PressMachine::new(); + passing_pass(&mut machine, &[press(0.0, 1.0)]); + let end = passing_pass(&mut machine, &[up(far), press(far, 1.5)]); + assert!(matches!(end.phase, Some(PressPhase::Release { pos, click: false, .. }) if pos == pos2(far, 0.0)), "{:?}", end.phase); + assert!(!end.dragging, "no shape was ever told the drag started, so its release claims none"); + assert_eq!(end.activated, None, "a jump release past slop is no click"); + assert_eq!(machine.target(), Some(1), "the new press is open"); + assert!(!machine.dragging(), "and it is no drag"); + } + + /// A jump release past slop on a target that only clicks abandons the click as a move past slop does: the release + /// is reported with no click and nothing activates. + #[test] + fn a_jump_release_past_slop_on_a_click_only_part_abandons_the_click() { + let (far, near) = (SLOP * 4.0, SLOP / 2.0); + let jumped = phases(&[&[press(0.0, 1.0)], &[up(far)]], Sense::CLICK); + assert_eq!(jumped, phases(&[&[press(0.0, 1.0)], &[moved(far), up(far)]], Sense::CLICK), "a jump is a move and a release"); + assert_eq!(jumped, "D R", "the release is no click"); + assert_eq!(phases(&[&[press(0.0, 1.0)], &[up(near)]], Sense::CLICK), "D R!", "a jump within slop still clicks"); + + let mut machine = PressMachine::new(); + pass(&mut machine, &[press(0.0, 1.0)], Sense::CLICK); + let end = pass(&mut machine, &[up(far)], Sense::CLICK); + assert_eq!(end.target, Some(1)); + assert!(matches!(end.phase, Some(PressPhase::Release { pos, click: false, .. }) if pos == pos2(far, 0.0)), "{:?}", end.phase); + assert!(!end.dragging, "a click-only part never drags"); + assert_eq!(end.activated, None, "the abandoned click activates nothing"); + assert!(machine.target().is_none(), "the release ends the press"); + } } diff --git a/crates/behavior/src/quantity.rs b/crates/behavior/src/quantity.rs index af3c06e5d1..5fc76f2b05 100644 --- a/crates/behavior/src/quantity.rs +++ b/crates/behavior/src/quantity.rs @@ -7,7 +7,7 @@ use crate::codec::NotAValue; const DIGIT_BLOCKS: [u32; 5] = [0x30, 0x660, 0x6F0, 0x966, 0xFF10]; /// The value of a decimal digit of any supported script. -fn digit(c: char) -> Option { +pub(crate) fn digit(c: char) -> Option { DIGIT_BLOCKS.iter().find_map(|&zero| (zero..zero + 10).contains(&(c as u32)).then(|| c as u32 - zero)) } @@ -198,15 +198,12 @@ impl Parse<'_> { /// A factor; `scaled` says it starts a term, where a number with no unit counts as the reader's bare factor. /// Otherwise it is a multiplier, which may be a percentage. fn factor(&mut self, scaled: bool) -> Result { - match self.peek() { - Some('-') => { - self.at += 1; - self.factor(scaled).map(|value| -value) - } - Some('+') => { - self.at += 1; - self.factor(scaled) - } + let mut negative = false; + while let Some(sign @ ('+' | '-')) = self.peek() { + negative ^= sign == '-'; + self.at += 1; + } + let value = match self.peek() { Some('(') => { self.at += 1; let value = self.expr()?; @@ -214,7 +211,8 @@ impl Parse<'_> { Ok(value) } _ => self.quantity(scaled), - } + }?; + Ok(if negative { -value } else { value }) } /// A number and the longest registered unit spelling at the start of the letters after it, or after a `/` when a diff --git a/crates/behavior/src/wheel.rs b/crates/behavior/src/wheel.rs index a5de8554a7..9d81b764ea 100644 --- a/crates/behavior/src/wheel.rs +++ b/crates/behavior/src/wheel.rs @@ -106,8 +106,20 @@ pub struct Wheel { /// 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. + /// modal layer held the wheel: the turn began or went on under the modal, and it stays marked until it ends. An + /// app's own modal window marks it too (`CanvasSpace::mark_wheel_modal`). pub modal: bool, + /// The owner claimed an earlier share of the running gesture (`CanvasSpace::claim_wheel`): it takes the gesture + /// for itself. For the taker that owns the gesture; another taker's share is never claimed. + pub claimed: bool, + /// The `scroll` of the running gesture's shares the owner claimed before this one. Motion the owner did not + /// claim is not counted. + pub claimed_gathered: Vec2, + /// The `zoom_lines` of the running gesture's shares the owner claimed before this one. + pub claimed_zoom_gathered: Vec2, + /// The motion the owner said it used up (`spent`) with its claims of the running gesture so far, in its own + /// unit: `claimed_gathered` or `claimed_zoom_gathered` less this is what the claimed shares left over. + pub claimed_spent: Vec2, } /// The eased motion of a canvas's line wheel: notches gather into owed motion that later passes pay out. @@ -256,6 +268,10 @@ impl Wheel { moved: false, held: mods, modal: false, + claimed: false, + claimed_gathered: Vec2::ZERO, + claimed_zoom_gathered: Vec2::ZERO, + claimed_spent: Vec2::ZERO, } } 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/src/ui/mod.rs b/crates/color-ui/src/ui/mod.rs index e0fb35b3e2..d0a5b4eb0a 100644 --- a/crates/color-ui/src/ui/mod.rs +++ b/crates/color-ui/src/ui/mod.rs @@ -81,8 +81,8 @@ pub use picker::{ PickedColor, ScreenPickGesture, TrackRamp, }; pub use picker_dialog::{ - ColorPickerDialog, ColorPickerDialogLayout, ColorPickerDialogWords, ColorPickerMemory, ColorPickerResult, ColorPickerTab, PickerLibrary, - PickerSwatches, + ColorPickerDialog, ColorPickerDialogLayout, ColorPickerDialogWords, ColorPickerMemory, ColorPickerResult, ColorPickerTab, PickedSwatch, + PickerLibrary, PickerSwatches, }; pub use popover::{ColorPopover, ColorPopoverOutput}; pub use profile_prompts::{ProfileAction, ProfileAnswer, ProfileMismatchDialog, ProfileMode, ProfileQuestion, ProfileStatus, ProfileWords}; diff --git a/crates/color-ui/src/ui/picker/full.rs b/crates/color-ui/src/ui/picker/full.rs index 9631147625..0a6ffb7525 100644 --- a/crates/color-ui/src/ui/picker/full.rs +++ b/crates/color-ui/src/ui/picker/full.rs @@ -99,6 +99,7 @@ impl<'a> Body<'a> { if shown.restore && let Mixed::Same(current) = pass.compare { + got.restored = true; got.clicks.push(current); } if let Some(warning) = shown.warning.and_then(|at| self.warnings.get(at)) { diff --git a/crates/color-ui/src/ui/picker/mod.rs b/crates/color-ui/src/ui/picker/mod.rs index d98387f4c6..8b462a9966 100644 --- a/crates/color-ui/src/ui/picker/mod.rs +++ b/crates/color-ui/src/ui/picker/mod.rs @@ -106,6 +106,8 @@ pub struct ColorPickerOutput { pub events: EditEvents, /// The screen-pick button's press this pass. pub screen_pick: Option, + /// The compare block's current half was activated this pass. + pub restored: bool, } impl Outcome for ColorPickerOutput { @@ -181,6 +183,7 @@ struct Collected { edits: EditEvents, /// Colours the compare swatch and the warning chips set. clicks: Vec, + restored: bool, screen_pick: Option, model_pick: Option<&'static str>, /// The mode the "Field shows" group picked. @@ -430,8 +433,8 @@ impl<'a> ColorPicker<'a> { events: EditEvents::new(), }; let shown = Stack::new().label(label).show(ui, |ui, body| run.show(ui, body)); - let (events, screen_pick) = shown.inner.unwrap_or_default(); - ColorPickerOutput { response: shown.output, events, screen_pick } + let (events, screen_pick, restored) = shown.inner.unwrap_or_default(); + ColorPickerOutput { response: shown.output, events, screen_pick, restored } } } @@ -461,7 +464,7 @@ struct Run<'s, 'a> { } impl<'a> Run<'_, 'a> { - fn show(&mut self, ui: &mut Ui, body: &mut BodyCx<'_>) -> (EditEvents, Option) { + fn show(&mut self, ui: &mut Ui, body: &mut BodyCx<'_>) -> (EditEvents, Option, bool) { let memo = body.memory::().clone(); let held_mode = self.mode.as_ref().and_then(|held| held.read(&mut *body)).and_then(|held| held.same().copied()); let mut mode = held_mode.unwrap_or(memo.mode); @@ -546,7 +549,7 @@ impl<'a> Run<'_, 'a> { None => body.memory::().model = Some(next), } } - (std::mem::take(&mut self.events), got.screen_pick) + (std::mem::take(&mut self.events), got.screen_pick, got.restored) } /// Lands `event`, an edit of the colour: a gesture's end takes the colour it began from, the binding takes the diff --git a/crates/color-ui/src/ui/picker_dialog.rs b/crates/color-ui/src/ui/picker_dialog.rs index e74230735c..13a7cb43b1 100644 --- a/crates/color-ui/src/ui/picker_dialog.rs +++ b/crates/color-ui/src/ui/picker_dialog.rs @@ -128,9 +128,19 @@ impl PickerSwatches { /// The Color Swatches view: the library `Select` over the chosen library's spaced palette, whose cell equal to the colour /// in `held` is marked and whose pick replaces `held`; the notice for a library without swatches. `library` is the /// remembered index, which may lie past the end; it is written only when the user chooses another. The dialog's buttons -/// stand in the cell after it, as they head the Full picker's second column. -fn show_swatches(ui: &mut Ui, view: &PickerSwatches, library: &mut usize, held: &mut Mixed, library_label: &Label) { +/// stand in the cell after it, as they head the Full picker's second column. `selected`, the swatch the colour was +/// picked from, is the marked cell when its library is shown. Returns the swatch clicked this pass, also one with the +/// colour already held, whose colour `held` then takes. +fn show_swatches( + ui: &mut Ui, + view: &PickerSwatches, + library: &mut usize, + held: &mut Mixed, + selected: Option, + library_label: &Label, +) -> Option { let mut chosen = (*library).min(view.libraries.len().saturating_sub(1)); + let mut clicked = None; Grid::new(TWO_COLUMNS).fit(GridFit::Fixed).cells(CellAlign::Top).gap(Gap::Section).show(ui, |ui, _| { Stack::new().show(ui, |ui, _| { if !view.libraries.is_empty() { @@ -145,10 +155,20 @@ fn show_swatches(ui: &mut Ui, view: &PickerSwatches, library: &mut usize, held: Some(lib) => { // A colour that is not set marks no cell of a library without it; black stands for "none yet". let color = held.same().map_or(Srgba::BLACK, |picked| picked.color); - let shown = SwatchPalette::new(lib.name.clone(), Bind::given(color), &lib.swatches).spacing(SwatchSpacing::Spaced).show(ui); + let marked = selected.filter(|s| s.library == chosen).map(|s| s.index); + let shown = SwatchPalette::new(lib.name.clone(), Bind::given(color), &lib.swatches) + .spacing(SwatchSpacing::Spaced) + .selected_swatch(marked) + .show(ui); if let Some(picked) = shown.edit.as_ref().and_then(|edit| edit.value()).copied() { *held = Mixed::Same(PickedColor::rgb(picked)); } + // The clicked swatch's own colour, also when the palette files no edit for it (the colour held, or + // one that rounds to it). + if let Some((index, (_, color))) = shown.picked_swatch.and_then(|index| Some((index, lib.swatches.get(index)?))) { + *held = Mixed::Same(PickedColor::rgb(*color)); + clicked = Some(PickedSwatch { library: chosen, index }); + } } None => { Notice::new(Tone::Neutral, view.empty.clone()).layout(NoticeLayout::Centred).show(ui); @@ -157,6 +177,24 @@ fn show_swatches(ui: &mut Ui, view: &PickerSwatches, library: &mut usize, held: }); let _ = FooterSlot::new().show(ui); }); + clicked +} + +/// A swatch of a [`ColorPickerDialog`]'s Color Swatches view, by its place in the [`PickerSwatches`] the app gave. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub struct PickedSwatch { + /// The index of its library in [`PickerSwatches::libraries`]. + pub library: usize, + /// The index of the swatch in that library's [`PickerLibrary::swatches`]. + pub index: usize, +} + +impl PickedSwatch { + /// The swatch at `index` of library `library`. + pub fn new(library: usize, index: usize) -> Self { + PickedSwatch { library, index } + } } /// The remembered scope of [`ColorPickerMemory`]. @@ -170,6 +208,9 @@ pub struct ColorPickerResult { pub key: String, /// The colour, with the model values the user typed while they still give it (CMYK inks, Lab values outside sRGB). pub picked: PickedColor, + /// The swatch of the Color Swatches view the colour was picked from, when the last change to the colour was a click + /// on that swatch; `None` when the colour was set any other way, or changed after the click. + pub swatch: Option, } /// How a [`ColorPickerDialog`] lays out its body. @@ -238,6 +279,9 @@ pub struct ColorPickerDialog { opening: Option, /// The colour as it stands; `None` until the first pick when the dialog opened without one. current: Option, + /// The colour was set by the caller ([`set_color`](Self::set_color), [`pick_swatch`](Self::pick_swatch)); the + /// Only Web Colors snap at the start then leaves it as it is. + color_set: bool, compare: bool, /// [`no_current`](Self::no_current). no_current: bool, @@ -247,6 +291,8 @@ pub struct ColorPickerDialog { working_rgb: Option>, gamut: Option>, swatches: Option, + /// The swatch the current colour was picked from, while no other change has followed the click. + picked_swatch: Option, eyedropper: bool, canvas_samples: bool, canvas: Option, @@ -420,6 +466,7 @@ impl ColorPickerDialog { title_args: Vec::new(), opening, current: opening, + color_set: false, compare: true, no_current: false, remember: true, @@ -428,6 +475,7 @@ impl ColorPickerDialog { working_rgb: None, gamut: None, swatches: None, + picked_swatch: None, eyedropper: true, canvas_samples: true, canvas: None, @@ -449,10 +497,12 @@ impl ColorPickerDialog { } /// In the Full layout, a body button after Cancel switches between Color Models and Color Swatches: a library `Select` over a spaced - /// `SwatchPalette` with the current colour's cell marked, a pick being an edit. Without it there is no button. + /// `SwatchPalette` with the current colour's cell marked, a pick being an edit. Without it there is no button. A swatch + /// picked from the view it replaces is no longer named. #[must_use] pub fn swatch_view(mut self, swatches: PickerSwatches) -> ColorPickerDialog { self.swatches = Some(swatches); + self.picked_swatch = None; self } @@ -465,9 +515,13 @@ impl ColorPickerDialog { } /// Sets the dialog's layout: Full (Photoshop) or Tabbed (Word's Colors dialog). + /// A layout other than Full clears the picked swatch and keeps the current color. #[must_use] pub fn layout(mut self, l: ColorPickerDialogLayout) -> ColorPickerDialog { self.layout = l; + if l != ColorPickerDialogLayout::Full { + self.picked_swatch = None; + } self } @@ -497,7 +551,12 @@ impl ColorPickerDialog { /// what the sRGB colour converts to (storytold/photocraft#4196). #[must_use] pub fn kept(mut self, values: craft_theme::ModelValues) -> ColorPickerDialog { - for held in [&mut self.opening, &mut self.current].into_iter().flatten() { + if let Some(held) = &mut self.opening { + held.model = Some(values); + } + if self.picked_swatch.is_none() + && let Some(held) = &mut self.current + { held.model = Some(values); } self @@ -614,6 +673,28 @@ impl ColorPickerDialog { /// model values when it has them, and the colour is what OK answers. The compare swatch keeps the opening colour. pub fn set_color(&mut self, picked: PickedColor) { self.current = Some(picked); + self.color_set = true; + self.picked_swatch = None; + } + + /// The swatch of the Color Swatches view the colour was picked from, while no other change has followed the click + /// (what OK answers as [`ColorPickerResult::swatch`]). + pub fn picked_swatch(&self) -> Option { + self.picked_swatch + } + + /// Picks `swatch` of the Color Swatches view as a click on it would, for automation and scripts: the colour becomes + /// the swatch's and its library the one shown. `None` when the layout is not Full or the view has no such swatch. + pub fn pick_swatch(&mut self, swatch: PickedSwatch) -> Option<()> { + if self.layout != ColorPickerDialogLayout::Full { + return None; + } + let (_, color) = self.swatches.as_ref()?.libraries.get(swatch.library)?.swatches.get(swatch.index)?; + self.current = Some(PickedColor::rgb(*color)); + self.color_set = true; + self.memory.library = swatch.library; + self.picked_swatch = Some(swatch); + Some(()) } /// The colour Add to Swatches was pressed for, once; `None` otherwise. @@ -640,7 +721,7 @@ impl ColorPickerDialog { { Remembered::::new(MEMORY_SCOPE).store(host, &self.memory); } - Some(ColorPickerResult { key: self.key.clone(), picked }) + Some(ColorPickerResult { key: self.key.clone(), picked, swatch: self.picked_swatch }) } /// Runs the dialog's start for automation that reaches it before its first pass. @@ -651,6 +732,29 @@ impl ColorPickerDialog { } } + /// Sets one JSON field after the dialog's start: `swatch`, `color` or a memory field. + fn set_field(&mut self, field: &str, value: serde_json::Value) -> Result<(), String> { + if field == "swatch" { + if value.is_null() { + self.picked_swatch = None; + return Ok(()); + } + let index = |i: usize| value.get(i).and_then(serde_json::Value::as_u64).and_then(|n| usize::try_from(n).ok()); + let swatch = match (value.as_array().map(Vec::len), index(0), index(1)) { + (Some(2), Some(library), Some(index)) => PickedSwatch { library, index }, + _ => return Err(FieldRefusal::Rejects(&value).message(field)), + }; + return self.pick_swatch(swatch).ok_or_else(|| FieldRefusal::Rejects(&value).message(field)); + } + if field != "color" { + return set_serde_field(&mut self.memory, field, value); + } + let parsed = value.as_str().and_then(Srgba::from_hex); + let color = parsed.ok_or_else(|| FieldRefusal::Rejects(&value).message(field))?; + self.set_color(PickedColor { color, model: None }); + Ok(()) + } + /// The first pass: recalls the remembered field component and Only Web Colors, and with Only Web Colors on snaps /// the opening colour, which the compare swatch's current half follows (storytold/photocraft#4995). fn start(&mut self, host: Option<&Arc>) { @@ -672,7 +776,12 @@ impl ColorPickerDialog { { let [r, g, b] = web_safe([opening.color.r, opening.color.g, opening.color.b]); self.opening = Some(PickedColor { color: Srgba { r, g, b, a: opening.color.a }, model: None }); - self.current = self.opening; + if !self.color_set { + self.current = self.opening; + } + } + if let Some(swatch) = self.picked_swatch { + self.memory.library = swatch.library; } } @@ -710,24 +819,46 @@ impl StackDialog for ColorPickerDialog { self.instance } - /// `color` (`#rrggbb`, null when there is none yet), and the memory's own `mode`, `webColors`, `swatches`, `library`, `tab` - /// and `model`. + /// `color` (`#rrggbb`, null when there is none yet), `swatch` (`[library, index]` of the swatch the colour was picked + /// from, or null), and the memory's own `mode`, `webColors`, `swatches`, `library`, `tab` and `model`. fn json_fields(&self) -> Option { let mut fields = serde_fields(&self.memory)?; let color = self.current.map_or(serde_json::Value::Null, |picked| picked.color.to_hex().into()); - fields.as_object_mut()?.insert("color".to_owned(), color); + let swatch = self.picked_swatch.map_or(serde_json::Value::Null, |s| serde_json::json!([s.library, s.index])); + let object = fields.as_object_mut()?; + object.insert("color".to_owned(), color); + object.insert("swatch".to_owned(), swatch); Some(fields) } fn set_json_field(&mut self, ctx: &Context, field: &str, value: serde_json::Value) -> Result<(), String> { - // The dialog's start recalls the memory and snaps the opening colour; a field set before it would be overwritten. + self.set_json_fields(ctx, &[(field.to_owned(), value)]) + } + + /// Sets the fields in order; when one is refused, the fields and startup state are restored to their earlier values. + fn set_json_fields(&mut self, ctx: &Context, fields: &[(String, serde_json::Value)]) -> Result<(), String> { + if fields.is_empty() { + return Ok(()); + } + let before = ( + self.started, + self.host.clone(), + self.opening, + self.current, + self.color_set, + self.picked_swatch, + self.memory.clone(), + self.tab, + self.on_swatches, + ); self.start_headless(ctx); - if field != "color" { - return set_serde_field(&mut self.memory, field, value); + for (field, value) in fields { + if let Err(refusal) = self.set_field(field, value.clone()) { + (self.started, self.host, self.opening, self.current, self.color_set, self.picked_swatch, self.memory, self.tab, self.on_swatches) = + before; + return Err(refusal); + } } - let parsed = value.as_str().and_then(Srgba::from_hex); - let color = parsed.ok_or_else(|| FieldRefusal::Rejects(&value).message(field))?; - self.set_color(PickedColor { color, model: None }); Ok(()) } @@ -774,7 +905,8 @@ impl StackDialog for ColorPickerDialog { } }; let footer = ResetFooter::new(ui, None, true); - let changed = self.current != self.opening; + // A swatch picked at the opening colour is a change Reset takes back. + let changed = self.current != self.opening || self.picked_swatch.is_some(); let mut buttons = footer.buttons(FooterButton::new(common.ok.clone(), DialogRole::Accept).enabled(self.current.is_some()), changed).to_vec(); let full = self.layout == ColorPickerDialogLayout::Full; // The buttons after OK and Cancel are placed by position; their indices are read back from the list. @@ -809,6 +941,7 @@ impl StackDialog for ColorPickerDialog { layout, standard, swatches: view, + picked_swatch, working_rgb, .. } = self; @@ -817,6 +950,9 @@ impl StackDialog for ColorPickerDialog { let (sampled, busy, compare_with) = (sample.take(), *screen_busy, compare.then(|| opening.map_or(Mixed::Mixed, Mixed::Same))); let color = current.map(|current| current.color); let web_only = memory.web_colors; + let mut clicked = None; + let mut restored = false; + let mut sample_processed = false; let shown = Dialog::new(title.clone()) .opened(Bind::bound(open)) .buttons(buttons) @@ -846,7 +982,7 @@ impl StackDialog for ColorPickerDialog { // PLAN: the swatch view should keep the value fields and replace only the area and strip, which the picker body // (picker/mod.rs, not in this set) lays out; here it replaces the whole picker body. if let Some(view) = view.as_ref().filter(|_| memory.swatches) { - show_swatches(ui, view, &mut memory.library, &mut held, &words.library); + clicked = show_swatches(ui, view, &mut memory.library, &mut held, *picked_swatch, &words.library); return; } let mut models = models_with(working_rgb, |on| on.full); @@ -874,16 +1010,26 @@ impl StackDialog for ColorPickerDialog { .eyedropper_busy(busy); if let Some(sampled) = sampled { picker = picker.sampled(sampled); + sample_processed = true; } if let Some(compare) = compare_with { picker = picker.compare(compare); } picker = picker.compare_none(*no_current); - if let Some(gesture) = picker.show(ui).screen_pick { + let output = picker.show(ui); + restored = output.restored; + if let Some(gesture) = output.screen_pick { *pending_screen = Some(gesture); } }); - self.current = held.same().copied(); + let after = held.same().copied(); + // A swatch click names the swatch; any other change to the colour leaves it picked from no swatch. + if clicked.is_some() { + self.picked_swatch = clicked; + } else if restored || sample_processed || after != self.current { + self.picked_swatch = None; + } + self.current = after; let (picked, closed) = (shown.output.picked, shown.output.closed); if picked.is_some() && picked == toggle_at { @@ -893,6 +1039,7 @@ impl StackDialog for ColorPickerDialog { let ok = (picked == Some(0) || closed == Some(CloseReason::Enter)) && self.current.is_some(); if !ok && picked == Some(1) && footer.resetting() { self.current = self.opening; + self.picked_swatch = None; return None; } if picked.is_some() && picked == add_at { diff --git a/crates/color-ui/src/ui/swatches/panel.rs b/crates/color-ui/src/ui/swatches/panel.rs index 69c854b2aa..b890470ab8 100644 --- a/crates/color-ui/src/ui/swatches/panel.rs +++ b/crates/color-ui/src/ui/swatches/panel.rs @@ -101,6 +101,7 @@ pub struct SwatchesPanel<'a> { report_invalid_renames: bool, payloads: Vec>, row_items: Option>, + host_version: Option, document: Option, select_groups: bool, } @@ -135,6 +136,7 @@ impl<'a> SwatchesPanel<'a> { report_invalid_renames: false, payloads: Vec::new(), row_items: None, + host_version: None, document: None, select_groups: false, } @@ -240,6 +242,14 @@ impl<'a> SwatchesPanel<'a> { self } + /// The version of everything the host's `row_items`, `takes_drop` and `drag_payload` closures read, as + /// `PresetBrowser::host_version` takes it: while it holds and nothing reaches the swatches, their view repaints its + /// last run instead of running in every pass. + pub fn host_version(mut self, version: u64) -> Self { + self.host_version = Some(version); + self + } + /// The document whose swatches the panel shows. The browser keeps its own state (an open rename field, the scroll /// position) for each document, so a rename left open in one document does not open on another document's /// swatch of the same name. Without it the browser keeps that state for the `Ui` it is shown in. @@ -274,6 +284,7 @@ impl<'a> SwatchesPanel<'a> { report_invalid_renames, payloads, row_items, + host_version, document, select_groups, } = self; @@ -316,6 +327,9 @@ impl<'a> SwatchesPanel<'a> { if let Some(id) = document_id { browser = browser.browser_id(id); } + if let Some(version) = host_version { + browser = browser.host_version(version); + } if let Some(options) = footer_options { browser = browser.footer(options); } diff --git a/crates/color-ui/tests/it/picker.rs b/crates/color-ui/tests/it/picker.rs index 03119e8114..847a042376 100644 --- a/crates/color-ui/tests/it/picker.rs +++ b/crates/color-ui/tests/it/picker.rs @@ -6,7 +6,7 @@ use std::rc::Rc; use craft_behavior::Mixed; use craft_color_ui::ui::{ ChannelRow, ChannelRowOutput, ChannelRule, ColorPicker, ColorPickerDialog, ColorPickerDialogLayout, ColorPickerLayout, ColorPickerTab, - ColorPopover, ColorReadout, ColorWarning, PickedColor, PickerLibrary, PickerSwatches, + ColorPopover, ColorReadout, ColorWarning, PickedColor, PickedSwatch, PickerLibrary, PickerSwatches, }; use craft_host::{AppInfo, Host}; use craft_theme::{ColorModel, HsbModel, LabModel, ModelValues, OklchModel, RgbModel, Rgba, Size, Srgba, ThemeId}; @@ -509,6 +509,324 @@ fn the_color_picker_dialogs_swatch_view_marks_the_current_colour_and_a_pick_is_a assert!(fixture.texts().iter().any(|run| run.text == "No swatches"), "an empty library shows the notice"); } +const SWATCH_RED: Srgba = Srgba { r: 1.0, g: 0.0, b: 0.0, a: 1.0 }; +const SWATCH_BLUE: Srgba = Srgba { r: 0.0, g: 0.0, b: 1.0, a: 1.0 }; + +/// A picker opened on red over two libraries, showing library 1: two swatches of one blue, and red. +fn swatch_picker() -> (Rc>, Fixture) { + let (red, blue) = (SWATCH_RED, SWATCH_BLUE); + let id = dialog_id(("color-picker", "fill")); + let dialogs = Rc::new(RefCell::new(DialogHost::new())); + let shown = Rc::clone(&dialogs); + let mut fixture = Fixture::new(move |ui| shown.borrow_mut().run(ui)); + fixture.room(vec2(900.0, 700.0)); + let libraries = vec![ + PickerLibrary::new("Basic", vec![(Label::from("Red"), red)]), + PickerLibrary::new("Inks", vec![(Label::from("Blue A"), blue), (Label::from("Blue B"), blue), (Label::from("Ink Red"), red)]), + ]; + dialogs.borrow_mut().open(ColorPickerDialog::new("fill", "Fill", red).swatch_view(PickerSwatches::new(libraries, "No swatches"))); + fixture.idle(6); + let ctx = fixture.ctx().clone(); + assert_eq!(dialogs.borrow_mut().set_json_field(&ctx, id, "swatches", serde_json::json!(true)), Ok(())); + assert_eq!(dialogs.borrow_mut().set_json_field(&ctx, id, "library", serde_json::json!(1)), Ok(())); + fixture.idle(4); + (dialogs, fixture) +} + +/// OK on the picker: its colour and the swatch it names. +fn swatch_answer(dialogs: &Rc>, fixture: &Fixture) -> Option<(String, Option)> { + let ctx = fixture.ctx().clone(); + assert!(dialogs.borrow_mut().confirm::(&ctx)); + dialogs.borrow_mut().take::().and_then(DialogResult::ok).map(|result| (result.picked.color.to_hex(), result.swatch)) +} + +/// OK names the swatch the colour was picked from, by its library and its place there, also among swatches of one +/// colour and for a click on the colour already held; a later change to the colour leaves it named by none. +#[trial] +fn the_color_picker_dialog_answers_the_swatch_its_colour_was_picked_from() { + let (red, blue) = (SWATCH_RED, SWATCH_BLUE); + let id = dialog_id(("color-picker", "fill")); + let open = swatch_picker; + let answer = swatch_answer; + let click = |fixture: &mut Fixture, name: &str| { + let cell = fixture.by_label(name).unwrap_or_else(|| panic!("the swatch view shows {name}")); + fixture.click(&cell).idle(4); + }; + + let (dialogs, mut fixture) = open(); + click(&mut fixture, "Blue B"); + assert_eq!(dialogs.borrow().get::().and_then(|d| d.picked_swatch()), Some(PickedSwatch::new(1, 1))); + let selected = |fixture: &Fixture, name: &str| { + let cell = fixture.by_label(name).unwrap_or_else(|| panic!("the swatch view shows {name}")); + fixture.tree().selected_of(cell.node).unwrap_or(false) + }; + assert!(selected(&fixture, "Blue B") && !selected(&fixture, "Blue A"), "the clicked one of two blue swatches is marked"); + assert_eq!(answer(&dialogs, &fixture), Some((blue.to_hex(), Some(PickedSwatch::new(1, 1)))), "the second of two blue swatches"); + + let (dialogs, mut fixture) = open(); + click(&mut fixture, "Ink Red"); + assert_eq!(answer(&dialogs, &fixture), Some((red.to_hex(), Some(PickedSwatch::new(1, 2)))), "a click on the colour already held"); + + let (dialogs, mut fixture) = open(); + click(&mut fixture, "Blue A"); + let ctx = fixture.ctx().clone(); + assert_eq!(dialogs.borrow_mut().set_json_field(&ctx, id, "color", serde_json::json!("#00ff00")), Ok(())); + fixture.idle(2); + assert_eq!(answer(&dialogs, &fixture), Some(("#00ff00".to_owned(), None)), "a colour set after the click is no swatch's"); + + let (dialogs, fixture) = open(); + assert_eq!(answer(&dialogs, &fixture), Some((red.to_hex(), None)), "the opening colour was picked from no swatch"); +} + +/// Automation picks a swatch by its place, as a click does, is refused a place the view does not have, and clears the +/// pick with null; a refused batch of fields leaves the colour, the pick and the library as they were. +#[trial] +fn automation_picks_a_color_picker_swatch_and_a_refused_batch_restores_the_pick() { + let (red, blue) = (SWATCH_RED, SWATCH_BLUE); + let id = dialog_id(("color-picker", "fill")); + let open = swatch_picker; + let answer = swatch_answer; + let (dialogs, fixture) = open(); + let ctx = fixture.ctx().clone(); + for bad in [serde_json::json!([1, 3]), serde_json::json!([2, 0]), serde_json::json!([1]), serde_json::json!("1,1")] { + assert!(dialogs.borrow_mut().set_json_field(&ctx, id, "swatch", bad.clone()).is_err(), "{bad} is refused"); + } + assert_eq!(dialogs.borrow_mut().set_json_field(&ctx, id, "swatch", serde_json::json!([1, 1])), Ok(())); + let fields = dialogs.borrow().get::().and_then(StackDialog::json_fields); + assert_eq!(fields.as_ref().map(|f| f["swatch"].clone()), Some(serde_json::json!([1, 1])), "the fields report the picked swatch"); + assert_eq!(answer(&dialogs, &fixture), Some((blue.to_hex(), Some(PickedSwatch::new(1, 1)))), "a swatch picked by automation"); + + let (dialogs, fixture) = open(); + let ctx = fixture.ctx().clone(); + assert_eq!(dialogs.borrow_mut().set_json_field(&ctx, id, "swatch", serde_json::json!([1, 1])), Ok(())); + assert_eq!(dialogs.borrow_mut().set_json_field(&ctx, id, "swatch", serde_json::Value::Null), Ok(())); + assert_eq!(dialog_field(&dialogs, "swatch"), Some(serde_json::Value::Null)); + assert_eq!(answer(&dialogs, &fixture), Some((blue.to_hex(), None)), "clearing the pick keeps its colour"); + + for picked in [None, Some(PickedSwatch::new(1, 1))] { + let (dialogs, fixture) = open(); + let ctx = fixture.ctx().clone(); + if let Some(swatch) = picked { + assert_eq!(dialogs.borrow_mut().get_mut::().expect("the picker").pick_swatch(swatch), Some(())); + } + assert_eq!(dialogs.borrow_mut().set_json_field(&ctx, id, "library", serde_json::json!(0)), Ok(())); + let before = dialogs.borrow().get::().and_then(StackDialog::json_fields); + let current = dialogs.borrow().get::().and_then(|d| d.current()); + for order in [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]] { + let edits = [ + ("color".to_owned(), serde_json::json!("#00ff00")), + ("swatch".to_owned(), serde_json::json!([0, 0])), + ("library".to_owned(), serde_json::json!(1)), + ]; + let mut fields: Vec<_> = order.into_iter().map(|index| edits[index].clone()).collect(); + fields.push(("swatch".to_owned(), serde_json::json!([2, 0]))); + assert!(dialogs.borrow_mut().set_json_fields(&ctx, id, &fields).is_err()); + assert_eq!(dialogs.borrow().get::().and_then(StackDialog::json_fields), before); + assert_eq!(dialogs.borrow().get::().and_then(|d| d.current()), current); + } + let color = if picked.is_some() { blue } else { red }; + assert_eq!(answer(&dialogs, &fixture), Some((color.to_hex(), picked)), "a refused batch restores the earlier pick"); + } +} + +/// A tabbed picker shows no swatch view, so it refuses a swatch pick and keeps its colour. +#[trial] +fn a_tabbed_color_picker_refuses_swatch_picks() { + let red = SWATCH_RED; + let libraries = vec![PickerLibrary::new("Inks", vec![(Label::from("Blue"), SWATCH_BLUE)])]; + let mut dialog = ColorPickerDialog::new("fill", "Fill", red) + .layout(ColorPickerDialogLayout::Tabbed) + .swatch_view(PickerSwatches::new(libraries, "No swatches")); + let before = dialog.json_fields(); + assert_eq!(dialog.pick_swatch(PickedSwatch::new(0, 0)), None); + assert_eq!(dialog.json_fields(), before); + assert!(dialog.set_json_field(&egui::Context::default(), "swatch", serde_json::json!([0, 0])).is_err()); + assert_eq!(dialog.json_fields(), before); + assert_eq!(dialog.current(), Some(PickedColor::rgb(red))); + assert_eq!(dialog.picked_swatch(), None); + + let mut dialog = dialog.layout(ColorPickerDialogLayout::Full); + assert_eq!(dialog.pick_swatch(PickedSwatch::new(0, 0)), Some(())); + let dialog = dialog.layout(ColorPickerDialogLayout::Tabbed); + assert_eq!(dialog.current(), Some(PickedColor::rgb(SWATCH_BLUE))); + assert_eq!(dialog.picked_swatch(), None); +} + +/// A refused batch of fields set before the dialog first runs leaves it as it was, and its start runs later as usual. +#[trial] +fn a_refused_color_picker_batch_restores_state_before_startup() { + let opened = Srgba::from_hex("#123456").expect("a color outside the web colors"); + let snapped = Srgba::from_hex("#003366").expect("the nearest web color"); + let id = dialog_id(("color-picker", "fill")); + for render in [false, true] { + for picked in [None, Some(PickedSwatch::new(1, 0))] { + let dialogs = Rc::new(RefCell::new(DialogHost::new())); + let shown = Rc::clone(&dialogs); + let mut fixture = Fixture::new(move |ui| shown.borrow_mut().run(ui)); + fixture.room(vec2(900.0, 700.0)); + fixture.host(std::sync::Arc::new(Host::builder(AppInfo { id: "swatch-batch-test", name: "Picker test", version: "0" }).build())); + fixture.idle(1); + let ctx = fixture.ctx().clone(); + dialogs.borrow_mut().open(ColorPickerDialog::new("fill", "Fill", SWATCH_RED)); + assert_eq!(dialogs.borrow_mut().set_json_field(&ctx, id, "webColors", serde_json::json!(true)), Ok(())); + assert_eq!(swatch_answer(&dialogs, &fixture), Some((SWATCH_RED.to_hex(), None))); + + let libraries = vec![ + PickerLibrary::new("Basic", vec![(Label::from("Red"), SWATCH_RED)]), + PickerLibrary::new("Inks", vec![(Label::from("Blue"), SWATCH_BLUE)]), + ]; + let request = craft_ui::runtime::requests::ColorRequest::new("fill", opened).on_swatches(); + let mut dialog = + ColorPickerDialog::from_request(request).tab(ColorPickerTab::Custom).swatch_view(PickerSwatches::new(libraries, "No swatches")); + if let Some(swatch) = picked { + assert_eq!(dialog.pick_swatch(swatch), Some(())); + } + let before = dialog.json_fields(); + let current = dialog.current(); + assert!(dialog.set_json_field(&ctx, "swatch", serde_json::json!([2, 0])).is_err()); + assert_eq!(dialog.json_fields(), before); + assert_eq!(dialog.opening(), Some(PickedColor::rgb(opened))); + assert_eq!(dialog.current(), current); + assert_eq!(dialog.picked_swatch(), picked); + let fields = [("swatch".to_owned(), serde_json::json!([0, 0])), ("swatch".to_owned(), serde_json::json!([2, 0]))]; + assert!(dialog.set_json_fields(&ctx, &fields).is_err()); + assert_eq!(dialog.json_fields(), before); + assert_eq!(dialog.opening(), Some(PickedColor::rgb(opened))); + assert_eq!(dialog.current(), current); + assert_eq!(dialog.picked_swatch(), picked); + + dialogs.borrow_mut().open(dialog); + if render { + fixture.idle(6); + assert_eq!(dialogs.borrow().get::().and_then(|d| d.opening()), Some(PickedColor::rgb(snapped))); + } + let color = if picked.is_some() { SWATCH_BLUE } else { snapped }; + assert_eq!(swatch_answer(&dialogs, &fixture), Some((color.to_hex(), picked)), "startup runs after a refused batch"); + dialogs.borrow_mut().open(ColorPickerDialog::new("fill", "Fill", SWATCH_RED)); + fixture.idle(6); + assert_eq!(dialog_field(&dialogs, "tab"), Some(serde_json::json!("custom"))); + assert_eq!(dialog_field(&dialogs, "swatches"), Some(serde_json::json!(true))); + assert_eq!(dialog_field(&dialogs, "library"), Some(serde_json::json!(usize::from(picked.is_some())))); + } + } +} + +/// Restoring the opening color clears an equal-color swatch selection. +#[trial] +fn restoring_the_current_color_clears_the_picked_swatch() { + let (dialogs, mut fixture) = swatch_picker(); + let red = fixture.by_label("Ink Red").expect("the opening color's swatch"); + fixture.click(&red).idle(4); + assert_eq!(dialogs.borrow().get::().and_then(|d| d.picked_swatch()), Some(PickedSwatch::new(1, 2))); + let models = fixture.by_label("Color Models").expect("the model view button"); + fixture.click(&models).idle(4); + let restore = fixture.by_label("Restore current color").expect("the compare block's current half"); + fixture.click(&restore).idle(4); + assert_eq!(dialogs.borrow().get::().and_then(|d| d.picked_swatch()), None); + assert_eq!(swatch_answer(&dialogs, &fixture), Some((SWATCH_RED.to_hex(), None))); +} + +/// Opening model values leave a picked swatch's RGB-only result unchanged. +#[trial] +fn opening_model_values_do_not_change_a_picked_swatch() { + let values = ModelValues::new("cmyk", &[0.0, 100.0, 100.0, 0.0]); + let libraries = vec![PickerLibrary::new("Inks", vec![(Label::from("Blue"), SWATCH_BLUE)])]; + let mut dialog = ColorPickerDialog::new("fill", "Fill", SWATCH_RED).swatch_view(PickerSwatches::new(libraries, "No swatches")); + assert_eq!(dialog.pick_swatch(PickedSwatch::new(0, 0)), Some(())); + let mut dialog = dialog.kept(values); + assert_eq!(dialog.opening(), Some(PickedColor { color: SWATCH_RED, model: Some(values) })); + assert_eq!(dialog.current(), Some(PickedColor::rgb(SWATCH_BLUE))); + let result = dialog.confirm(&egui::Context::default()).expect("the selected swatch"); + assert_eq!(result.picked, PickedColor::rgb(SWATCH_BLUE)); + assert_eq!(result.swatch, Some(PickedSwatch::new(0, 0))); +} + +/// A swatch picked before the dialog first runs keeps its colour through the Only Web Colors snap, and OK remembers its +/// library. +#[trial] +fn a_color_picker_swatch_picked_before_startup_survives_it() { + let red = SWATCH_RED; + let id = dialog_id(("color-picker", "fill")); + let answer = swatch_answer; + for render in [false, true] { + let dialogs = Rc::new(RefCell::new(DialogHost::new())); + let shown = Rc::clone(&dialogs); + let mut fixture = Fixture::new(move |ui| shown.borrow_mut().run(ui)); + fixture.room(vec2(900.0, 700.0)); + fixture.host(std::sync::Arc::new(Host::builder(AppInfo { id: "swatch-start-test", name: "Picker test", version: "0" }).build())); + fixture.idle(1); + let ctx = fixture.ctx().clone(); + dialogs.borrow_mut().open(ColorPickerDialog::new("fill", "Fill", red)); + assert_eq!(dialogs.borrow_mut().set_json_field(&ctx, id, "webColors", serde_json::json!(true)), Ok(())); + assert_eq!(dialogs.borrow_mut().set_json_field(&ctx, id, "swatches", serde_json::json!(true)), Ok(())); + assert_eq!(dialogs.borrow_mut().set_json_field(&ctx, id, "library", serde_json::json!(0)), Ok(())); + assert_eq!(answer(&dialogs, &fixture), Some((red.to_hex(), None))); + + let ink = Srgba::from_hex("#123456").expect("a colour outside the web colours"); + let libraries = + vec![PickerLibrary::new("Basic", vec![(Label::from("Red"), red)]), PickerLibrary::new("Inks", vec![(Label::from("Ink"), ink)])]; + let mut dialog = ColorPickerDialog::new("fill", "Fill", red).swatch_view(PickerSwatches::new(libraries, "No swatches")); + assert_eq!(dialog.pick_swatch(PickedSwatch::new(1, 0)), Some(())); + dialogs.borrow_mut().open(dialog); + if render { + fixture.idle(6); + } + assert_eq!(answer(&dialogs, &fixture), Some((ink.to_hex(), Some(PickedSwatch::new(1, 0)))), "startup keeps the direct pick"); + dialogs.borrow_mut().open(ColorPickerDialog::new("fill", "Fill", red)); + fixture.idle(6); + assert_eq!(dialog_field(&dialogs, "library"), Some(serde_json::json!(1)), "OK remembers the picked swatch's library"); + } +} + +/// Replacing the swatch view before startup keeps the selected color and clears its swatch identity. +#[trial] +fn replacing_the_swatch_view_before_startup_preserves_the_selected_color() { + for render in [false, true] { + let dialogs = Rc::new(RefCell::new(DialogHost::new())); + let shown = Rc::clone(&dialogs); + let mut fixture = Fixture::new(move |ui| shown.borrow_mut().run(ui)); + fixture.room(vec2(900.0, 700.0)); + fixture.host(std::sync::Arc::new(Host::builder(AppInfo { id: "swatch-replace-test", name: "Picker test", version: "0" }).build())); + fixture.idle(1); + let ctx = fixture.ctx().clone(); + let id = dialog_id(("color-picker", "fill")); + dialogs.borrow_mut().open(ColorPickerDialog::new("fill", "Fill", SWATCH_RED)); + assert_eq!(dialogs.borrow_mut().set_json_field(&ctx, id, "webColors", serde_json::json!(true)), Ok(())); + assert_eq!(swatch_answer(&dialogs, &fixture), Some((SWATCH_RED.to_hex(), None))); + + let ink = Srgba::from_hex("#123456").expect("a color outside the web colors"); + let libraries = vec![PickerLibrary::new("Inks", vec![(Label::from("Ink"), ink)])]; + let mut dialog = ColorPickerDialog::new("fill", "Fill", SWATCH_RED).swatch_view(PickerSwatches::new(libraries, "No swatches")); + assert_eq!(dialog.pick_swatch(PickedSwatch::new(0, 0)), Some(())); + let dialog = dialog.swatch_view(PickerSwatches::new(Vec::new(), "No swatches")); + assert_eq!(dialog.picked_swatch(), None); + assert_eq!(dialog.current(), Some(PickedColor::rgb(ink))); + dialogs.borrow_mut().open(dialog); + if render { + fixture.idle(6); + } + assert_eq!(swatch_answer(&dialogs, &fixture), Some((ink.to_hex(), None))); + } +} + +/// Sampling the selected swatch's color from the canvas clears its swatch identity. +#[trial] +fn an_equal_color_canvas_sample_clears_the_picked_swatch() { + let (dialogs, mut fixture) = swatch_picker(); + let blue = fixture.by_label("Blue B").expect("the blue swatch"); + fixture.click(&blue); + fixture.settle(); + assert_eq!(dialogs.borrow().get::().and_then(|d| d.picked_swatch()), Some(PickedSwatch::new(1, 1))); + let models = fixture.by_label("Color Models").expect("the model view button"); + fixture.click(&models); + fixture.settle(); + dialogs.borrow_mut().get_mut::().expect("the picker").requests().answer_eyedropper("fill", SWATCH_BLUE); + fixture.settle(); + assert_eq!(dialogs.borrow().get::().and_then(|d| d.current()), Some(PickedColor::rgb(SWATCH_BLUE))); + assert_eq!(dialogs.borrow().get::().and_then(|d| d.picked_swatch()), None); + assert_eq!(swatch_answer(&dialogs, &fixture), Some((SWATCH_BLUE.to_hex(), None))); +} + /// The Compact picker's width is set by the area and the strip, and its rows take that width; its popover is as wide /// wherever the well stands and whatever the room. #[trial] diff --git a/crates/craft/Cargo.toml b/crates/craft/Cargo.toml index 994f26396f..75ace36173 100644 --- a/crates/craft/Cargo.toml +++ b/crates/craft/Cargo.toml @@ -238,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 = [ @@ -490,6 +491,7 @@ file-formats-ase = ["file-formats", "craft-file-formats/ase"] file-formats-avif = ["file-formats", "craft-file-formats/avif"] file-formats-designcraft = ["file-formats", "craft-file-formats/designcraft"] file-formats-heif = ["file-formats", "craft-file-formats/heif"] +file-formats-jp2 = ["file-formats", "craft-file-formats/jp2"] file-formats-kra = ["file-formats", "craft-file-formats/kra"] file-formats-office = ["file-formats", "craft-file-formats/office"] file-formats-ora = ["file-formats", "craft-file-formats/ora"] @@ -591,11 +593,25 @@ image-codecs-avif = ["image-codecs", "craft-image-codecs/avif"] image-codecs-avif-decode = ["image-codecs", "craft-image-codecs/avif-decode"] image-codecs-cms = ["image-codecs", "craft-image-codecs/cms"] image-codecs-corpus = ["image-codecs", "craft-image-codecs/corpus"] +image-codecs-dds = ["image-codecs", "craft-image-codecs/dds"] +image-codecs-dicom = ["image-codecs", "craft-image-codecs/dicom"] +image-codecs-dpx = ["image-codecs", "craft-image-codecs/dpx"] +image-codecs-exr = ["image-codecs", "craft-image-codecs/exr"] +image-codecs-fits = ["image-codecs", "craft-image-codecs/fits"] image-codecs-heif = ["image-codecs", "craft-image-codecs/heif"] +image-codecs-iff = ["image-codecs", "craft-image-codecs/iff"] +image-codecs-jp2 = ["image-codecs", "craft-image-codecs/jp2"] +image-codecs-jpegls = ["image-codecs", "craft-image-codecs/jpegls"] image-codecs-jxl = ["image-codecs", "craft-image-codecs/jxl"] +image-codecs-jxl-encode = ["image-codecs", "craft-image-codecs/jxl-encode"] +image-codecs-pnm = ["image-codecs", "craft-image-codecs/pnm"] image-codecs-sgi = ["image-codecs", "craft-image-codecs/sgi"] image-codecs-sunraster = ["image-codecs", "craft-image-codecs/sunraster"] +image-codecs-tga = ["image-codecs", "craft-image-codecs/tga"] image-codecs-threads = ["image-codecs", "craft-image-codecs/threads"] +image-codecs-tiff = ["image-codecs", "craft-image-codecs/tiff"] +image-codecs-webp = ["image-codecs", "craft-image-codecs/webp"] +image-codecs-xpm = ["image-codecs", "craft-image-codecs/xpm"] imaging = ["dep:craft-imaging", "color-ui", "keymap"] @@ -623,6 +639,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"] @@ -802,6 +819,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/lib.rs b/crates/craft/src/lib.rs index ed6ccb2f84..f3865fae1d 100644 --- a/crates/craft/src/lib.rs +++ b/crates/craft/src/lib.rs @@ -331,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/pen/bezier/mod.rs b/crates/draw/src/ui/pen/bezier/mod.rs index 84decd8143..b611238295 100644 --- a/crates/draw/src/ui/pen/bezier/mod.rs +++ b/crates/draw/src/ui/pen/bezier/mod.rs @@ -11,6 +11,8 @@ mod style; mod tools; mod words; +use std::rc::Rc; + use craft_behavior::geometry::{SelectionOperation, axis_or_diagonal}; use craft_behavior::kurbo::{Point, Rect as DocRect, Vec2}; use craft_behavior::{ @@ -72,7 +74,8 @@ pub enum BezierTool { /// handles; a handle drag moves that handle alone; a drag on a straight segment bends it, or moves the whole path /// when every anchor is selected. Convert, - /// Anchors drawn, not edited (PhotoCraft's Path Selection and Pen tools). + /// Anchors drawn, not edited (PhotoCraft's Path Selection and Pen tools). The overlay declares no part and no + /// AccessKit object for its anchors and handles. Anchors, /// Add Anchor Point: a click on a segment, within 5 screen points of it, inserts an anchor at the hit's `t` /// ([`PathEdit::InsertAnchor`]); a drag inserts it and pulls out its handles as the Pen does @@ -394,6 +397,44 @@ struct Scene { selected: SelectedAnchors, } +/// A scene and what it was laid out from, kept on the overlay so that the later steps of the same pass reuse it. +struct Laid { + scene: Rc, + paths: Vec, + view: CanvasView, + rect: Rect, + reach: f32, + tool: BezierTool, +} + +impl Laid { + /// Whether the scene is the one of `paths` with these view, rect, reach and tool: a step that sees other paths (an + /// edit, a reset or the end of a press changed them) lays out its own. + fn matches(&self, paths: &[EditPath], view: &CanvasView, rect: Rect, reach: f32, tool: BezierTool) -> bool { + self.view == *view && self.rect == rect && self.reach.to_bits() == reach.to_bits() && self.tool == tool && self.paths == paths + } +} + +/// The number of scenes the overlay laid out on this thread, for trials that count the overlay's work. +#[cfg(all(test, feature = "screen-testing"))] +pub(crate) mod laid { + use std::cell::Cell; + + thread_local! { + static LAID: Cell = const { Cell::new(0) }; + } + + /// Counts one scene laid out. + pub(crate) fn add() { + LAID.with(|laid| laid.set(laid.get() + 1)); + } + + /// The scenes laid out since the last call, and starts the count again. + pub(crate) fn take() -> usize { + LAID.with(|laid| laid.replace(0)) + } +} + /// Paths with anchors and direction handles over a canvas, edited by the pointer and the keyboard as PhotoCraft's /// Direct Selection and Convert Point tools edit them. The value is the paths: a drag proposes them with the gesture's /// edit applied and Escape restores the start; [`BezierOutput::change`] carries the gesture's [`PathEdit`] from its @@ -420,7 +461,10 @@ struct Scene { /// [`path_options`](Self::path_options) change the look; [`hit_test`](Self::hit_test) answers the press priority /// without a pass. /// - The units and the zero point of the AccessKit values come from the canvas, and snapping of a dragged point is -/// the canvas's [`Snap`]. +/// the canvas's [`Snap`]. Under [`BezierTool::Anchors`] the anchors and handles have no parts and no AccessKit +/// objects. +/// - A pass lays out its anchors, handles and segments once and its steps share them; a step that sees other paths +/// (after an edit or a reset) lays them out again. #[derive(craft_ui::contract::Component, craft_ui::contract::Props)] #[component(canvas_control, content_painter)] pub struct BezierOverlay<'a> { @@ -447,6 +491,8 @@ pub struct BezierOverlay<'a> { report: Report, marquee: Option, hover_mark: Option, + /// The scene the latest step of this pass laid out. + laid: Option, } impl<'a> BezierOverlay<'a> { @@ -464,6 +510,7 @@ impl<'a> BezierOverlay<'a> { report: Report::default(), marquee: None, hover_mark: None, + laid: None, } .label(label) } @@ -483,6 +530,8 @@ impl<'a> BezierOverlay<'a> { if limited { return Scene { items, limited, selected: SelectedAnchors::default() }; } + #[cfg(all(test, feature = "screen-testing"))] + laid::add(); let selected = SelectedAnchors::of(self.selection); let near = rect.expand(reach); let shown = @@ -567,6 +616,17 @@ impl<'a> BezierOverlay<'a> { Scene { items, limited, selected } } + /// The scene of `paths`: the one an earlier step of this pass laid out from equal paths with the same view, rect, + /// reach and tool, else a new one, kept for the later steps. + fn scene_of(&mut self, paths: &[EditPath], view: &CanvasView, rect: Rect, reach: f32) -> Rc { + if let Some(laid) = self.laid.as_ref().filter(|laid| laid.matches(paths, view, rect, reach, self.tool)) { + return Rc::clone(&laid.scene); + } + let scene = Rc::new(self.scene(paths, view, rect, reach)); + self.laid = Some(Laid { scene: Rc::clone(&scene), paths: paths.to_vec(), view: *view, rect, reach, tool: self.tool }); + scene + } + /// Whether the press on `item` is the tool's. fn takes(&self, item: &Item) -> bool { self.tool.takes(&item.proxy(), item.interior, item.straight) @@ -1304,20 +1364,24 @@ impl Component for BezierOverlay<'_> { /// The anchors and shown handles in view, then the segments the tool takes, and under Direct Selection one part /// below them all for the marquee. The anchors and handles are one roving group in keyboard order: one Tab stop, - /// arriving at the first selected anchor. The Page keys, Home and End are the overlay's own moves. + /// arriving at the first selected anchor. The Page keys, Home and End are the overlay's own moves. Anchors declares + /// none. fn parts(&mut self, rect: egui::Rect, cx: &mut PartsCx<'_, Self>) { let held = cx.press_slot::(); self.press_tool(held.as_ref()); let Some(space) = canvas_space(&cx.env) else { return }; let reach = cx.style.reach; let scene = match &held { - Some(held) => self.scene(&held.start, &space.view, rect, reach), + Some(held) => self.scene_of(&held.start, &space.view, rect, reach), None => { let Some(paths) = cx.value() else { return }; - self.scene(paths, &space.view, rect, reach) + self.scene_of(paths, &space.view, rect, reach) } }; - let focusable = self.tool != BezierTool::Anchors; + // Anchors draws the anchors and handles without parts: nothing of them takes a press or the keyboard. + if self.tool == BezierTool::Anchors { + return; + } if self.tool == BezierTool::Direct && !scene.limited { cx.part(MARQUEE, HitShape::Rect(rect)) .sense(Sense::DRAG.union(Sense::CLICK).union(Sense::TAKE_FOCUS)) @@ -1333,7 +1397,7 @@ impl Component for BezierOverlay<'_> { let arrival = self.selection.path.zip(self.selection.anchors.first().copied()); for item in &scene.items { let press = self.takes(item); - let keyboard = item.kind != Kind::Segment && item.shown && focusable; + let keyboard = item.kind != Kind::Segment && item.shown; let selected = item.kind == Kind::Anchor && scene.selected.has_anchor(item.key, item.knot); let part = cx.part(item.part(), item.shape.clone()).priority(item.priority()); let part = if press { part.sense(PRESS) } else { part }; @@ -1349,7 +1413,7 @@ impl Component for BezierOverlay<'_> { part.selected(); } } - if focusable && scene.items.iter().any(|item| item.kind != Kind::Segment && item.shown) { + if scene.items.iter().any(|item| item.kind != Kind::Segment && item.shown) { cx.roving(Roving::new(NavShape::Flat).home_end(false)); } } @@ -1360,7 +1424,7 @@ impl Component for BezierOverlay<'_> { let held = cx.press_slot::().clone(); let Some(paths) = held.as_ref().map(|held| held.start.clone()).or_else(|| cx.value().cloned()) else { return }; self.press_tool(held.as_ref()); - let scene = self.scene(&paths, &space.view, cx.rect, cx.style.reach); + let scene = self.scene_of(&paths, &space.view, cx.rect, cx.style.reach); self.run_pointer(cx, &space, &scene, &paths); self.run_keys(cx, &space, &scene, &paths); } @@ -1368,7 +1432,7 @@ impl Component for BezierOverlay<'_> { fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) { let (Some(space), Some(paths)) = (canvas_space(&cx.env), cx.value()) else { return }; let (view, style) = (space.view, &cx.style); - let scene = self.scene(paths, &view, cx.rect, style.reach); + let scene = self.scene_of(paths, &view, cx.rect, style.reach); let options = self.path_options; let thickness = options.and_then(|options| options.thickness); let option_color = @@ -1484,10 +1548,21 @@ impl Component for BezierOverlay<'_> { } /// A graphics object per anchor and shown handle, named "Anchor 3 of 12", "In handle" and "Out handle" and valued - /// in the canvas's units. None above [`MAX_ANCHORS`]. + /// in the canvas's units. None above [`MAX_ANCHORS`] or under [`BezierTool::Anchors`]. fn access(&self, access: &mut Access, cx: &Cx<'_, Self>) { + if self.tool == BezierTool::Anchors { + return; + } let (Some(space), Some(paths)) = (canvas_space(&cx.env), cx.value()) else { return }; - let scene = self.scene(paths, &space.view, cx.rect, cx.style.reach); + let (rect, reach) = (cx.rect, cx.style.reach); + let built; + let scene = match self.laid.as_ref().filter(|laid| laid.matches(paths, &space.view, rect, reach, self.tool)) { + Some(laid) => &*laid.scene, + None => { + built = self.scene(paths, &space.view, rect, reach); + &built + } + }; let (words, units, rulers) = (cx.words::(), cx.env.units(), space.rulers()); for item in scene.items.iter().filter(|item| item.kind != Kind::Segment && item.shown) { let Some(knot) = paths[item.path].knot(item.knot) else { continue }; diff --git a/crates/draw/tests/it/bezier.rs b/crates/draw/tests/it/bezier.rs index 82a6612dc5..8bc0a5fe6f 100644 --- a/crates/draw/tests/it/bezier.rs +++ b/crates/draw/tests/it/bezier.rs @@ -2,7 +2,7 @@ use craft_behavior::geometry::{SnapKind, SnapOptions, SnapTarget, SnapTargets}; use craft_behavior::kurbo::{ParamCurve as _, Point, Size, Vec2}; -use craft_behavior::{CanvasView, EditEvent}; +use craft_behavior::{CanvasView, EditEvent, PartKey}; use craft_draw::ui::{ AnchorDelete, AnchorTool, AnchorsShown, BezierHit, BezierOverlay, BezierTool, EditPath, EditSubpath, HandleSide, HandlesShown, Knot, KnotRef, PathEdit, PathSelection, PathTool, SegmentMark, @@ -11,6 +11,7 @@ use craft_ui::canvas::{Canvas, Guide, Momentary, NavigationOptions, Snap, ToolHo use craft_ui::canvas_controls::Guides; use craft_ui::contract::{Bind, Props as _, Show as _, ShowContainer as _}; use craft_ui::primitives::cancel_press_of; +use craft_ui::runtime::access::Role; use craft_ui::testing::{Fixture, pointer, trial}; use egui::{Id, Pos2, Vec2 as ScreenVec, vec2}; use std::cell::RefCell; @@ -530,6 +531,55 @@ fn a_frame_reads_the_selections_anchor_lists_in_proportion_to_the_selection() { assert!(large < small * 3, "{small} entries read for 60 selected paths, {large} for 120"); } +// A pass lays out the anchors, handles and segments once for all of its steps (parts, update, paint, access): a frame +// at rest lays out one scene per pass. +#[trial] +fn a_pass_lays_out_the_overlays_scene_once() { + for tool in [BezierTool::Direct, BezierTool::Anchors] { + let mut h = two_paths(); + h.update(|st| (st.tool, st.selection) = (tool, sel(1, &[(0, 1)]))); + craft_draw::ui::pen::bezier::laid::take(); + h.fixture.frame(Vec::new()); + let (laid, passes) = (craft_draw::ui::pen::bezier::laid::take(), h.fixture.passes()); + assert!(passes > 0, "{tool:?}: the frame ran"); + assert_eq!(laid, passes, "{tool:?}: {laid} scenes laid out in {passes} passes"); + } +} + +// A step that sees other paths than the one before it lays out its own scene: the pass of an arrow nudge paints the +// moved anchor where the next frame, at rest, paints it. +#[trial] +fn the_pass_of_an_edit_paints_the_edited_anchors() { + let mut h = two_paths(); + h.update(|st| st.selection = sel(1, &[(0, 1)])); + h.fixture.key(egui::Key::Tab, egui::Modifiers::NONE).key(egui::Key::Tab, egui::Modifiers::NONE).settle(); + let arrow = egui::Event::Key { key: egui::Key::ArrowRight, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + let nudged = format!("{:?}", h.fixture.frame_shapes_with(vec![arrow])); + assert!(matches!(h.last_change(), Some(PathEdit::MoveAnchors { path: 1, .. })), "{:?}", h.last_change()); + let rest = format!("{:?}", h.fixture.frame_shapes()); + assert_eq!(nudged, rest, "the nudge's pass paints the anchors of the nudged paths"); +} + +// Under Anchors the overlay draws the anchors without declaring them: no part of an anchor and no AccessKit object, +// where Direct Selection declares both. The anchors still draw. +#[trial] +fn anchors_draws_its_anchors_with_no_part_and_no_accesskit_object() { + for (tool, declared) in [(BezierTool::Direct, true), (BezierTool::Anchors, false)] { + let mut h = two_paths(); + h.update(|st| (st.tool, st.selection) = (tool, sel(1, &[(0, 1)]))); + let id = h.state.borrow().id; + assert_eq!(h.fixture.part_rect(id, PartKey::new("anchor").at(0)).is_some(), declared, "{tool:?}: the first anchor's part"); + let objects = h.fixture.by_role(Role::GRAPHICS_OBJECT).len(); + assert_eq!(objects > 0, declared, "{tool:?}: {objects} AccessKit objects"); + } + let shapes = |anchors: AnchorsShown| { + let mut h = two_paths(); + h.update(|st| (st.tool, st.anchors, st.selection) = (BezierTool::Anchors, anchors, sel(1, &[(0, 1)]))); + h.fixture.frame_shapes().len() + }; + assert!(shapes(AnchorsShown::All) > shapes(AnchorsShown::Hidden), "Anchors draws the anchors that outlines only leave out"); +} + // Hovering a segment under Add reports the segment with its parameter, which the preview anchor stands at. // `AnchorsShown::Hidden` draws outlines only: no anchor, no handle, no part, no AccessKit object. diff --git a/crates/dxf/src/paths.rs b/crates/dxf/src/paths.rs index 7e4f18f0f7..282ad7b4fd 100644 --- a/crates/dxf/src/paths.rs +++ b/crates/dxf/src/paths.rs @@ -1,7 +1,8 @@ //! Bounded conversion of common planar DXF entities into neutral Bézier paths. //! -//! This is geometry extraction, not a full CAD scene renderer: unsupported entities such as -//! text, dimensions, meshes, and block inserts are reported as warnings and omitted. +//! This is geometry extraction, not a full CAD scene renderer: block inserts are expanded +//! (scaled, rotated, arrayed and nested up to [`MAX_INSERT_DEPTH`] levels), while unsupported +//! entities such as text, dimensions and meshes are reported as warnings and omitted. use kurbo::{BezPath, Point, Rect, Shape as _}; @@ -39,51 +40,16 @@ pub fn import(bytes: &[u8]) -> Result { let unit_to_mm = units_to_mm(drawing.header.insunits(), drawing.header.measurement()); let layer_visibility: std::collections::HashMap<_, _> = drawing.layers().into_iter().map(|layer| (layer.name, layer.on && !layer.frozen)).collect(); - let mut paths = Vec::new(); + let blocks: std::collections::HashMap<&str, &crate::model::Block<'_>> = drawing.blocks.iter().map(|b| (b.name, b)).collect(); + let mut state = State { paths: Vec::new(), unsupported: 0, elements: 0, layers: &layer_visibility, blocks: &blocks }; let mut warnings = Vec::new(); - let mut unsupported = 0usize; - let mut elements = 0usize; for record in &drawing.entities { - let entity = crate::model::Entity::read(record); - if !entity.common.visible || record.paper_space() || layer_visibility.get(&entity.common.layer) == Some(&false) { + if record.paper_space() { continue; } - if excessive_sweep(&entity.kind) { - return Err(Error::TooManySegments); - } - let remaining = MAX_PATH_ELEMENTS.saturating_sub(elements); - if estimated_elements(&entity.kind) > remaining { - return Err(Error::TooManySegments); - } - let converted = if let crate::model::EntityKind::Spline(spline) = &entity.kind { - spline_path(spline)?.into_iter().collect() - } else { - entity_paths(&entity.kind, entity.common.extrusion) - }; - if converted.iter().flat_map(|path| path.elements()).any(|element| { - let finite = |p: Point| p.x.is_finite() && p.y.is_finite(); - match *element { - kurbo::PathEl::MoveTo(p) | kurbo::PathEl::LineTo(p) => !finite(p), - kurbo::PathEl::QuadTo(a, b) => !finite(a) || !finite(b), - kurbo::PathEl::CurveTo(a, b, c) => !finite(a) || !finite(b) || !finite(c), - kurbo::PathEl::ClosePath => false, - } - }) { - return Err(Error::NonFinite); - } - if converted.is_empty() { - unsupported = unsupported.saturating_add(1); - continue; - } - elements = elements.saturating_add(converted.iter().map(|path| path.elements().len()).sum::()); - if elements > MAX_PATH_ELEMENTS { - return Err(Error::TooManySegments); - } - if paths.len().saturating_add(converted.len()) > MAX_PATHS { - return Err(Error::TooManyPaths); - } - paths.extend(converted); + convert(&mut state, record, kurbo::Affine::IDENTITY, 0)?; } + let State { paths, unsupported, .. } = state; if unsupported > 0 { warnings.push(format!("{unsupported} visible DXF entities are unsupported and were omitted")); } @@ -94,6 +60,100 @@ pub fn import(bytes: &[u8]) -> Result { Ok(Imported { paths, bounds, unit_to_mm, warnings }) } +/// The deepest chain of block inserts expanded (deeper ones are omitted with a warning). +pub const MAX_INSERT_DEPTH: usize = 16; +/// The most copies one arrayed insert makes. +const MAX_INSERT_COPIES: i64 = 10_000; + +struct State<'s, 'a> { + paths: Vec, + unsupported: usize, + elements: usize, + layers: &'s std::collections::HashMap, + blocks: &'s std::collections::HashMap<&'a str, &'s crate::model::Block<'a>>, +} + +/// Convert one entity record through `transform`, expanding block inserts. +fn convert(state: &mut State<'_, '_>, record: &crate::model::EntityRecord<'_>, transform: kurbo::Affine, depth: usize) -> Result<(), Error> { + let entity = crate::model::Entity::read(record); + if !entity.common.visible || state.layers.get(&entity.common.layer) == Some(&false) { + return Ok(()); + } + if let crate::model::EntityKind::Insert(insert) = &entity.kind { + let Some(block) = state.blocks.get(insert.block.trim()).copied() else { + state.unsupported = state.unsupported.saturating_add(1); + return Ok(()); + }; + if depth >= MAX_INSERT_DEPTH { + state.unsupported = state.unsupported.saturating_add(1); + return Ok(()); + } + let [bx, by, _] = block.groups().point(10); + let [ix, iy, _] = insert.insert; + let [sx, sy, _] = insert.scale; + let (columns, rows) = (insert.columns.max(1), insert.rows.max(1)); + if columns.saturating_mul(rows) > MAX_INSERT_COPIES { + return Err(Error::TooManyPaths); + } + let all_finite = [bx, by, ix, iy, sx, sy, insert.rotation, insert.column_spacing, insert.row_spacing].iter().all(|v| v.is_finite()); + if !all_finite { + return Err(Error::NonFinite); + } + for row in 0..rows { + for column in 0..columns { + // Array offsets are along the insert's rotated axes, before scaling. + let offset = kurbo::Vec2::new(column as f64 * insert.column_spacing, row as f64 * insert.row_spacing); + let local = kurbo::Affine::translate((ix, iy)) + * kurbo::Affine::rotate(insert.rotation.to_radians()) + * kurbo::Affine::translate(offset) + * kurbo::Affine::scale_non_uniform(sx, sy) + * kurbo::Affine::translate((-bx, -by)); + for child in &block.entities { + convert(state, child, transform * local, depth + 1)?; + } + } + } + return Ok(()); + } + if excessive_sweep(&entity.kind) { + return Err(Error::TooManySegments); + } + let remaining = MAX_PATH_ELEMENTS.saturating_sub(state.elements); + if estimated_elements(&entity.kind) > remaining { + return Err(Error::TooManySegments); + } + let converted: Vec = if let crate::model::EntityKind::Spline(spline) = &entity.kind { + spline_path(spline)?.into_iter().collect() + } else { + entity_paths(&entity.kind, entity.common.extrusion) + }; + let converted: Vec = converted.into_iter().map(|path| transform * path).collect(); + if converted.iter().flat_map(|path| path.elements()).any(|element| { + let finite = |p: Point| p.x.is_finite() && p.y.is_finite(); + match *element { + kurbo::PathEl::MoveTo(p) | kurbo::PathEl::LineTo(p) => !finite(p), + kurbo::PathEl::QuadTo(a, b) => !finite(a) || !finite(b), + kurbo::PathEl::CurveTo(a, b, c) => !finite(a) || !finite(b) || !finite(c), + kurbo::PathEl::ClosePath => false, + } + }) { + return Err(Error::NonFinite); + } + if converted.is_empty() { + state.unsupported = state.unsupported.saturating_add(1); + return Ok(()); + } + state.elements = state.elements.saturating_add(converted.iter().map(|path| path.elements().len()).sum::()); + if state.elements > MAX_PATH_ELEMENTS { + return Err(Error::TooManySegments); + } + if state.paths.len().saturating_add(converted.len()) > MAX_PATHS { + return Err(Error::TooManyPaths); + } + state.paths.extend(converted); + Ok(()) +} + fn estimated_elements(kind: &crate::model::EntityKind) -> usize { use crate::model::EntityKind as E; let arc_count = |sweep: f64| (sweep.abs() / std::f64::consts::FRAC_PI_2).ceil().max(1.0) as usize; @@ -857,3 +917,124 @@ mod spline_tests { } } } + +#[cfg(test)] +mod insert_tests { + use super::*; + + /// A DXF with the given BLOCKS and ENTITIES section bodies (group-code / value pairs). + fn dxf(blocks: &[(&str, &str)], entities: &[(&str, &str)]) -> Vec { + let mut out = String::from("0\nSECTION\n2\nBLOCKS\n"); + for (code, value) in blocks { + out.push_str(&format!("{code}\n{value}\n")); + } + out.push_str("0\nENDSEC\n0\nSECTION\n2\nENTITIES\n"); + for (code, value) in entities { + out.push_str(&format!("{code}\n{value}\n")); + } + out.push_str("0\nENDSEC\n0\nEOF\n"); + out.into_bytes() + } + + /// Block `name` with base point (`bx`, `by`) holding one line from (bx, by) to (bx + 10, by). + fn block(name: &'static str, bx: &'static str, by: &'static str, x1: &'static str) -> Vec<(&'static str, &'static str)> { + vec![ + ("0", "BLOCK"), + ("8", "0"), + ("2", name), + ("70", "0"), + ("10", bx), + ("20", by), + ("30", "0"), + ("0", "LINE"), + ("8", "0"), + ("10", bx), + ("20", by), + ("30", "0"), + ("11", x1), + ("21", by), + ("31", "0"), + ("0", "ENDBLK"), + ] + } + + fn ends(imported: &Imported) -> Vec<(f64, f64, f64, f64)> { + imported + .paths + .iter() + .map(|p| { + let b = p.bounding_box(); + let r = |v: f64| (v * 1000.0).round() / 1000.0; + (r(b.x0), r(b.y0), r(b.x1), r(b.y1)) + }) + .collect() + } + + #[test] + fn inserts_place_their_blocks_scaled_rotated_and_arrayed() { + let b = block("SEG", "5", "5", "15"); + // Insert at (100, 0), scale 2 in x, rotated 90°: the 10-long line from the base point + // becomes 20 long, pointing up from (100, 0). + let one = + dxf(&b, &[("0", "INSERT"), ("8", "0"), ("2", "SEG"), ("10", "100"), ("20", "0"), ("30", "0"), ("41", "2"), ("42", "1"), ("50", "90")]); + let got = import(&one).unwrap(); + assert_eq!(ends(&got), vec![(100.0, 0.0, 100.0, 20.0)]); + assert!(got.warnings.is_empty(), "{:?}", got.warnings); + // A 3 × 2 array, 30 apart in columns and 7 in rows. + let array = dxf( + &b, + &[("0", "INSERT"), ("8", "0"), ("2", "SEG"), ("10", "0"), ("20", "0"), ("30", "0"), ("70", "3"), ("71", "2"), ("44", "30"), ("45", "7")], + ); + let got = import(&array).unwrap(); + assert_eq!(got.paths.len(), 6); + assert!(ends(&got).contains(&(60.0, 7.0, 70.0, 7.0)), "{:?}", ends(&got)); + } + + #[test] + fn nested_blocks_expand_and_self_reference_stops() { + let mut blocks = block("INNER", "0", "0", "10"); + blocks.extend([ + ("0", "BLOCK"), + ("8", "0"), + ("2", "OUTER"), + ("70", "0"), + ("10", "0"), + ("20", "0"), + ("30", "0"), + ("0", "INSERT"), + ("8", "0"), + ("2", "INNER"), + ("10", "50"), + ("20", "50"), + ("30", "0"), + ("0", "ENDBLK"), + ("0", "BLOCK"), + ("8", "0"), + ("2", "LOOP"), + ("70", "0"), + ("10", "0"), + ("20", "0"), + ("30", "0"), + ("0", "INSERT"), + ("8", "0"), + ("2", "LOOP"), + ("10", "1"), + ("20", "0"), + ("30", "0"), + ("0", "ENDBLK"), + ]); + let got = import(&dxf(&blocks, &[("0", "INSERT"), ("8", "0"), ("2", "OUTER"), ("10", "10"), ("20", "0"), ("30", "0")])).unwrap(); + assert_eq!(ends(&got), vec![(60.0, 50.0, 70.0, 50.0)]); + let looped = import(&dxf(&blocks, &[("0", "INSERT"), ("8", "0"), ("2", "LOOP"), ("10", "0"), ("20", "0"), ("30", "0")])).unwrap(); + assert!(looped.paths.is_empty()); + assert!(!looped.warnings.is_empty(), "the cut-off chain is reported"); + // A missing block and an absurd array are reported, not crashes. + let missing = import(&dxf(&[], &[("0", "INSERT"), ("8", "0"), ("2", "NOPE"), ("10", "0"), ("20", "0"), ("30", "0")])).unwrap(); + assert!(!missing.warnings.is_empty()); + let huge = dxf( + &block("SEG", "0", "0", "1"), + &[("0", "INSERT"), ("8", "0"), ("2", "SEG"), ("10", "0"), ("20", "0"), ("30", "0"), ("70", "100000"), ("71", "100000")], + ); + assert!(import(&huge).is_err()); + } +} diff --git a/crates/figcraft-format/src/lib.rs b/crates/figcraft-format/src/lib.rs index 7475c5e216..a06dc1b869 100644 --- a/crates/figcraft-format/src/lib.rs +++ b/crates/figcraft-format/src/lib.rs @@ -150,6 +150,9 @@ impl<'de> Deserialize<'de> for BranchIndex { pub struct Header { pub version: Option, pub images: Option>, + /// Stored dimensions, retained even when a consumer cannot decode an image's codec. + /// These are untrusted metadata, not permission to allocate a pixel buffer. + pub image_dimensions: std::collections::BTreeMap, } pub fn read_header(text: &str) -> Result { @@ -170,10 +173,20 @@ impl<'de> Deserialize<'de> for Header { match k.as_str() { "version" => h.version = m.next_value::()?.as_u64(), "imageIndex" => { - h.images = m - .next_value::()? + let value = m.next_value::()?; + h.images = + value.as_array().map(|a| a.iter().filter_map(|v| v.get("hash").and_then(Value::as_str).map(str::to_owned)).collect()); + h.image_dimensions = value .as_array() - .map(|a| a.iter().filter_map(|v| v.get("hash").and_then(Value::as_str).map(str::to_owned)).collect()) + .into_iter() + .flatten() + .filter_map(|v| { + let hash = v.get("hash")?.as_str()?.to_owned(); + let width = u32::try_from(v.get("width")?.as_u64()?).ok()?; + let height = u32::try_from(v.get("height")?.as_u64()?).ok()?; + Some((hash, (width, height))) + }) + .collect(); } _ => { m.next_value::()?; @@ -324,6 +337,17 @@ pub fn write_document_json(doc: &D, images: &[I #[cfg(test)] mod tests { + #[test] + fn image_dimensions_survive_the_native_envelope() { + let images = [super::ImageIndexEntry { hash: "original-image".into(), width: 731, height: 419 }]; + let mut json = Vec::new(); + super::write_document_json(&serde_json::json!({"name":"original fixture"}), &images, &mut json).unwrap(); + let header = super::read_header(std::str::from_utf8(&json).unwrap()).unwrap(); + assert_eq!(header.image_dimensions.get(&images[0].hash), Some(&(images[0].width, images[0].height))); + let legacy = super::read_header(r#"{"imageIndex":[{"hash":"legacy"},{"hash":"overflow","width":4294967296,"height":1}]}"#).unwrap(); + assert_eq!(legacy.images.unwrap().len(), 2); + assert!(legacy.image_dimensions.is_empty()); + } use super::*; #[test] @@ -437,8 +461,8 @@ mod tests { } #[test] fn newer_version_is_reported_before_document_decode() { - assert_eq!(check_version(&Header { version: Some(2), images: None }), Err(NewerVersion(2))); - assert_eq!(check_version(&Header { version: Some(u64::MAX), images: None }), Err(NewerVersion(u32::MAX))); + assert_eq!(check_version(&Header { version: Some(2), ..Header::default() }), Err(NewerVersion(2))); + assert_eq!(check_version(&Header { version: Some(u64::MAX), ..Header::default() }), Err(NewerVersion(u32::MAX))); #[derive(Deserialize)] struct Payload { diff --git a/crates/file-formats/Cargo.toml b/crates/file-formats/Cargo.toml index afe7c6391d..293bcfaeea 100644 --- a/crates/file-formats/Cargo.toml +++ b/crates/file-formats/Cargo.toml @@ -27,6 +27,7 @@ default = [] raster-codecs = ["dep:craft-image-codecs"] heif = ["raster-codecs", "craft-image-codecs/heif"] avif = ["raster-codecs", "craft-image-codecs/avif"] +jp2 = ["raster-codecs", "craft-image-codecs/jp2"] pdf = [] svg = [] ora = ["dep:craft-ora"] diff --git a/crates/file-import/Cargo.toml b/crates/file-import/Cargo.toml index ab4eb9c6f6..7de324895e 100644 --- a/crates/file-import/Cargo.toml +++ b/crates/file-import/Cargo.toml @@ -12,7 +12,7 @@ craft-file-formats = { workspace = true } craft-raster-codecs = { workspace = true } craft-svg = { workspace = true } craft-dxf = { workspace = true } -craft-pdf = { workspace = true, features = ["paths", "write"] } +craft-pdf = { workspace = true, features = ["paths", "write", "raster"] } craft-eps = { workspace = true, features = ["paths"] } kurbo = { workspace = true } thiserror = { workspace = true } diff --git a/crates/file-import/src/lib.rs b/crates/file-import/src/lib.rs index ebf5dc3d09..e42060210d 100644 --- a/crates/file-import/src/lib.rs +++ b/crates/file-import/src/lib.rs @@ -311,6 +311,40 @@ fn import_dxf(bytes: &[u8], format: ImportFormat, limits: Limits) -> Result Result { + if bytes.len() > limits.max_input_bytes { + return Err(Error::InputLimit { size: bytes.len(), limit: limits.max_input_bytes }); + } + if !(dpi.is_finite() && (1.0..=1200.0).contains(&dpi)) { + return Err(Error::Decode(format!("dpi {dpi} is outside 1–1200"))); + } + let doc = craft_pdf::open_slice(bytes, None).map_err(|error| Error::Decode(error.to_string()))?; + let pages = doc.pages(); + let page = pages.get(page).ok_or_else(|| Error::Decode(format!("the PDF has no page {}", page + 1)))?; + // In 1/72..=1200/72, so the cast keeps its value. + let scale = (dpi / 72.0) as f32; + let options = craft_pdf::raster::Options { scale: [scale, scale], background: [255; 4], ..Default::default() }; + let [width, height] = craft_pdf::raster::dimensions(page, &options).map_err(|error| Error::Decode(error.to_string()))?; + let pixels = u64::from(width) * u64::from(height); + if width == 0 + || height == 0 + || width > limits.max_raster_width + || height > limits.max_raster_height + || pixels > limits.max_raster_pixels + || pixels.saturating_mul(4) > limits.max_raster_alloc_bytes + { + return Err(Error::Decode(format!("a {width} × {height} pixel page is outside the raster limits"))); + } + let raster = + craft_pdf::raster::render(page, &craft_pdf::raster::RenderCache::new(), &craft_pdf::interpret::InterpreterSettings::default(), &options) + .map_err(|error| Error::Decode(error.to_string()))?; + // Opaque over the white background, so premultiplied and straight alpha agree. + Ok(RasterImage { format: ImportFormat::Pdf, width: raster.width, height: raster.height, rgba: raster.bytes().to_vec() }) +} + fn import_pdf(bytes: &[u8], format: ImportFormat, limits: Limits) -> Result { let imported = craft_pdf::paths::import_page( bytes, @@ -396,6 +430,41 @@ fn path_is_finite(path: &BezPath) -> bool { #[cfg(test)] mod format_tests { + + #[test] + fn a_pdf_page_renders_as_a_picture_of_everything_on_it() { + // A 50 × 50 mm page with a filled red square from 10 to 30 mm. + let mut square = kurbo::BezPath::new(); + square.move_to((10.0, 10.0)); + square.line_to((30.0, 10.0)); + square.line_to((30.0, 30.0)); + square.line_to((10.0, 30.0)); + square.close_path(); + let pdf = crate::write::write_pdf_pages(&[crate::write::PdfPage { + width_mm: 50.0, + height_mm: 50.0, + view_box: [0.0, 0.0, 50.0, 50.0], + paths: vec![crate::write::PdfPath { path: square, color_rgb: [255, 0, 0], stroke_width_mm: None }], + images: vec![], + }]) + .unwrap(); + let image = render_pdf_page(&pdf, 0, 72.0, Limits::default()).unwrap(); + // 50 mm at 72 dpi is about 142 px. + assert!((140..=143).contains(&image.width), "{}", image.width); + assert_eq!(image.rgba.len(), (image.width * image.height * 4) as usize); + let at = |x_mm: f64, y_mm: f64| { + let (x, y) = ((x_mm / 25.4 * 72.0) as u32, (y_mm / 25.4 * 72.0) as u32); + let i = ((y * image.width + x) * 4) as usize; + [image.rgba[i], image.rgba[i + 1], image.rgba[i + 2]] + }; + assert_eq!(at(20.0, 20.0), [255, 0, 0], "the square"); + assert_eq!(at(40.0, 40.0), [255, 255, 255], "the white page"); + assert!(render_pdf_page(&pdf, 3, 72.0, Limits::default()).is_err(), "no such page"); + assert!(render_pdf_page(&pdf, 0, f64::NAN, Limits::default()).is_err()); + let tight = Limits { max_raster_pixels: 100, ..Limits::default() }; + assert!(render_pdf_page(&pdf, 0, 72.0, tight).is_err(), "over the raster limit"); + } + use super::*; #[test] diff --git a/crates/file-import/src/write.rs b/crates/file-import/src/write.rs index 6762062826..20b60be995 100644 --- a/crates/file-import/src/write.rs +++ b/crates/file-import/src/write.rs @@ -36,6 +36,42 @@ pub struct OutputPath { pub data_kind: Option, /// Close each open contour for formats that require closed cutting operations. pub close_open_contours: bool, + /// The colour the path is filled with in SVG and PDF output (even-odd, as drawn); `None` + /// leaves it unfilled. Cutter and DXF writers ignore it. + pub fill_rgb: Option<[u8; 3]>, +} + +/// A placed raster picture: straight RGBA pixels, row by row from the top, and the box it +/// fills in view-box coordinates (millimetres for the PDF writer). +#[derive(Debug, Clone, PartialEq)] +pub struct OutputImage { + pub x: f64, + pub y: f64, + pub width: f64, + pub height: f64, + pub width_px: u32, + pub height_px: u32, + pub rgba: Vec, +} + +/// The largest side of an [`OutputImage`], in pixels. +pub const MAX_IMAGE_SIDE_PX: u32 = 16_384; + +/// The most images one scene or page holds. +pub const MAX_IMAGES: usize = 1_000; + +impl OutputImage { + /// Whether the box is finite and positive and `rgba` holds exactly `width_px × height_px` + /// pixels within [`MAX_IMAGE_SIDE_PX`]. + pub fn is_valid(&self) -> bool { + let pixels = u64::from(self.width_px) * u64::from(self.height_px); + [self.x, self.y, self.width, self.height].iter().all(|v| v.is_finite()) + && self.width > 0.0 + && self.height > 0.0 + && (1..=MAX_IMAGE_SIDE_PX).contains(&self.width_px) + && (1..=MAX_IMAGE_SIDE_PX).contains(&self.height_px) + && u64::try_from(self.rgba.len()).is_ok_and(|len| Some(len) == pixels.checked_mul(4)) + } } #[derive(Debug, Clone, PartialEq)] @@ -45,6 +81,9 @@ pub struct OutputScene { pub view_box: [f64; 4], pub layers: Vec, pub paths: Vec, + /// Placed pictures, drawn under the paths in order. The PDF writer embeds them; the SVG, + /// DXF and cutter writers leave them out. + pub images: Vec, } /// One page for the shared PDF path writer. Coordinates and stroke widths are millimetres. @@ -54,6 +93,8 @@ pub struct PdfPage { pub height_mm: f64, pub view_box: [f64; 4], pub paths: Vec, + /// Placed pictures in view-box coordinates, drawn under the paths in order. + pub images: Vec, } /// A PDF path with either a fill or a stroke. `None` fills the path; `Some(width)` strokes it. @@ -133,11 +174,15 @@ fn write_svg(scene: &OutputScene) -> Result { .iter() .map(|path| { let color = path.color_rgb; + let fill = path.fill_rgb.map_or_else(|| "none".to_string(), |[r, g, b]| format!("#{r:02x}{g:02x}{b:02x}")); let mut attributes = vec![ - craft_svg::write::Attribute::text("fill", "none"), + craft_svg::write::Attribute::text("fill", fill), craft_svg::write::Attribute::text("stroke", format!("#{:02x}{:02x}{:02x}", color[0], color[1], color[2])), craft_svg::write::Attribute::text("stroke-width", format_float(path.stroke_width_mm / view_scale)), ]; + if path.fill_rgb.is_some() { + attributes.push(craft_svg::write::Attribute::text("fill-rule", "evenodd")); + } if let Some(class) = &path.class { attributes.push(craft_svg::write::Attribute::text("class", class.clone())); } @@ -173,9 +218,20 @@ fn write_pdf(scene: &OutputScene) -> Result, Error> { .enumerate() .filter(|(_, layer)| layer.visible) .flat_map(|(layer_index, _)| paths_by_layer[layer_index].iter().copied()) - .map(|path| PdfPath { path: path.path.clone(), color_rgb: path.color_rgb, stroke_width_mm: Some(path.stroke_width_mm) }) + // A filled path paints its fill, then its line over it. + .flat_map(|path| { + let fill = path.fill_rgb.map(|rgb| PdfPath { path: path.path.clone(), color_rgb: rgb, stroke_width_mm: None }); + fill.into_iter().chain(std::iter::once(PdfPath { + path: path.path.clone(), + color_rgb: path.color_rgb, + stroke_width_mm: Some(path.stroke_width_mm), + })) + }) .collect(); - write_pdf_pages(&[PdfPage { width_mm: scene.width_mm, height_mm: scene.height_mm, view_box: scene.view_box, paths }]) + write_pdf_pages_with_rule( + &[PdfPage { width_mm: scene.width_mm, height_mm: scene.height_mm, view_box: scene.view_box, paths, images: scene.images.clone() }], + craft_pdf::write::backend::paint::FillRule::EvenOdd, + ) } /// Group the neutral paths once so writing does not rescan all paths for every layer. @@ -191,6 +247,11 @@ fn paths_by_layer(scene: &OutputScene) -> Vec> { /// Encode a neutral list of laid-out pages with vector paths as PDF. pub fn write_pdf_pages(pages: &[PdfPage]) -> Result, Error> { + write_pdf_pages_with_rule(pages, craft_pdf::write::backend::paint::FillRule::NonZero) +} + +// Scene fills are explicitly even-odd. Keep the existing standalone PDF page API's nonzero rule. +fn write_pdf_pages_with_rule(pages: &[PdfPage], fill_rule: craft_pdf::write::backend::paint::FillRule) -> Result, Error> { use craft_pdf::write::{Metadata, Writer, backend}; const PT_PER_MM: f64 = 72.0 / 25.4; craft_pdf::write::guard(|| { @@ -235,6 +296,26 @@ pub fn write_pdf_pages(pages: &[PdfPage]) -> Result, Error> { if !(view_scale.is_finite() && view_scale > 0.0 && offset_x.is_finite() && offset_y.is_finite()) { return Err(Error::InvalidGeometry); } + if source_page.images.len() > MAX_IMAGES { + return Err(Error::Write(format!("more than {MAX_IMAGES} images on a page"))); + } + for image in &source_page.images { + if !image.is_valid() { + return Err(Error::Write("an image's box or pixels are not usable".into())); + } + let x = ((image.x - view_x) * view_scale + offset_x) * PT_PER_MM; + let y = ((image.y - view_y) * view_scale + offset_y) * PT_PER_MM; + let w = image.width * view_scale * PT_PER_MM; + let h = image.height * view_scale * PT_PER_MM; + if ![x, y, w, h].iter().all(|v| v.is_finite() && v.abs() <= f64::from(f32::MAX)) { + return Err(Error::Write("an image is outside the PDF range".into())); + } + let size = backend::geom::Size::from_wh(w as f32, h as f32).ok_or_else(|| Error::Write("an image has no size".into()))?; + let picture = backend::image::Image::from_rgba8(image.rgba.clone(), image.width_px, image.height_px); + surface.push_transform(&backend::geom::Transform::from_translate(x as f32, y as f32)); + surface.draw_image(picture, size); + surface.pop(); + } for source in &source_page.paths { let mut path = backend::geom::PathBuilder::new(); for element in source.path.elements() { @@ -288,7 +369,7 @@ pub fn write_pdf_pages(pages: &[PdfPage]) -> Result, Error> { } None => { surface.set_stroke(None); - surface.set_fill(Some(backend::paint::Fill { paint: color.into(), ..Default::default() })); + surface.set_fill(Some(backend::paint::Fill { paint: color.into(), rule: fill_rule, ..Default::default() })); } } surface.draw_path(&path); @@ -420,6 +501,9 @@ fn validate_scene(scene: &OutputScene) -> Result<(), Error> { if !(scene.width_mm.is_finite() && scene.height_mm.is_finite() && scene.width_mm > 0.0 && scene.height_mm > 0.0) { return Err(Error::InvalidGeometry); } + if scene.images.len() > MAX_IMAGES || scene.images.iter().any(|image| !image.is_valid()) { + return Err(Error::InvalidGeometry); + } if !(scene.view_box.iter().all(|value| value.is_finite()) && scene.view_box[2] > 0.0 && scene.view_box[3] > 0.0) || scene.paths.len() > crate::MAX_SHAPES || scene.paths.iter().any(|path| { @@ -445,3 +529,123 @@ fn point_is_finite(point: Point) -> bool { fn format_float(value: f64) -> String { value.to_string() } + +#[cfg(test)] +mod fill_tests { + use super::*; + + fn scene(fill_rgb: Option<[u8; 3]>) -> OutputScene { + let mut square = BezPath::new(); + square.move_to((10.0, 10.0)); + square.line_to((30.0, 10.0)); + square.line_to((30.0, 30.0)); + square.line_to((10.0, 30.0)); + square.close_path(); + OutputScene { + width_mm: 50.0, + height_mm: 50.0, + view_box: [0.0, 0.0, 50.0, 50.0], + layers: vec![OutputLayer { name: "cut".into(), dxf_name: "CUT".into(), visible: true, dxf_color_index: 1, class: None, data_kind: None }], + paths: vec![OutputPath { + path: square, + layer: 0, + color_rgb: [255, 0, 0], + stroke_width_mm: 0.25, + class: None, + data_kind: None, + close_open_contours: false, + fill_rgb, + }], + images: Vec::new(), + } + } + + #[test] + fn a_filled_path_is_filled_in_svg_and_pdf() { + let svg = write_svg(&scene(Some([0x12, 0x34, 0x56]))).unwrap(); + assert!(svg.contains("fill=\"#123456\""), "{svg}"); + assert!(write_svg(&scene(None)).unwrap().contains("fill=\"none\"")); + let filled = write_pdf(&scene(Some([0x12, 0x34, 0x56]))).unwrap(); + let plain = write_pdf(&scene(None)).unwrap(); + assert!(filled.len() > plain.len(), "a fill is drawn as well as the line"); + } + + #[test] + fn same_direction_nested_contours_preserve_the_hole() { + let mut scene = scene(Some([255, 0, 0])); + let path = &mut scene.paths[0].path; + path.move_to((15.0, 15.0)); + path.line_to((25.0, 15.0)); + path.line_to((25.0, 25.0)); + path.line_to((15.0, 25.0)); + path.close_path(); + assert!(write_svg(&scene).unwrap().contains("fill-rule=\"evenodd\"")); + let sample = |pdf: &[u8], x_mm: f64, y_mm: f64| { + let image = crate::render_pdf_page(pdf, 0, 72.0, crate::Limits::default()).unwrap(); + let (x, y) = ((x_mm / 25.4 * 72.0) as u32, (y_mm / 25.4 * 72.0) as u32); + let i = ((y * image.width + x) * 4) as usize; + [image.rgba[i], image.rgba[i + 1], image.rgba[i + 2]] + }; + let pdf = write_pdf(&scene).unwrap(); + assert_eq!(sample(&pdf, 12.0, 12.0), [255, 0, 0]); + assert_eq!(sample(&pdf, 20.0, 20.0), [255, 255, 255]); + let standalone = write_pdf_pages(&[PdfPage { + width_mm: scene.width_mm, + height_mm: scene.height_mm, + view_box: scene.view_box, + paths: vec![PdfPath { path: scene.paths[0].path.clone(), color_rgb: [255, 0, 0], stroke_width_mm: None }], + images: Vec::new(), + }]) + .unwrap(); + assert_eq!(sample(&standalone, 20.0, 20.0), [255, 0, 0], "standalone PDF API retains nonzero fill"); + } +} + +#[cfg(test)] +mod image_tests { + use super::*; + + fn page(images: Vec) -> PdfPage { + let mut square = BezPath::new(); + square.move_to((10.0, 10.0)); + square.line_to((20.0, 10.0)); + square.line_to((20.0, 20.0)); + square.close_path(); + PdfPage { + width_mm: 100.0, + height_mm: 100.0, + view_box: [0.0, 0.0, 100.0, 100.0], + paths: vec![PdfPath { path: square, color_rgb: [255, 0, 0], stroke_width_mm: Some(0.25) }], + images, + } + } + + fn picture(width_px: u32, height_px: u32) -> OutputImage { + OutputImage { x: 30.0, y: 30.0, width: 40.0, height: 20.0, width_px, height_px, rgba: vec![200; (width_px * height_px * 4) as usize] } + } + + #[test] + fn a_placed_picture_is_embedded_under_the_paths() { + let plain = write_pdf_pages(&[page(Vec::new())]).unwrap(); + let with = write_pdf_pages(&[page(vec![picture(4, 2)])]).unwrap(); + let text = String::from_utf8_lossy(&with); + assert!(text.contains("/Subtype/Image"), "an image XObject"); + assert!(!String::from_utf8_lossy(&plain).contains("/Subtype/Image")); + } + + #[test] + fn unusable_pictures_are_errors_not_crashes() { + let mut short = picture(4, 2); + short.rgba.pop(); + for bad in [ + short, + OutputImage { width: f64::NAN, ..picture(4, 2) }, + OutputImage { height: 0.0, ..picture(4, 2) }, + OutputImage { width_px: 0, rgba: Vec::new(), ..picture(4, 2) }, + OutputImage { width_px: MAX_IMAGE_SIDE_PX + 1, ..picture(4, 2) }, + ] { + assert!(!bad.is_valid()); + assert!(write_pdf_pages(&[page(vec![bad])]).is_err()); + } + } +} 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/picker.rs b/crates/font-manager/src/picker.rs index f25d489bf7..38494890c6 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 bdba2c9bc4..30844bd35a 100644 --- a/crates/font-manager/src/picker/stories.rs +++ b/crates/font-manager/src/picker/stories.rs @@ -235,7 +235,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/picker.rs b/crates/font-manager/tests/it/picker.rs index c49b251ebd..f4abffaf77 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 } + } + /// `" + + + + + + + + "#, + ); + assert_eq!(got.shapes.len(), 3); + assert_eq!(got.groups.len(), 2); + assert_eq!(got.groups[0].source_id.as_deref(), Some("decor")); + assert_eq!(got.groups[0].label.as_deref(), Some("Decorative motif")); + assert_eq!( + got.groups[0].attributes, + vec![ + GroupMetadata { attribute: GroupAttribute::unqualified("data-group"), value: "15".into() }, + GroupMetadata { attribute: GroupAttribute::namespaced("urn:editor-metadata", "group-id"), value: "42".into() }, + ] + ); + assert!(got.groups[0].parent.is_none()); + assert_eq!(got.groups[1].source_id.as_deref(), Some("details")); + assert_eq!(got.groups[1].parent, Some(0)); + assert!(got.groups[1].attributes.is_empty()); + assert_eq!(got.shapes.iter().map(|s| s.group).collect::>(), [Some(1), Some(0), None]); + } + + #[test] + fn repeated_use_groups_have_distinct_membership_at_each_site() { + let got = read( + r##" + + + + + + "##, + ); + assert_eq!(got.shapes.len(), 2); + assert_eq!(got.groups.len(), 5); + assert_eq!(got.groups.iter().map(|g| g.parent).collect::>(), [None, Some(0), Some(1), Some(0), Some(3)]); + assert_eq!(got.shapes.iter().map(|s| s.group).collect::>(), [Some(2), Some(4)]); + assert_eq!(got.groups[1].source_id, got.groups[3].source_id); + assert!(bounds(&got, 1).x0 > bounds(&got, 0).x0); + } + #[test] fn local_use_instances_take_x_y_transform_and_symbol_viewboxes() { let got = read( diff --git a/crates/svg/src/write.rs b/crates/svg/src/write.rs index 7fb4986914..1df9d2f1fc 100644 --- a/crates/svg/src/write.rs +++ b/crates/svg/src/write.rs @@ -40,13 +40,16 @@ pub struct Scene { pub elements: Vec, } -/// Structured SVG elements supported by the path-document writer. +/// Structured SVG elements supported by the path-document writer. An `Image`'s `href` is its +/// URL, usually a `data:` URL that embeds the picture (SVG 2's `href`, so the document needs no +/// xlink namespace); it is escaped like every attribute value. #[derive(Clone, Debug, PartialEq)] pub enum Element { Group { attributes: Vec, children: Vec }, Path { attributes: Vec, path: BezPath }, Rect { attributes: Vec, x: f64, y: f64, width: f64, height: f64 }, Text { attributes: Vec, x: f64, y: f64, text: String }, + Image { attributes: Vec, x: f64, y: f64, width: f64, height: f64, href: String }, Title(String), Style(String), NestedSvg { attributes: Vec, children: Vec }, @@ -172,6 +175,17 @@ fn write_elements(writer: &mut SvgWriter, elements: &[Element], depth: usize) { attrs.extend(attributes.iter().cloned()); write_attributes(writer.tag("rect"), &attrs).empty(); } + Element::Image { attributes, x, y, width, height, href } => { + let mut attrs = vec![ + Attribute::number("x", *x), + Attribute::number("y", *y), + Attribute::number("width", *width), + Attribute::number("height", *height), + Attribute::text("href", href.as_str()), + ]; + attrs.extend(attributes.iter().cloned()); + write_attributes(writer.tag("image"), &attrs).empty(); + } Element::Text { attributes, x, y, text } => { let mut attrs = vec![Attribute::number("x", *x), Attribute::number("y", *y)]; attrs.extend(attributes.iter().cloned()); @@ -437,6 +451,33 @@ mod tests { assert_eq!(Attribute::translate_scale_fixed(6.0, 46.0, 0.5, -0.5).value, Value::Text("translate(6.000 46.000) scale(0.5000 -0.5000)".into())); } + #[test] + fn scene_images_are_placed_and_their_url_cannot_add_markup() { + let image = |href: &str| Element::Image { + attributes: vec![Attribute::text("preserveAspectRatio", "none")], + x: 1.0, + y: 2.0, + width: 30.0, + height: 20.0, + href: href.into(), + }; + let scene = Scene { + width_mm: 100.0, + height_mm: 150.0, + view_box: [0.0, 0.0, 100.0, 150.0], + elements: vec![image("data:image/png;base64,iVBORw0KGgo="), image("x\"/>"# + ), + "{svg}" + ); + assert!(!svg.contains("-` in the system temporary directory and returns an error instead of panicking. Dropping it removes the folder with its contents, also when the test panics; removal on drop is best effort, and `close()` removes it and returns the error. A folder with a name that is already taken is skipped and left as it is. On Unix `new` asks for mode 0o700 (the umask can remove more bits), and returns an error when the folder it made is a link, is open to other users or is owned by another user. It returns `PermissionDenied` when the mode lacks owner read, write or search permission. The check reads mode bits only. It does not read POSIX or NFSv4 access control lists, so an entry that grants another user access is not detected. On Windows the folder gets the inheritable access entries of the temporary directory (the user's own `%LOCALAPPDATA%\Temp` by default) and is not checked. When `TMP` or `TEMP` names a shared folder, other users may be able to open the new folder, depending on that folder's access entries. `path()` returns the canonical path (`/private/var/...` on macOS, `\\?\...` on Windows). `file(name)` returns the path of `name` in the folder. On every platform, `new(tag)` and `file(name)` return `InvalidInput` for an empty tag or name, `.`, `..`, or a tag or name with `/`, `\`, `:`, `<`, `>`, `"`, `|`, `?`, `*`, NUL or a control character U+0001 to U+001F. The module is not built for `wasm32`. + +```rust +let dir = craft_testkit::TempDir::new("export")?; +std::fs::write(dir.file("out.png")?, &png)?; +``` + +## log + +The `log` feature adds `craft_testkit::log` and the `log` dependency. The module is built on every target except `wasm32`. + +| Function | Captures | Returns | +|---|---|---| +| `warnings(f)` | warnings and errors logged on the calling thread while `f` runs | `Result<(T, Vec), CaptureError>` with the messages | +| `records(level, f)` | records at `level` or more severe logged on the calling thread while `f` runs | `Result<(T, Vec), CaptureError>` with level, target and message | +| `capture_global(level)` | records at `level` or more severe logged on any thread | `Result`; `drain()` takes the records captured since the last drain | + +`log::set_logger` can be called once per process, so the first capture to install the logger sets the mode for the whole test binary: per thread (`warnings`, `records`) or process wide (`capture_global`). The functions return these errors without running the closure or changing the maximum level: + +| Error | When | +|---|---| +| `LoggerAlreadySet` | another logger was installed first | +| `ModeConflict` | the binary already captures in the other mode | +| `NestedCapture` | `warnings` or `records` is called inside a capture on the same thread | +| `GlobalCaptureActive` | another `GlobalCapture` is alive; dropping it ends that capture, and the logger stays installed | + +A capture raises `log::max_level()` to the level it asks for and never lowers it. When the closure panics, the capture on that thread ends and the panic continues. Records from other threads do not appear in a per-thread capture. + +A capture keeps at most `MAX_RECORDS` (4,096) records and `MAX_BYTES` (1 MiB) of message and target text. Formatting a message stops at the first write that would take it past `MAX_BYTES`. A record over either limit is dropped and counted, and the capture returns `CaptureError::Overflow { dropped }` instead of a partial list. For `drain`, the limits apply to each interval between drains. + +Run process-wide captures in a binary of their own, for example a `[[test]]` with `harness = false`: + +```rust +fn drop_the_plugin() { + log::warn!("plugin dropped off the main thread"); +} + +fn main() { + let capture = craft_testkit::log::capture_global(log::LevelFilter::Warn).expect("capture"); + std::thread::Builder::new() + .name("audio".into()) + .spawn(drop_the_plugin) + .expect("spawn") + .join() + .expect("join"); + let records = capture.drain().expect("drain"); + assert!(records.iter().any(|r| r.message.contains("off the main thread"))); +} +``` + ## `image` feature `craft-testkit = { ..., features = ["image"] }` adds `craft_testkit::image` and `assert_similar!`. It depends on `png` 0.18. @@ -445,6 +497,44 @@ test binary again as a child process with that variable set. The tests use channel handshakes and contain no sleeps or time limits. +## prop + +The `prop` feature adds the `prop` module and the `proptest` dependency. The module is not built for +`wasm32`. + +`prop::config(cases)` returns a `proptest::test_runner::Config` with failure persistence off. It +reads proptest's own variables: + +| Variable | Not set | Set | +|---|---|---| +| `PROPTEST_CASES` | `cases`. A `cases` of 0 makes `config` panic. | The value as a `u32` greater than 0. Any other value, 0 included, makes `config` panic. | +| `PROPTEST_RNG_SEED` | `prop::SEED` (`0x5eed_9a7f`) | The value as a `u64`. Any other value makes `config` panic. | + +A suite under `prop::config` repeats the same cases on every run. To run it with other cases, set +`PROPTEST_RNG_SEED` to another number. No file under `proptest-regressions/` is read +or written, so a minimal failure found with other seeds or counts is kept as a named regression test +in the suite. + +`config` uses the generator that `PROPTEST_RNG_ALGORITHM` names: `xs` (XorShift), `cc` (ChaCha) or +`rc` (Recorder). Any other value, including `pt` (the pass-through generator, which reads +caller-supplied bytes instead of a `u64` seed), makes `config` panic. When the variable is unset, +`config` keeps the generator from `Config::default()`. To +repeat a failing run, set the same `PROPTEST_RNG_ALGORITHM` value as well as the same seed and count, +and keep every other `PROPTEST_*` variable the run had, such as `PROPTEST_MAX_DEFAULT_SIZE_RANGE`. + +```rust +use proptest::prelude::*; + +proptest! { + #![proptest_config(craft_testkit::prop::config(64))] + + #[test] + fn parse_never_panics(bytes in proptest::collection::vec(any::(), 0..256)) { + let _ = my_crate::parse(&bytes); + } +} +``` + ## Origin ### serial @@ -494,6 +584,22 @@ PhotoCraft and DeckCraft. `holders_take_turns` waits on channels where the copie |---|---|---|---| | `Rng`, the edits of `mutations` and `hammer` | storytold/craft-libs | `crates/media-testkit/src/hostile.rs` | `75a654f4` | +### temp + +| Code | Repository | Path | SHA | +|---|---|---|---| +| `temp_dir`, `TempDir` | storytold/vectorcraft | `crates/testkit/src/lib.rs` | `bada8e1710` | +| `ScratchDir` | storytold/pdfcraft#6124 | `crates/testkit/src/scratch.rs` | `92e2071199` | +| `private_dir` | storytold/craft-libs | `crates/media-testkit/src/lib.rs` | `75a654f4f8` | +| `TempDir` | storytold/cadcraft | `crates/engine/tests/support/temp_dir.rs`, `crates/ui-egui/tests/support/temp_dir.rs` | `8e69890223` | + +### log + +| Code | Repository | Path | SHA | +|---|---|---|---| +| `log` (per thread) | storytold/craft-libs | `crates/docx/src/test_log.rs` (the same file as `crates/wordmodel/src/test_log.rs` and WordCraft's `crates/doc/src/test_log.rs` and `crates/formats/src/test_log.rs`) | `e3e31693` | +| `log` (process wide) | storytold/soundcraft | `crates/clap-host/tests/editor_main_thread.rs:18-41` | `e6cbf761` | + ### image | Code | Source | @@ -541,6 +647,12 @@ PhotoCraft and DeckCraft. `holders_take_turns` waits on channels where the copie | `rng` (`XorShift64`) | storytold/craft-libs | `crates/video/tests/dnx/fuzz_hostile.rs:9-20` | `9f10d434` | | `rng` (`XorShift64Star`) | storytold/craft-libs | `crates/jpeg/tests/mutation.rs:28-46` | `97c83dc9` | +### prop + +| Code | Repository | Path | SHA | +|---|---|---|---| +| `config` and `SEED` | storytold/vectorcraft | `crates/pathops/tests/common/mod.rs:3-20` | `34627134` | + ## Migration ### guards @@ -591,6 +703,23 @@ An adoption keeps the variable name the app uses today. CADCraft's and TextureCraft's loops make other edits than `mutations`. Their adoptions say which cases change, and keep the test names. +### temp + +| Consumer | Code it replaces | State | +|---|---|---| +| VectorCraft | `temp_dir` and `TempDir` in `crates/testkit/src/lib.rs` | Pending. `temp_dir(tag)` shares one folder per tag in a process; its test of that is not moved. | +| PdfCraft | `ScratchDir` in `crates/testkit/src/scratch.rs` (#6124) | Pending. `ScratchFile` has no counterpart; `TempDir::file` returns a path in a `TempDir`. | +| CADCraft | `crates/engine/tests/support/temp_dir.rs`, `crates/ui-egui/tests/support/temp_dir.rs` | Pending. Its `TempDir` empties a leftover folder of the same name; `temp` makes a new one. | +| `craft-media-testkit` | `private_dir()` in `crates/media-testkit/src/lib.rs` | Pending. `private_dir()` is unchanged. | + +### log + +| Consumer | Code it replaces | State | +|---|---|---| +| craft-libs `docx`, `wordmodel` | their private `test_log.rs` | Pending: a separate pull request switches both | +| WordCraft `doc`, `formats` | their private `test_log.rs` | Pending: a separate pull request in WordCraft | +| SoundCraft `clap-host` | the logger in `tests/editor_main_thread.rs` | Pending: a separate pull request in SoundCraft switches it to `capture_global` | + ### image | Consumer | Today | State | @@ -655,3 +784,14 @@ Each adoption says which values change and keeps the variable name. | DeckCraft | `serial` | No | | EffectCraft | `serial` | No | | PdfCraft | `serial` | No | + +### prop + +| Consumer | Code it replaces | State | +|---|---|---| +| VectorCraft `pathops` | the `Config` of `tests/props.rs` and `tests/prop_pathops.rs` | Pending | +| craft-libs | the 34 `Config` values that set `cases` directly, and the eight committed `proptest-regressions` files outside `vendor/` | Pending | +| LightCraft, FilmCraft | the property suites that set their case count | Pending | + +Each adoption names every suite whose seed changes from random to pinned, and turns committed +regression cases into named tests. diff --git a/crates/testkit/src/lib.rs b/crates/testkit/src/lib.rs index 1075741832..1025dd3a95 100644 --- a/crates/testkit/src/lib.rs +++ b/crates/testkit/src/lib.rs @@ -38,11 +38,20 @@ //! truncation of it and those copies, one after another on a worker thread with a time limit for //! each, and fails the test with the case that panicked or did not finish. //! +//! With the `log` feature, on targets other than `wasm32`, `log::warnings` and `log::records` +//! capture the records the calling thread logs while a closure runs, and `log::capture_global` +//! captures the records every thread logs. One test binary uses one of the two modes. +//! //! On targets other than `wasm32`, `serial` holds `serial::TestLock`, a lock that a `static` //! can hold and that the thread holding it can take again, and `serial::gpu_lock`, the one lock //! for GPU tests. Every GPU test in a process must take this lock, because a test that takes a //! different lock can run at the same time as one that takes this one. //! +//! On targets other than `wasm32`, `temp::TempDir` is a new test folder, private to the user on +//! Unix, that is removed with its contents when dropped, also when the test panics. Removal on drop +//! is best effort; `temp::TempDir::close` returns the error. The Unix privacy check reads the mode +//! bits only; it does not read POSIX or NFSv4 access control lists. +//! //! `skip` decides what a test does when something it needs is missing (a program, a corpus, //! the craft-fonts faces): it prints one `SKIPPED:` line and returns, or fails the test when the //! variable the caller names is `1`. A value other than unset, empty or `1` fails the test as a @@ -53,6 +62,11 @@ //! corpus folder against them: `corpus::Manifest`, `corpus::verify` and the test gate //! `corpus::pinned`, which skips or fails under the rule of `skip`. //! +//! With the `prop` feature, on targets other than `wasm32`, `prop::config` returns a proptest +//! configuration with a pinned seed and failure persistence off. `PROPTEST_CASES` and +//! `PROPTEST_RNG_SEED` override the case count and the seed, and `config` panics on a value it cannot +//! parse. +//! //! With the `mcp` feature, on targets other than `wasm32`, `mcp::McpChild` runs an MCP server as a //! child process and talks to it over stdin and stdout, with a deadline on every wait and a length //! limit on every line it reads. @@ -84,14 +98,20 @@ pub mod guards; pub mod hostile; #[cfg(feature = "image")] pub mod image; +#[cfg(all(feature = "log", not(target_arch = "wasm32")))] +pub mod log; #[cfg(all(feature = "mcp", not(target_arch = "wasm32")))] pub mod mcp; +#[cfg(all(feature = "prop", not(target_arch = "wasm32")))] +pub mod prop; pub mod rng; pub mod sample_damage; #[cfg(not(target_arch = "wasm32"))] pub mod serial; #[cfg(not(target_arch = "wasm32"))] pub mod skip; +#[cfg(not(target_arch = "wasm32"))] +pub mod temp; #[cfg(not(target_arch = "wasm32"))] pub use deadline::{DeadlineLimit, Signal, wait_until, with_deadline}; @@ -99,3 +119,5 @@ pub use guards::{AsFileSource, Finding, predefined_quit, std_instant, wgsl_float #[cfg(not(target_arch = "wasm32"))] pub use guards::{SourceLimits, rust_sources, rust_sources_with_limits}; +#[cfg(not(target_arch = "wasm32"))] +pub use temp::TempDir; diff --git a/crates/testkit/src/log.rs b/crates/testkit/src/log.rs new file mode 100644 index 0000000000..d48410391f --- /dev/null +++ b/crates/testkit/src/log.rs @@ -0,0 +1,360 @@ +//! Capture of the records a test logs through the `log` crate. +//! +//! The module installs one `log::Log` implementation for the process. `log::set_logger` can be +//! called once per process, so a test binary uses one of two modes, and the first call that +//! installs the logger fixes the mode for the rest of the process: +//! +//! - Per thread: [`warnings`] and [`records`] run a closure and return its result with the records +//! logged on the calling thread while it ran. Records from other threads are not captured. +//! - Process wide: [`capture_global`] returns a [`GlobalCapture`] whose [`GlobalCapture::drain`] +//! takes the records logged on every thread since the last drain. +//! +//! A call for the other mode returns [`CaptureError::ModeConflict`]. When another logger is already +//! installed, every call returns [`CaptureError::LoggerAlreadySet`], runs no closure and leaves the +//! global maximum level as it is. +//! +//! A capture raises the global maximum level (`log::max_level`) to the level it asks for and never +//! lowers it, so a capture does not hide records from code that raised the level earlier. Each +//! capture filters by its own level. +//! +//! A capture keeps at most [`MAX_RECORDS`] records and [`MAX_BYTES`] bytes of message and target +//! text. Formatting a message stops at the first write that would take it past [`MAX_BYTES`]. A +//! record over either limit is dropped and counted, and the capture then returns +//! [`CaptureError::Overflow`] with the number dropped instead of a partial list. + +use std::cell::RefCell; +use std::fmt; +use std::sync::atomic::{AtomicU8, AtomicU64, Ordering}; +use std::sync::{Mutex, MutexGuard, PoisonError}; + +use ::log::{Level, LevelFilter, Log, Metadata, Record}; + +/// The most records one capture keeps. +pub const MAX_RECORDS: usize = 4096; + +/// The most bytes of message and target text one capture keeps. +pub const MAX_BYTES: usize = 1 << 20; + +/// One captured record. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CapturedRecord { + /// The record's level. + pub level: Level, + /// The record's target, by default the module path of the call. + pub target: String, + /// The formatted message. + pub message: String, +} + +/// Why a capture could not run or could not return its records. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[non_exhaustive] +pub enum CaptureError { + /// Another logger was installed in this process before this module's logger. + LoggerAlreadySet, + /// This process captures in the other mode: per thread or process wide. + ModeConflict, + /// [`warnings`] or [`records`] was called inside a capture on the same thread. + NestedCapture, + /// A [`GlobalCapture`] is still alive in this process. + GlobalCaptureActive, + /// The capture reached [`MAX_RECORDS`] or [`MAX_BYTES`] and dropped this many records. + Overflow { + /// The number of records dropped. + dropped: usize, + }, +} + +impl fmt::Display for CaptureError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::LoggerAlreadySet => f.write_str("another logger is already installed in this process"), + Self::ModeConflict => f.write_str("this process already captures logs in the other mode (per thread or process wide)"), + Self::NestedCapture => f.write_str("a log capture is already running on this thread"), + Self::GlobalCaptureActive => f.write_str("a process-wide log capture is already alive"), + Self::Overflow { dropped } => { + write!(f, "the log capture dropped {dropped} records over its limit of {MAX_RECORDS} records or {MAX_BYTES} bytes") + } + } + } +} + +impl std::error::Error for CaptureError {} + +const MODE_NONE: u8 = 0; +const MODE_THREAD: u8 = 1; +const MODE_GLOBAL: u8 = 2; + +/// The installed mode, read by the logger on every record. +static MODE: AtomicU8 = AtomicU8::new(MODE_NONE); + +/// Serializes installation and changes of the global maximum level. +static INSTALL: Mutex<()> = Mutex::new(()); + +/// The bits of [`GLOBAL_STATE`] that hold the level. +const LEVEL_BITS: u32 = 3; +const LEVEL_MASK: u64 = (1 << LEVEL_BITS) - 1; + +/// The process-wide capture's session number shifted left by [`LEVEL_BITS`], with its level as a +/// `LevelFilter` number in the low bits (`0`, `Off`, when no capture is alive). The logger reads +/// both in one load, so a record checked against one capture is never kept by a later one. +static GLOBAL_STATE: AtomicU64 = AtomicU64::new(0); + +static GLOBAL: Mutex = Mutex::new(Buffer::new()); + +/// Records kept within [`MAX_RECORDS`] and [`MAX_BYTES`], with a count of those dropped. +struct Buffer { + records: Vec, + bytes: usize, + dropped: usize, + /// For the process-wide buffer: whether a [`GlobalCapture`] is alive, and its session. + alive: bool, + session: u64, +} + +impl Buffer { + const fn new() -> Self { + Self { records: Vec::new(), bytes: 0, dropped: 0, alive: false, session: 0 } + } + + /// Keeps `record`, or counts it as dropped when it is `None` or over a limit. + fn push(&mut self, record: Option) { + let Some(record) = record else { + self.dropped = self.dropped.saturating_add(1); + return; + }; + let size = record.message.len().saturating_add(record.target.len()); + if self.records.len() >= MAX_RECORDS || size > MAX_BYTES.saturating_sub(self.bytes) { + self.dropped = self.dropped.saturating_add(1); + return; + } + self.bytes += size; + self.records.push(record); + } + + /// The kept records, or the overflow, leaving the buffer empty. + fn take(&mut self) -> Result, CaptureError> { + let records = std::mem::take(&mut self.records); + let dropped = std::mem::take(&mut self.dropped); + self.bytes = 0; + if dropped > 0 { Err(CaptureError::Overflow { dropped }) } else { Ok(records) } + } +} + +/// The per-thread capture running on a thread. +struct Scope { + level: LevelFilter, + buffer: Buffer, +} + +thread_local! { + static SCOPE: RefCell> = const { RefCell::new(None) }; +} + +/// A `fmt::Write` that keeps at most [`MAX_BYTES`] bytes and fails the write that would pass them. +struct Bounded { + text: String, + over: bool, +} + +impl fmt::Write for Bounded { + fn write_str(&mut self, s: &str) -> fmt::Result { + if s.len() > MAX_BYTES.saturating_sub(self.text.len()) { + self.over = true; + return Err(fmt::Error); + } + self.text.push_str(s); + Ok(()) + } +} + +/// The record with its message formatted, or `None` when its message or target passes +/// [`MAX_BYTES`]. +fn capture(record: &Record) -> Option { + let target = record.target(); + if target.len() > MAX_BYTES { + return None; + } + let mut message = Bounded { text: String::new(), over: false }; + // A `Display` implementation's own error leaves the text written so far. + let _ = fmt::write(&mut message, *record.args()); + if message.over { + return None; + } + Some(CapturedRecord { level: record.level(), target: target.to_owned(), message: message.text }) +} + +struct Capture; + +static CAPTURE: Capture = Capture; + +fn lock(m: &Mutex) -> MutexGuard<'_, T> { + m.lock().unwrap_or_else(PoisonError::into_inner) +} + +fn thread_level() -> LevelFilter { + SCOPE.try_with(|s| s.try_borrow().ok().and_then(|s| s.as_ref().map(|s| s.level))).ok().flatten().unwrap_or(LevelFilter::Off) +} + +impl Log for Capture { + fn enabled(&self, metadata: &Metadata) -> bool { + match MODE.load(Ordering::Acquire) { + MODE_THREAD => metadata.level() <= thread_level(), + MODE_GLOBAL => metadata.level() as u64 <= GLOBAL_STATE.load(Ordering::Acquire) & LEVEL_MASK, + _ => false, + } + } + + fn log(&self, record: &Record) { + let level = record.level(); + // Each message is formatted before any capture state is borrowed or locked, so a + // `Display` implementation that logs does not find that state in use. + match MODE.load(Ordering::Acquire) { + MODE_THREAD => { + if level > thread_level() { + return; + } + let captured = capture(record); + let _ = SCOPE.try_with(|s| { + if let Ok(mut s) = s.try_borrow_mut() + && let Some(scope) = s.as_mut() + && level <= scope.level + { + scope.buffer.push(captured); + } + }); + } + MODE_GLOBAL => { + let state = GLOBAL_STATE.load(Ordering::Acquire); + if level as u64 > state & LEVEL_MASK { + return; + } + let captured = capture(record); + let mut buffer = lock(&GLOBAL); + if buffer.alive && buffer.session == state >> LEVEL_BITS { + buffer.push(captured); + } + } + _ => {} + } + } + + fn flush(&self) {} +} + +/// Installs the logger in `mode` if no mode is set, then raises the global maximum level to +/// `level`. Nothing changes when the logger cannot be installed or the mode differs. +fn install(mode: u8, level: LevelFilter) -> Result<(), CaptureError> { + let _guard = lock(&INSTALL); + match MODE.load(Ordering::Acquire) { + MODE_NONE => { + ::log::set_logger(&CAPTURE).map_err(|_| CaptureError::LoggerAlreadySet)?; + MODE.store(mode, Ordering::Release); + } + m if m == mode => {} + _ => return Err(CaptureError::ModeConflict), + } + if ::log::max_level() < level { + ::log::set_max_level(level); + } + Ok(()) +} + +/// Clears this thread's capture when dropped, including during a panic in the captured closure. +struct ScopeGuard; + +impl Drop for ScopeGuard { + fn drop(&mut self) { + let _ = SCOPE.try_with(|s| { + if let Ok(mut s) = s.try_borrow_mut() { + *s = None; + } + }); + } +} + +/// `f`'s result and the records at `level` or more severe that the calling thread logged while +/// `f` ran. +/// +/// Records logged on other threads are not captured. Returns an error without running `f` when +/// another logger is installed, when this process captures process wide, or when a capture is +/// already running on this thread. Returns [`CaptureError::Overflow`] after `f` has run when it +/// logged more than the limits allow; `f`'s result is dropped in that case. +/// +/// If `f` panics, the capture ends and the panic continues. +pub fn records(level: LevelFilter, f: impl FnOnce() -> T) -> Result<(T, Vec), CaptureError> { + let running = SCOPE.try_with(|s| s.try_borrow().map_or(true, |s| s.is_some())).unwrap_or(true); + if running { + return Err(CaptureError::NestedCapture); + } + install(MODE_THREAD, level)?; + let started = SCOPE + .try_with(|s| match s.try_borrow_mut() { + Ok(mut s) if s.is_none() => { + *s = Some(Scope { level, buffer: Buffer::new() }); + true + } + _ => false, + }) + .unwrap_or(false); + if !started { + return Err(CaptureError::NestedCapture); + } + let guard = ScopeGuard; + let out = f(); + let taken = + SCOPE.try_with(|s| s.try_borrow_mut().ok().and_then(|mut s| s.take()).map(|mut s| s.buffer.take())).ok().flatten().unwrap_or(Ok(Vec::new())); + drop(guard); + taken.map(|records| (out, records)) +} + +/// `f`'s result and the messages of the warnings and errors the calling thread logged while `f` +/// ran. +/// +/// The same as [`records`] at `LevelFilter::Warn`, keeping only each record's message. +pub fn warnings(f: impl FnOnce() -> T) -> Result<(T, Vec), CaptureError> { + records(LevelFilter::Warn, f).map(|(out, records)| (out, records.into_iter().map(|r| r.message).collect())) +} + +/// Starts capturing the records at `level` or more severe that any thread logs. +/// +/// Returns an error when another logger is installed, when this process captures per thread, or +/// when another [`GlobalCapture`] is alive. Dropping the handle stops the capture and discards +/// the records it holds; the logger stays installed, and a later call starts a new capture. +pub fn capture_global(level: LevelFilter) -> Result { + let mut buffer = lock(&GLOBAL); + if buffer.alive { + return Err(CaptureError::GlobalCaptureActive); + } + install(MODE_GLOBAL, level)?; + let session = buffer.session.wrapping_add(1) & (u64::MAX >> LEVEL_BITS); + *buffer = Buffer { alive: true, session, ..Buffer::new() }; + GLOBAL_STATE.store((session << LEVEL_BITS) | level as u64, Ordering::Release); + Ok(GlobalCapture { _private: () }) +} + +/// A live process-wide capture. See [`capture_global`]. +#[derive(Debug)] +pub struct GlobalCapture { + _private: (), +} + +impl GlobalCapture { + /// The records captured on every thread since the capture started or since the last drain, in + /// the order they reached the capture. + /// + /// Returns [`CaptureError::Overflow`] when records were dropped in that interval; the records + /// kept in that interval are then discarded, and the next interval starts empty. + pub fn drain(&self) -> Result, CaptureError> { + lock(&GLOBAL).take() + } +} + +impl Drop for GlobalCapture { + fn drop(&mut self) { + let mut buffer = lock(&GLOBAL); + let session = buffer.session; + GLOBAL_STATE.store(session << LEVEL_BITS, Ordering::Release); + *buffer = Buffer { session, ..Buffer::new() }; + } +} diff --git a/crates/testkit/src/prop.rs b/crates/testkit/src/prop.rs new file mode 100644 index 0000000000..10ba18df88 --- /dev/null +++ b/crates/testkit/src/prop.rs @@ -0,0 +1,98 @@ +//! Proptest configuration for property suites that must repeat the same cases on every run. +//! +//! [`config`] starts from proptest's `Config::default()`, which has already read the `PROPTEST_*` +//! variables, turns failure persistence off, and then: +//! +//! - uses the caller's case count unless `PROPTEST_CASES` is set, and +//! - pins the seed to [`SEED`] unless `PROPTEST_RNG_SEED` is set. +//! +//! The effective case count must be greater than zero. If `PROPTEST_CASES` is unset, `config(0)` +//! panics with a message naming the caller's case count. A set `PROPTEST_CASES` must parse as a +//! nonzero `u32`, and a set `PROPTEST_RNG_SEED` must parse as a `u64`. +//! For any other value, `config` panics with a message that names the variable and its value, +//! and the suite fails. Proptest's own fallback of 256 cases or a random seed is not used, so every +//! run's seed is either [`SEED`] or the number in `PROPTEST_RNG_SEED`. +//! +//! No file under `proptest-regressions/` is read or written. A minimal failure found with other +//! seeds or counts, for example with `PROPTEST_CASES=5000 PROPTEST_RNG_SEED=`, is kept as a named +//! regression test in the suite. + +use std::ffi::OsStr; +use std::str::FromStr; + +use proptest::test_runner::{Config, RngAlgorithm, RngSeed}; + +/// The seed [`config`] uses when `PROPTEST_RNG_SEED` is not set. +pub const SEED: u64 = 0x5eed_9a7f; + +/// A proptest configuration that runs `cases` cases from [`SEED`] with failure persistence off. +/// +/// `PROPTEST_CASES` replaces `cases` and `PROPTEST_RNG_SEED` replaces the seed when either is set. +/// Pass the result to `#![proptest_config(...)]` or to `TestRunner::new`. When `PROPTEST_FORK` or +/// `PROPTEST_TIMEOUT` turns on fork mode, `TestRunner::run` needs `test_name` set to the test's fully +/// qualified name. The named-test form of `proptest!` sets it, and drawing values without `run` does +/// not need it. +/// +/// # Panics +/// +/// Panics when `cases` is zero and `PROPTEST_CASES` is unset, or when `PROPTEST_CASES` is set to +/// zero or a value that is not a `u32`. Also panics when `PROPTEST_RNG_SEED` is set to a value +/// that is not a `u64`, or `PROPTEST_RNG_ALGORITHM` is set to a value other than `xs`, `cc` or `rc`. +pub fn config(cases: u32) -> Config { + let mut c = Config { failure_persistence: None, ..Config::default() }; + let cases_var = std::env::var_os("PROPTEST_CASES"); + c.cases = match cases_var.as_deref() { + None => cases, + Some(value) => parse_var("PROPTEST_CASES", value, "a u32"), + }; + if c.cases == 0 { + reject_zero_cases(cases_var.as_deref()); + } + c.rng_seed = match std::env::var_os("PROPTEST_RNG_SEED") { + None => RngSeed::Fixed(SEED), + Some(value) => RngSeed::Fixed(parse_var("PROPTEST_RNG_SEED", &value, "a u64")), + }; + if let Some(value) = std::env::var_os("PROPTEST_RNG_ALGORITHM") { + c.rng_algorithm = parse_rng_algorithm(&value); + } + if c.rng_algorithm == RngAlgorithm::PassThrough { + reject_pass_through(); + } + c +} + +#[allow(clippy::panic)] +fn reject_zero_cases(value: Option<&OsStr>) -> ! { + match value { + Some(value) => panic!("PROPTEST_CASES={value:?} must be greater than zero"), + None => panic!("the caller's case count is zero: config(0) requires a positive case count"), + } +} + +// Proptest falls back to ChaCha with only a warning for a value it does not know. +#[allow(clippy::panic)] +fn parse_rng_algorithm(value: &OsStr) -> RngAlgorithm { + match value.to_str() { + Some("xs") => RngAlgorithm::XorShift, + Some("cc") => RngAlgorithm::ChaCha, + Some("rc") => RngAlgorithm::Recorder, + Some("pt") => RngAlgorithm::PassThrough, + _ => panic!("PROPTEST_RNG_ALGORITHM={value:?} is not a supported RNG algorithm (expected xs, cc or rc)"), + } +} + +// The pass-through generator needs bytes from the caller, so a runner built from it panics later +// with a message that does not name the variable. +#[allow(clippy::panic)] +fn reject_pass_through() { + panic!("PROPTEST_RNG_ALGORITHM=\"pt\" is not supported: the pass-through generator reads caller-supplied bytes, not a u64 seed"); +} + +// Failing the calling test is what this function is for. +#[allow(clippy::panic)] +fn parse_var(name: &str, value: &OsStr, expected: &str) -> T { + match value.to_str().and_then(|s| s.parse().ok()) { + Some(parsed) => parsed, + None => panic!("{name}={value:?} is not {expected}"), + } +} diff --git a/crates/testkit/src/temp.rs b/crates/testkit/src/temp.rs new file mode 100644 index 0000000000..1b86bcefb6 --- /dev/null +++ b/crates/testkit/src/temp.rs @@ -0,0 +1,475 @@ +//! Test folders that are removed with their contents when the test that made them ends. +//! +//! [`TempDir::new`] makes a new, empty folder in the system temporary directory with +//! [`tempfile::Builder`]: the name is `craft-testkit--` followed by random characters, and a +//! name that is already taken is skipped. A folder this module did not make is never emptied or +//! reused. On Unix the folder is made with mode 0o700, and before [`TempDir::new`] returns it checks +//! that the folder is a real folder, not a link, with no access for other users, and owned by the +//! user running the test. The access check reads the mode bits only; it does not read POSIX or NFSv4 +//! access control lists, so an entry that grants another user access is not detected. The checks apply to the created folder only, so a temporary directory +//! reached through a link (`/var` on macOS links to `/private/var`) works. On Windows the folder +//! gets the inheritable access entries of the temporary directory, which is the user's own +//! `%LOCALAPPDATA%\Temp` by default, and no access check is made. When `TMP` or `TEMP` names a +//! shared folder, other users may be able to open the new folder, depending on that folder's +//! access entries. +//! +//! [`TempDir::path`] returns the canonical path of the folder: `/private/var/...` on macOS, and a +//! `\\?\` path on Windows. Compare it with another canonical path, not with a join of +//! [`std::env::temp_dir`]. +//! +//! Dropping a [`TempDir`], also while a test panics, removes the folder with everything in it. A +//! link inside the folder is removed, not followed. Removal on drop is best effort: a file another +//! process holds open can stop it on Windows. [`TempDir::close`] removes the folder and returns the +//! error. A process that is killed or aborts leaves its folders behind, and later calls skip them. +//! +//! The checks read the folder once, after it is made. They do not protect against a process of the +//! same user that replaces the folder after the check. + +use std::io; +use std::path::{Path, PathBuf}; + +/// How many random characters follow the tag in a folder name. +const RANDOM_CHARS: usize = 10; + +/// The file [`TempDir::new`] makes, reads and removes in a new folder on Unix to learn which user +/// owns the files this process makes. +#[cfg(unix)] +const OWNER_PROBE: &str = ".craft-testkit-owner"; + +/// A new, empty folder in the system temporary directory, removed with its contents when dropped, +/// also when the test panics. +/// +/// Bind it to a variable that lives as long as the folder is needed. Used as a temporary, as in +/// `TempDir::new("x")?.file("a.png")`, it is dropped, and the folder removed, at the end of that +/// statement. +#[derive(Debug)] +pub struct TempDir { + /// The canonical path of the folder. + path: PathBuf, + /// Removes the folder when dropped. + dir: tempfile::TempDir, +} + +impl TempDir { + /// Makes a new folder named `craft-testkit--` in + /// [`std::env::temp_dir`]. Each call makes a folder of its own, also for calls with the same + /// tag at the same time. + /// + /// # Errors + /// + /// `InvalidInput` when `tag` is empty, `.` or `..`, or holds `/`, `\`, `:`, `<`, `>`, `"`, + /// `|`, `?`, `*`, NUL or a control character U+0001 to U+001F, on every platform. + /// The error from the file system when the folder cannot be made. An error when the folder that + /// was made is a link or another kind of entry, is open to other users, or is owned by another + /// user; such a folder is left in place. On Unix, `PermissionDenied` when the mode lacks owner + /// read, write or search permission; such a folder is also left in place. + pub fn new(tag: &str) -> io::Result { + Self::new_in(tag, &std::env::temp_dir(), RANDOM_CHARS) + } + + /// Makes the folder in `root`, with `random` random characters after the tag. + fn new_in(tag: &str, root: &Path, random: usize) -> io::Result { + one_name("tag", tag)?; + let prefix = format!("craft-testkit-{tag}-"); + let mut builder = tempfile::Builder::new(); + builder.prefix(&prefix).rand_bytes(random); + #[cfg(unix)] + builder.permissions(std::os::unix::fs::PermissionsExt::from_mode(0o700)); + Self::guard(builder.tempdir_in(std::fs::canonicalize(root)?)?) + } + + /// Checks the folder `dir` made and returns it with its canonical path. A folder that fails the + /// check is left in place, since it may not be the one `dir` made. + fn guard(mut dir: tempfile::TempDir) -> io::Result { + if let Err(e) = verify(dir.path()) { + dir.disable_cleanup(true); + return Err(e); + } + let path = std::fs::canonicalize(dir.path())?; + Ok(Self { path, dir }) + } + + /// The canonical, absolute path of the folder. + pub fn path(&self) -> &Path { + &self.path + } + + /// The path of `name` in the folder. The file is not made. + /// + /// # Errors + /// + /// `InvalidInput` when `name` is empty, `.` or `..`, or holds `/`, `\`, `:`, `<`, `>`, `"`, + /// `|`, `?`, `*`, NUL or a control character U+0001 to U+001F, on every platform. + pub fn file(&self, name: &str) -> io::Result { + one_name("file name", name)?; + Ok(self.path.join(name)) + } + + /// Removes the folder with everything in it. + /// + /// # Errors + /// + /// The error from the file system when the folder or something in it cannot be removed. + pub fn close(self) -> io::Result<()> { + self.dir.close() + } +} + +impl AsRef for TempDir { + fn as_ref(&self) -> &Path { + &self.path + } +} + +/// Returns `InvalidInput` unless `name` is one path component on every platform. +fn one_name(what: &str, name: &str) -> io::Result<()> { + if name.is_empty() + || name == "." + || name == ".." + || name.contains(['/', '\\', ':', '<', '>', '"', '|', '?', '*']) + || name.chars().any(|c| c <= '\u{1f}') + { + return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("{what} {name:?} is not a single file name"))); + } + Ok(()) +} + +/// What [`verify`] reads about a folder, without following a link. +#[derive(Debug, Clone, Copy)] +struct Entry { + is_dir: bool, + is_symlink: bool, + /// The permission bits, on Unix. + mode: Option, + /// The user id of the owner, on Unix. + owner: Option, +} + +/// Checks that `path` is a folder this process made, as [`check`] describes. +fn verify(path: &Path) -> io::Result<()> { + let meta = std::fs::symlink_metadata(path)?; + #[cfg(unix)] + let (mode, owner) = (Some(std::os::unix::fs::PermissionsExt::mode(&meta.permissions())), Some(std::os::unix::fs::MetadataExt::uid(&meta))); + #[cfg(not(unix))] + let (mode, owner) = (None, None); + let entry = Entry { is_dir: meta.is_dir(), is_symlink: meta.file_type().is_symlink(), mode, owner }; + check(path, entry, || my_uid(path)) +} + +/// Returns an error unless `entry` is a real folder, not a link, with no access for group or other +/// users, with owner read, write and search permission on Unix, owned by the user `me` returns. +/// `me` runs only after the other checks pass. +fn check(path: &Path, entry: Entry, me: impl FnOnce() -> io::Result>) -> io::Result<()> { + if entry.is_symlink || !entry.is_dir { + return Err(io::Error::other(format!("{}: a link or another kind of entry is in place of the new folder", path.display()))); + } + if entry.mode.is_some_and(|mode| mode & 0o077 != 0) { + return Err(io::Error::new(io::ErrorKind::PermissionDenied, format!("{}: the new folder is open to other users", path.display()))); + } + if entry.mode.is_some_and(|mode| mode & 0o700 != 0o700) { + return Err(io::Error::new(io::ErrorKind::PermissionDenied, format!("{}: the owner cannot use the new folder", path.display()))); + } + if entry.owner != me()? { + return Err(io::Error::new(io::ErrorKind::PermissionDenied, format!("{}: the new folder is owned by another user", path.display()))); + } + Ok(()) +} + +/// The user id that owns a file this process makes, read from a probe file made new in `dir` and +/// removed again. +#[cfg(unix)] +fn my_uid(dir: &Path) -> io::Result> { + let probe = dir.join(OWNER_PROBE); + let meta = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?.metadata(); + std::fs::remove_file(&probe)?; + Ok(Some(std::os::unix::fs::MetadataExt::uid(&meta?))) +} + +/// Files have no Unix owner here. +#[cfg(not(unix))] +fn my_uid(_dir: &Path) -> io::Result> { + Ok(None) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn entries(dir: &Path) -> usize { + std::fs::read_dir(dir).unwrap().count() + } + + #[test] + fn a_test_dir_is_removed_with_its_contents_when_dropped() { + let dir = TempDir::new("dropped").unwrap(); + let path = dir.path().to_path_buf(); + std::fs::create_dir_all(path.join("nested")).unwrap(); + std::fs::write(path.join("nested").join("a.txt"), b"a").unwrap(); + drop(dir); + assert!(!path.exists(), "{} is left", path.display()); + } + + #[test] + fn a_test_dir_is_removed_when_its_test_panics() { + let mut path = None; + let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let dir = TempDir::new("panicked").unwrap(); + std::fs::write(dir.file("a.txt").unwrap(), b"a").unwrap(); + path = Some(dir.path().to_path_buf()); + panic!("the test fails"); + })); + assert_eq!(r.err().and_then(|p| p.downcast_ref::<&str>().copied()), Some("the test fails")); + let path = path.unwrap(); + assert!(!path.exists(), "{} is left", path.display()); + } + + #[test] + fn test_dirs_with_one_tag_are_separate_and_private() { + let (a, b) = (TempDir::new("shared-tag").unwrap(), TempDir::new("shared-tag").unwrap()); + assert_ne!(a.path(), b.path()); + std::fs::write(a.file("a.txt").unwrap(), b"a").unwrap(); + assert_eq!(entries(b.path()), 0, "one test's files are not in another's directory"); + #[cfg(unix)] + assert_eq!(std::os::unix::fs::PermissionsExt::mode(&std::fs::metadata(a.path()).unwrap().permissions()) & 0o777, 0o700); + drop(a); + assert!(b.path().is_dir(), "dropping one leaves the other"); + } + + #[test] + fn a_scratch_dir_is_removed_with_its_contents_when_dropped() { + let dir = TempDir::new("testkit-scratch").unwrap(); + let path = dir.path().to_path_buf(); + assert!(path.is_dir(), "{path:?} exists while the test holds it"); + assert_eq!(entries(&path), 0, "and starts empty"); + std::fs::create_dir_all(path.join("nested")).unwrap(); + std::fs::write(path.join("nested").join("a.pdf"), b"%PDF").unwrap(); + drop(dir); + assert!(!path.exists(), "{path:?} is gone, contents and all"); + } + + #[test] + fn scratch_dirs_with_the_same_name_are_separate_folders() { + let (a, b) = (TempDir::new("testkit-same").unwrap(), TempDir::new("testkit-same").unwrap()); + assert_ne!(a.path(), b.path()); + std::fs::write(a.file("x").unwrap(), b"a").unwrap(); + drop(b); + assert_eq!(std::fs::read(a.file("x").unwrap()).unwrap(), b"a", "dropping one leaves the other's files"); + } + + /// With one random character there are 62 names, and every one but `7` is taken: the new folder + /// is `7`, and the folders that were there keep their files. + #[test] + fn a_taken_name_is_skipped_and_its_folder_left_alone() { + let root = TempDir::new("taken-root").unwrap(); + let free = '7'; + let mut planted = Vec::new(); + for c in ('a'..='z').chain('A'..='Z').chain('0'..='9').filter(|&c| c != free) { + let folder = root.path().join(format!("craft-testkit-taken-{c}")); + // On a file system that ignores case, `A` is the folder `a` made. + match std::fs::create_dir(&folder) { + Ok(()) => std::fs::write(folder.join("theirs.pdf"), b"%PDF").unwrap(), + Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {} + Err(e) => panic!("{}: {e}", folder.display()), + } + planted.push(folder); + } + let dir = TempDir::new_in("taken", root.path(), 1).unwrap(); + assert_eq!(dir.path().file_name().and_then(|n| n.to_str()), Some("craft-testkit-taken-7")); + assert_eq!(entries(dir.path()), 0, "and starts empty"); + drop(dir); + for folder in &planted { + assert_eq!(std::fs::read(folder.join("theirs.pdf")).unwrap(), b"%PDF", "{folder:?} kept its file"); + } + } + + #[test] + fn existing_folder_is_never_reused() { + let root = TempDir::new("reuse-root").unwrap(); + let theirs = root.path().join("craft-testkit-reuse-"); + std::fs::create_dir(&theirs).unwrap(); + std::fs::write(theirs.join("theirs.txt"), b"theirs").unwrap(); + // With no random characters the one name tried is the folder above. + let err = TempDir::new_in("reuse", root.path(), 0).unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::AlreadyExists); + assert_eq!(std::fs::read(theirs.join("theirs.txt")).unwrap(), b"theirs"); + assert_eq!(entries(&theirs), 1); + } + + #[test] + fn creation_failure_returns_error() { + let root = TempDir::new("failure-root").unwrap(); + let file = root.file("a-file").unwrap(); + std::fs::write(&file, b"not a folder").unwrap(); + assert!(TempDir::new_in("x", &file, RANDOM_CHARS).is_err(), "a file as the root"); + assert!(TempDir::new_in("x", &root.path().join("missing"), RANDOM_CHARS).is_err(), "a missing root"); + } + + #[test] + fn tag_rejects_empty_and_separators() { + for tag in ["", ".", "..", "a/b", "a\\b", "../x", "..\\x", "/x", "C:\\x", "C:x", "a\0b"] { + let err = TempDir::new(tag).unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::InvalidInput, "{tag:?}"); + } + for c in ['<', '>', '"', '|', '?', '*'].into_iter().chain('\u{1}'..='\u{1f}') { + let tag = format!("a{c}b"); + assert_eq!(TempDir::new(&tag).unwrap_err().kind(), io::ErrorKind::InvalidInput, "{tag:?}"); + } + } + + #[test] + fn file_rejects_absolute_parent_and_separators() { + let root = TempDir::new("file-root").unwrap(); + let dir = TempDir::new_in("file", root.path(), RANDOM_CHARS).unwrap(); + for name in ["", ".", "..", "a/b", "a\\b", "../outside.txt", "..\\outside.txt", "/x", "\\x", "C:\\x", "C:x", "a:stream", "a\0b"] { + let err = dir.file(name).unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::InvalidInput, "{name:?}"); + } + for c in ['<', '>', '"', '|', '?', '*'].into_iter().chain('\u{1}'..='\u{1f}') { + let name = format!("report{c}.txt"); + assert_eq!(dir.file(&name).unwrap_err().kind(), io::ErrorKind::InvalidInput, "{name:?}"); + } + let a = dir.file("a.txt").unwrap(); + assert_eq!(a, dir.path().join("a.txt")); + assert!(!a.exists(), "file does not make the file"); + drop(dir); + assert_eq!(entries(root.path()), 0, "nothing was written next to the folder"); + } + + #[test] + fn path_is_canonical() { + let dir = TempDir::new("canonical").unwrap(); + assert!(dir.path().is_absolute()); + assert_eq!(dir.path(), std::fs::canonicalize(dir.path()).unwrap()); + assert_eq!(dir.path().parent().map(Path::to_path_buf), Some(std::fs::canonicalize(std::env::temp_dir()).unwrap())); + } + + #[cfg(windows)] + #[test] + fn windows_path_is_verbatim() { + let dir = TempDir::new("verbatim").unwrap(); + assert!(dir.path().to_string_lossy().starts_with(r"\\?\"), "{:?}", dir.path()); + } + + #[test] + fn same_tag_concurrent_creation_is_unique() { + let barrier = std::sync::Arc::new(std::sync::Barrier::new(16)); + let threads: Vec<_> = (0..16) + .map(|_| { + let barrier = std::sync::Arc::clone(&barrier); + std::thread::spawn(move || { + barrier.wait(); + TempDir::new("concurrent") + }) + }) + .collect(); + let dirs: Vec = threads.into_iter().map(|t| t.join().unwrap().unwrap()).collect(); + let paths: std::collections::BTreeSet<&Path> = dirs.iter().map(TempDir::path).collect(); + assert_eq!(paths.len(), 16); + assert!(dirs.iter().all(|d| entries(d.path()) == 0), "each starts empty"); + } + + #[test] + fn close_removes_the_folder() { + let dir = TempDir::new("close").unwrap(); + let path = dir.path().to_path_buf(); + std::fs::write(dir.file("a.txt").unwrap(), b"a").unwrap(); + dir.close().unwrap(); + assert!(!path.exists()); + } + + #[test] + fn close_reports_cleanup_failure() { + let dir = TempDir::new("close-failure").unwrap(); + std::fs::remove_dir(dir.path()).unwrap(); + assert!(dir.close().is_err(), "a folder that is already gone cannot be removed"); + } + + #[test] + fn wrong_owner_or_public_mode_is_rejected() { + let path = Path::new("folder"); + let private = Entry { is_dir: true, is_symlink: false, mode: Some(0o40700), owner: Some(1000) }; + assert!(check(path, private, || Ok(Some(1000))).is_ok()); + for mode in [0o40750, 0o40705, 0o40777] { + let err = check(path, Entry { mode: Some(mode), ..private }, || Ok(Some(1000))).unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::PermissionDenied, "{mode:o}"); + } + for mode in [0o40300, 0o40500, 0o40600] { + let err = check(path, Entry { mode: Some(mode), ..private }, || panic!("no probe without owner access")).unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::PermissionDenied, "{mode:o}"); + } + let err = check(path, private, || Ok(Some(1001))).unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::PermissionDenied); + assert!(check(path, Entry { is_symlink: true, ..private }, || panic!("no probe through a link")).is_err()); + assert!(check(path, Entry { is_dir: false, ..private }, || panic!("no probe in a file")).is_err()); + let open = Entry { mode: Some(0o40777), ..private }; + assert!(check(path, open, || panic!("no probe in an open folder")).is_err()); + } + + #[cfg(unix)] + #[test] + fn new_dir_is_owner_private() { + use std::os::unix::fs::{MetadataExt, PermissionsExt}; + let dir = TempDir::new("private").unwrap(); + let meta = std::fs::symlink_metadata(dir.path()).unwrap(); + assert_eq!(meta.permissions().mode() & 0o777, 0o700); + let mine = dir.file("mine.txt").unwrap(); + std::fs::write(&mine, b"a").unwrap(); + assert_eq!(meta.uid(), std::fs::metadata(&mine).unwrap().uid()); + std::fs::remove_file(&mine).unwrap(); + assert_eq!(entries(dir.path()), 0, "the owner probe is removed"); + } + + #[cfg(unix)] + #[test] + fn created_folder_symlink_is_rejected() { + let root = TempDir::new("link-root").unwrap(); + let real = root.path().join("real"); + std::fs::create_dir(&real).unwrap(); + std::fs::write(real.join("theirs.txt"), b"theirs").unwrap(); + let made = tempfile::Builder::new().prefix("craft-testkit-link-").tempdir_in(root.path()).unwrap(); + let link = made.path().to_path_buf(); + std::fs::remove_dir(&link).unwrap(); + std::os::unix::fs::symlink(&real, &link).unwrap(); + assert!(TempDir::guard(made).is_err()); + assert!(std::fs::symlink_metadata(&link).unwrap().file_type().is_symlink(), "the link is left in place"); + assert_eq!(std::fs::read(real.join("theirs.txt")).unwrap(), b"theirs"); + assert_eq!(entries(&real), 1, "no probe was made through the link"); + } + + #[cfg(unix)] + #[test] + fn temp_root_reached_through_symlink_works() { + let root = TempDir::new("symlink-root").unwrap(); + let real = root.path().join("real"); + std::fs::create_dir(&real).unwrap(); + let link = root.path().join("link"); + std::os::unix::fs::symlink(&real, &link).unwrap(); + let dir = TempDir::new_in("through-link", &link, RANDOM_CHARS).unwrap(); + assert_eq!(dir.path().parent(), Some(real.as_path()), "the path is canonical"); + assert!(dir.path().is_dir()); + let path = dir.path().to_path_buf(); + let other = root.path().join("other"); + std::fs::create_dir_all(other.join(path.file_name().unwrap())).unwrap(); + std::fs::remove_file(&link).unwrap(); + std::os::unix::fs::symlink(&other, &link).unwrap(); + drop(dir); + assert!(!path.exists(), "the folder that was made is removed after the link changes"); + assert!(other.join(path.file_name().unwrap()).is_dir(), "a folder with the same name under the new target stays"); + assert!(real.is_dir() && link.is_symlink(), "the root and the link stay"); + } + + #[cfg(unix)] + #[test] + fn drop_does_not_follow_inner_symlink() { + let root = TempDir::new("inner-link-root").unwrap(); + let outside = root.path().join("outside"); + std::fs::create_dir(&outside).unwrap(); + std::fs::write(outside.join("keep.txt"), b"keep").unwrap(); + let dir = TempDir::new_in("inner-link", root.path(), RANDOM_CHARS).unwrap(); + std::os::unix::fs::symlink(&outside, dir.file("link").unwrap()).unwrap(); + let path = dir.path().to_path_buf(); + drop(dir); + assert!(!path.exists()); + assert_eq!(std::fs::read(outside.join("keep.txt")).unwrap(), b"keep"); + } +} diff --git a/crates/testkit/tests/it/main.rs b/crates/testkit/tests/it/main.rs index 6d0f5f8080..6a19688a73 100644 --- a/crates/testkit/tests/it/main.rs +++ b/crates/testkit/tests/it/main.rs @@ -2,4 +2,6 @@ mod fonts; mod guards; +#[cfg(feature = "prop")] +mod prop; mod source_limits; diff --git a/crates/testkit/tests/it/prop.rs b/crates/testkit/tests/it/prop.rs new file mode 100644 index 0000000000..bb2435218c --- /dev/null +++ b/crates/testkit/tests/it/prop.rs @@ -0,0 +1,177 @@ +//! Each test runs this test binary again as a child with the `PROPTEST_*` variables it needs, so no +//! test changes the environment of the process that runs it. The child runs `child_reports_config`, +//! which prints one `PROPCFG` line describing `config(7)` unless the caller's count is zero. + +#![cfg(not(target_arch = "wasm32"))] + +use std::process::{Command, Output}; + +use craft_testkit::prop::{SEED, config}; +use proptest::prelude::any; +use proptest::strategy::{Strategy, ValueTree}; +use proptest::test_runner::TestRunner; + +/// Set in a child's environment so that `child_reports_config` prints its line. +const CHILD: &str = "CRAFT_TESTKIT_PROP_CHILD"; + +/// The default case count a child passes to `config`. +const CASES: u32 = 7; + +/// Variables removed from every child's environment before a test sets its own. +const PROPTEST_VARS: [&str; 4] = ["PROPTEST_CASES", "PROPTEST_RNG_SEED", "PROPTEST_RNG_ALGORITHM", "PROPTEST_DISABLE_FAILURE_PERSISTENCE"]; + +#[test] +fn child_reports_config() { + if std::env::var_os(CHILD).is_none() { + return; + } + let cases = if std::env::var(CHILD).as_deref() == Ok("zero") { 0 } else { CASES }; + let c = config(cases); + let line = format!("cases={} seed={} persistence={}", c.cases, c.rng_seed, c.failure_persistence.is_some()); + let mut runner = TestRunner::new(c); + let draws: Vec = (0..4).map(|_| any::().new_tree(&mut runner).expect("draw a value").current().to_string()).collect(); + println!("PROPCFG {line} draws={}", draws.join(",")); +} + +/// The fields of one child's `PROPCFG` line. +#[derive(Debug, PartialEq)] +struct Report { + cases: String, + seed: String, + persistence: String, + draws: String, +} + +fn spawn_child(vars: &[(&str, &str)]) -> Output { + let exe = std::env::current_exe().expect("locate the test binary"); + let mut cmd = Command::new(exe); + cmd.args(["--exact", "prop::child_reports_config", "--nocapture", "--test-threads=1"]).env(CHILD, "1"); + for var in PROPTEST_VARS { + cmd.env_remove(var); + } + for (name, value) in vars { + cmd.env(name, value); + } + cmd.output().expect("run the child test") +} + +/// Runs a child that `config` must reject, and returns its stderr. +fn rejected_child(vars: &[(&str, &str)]) -> String { + let out = spawn_child(vars); + let stdout = String::from_utf8_lossy(&out.stdout); + let stderr = String::from_utf8_lossy(&out.stderr).into_owned(); + assert!(!out.status.success(), "child passed with {vars:?}\nstdout:\n{stdout}\nstderr:\n{stderr}"); + assert!(!stdout.contains("PROPCFG "), "child printed a config with {vars:?}\nstdout:\n{stdout}"); + stderr +} + +fn run_child(vars: &[(&str, &str)]) -> Report { + let out = spawn_child(vars); + let stdout = String::from_utf8_lossy(&out.stdout); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(out.status.success(), "child failed with {vars:?}\nstdout:\n{stdout}\nstderr:\n{stderr}"); + let line = stdout + .lines() + .find_map(|l| l.split_once("PROPCFG ").map(|(_, rest)| rest)) + .unwrap_or_else(|| panic!("no PROPCFG line with {vars:?}\nstdout:\n{stdout}\nstderr:\n{stderr}")); + let field = |name: &str| { + line.split(' ') + .find_map(|part| part.strip_prefix(name).and_then(|rest| rest.strip_prefix('='))) + .unwrap_or_else(|| panic!("no {name} in {line:?}")) + .to_string() + }; + Report { cases: field("cases"), seed: field("seed"), persistence: field("persistence"), draws: field("draws") } +} + +#[test] +fn without_variables_the_caller_count_and_pinned_seed_apply() { + let r = run_child(&[]); + assert_eq!(r.cases, CASES.to_string()); + assert_eq!(r.seed, SEED.to_string()); + assert_eq!(r.persistence, "false"); +} + +#[test] +fn without_variables_every_run_draws_the_same_values() { + let first = run_child(&[]); + let second = run_child(&[]); + assert_eq!(first.draws, second.draws); +} + +#[test] +fn proptest_cases_replaces_the_caller_count() { + let r = run_child(&[("PROPTEST_CASES", "19")]); + assert_eq!(r.cases, "19"); + assert_eq!(r.seed, SEED.to_string()); + assert_eq!(r.persistence, "false"); +} + +#[test] +fn proptest_rng_seed_replaces_the_pinned_seed() { + let pinned = run_child(&[]); + let r = run_child(&[("PROPTEST_RNG_SEED", "12345")]); + assert_eq!(r.cases, CASES.to_string()); + assert_eq!(r.seed, "12345"); + assert_eq!(r.persistence, "false"); + assert_ne!(r.draws, pinned.draws); + assert_eq!(run_child(&[("PROPTEST_RNG_SEED", "12345")]).draws, r.draws); +} + +#[test] +fn both_variables_apply_together() { + let r = run_child(&[("PROPTEST_CASES", "19"), ("PROPTEST_RNG_SEED", "12345")]); + assert_eq!(r.cases, "19"); + assert_eq!(r.seed, "12345"); + assert_eq!(r.persistence, "false"); +} + +#[test] +fn a_zero_caller_count_is_rejected() { + let stderr = rejected_child(&[(CHILD, "zero")]); + assert!(stderr.contains("the caller's case count is zero: config(0)"), "stderr:\n{stderr}"); +} + +#[test] +fn a_zero_environment_case_count_is_rejected() { + let stderr = rejected_child(&[("PROPTEST_CASES", "0")]); + assert!(stderr.contains("PROPTEST_CASES=\"0\" must be greater than zero"), "stderr:\n{stderr}"); +} + +#[test] +fn an_unparsable_case_count_is_rejected() { + for value in ["many", "", "-1", "4294967296"] { + let stderr = rejected_child(&[("PROPTEST_CASES", value)]); + assert!(stderr.contains(&format!("PROPTEST_CASES={value:?} is not a u32")), "PROPTEST_CASES={value:?}\nstderr:\n{stderr}"); + } +} + +#[test] +fn an_unparsable_seed_is_rejected() { + for value in ["random", "", "-1", "18446744073709551616"] { + let stderr = rejected_child(&[("PROPTEST_RNG_SEED", value)]); + assert!(stderr.contains(&format!("PROPTEST_RNG_SEED={value:?} is not a u64")), "PROPTEST_RNG_SEED={value:?}\nstderr:\n{stderr}"); + } +} + +#[test] +fn the_pass_through_generator_is_rejected() { + let stderr = rejected_child(&[("PROPTEST_RNG_ALGORITHM", "pt")]); + assert!(stderr.contains("PROPTEST_RNG_ALGORITHM=\"pt\" is not supported"), "stderr:\n{stderr}"); +} + +#[test] +fn an_unknown_generator_is_rejected() { + for value in ["xx", "", "CC", " cc"] { + let stderr = rejected_child(&[("PROPTEST_RNG_ALGORITHM", value)]); + assert!(stderr.contains(&format!("PROPTEST_RNG_ALGORITHM={value:?} is not a supported RNG algorithm")), "stderr:\n{stderr}"); + } +} + +#[test] +fn the_xorshift_generator_is_kept() { + let default = run_child(&[]); + let r = run_child(&[("PROPTEST_RNG_ALGORITHM", "xs")]); + assert_eq!(r.seed, SEED.to_string()); + assert_ne!(r.draws, default.draws); + assert_eq!(run_child(&[("PROPTEST_RNG_ALGORITHM", "xs")]).draws, r.draws); +} diff --git a/crates/testkit/tests/log_foreign.rs b/crates/testkit/tests/log_foreign.rs new file mode 100644 index 0000000000..24650a83a0 --- /dev/null +++ b/crates/testkit/tests/log_foreign.rs @@ -0,0 +1,33 @@ +//! Capture in a process where another logger was installed first. +#![cfg(not(target_arch = "wasm32"))] + +use craft_testkit::log::{CaptureError, capture_global, records, warnings}; +use log::{LevelFilter, Log, Metadata, Record}; + +struct Foreign; + +impl Log for Foreign { + fn enabled(&self, _: &Metadata) -> bool { + true + } + + fn log(&self, _: &Record) {} + + fn flush(&self) {} +} + +static FOREIGN: Foreign = Foreign; + +#[test] +fn every_capture_is_refused_and_nothing_changes() { + // The first call installs the foreign logger; this is the only test in the binary. + log::set_logger(&FOREIGN).expect("install the foreign logger"); + log::set_max_level(LevelFilter::Error); + + let mut ran = false; + assert_eq!(warnings(|| ran = true).map(|_| ()), Err(CaptureError::LoggerAlreadySet)); + assert_eq!(records(LevelFilter::Trace, || ran = true).map(|_| ()), Err(CaptureError::LoggerAlreadySet)); + assert_eq!(capture_global(LevelFilter::Trace).map(|_| ()), Err(CaptureError::LoggerAlreadySet)); + assert!(!ran, "a refused capture must not run its closure"); + assert_eq!(log::max_level(), LevelFilter::Error); +} diff --git a/crates/testkit/tests/log_global.rs b/crates/testkit/tests/log_global.rs new file mode 100644 index 0000000000..4345c2a2ce --- /dev/null +++ b/crates/testkit/tests/log_global.rs @@ -0,0 +1,123 @@ +//! Process-wide capture, in a binary without the test harness so the cases run one after another +//! on the main thread, as a `harness = false` consumer runs them. The process captures process +//! wide from the first case on. The module is native only, so on `wasm32` the binary runs nothing. + +fn main() { + // nextest lists custom-harness tests with `--list`; this binary is one test. + if std::env::args().any(|a| a == "--list") { + println!("log_global: test"); + return; + } + #[cfg(not(target_arch = "wasm32"))] + cases::run(); +} + +#[cfg(not(target_arch = "wasm32"))] +mod cases { + use std::fmt; + use std::sync::mpsc::{self, Receiver, Sender}; + + use craft_testkit::log::{CaptureError, CapturedRecord, MAX_RECORDS, capture_global, records, warnings}; + use log::{Level, LevelFilter}; + + pub fn run() { + a_record_from_another_thread_is_drained(); + the_level_filters_and_a_drain_empties_the_capture(); + a_second_live_capture_is_refused_and_a_new_one_starts_after_drop(); + a_record_checked_against_one_capture_is_not_kept_by_the_next(); + an_undrained_capture_reports_what_it_dropped(); + a_capture_does_not_lower_a_raised_maximum_level(); + per_thread_captures_are_refused_in_a_process_wide_process(); + println!("log_global: 7 cases passed"); + } + + fn a_record_from_another_thread_is_drained() { + let capture = capture_global(LevelFilter::Warn).expect("capture"); + std::thread::Builder::new() + .name("audio".into()) + .spawn(|| log::warn!(target: "clap_host", "editor dropped off the main thread")) + .expect("spawn") + .join() + .expect("join"); + assert_eq!( + capture.drain().expect("drain"), + [CapturedRecord { level: Level::Warn, target: "clap_host".into(), message: "editor dropped off the main thread".into() }] + ); + } + + fn the_level_filters_and_a_drain_empties_the_capture() { + let capture = capture_global(LevelFilter::Info).expect("capture"); + log::debug!("below info"); + log::info!("info"); + log::error!("error"); + let messages: Vec = capture.drain().expect("drain").into_iter().map(|r| r.message).collect(); + assert_eq!(messages, ["info", "error"]); + assert!(capture.drain().expect("second drain").is_empty()); + } + + fn a_second_live_capture_is_refused_and_a_new_one_starts_after_drop() { + let first = capture_global(LevelFilter::Warn).expect("capture"); + log::warn!("held by the first capture"); + assert_eq!(capture_global(LevelFilter::Warn).map(|_| ()), Err(CaptureError::GlobalCaptureActive)); + drop(first); + log::warn!("between captures"); + let second = capture_global(LevelFilter::Warn).expect("a new capture after drop"); + log::warn!("held by the second capture"); + let messages: Vec = second.drain().expect("drain").into_iter().map(|r| r.message).collect(); + assert_eq!(messages, ["held by the second capture"]); + } + + /// Signals on `started` when formatting begins, then waits on `go` before writing its text. + struct Gate { + started: Sender<()>, + go: Receiver<()>, + } + + impl fmt::Display for Gate { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.started.send(()).expect("signal the start"); + self.go.recv().expect("wait for go"); + f.write_str("checked against the first capture") + } + } + + fn a_record_checked_against_one_capture_is_not_kept_by_the_next() { + let first = capture_global(LevelFilter::Warn).expect("capture"); + let (started_tx, started_rx) = mpsc::channel(); + let (go_tx, go_rx) = mpsc::channel(); + let gate = Gate { started: started_tx, go: go_rx }; + let logger = std::thread::spawn(move || log::warn!("{gate}")); + started_rx.recv().expect("formatting started"); + drop(first); + let second = capture_global(LevelFilter::Warn).expect("a new capture"); + go_tx.send(()).expect("release the formatter"); + logger.join().expect("join"); + assert!(second.drain().expect("drain").is_empty()); + } + + fn an_undrained_capture_reports_what_it_dropped() { + let capture = capture_global(LevelFilter::Warn).expect("capture"); + for i in 0..MAX_RECORDS + 2 { + log::warn!("{i}"); + } + assert_eq!(capture.drain(), Err(CaptureError::Overflow { dropped: 2 })); + log::warn!("after the overflow"); + let messages: Vec = capture.drain().expect("drain after an overflow").into_iter().map(|r| r.message).collect(); + assert_eq!(messages, ["after the overflow"]); + } + + fn a_capture_does_not_lower_a_raised_maximum_level() { + log::set_max_level(LevelFilter::Trace); + let capture = capture_global(LevelFilter::Warn).expect("capture"); + log::info!("below warn"); + assert_eq!(log::max_level(), LevelFilter::Trace); + assert!(capture.drain().expect("drain").is_empty()); + } + + fn per_thread_captures_are_refused_in_a_process_wide_process() { + let mut ran = false; + assert_eq!(warnings(|| ran = true).map(|_| ()), Err(CaptureError::ModeConflict)); + assert_eq!(records(LevelFilter::Trace, || ran = true).map(|_| ()), Err(CaptureError::ModeConflict)); + assert!(!ran, "a refused capture must not run its closure"); + } +} diff --git a/crates/testkit/tests/log_thread.rs b/crates/testkit/tests/log_thread.rs new file mode 100644 index 0000000000..9c472f806d --- /dev/null +++ b/crates/testkit/tests/log_thread.rs @@ -0,0 +1,141 @@ +//! Per-thread capture. Every test in this binary captures per thread, so the logger runs in that +//! mode for the whole process. +#![cfg(not(target_arch = "wasm32"))] + +use std::fmt; +use std::panic::{AssertUnwindSafe, catch_unwind}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + +use craft_testkit::log::{CaptureError, CapturedRecord, MAX_BYTES, MAX_RECORDS, capture_global, records, warnings}; +use log::{Level, LevelFilter}; + +#[test] +fn warnings_returns_the_result_and_the_warnings_and_errors() { + let (out, lines) = warnings(|| { + log::info!("not a warning"); + log::warn!("kept {} of {}", 3, 4); + log::error!("an error"); + log::debug!("not a warning either"); + 7 + }) + .expect("capture"); + assert_eq!(out, 7); + assert_eq!(lines, ["kept 3 of 4", "an error"]); +} + +#[test] +fn records_keep_level_and_target_at_the_requested_level() { + let ((), got) = records(LevelFilter::Info, || { + log::info!(target: "craft::test", "opened"); + log::debug!("dropped"); + log::warn!("short"); + }) + .expect("capture"); + assert_eq!( + got, + [ + CapturedRecord { level: Level::Info, target: "craft::test".into(), message: "opened".into() }, + CapturedRecord { level: Level::Warn, target: module_path!().into(), message: "short".into() }, + ] + ); +} + +// No test in this binary raises the maximum level above `Info`, so the nested-capture test can +// check that a refused `Trace` capture leaves it below `Trace`. + +#[test] +fn a_capture_does_not_lower_a_raised_maximum_level() { + log::set_max_level(LevelFilter::Info); + let ((), lines) = warnings(|| log::info!("below warn")).expect("capture"); + assert!(lines.is_empty()); + assert_eq!(log::max_level(), LevelFilter::Info); +} + +#[test] +fn a_nested_capture_is_refused_and_the_outer_one_keeps_its_records() { + let ran = AtomicBool::new(false); + let (inner, lines) = warnings(|| { + log::warn!("before"); + let inner = warnings(|| ran.store(true, Ordering::SeqCst)); + let deeper = records(LevelFilter::Trace, || ran.store(true, Ordering::SeqCst)); + log::warn!("after"); + (inner.map(|_| ()), deeper.map(|_| ())) + }) + .expect("outer capture"); + assert_eq!(inner, (Err(CaptureError::NestedCapture), Err(CaptureError::NestedCapture))); + assert!(!ran.load(Ordering::SeqCst), "a nested closure must not run"); + assert!(log::max_level() < LevelFilter::Trace, "a refused capture must not raise the maximum level"); + assert_eq!(lines, ["before", "after"]); +} + +#[test] +fn a_panic_ends_the_capture_and_the_next_one_starts_empty() { + let caught = catch_unwind(AssertUnwindSafe(|| { + warnings(|| { + log::warn!("left behind"); + panic!("closure failed"); + }) + })); + assert!(caught.is_err()); + let ((), lines) = warnings(|| log::warn!("next")).expect("a new capture after the panic"); + assert_eq!(lines, ["next"]); +} + +#[test] +fn records_from_other_threads_are_not_captured() { + let ((), lines) = warnings(|| { + std::thread::spawn(|| log::warn!("elsewhere")).join().expect("join"); + log::warn!("here"); + }) + .expect("capture"); + assert_eq!(lines, ["here"]); +} + +#[test] +fn records_over_the_count_limit_are_reported() { + let got = warnings(|| { + for i in 0..=MAX_RECORDS { + log::warn!("{i}"); + } + }); + assert_eq!(got.map(|_| ()), Err(CaptureError::Overflow { dropped: 1 })); + let ((), lines) = warnings(|| log::warn!("fits")).expect("a new capture after an overflow"); + assert_eq!(lines, ["fits"]); +} + +#[test] +fn a_message_over_the_byte_limit_is_reported() { + let long = "x".repeat(MAX_BYTES); + let got = warnings(|| { + log::warn!("short"); + log::warn!("{long}"); + }); + assert_eq!(got.map(|_| ()), Err(CaptureError::Overflow { dropped: 1 })); +} + +/// Writes one byte at a time until a write fails, counting the writes that succeed. +struct Endless<'a>(&'a AtomicUsize); + +impl fmt::Display for Endless<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + for _ in 0..2 * MAX_BYTES { + f.write_str("x")?; + self.0.fetch_add(1, Ordering::SeqCst); + } + Ok(()) + } +} + +#[test] +fn formatting_a_message_stops_at_the_byte_limit() { + let written = AtomicUsize::new(0); + let got = warnings(|| log::warn!("{}", Endless(&written))); + assert_eq!(got.map(|_| ()), Err(CaptureError::Overflow { dropped: 1 })); + assert_eq!(written.load(Ordering::SeqCst), MAX_BYTES); +} + +#[test] +fn a_global_capture_is_refused_in_a_per_thread_process() { + warnings(|| ()).expect("per-thread capture installs the logger"); + assert_eq!(capture_global(LevelFilter::Warn).map(|_| ()), Err(CaptureError::ModeConflict)); +} diff --git a/crates/text/src/ui/character.rs b/crates/text/src/ui/character.rs index 3caf14d2f2..ddc879ff40 100644 --- a/crates/text/src/ui/character.rs +++ b/crates/text/src/ui/character.rs @@ -94,6 +94,7 @@ craft_ui::words! { titling_alternates: "character.titlingAlternates" = "Titling Alternates"; ordinals: "character.ordinals" = "Ordinals"; fractions: "character.fractions" = "Fractions"; + digits: "character.digits" = "Digits"; language: "character.language" = "Language"; rotation: "character.rotation" = "Rotation"; anti_alias: "character.antiAlias" = "Anti-aliasing"; @@ -646,6 +647,8 @@ pub struct CharacterValues { pub strikethrough: Option, /// The [`OPENTYPE_FEATURES`] that are on, by tag. pub opentype: Vec<&'static str>, + /// The app's tag for the digits the text is drawn with (see [`CharacterControls::digits`]). + pub digits: Option, /// BCP 47 tag of the text's language (hyphenation, spelling, smart quotes). pub language: Option, /// The variable-font axis values of the selection, by axis tag; `None` while the selection has no variable axes. @@ -725,6 +728,7 @@ impl CharacterValues { underline: agree(&self.underline, &other.underline), strikethrough: agree(&self.strikethrough, &other.strikethrough), opentype: self.opentype.iter().copied().filter(|tag| other.opentype.contains(tag)).collect(), + digits: agree(&self.digits, &other.digits), language: agree(&self.language, &other.language), axes, mixed_axes, @@ -784,6 +788,8 @@ pub enum CharacterChange { /// On. on: bool, }, + /// The digits, by the app's tag. + Digits(String), /// Language. Language(String), /// The variable-font axis values, by axis tag. @@ -842,7 +848,8 @@ impl Outcome for CharacterControlsOutput { /// The Character panel's controls, in Photoshop's rows: family; style; size and leading; kerning and tracking; /// vertical and horizontal scale; baseline shift ([`CharacterRows::BASELINE`]) and colour; the style toggles /// ([`CharacterRows::STYLE_TOGGLES`]: Faux Bold, Faux Italic, All Caps, Small Caps, then Superscript and Subscript with -/// [`CharacterRows::SUPERSCRIPT`], Underline, Strikethrough); the OpenType buttons; the language when +/// [`CharacterRows::SUPERSCRIPT`], Underline, Strikethrough); the OpenType buttons; the digits when +/// [`digits`](Self::digits) is given; the language when /// [`languages`](Self::languages) is given. [`rows`](Self::rows) turns these and the other groups (rotation, /// anti-aliasing, font height reference, East Asian and Middle Eastern fields) on or off; /// [`CharacterRows::PROPERTIES`] keeps family, style, the axes, size, leading, kerning and tracking. @@ -877,6 +884,10 @@ pub struct CharacterControls<'a> { /// Shows the Superscript and Subscript toggles (Photoshop; off by default, PhotoCraft has no superscript). #[prop] superscript: bool, + /// Shows the Digits select over the app's `(tag, name)` pairs, above the language: which digits the text's 0–9 + /// are drawn with (Western, Indic, Arabic, …). Which styles exist is the app's choice. + #[prop] + digits: Option<&'a [(String, String)]>, /// Shows the Language select over `(tag, name)` pairs (Photoshop's bottom row). #[prop] languages: Option<&'a [(String, String)]>, @@ -911,6 +922,7 @@ impl<'a> CharacterControls<'a> { styles, unit: DocUnit::points(), superscript: false, + digits: None, languages: None, #[cfg(feature = "font-picker")] picker: None, @@ -953,6 +965,7 @@ impl<'a> CharacterControls<'a> { .collect(); let style_entries = string_entries(styles.iter().map(|name| (name.clone(), name.clone()))); + let digit_entries = self.digits.map(|digits| string_entries(digits.iter().cloned())); let language_entries = languages.map(|languages| string_entries(languages.iter().cloned())); let kerning_shown = values.kerning.map(|kerning| match kerning { @@ -1220,6 +1233,17 @@ impl<'a> CharacterControls<'a> { edits.extend(toggle_row(ui, None, &features)); } + if let Some(entries) = &digit_entries { + edits.extend(select_row( + ui, + &words.digits, + hidden_side(), + mixed(values.digits.clone()), + entries, + Some(Sizing::FillWidth), + CharacterChange::Digits, + )); + } if let Some(entries) = &language_entries { edits.extend(select_row( ui, diff --git a/crates/text/src/ui/character/stories.rs b/crates/text/src/ui/character/stories.rs index f55727809d..89041d8963 100644 --- a/crates/text/src/ui/character/stories.rs +++ b/crates/text/src/ui/character/stories.rs @@ -28,6 +28,12 @@ fn languages() -> Vec<(String, String)> { [("en-US", "English: USA"), ("fr-FR", "French"), ("de-DE", "German")].map(|(tag, name)| (tag.to_owned(), name.to_owned())).to_vec() } +fn digits() -> Vec<(String, String)> { + [("asTyped", "As Typed"), ("western", "Western"), ("devanagari", "Devanagari"), ("gujarati", "Gujarati")] + .map(|(tag, name)| (tag.to_owned(), name.to_owned())) + .to_vec() +} + /// The values every row story starts from. fn single() -> CharacterValues { CharacterValues { @@ -48,6 +54,7 @@ fn single() -> CharacterValues { underline: Some(true), strikethrough: Some(false), opentype: vec!["liga", "frac"], + digits: Some("devanagari".to_owned()), language: Some("en-US".to_owned()), ..CharacterValues::default() } @@ -56,9 +63,10 @@ fn single() -> CharacterValues { #[story(CharacterControls<'static>, covers = [], drive = Drive::Never)] fn single_values(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { let values = single(); - let (families, styles, languages) = (families(), styles(), languages()); + let (families, styles, languages, digits) = (families(), styles(), languages(), digits()); CharacterControls::new("Character", &values, &families, &styles) .rows(CharacterRows::default() | CharacterRows::SUPERSCRIPT) + .digits(&digits) .languages(&languages) .show(ui) .into() diff --git a/crates/text/src/ui/spelling.rs b/crates/text/src/ui/spelling.rs index 7f44d20e97..28d6051d3b 100644 --- a/crates/text/src/ui/spelling.rs +++ b/crates/text/src/ui/spelling.rs @@ -207,9 +207,10 @@ pub enum SpellingScope { /// "Spell check complete." once the list is empty; at the right, a column of Done and the buttons Ignore, Ignore All, /// Change, Change All and Add, which are disabled when the list is empty. /// -/// - A click on a suggestion puts it in Change To; a double click or Enter also changes. -/// - Enter is Done unless Change To has focus; Escape and the close action are Done too (nothing to undo: every -/// change was made as it was asked for). Tab walks Change To, the suggestions (one stop, arrows inside), the check +/// - A click on a suggestion puts it in Change To; a double click or Enter on the list also changes. +/// - Done is the default button: Enter runs it, also from Change To (where it does not change the word), and a +/// focused button keeps its own Enter. Escape and the close action are Done too (nothing to undo: every change was +/// made as it was asked for). Tab walks Change To, the suggestions (one stop, arrows inside), the check /// box and the buttons. /// - Result: `()`; every close from inside (Done, Escape, the close action, automation's confirm) is /// [`DialogResult::Ok`], and a close from outside is `Cancel`. @@ -362,7 +363,8 @@ impl CheckSpellingDialog { let enabled = has_item && (!repeated || !matches!(press, Press::ChangeAll | Press::Add)); FooterButton::new((*label).clone(), DialogRole::Other).stays_open(true).enabled(enabled) })); - let mut dialog = Dialog::new(words.title.clone()).button_place(ButtonPlace::Side).buttons(buttons).opened(Bind::bound(open)); + let mut dialog = + Dialog::new(words.title.clone()).button_place(ButtonPlace::Side).buttons(buttons).close_on_enter(true).opened(Bind::bound(open)); if *modeless { dialog = dialog.modeless(); } diff --git a/crates/text/tests/it/character.rs b/crates/text/tests/it/character.rs index 8671198e28..cf7bf67a4c 100644 --- a/crates/text/tests/it/character.rs +++ b/crates/text/tests/it/character.rs @@ -108,3 +108,35 @@ fn character_fields_line_up_in_their_columns_at_every_width_and_text_size() { } } } + +/// The Digits select shows only for an app that passes its digit styles, and a pick reports the app's tag. +#[trial] +fn the_digits_select_reports_the_picked_tag() { + use std::cell::RefCell; + use std::rc::Rc; + + use craft_text::ui::character::CharacterChange; + + let values = CharacterValues { digits: Some("western".to_owned()), ..CharacterValues::default() }; + let plain = values.clone(); + let shown = Fixture::new(move |ui| { + CharacterControls::new("Character", &plain, &[], &[]).show(ui); + }); + assert!(shown.by_label("Digits").is_none(), "no Digits row without the app's styles"); + + let digits: Vec<(String, String)> = [("western", "Western"), ("devanagari", "Devanagari")].map(|(t, n)| (t.to_owned(), n.to_owned())).to_vec(); + let edits = Rc::new(RefCell::new(Vec::new())); + let sink = edits.clone(); + let picking = values; + let mut fixture = Fixture::new(move |ui| { + let out = CharacterControls::new("Character", &picking, &[], &[]).digits(&digits).show(ui); + sink.borrow_mut().extend(out.edits); + }); + fixture.idle(10); + let select = fixture.by_label("Digits").expect("the Digits row is shown"); + fixture.click(&select).idle(10); + let entry = fixture.by_label("Devanagari").expect("the app's styles are offered"); + fixture.click(&entry).idle(10); + let picked: Vec = edits.borrow().iter().filter_map(|e| e.value().cloned()).collect(); + assert_eq!(picked, vec![CharacterChange::Digits("devanagari".to_owned())]); +} diff --git a/crates/text/tests/it/spelling.rs b/crates/text/tests/it/spelling.rs index 0bee60e0e3..8b1df16049 100644 --- a/crates/text/tests/it/spelling.rs +++ b/crates/text/tests/it/spelling.rs @@ -1,12 +1,13 @@ -//! Check Spelling's Ignore and restart. +//! Check Spelling's Ignore and restart, and its keys: Enter and Escape are Done (#14179 in storytold/photocraft). -use std::cell::RefCell; +use std::cell::{Cell, RefCell}; use std::rc::Rc; use craft_text::ui::spelling::{CheckSpellingDialog, SpellingAction, SpellingItem}; use craft_ui::contract::Role; use craft_ui::dialog::StackDialog as _; use craft_ui::testing::{Fixture, trial}; +use egui::{Key, Modifiers}; use serde_json::json; fn items() -> Vec { @@ -56,3 +57,52 @@ fn restarting_drops_a_change_waiting_on_the_previous_word() { fixture.click(&change).settle(); assert_eq!(dialog.borrow_mut().take_action(), Some(SpellingAction::Change { item: next, to: "and".to_owned() })); } + +/// A fixture showing the dialog, with whether it has closed. +fn shown() -> (Fixture, Rc>, Rc>) { + let dialog = Rc::new(RefCell::new(CheckSpellingDialog::new(items()))); + let closed = Rc::new(Cell::new(false)); + let (shown, ended) = (dialog.clone(), closed.clone()); + let mut fixture = Fixture::new(move |ui| { + if shown.borrow_mut().show(ui).closed.is_some() { + ended.set(true); + } + }); + fixture.settle(); + (fixture, dialog, closed) +} + +/// Focuses Change To and types into it, so the keys after go to the field. +fn type_in_change_to(fixture: &mut Fixture, dialog: &Rc>) { + let field = fixture.by_label("Change To:").expect("the Change To field"); + fixture.click(&field).settle(); + fixture.type_text("x").settle(); + assert_eq!(dialog.borrow().json_fields().expect("fields")["changeTo"], json!("thex"), "Change To has the focus"); +} + +// Done is the default button: Enter in Change To closes the dialog and does not change the word. +#[trial] +fn enter_in_change_to_is_done_and_changes_nothing() { + let (mut fixture, dialog, closed) = shown(); + type_in_change_to(&mut fixture, &dialog); + fixture.key(Key::Enter, Modifiers::NONE).settle(); + assert!(closed.get(), "Enter in Change To closes the dialog"); + assert_eq!(dialog.borrow_mut().take_action(), None, "and does not change the word"); +} + +#[trial] +fn enter_with_nothing_focused_is_done() { + let (mut fixture, dialog, closed) = shown(); + fixture.key(Key::Enter, Modifiers::NONE).settle(); + assert!(closed.get(), "Enter closes the dialog"); + assert_eq!(dialog.borrow_mut().take_action(), None, "as Done, with no action"); +} + +#[trial] +fn escape_in_change_to_is_done() { + let (mut fixture, dialog, closed) = shown(); + type_in_change_to(&mut fixture, &dialog); + fixture.key(Key::Escape, Modifiers::NONE).settle(); + assert!(closed.get(), "Escape in Change To closes the dialog"); + assert_eq!(dialog.borrow_mut().take_action(), None, "with no action"); +} diff --git a/crates/ui-canvas/src/canvas/mod.rs b/crates/ui-canvas/src/canvas/mod.rs index 2e624791f3..60e7ed9314 100644 --- a/crates/ui-canvas/src/canvas/mod.rs +++ b/crates/ui-canvas/src/canvas/mod.rs @@ -313,6 +313,7 @@ struct Settled { keys: BodyKeys, /// The wheel share the canvas took this pass, handed on to its body. wheel: Option, + wheel_token: Option, /// A middle-button autoscroll or a held middle pan runs. auto_scrolling: bool, /// The mark of a running middle-button autoscroll, in screen points. @@ -501,7 +502,15 @@ impl<'a> Canvas<'a> { let mut zoom_anchor = None; let wheel = cx.take_wheel(); let wheeled = wheel.is_some(); - if let Some(wheel) = &wheel { + // A share of a gesture the body claimed (`CanvasSpace::claim_wheel`) goes to the body alone: the view stays, and + // the motion the eased wheel and the eased wheel zoom still owe is dropped. + if crate::runtime::wheel::claimed(&ctx, id) || wheel.as_ref().is_some_and(|wheel| wheel.claimed) { + motion.glide.stop(); + cx.stop_wheel_ease(); + motion.wheel_zoom.stop_if(true); + motion.wheel = WheelNavigation::default(); + } + if let Some(wheel) = wheel.as_ref().filter(|wheel| !wheel.claimed) { let read = self.read_wheel(cx, &mut motion, &mut view, wheel, now); line_pan = read.line_pan; jumped |= read.jumped; @@ -642,7 +651,8 @@ impl<'a> Canvas<'a> { let easing = motion.animation.running(); let mark = motion.autoscroll.mark(); motion.restore(&ctx, id); - Settled { target, shown, easing, zoomed, keys, wheel, auto_scrolling, mark, swallowing, zoom_anchor } + let wheel_token = crate::runtime::wheel::claim_token(&ctx, id); + Settled { target, shown, easing, zoomed, keys, wheel, wheel_token, auto_scrolling, mark, swallowing, zoom_anchor } } /// One pass's wheel on `view`: a pan the eased wheel pays out later, or a pan, zoom or turn applied now, and the @@ -802,6 +812,7 @@ impl<'a> Canvas<'a> { .with_precise(self.precise_cursors != caps_lock) .with_zoom_scheme(scheme) .with_wheel(wheel) + .with_wheel_token(self.settled.and_then(|settled| settled.wheel_token)) .with_canvas(id); Some(match self.picture { Some(slot) => space.with_picture(slot), diff --git a/crates/ui-canvas/src/canvas/navigate/mod.rs b/crates/ui-canvas/src/canvas/navigate/mod.rs index b5744689c5..504fe3ba63 100644 --- a/crates/ui-canvas/src/canvas/navigate/mod.rs +++ b/crates/ui-canvas/src/canvas/navigate/mod.rs @@ -165,6 +165,7 @@ impl TouchpadGlide { /// Stops a glide (the view hit a limit, a press, a key move, a zoom, a view command). pub(crate) fn stop(&mut self) { + self.samples.clear(); self.velocity = Vec2::ZERO; } @@ -206,7 +207,7 @@ impl TouchpadGlide { /// Reads the pass's wheel share at `now`; any wheel input stops a glide, a touchpad gesture's end may start one. /// `glide` is false where the view must not glide this pass (Touchpad Glide off, a zoom, a dialog). pub(crate) fn read(&mut self, wheel: &Wheel, now: f64, glide: bool) { - self.stop(); + self.velocity = Vec2::ZERO; // Zooming, a mouse wheel and sideways Shift scrolling never glide. if wheel.unit != WheelUnit::Point || wheel.mods.cmd || wheel.mods.ctrl || wheel.mods.shift || wheel.zoom != 1.0 { self.samples.clear(); @@ -328,3 +329,29 @@ fn document_bounds(view: &CanvasView, size: Size) -> Option { let bounds = quad.iter().skip(1).fold(Rect::from_min_max(quad[0], quad[0]), |r, &p| r.union(Rect::from_min_max(p, p))); (bounds.is_finite() && view.rect.is_finite()).then_some(bounds) } + +#[cfg(feature = "suite")] +pub(crate) mod trials { + use super::TouchpadGlide; + use crate::testing::trial; + use egui::Vec2; + + /// One sample of a touchpad swipe upward, in points: the glide's input, not a size of anything drawn. + const SWIPE: Vec2 = Vec2::new(0.0, -30.0); + + #[trial] + fn stopping_a_touchpad_glide_clears_its_lift_samples() { + let mut glide = TouchpadGlide::default(); + glide.push(0.0, SWIPE); + glide.push(0.01, SWIPE); + assert_ne!(glide.lift_velocity(0.02), Vec2::ZERO); + glide.velocity = glide.lift_velocity(0.02); + + glide.stop(); + + assert!(!glide.gliding()); + assert!(glide.samples.is_empty()); + glide.push(0.03, Vec2::new(0.0, -1.0)); + assert_eq!(glide.lift_velocity(0.04), Vec2::ZERO); + } +} diff --git a/crates/ui-canvas/src/canvas/space.rs b/crates/ui-canvas/src/canvas/space.rs index 4e2a6a09f4..6d70d58f5d 100644 --- a/crates/ui-canvas/src/canvas/space.rs +++ b/crates/ui-canvas/src/canvas/space.rs @@ -42,7 +42,7 @@ pub struct CanvasSpace { /// The canvas's picture slot for this pass, which [`paint_picture`](Self::paint_picture) appends to; `None` in a /// measuring pass. picture: Option, - wheel: Option, + wheel: Option<(craft_behavior::Wheel, Option)>, zoom_anchor: Option, } @@ -73,13 +73,21 @@ impl CanvasSpace { /// The wheel share the canvas read this pass, for a body that pages by wheel to read once. pub fn wheel(&self) -> Option { - self.wheel + self.wheel.map(|(wheel, _)| wheel) } - /// This space with the wheel share the canvas read this pass. + /// This space with the wheel share the canvas read. #[must_use] pub fn with_wheel(mut self, wheel: Option) -> Self { - self.wheel = wheel; + self.wheel = wheel.map(|wheel| (wheel, None)); + self + } + + #[must_use] + pub(crate) fn with_wheel_token(mut self, token: Option) -> Self { + if let Some((_, claim)) = self.wheel.as_mut() { + *claim = token; + } self } @@ -308,6 +316,29 @@ impl CanvasSpace { nudge } + /// Claims this pass's wheel share ([`wheel`](Self::wheel)) for the canvas's body, recording `spent`, the part of + /// the claimed motion the body used up, in its own unit, and returning whether the claim succeeded. The gesture's + /// later shares carry `Wheel::claimed` and count only the claimed shares in `claimed_gathered`, + /// `claimed_zoom_gathered` and `claimed_spent`, so a body that turns a gesture into steps keeps no state of its + /// own. A second claim in the same pass replaces the first. + /// The canvas must own the gesture and have a share in the running pass. A share returned by `wheel` can belong + /// to a gesture another scroller owns; that share cannot be claimed. A snapshot from another share cannot claim the + /// running pass's share, including after a viewport is recreated. The body should act only on an accepted claim. + pub fn claim_wheel(&self, ctx: &egui::Context, spent: Vec2) -> bool { + if let (Some(canvas), Some((_, Some(token)))) = (self.canvas, self.wheel) { + return crate::runtime::wheel::claim(ctx, canvas, token, spent); + } + false + } + + /// Marks the running wheel gesture as begun or gone on under a modal, for one of the app's own modal windows that + /// the wheel service does not see. The gesture's later shares carry `Wheel::modal` until it ends. + pub fn mark_wheel_modal(&self, ctx: &egui::Context) { + if let Some(canvas) = self.canvas { + crate::runtime::wheel::mark_modal(ctx, canvas); + } + } + /// Device pixels per document unit (1 is 100 %) of the view at this scale. pub fn zoom_device(&self) -> f64 { zoom::device(&self.view, self.pixels_per_point) diff --git a/crates/ui-canvas/src/canvas/tools.rs b/crates/ui-canvas/src/canvas/tools.rs index 25ec57368a..618e0b474f 100644 --- a/crates/ui-canvas/src/canvas/tools.rs +++ b/crates/ui-canvas/src/canvas/tools.rs @@ -12,6 +12,7 @@ use super::rotate::ViewTurn; use super::zoom_motion::{HoldZoom, ZoomDrag}; use super::{CanvasTool, CanvasWords, ToolAction, ToolContext, ToolKey, ToolPath, ToolPointer}; use crate::primitives::Draw; +use crate::runtime::env::Label; use craft_behavior::PointerButton; use craft_behavior::canvas::zoom; use craft_behavior::geometry::crop::normalized_angle; @@ -570,6 +571,24 @@ impl ZoomTool { cx.set_view(view); } } + + /// The zoom rectangle's width and height in document pixels beside the pointer, as the marquee shows its size + /// (Scrubby Zoom off). The sides are measured along the screen, so a turned view reads them as drawn. A press held + /// still that zooms has no rectangle to size. + fn show_readout(&self, cx: &mut ToolContext<'_>) { + if self.hold.is_some() { + return; + } + let (Some(rect), Some(space)) = (self.drag.as_ref().and_then(ZoomDrag::rect), cx.space()) else { return }; + let view = space.view; + let side = |to: Pos2| (view.to_doc(to) - view.to_doc(rect.left_top())).hypot().round(); + let (w, h) = (side(rect.right_top()), side(rect.left_bottom())); + let (words, units) = (cx.words::(), cx.units()); + cx.readout(vec![ + (Label::from(words.crop_width.as_str().to_owned()), units.pixels(w)), + (Label::from(words.crop_height.as_str().to_owned()), units.pixels(h)), + ]); + } } /// The view after a Zoom tool click at `screen`: one rung of `scheme` in (or `out`) about the point, or centred on it @@ -636,6 +655,7 @@ impl CanvasTool for ZoomTool { self.hold = None; } self.advance(pointer.pos, pointer.mods, pointer.time, cx); + self.show_readout(cx); } fn release(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) { diff --git a/crates/ui-canvas/tests/it/canvas/modal_wheel.rs b/crates/ui-canvas/tests/it/canvas/modal_wheel.rs index 314fe1eeb2..a6e7b64038 100644 --- a/crates/ui-canvas/tests/it/canvas/modal_wheel.rs +++ b/crates/ui-canvas/tests/it/canvas/modal_wheel.rs @@ -2,12 +2,12 @@ use craft_behavior::CanvasView; use craft_behavior::kurbo::{Point, Size}; -use craft_ui::canvas::{Canvas, NavigationOptions}; +use craft_ui::canvas::{Canvas, CanvasSpace, NavigationOptions, WheelScheme, canvas_space}; use craft_ui::contract::{Common, Component, Container, ContainerProps, Cx, Mount, Overlay, Props as _, Role, ShowContainer as _}; use craft_ui::style::StyleCx; -use craft_ui::testing::{Fixture, pointer, trial}; +use craft_ui::testing::{Fixture, Frames, pointer, trial}; use craft_ui_test_kit::contract::PlainStyle; -use egui::{Response, Vec2}; +use egui::{Response, TouchPhase, Vec2}; use std::cell::Cell; use std::rc::Rc; @@ -81,3 +81,529 @@ fn the_wheel_over_a_canvas_under_a_modal_moves_nothing() { } } } + +/// A body that claims a wheel gesture (`CanvasSpace::claim_wheel`) reads the rest of it alone: the later shares reach +/// the body, and the view does not move by them. +#[trial] +fn the_rest_of_a_wheel_gesture_the_body_claimed_does_not_move_the_view() { + for eased in [false, true] { + claimed_gesture_keeps_the_view(eased); + } +} + +/// The claimed rest of a gesture of point scroll, or with `eased` of eased wheel lines whose first notch still owes +/// motion when the body claims the gesture. +fn claimed_gesture_keeps_the_view(eased: bool) { + let mut options = NavigationOptions::default(); + options.eased_wheel = eased; + let event = move || if eased { pointer::wheel_lines(-1.0) } else { pointer::wheel(-30.0) }; + let view = Rc::new(Cell::new(CanvasView::new(egui::Rect::ZERO, Point::new(2000.0, 2000.0), 1.0))); + let claims = Rc::new(Cell::new(false)); + let read = Rc::new(Cell::new(0_u32)); + let (shown, claiming, reads) = (Rc::clone(&view), Rc::clone(&claims), Rc::clone(&read)); + let mut fixture = Fixture::new(move |ui| { + let mut given = shown.get(); + given.rect = ui.available_rect_before_wrap(); + let canvas = Canvas::new("Document").document(Size::new(4000.0, 4000.0)).navigation(options).view(given).show(ui, |ui, body| { + if let Some(space) = canvas_space(&body.env) + && space.wheel().is_some() + { + reads.set(reads.get() + 1); + if claiming.get() { + assert!(space.claim_wheel(ui.ctx(), Vec2::ZERO), "the canvas owns this gesture"); + } + } + }); + shown.set(canvas.output.view.unwrap_or(given)); + }); + fixture.settle(); + let at = view.get().rect.center() + Vec2::new(0.0, 150.0); + fixture.frame(vec![pointer::moved(at)]); + let start = view.get(); + fixture.frame(vec![event()]); + fixture.idle(40); + assert!(view.get().center.y > start.center.y + 1.0, "eased {eased}: precondition: an unclaimed share scrolls the canvas"); + + // The first share of the gesture moves the view before the body claims it; an eased notch still owes motion. + claims.set(true); + fixture.frame(vec![event()]); + let claimed = view.get(); + // The motion the claimed notch still owed is dropped, with no more wheel input too. + fixture.idle(5); + let still = view.get(); + assert!((still.center.y - claimed.center.y).abs() < 1e-3, "eased {eased}: owed motion moved the view: {claimed:?} -> {still:?}"); + read.set(0); + for _ in 0..3 { + fixture.frame(vec![event()]); + } + assert_eq!(read.get(), 3, "eased {eased}: the body reads every share of the claimed gesture"); + claims.set(false); + fixture.idle(40); + let after = view.get(); + assert!( + (after.center.y - claimed.center.y).abs() < 1e-3 && after.zoom == claimed.zoom, + "eased {eased}: the view moved: {claimed:?} -> {after:?}" + ); +} + +#[trial] +fn a_canvas_space_with_a_supplied_wheel_share_has_no_claim_token() { + let read = Rc::new(Cell::new(0_u32)); + let reads = Rc::clone(&read); + let mut fixture = Fixture::new(move |ui| { + let view = CanvasView::new(ui.available_rect_before_wrap(), Point::new(2000.0, 2000.0), 1.0); + Canvas::new("Document").document(Size::new(4000.0, 4000.0)).view(view).show(ui, |ui, body| { + if let Some(space) = canvas_space(&body.env) + && let Some(wheel) = space.wheel() + { + let supplied = space.with_wheel(Some(wheel)); + assert_eq!(supplied.wheel(), Some(wheel)); + assert!(!supplied.claim_wheel(ui.ctx(), Vec2::ZERO), "a supplied share has no claim token"); + assert!(supplied.with_wheel(None).wheel().is_none()); + assert!(space.claim_wheel(ui.ctx(), Vec2::ZERO), "the canvas's original share keeps its token"); + reads.set(reads.get() + 1); + } + }); + }); + fixture.settle(); + fixture.frame(vec![pointer::moved(egui::Pos2::new(200.0, 200.0))]); + fixture.frame(vec![pointer::wheel(-30.0)]); + assert_eq!(read.get(), 1); +} + +/// A canvas reports a rejected claim when a nested scroller owns the diagonal gesture. +#[trial] +fn a_canvas_cannot_claim_the_horizontal_share_of_a_nested_scrollers_gesture() { + let view = Rc::new(Cell::new(CanvasView::new(egui::Rect::ZERO, Point::new(2000.0, 2000.0), 1.0))); + let read = Rc::new(Cell::new(0_u32)); + let (shown, reads) = (Rc::clone(&view), Rc::clone(&read)); + let mut fixture = Fixture::new(move |ui| { + let mut given = shown.get(); + given.rect = ui.available_rect_before_wrap(); + let canvas = Canvas::new("Document").document(Size::new(4000.0, 4000.0)).view(given).show(ui, |ui, body| { + let scroller = egui::Id::unique("nested_wheel_scroller"); + let rect = egui::Rect::from_center_size(given.rect.center(), Vec2::splat(200.0)); + craft_ui::testing::wheel::register(ui.ctx(), craft_behavior::WheelTaker::new(scroller, rect).vertical(true).scrolls(true)); + if let Some(space) = canvas_space(&body.env) + && let Some(wheel) = space.wheel() + { + assert!(wheel.scroll.x != 0.0 && wheel.scroll.y == 0.0, "the canvas receives only horizontal motion"); + let vertical = craft_ui::testing::wheel::take_share(ui.ctx(), scroller).expect("the nested scroller receives vertical motion"); + assert!(vertical.scroll.y != 0.0 && vertical.scroll.x == 0.0); + assert!(!space.claim_wheel(ui.ctx(), Vec2::ZERO), "the nested scroller owns the gesture"); + reads.set(reads.get() + 1); + } + }); + shown.set(canvas.output.view.unwrap_or(given)); + }); + fixture.settle(); + fixture.frame(vec![pointer::moved(view.get().rect.center())]); + let diagonal = || egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: Vec2::new(-20.0, -30.0), + phase: TouchPhase::Move, + modifiers: egui::Modifiers::NONE, + source: egui::MouseWheelSource::Wheel, + }; + fixture.frame(vec![diagonal()]); + let first = view.get(); + fixture.frame(vec![diagonal()]); + assert_eq!(read.get(), 2, "the canvas receives both horizontal shares"); + assert!(view.get().center.x > first.center.x, "a rejected claim leaves later horizontal panning enabled"); +} + +#[trial] +fn a_canvas_can_mark_the_horizontal_share_of_a_nested_scrollers_gesture_modal() { + let view = Rc::new(Cell::new(CanvasView::new(egui::Rect::ZERO, Point::new(2000.0, 2000.0), 1.0))); + let read = Rc::new(Cell::new(0_u32)); + let (shown, reads) = (Rc::clone(&view), Rc::clone(&read)); + let mut fixture = Fixture::new(move |ui| { + let mut given = shown.get(); + given.rect = ui.available_rect_before_wrap(); + let canvas = Canvas::new("Document").document(Size::new(4000.0, 4000.0)).view(given).show(ui, |ui, body| { + let scroller = egui::Id::unique("modal_nested_wheel_scroller"); + let rect = egui::Rect::from_center_size(given.rect.center(), Vec2::splat(200.0)); + craft_ui::testing::wheel::register(ui.ctx(), craft_behavior::WheelTaker::new(scroller, rect).vertical(true).scrolls(true)); + if let Some(space) = canvas_space(&body.env) + && let Some(wheel) = space.wheel() + { + let vertical = craft_ui::testing::wheel::take_share(ui.ctx(), scroller).expect("the nested scroller receives vertical motion"); + assert!(wheel.scroll.x != 0.0 && wheel.scroll.y == 0.0); + assert!(vertical.scroll.y != 0.0 && vertical.scroll.x == 0.0); + assert_eq!(wheel.modal, reads.get() == 1, "only the rest of the marked gesture is modal"); + assert_eq!(vertical.modal, wheel.modal, "both shares carry the gesture's modal mark"); + assert!(!space.claim_wheel(ui.ctx(), Vec2::ZERO), "marking does not let the canvas claim the gesture"); + assert!(craft_ui::runtime::wheel::claim_token(ui.ctx(), scroller).is_some(), "the nested scroller owns the gesture"); + if reads.get() == 0 { + space.mark_wheel_modal(ui.ctx()); + } + reads.set(reads.get() + 1); + } + }); + shown.set(canvas.output.view.unwrap_or(given)); + }); + fixture.settle(); + fixture.frame(vec![pointer::moved(view.get().rect.center())]); + let diagonal = || egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: Vec2::new(-20.0, -30.0), + phase: TouchPhase::Move, + modifiers: egui::Modifiers::NONE, + source: egui::MouseWheelSource::Wheel, + }; + fixture.frame(vec![diagonal()]); + fixture.frame(vec![diagonal()]); + assert_eq!(read.get(), 2, "the canvas receives both horizontal shares"); + fixture.advance(craft_behavior::GESTURE_GAP); + fixture.frame(vec![diagonal()]); + assert_eq!(read.get(), 3, "a new gesture starts without the modal mark"); +} + +/// A body that first claims the device End stops the canvas glide after the gesture closes. +#[trial] +fn claiming_the_device_end_stops_the_canvas_glide() { + for claim_end in [false, true] { + let mut options = NavigationOptions::default(); + options.touchpad_glide = true; + let view = Rc::new(Cell::new(CanvasView::new(egui::Rect::ZERO, Point::new(2000.0, 2000.0), 1.0))); + let claimed = Rc::new(Cell::new(false)); + let (shown, claims) = (Rc::clone(&view), Rc::clone(&claimed)); + let mut fixture = Fixture::new(move |ui| { + let mut given = shown.get(); + given.rect = ui.available_rect_before_wrap(); + let canvas = Canvas::new("Document").document(Size::new(4000.0, 4000.0)).navigation(options).view(given).show(ui, |ui, body| { + if claim_end + && let Some(space) = canvas_space(&body.env) + && space.wheel().is_some_and(|wheel| wheel.phase == craft_behavior::WheelPhase::End) + { + space.claim_wheel(ui.ctx(), Vec2::ZERO); + claims.set(true); + } + }); + shown.set(canvas.output.view.unwrap_or(given)); + }); + fixture.settle(); + fixture.frame(vec![pointer::moved(view.get().rect.center())]); + let event = |phase, dy| egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: Vec2::new(0.0, dy), + phase, + modifiers: egui::Modifiers::NONE, + source: egui::MouseWheelSource::Trackpad, + }; + fixture.frame(vec![event(TouchPhase::Start, -30.0)]); + for _ in 0..4 { + fixture.frame(vec![event(TouchPhase::Move, -30.0)]); + } + fixture.frame(vec![event(TouchPhase::End, 0.0)]); + assert_eq!(claimed.get(), claim_end, "the body claims only the device End"); + let lifted = view.get(); + fixture.idle(5); + let after = view.get(); + if claim_end { + assert!((after.center.y - lifted.center.y).abs() < 1e-3, "the claimed End left a glide: {lifted:?} -> {after:?}"); + } else { + assert!(after.center.y > lifted.center.y + 1.0, "precondition: the unclaimed End starts a glide"); + } + } +} + +/// A fresh notch and its eased tail move the view after the body claims the previous device End. +#[trial] +fn a_fresh_notch_eases_after_a_claimed_device_end() { + for zoom in [false, true] { + let mut options = NavigationOptions::default(); + options.eased_wheel = true; + options.eased_wheel_zoom = true; + options.touchpad_glide = true; + options.wheel = WheelScheme::Acrobat; + let view = Rc::new(Cell::new(CanvasView::new(egui::Rect::ZERO, Point::new(2000.0, 2000.0), 1.0))); + let shown = Rc::clone(&view); + let mut fixture = Fixture::new(move |ui| { + let mut given = shown.get(); + given.rect = ui.available_rect_before_wrap(); + let canvas = Canvas::new("Document").document(Size::new(4000.0, 4000.0)).navigation(options).view(given).show(ui, |ui, body| { + if let Some(space) = canvas_space(&body.env) + && space.wheel().is_some_and(|wheel| wheel.phase == craft_behavior::WheelPhase::End) + { + space.claim_wheel(ui.ctx(), Vec2::ZERO); + } + }); + shown.set(canvas.output.view.unwrap_or(given)); + }); + fixture.settle(); + fixture.frame(vec![pointer::moved(view.get().rect.center())]); + let swipe = |phase, dy| egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: Vec2::new(0.0, dy), + phase, + modifiers: egui::Modifiers::NONE, + source: egui::MouseWheelSource::Trackpad, + }; + fixture.frame(vec![swipe(TouchPhase::Start, -30.0)]); + fixture.frame(vec![swipe(TouchPhase::End, 0.0)]); + let before = view.get(); + fixture.frame(vec![egui::Event::MouseWheel { + unit: if zoom { egui::MouseWheelUnit::Point } else { egui::MouseWheelUnit::Line }, + delta: Vec2::new(0.0, if zoom { -60.0 } else { -1.0 }), + phase: TouchPhase::Move, + modifiers: if zoom { egui::Modifiers::COMMAND } else { egui::Modifiers::NONE }, + source: egui::MouseWheelSource::Wheel, + }]); + let first = view.get(); + fixture.idle(5); + let after = view.get(); + if zoom { + assert!( + first.zoom < before.zoom && after.zoom < first.zoom, + "the fresh zoom notch and its tail move the view: {before:?} -> {first:?} -> {after:?}" + ); + } else { + assert!( + first.center.y > before.center.y && after.center.y > first.center.y, + "the fresh scroll notch and its tail move the view: {before:?} -> {first:?} -> {after:?}" + ); + } + } +} + +/// A partial zoom notch from a claimed gesture does not combine with the next gesture's first half notch. +#[trial] +fn claiming_a_gesture_clears_its_partial_zoom_notch() { + let mut options = NavigationOptions::default(); + options.wheel = WheelScheme::Zoom; + let view = Rc::new(Cell::new(CanvasView::new(egui::Rect::ZERO, Point::new(2000.0, 2000.0), 1.0))); + let claim = Rc::new(Cell::new(true)); + let (shown, claiming) = (Rc::clone(&view), Rc::clone(&claim)); + let mut fixture = Fixture::new(move |ui| { + let mut given = shown.get(); + given.rect = ui.available_rect_before_wrap(); + let canvas = Canvas::new("Document").document(Size::new(4000.0, 4000.0)).navigation(options).view(given).show(ui, |ui, body| { + if let Some(space) = canvas_space(&body.env) + && space.wheel().is_some() + && claiming.replace(false) + { + space.claim_wheel(ui.ctx(), Vec2::ZERO); + } + }); + shown.set(canvas.output.view.unwrap_or(given)); + }); + fixture.settle(); + fixture.frame(vec![pointer::moved(view.get().rect.center())]); + let half = || egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: Vec2::new(0.0, 0.5), + phase: TouchPhase::Move, + modifiers: egui::Modifiers::SHIFT, + source: egui::MouseWheelSource::Wheel, + }; + let before = view.get().zoom; + fixture.frame(vec![half()]); + assert!(!claim.get(), "the body claimed the first half notch"); + assert_eq!(view.get().zoom, before, "a half notch does not zoom"); + fixture.frame(vec![egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: Vec2::ZERO, + phase: TouchPhase::End, + modifiers: egui::Modifiers::NONE, + source: egui::MouseWheelSource::Trackpad, + }]); + fixture.frame(vec![half()]); + assert_eq!(view.get().zoom, before, "the new gesture has only half a notch"); + fixture.frame(vec![half()]); + assert!(view.get().zoom > before, "the new gesture's two half notches complete a rung"); +} + +#[trial] +fn a_claimed_swipes_samples_do_not_glide_after_a_coalesced_start() { + let mut options = NavigationOptions::default(); + options.touchpad_glide = true; + let view = Rc::new(Cell::new(CanvasView::new(egui::Rect::ZERO, Point::new(2000.0, 2000.0), 1.0))); + let claim = Rc::new(Cell::new(false)); + let last = Rc::new(Cell::new(None)); + let (shown, claiming, shares) = (Rc::clone(&view), Rc::clone(&claim), Rc::clone(&last)); + let mut fixture = Fixture::new(move |ui| { + let mut given = shown.get(); + given.rect = ui.available_rect_before_wrap(); + let canvas = Canvas::new("Document").document(Size::new(4000.0, 4000.0)).navigation(options).view(given).show(ui, |ui, body| { + if let Some(space) = canvas_space(&body.env) + && let Some(wheel) = space.wheel() + { + shares.set(Some(wheel)); + if claiming.get() { + assert!(space.claim_wheel(ui.ctx(), Vec2::ZERO)); + } + } + }); + shown.set(canvas.output.view.unwrap_or(given)); + }); + fixture.settle(); + fixture.frame(vec![pointer::moved(view.get().rect.center())]); + let event = |phase, dy| egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: Vec2::new(0.0, dy), + phase, + modifiers: egui::Modifiers::NONE, + source: egui::MouseWheelSource::Trackpad, + }; + fixture.frame(vec![event(TouchPhase::Start, -30.0)]); + claim.set(true); + fixture.frame(vec![event(TouchPhase::Move, -30.0)]); + fixture.frame(vec![event(TouchPhase::End, 0.0)]); + assert!(last.get().expect("the claimed End").claimed); + + claim.set(false); + fixture.frame(vec![event(TouchPhase::Move, -1.0)]); + let fresh = last.get().expect("the next swipe's Move"); + assert_eq!(fresh.phase, craft_behavior::WheelPhase::Move); + assert!(!fresh.claimed); + fixture.frame(vec![event(TouchPhase::End, 0.0)]); + let lifted = view.get(); + fixture.idle(5); + assert_eq!(view.get().center, lifted.center, "one small sample cannot start a glide"); +} + +#[trial] +fn a_stale_canvas_space_cannot_claim_a_wheel_share_in_a_later_pass() { + claim_from_retained_space(false); +} + +#[trial] +fn a_fresh_canvas_space_can_claim_after_a_stale_claim_is_refused() { + claim_from_retained_space(true); +} + +#[trial] +fn a_retained_canvas_space_cannot_claim_a_recreated_viewports_share_with_the_same_pass_number() { + for claim_fresh in [false, true] { + let viewport = egui::ViewportId::from_hash_of("canvas window"); + let retained: Cell> = Cell::new(None); + let issued = Cell::new(None); + let owner = egui::Id::unique("moving canvas"); + let recreated = Cell::new(false); + let attempts = Cell::new(0); + let last = Cell::new(None); + let view = Cell::new(CanvasView::new(egui::Rect::ZERO, Point::new(2000.0, 2000.0), 1.0)); + let mut show = |ui: &mut egui::Ui| { + let mut given = view.get(); + given.rect = ui.available_rect_before_wrap(); + let canvas = Canvas::new("Document").id(owner).document(Size::new(4000.0, 4000.0)).view(given).show(ui, |ui, body| { + if let Some(space) = canvas_space(&body.env) + && let Some(wheel) = space.wheel() + { + last.set(Some(wheel)); + let pass = craft_ui::runtime::frame::running(ui.ctx()).expect("a running pass"); + if !recreated.get() { + retained.set(Some(space)); + issued.set(Some(pass.pass_nr)); + } else if attempts.get() == 0 { + assert_eq!(pass.viewport, viewport, "the recreated viewport has the same ID"); + assert_eq!(Some(pass.pass_nr), issued.get(), "the recreated viewport has the same pass counter"); + assert!(!retained.get().expect("the earlier snapshot").claim_wheel(ui.ctx(), Vec2::new(0.0, -30.0))); + assert!(!craft_ui::runtime::wheel::claimed(ui.ctx(), owner), "the rejected claim leaves the new share unclaimed"); + if claim_fresh { + assert!(space.claim_wheel(ui.ctx(), Vec2::ZERO)); + } + attempts.set(attempts.get() + 1); + } + } + }); + view.set(canvas.output.view.unwrap_or(given)); + }; + let mut frames = Frames::new(); + for reopen in [false, true] { + if reopen { + frames.close_viewport(viewport); + frames.frame(Vec::new(), |_| {}); + recreated.set(true); + } + frames.frame_in_viewport(viewport, Vec::new(), &mut show); + frames.frame_in_viewport(viewport, Vec::new(), &mut show); + frames.frame_in_viewport(viewport, vec![pointer::moved(view.get().rect.center())], &mut show); + frames.frame_in_viewport(viewport, vec![pointer::wheel_lines(-1.0)], &mut show); + } + assert_eq!(attempts.get(), 1); + last.set(None); + frames.frame_in_viewport(viewport, vec![pointer::wheel(-30.0)], &mut show); + let next = last.get().expect("the share after the claim attempt"); + assert_eq!(next.claimed, claim_fresh); + if !claim_fresh { + assert_eq!(next.claimed_gathered, Vec2::ZERO, "the rejected claim records no claimed motion"); + } + assert_eq!(next.claimed_spent, Vec2::ZERO, "the rejected claim records no spent motion"); + } +} + +fn claim_from_retained_space(claim_fresh: bool) { + let view = Rc::new(Cell::new(CanvasView::new(egui::Rect::ZERO, Point::new(2000.0, 2000.0), 1.0))); + let retained: Rc>> = Rc::new(Cell::new(None)); + let later = Rc::new(Cell::new(false)); + let read = Rc::new(Cell::new(None)); + let attempts = Rc::new(Cell::new(0)); + let (shown, saved, claiming, shares, claims) = + (Rc::clone(&view), Rc::clone(&retained), Rc::clone(&later), Rc::clone(&read), Rc::clone(&attempts)); + let mut fixture = Fixture::new(move |ui| { + let mut given = shown.get(); + given.rect = ui.available_rect_before_wrap(); + let canvas = Canvas::new("Document").document(Size::new(4000.0, 4000.0)).view(given).show(ui, |ui, body| { + if let Some(space) = canvas_space(&body.env) + && let Some(wheel) = space.wheel() + { + shares.set(Some(wheel)); + if claiming.get() { + assert!(!saved.get().expect("the earlier snapshot").claim_wheel(ui.ctx(), Vec2::ZERO)); + if claim_fresh { + assert!(space.claim_wheel(ui.ctx(), Vec2::ZERO)); + } + claims.set(claims.get() + 1); + } + } + }); + shown.set(canvas.output.view.unwrap_or(given)); + if !claiming.get() && canvas.output.space.is_some_and(|space| space.wheel().is_some()) { + saved.set(canvas.output.space); + } + }); + fixture.settle(); + fixture.frame(vec![pointer::moved(view.get().rect.center())]); + fixture.frame(vec![pointer::wheel(-30.0)]); + assert!(retained.get().is_some()); + later.set(true); + fixture.frame(vec![pointer::wheel(-30.0)]); + assert_eq!(attempts.get(), 1); + later.set(false); + fixture.frame(vec![pointer::wheel(-30.0)]); + let next = read.get().expect("the share after the claim attempt"); + assert_eq!(next.claimed, claim_fresh); + if claim_fresh { + assert_eq!(next.claimed_gathered, next.scroll, "only the fresh snapshot's share was claimed"); + } else { + assert_eq!(next.claimed_gathered, Vec2::ZERO, "the stale snapshot left the new share unclaimed"); + } +} + +#[trial] +fn a_small_reversal_of_a_claimed_gesture_keeps_the_step_count() { + let steps = Rc::new(Cell::new(0.0)); + let count = Rc::clone(&steps); + let mut fixture = Fixture::new(move |ui| { + let view = CanvasView::new(ui.available_rect_before_wrap(), Point::new(2000.0, 2000.0), 1.0); + Canvas::new("Document").document(Size::new(4000.0, 4000.0)).view(view).show(ui, |ui, body| { + if let Some(space) = canvas_space(&body.env) + && let Some(wheel) = space.wheel() + { + let remaining = wheel.claimed_gathered.y + wheel.scroll.y - wheel.claimed_spent.y; + let steps = (remaining / 30.0).trunc(); + if space.claim_wheel(ui.ctx(), Vec2::new(0.0, steps * 30.0)) { + count.set(count.get() + steps); + } + } + }); + }); + fixture.settle(); + fixture.frame(vec![pointer::moved(egui::Pos2::new(200.0, 200.0))]); + fixture.frame(vec![pointer::wheel(-30.0)]); + assert_eq!(steps.get(), -1.0, "the first share takes one step"); + fixture.frame(vec![pointer::wheel(5.0)]); + assert_eq!(steps.get(), -1.0, "a reversal smaller than one step leaves the count unchanged"); +} diff --git a/crates/ui-canvas/tests/it/canvas/tools.rs b/crates/ui-canvas/tests/it/canvas/tools.rs index 1c9afddd7a..5d9d3ffb3f 100644 --- a/crates/ui-canvas/tests/it/canvas/tools.rs +++ b/crates/ui-canvas/tests/it/canvas/tools.rs @@ -7,7 +7,7 @@ use craft_behavior::kurbo::{Point, Rect, Size}; use craft_keymap::Mods; use craft_ui::canvas::{ Canvas, CanvasTool, HandTool, LayerBounds, Momentary, MomentaryCommands, MomentaryShift, MomentaryTool, NavigationOptions, RotateViewTool, - ToolHost, ViewCommands, ViewFit, ViewRequest, ViewTarget, ZoomTool, tool_pass, + ToolHost, ToolReadout, ViewCommands, ViewFit, ViewRequest, ViewTarget, ZoomTool, tool_pass, }; use craft_ui::contract::{Bind, ShowContainer as _}; use craft_ui::runtime::access::Role; @@ -29,6 +29,8 @@ struct Rig { fixture: Fixture, view: Rc>>, pans: Rc>>, + /// The readout the host reported in the last frame. + readout: Rc>>, } impl Rig { @@ -42,7 +44,8 @@ impl Rig { let tool = Rc::new(RefCell::new(tool)); let view = Rc::new(Cell::new(None::)); let pans = Rc::new(RefCell::new(Vec::<(DocVec, bool)>::new())); - let (shown_tool, shown_view, shown_pans) = (Rc::clone(&tool), Rc::clone(&view), Rc::clone(&pans)); + let readout = Rc::new(RefCell::new(None::)); + let (shown_tool, shown_view, shown_pans, shown_readout) = (Rc::clone(&tool), Rc::clone(&view), Rc::clone(&pans), Rc::clone(&readout)); let mut fixture = Fixture::new(move |ui| { let room = ui.available_rect_before_wrap(); let current = shown_view.get().unwrap_or_else(|| start(room)); @@ -53,6 +56,7 @@ impl Rig { } }); let reply = reply.unwrap_or_default(); + shown_readout.replace(reply.readout.clone()); if let Some(pan) = reply.pan { shown_pans.borrow_mut().push((pan.delta, pan.scroll_all)); } @@ -60,13 +64,18 @@ impl Rig { }); fixture.ctx().set_pixels_per_point(ppp); fixture.settle(); - Rig { fixture, view, pans } + Rig { fixture, view, pans, readout } } fn view(&self) -> CanvasView { self.view.get().expect("the rig has shown a frame") } + /// The values of the readout the host reported in the last frame. + fn readout(&self) -> Option> { + self.readout.borrow().as_ref().map(|readout| readout.rows.iter().map(|(_, value)| value.clone()).collect()) + } + fn ppp(&self) -> f32 { self.fixture.ctx().pixels_per_point() } @@ -338,6 +347,29 @@ fn zoom_drag_keeps_the_press_point_and_fits_the_rectangle() { } } +#[trial] +fn a_zoom_rectangle_shows_its_size_in_document_pixels() { + // The plain view shows 2 points per document pixel, the turned one half a point, a quarter turn round. + type Start = fn(egui::Rect) -> CanvasView; + let views: [(Start, [&str; 2]); 2] = [(plain, ["150 px", "60 px"]), (|room| turned(room, 90.0, false), ["600 px", "240 px"])]; + for (start, size) in views { + let mut rig = Rig::new(ZoomTool::new(options(|o| (o.animated_zoom, o.scrubby_zoom) = (false, false))), start); + let a = rig.centre() + egui::vec2(-150.0, -60.0); + let b = a + egui::vec2(300.0, 120.0); + rig.press(a); + rig.drag_to(a, b, 6, FRAME); + assert_eq!(rig.readout(), Some(size.map(str::to_owned).to_vec()), "the rectangle shows its width and height while drawn"); + rig.release(b, FRAME); + assert_eq!(rig.readout(), None, "the readout ends with the drag"); + } + // A scrub draws no rectangle, so it has no size to show. + let mut rig = Rig::new(ZoomTool::new(options(|o| (o.animated_zoom, o.scrubby_zoom) = (false, true))), plain); + let at = rig.centre(); + rig.press(at); + rig.drag_to(at, at + egui::vec2(100.0, 0.0), 5, FRAME); + assert_eq!(rig.readout(), None, "a scrub shows no size"); +} + #[trial] fn a_hand_pan_reports_its_document_distance_and_its_scroll_all_choice() { // (Shift at the press, the Scroll All Windows option) and the choice the pans carry. diff --git a/crates/ui-contract/src/contract/body.rs b/crates/ui-contract/src/contract/body.rs index fdfddb5bb5..b5067f91eb 100644 --- a/crates/ui-contract/src/contract/body.rs +++ b/crates/ui-contract/src/contract/body.rs @@ -158,6 +158,16 @@ pub(super) struct BodyHooks<'b> { /// The axes (horizontal, vertical) the container is given: it fills them, and its own container was given them /// too or it is shown at a rect. Along the others it sizes from its content. given: (bool, bool), + /// The container is given both axes in a finite room and is not a share of a scrolling view + /// (`measure_open_room`): it takes its room whatever its content takes. A real pass takes it from its measuring run. + takes_room: bool, + /// The container is in a flow that leaves at least one axis unbounded, so its size there follows its content. + flow_unbounded: bool, + /// The height follows content up to a cap. A settled row line is a minimum, so it does not fix the height. + content_capped: bool, + /// The body's last measuring run counted a child that fills the axis the body shares: the real run gives that child + /// the share the record holds. + fills_share: bool, /// The height the container is given is a fixed extent (`fixed_height`): a rect it is shown at, a pane's, or the /// row line it fills. fixed_height: bool, @@ -255,6 +265,10 @@ impl<'b> BodyHooks<'b> { reports: Vec::new(), fixed: false, given: (false, false), + takes_room: false, + flow_unbounded: false, + content_capped: false, + fills_share: false, fixed_height: false, passes: false, held: false, diff --git a/crates/ui-contract/src/contract/body/hooks.rs b/crates/ui-contract/src/contract/body/hooks.rs index 2f6bb996a9..ebdb3033cd 100644 --- a/crates/ui-contract/src/contract/body/hooks.rs +++ b/crates/ui-contract/src/contract/body/hooks.rs @@ -50,8 +50,19 @@ impl ShapeHooks for BodyHooks<'_> { } fn regions(&self, id: Id) -> Vec<(Id, Vec2)> { + // A non-scrolling `Stack` that takes its room (`takes_room`) skips body-size comparison with `Sizing::Fill`, or + // with `Sizing::FillWidth` when its header is not inline. Rows, grids, other content-sized bodies, animated + // collapses, children that fill a share, and bodies in unbounded flows still compare their measured body sizes. + let inline = self.props.header.is_some_and(|header| header.inline); + let skips = matches!(self.props.layout, layout::BodyLayout::Stack) + && (self.sizing(&self.props) == Sizing::Fill || (self.sizing(&self.props) == Sizing::FillWidth && !inline)) + && !self.props.collapse.is_some_and(|collapse| collapse.animated) + && !self.content_capped + && !self.flow_unbounded + && !self.fills_share; + let body_fixed = self.takes_room && scroll_of(&self.props).is_none() && skips; [ - ("body", self.body_size), + ("body", self.body_size.filter(|_| !body_fixed)), ("header", self.header_size), ("footer", self.footer_size), ("end", self.end_size), @@ -180,6 +191,7 @@ impl ShapeHooks for BodyHooks<'_> { self.across = self.held && matches!(env.column, Some(ColumnSweep::Column(..))); self.in_column = label::in_column(ui, env); self.egui_cell = env.egui_cell; + self.content_capped = self.capped(props, env, at); self.given.1 |= self.given_room(props, env, at, ui.ctx(), id); let measured = self.measured_body.unwrap_or(Vec2::ZERO); let body = if self.presence.visible { Vec2::new(measured.x, measured.y * self.presence.t) } else { Vec2::ZERO }; @@ -231,13 +243,21 @@ impl ShapeHooks for BodyHooks<'_> { let (ctx, id) = (at.ui.ctx().clone(), at.resolved.id); let layer = matches!(props.mount, Mount::Layer(_) | Mount::FullWindow | Mount::Viewport { .. }); let fading = layer && !self.open && crate::runtime::motion::layer_fading(&ctx, sub(id, "presence")); + self.takes_room = false; + self.flow_unbounded = false; if !layer || self.open || fading { // The measuring run starts from what this run's `read` found: the measuring run of a sizing parent reads // the same state. let mut stage = MemoryStage::open_peek(&ctx, id); let mut fresh = self.measuring_hooks(fading); crate::contract::run::measured_extent(comp, &mut *fresh, at, &mut stage, style, shown); + let takes_room = fresh.takes_room; + let flow_unbounded = fresh.flow_unbounded; + drop(fresh); + self.takes_room = takes_room; + self.flow_unbounded = flow_unbounded; } + self.fills_share = layout_memory::measured(&ctx, sub(sub(id, "layout"), "share")).is_some_and(|found| found.took.y >= 1.0); let took = |key: Id| layout_memory::measured(&ctx, key).map(|measured| measured.took); // The real run decides the scroll from the content this pass measured: whether it overflows (the wheel, the // bars, the strips) and how far it scrolls. @@ -1321,7 +1341,17 @@ impl BodyHooks<'_> { ); let trailing = props.header.is_some_and(|header| header.trailing); let inset = props.header.map_or(0.0, |header| pad_of(&env.tokens, header.inset)); - let header_env = (!plan.real).then(|| plan.region_env.derive_local(|scoped| scoped.first_line = Some(plan.first.0))); + // A container that takes its width from its content holds a fill-width child of its header at its measured + // width and shows it across the header's band in the real run too, as it does in its body. + let column = !self.wide(); + let header_env = (!plan.real || column).then(|| { + plan.region_env.derive_local(|scoped| { + if !plan.real { + scoped.first_line = Some(plan.first.0); + } + scoped.content_column |= column; + }) + }); let frame = RegionFrame { id: plan.id, rtl: plan.rtl, node: plan.node, env: header_env.as_ref().unwrap_or(&plan.region_env), gap: plan.gap }; let closed = self.header_region(comp, ui, &mut bcx, &frame, plan.regions.header, (trailing, inset, header_parts)); plan.close = plan.close.or(closed); @@ -1349,8 +1379,9 @@ impl BodyHooks<'_> { } // A footer in the end region is part of a column sized from its content: a fill-width child takes its // measured width there and shows across the column, so it never sets the column's width. A footer the body - // places shows across its slot the same way. - if footer_in_end(props) || footer_in_body(props) { + // places shows across its slot the same way, and so does a footer in its own band under a container that takes + // its width from its content. + if footer_in_end(props) || footer_in_body(props) || !self.wide() { plan.footer_env = plan.region_env.derive_local(|scoped| scoped.content_column = true); } if plan.real { @@ -1983,6 +2014,7 @@ impl BodyHooks<'_> { }; self.view_room = crate::layout::view_room(at.ui, at.place, craft_behavior::Axis::X).filter(|_| self.room.x.is_infinite()); self.given = self.given_axes(&props, at.env, at.at); + self.content_capped = self.capped(&props, at.env, at.at); self.given.1 |= self.given_room(&props, at.env, at.at, at.ui.ctx(), id); self.fixed_height = self.fixed_height(&props, at.at); self.least_width = self.least_width_of(&props, at.env, at.scx.tokens); @@ -2021,7 +2053,9 @@ impl BodyHooks<'_> { // A body that fills both axes its parent gives it takes the room, whatever its contents take: a parent's // measuring run does not run them. It measures them in its own real run. A share of a scrolling view is the // least of what it takes: its content may be taller. - if at.ui.is_sizing_pass() && self.given == (true, true) && self.room.is_finite() && !scrolled_share { + self.takes_room = self.given == (true, true) && self.room.is_finite() && !scrolled_share; + self.flow_unbounded = flows && !bounded.is_finite(); + if at.ui.is_sizing_pass() && self.takes_room { return Err(self.room); } Ok(scrolled_share) diff --git a/crates/ui-contract/src/contract/body/inherit.rs b/crates/ui-contract/src/contract/body/inherit.rs index c830296e70..82231ba321 100644 --- a/crates/ui-contract/src/contract/body/inherit.rs +++ b/crates/ui-contract/src/contract/body/inherit.rs @@ -122,6 +122,7 @@ impl BodyHooks<'_> { scoped.after_rule = props.header.is_some_and(|header| (header.rule || (header.heads && heads)) && !header.inline) || (props.header.is_none() && props.surface.is_none() && props.mount == Mount::Inline && self.after_rule); scoped.flow_body = None; + scoped.view_flow = None; scoped.column_row = self.in_column && matches!(props.layout, crate::layout::BodyLayout::Row { wrap: false, align: crate::layout::RowAlign::Start }); // Children side by side share the layer's width, so none of them spans it: a collection in a row or a grid takes diff --git a/crates/ui-contract/src/contract/body/regions.rs b/crates/ui-contract/src/contract/body/regions.rs index d3b73ff6a0..20efb82c40 100644 --- a/crates/ui-contract/src/contract/body/regions.rs +++ b/crates/ui-contract/src/contract/body/regions.rs @@ -101,7 +101,7 @@ impl RuleBands { let above = on(start != Some(true) && props.header.is_some_and(|header| header.rule_above)); let spaced = above > 0.0 && env.get::() == SectionRhythm::Spaced; let gaps = &tokens.tokens().space.gap; - let stack_gap = env.stack_gap.filter(|(body, _)| env.flow_body == Some(*body)).map_or(0.0, |(_, gap)| gap); + let stack_gap = env.flow_gap().unwrap_or(0.0); RuleBands { lead: if spaced && start.is_none() { (gaps.section - stack_gap).max(0.0) } else { 0.0 }, above, diff --git a/crates/ui-contract/src/contract/cx/pointer.rs b/crates/ui-contract/src/contract/cx/pointer.rs index bce2e0f7f0..b7feb34ef5 100644 --- a/crates/ui-contract/src/contract/cx/pointer.rs +++ b/crates/ui-contract/src/contract/cx/pointer.rs @@ -332,6 +332,10 @@ impl Pointer for Cx<'_, C> { impl Cx<'_, C> { /// The value a primary-button sweep sets on this toggle. Only siblings in the same layout /// participate. A control that uses this must sense both clicks and drags. + /// + /// A drag that starts on this toggle sets it only once it is a sweep: the pointer has crossed another + /// toggle of the layout, or the button goes up over this one. A drag that does neither is a press released + /// outside the control and leaves the value as it was. pub fn swept_toggle(&self, on: Option) -> Option { let group = self.pointer_group?; let target = crate::runtime::toggle_sweep::ToggleTarget { diff --git a/crates/ui-contract/src/contract/label/place.rs b/crates/ui-contract/src/contract/label/place.rs index d61e348f5d..96b0408f42 100644 --- a/crates/ui-contract/src/contract/label/place.rs +++ b/crates/ui-contract/src/contract/label/place.rs @@ -27,7 +27,7 @@ pub(crate) struct Placed { /// The `After` placement: the control's cell first, then the gap, then the label. A leaf control (a box, circle or /// track has no text baseline) and its label are centred on each other across the row. For a field's control, as in /// `LabelColumn::place`, the one with the lower baseline moves down so the two baselines line up, using the baseline -/// `record_control_baseline` stored last pass. +/// `record_control_baseline` stored last pass (`control_baseline`). fn place_after(ctx: &egui::Context, input: &LabelIn<'_>, flow: Flow, gap: f32, label: Vec2, label_baseline: f32, first_line: f32) -> Placed { let rtl = flow.is_rtl(); let (control_cell, rest) = flow.take_start(input.control_min.min(flow.rect().width())); @@ -41,7 +41,7 @@ fn place_after(ctx: &egui::Context, input: &LabelIn<'_>, flow: Flow, gap: f32, l let control = control_cell.translate(Vec2::new(0.0, (line - control_cell.height()) / 2.0)); return Placed { label, control, trailing: Rect::NOTHING, caption: 0.0 }; } - let control_baseline = crate::layout::control_baseline(ctx, input.scope, label, label_baseline); + let control_baseline = crate::layout::control_baseline(ctx, input.scope, input.size, label, label_baseline); let drop = control_baseline.map_or(0.0, |control| control - label_baseline); let (label_drop, control_drop) = (drop.max(0.0), (-drop).max(0.0)); let label_size = Vec2::new(label_width, label.y); @@ -193,6 +193,7 @@ pub(super) fn decide(ctx: &egui::Context, env: &Env, input: &LabelIn<'_>, kids: let placed = crate::layout::place_label( kids, input.scope, + input.size, &LabelColumn::new(column, if stacks { f32::INFINITY } else { 0.0 }, gap), flow, natural.min(Vec2::new(column, natural.y)), diff --git a/crates/ui-contract/src/contract/label/step.rs b/crates/ui-contract/src/contract/label/step.rs index b34598318c..4c926618d3 100644 --- a/crates/ui-contract/src/contract/label/step.rs +++ b/crates/ui-contract/src/contract/label/step.rs @@ -299,7 +299,7 @@ fn show(ui: &mut Ui, env: &Env, input: &LabelIn<'_>, decided: Decided, trailing: let Decided { placed, leaf, .. } = decided; let Some(DecidedLeaf { leaf, mut kids, installed, reset }) = leaf else { scope::begin(&ctx, input.scope, input.owner, scope::Kind::Label(field_label(env, input, label_id, Rect::NOTHING).shown(false))); - scope::place_controls(&ctx, input.scope, placed.control.top()); + scope::place_controls(&ctx, input.scope, placed.control.top(), input.size); return placed; }; let slot = if reset.is_some() && input.side.reset_dot { env.tokens.size.handle.sm } else { 0.0 }; @@ -326,7 +326,7 @@ fn show(ui: &mut Ui, env: &Env, input: &LabelIn<'_>, decided: Decided, trailing: .activated(shown.activated && !linked) .linked(shown.activated && linked); scope::begin(&ctx, input.scope, input.owner, scope::Kind::Label(label)); - scope::place_controls(&ctx, input.scope, placed.control.top()); + scope::place_controls(&ctx, input.scope, placed.control.top(), input.size); if input.claims { scope::offer_claim(&ctx, unslotted.rect()); } diff --git a/crates/ui-contract/src/contract/lazy.rs b/crates/ui-contract/src/contract/lazy.rs index b3659ec000..2644823b53 100644 --- a/crates/ui-contract/src/contract/lazy.rs +++ b/crates/ui-contract/src/contract/lazy.rs @@ -3,7 +3,7 @@ use crate::layout::{flow_region, take_cell, take_in_flow}; use crate::runtime::egui::alloc; -use crate::runtime::env::{Env, Shrink}; +use crate::runtime::env::{Env, Flow, Shrink}; use crate::runtime::focus; use crate::runtime::layout_memory; use crate::runtime::lazy::{self, Call, Decision, Key, Place}; @@ -39,6 +39,9 @@ pub struct Lazy { key: u64, estimate: f32, reveal: bool, + /// Out of view in a scroll area it takes its remembered extent in place of running; a memoized view shown out of + /// view ([`MemoView::shown_out_of_view`](super::MemoView::shown_out_of_view)) does not. + pub(super) culls: bool, } impl Lazy { @@ -48,7 +51,7 @@ impl Lazy { use std::hash::Hasher; let mut hasher = std::collections::hash_map::DefaultHasher::new(); key.hash(&mut hasher); - Lazy { key: hasher.finish(), estimate, reveal: false } + Lazy { key: hasher.finish(), estimate, reveal: false, culls: true } } /// When `reveal` holds, the scroll area glides until the child starts at the view's start (as far as the @@ -115,7 +118,7 @@ impl Lazy { let owner = view.map(|view| view.owner); // A run around this one that is replayed later keeps the child's entry. replay::journal(&ctx, || (owner, id), |ctx, &(owner, id)| lazy::keep(ctx, owner, id)); - if let Some(view) = view { + if let Some(view) = view.filter(|_| self.culls) { // A run around this child decides it by the scroll view: it replays only while the view is the same. replay::note_input(&ctx, crate::runtime::inputs::Input::Scroll); let at = |size: Vec2| Rect::from_min_size(at_start(available, rtl, size), size); @@ -146,7 +149,7 @@ impl Lazy { access: crate::runtime::egui::access::builds_nodes(&ctx), opacity: ui.opacity(), env: env.key, - flow: env.flow(), + flow: flow_around(&ctx, &env, memo), }; if real && memo { crate::runtime::memory::claim_id(&ctx, id, "two memoized views share an id in one pass"); @@ -311,6 +314,12 @@ fn open_record(ctx: &egui::Context, audited: bool) { replay::open(ctx); } +/// The flow facts of the body around a child shown under `env` (`Place::flow`). A memoized view's also hold where it +/// stands in that body's flow, which its content goes on with (`layout::open_view_flow`). +fn flow_around(ctx: &egui::Context, env: &Env, memo: bool) -> Flow { + if memo { env.flow().in_flow(crate::layout::flow_start(ctx, env), env.flow_gap()) } else { env.flow() } +} + /// Where content of `size` starts in `region`: at its start edge, the right one in a right-to-left layout. fn at_start(region: Rect, rtl: bool, size: Vec2) -> Pos2 { Pos2::new(if rtl { region.max.x - size.x } else { region.min.x }, region.min.y) diff --git a/crates/ui-contract/src/contract/memo_view.rs b/crates/ui-contract/src/contract/memo_view.rs index 5838a2cddf..737a9d4620 100644 --- a/crates/ui-contract/src/contract/memo_view.rs +++ b/crates/ui-contract/src/contract/memo_view.rs @@ -50,7 +50,8 @@ use std::sync::Arc; /// theme, density, direction, language, window active) and the flow of the body around it (whether that body is a /// content-sized or a given column, the axes it sizes from its content, the axis it shares among the children that /// fill it, a least measure, the axes a scroll leaves unbounded, a beside label's cell, whether its leaves fit the -/// room), compared for every view and for each kind of run on its own; +/// room, whether it starts that body's flow and the gap a `Stack` body leaves before it), compared for every view and +/// for each kind of run on its own; /// - what the scope around it hands down beyond those (enabled, read-only, size, ink, the command chain, motion, every /// app value, and the rest of `Scoped::scope_key`), in the key; /// - the framework inputs it reads outside its props (`runtime::inputs`: the modifiers, the pointer, the keys held, the @@ -67,7 +68,9 @@ use std::sync::Arc; /// no version: the containers inside measure as outside any view. /// /// Its content is a layout room of its own, as a pane's is: the flow of the body around it (a column's sweep, a grid's -/// cursor) does not reach in, so the room it is given reaches it only through its place. To the body +/// cursor) does not reach in, so the room it is given reaches it only through its place. Its direct children go on with +/// the flow the view stands in: the first one starts that flow when the view does, and each one keeps the gap a `Stack` +/// body leaves before the view, so a section shown in the view stands where it stands shown without it. To the body /// around it the view is one unit, sized by its content's measure. In a shrinking `Row` it is a unit the row narrows /// as it narrows a body unit: from what its content takes in no room down to what it takes with every leaf at its /// least. When the row narrows it, the width the row gives it is the room of its place; otherwise it shows as in no @@ -123,6 +126,14 @@ impl MemoVie MemoView { lazy: Lazy::new(id, 0.0), props, show } } + /// Shows the view in a scroll area as outside one: out of view it still runs or replays, its focus stops and + /// accessibility nodes stay registered, and `show` returns a value. A toolbar that scrolls shows each button's view + /// this way. + pub fn shown_out_of_view(mut self) -> Self { + self.lazy.culls = false; + self + } + /// Runs the view in a child `Ui` placed in flow in `ui`, or adds its last run again. Returns what the run returned, /// the kept value when it replayed; `None` only when it is out of view in a scroll area. A measuring run that /// replays returns the kept real run's value, laid out in that run's room and flow: code that measures sizes from @@ -146,11 +157,13 @@ impl MemoVie // that body sizes from its content, whether its leaves fit their room and which axis it shares among the // children that fill it (`Scoped::start_view_room`), so the view takes what its content used there, as the // same content shown without the view would. + // Its direct children go on with the flow the view stands in (`layout::open_view_flow`). // Its key is its content's version: a body inside measures under it (`Scoped::view_version`). + let flow = crate::layout::open_view_flow(&ctx, &env, id); let installed = Env::install_for( ui, env.derive_local(|scoped| { - scoped.start_view_room(id); + scoped.start_view_room(id, flow); scoped.view_version = follows.then_some(key); }), ); diff --git a/crates/ui-contract/src/contract/overlay.rs b/crates/ui-contract/src/contract/overlay.rs index ef6b8189f3..29882ff937 100644 --- a/crates/ui-contract/src/contract/overlay.rs +++ b/crates/ui-contract/src/contract/overlay.rs @@ -28,7 +28,7 @@ pub(crate) use placement::{measuring_room, region_for, resolve_anchor, screen_fo pub(crate) use popups::dwell; pub use popups::{HOLD, Overlays, PopupHandle}; pub(crate) use popups::{apply_closes, begin_owner, note_layer_closed, open_map, popup_layer_open, popup_shown, popups_shown, write_open}; -pub use props::{Dismiss, Outside, Overlay, PlacementChange, PlacementKind}; +pub use props::{Dismiss, OpenerEscape, Outside, Overlay, PlacementChange, PlacementKind}; pub(crate) use toggles::{ToggleDecl, drive_toggles, has_toggle_nodes}; pub(crate) use ui::OverlayOwner; pub use ui::OverlayUi; diff --git a/crates/ui-contract/src/contract/overlay/dismissal.rs b/crates/ui-contract/src/contract/overlay/dismissal.rs index 627f6a5e87..f7733a8bb4 100644 --- a/crates/ui-contract/src/contract/overlay/dismissal.rs +++ b/crates/ui-contract/src/contract/overlay/dismissal.rs @@ -1,7 +1,7 @@ //! When a layer closes by itself (15.4): presses outside, Escape, and activations that keep it open. use super::host::{Layer, LayerMemory}; -use super::props::Outside; +use super::props::{OpenerEscape, Outside}; use crate::contract::{Component, Cx}; use crate::runtime::commands::FireSource; use crate::runtime::egui::pass; @@ -22,7 +22,7 @@ pub(super) fn dismissal( memory: &mut LayerMemory, ) -> Option { let dismiss = layer.overlay.dismiss; - // Both the Escape rule and the focus rule read the same fact: whether the focus is in the layer. + // Both start from actual layer membership; any opt-in opener Escape eligibility is handled separately. let inside = focus::focus_in_layer(ctx, layer.id); let was_inside = memory.focus_inside; if let Some(now) = inside { @@ -121,7 +121,17 @@ fn escape(ctx: &Context, layer: &Layer<'_>, scope: Option, inside: // below): its card may have nothing to focus. So does a popup, whose body may have nothing to focus, and a // keep-anchor popup, which leaves the focus where it was. let owns_loose = layer.overlay.rank.is_modal() || layer.overlay.rank == Rank::Popup || policy.initial == Initial::KeepAnchor; - if inside != Some(true) && !(owns_loose && focus_in_no_layer(ctx)) { + // An opt-in opener rule is an Escape eligibility decision, not focus-scope membership. Match only the + // actual registered root of the explicit active opener, not a mutable scope-restoration opener or parent. + let opener = if layer.overlay.rank == Rank::Popup && layer.overlay.dismiss.opener_escape != OpenerEscape::Default { + layer.overlay.opener.as_ref().and_then(|first| { + let (opener, _) = first.active(ctx, None); + opener.enabled.then(|| focus::stop_rec(ctx, (opener.id, None))).flatten().filter(|rec| focus::focused_stop(ctx) == Some(rec.stop.key())) + }) + } else { + None + }; + if inside != Some(true) && !(owns_loose && focus_in_no_layer(ctx)) && opener.is_none() { return None; } // The focus may be in no record of the layer's host: the Escape is read from the events of the frame. @@ -140,7 +150,15 @@ fn escape(ctx: &Context, layer: &Layer<'_>, scope: Option, inside: } else { keys::scope_escape(ctx, policy.cancel, pointer::press_captured(ctx), false)? }; - matches!(step, craft_behavior::focus::EscapeStep::CloseScope).then_some(CloseReason::Escape) + if !matches!(step, craft_behavior::focus::EscapeStep::CloseScope) { + return None; + } + if layer.overlay.dismiss.opener_escape == OpenerEscape::CloseAndBlur + && let Some(opener) = opener + { + focus::surrender_stop(ctx, opener.stop.key()); + } + Some(CloseReason::Escape) } impl Cx<'_, C> { diff --git a/crates/ui-contract/src/contract/overlay/props.rs b/crates/ui-contract/src/contract/overlay/props.rs index 6357f13eba..863072eaef 100644 --- a/crates/ui-contract/src/contract/overlay/props.rs +++ b/crates/ui-contract/src/contract/overlay/props.rs @@ -28,6 +28,26 @@ pub enum Outside { Absorb, } +/// What an untaken Escape at a popup's explicit registered opener does. This does not make the opener a member +/// of the popup's focus scope or change its Tab order; the focus policy's `CancelRule::Ignore` still wins. +/// +/// `Default` is the focus policy's own eligibility: an untaken Escape reaches the top layer while the focus is in its +/// scope, in no layer at all, or on the opener of a scope that opens with `Initial::KeepAnchor` +/// (`focus::focus_in_layer` counts that opener). [`Overlay::popover`] normally opens with `Initial::First`. If a +/// popover opts into `Initial::Keep` and leaves focus on its opener in another layer, `Default` does not make that +/// opener eligible for dismissal. `Close` and `CloseAndBlur` opt into dismissal from that opener. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +pub enum OpenerEscape { + /// Use the existing focus-policy eligibility; no additional opener rule. + #[default] + Default, + /// Close from the exact registered opener, without an extra focus change. + Close, + /// Close from that opener and leave its key focus, without focusing or clearing any other stop. + CloseAndBlur, +} + /// When a layer closes by itself. Escape goes through the focus policy's `CancelRule`. #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] @@ -38,6 +58,8 @@ pub struct Dismiss { pub enter: bool, /// Focus moved out of the layer's scope. pub focus_left: bool, + /// Additional Escape eligibility at the exact registered opener of a popup; unchanged by default. + pub opener_escape: OpenerEscape, /// A component inside was activated. An opener whose activation toggled its popup (a trigger, `Popup::toggle`) and /// a row that keeps the chain open (`Cx::keep_open`) do not count. pub on_activate: bool, @@ -52,7 +74,16 @@ pub struct Dismiss { impl Dismiss { /// An outside press or a command closes; nothing else does. pub const fn new() -> Self { - Dismiss { outside: Outside::Close, enter: false, focus_left: false, on_activate: false, anchor_gone: true, commands: true, timeout: None } + Dismiss { + outside: Outside::Close, + enter: false, + focus_left: false, + opener_escape: OpenerEscape::Default, + on_activate: false, + anchor_gone: true, + commands: true, + timeout: None, + } } /// Sets what an outside press does. @@ -73,6 +104,13 @@ impl Dismiss { self } + /// Chooses what an untaken Escape at a popup's explicit registered opener does, independently of traversal + /// and the usual restoration policy. Only that exact root stop qualifies, never another stop of its parent. + pub const fn opener_escape(mut self, policy: OpenerEscape) -> Self { + self.opener_escape = policy; + self + } + /// Closes when a component inside is activated, except an opener toggling its popup. pub const fn on_activate(mut self, on: bool) -> Self { self.on_activate = on; diff --git a/crates/ui-contract/src/contract/steps/report.rs b/crates/ui-contract/src/contract/steps/report.rs index 726c79d1fa..2b4641ae2e 100644 --- a/crates/ui-contract/src/contract/steps/report.rs +++ b/crates/ui-contract/src/contract/steps/report.rs @@ -90,6 +90,14 @@ fn register_validity(p: &dyn ErasedPass<'_>) -> Option<(String, bool)> { Some((text, shown)) } +/// Records the component's command for the inspected region. Outside a recording nothing keeps it, so the command is +/// not cloned. +fn note_command(core: &CxCore<'_>) { + if inspect::recording(&core.ctx) { + inspect::note_command(&core.ctx, core.id, core.command.as_deref().map(|command| (*command.command).clone())); + } +} + /// `validity` is the validity message as text: the node's description when the component gives none. fn report_access(p: &dyn ErasedPass<'_>, facts: &TypeFacts, input: &ReportIn<'_>, validity: Option) { let core = p.core_ref(); @@ -115,7 +123,7 @@ fn report_access(p: &dyn ErasedPass<'_>, facts: &TypeFacts, input: &ReportIn<'_> let resolved = core.resolved; // Before any return: a component without an AccessKit node (merged, or AccessKit off) still records its command // for the inspected region, which keytips place their badges by. - inspect::note_command(ctx, id, core.command.as_deref().map(|command| (*command.command).clone())); + note_command(core); let paint = core.paint.borrow(); if role == Role::Merged { let facts = scope::Merged { diff --git a/crates/ui-contract/src/layout/body.rs b/crates/ui-contract/src/layout/body.rs index a98971add0..edf92773db 100644 --- a/crates/ui-contract/src/layout/body.rs +++ b/crates/ui-contract/src/layout/body.rs @@ -364,12 +364,31 @@ pub(crate) struct FlowStarts(IdMap); /// Where the next child placed in flow under `env` starts: `Some(edge)` while the body that places it has placed /// nothing yet in this sweep or run, with `after_rule` when a rule precedes that body's start (`Scoped::after_rule`); -/// `None` once a child took room there, and outside a body. +/// `None` once a child took room there, and outside a body. The children of a memoized view's content read the flow +/// they go on with (`Scoped::flow_of`). pub(crate) fn flow_start(ctx: &egui::Context, env: &Env) -> Option { - let body = env.flow_body?; + let body = env.flow_of()?; pass_state::with::(ctx, |starts| starts.0.get(&body).copied()) } +/// Opens the flow of the content of the memoized view `view`, which is placed in flow under `env`, and returns its id +/// (`Scoped::view_flow`); `None` when no flow places the view. The content's first child starts that flow when the +/// view starts the flow it stands in, after a rule when the view is; otherwise something precedes it there. +pub(crate) fn open_view_flow(ctx: &egui::Context, env: &Env, view: Id) -> Option { + env.flow_of()?; + let flow = sub(view, "flow"); + let start = flow_start(ctx, env); + pass_state::with::(ctx, |starts| match start { + Some(after_rule) => { + starts.0.insert(flow, after_rule); + } + None => { + starts.0.remove(&flow); + } + }); + Some(flow) +} + /// Whether the next child placed in flow under `env` starts its body's flow (`flow_start`). pub(crate) fn at_flow_start(ctx: &egui::Context, env: &Env) -> bool { flow_start(ctx, env).is_some() @@ -377,7 +396,7 @@ pub(crate) fn at_flow_start(ctx: &egui::Context, env: &Env) -> bool { /// A child took room in the flow of the body that places the children under `env`: its flow start closes. pub(crate) fn close_flow_start(ctx: &egui::Context, env: &Env) { - if let Some(body) = env.flow_body { + if let Some(body) = env.flow_of() { pass_state::with::(ctx, |starts| starts.0.remove(&body)); } } diff --git a/crates/ui-contract/src/layout/label.rs b/crates/ui-contract/src/layout/label.rs index 2c8f743d41..115472679b 100644 --- a/crates/ui-contract/src/layout/label.rs +++ b/crates/ui-contract/src/layout/label.rs @@ -3,26 +3,35 @@ use crate::runtime::layout_memory; use crate::runtime::memory::sub; use craft_behavior::{Flow, LabelColumn, LabelPlacement}; +use craft_theme::ControlSize; use egui::{Id, Ui, Vec2}; -/// Places a label of `label` size with baseline `label_baseline` and the control of the row `id` in `flow`'s -/// rect. The label's baseline follows the control baseline `record_control_baseline` stored last pass; on the -/// first appearance the tops align and the missing entry asks for one discard pass. -pub fn place_label(ui: &Ui, id: Id, column: &LabelColumn, flow: Flow, label: Vec2, label_baseline: f32) -> LabelPlacement { - let control_baseline = control_baseline(ui.ctx(), id, label, label_baseline); +/// Places a label of `label` size with baseline `label_baseline` and the control of `size` of the row `id` in `flow`'s +/// rect. The label's baseline follows the control baseline `record_control_baseline` stored last pass. On the row's +/// first appearance it follows the baseline the last control of `size` stored, and a control whose baseline differs +/// from that asks for one discard pass; where none is stored the tops align and the missing entry asks for one. +pub fn place_label(ui: &Ui, id: Id, size: ControlSize, column: &LabelColumn, flow: Flow, label: Vec2, label_baseline: f32) -> LabelPlacement { + let control_baseline = control_baseline(ui.ctx(), id, size, label, label_baseline); column.place(flow, label, label_baseline, control_baseline) } -/// Stores the distance from the top of the control of the row `id` to its first baseline, for the next -/// pass's `place_label`. -pub fn record_control_baseline(ui: &Ui, id: Id, baseline: f32) { - layout_memory::record(ui.ctx(), sub(id, "baseline"), Vec2::new(0.0, baseline)); +/// Stores the distance from the top of the control of `size` of the row `id` to its first baseline, for the next +/// pass's `place_label`, and for the first appearance of later rows with a control of `size`. +pub fn record_control_baseline(ui: &Ui, id: Id, size: ControlSize, baseline: f32) { + layout_memory::record_control_baseline(ui.ctx(), id, Some(size), baseline); } -/// The control's first baseline from its top, as `record_control_baseline` stored it last pass. A control that paints -/// no text stored its centre line instead; the label's baseline then sits where its text is centred on that line. -pub fn control_baseline(ctx: &egui::Context, id: Id, label: Vec2, label_baseline: f32) -> Option { - layout_memory::read(ctx, sub(id, "baseline")) +/// The first baseline of the control of `size` of the row `id`, from its top, as `record_control_baseline` stored it +/// last pass. A control that paints no text stored its center line instead; the label's baseline then sits where its +/// text is centered on that line. A row that stored neither (on its first appearance) takes the baseline the last +/// control of `size` stored before this pass, and its own baseline is compared with that one when it records. +pub fn control_baseline(ctx: &egui::Context, id: Id, size: ControlSize, label: Vec2, label_baseline: f32) -> Option { + let own = layout_memory::read(ctx, sub(id, "baseline")) .map(|size| size.y) - .or_else(|| layout_memory::read(ctx, sub(id, "centre")).map(|size| size.y + label_baseline - label.y / 2.0)) + .or_else(|| layout_memory::read(ctx, sub(id, "centre")).map(|size| size.y + label_baseline - label.y / 2.0)); + own.or_else(|| { + let typical = layout_memory::typical(ctx, layout_memory::control_baseline_kind(size))?; + layout_memory::assume(ctx, sub(id, "baseline"), typical); + Some(typical.y) + }) } diff --git a/crates/ui-contract/src/layout/mod.rs b/crates/ui-contract/src/layout/mod.rs index 56f35ae858..c467770a73 100644 --- a/crates/ui-contract/src/layout/mod.rs +++ b/crates/ui-contract/src/layout/mod.rs @@ -26,7 +26,7 @@ pub(crate) use body::run_body; pub(crate) use body::{ BodyLine, BracketTook, HeldKind, InFlow, ask_shortfall, at_flow_start, close_first_line, close_flow_start, count_fill_view, counting_fills, fill_share, fill_size, flow_fill_room, flow_region, flow_room, flow_start, grid_cell, held_kind, in_grid_content_column, leaf_fill_room, - members_line, open_first_lines, open_view_fill, place_in_cell, report_bracket_control, report_fill_least, report_held, report_least, - report_shrink, row_alone_room, run_body_measured, shares_y, shrink_cap, take_bracket, take_cell, take_in_flow, take_shortfall, take_view_fill, - view_room, + members_line, open_first_lines, open_view_fill, open_view_flow, place_in_cell, report_bracket_control, report_fill_least, report_held, + report_least, report_shrink, row_alone_room, run_body_measured, shares_y, shrink_cap, take_bracket, take_cell, take_in_flow, take_shortfall, + take_view_fill, view_room, }; diff --git a/crates/ui-contract/src/runtime/access/scope.rs b/crates/ui-contract/src/runtime/access/scope.rs index f1409fc0f9..8a8785c050 100644 --- a/crates/ui-contract/src/runtime/access/scope.rs +++ b/crates/ui-contract/src/runtime/access/scope.rs @@ -155,6 +155,8 @@ struct Scope { /// The screen y of the top of the rect the label step placed the controls in; the recorded baseline and centre /// are stored measured from it. control_top: f32, + /// The size of the controls the label step placed: the recorded baseline is also noted for rows of that size. + control_size: Option, /// The screen y of the bottom of the first control that reported its line: the label's line is that control's. first_bottom: Option, /// The screen y of the first baseline of the first control on the first line. @@ -247,6 +249,7 @@ pub(crate) fn begin(ctx: &Context, container: Id, owner: Id, kind: Kind) { nodes: Vec::new(), open: Vec::new(), control_top: 0.0, + control_size: None, first_bottom: None, baseline: None, centre: None, @@ -338,11 +341,12 @@ fn report_unnamed(ctx: &Context, unnamed: Option) { /// Sets the screen y of the top of the rect the label step of `container` placed its controls in. The label lines up /// with a baseline measured from there: a control that sits lower in that rect (a short piece a row centres beside a -/// taller one) reports a baseline further down. -pub(crate) fn place_controls(ctx: &Context, container: Id, top: f32) { +/// taller one) reports a baseline further down. `size` is the size of the controls. +pub(crate) fn place_controls(ctx: &Context, container: Id, top: f32, size: craft_theme::ControlSize) { pass_state::with::(ctx, |stack| { if let Some(scope) = stack.0.iter_mut().rev().find(|scope| scope.container == container && matches!(scope.kind, Kind::Label(_))) { scope.control_top = top; + scope.control_size = Some(size); } }); } @@ -703,7 +707,7 @@ pub(crate) fn finish(ctx: &Context, container: Id, merged: Option) { crate::runtime::focus::request(ctx, only.inner_stop.unwrap_or(crate::runtime::focus::FocusTarget::Id(only.id))); } if let Some(baseline) = scope.baseline { - layout_memory::record(ctx, sub(scope.container, "baseline"), Vec2::new(0.0, baseline - scope.control_top)); + layout_memory::record_control_baseline(ctx, scope.container, scope.control_size, baseline - scope.control_top); } if let (None, Some(centre)) = (scope.baseline, scope.centre) { layout_memory::record(ctx, sub(scope.container, "centre"), Vec2::new(0.0, centre - scope.control_top)); diff --git a/crates/ui-contract/src/runtime/egui/alt_code.rs b/crates/ui-contract/src/runtime/egui/alt_code.rs index cbb33ade2c..4d6b7f4730 100644 --- a/crates/ui-contract/src/runtime/egui/alt_code.rs +++ b/crates/ui-contract/src/runtime/egui/alt_code.rs @@ -1,6 +1,6 @@ //! Alt+numpad code entry, folded into the input events in the raw-input step. //! -//! Keypad digits typed with Alt as the only modifier held collect into a decimal code; letting go of Alt types the character +//! Digits typed with Alt as the only modifier held collect into a decimal code; letting go of Alt types the character //! the code names (`craft_codepage::alt_code_char`: `0233` is é in Windows-1252, `233` is Θ in OEM 437). The digits' //! presses and their own text (Linux sends it with Alt held) reach nothing. The step runs before the IME and key //! stages, so every field and the canvas read the result as typed text, and only the first pass of a frame gets the @@ -18,6 +18,9 @@ const MAX_DIGITS: usize = 8; pub(crate) struct AltCodeEntry { /// The digits typed while Alt is held. code: String, + /// A digit of the code came from the top row (its physical key is `Num0`…`Num9`, a keypad digit's is + /// `Numpad0`…`Numpad9`). Windows composes keypad codes only, so it sends no character of its own for this code. + top_row: bool, /// A digit was typed in this Alt hold, also when the code was then dropped (a focus loss): the Alt release is no /// lone Alt, since the key stage never saw the digits. digits_typed: bool, @@ -25,20 +28,44 @@ pub(crate) struct AltCodeEntry { swallow_text: bool, /// What the last code typed, for the character a platform composes itself and sends after it. echo: Option, + /// The key of the press that carries the platform's composed character, whose release is left out with it. + carrier: Option, } -/// The character an Alt code typed, kept until the next key or pointer press. +/// The character an Alt code typed, kept until the next key or pointer press or a focus loss. struct Echo { typed: String, /// The code names a byte of the code pages (1–255): the platform's own character for it wins over ours, since it /// knows the system's code pages (double-byte ones too) better than the app's locale guess. byte_code: bool, + /// The platform composes this code itself and sends its character after it: Windows, for a code typed on the + /// keypad. + native: bool, + /// The keys egui names the platform's character by, for the press that can carry it on Windows: the key of our + /// character, and for a code above 255 the key of the character of the byte Windows reduces it to. + carriers: Vec, } -/// Folds Alt+numpad entry out of `events` and into text events, decoding with `pages`. Only a digit whose physical key -/// is on the keypad (`Key::Numpad0`…`Numpad9`) enters a code, so a main-row Alt+digit stays a shortcut, and a press -/// with no physical key (injected input) is no keypad digit. `os` is the platform the events -/// come from: on Windows (a browser on Windows too) the platform composes the code itself and sends its character +impl Echo { + /// The echo of `typed`, the character `code` names in `pages`. `native` tells whether the platform composes the + /// code too. + fn new(typed: char, code: &str, pages: AltCodePages, native: bool) -> Self { + let value = code.trim_start_matches('0').parse::().ok(); + let byte_code = value.is_some_and(|value| value <= 255); + let mut carriers: Vec = Key::from_name(&typed.to_string()).into_iter().collect(); + if let Some(value) = value.filter(|value| *value > 255) { + let byte = value % 256; + let byte_digits = if code.starts_with('0') { format!("0{byte}") } else { byte.to_string() }; + if let Some(key) = craft_codepage::alt_code_char(&byte_digits, pages.ansi, pages.oem).and_then(|c| Key::from_name(&c.to_string())) { + carriers.push(key); + } + } + Echo { typed: typed.to_string(), byte_code, native, carriers } + } +} + +/// Folds Alt+numpad entry out of `events` and into text events, decoding with `pages`. `os` is the platform the events +/// come from: on Windows (a browser on Windows too) the platform composes a keypad code itself and sends its character /// after the Alt release. Returns whether an Alt release in `events` ended a hold in which digits were typed (a code, /// or one a focus loss dropped), so the key stage does not take it for a lone Alt. The caller does not call it on macOS, where Option+digit types its own characters. /// @@ -51,28 +78,44 @@ pub(crate) fn fold(entry: &mut AltCodeEntry, events: &mut Vec, pages: Alt let mut out = Vec::with_capacity(events.len() + 1); for event in events.drain(..) { match &event { - Event::Key { key, physical_key, pressed: true, repeat, modifiers } => { + // On Windows the composed character can come on a press of its own after the Alt release, with no + // physical key and the key egui names the character by (`\` is `Key::Backslash`). It is no key the user + // pressed: the press and its release are left out, and the text that follows meets the echo. A press of + // another key with no physical key (one egui does not map, such as a JIS key) is the user's, and so is any + // such press after a top-row code, which Windows does not compose. + Event::Key { key, physical_key: None, pressed: true, repeat: false, .. } + if entry.echo.as_ref().is_some_and(|echo| echo.native && echo.carriers.contains(key)) => + { + entry.carrier = Some(*key); + continue; + } + Event::Key { key, physical_key: None, pressed: false, .. } if entry.carrier == Some(*key) => { + entry.carrier = None; + continue; + } + Event::Key { key, physical_key, pressed: true, repeat, modifiers, .. } => { entry.swallow_text = false; entry.echo = None; + // A carrier whose release never came (the platform dropped it with the held physical key's) does not + // take the release of a key pressed after it. + if !*repeat { + entry.carrier = None; + } match digit(*key).filter(|_| alt_only(modifiers) && !claimed(&event)) { - Some(d) if physical_key.is_some_and(on_keypad) => { + Some(d) => { // A held digit's auto-repeat adds nothing, as on Windows. if !*repeat && entry.code.len() < MAX_DIGITS { entry.code.push(d); } + entry.top_row |= physical_key.is_some_and(|physical| digit(physical).is_some()); entry.digits_typed = true; entry.swallow_text = true; continue; } - // A main-row digit is the app's shortcut and ends the entry: its press goes on to the key stage, - // and its own text (Linux and Windows send it with Alt held) is the chord's, typed nowhere. - Some(_) => { - entry.code.clear(); - entry.swallow_text = true; - } // Another key (Alt itself, a letter, a digit with Ctrl or Shift) ends the entry unfinished. None => { entry.code.clear(); + entry.top_row = false; // A new Alt hold starts clean: a release that went to another window ended the last one. if matches!(key, Key::AltLeft | Key::AltRight) && !*repeat { entry.digits_typed = false; @@ -87,8 +130,8 @@ pub(crate) fn fold(entry: &mut AltCodeEntry, events: &mut Vec, pages: Alt // The platform composed the same character: it is typed once. continue; } - if composes { - // On Windows the text after a code is the platform's character for it. For a code up to 255 + if echo.native { + // On Windows the text after a keypad code is the platform's character for it. For a code up to 255 // it replaces ours, which was typed just before with no key or click since; above 255 ours // stays (Windows reduces the code to a byte, Word types the Unicode character). if echo.byte_code && text.chars().count() == 1 { @@ -101,7 +144,8 @@ pub(crate) fn fold(entry: &mut AltCodeEntry, events: &mut Vec, pages: Alt } continue; } - // Linux and the BSDs compose nothing: a different text is what was typed next. + // Linux and the BSDs compose nothing, nor Windows a top-row code: a different text is what was + // typed next. } } Event::PointerButton { pressed: true, .. } => entry.echo = None, @@ -110,23 +154,28 @@ pub(crate) fn fold(entry: &mut AltCodeEntry, events: &mut Vec, pages: Alt // Focus in another window ends a code unfinished: Alt's release goes there. Event::WindowFocused(false) => { entry.code.clear(); + entry.top_row = false; entry.swallow_text = false; + entry.echo = None; + entry.carrier = None; } _ => {} } let released = alt_released(&event); out.push(event); + let mut top_row = false; if released { ended |= std::mem::take(&mut entry.digits_typed); + top_row = std::mem::take(&mut entry.top_row); } if released && !entry.code.is_empty() { let code = std::mem::take(&mut entry.code); + let native = composes && !top_row; // A digit's own text comes with its press, before Alt is let go: text after this is the platform's // composed character or what is typed next. A digit that sent no text must not cost the next one. entry.swallow_text = false; if let Some(c) = craft_codepage::alt_code_char(&code, pages.ansi, pages.oem) { - let byte_code = code.trim_start_matches('0').parse::().is_ok_and(|value| value <= 255); - entry.echo = Some(Echo { typed: c.to_string(), byte_code }); + entry.echo = Some(Echo::new(c, &code, pages, native)); out.push(Event::Text(c.to_string())); } } @@ -135,25 +184,8 @@ pub(crate) fn fold(entry: &mut AltCodeEntry, events: &mut Vec, pages: Alt ended } -/// Whether `physical` is a digit key of the numeric keypad. -fn on_keypad(physical: Key) -> bool { - matches!( - physical, - Key::Numpad0 - | Key::Numpad1 - | Key::Numpad2 - | Key::Numpad3 - | Key::Numpad4 - | Key::Numpad5 - | Key::Numpad6 - | Key::Numpad7 - | Key::Numpad8 - | Key::Numpad9 - ) -} - -/// The digit `key` adds to a code. egui names keypad and main-row digits alike as logical keys (`Key::Num0`…`Num9`); -/// `fold` tells them apart by the physical key (`on_keypad`). +/// The digit `key` adds to a code. egui's logical key is the same for keypad and top-row digits (`Key::Num0`…`Num9`), +/// so the top-row digits compose codes too; with Alt alone held they type nothing else. fn digit(key: Key) -> Option { let n = match key { Key::Num0 => 0, diff --git a/crates/ui-contract/src/runtime/egui/areas.rs b/crates/ui-contract/src/runtime/egui/areas.rs index 6774467e4d..d1d4c46eb9 100644 --- a/crates/ui-contract/src/runtime/egui/areas.rs +++ b/crates/ui-contract/src/runtime/egui/areas.rs @@ -188,6 +188,7 @@ pub(crate) fn show_body_layer(ctx: &Context, body_layer: BodyLayer, body: imp let BodyLayer { parent, layer, transform, at, clip, forward } = body_layer; ctx.set_transform_layer(layer, transform); ctx.set_sublayer(parent, layer); + crate::runtime::overlay::note_sublayer(ctx, layer, parent); egui::Area::new(layer.id) .fade_in(false) .order(layer.order) @@ -448,6 +449,12 @@ pub(crate) fn move_to_top(ctx: &Context, layer: LayerId) { ctx.move_to_top(layer); } +/// egui's own area order as of the running pass, bottom first: the order of the last pass, with the layers that first +/// showed in this one at the end. +pub(crate) fn area_order(ctx: &Context) -> Vec { + ctx.memory(|memory| memory.layer_ids().collect()) +} + /// Whether egui showed `layer` in the last pass. pub(crate) fn visible_last_frame(ctx: &Context, layer: LayerId) -> bool { ctx.memory(|memory| memory.areas().visible_last_frame(&layer)) diff --git a/crates/ui-contract/src/runtime/egui/fixture.rs b/crates/ui-contract/src/runtime/egui/fixture.rs index c41f3cf1be..9999ed43f1 100644 --- a/crates/ui-contract/src/runtime/egui/fixture.rs +++ b/crates/ui-contract/src/runtime/egui/fixture.rs @@ -1,5 +1,7 @@ //! The egui calls `craft_ui::testing` needs: frames, raw input and options that apps reach only through the runtime. +use egui::emath::TSTransform; +use egui::epaint::ClippedShape; use egui::{Context, Event, Key, Modifiers, Pos2, Rect, Shape, Ui, Vec2, ViewportCommand}; use std::sync::Arc; @@ -282,32 +284,63 @@ pub(crate) fn run_frame( } let mut flat = Vec::new(); for clipped in &output.shapes { - let mut shapes = Vec::new(); - flatten_ref(&clipped.shape, &mut shapes); - flat.extend(shapes.into_iter().map(|shape| (shape, clipped.clip_rect))); + flatten_ref(&clipped.shape, clipped.transform_after_tessellation, clipped.clip_rect, false, &mut flat); } + let (pixels_per_point, options) = (output.pixels_per_point, ctx.tessellation_options(|options| *options)); // A shape shows only inside its clip rect. let (bounds, overshoot): (Vec, Vec) = flat .iter() - .filter(|(shape, _)| !is_shadow(shape) && shape.visual_bounding_rect().is_finite()) - .map(|(shape, clip)| (shape.visual_bounding_rect().intersect(*clip), stroke_width(shape) / 2.0)) + .filter_map(|(shape, transform, clip, in_chunk)| { + if !fixture_draws(shape, *transform, *clip, *in_chunk, pixels_per_point, options) || is_shadow(shape) { + return None; + } + let rect = match shape { + Shape::Text(text) if *transform != TSTransform::IDENTITY && options.round_text_to_pixels => { + let mut text = text.clone(); + text.pos = egui::emath::GuiRounding::round_to_pixels(text.pos, pixels_per_point); + text.visual_bounding_rect() + } + _ => shape.visual_bounding_rect(), + }; + if !rect.is_finite() { + return None; + } + let moved = *transform * rect; + // egui mirrors the vertices of a shape it draws under a negative scale, so its drawn rect is the moved one's + // corners in order. A callback keeps the moved rect as egui passes it on. + let flipped = transform.scaling < 0.0 && !matches!(shape, Shape::Callback(_)); + let moved = if flipped { Rect::from_two_pos(moved.min, moved.max) } else { moved }; + Some((moved.intersect(*clip), stroke_width(shape) * transform.scaling.abs() / 2.0)) + }) .filter(|(rect, _)| rect.is_finite() && rect.min.x <= rect.max.x && rect.min.y <= rect.max.y) .unzip(); let mut painted_before: std::collections::HashMap = std::collections::HashMap::new(); let texts = flat .iter() - .filter_map(|(shape, clip)| match shape { + .filter_map(|(shape, transform, clip, in_chunk)| match shape { Shape::Text(text) => { let nth = painted_before.entry(Arc::as_ptr(&text.galley) as usize).or_insert(0); let full = super::painted::full_text_of_painted(ctx, &text.galley, *nth); *nth += 1; + if !fixture_draws(shape, *transform, *clip, *in_chunk, pixels_per_point, options) { + return None; + } let baseline = text.galley.rows.first().map_or(0.0, |placed| match placed.row.glyphs.first() { Some(glyph) => placed.pos.y + glyph.pos.y, None => placed.pos.y + placed.row.size.y, }); + // egui snaps a text origin before a paint transform; an untransformed text is reported at its own origin. + let pos = if options.round_text_to_pixels && *transform != TSTransform::IDENTITY { + egui::emath::GuiRounding::round_to_pixels(text.pos, pixels_per_point) + } else { + text.pos + }; Some(PaintedText { - rect: text.galley.rect.translate(text.pos.to_vec2()), - baseline: text.pos.y + baseline, + rect: { + let moved = *transform * text.galley.rect.translate(pos.to_vec2()); + Rect::from_two_pos(moved.min, moved.max) + }, + baseline: transform.scaling * (pos.y + baseline) + transform.translation.y, elided: full.is_some(), text: full.unwrap_or_else(|| text.galley.job.text.clone()), clip: *clip, @@ -454,6 +487,7 @@ pub(crate) fn reordered_fonts() -> egui::FontDefinitions { } /// Runs one frame like `run_frame` and returns the shapes it painted, nested shapes flattened. +/// Mirrored text returns its visible underlines as separate line segments immediately after the text, whose underline is `Stroke::NONE`. pub(crate) fn run_frame_shapes(ctx: &Context, time: f64, screen: Vec2, ui: impl FnMut(&mut Ui)) -> Vec { let screen = Rect::from_min_size(Pos2::ZERO, screen); let children = open_children(ctx, egui::ViewportId::ROOT); @@ -466,10 +500,106 @@ pub(crate) fn run_frame_shapes(ctx: &Context, time: f64, screen: Vec2, ui: impl let mut output = drive(|| run_ui(ctx, input, &children, ui)); output.textures_delta.clear(); let mut flat = Vec::new(); + let options = ctx.tessellation_options(|options| *options); for clipped in output.shapes { - flatten(clipped.shape, &mut flat); + flatten(clipped, output.pixels_per_point, options, &mut flat); + } + flat.into_iter().map(|(shape, _)| shape).collect() +} + +/// Whether egui's tessellator draws `shape` moved by `transform` inside `clip`. Under a negative scale, egui tessellates +/// the shape against the clip mapped back through the inverse transform, which comes out inverted, so its coarse culling +/// keeps only shapes whose bounds enclose that clip. This asks the tessellator itself. +fn egui_draws(shape: &Shape, transform: TSTransform, clip: Rect, pixels_per_point: f32, options: egui::epaint::TessellationOptions) -> bool { + if matches!(shape, Shape::Callback(_)) { + return true; + } + let clipped = ClippedShape { clip_rect: clip, shape: shape.clone(), transform_after_tessellation: transform }; + let options = egui::epaint::TessellationOptions { debug_paint_clip_rects: false, ..options }; + let mut tessellator = egui::epaint::Tessellator::new(pixels_per_point, options, [1, 1], Vec::new()); + let mut primitives = Vec::new(); + tessellator.tessellate_clipped_shape(clipped, &mut primitives); + primitives.into_iter().any(|primitive| { + primitive.clip_rect.is_positive() + && match primitive.primitive { + egui::epaint::Primitive::Mesh(mesh) => !mesh.is_empty() && mesh.calc_bounds().intersects(primitive.clip_rect), + egui::epaint::Primitive::Callback(_) => true, + } + }) +} + +fn fixture_draws( + shape: &Shape, + transform: TSTransform, + clip: Rect, + in_chunk: bool, + pixels_per_point: f32, + options: egui::epaint::TessellationOptions, +) -> bool { + // A top-level shape that egui paints untransformed is reported as before, whatever its clip rect. + if !in_chunk && transform == TSTransform::IDENTITY { + return true; + } + // An untransformed chunk member is reported like a top-level shape, invisible paint included, unless its clip hides it. + if transform == TSTransform::IDENTITY { + let bounds = shape.visual_bounding_rect(); + return clip.is_positive() && (!bounds.is_finite() || bounds.intersects(clip)); + } + transform.is_valid() && clip.is_positive() && egui_draws(shape, transform, clip, pixels_per_point, options) +} + +fn transform_fixture_shape(shape: &mut Shape, transform: TSTransform) { + let corner_radius = if let Shape::Rect(rect) = shape { Some(rect.corner_radius) } else { None }; + shape.transform(transform); + if transform.scaling >= 0.0 { + return; + } + match shape { + Shape::Circle(circle) => { + circle.radius = -circle.radius; + circle.stroke.width = -circle.stroke.width; + } + Shape::Ellipse(ellipse) => { + ellipse.radius = -ellipse.radius; + ellipse.stroke.width = -ellipse.stroke.width; + } + Shape::LineSegment { stroke, .. } => stroke.width = -stroke.width, + Shape::Path(path) => path.stroke.width = -path.stroke.width, + Shape::QuadraticBezier(bezier) => bezier.stroke.width = -bezier.stroke.width, + Shape::CubicBezier(bezier) => bezier.stroke.width = -bezier.stroke.width, + Shape::Band(band) => { + band.points.reverse(); + for point in &mut band.points { + std::mem::swap(&mut point.y.min, &mut point.y.max); + } + band.stroke.width = -band.stroke.width; + } + Shape::Rect(rect) => { + rect.rect = Rect::from_two_pos(rect.rect.min, rect.rect.max); + if let Some(brush) = &mut rect.brush { + let uv = &mut Arc::make_mut(brush).uv; + std::mem::swap(&mut uv.min, &mut uv.max); + } + if let Some(corner_radius) = corner_radius { + rect.corner_radius = egui::CornerRadius { nw: corner_radius.se, ne: corner_radius.sw, sw: corner_radius.ne, se: corner_radius.nw } + * transform.scaling.abs(); + } + rect.stroke.width = -rect.stroke.width; + rect.blur_width = -rect.blur_width; + } + Shape::Text(text) => { + text.underline.width = -text.underline.width; + let galley = Arc::make_mut(&mut text.galley); + galley.rect = Rect::from_two_pos(galley.rect.min, galley.rect.max); + galley.mesh_bounds = Rect::from_two_pos(galley.mesh_bounds.min, galley.mesh_bounds.max); + for placed in &mut galley.rows { + let row = Arc::make_mut(&mut placed.row); + let bounds = &mut row.visuals.mesh_bounds; + *bounds = Rect::from_two_pos(bounds.min, bounds.max); + } + } + _ => {} } - flat } /// A blurred rect: the shadow of a surface. @@ -488,19 +618,137 @@ fn stroke_width(shape: &Shape) -> f32 { } } -fn flatten_ref<'a>(shape: &'a Shape, out: &mut Vec<&'a Shape>) { +/// Pushes each shape in `shape`, nested shapes flattened, with the transform and clip rect egui paints it under: a paint +/// chunk's member moves by its own transform after the chunk's and shows only inside its own clip rect within the chunk's. +fn flatten_ref<'a>(shape: &'a Shape, transform: TSTransform, clip: Rect, in_chunk: bool, out: &mut Vec<(&'a Shape, TSTransform, Rect, bool)>) { match shape { - Shape::Vec(shapes) => shapes.iter().for_each(|shape| flatten_ref(shape, out)), - Shape::PaintChunk(shapes) => shapes.iter().for_each(|clipped| flatten_ref(&clipped.shape, out)), - other => out.push(other), + Shape::Vec(shapes) => shapes.iter().for_each(|shape| flatten_ref(shape, transform, clip, in_chunk, out)), + Shape::PaintChunk(shapes) => shapes.iter().for_each(|clipped| { + let clip = clip.intersect(transform * clipped.clip_rect); + flatten_ref(&clipped.shape, transform * clipped.transform_after_tessellation, clip, true, out); + }), + other => out.push((other, transform, clip, in_chunk)), } } -pub(crate) fn flatten(shape: Shape, out: &mut Vec) { +/// Pushes each shape in `clipped`, nested shapes flattened as [`flatten_ref`] lists them, moved by its transform, with +/// the clip rect it shows inside. +/// Mirrored text with a visible underline uses `Stroke::NONE`. Its transformed underlines follow it as separate line segments under the same clip. +pub(crate) fn flatten(clipped: ClippedShape, pixels_per_point: f32, options: egui::epaint::TessellationOptions, out: &mut Vec<(Shape, Rect)>) { + flatten_owned(clipped.shape, clipped.transform_after_tessellation, clipped.clip_rect, false, pixels_per_point, options, out); +} + +fn flatten_owned( + shape: Shape, + transform: TSTransform, + clip: Rect, + in_chunk: bool, + pixels_per_point: f32, + options: egui::epaint::TessellationOptions, + out: &mut Vec<(Shape, Rect)>, +) { match shape { - Shape::Vec(shapes) => shapes.into_iter().for_each(|shape| flatten(shape, out)), - Shape::PaintChunk(shapes) => shapes.iter().for_each(|clipped| flatten(clipped.shape.clone(), out)), - other => out.push(other), + Shape::Vec(shapes) => shapes.into_iter().for_each(|shape| flatten_owned(shape, transform, clip, in_chunk, pixels_per_point, options, out)), + Shape::PaintChunk(shapes) => shapes.iter().for_each(|clipped| { + let clip = clip.intersect(transform * clipped.clip_rect); + let transform = transform * clipped.transform_after_tessellation; + flatten_owned(clipped.shape.clone(), transform, clip, true, pixels_per_point, options, out); + }), + mut other => { + if !fixture_draws(&other, transform, clip, in_chunk, pixels_per_point, options) { + return; + } + let mut underlines = Vec::new(); + if transform.scaling < 0.0 + && let Shape::Text(text) = &mut other + && !text.underline.is_empty() + && !text.galley.is_empty() + && text.opacity_factor > 0.0 + { + let pos = if options.round_text_to_pixels { egui::emath::GuiRounding::round_to_pixels(text.pos, pixels_per_point) } else { text.pos }; + let rotation = egui::emath::Rot2::from_angle(text.angle); + let source_clip = transform.inverse() * clip; + for row in &text.galley.rows { + if row.visuals.mesh.is_empty() { + continue; + } + let mut rect = row.visuals.mesh_bounds; + if text.angle != 0.0 { + rect = rect.rotate_bb(rotation); + } + rect = rect.translate((pos + rotation * row.pos.to_vec2()).to_vec2()); + if options.coarse_tessellation_culling && !source_clip.intersects(rect) { + continue; + } + let mut tessellator = egui::epaint::Tessellator::new(pixels_per_point, options, [1, 1], Vec::new()); + tessellator.set_clip_rect(source_clip); + let mut mesh = egui::epaint::Mesh::default(); + tessellator.tessellate_line_segment([rect.left_bottom(), rect.right_bottom()], text.underline, &mut mesh); + if mesh.is_empty() { + continue; + } + for vertex in &mut mesh.vertices { + vertex.pos = transform * vertex.pos; + } + underlines.push(Shape::Mesh(Arc::new(mesh))); + } + text.underline = egui::Stroke::NONE; + } + if transform != TSTransform::IDENTITY { + if options.round_text_to_pixels + && let Shape::Text(text) = &mut other + { + text.pos = egui::emath::GuiRounding::round_to_pixels(text.pos, pixels_per_point); + } + transform_fixture_shape(&mut other, transform); + if transform.scaling != 1.0 + && let Shape::Text(text) = &mut other + { + for placed in &mut Arc::make_mut(&mut text.galley).rows { + let row = Arc::make_mut(&mut placed.row); + for glyph in &mut row.glyphs { + glyph.pos *= transform.scaling; + glyph.advance_width *= transform.scaling; + glyph.line_height *= transform.scaling; + glyph.font_ascent *= transform.scaling; + glyph.font_height *= transform.scaling; + glyph.font_face_ascent *= transform.scaling; + glyph.font_face_height *= transform.scaling; + glyph.uv_rect.offset *= transform.scaling; + glyph.uv_rect.size *= transform.scaling; + if transform.scaling < 0.0 { + let rect = glyph.logical_rect(); + let uv_from = glyph.pos + glyph.uv_rect.offset; + let uv = Rect::from_two_pos(uv_from, uv_from + glyph.uv_rect.size); + glyph.advance_width = glyph.advance_width.abs(); + glyph.line_height = glyph.line_height.abs(); + glyph.font_ascent = glyph.font_ascent.abs(); + glyph.font_height = glyph.font_height.abs(); + glyph.font_face_ascent = glyph.font_face_ascent.abs(); + glyph.font_face_height = glyph.font_face_height.abs(); + glyph.pos = Rect::from_two_pos(rect.min, rect.max).min + egui::vec2(0.0, glyph.font_ascent); + glyph.uv_rect.offset = uv.min - glyph.pos; + glyph.uv_rect.size = uv.size(); + } + } + if transform.scaling < 0.0 { + let offset = row.size; + placed.pos += offset; + row.size = -offset; + for glyph in &mut row.glyphs { + glyph.pos -= offset; + } + for vertex in &mut row.visuals.mesh.vertices { + vertex.pos -= offset; + } + row.visuals.mesh_bounds = row.visuals.mesh_bounds.translate(-offset); + } + } + } + } + out.push((other, clip)); + out.extend(underlines.into_iter().map(|shape| (shape, clip))); + } } } diff --git a/crates/ui-contract/src/runtime/egui/widgets.rs b/crates/ui-contract/src/runtime/egui/widgets.rs index b4f84f054f..950054ab3d 100644 --- a/crates/ui-contract/src/runtime/egui/widgets.rs +++ b/crates/ui-contract/src/runtime/egui/widgets.rs @@ -4,19 +4,22 @@ use egui::{AreaState, Context, Id, Order, Rect}; -/// The interact rects, in screen space, of the interactive egui widgets of the running pass that egui's hit test +/// The ids and interact rects, in screen space, of the interactive egui widgets of the running pass that egui's hit test /// puts above the widget `below`: those on a layer higher in its order, or later on `below`'s layer. A layer that is /// not interactable is click-through and holds none. Widgets in `skip` are left out. Empty when `below` is not shown /// in the pass. -pub(crate) fn above(ctx: &Context, below: Id, skip: &[Id]) -> Vec { +pub(crate) fn above(ctx: &Context, below: Id, skip: &[Id]) -> Vec<(Id, Rect)> { let (base, layers) = ctx.viewport(|viewport| { let widgets = &viewport.this_pass.widgets; let Some(base) = widgets.get(below).map(|rect| rect.layer_id) else { return (None, Vec::new()) }; let mut layers = Vec::new(); for (layer, rects) in widgets.layers().filter(|(layer, _)| layer.order.allow_interaction()) { let after = if *layer == base { rects.iter().position(|rect| rect.id == below).map_or(rects.len(), |at| at + 1) } else { 0 }; - let hits: Vec = - rects[after..].iter().filter(|rect| rect.sense.interactive() && !skip.contains(&rect.id)).map(|rect| rect.interact_rect).collect(); + let hits: Vec<(Id, Rect)> = rects[after..] + .iter() + .filter(|rect| rect.sense.interactive() && !skip.contains(&rect.id)) + .map(|rect| (rect.id, rect.interact_rect)) + .collect(); if !hits.is_empty() { layers.push((*layer, hits)); } @@ -36,7 +39,7 @@ pub(crate) fn above(ctx: &Context, below: Id, skip: &[Id]) -> Vec { continue; } let to_screen = ctx.layer_transform_to_global(layer).unwrap_or(egui::emath::TSTransform::IDENTITY); - found.extend(hits.into_iter().map(|rect| to_screen * rect)); + found.extend(hits.into_iter().map(|(id, rect)| (id, to_screen * rect))); } found } diff --git a/crates/ui-contract/src/runtime/env.rs b/crates/ui-contract/src/runtime/env.rs index 6b36f4c164..f2748967b4 100644 --- a/crates/ui-contract/src/runtime/env.rs +++ b/crates/ui-contract/src/runtime/env.rs @@ -80,10 +80,11 @@ pub(crate) struct FooterSlotOf { /// The flow facts of the body around a memoized view that its content is laid out by: whether that body is a /// content-sized or a given column, the axes it sizes from its content, the axis it shares among the children that fill /// it, whether the view runs in a least measure, the -/// axes a scrolling body leaves unbounded, whether it fills a beside label's cell and whether its leaves fit the view's -/// room (`Scoped::view_fits`). A measuring run of a container or a row lays the view out under other facts than its -/// real run, so they are a fact of the view's place, which each kind of run compares on its own (`lazy::Place`, -/// `lazy::Measured`), not of its key. +/// axes a scrolling body leaves unbounded, whether it fills a beside label's cell, whether its leaves fit the view's +/// room (`Scoped::view_fits`), and where the view stands in that body's flow: whether it starts the flow, after a rule +/// or not (`layout::flow_start`), and the gap a `Stack` body leaves before it (`Scoped::flow_gap`). A measuring run of a +/// container or a row lays the view out under other facts than its real run, so they are a fact of the view's place, +/// which each kind of run compares on its own (`lazy::Place`, `lazy::Measured`), not of its key. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub(crate) struct Flow { content_column: bool, @@ -95,6 +96,17 @@ pub(crate) struct Flow { cell_fills: bool, fits: bool, egui_cell: bool, + start: Option, + /// The bits of the gap, so the facts compare exactly. + gap: Option, +} + +impl Flow { + /// These facts for a view that stands at `start` in the flow of the body around it (`layout::flow_start`), with + /// `gap` the gap a `Stack` body leaves before it (`Scoped::flow_gap`). + pub(crate) fn in_flow(self, start: Option, gap: Option) -> Flow { + Flow { start, gap: gap.map(f32::to_bits), ..self } + } } /// The values of an env. @@ -173,8 +185,13 @@ pub struct Scoped { /// and the one a child placed in flow closes. pub(crate) flow_body: Option, /// The `Stack` body that places the scope's direct children in flow and the gap it leaves between them; it holds - /// only while that body is `flow_body`. + /// only while that body is the scope's flow (`flow_of`). pub(crate) stack_gap: Option<(Id, f32)>, + /// The flow of a memoized view's content, when the view stands in a body's flow: the scope's direct children go on + /// with that body's flow from where the view stands in it. The first one starts the flow when the view does + /// (`layout::open_view_flow`), and each one follows the gap a `Stack` body left before the view (`stack_gap`), as + /// the same children shown in that body without the view would. + pub(crate) view_flow: Option, /// A rule precedes the start of the body this scope opens: its container draws one under its header, or draws /// nothing of its own and itself follows one. The body's layout opens its flow start with it. pub(crate) after_rule: bool, @@ -488,6 +505,7 @@ impl Scoped { self.row_line = None; self.first_line = None; self.flow_body = None; + self.view_flow = None; self.column_row = false; self.fill_body = None; self.fill_share = None; @@ -508,6 +526,7 @@ impl Scoped { || self.row_line.is_some() || self.first_line.is_some() || self.flow_body.is_some() + || self.view_flow.is_some() || self.column_row || self.fill_body.is_some() || self.fill_share.is_some() @@ -529,10 +548,14 @@ impl Scoped { /// body, given its share as its room, as the child shown without the view would be. A view that is a unit of a /// shrinking `Row` that does not share its width sizes from its content along x, as the row counted it: a child /// that fills there takes its measured width, not the row's flow region a view the row does not narrow is shown in. - pub(crate) fn start_view_room(&mut self, view: Id) { + /// + /// `flow` is the flow the content's direct children go on with (`view_flow`, from `layout::open_view_flow`): they + /// keep the gap a `Stack` body around the view leaves before it. + pub(crate) fn start_view_room(&mut self, view: Id, flow: Option) { let fits = self.view_fits(); let row_unit = matches!(self.shrink, Some(Shrink::Count(_) | Shrink::Least(_) | Shrink::Apply(_))); let shares = self.shares(); + let gap = self.flow_gap(); let (content_column, given_column, egui_cell) = (self.content_column, self.given_column, self.egui_cell); // The view stands on the line of the row around it only to fill it, as a levelled unit does: a fill-width row in // it (a bar in a shell slot) takes the line's height and centres on it, as shown without the view; its children @@ -541,6 +564,8 @@ impl Scoped { self.start_room(); (self.content_column, self.given_column, self.egui_cell) = (content_column, given_column, egui_cell); self.row_line = line; + self.view_flow = flow; + self.stack_gap = flow.zip(gap); self.fill_view = shares.map(|axis| (view, axis)); if fits { self.shrink = Some(Shrink::Fit); @@ -550,6 +575,21 @@ impl Scoped { } } + /// The flow that places the scope's direct children: the enclosing body's (`flow_body`), else the flow a memoized + /// view's content goes on with (`view_flow`). + pub(crate) const fn flow_of(&self) -> Option { + match self.flow_body { + Some(body) => Some(body), + None => self.view_flow, + } + } + + /// The gap a `Stack` body leaves before each of the scope's direct children it places in flow after its first + /// (`stack_gap`), while that body is the scope's flow (`flow_of`). + pub(crate) fn flow_gap(&self) -> Option { + self.stack_gap.filter(|(body, _)| self.flow_of() == Some(*body)).map(|(_, gap)| gap) + } + /// The axis the enclosing body shares among its direct children that fill it (`fill_body`). pub(crate) const fn shares(&self) -> Option { match self.fill_body { @@ -606,7 +646,8 @@ impl Scoped { }) } - /// The flow facts of the enclosing body a memoized view shown in this scope is laid out by (`Flow`). + /// The flow facts of the enclosing body a memoized view shown in this scope is laid out by (`Flow`), without where + /// the view stands in that body's flow (`Flow::in_flow`). pub(crate) const fn flow(&self) -> Flow { Flow { content_column: self.content_column, @@ -618,6 +659,8 @@ impl Scoped { cell_fills: self.cell_fills, fits: self.view_fits(), egui_cell: self.egui_cell, + start: None, + gap: None, } } @@ -759,6 +802,7 @@ impl Env { first_line: None, flow_body: None, stack_gap: None, + view_flow: None, after_rule: false, column_row: false, bracket: None, diff --git a/crates/ui-contract/src/runtime/focus.rs b/crates/ui-contract/src/runtime/focus.rs index 2bf8bc94b0..262dcf68ca 100644 --- a/crates/ui-contract/src/runtime/focus.rs +++ b/crates/ui-contract/src/runtime/focus.rs @@ -725,6 +725,17 @@ fn opener(state: &State, id: Id, noted: Option, focused: Option) -> } } +/// The layer `id` ended its shown life in the running pass after its body ran (a dialog host removed the dialog it +/// showed): its scope plays its exit from now on, so the end hook of this pass moves the focus inside it to its opener, +/// or nowhere, as for a scope that went away. A scope this pass did not show is left as it is. +pub(crate) fn end_scope(ctx: &Context, id: Id) { + with(ctx, |state| { + if let Some(scope) = state.scopes.get_mut(&id) { + scope.closing = true; + } + }); +} + /// The innermost scope open in the running pass: the scope whose body is being shown. #[doc(hidden)] pub fn open_scope(ctx: &Context) -> Option { @@ -1010,6 +1021,14 @@ pub(crate) fn text_root(ctx: &Context) -> Option { .map(|rec| rec.stop.root) } +/// Gives up the focus of this exact registered stop only if it still holds it. The overlay's explicit +/// opener-Escape blur uses the focus service's usual action path; it cannot clear another member of an arena. +pub(crate) fn surrender_stop(ctx: &Context, key: StopKey) { + if let Some(rec) = focused_rec(ctx).filter(|rec| rec.stop.key() == key) { + apply(ctx, vec![Act::Surrender(rec.stop.root)]); + } +} + /// Whether the focus stop is a child of a collection row's roving group. pub(crate) fn in_row_child(ctx: &Context) -> bool { with(ctx, |state| { diff --git a/crates/ui-contract/src/runtime/focus/nav.rs b/crates/ui-contract/src/runtime/focus/nav.rs index 76496d27f7..6cea88b4a2 100644 --- a/crates/ui-contract/src/runtime/focus/nav.rs +++ b/crates/ui-contract/src/runtime/focus/nav.rs @@ -413,12 +413,22 @@ impl State { self.last_scope_order.iter().rev().find(|id| self.last_scopes.get(id).is_some_and(|scope| scope.policy.trap)).copied() } + /// A stop's place in last pass's Tab order: its index among the stops Tab and the arrows move over, the order the + /// entries keep. + fn place(&self, rec: &StopRec) -> usize { + self.last_stops.iter().position(|stop| stop.stop.key() == rec.stop.key()).unwrap_or(usize::MAX) + } + /// A Tab move. In a dialog's trap with `dialog_tab` at `Fields`, only text stops are entries, whatever the /// window's rule: a roving group whose arrival member holds no text is skipped too. pub(super) fn tab(&mut self, forward: bool, all_controls: bool, dialog_tab: TabReach) -> Vec { - let (current, entries) = self.tab_entries(all_controls, dialog_tab); + let (current, entries, after) = self.tab_entries(all_controls, dialog_tab); let top = current.as_ref().and_then(|rec| rec.stop.group).map(|group| self.last().outermost(group)); - let Some(next) = cycle(&entries, current.as_ref(), top, forward) else { return Vec::new() }; + let Some(mut next) = cycle(&entries, current.as_ref(), top, forward) else { return Vec::new() }; + if let Some(after) = after { + let count = entries.len(); + next = if forward { after % count } else { (after + count - 1) % count }; + } let arrival = entries[next].arrival().clone(); self.focus_stop(arrival) } @@ -426,18 +436,75 @@ impl State { /// The Tab entries this pass moves over, from the stop the focus is on (a row's child tabs on from its collection, /// a dropdown's content from its anchor). They are last pass's entries: what `tab` cycles, and what a Tab that /// landed on a stop this pass does not show goes on through. - fn tab_entries(&self, all_controls: bool, dialog_tab: TabReach) -> (Option, Vec) { + fn tab_entries(&self, all_controls: bool, dialog_tab: TabReach) -> (Option, Vec, Option) { let current = self.stop_of_focus().map(|rec| { let owner = rec.stop.group.and_then(|group| self.group(group)).filter(|group| group.row).and_then(|group| self.row_owner(&group)); let rec = owner.unwrap_or(rec); self.anchored_layer(rec.scope).and_then(|opener| self.find_stop(opener)).unwrap_or(rec) }); - let trap = self.trap_of(current.as_ref()); + // Tab out of a menu that lets it leave (`Menu::tab_exits`) goes on from the menu's opener, either way, as if the + // menu were part of it: the menu's own rows are no entries, so Shift+Tab reaches the stop before the opener. + let exits = current.as_ref().and_then(|rec| self.tab_exit_menu(rec.scope)); + // the trap is read before the exit swaps the focus for the menu's opener: a trapping submenu's trap must still + // hold, and its opener sits outside it + let trap_of_focus = self.trap_of(current.as_ref()); + let current = exits.and_then(|menu| self.return_stop(menu)).or(current); + let trap = trap_of_focus.or_else(|| self.trap_of(current.as_ref())); let in_dialog = trap.and_then(|id| self.last_scopes.get(&id)).is_some_and(|scope| scope.policy.kind == ScopeKind::Dialog); let fields = in_dialog && dialog_tab == TabReach::Fields; let mut entries = self.entries(trap, all_controls && !fields); - entries.retain(|entry| self.anchored_layer(entry.arrival().scope).is_none() && (!fields || entry.arrival().stop.text)); - (current, entries) + // A layer playing its exit takes no focus (`exiting`): an Escape that closed a menu leaves it no Tab entry for the + // fade's frames, so the next Tab does not land in it and have the closed menu hand the focus back to its opener. + entries.retain(|entry| { + let scope = entry.arrival().scope; + self.anchored_layer(scope).is_none() + && !self.exiting(scope) + && exits.is_none_or(|menu| !self.within(scope, menu)) + && (!fields || entry.arrival().stop.text) + }); + // The opener a `tab_exits` menu hands Tab to is no entry itself where only some stops are (a non-text opener in a + // dialog that tabs through fields): it keeps its place in the order, so Tab takes the entry after that place and + // Shift+Tab the one before, and the neighbour stays the one beside the opener. + let missing_opener = current.as_ref().filter(|opener| { + exits.is_some() && !entries.iter().any(|entry| entry.holds(opener, opener.stop.group.map(|group| self.last().outermost(group)))) + }); + let after = missing_opener.map(|opener| { + let place = self.place(opener); + entries.iter().filter(|entry| self.place(entry.arrival()) < place).count() + }); + (current, entries, after) + } + + /// The menu around `scope` that Tab leaves (`Menu::tab_exits`): a menu scope that traps nothing. The walk stops at a + /// dialog: a dialog shown from inside such a menu records it as the scope around it, and its trap keeps Tab inside + /// it until it closes. + fn tab_exit_menu(&self, scope: Option) -> Option { + let mut at = scope; + while let Some(id) = at { + let rec = self.last_scopes.get(&id)?; + // The first scope that traps ends the walk, whatever it is: a dialog shown from inside such a menu, or a + // submenu that traps its own keys. Its trap keeps Tab inside it until it closes. + if rec.policy.trap { + return None; + } + if rec.policy.kind == ScopeKind::Menu { + return Some(id); + } + at = rec.parent; + } + None + } + + /// Whether the scope `scope`, or one around it, is a layer playing its exit, by this pass's record or else the last. + fn exiting(&self, scope: Option) -> bool { + let mut at = scope; + while let Some(rec) = at.and_then(|id| self.scopes.get(&id).or_else(|| self.last_scopes.get(&id))) { + if rec.closing { + return true; + } + at = rec.parent; + } + false } /// F6: the first stop of the next pane, with its label as the announcement. Inside a trapping scope (a modal @@ -641,7 +708,7 @@ impl State { if !arrived { return None; } - let (current, entries) = self.tab_entries(self.tab_all_controls, self.dialog_tab); + let (current, entries, _) = self.tab_entries(self.tab_all_controls, self.dialog_tab); let current = current?; let top = current.stop.group.map(|group| self.last().outermost(group)); let at = entries.iter().position(|entry| entry.holds(¤t, top))?; diff --git a/crates/ui-contract/src/runtime/ime.rs b/crates/ui-contract/src/runtime/ime.rs index 55fd9ef69b..5cfa0d642f 100644 --- a/crates/ui-contract/src/runtime/ime.rs +++ b/crates/ui-contract/src/runtime/ime.rs @@ -270,19 +270,28 @@ impl Engine { /// Notes an answer to one of the app's own reset requests. A completion answers that request and every older one, /// as completions arrive in request order, and ends the fence when it waits for one of them; a retirement answers - /// only its own request and, when the fence waits for it, leaves the end hook to ask again. - fn host_answered(&mut self, event: &Event) { + /// only its own request and, when the fence waits for it, leaves the end hook to ask again. While a framework editor + /// owns the IME, a completion that ends the fence goes into the queue at its place among the events this hook + /// queued from `start` on, so the begin hook still drops the interrupted composition's events that arrived before + /// it. `place` counts the events left in egui's input before the completion. With no framework editor, the fence + /// ends here, before the hook follows the app's editor. + fn host_answered(&mut self, event: &Event, start: usize, place: usize) { let (Event::ImeResetCompleted { request_id: id } | Event::ImeResetRetired { request_id: id }) = event else { return }; let Some(at) = self.host_resets.iter().position(|own| own == id) else { return }; let answered: Vec<_> = match event { Event::ImeResetCompleted { .. } => self.host_resets.drain(..=at).collect(), _ => vec![self.host_resets.remove(at)], }; - if self.reset.is_some_and(|reset| answered.contains(&reset)) { + let Some(reset) = self.reset.filter(|reset| answered.contains(reset)) else { return }; + if !matches!(event, Event::ImeResetCompleted { .. }) { self.reset = None; - if matches!(event, Event::ImeResetCompleted { .. }) { - self.stale = false; - } + } else if self.owner.is_none() { + self.reset = None; + self.stale = false; + } else { + let start = start.min(self.queue.len()); + let at = start + self.queue[start..].partition_point(|(_, queued)| *queued <= place); + self.queue.insert(at, (os::Raw::ResetCompleted(reset), place)); } } @@ -346,10 +355,11 @@ pub(crate) fn input_hook(ctx: &Context, events: &mut Vec, viewport: Vie matches!(event, Event::Key { key: Key::Enter | Key::Escape | Key::Backspace | Key::Delete | Key::Space, pressed: true, .. }) }; let taken = os::take_events(events, |event| take && !host_answer(event), |event| guarded && ends_composition(event)); + let start = engine.queue.len(); engine.queue.extend(taken); engine.guard = engine.guard.saturating_sub(1); - for arrived in events.iter().chain(after.iter().flatten()) { - engine.host_answered(&arrived.event); + for (place, arrived) in events.iter().chain(after.iter().flatten()).enumerate() { + engine.host_answered(&arrived.event, start, place); } if engine.owner.is_none() { match &mut after { diff --git a/crates/ui-contract/src/runtime/inspect.rs b/crates/ui-contract/src/runtime/inspect.rs index bd27e8f9d1..30c0ff77ba 100644 --- a/crates/ui-contract/src/runtime/inspect.rs +++ b/crates/ui-contract/src/runtime/inspect.rs @@ -167,6 +167,11 @@ pub struct HitArea { pub owner: Id, /// The part, `None` for the component's own area. pub part: Option, + /// The sensing shape's original bounds, before minimum-hit-size expansion, in the points + /// of the region's layer. Pointer-only parts are included even without an access node or + /// Tab stop. This is geometry, not a promise that every point is interactable: the shape, + /// clipping and layer ownership still decide the hit. + pub bounds: Rect, /// The area at its least size across, in the points of the region's layer. pub rect: Rect, } @@ -188,7 +193,7 @@ impl crate::runtime::Shift for Arc { fn shifted(&self, by: &egui::RecordShift) -> Self { let elements = self.elements.iter().map(|element| Element { rect: by.rect(element.rect), content: by.rect(element.content), ..element.clone() }); - let hits = self.hits.iter().map(|hit| HitArea { rect: by.rect(hit.rect), ..hit.clone() }); + let hits = self.hits.iter().map(|hit| HitArea { rect: by.rect(hit.rect), bounds: by.rect(hit.bounds), ..hit.clone() }); Arc::new(Recorded { layer: self.layer, elements: elements.collect(), hits: hits.collect() }) } @@ -201,7 +206,11 @@ impl crate::runtime::Shift for Arc { content: element.content.snapped(&to.content, within), ..element.clone() }); - let hits = self.hits.iter().zip(&to.hits).map(|(hit, to)| HitArea { rect: hit.rect.snapped(&to.rect, within), ..hit.clone() }); + let hits = self.hits.iter().zip(&to.hits).map(|(hit, to)| HitArea { + rect: hit.rect.snapped(&to.rect, within), + bounds: hit.bounds.snapped(&to.bounds, within), + ..hit.clone() + }); Arc::new(Recorded { layer: self.layer, elements: elements.collect(), hits: hits.collect() }) } } @@ -375,7 +384,7 @@ fn finish(ctx: &Context, open: Open) -> Recorded { } let mut hits: Vec = pointer::hit_areas(ctx, |owner| ids.contains(&owner)) .into_iter() - .map(|(owner, part, rect)| HitArea { owner, part, rect: from_screen * rect }) + .map(|(owner, part, bounds, rect)| HitArea { owner, part, bounds: from_screen * bounds, rect: from_screen * rect }) .collect(); // Keep the first occurrence, matching the tree-order lookup when an id appears more than once. let mut index = std::collections::HashMap::new(); diff --git a/crates/ui-contract/src/runtime/layout_memory.rs b/crates/ui-contract/src/runtime/layout_memory.rs index 51a98f0558..d9c17e1578 100644 --- a/crates/ui-contract/src/runtime/layout_memory.rs +++ b/crates/ui-contract/src/runtime/layout_memory.rs @@ -232,9 +232,21 @@ struct Scope { reported: Vec<(Id, f32)>, } +/// The size the last block of a kind recorded (`note_typical`): what a pass reads, and what this pass's real runs +/// recorded for the passes after it. +#[derive(Clone, Copy, Debug, Default)] +struct Typical { + now: Option, + next: Option, + /// The last frame that recorded it. + touched: u64, +} + #[derive(Default)] pub(crate) struct Entries { entries: IdMap, + /// By kind, the size the blocks of that kind recorded last (`typical`). + typical: IdMap, measured: IdMap, kept: IdMap, /// The bodies whose records a kept transcript gave in this pass, with that transcript. @@ -494,6 +506,62 @@ pub(crate) fn record(ctx: &Context, id: Id, real: Vec2) { }); } +/// The size a block of `kind` recorded last ([`note_typical`]) before this pass. Every run of a pass reads the same +/// value: what a real run notes in this pass serves from the next pass on. +pub(crate) fn typical(ctx: &Context, kind: Id) -> Option { + let moment = Moment::of(ctx); + with(ctx, &moment, |memory| memory.typical.get(&kind).and_then(|typical| typical.now)) +} + +/// Notes `size` as what a block of `kind` recorded, for the passes after this one ([`typical`]). A measuring run notes +/// nothing. A replay of the run keeps the note ([`keep`]). +pub(crate) fn note_typical(ctx: &Context, kind: Id, size: Vec2) { + if !real(ctx) { + return; + } + crate::runtime::replay::note_layout_keep(ctx, kind); + let moment = Moment::of(ctx); + with(ctx, &moment, |memory| { + let typical = memory.typical.entry(kind).or_default(); + typical.next = Some(size); + typical.touched = moment.frame; + }); +} + +/// Stores `baseline`, the distance from the top of the control of the labeled row `row` to its first baseline, for the +/// next pass's label placement. With the control's `size`, it also notes the baseline for the first appearance of +/// later rows with a control of that size ([`control_baseline_kind`]). +pub(crate) fn record_control_baseline(ctx: &Context, row: Id, size: Option, baseline: f32) { + record(ctx, crate::runtime::memory::sub(row, "baseline"), Vec2::new(0.0, baseline)); + if let Some(size) = size { + note_typical(ctx, control_baseline_kind(size), Vec2::new(0.0, baseline)); + } +} + +/// The key the baselines of the controls of `size` are noted under ([`typical`]). +pub(crate) fn control_baseline_kind(size: craft_theme::ControlSize) -> Id { + crate::runtime::memory::unique(("label control baseline", size)) +} + +/// This pass placed the block `id` by `size`, which it took from elsewhere (a block of the same kind, [`typical`]), +/// where the entry under `id` holds no size yet: [`record`] compares the real size with `size`, as it compares a size +/// from the last pass, so a first appearance that measures what the placement assumed asks no discard pass. It +/// changes nothing when the entry holds a size, when this pass did not read the entry, or in a measuring run. +pub(crate) fn assume(ctx: &Context, id: Id, size: Vec2) { + if !real(ctx) { + return; + } + let moment = Moment::of(ctx); + with(ctx, &moment, |memory| { + if let Some(entry) = memory.entries.get_mut(&id) + && entry.value.is_none() + && entry.used.is_some_and(|(pass, read)| pass == moment.pass && read.is_none()) + { + entry.used = Some((moment.pass, Some(size))); + } + }); +} + /// Whether this pass is a real run's: no measuring run is open and egui does not run a sizing pass. fn real(ctx: &Context) -> bool { !crate::runtime::measure::active(ctx) @@ -1248,7 +1316,7 @@ pub(crate) fn discard_pending(ctx: &Context) -> bool { with(ctx, &moment, |memory| memory.ask && memory.asked != Some(moment.frame)) && sizing::discardable(ctx) } -/// Keeps the entries and kept transcripts of `ids` through this frame, for a replayed run that kept them +/// Keeps the entries, typical sizes and kept transcripts of `ids` through this frame, for a replayed run that kept them /// (`replay::note_layout_keep`): the replay does not reach them, and an entry no pass touched in a frame is dropped. pub(crate) fn keep(ctx: &Context, ids: &[Id]) { if ids.is_empty() { @@ -1260,6 +1328,9 @@ pub(crate) fn keep(ctx: &Context, ids: &[Id]) { if let Some(entry) = memory.entries.get_mut(id) { entry.touched = moment.frame; } + if let Some(typical) = memory.typical.get_mut(id) { + typical.touched = moment.frame; + } if let Some(kept) = memory.kept.get_mut(id) { kept.touched = moment.frame; } @@ -1278,6 +1349,12 @@ pub(crate) fn end_hook(ctx: &Context) { memory.asked = Some(moment.frame); } memory.entries.retain(|_, entry| entry.touched + 1 >= moment.frame); + memory.typical.retain(|_, typical| typical.touched + 1 >= moment.frame); + for typical in memory.typical.values_mut() { + if let Some(next) = typical.next.take() { + typical.now = Some(next); + } + } memory.kept.retain(|_, kept| kept.touched + 1 >= moment.frame); memory.measured.clear(); memory.served.clear(); diff --git a/crates/ui-contract/src/runtime/memory.rs b/crates/ui-contract/src/runtime/memory.rs index 045249fc58..4ce8e77cff 100644 --- a/crates/ui-contract/src/runtime/memory.rs +++ b/crates/ui-contract/src/runtime/memory.rs @@ -289,27 +289,29 @@ pub(crate) struct Registry { /// not show the base (a page left and opened again before its owner was evicted) makes its next showing an /// appearance again, as WordCraft told a reopened page by a gap in the frames it was drawn in. #[derive(Clone, Copy)] -struct Seen { - first: u64, - last: u64, +enum Seen { + /// A copied base has not yet been shown on the destination's own frame timeline. + Forked, + Shown { + first: u64, + last: u64, + }, } impl Seen { - /// Whether the frames since the base was last shown leave a gap before `frame`. - fn gap_before(self, frame: u64) -> bool { - self.last.saturating_add(1) < frame - } - /// Whether a stage of this base in `frame` is the base appearing. fn appears(self, frame: u64) -> bool { - self.first == frame || self.gap_before(frame) + match self { + Seen::Forked => true, + Seen::Shown { first, last } => first == frame || last.saturating_add(1) < frame, + } } /// The mark after a write-back in `frame`. fn shown(old: Option, frame: u64) -> Seen { match old { - Some(seen) if !seen.gap_before(frame) => Seen { first: seen.first, last: frame.max(seen.last) }, - _ => Seen { first: frame, last: frame }, + Some(Seen::Shown { first, last }) if last.saturating_add(1) >= frame => Seen::Shown { first, last: frame.max(last) }, + _ => Seen::Shown { first: frame, last: frame }, } } } @@ -558,16 +560,31 @@ fn forget_tier(ctx: &Context, id: Id, tier: u8) { drop(moved); } -/// Takes the destination's registry records for every slot a fork copied into it: `Registry` is per-context framework -/// state while `fork_into` copies egui memory, so without this the copied slots read as `recorded` (that flag comes from -/// finding the slot in context data) and `write_back` never records them — no owner, so `evict` and `forget_tier` could -/// never reach them. The owner kept is the source's: the slot is that component's state, and the destination's passes -/// record it under their own owner as soon as they write it again. -pub(crate) fn adopt_copied_slots(from: &Context, to: &Context) { - let copied: Vec<((Id, u8, TypeId), SlotRecord)> = pass_state::with::(from, |reg| reg.slots.iter().map(|(k, v)| (*k, *v)).collect()); +/// Replaces the destination's slot records to match the copied memory. Copied shown and press slots get an owner +/// on the destination's clock, even when the owner never draws there; otherwise their normal eviction cannot run. +/// The destination's other runtime services stay its own, and any cached run of a replaced owner is invalidated. +fn adopt_copied_slots(from: &Context, to: &Context, facts: frame::PassFacts) { + let copied = pass_state::with::(from, |reg| reg.slots.clone()); + // Appearance is a property of the destination's frames, not the source's. Keep the remembered values, + // but let each base report its first appearance when first drawn in the fork. + store::locked(to, |data| { + for &(id, tier, ty) in copied.keys() { + if tier == SHOWN && ty == TypeId::of::() { + store::mark_seen(data, id, |_| Seen::Forked); + } + } + }); + let stamp = OwnerStamp { viewport: facts.viewport, pass: facts.pass_nr, at: facts.now, before: None }; + let owners: IdSet = copied.iter().filter(|(key, _)| matches!(key.1, SHOWN | PRESS)).map(|(_, record)| record.owner).collect(); pass_state::with::(to, |reg| { - for (key, record) in copied { - reg.slots.insert(key, record); + let replaced = std::mem::take(&mut reg.owners); + if !replaced.is_empty() { + end_lives(reg, replaced.into_keys()); + } + reg.owner_batches.clear(); + reg.slots = copied; + for owner in owners { + reg.owners.insert(owner, OwnerRecord { stamp, batch: None }); } }); } @@ -1164,7 +1181,8 @@ impl std::error::Error for ForkError {} /// (scroll offsets, open sections, the session and shown slots of every component), copied by value. `to` keeps its /// own runtime: its pass state, focus, overlays, commands, windows and the rest of the services its install made, so /// a pass of `to` neither reads nor moves `from`'s, and `to` may run a pass inside one of `from`'s. A runtime service -/// `to` has none of yet starts fresh in `to` on first use. +/// `to` has none of yet starts fresh in `to` on first use. Remembered values are preserved, but owners +/// get a destination-local eviction grace and each base starts its own appearance history. /// /// Copying egui's memory alone (`to.memory_mut(|m| *m = from.memory(Clone::clone))`) shares the runtime's state /// between the two: its services are handles, and a copy of a handle reaches the same state. @@ -1176,9 +1194,9 @@ pub fn fork_into(from: &Context, to: &Context) -> Result<(), ForkError> { if store::aliased(from, to) { return Err(ForkError::SameContext); } + let facts = frame::facts(to); store::copy_memory(from, to); - // the copied slots' registry records follow them, or nothing in the destination could ever evict them - adopt_copied_slots(from, to); + adopt_copied_slots(from, to, facts); pending::detach_fork(from, to); Ok(()) } diff --git a/crates/ui-contract/src/runtime/overlay.rs b/crates/ui-contract/src/runtime/overlay.rs index c4b352c1dd..9cab5e77bf 100644 --- a/crates/ui-contract/src/runtime/overlay.rs +++ b/crates/ui-contract/src/runtime/overlay.rs @@ -265,6 +265,10 @@ impl OpenEntry { pub(crate) struct Pass { current: Vec, last: Vec, + /// Each transformed body's layer and the layer it is a sublayer of, this pass and the last: egui forgets its own + /// record of sublayers at the end of each pass, before the next pass's begin hooks read it. + sublayers: Vec<(Layer, Layer)>, + last_sublayers: Vec<(Layer, Layer)>, /// The layers whose bodies are running and the tier each shows in, innermost last. drawing: Vec<(Id, Tier)>, /// Whether each body of `drawing` is that of a layer fading out, in the same order. @@ -326,7 +330,8 @@ pub(crate) struct Persist { appeared: IdMap<(u64, u64)>, /// The roots whose asked raise ran in a pass where a floating window (re)appeared: egui raises every layer that /// shows again, and its area order keeps the old order among the layers raised in one pass, so the raise is asked - /// again in the next pass. + /// again in the next pass. Also the roots raised in a pass that moved only its own raises up, past a carried one + /// that stood above them, asked again in the order they were asked. raise_again: Vec, } @@ -343,8 +348,10 @@ fn with_pass(ctx: &Context, f: impl FnOnce(&mut Pass) -> R) -> R { pass::pass_nr(ctx, viewport), |pass, step| { pass.last = std::mem::take(&mut pass.current); + pass.last_sublayers = std::mem::take(&mut pass.sublayers); if matches!(step, PassStep::Skipped) { pass.last.clear(); + pass.last_sublayers.clear(); } pass.drawing.clear(); pass.exiting.clear(); @@ -828,14 +835,20 @@ pub fn take_keys_for_new_dialog(ctx: &Context) { /// A dialog host removed `dialog`: the layers it showed for it (`stack_place`) in the running or the last pass end /// their shown life at once (`memory::end_shown`), as a container that shows nothing does, and forget the open state /// they kept for the session (`memory::open_slot`), so the next open of the dialog is a first pass and starts open: the -/// close that ended the dialog wrote that state closed. +/// close that ended the dialog wrote that state closed. The layers leave this pass's stack, so its end hook records no +/// modal and no top layer for them, and their focus scopes close (`focus::end_scope`): the end hook of this pass moves +/// the focus inside them back to the opener, and the next frame's keys go there. #[doc(hidden)] pub fn end_stack_dialog(ctx: &Context, dialog: Id) { - let shown: Vec = - with_pass(ctx, |pass| pass.current.iter().chain(&pass.last).filter(|entry| entry.dialog == Some(dialog)).map(|entry| entry.id).collect()); + let shown: Vec = with_pass(ctx, |pass| { + let shown = pass.current.iter().chain(&pass.last).filter(|entry| entry.dialog == Some(dialog)).map(|entry| entry.id).collect(); + pass.current.retain(|entry| entry.dialog != Some(dialog)); + shown + }); for id in shown { crate::runtime::memory::end_shown(ctx, id); crate::runtime::memory::forget(ctx, crate::runtime::memory::open_slot(id)); + crate::runtime::focus::end_scope(ctx, id); } } @@ -916,8 +929,10 @@ pub(crate) fn end_pass(ctx: &Context) { }); let pressed = pointer::frame_raw(ctx).press.map(|press| press.origin); let now = pass::root_frame_nr(ctx); - let (order, to_top, floats, asked) = with_persist(ctx, viewport, |persist| { - let raise: Vec = std::mem::take(&mut persist.raise_again).into_iter().chain(raise).collect(); + let (order, lifted, floats, asked) = with_persist(ctx, viewport, |persist| { + let carried = std::mem::take(&mut persist.raise_again); + let carried_count = carried.len(); + let raise: Vec = carried.into_iter().chain(raise).collect(); let stamp = |id: Id, persist: &mut Persist| { persist.counter += 1; persist.raised.insert(id, persist.counter); @@ -929,6 +944,8 @@ pub(crate) fn end_pass(ctx: &Context) { .map(|entry| entry.id) .collect(); let mut asked: Vec = Vec::new(); + // The roots raised by this pass's own reasons, without the raises carried from the last pass. + let mut fresh: Vec = Vec::new(); for root in &roots { let shown = current.iter().find(|entry| entry.id == *root); // A root the last pass did not have appears, and so does one that faded out then and is open again @@ -943,9 +960,10 @@ pub(crate) fn end_pass(ctx: &Context) { // its area in the pass before, so it raises none. A root that first shows there is raised by egui itself. if reopened && shown.is_some_and(|entry| !entry.window && (entry.rank == Rank::Window || entry.among_windows)) { asked.push(*root); + fresh.push(*root); } } - for id in raise { + for (at_raise, id) in raise.into_iter().enumerate() { let mut at = current.iter().find(|entry| entry.id == id); while let Some(parent) = at.and_then(|entry| entry.parent).and_then(|parent| current.iter().find(|other| other.id == parent)) { at = Some(parent); @@ -953,8 +971,20 @@ pub(crate) fn end_pass(ctx: &Context) { if let Some(root) = at { stamp(root.id, persist); asked.push(root.id); + if at_raise >= carried_count { + fresh.push(root.id); + } } } + // A root asked more than once keeps its last place, so a raise asked again in every pass carries one entry. + let mut once: Vec = Vec::new(); + for id in asked.iter().rev() { + if !once.contains(id) { + once.push(*id); + } + } + once.reverse(); + let asked = once; persist.raised.retain(|id, _| roots.contains(id)); persist.appeared.retain(|id, _| current.iter().any(|entry| entry.id == *id)); let before = families(¤t, &persist.raised); @@ -970,7 +1000,9 @@ pub(crate) fn end_pass(ctx: &Context) { let families = families(¤t, &persist.raised); let mut order: Vec = Vec::new(); let mut listed: Vec = Vec::new(); - let mut to_top: Vec = Vec::new(); + // The layers an asked raise moves to the top of egui's area order, in the raise order, each with whether this + // pass asked for it. + let mut lifted: Vec<(Layer, bool)> = Vec::new(); let mut floats: Vec = Vec::new(); persist.stack.clear(); for members in &families { @@ -990,9 +1022,9 @@ pub(crate) fn end_pass(ctx: &Context) { listed.push(member.id); } else if !member.window { floats.push(member.layer); - if members.first().is_some_and(|root| asked.contains(&root.id)) { + if let Some(root) = members.first().filter(|root| asked.contains(&root.id)) { // An asked raise of a layer left to egui's area order raises it there, as a press on it does. - to_top.push(member.layer); + lifted.push((member.layer, fresh.contains(&root.id))); } } persist.stack.push(member.id); @@ -1020,13 +1052,22 @@ pub(crate) fn end_pass(ctx: &Context) { .map(|(_, members)| { members.iter().flat_map(|member| std::iter::once(member.rect).chain(member.anchor).chain(member.peers.iter().copied())).collect() }); - (order, to_top, floats, asked) + (order, lifted, floats, asked) }); + // egui keeps the old order among the layers it moves to the top in one pass. When that order differs from the + // raise order, a raise carried from the last pass and a raise asked in this one cannot go up together: the carried + // one would stay above the newer one. Only this pass's raises go up then, and `held_back` asks every raise again in + // the next pass, where this pass's raises already stand above the carried ones. + let stacked = areas::area_order(ctx); + let place = |layer: &Layer| stacked.iter().position(|at| at == layer).unwrap_or(stacked.len()); + let in_order = lifted.windows(2).all(|pair| place(&pair[0].0) <= place(&pair[1].0)); + let held_back = !in_order && lifted.iter().any(|(_, fresh)| *fresh) && lifted.iter().any(|(_, fresh)| !fresh); + let to_top: Vec = lifted.into_iter().filter(|(_, fresh)| *fresh || !held_back).map(|(layer, _)| layer).collect(); areas::set_layer_order(ctx, &order); for layer in &to_top { areas::move_to_top(ctx, *layer); } - if !to_top.is_empty() && floats.iter().any(|layer| !areas::visible_last_frame(ctx, *layer)) { + if held_back || (!to_top.is_empty() && floats.iter().any(|layer| !areas::visible_last_frame(ctx, *layer))) { with_persist(ctx, viewport, |persist| persist.raise_again = asked); } // An owner takes a close in the frame after the request at the latest; one nobody took is for a layer that is not shown. @@ -1151,6 +1192,54 @@ pub(crate) fn class_open_away_from(ctx: &Context, class: OwnerClass, at: Pos2) - }) } +/// Records that the transformed body's layer `child` is shown in this pass as a sublayer of `parent`. +pub(crate) fn note_sublayer(ctx: &Context, child: Layer, parent: Layer) { + crate::runtime::replay::journal(ctx, || (child, parent), |ctx, &(child, parent)| note_sublayer(ctx, child, parent)); + with_pass(ctx, |pass| pass.sublayers.push((child, parent))); +} + +/// The layer of last pass's stack that lies topmost under a screen point, among the layers the running viewport shows +/// as egui layers of its own. +pub(crate) struct Under { + /// The layer under the point, `None` over the window's base. + layer: Option, + /// The layers the running viewport showed last pass, not fading out. + shown: SmallVec<[Id; 8]>, +} + +impl Under { + /// Whether something drawn inside the layer `drawn_in` (`drawing_parent` when it was drawn) lies in the layer under + /// the point. A layer the viewport does not show as its own egui layer, such as the OS window a body is mounted + /// in, counts as the window's base. + pub(crate) fn holds(&self, drawn_in: Option) -> bool { + drawn_in.filter(|layer| self.shown.contains(layer)) == self.layer + } +} + +/// The layer of last pass's stack that lies topmost under the screen point `at`, or `None` over a layer that is fading +/// out, which registers no wheel takers of its own. +pub(crate) fn layer_under(ctx: &Context, at: Pos2) -> Option { + let top = areas::layer_at(ctx, at); + with_pass(ctx, |pass| { + // A transformed body is a sublayer of its layer, and the entry names the layer. + let top = top.map(|mut layer| { + for _ in 0..pass.last_sublayers.len() { + match pass.last_sublayers.iter().find(|(child, _)| *child == layer) { + Some((_, parent)) => layer = *parent, + None => break, + } + } + layer + }); + let own = || pass.last.iter().filter(|entry| !entry.window && !entry.popup); + let shown = own().filter(|entry| !entry.exiting).map(|entry| entry.id).collect(); + match top.and_then(|top| own().rev().find(|entry| entry.layer == top)) { + Some(entry) if entry.exiting => None, + entry => Some(Under { layer: entry.map(|entry| entry.id), shown }), + } + }) +} + // The facts the canvas reach under a modal reads (`runtime::sampler`). /// The top live modal layer shown in `viewport` as of its last finished pass. diff --git a/crates/ui-contract/src/runtime/pointer.rs b/crates/ui-contract/src/runtime/pointer.rs index c44e5992ca..4ee74fcf3e 100644 --- a/crates/ui-contract/src/runtime/pointer.rs +++ b/crates/ui-contract/src/runtime/pointer.rs @@ -924,26 +924,64 @@ pub(crate) fn over_part(ctx: &Context, viewport: ViewportId, root: Id, part: Par OverPart { widgets, above } } +/// The hit areas, in screen points and clipped to where each shows, of the press-taking shapes of the root whose egui widgets include `widget` in the +/// running pass: where a press over that widget goes to the root's parts (8.3). `None` when no root recorded it, so it +/// is a plain egui widget that takes a press anywhere in its rect. +pub(crate) fn press_shapes_of_widget(ctx: &Context, viewport: ViewportId, widget: Id) -> Option> { + let layers: Vec<(Layer, Vec)> = PerViewport::::with(ctx, viewport, |record| { + let mut found = None::)>>; + for (layer, roots) in &record.this { + for entry in roots.values().filter(|entry| entry.widgets.contains(&widget)) { + // A press reaches a shape across its hit area, grown to its least size across (`Shape::hits`), and only + // where it shows through its clip (`find_under`). + let bounds = entry + .shapes + .iter() + .zip(&entry.placed) + .filter(|(shape, _)| shape.sense.takes_press()) + .map(|(shape, placed)| { + let bounds = shape.shape.bounds(); + let grow = (egui::Vec2::splat(shape.min_across) - bounds.size()).max(egui::Vec2::ZERO) / 2.0; + bounds.expand2(grow).intersect(placed.clip) + }) + .filter(|rect| rect.is_positive()) + .collect(); + found.get_or_insert_with(Vec::new).push((*layer, bounds)); + } + } + found + })?; + Some( + layers + .into_iter() + .flat_map(|(layer, bounds)| { + let to_screen = areas::layer_to_screen(ctx, layer); + bounds.into_iter().map(move |rect| to_screen * rect) + }) + .collect(), + ) +} + /// The hit areas the running pass has registered so far for the components `of` takes, in screen points: each shape's -/// bounds grown to its least size across, with the component and part it belongs to. -pub(crate) fn hit_areas(ctx: &Context, of: impl Fn(Id) -> bool) -> Vec<(Id, Option, egui::Rect)> { +/// bounds before and after growing to its least size across, with its component and part. +pub(crate) fn hit_areas(ctx: &Context, of: impl Fn(Id) -> bool) -> Vec<(Id, Option, egui::Rect, egui::Rect)> { let viewport = pass::current_viewport(ctx); - let found: Vec<(Layer, Id, Option, egui::Rect)> = PerViewport::::with(ctx, viewport, |record| { + let found: Vec<(Layer, Id, Option, egui::Rect, egui::Rect)> = PerViewport::::with(ctx, viewport, |record| { let mut found = Vec::new(); for (layer, roots) in &record.this { for shape in roots.values().flat_map(|root| root.shapes.iter()).filter(|shape| of(shape.owner)) { let bounds = shape.shape.bounds(); let grow = (egui::Vec2::splat(shape.min_across) - bounds.size()).max(egui::Vec2::ZERO) / 2.0; - found.push((*layer, shape.owner, shape.part, bounds.expand2(grow))); + found.push((*layer, shape.owner, shape.part, bounds, bounds.expand2(grow))); } } found }); found .into_iter() - .map(|(layer, owner, part, rect)| { + .map(|(layer, owner, part, bounds, rect)| { let to_screen = areas::layer_to_screen(ctx, layer); - (owner, part, to_screen * rect) + (owner, part, to_screen * bounds, to_screen * rect) }) .collect() } diff --git a/crates/ui-contract/src/runtime/toggle_sweep.rs b/crates/ui-contract/src/runtime/toggle_sweep.rs index 4c151ffb6d..132009e2a4 100644 --- a/crates/ui-contract/src/runtime/toggle_sweep.rs +++ b/crates/ui-contract/src/runtime/toggle_sweep.rs @@ -1,11 +1,16 @@ //! A primary press on a standalone toggle can set the other toggles of its layout as it sweeps. +//! +//! A drag from a toggle that crosses no other toggle of its layout and does not end on the toggle itself is not a sweep: +//! it cancels, as a press released outside a control does, and the pressed toggle keeps its value. Only a toggle that +//! takes the sweep in the pass the drag reaches it counts as crossed: one that pass disables, hides, moves or leaves out +//! takes nothing, so the press stays one released outside the control. use std::sync::Arc; use craft_behavior::{PointerButton, PointerEvent, PressPhase, PressStart}; use egui::{Context, Id, IdSet, Pos2, Rect}; -use crate::runtime::egui::{areas, pass}; +use crate::runtime::egui::{areas, pass, sizing}; use crate::runtime::frame::{PerViewport, Stored}; use crate::runtime::pointer::{self, PassPointer}; @@ -69,11 +74,46 @@ struct Sweep { on: bool, travel: Travel, visited: IdSet, + /// A sibling of the group took the sweep's value in a pass, or the button went up over the owner: the owner takes + /// the value too, in this pass or the next. + engaged: bool, +} + +/// What a sweep shows its owner: it has engaged, or the button went up over the owner itself. +#[derive(Clone, Copy)] +struct Gives { + /// The sweep has engaged: a sibling took its value in a pass, or the button went up over the owner. + engaged: bool, + /// Where the button went up, when it went up in this pass. + end: Option, +} + +impl Gives { + /// What `sweep` shows its owner so far. + fn of(sweep: &Sweep) -> Self { + Gives { engaged: sweep.engaged, end: sweep.travel.released.then_some(sweep.travel.last).flatten() } + } + + /// Whether the sweep gives the owner the value at `layer` and `visible`: it has engaged, or the button went up over + /// the owner, which is a click rather than a sweep. The last pass's layout says nothing here: a sibling the crossing + /// pass disables, hides, moves or leaves out takes no sweep. + fn takes(self, ctx: &Context, layer: areas::Layer, visible: Rect) -> bool { + self.engaged || self.end.is_some_and(|end| crosses_visible(ctx, layer, visible, &[(end, end)])) + } +} + +/// What a pass's records say about the toggle asking. +enum Ready { + Owner { on: bool, replay: bool, gives: Gives }, + Sibling { on: bool, path: Arc> }, } struct CompletedSweep { sweep: Sweep, path: Arc>, + /// A sibling took the finished sweep's value after its owner asked in that pass, so the owner takes the value in the + /// next pass: the finished sweep waits for it there. + owner_late: bool, } #[derive(Default)] @@ -82,10 +122,15 @@ struct Record { sweep: Option, path: Arc>, // A press and move may arrive together; siblings drawn before the pressed control get that - // initial path on the following pass. Visited ids keep the edit from applying twice. + // initial path on the following pass. Visited ids keep the edit from applying twice. A sweep released + // in the pass a sibling after its owner took the value is kept the same way, for the owner (`accept`). replay_first_path: bool, - // The replay survives opening another gesture in the same pass. + // The replay survives opening another gesture in the same pass, and one more pass for its owner when a sibling took + // it after the owner asked. completed: Option, + /// The toggles that asked in this pass: an owner among them read the sweep before a sibling took it, so it takes the + /// value in the next pass. + asked: IdSet, } impl Stored for Record {} @@ -95,7 +140,8 @@ impl Record { if self.pass == pass { return; } - self.completed = None; + self.asked.clear(); + self.end_completed(); if !self.replay_first_path { Arc::make_mut(&mut self.path).clear(); } @@ -103,6 +149,7 @@ impl Record { let previous = std::mem::replace(&mut self.pass, pass); if cancelled || previous.saturating_add(1) != pass { self.sweep = None; + self.completed = None; return; } if self.sweep.as_ref().is_some_and(|sweep| sweep.travel.released) { @@ -128,12 +175,48 @@ impl Record { } } + /// `sibling` took the running sweep's value, so the sweep crossed another enabled toggle of the owner's group and the + /// owner takes the value too: only a toggle that takes the sweep in this pass counts as crossed. An owner that asked + /// in this pass before the sibling gets the value in the pass that runs again for it, which the caller asks for; a + /// sweep released before then is kept for the owner's check in that pass. Returns whether the pass runs again: the + /// owner read the sweep unengaged. + fn accept(&mut self, sibling: Id) -> bool { + let Some(sweep) = &mut self.sweep else { return false }; + sweep.visited.insert(sibling); + let late = !sweep.engaged && self.asked.contains(&sweep.owner); + sweep.engaged = true; + // A sweep still held keeps its path for the siblings it has yet to reach: only one released in this pass replays it. + self.replay_first_path |= late && sweep.travel.released; + late + } + + /// A finished sweep a sibling took after its owner asked waits one pass for the owner; any other is done with when the + /// next pass starts. + fn end_completed(&mut self) { + let waiting = self.completed.as_mut().is_some_and(|finished| std::mem::take(&mut finished.owner_late)); + if !waiting { + self.completed = None; + } + } + + /// `sibling` took the finished sweep's value. An owner that asked in this pass before it takes the value in the pass + /// that runs again for it, so the finished sweep waits for it there. Returns whether the pass runs again: the owner + /// read the finished sweep unengaged. + fn completed_taken(&mut self, sibling: Id) -> bool { + let Some(finished) = &mut self.completed else { return false }; + finished.sweep.visited.insert(sibling); + let late = !finished.sweep.engaged && self.asked.contains(&finished.sweep.owner); + finished.sweep.engaged = true; + finished.owner_late |= late; + late + } + fn finish(&mut self) { - self.completed = self.sweep.take().map(|sweep| CompletedSweep { sweep, path: std::mem::take(&mut self.path) }); + self.completed = self.sweep.take().map(|sweep| CompletedSweep { sweep, path: std::mem::take(&mut self.path), owner_late: false }); } fn start(&mut self, owner: Id, group: Id, press: PressStart, on: bool, input: &PassPointer) { - let mut sweep = Sweep { owner, group, on, travel: Travel::new(press.origin), visited: IdSet::default() }; + let mut sweep = Sweep { owner, group, on, travel: Travel::new(press.origin), visited: IdSet::default(), engaged: false }; let path = Arc::make_mut(&mut self.path); path.clear(); sweep.travel.advance(after_press(&input.events, press), input.frame.as_ref().map_or(0.0, |frame| frame.slop), path); @@ -142,6 +225,18 @@ impl Record { } } +/// Asks for the pass to run again, so the owner's value is current in the frame its sibling took the sweep: the owner +/// checked the sweep before the sibling in this pass and found it unengaged, so only a pass that runs again shows it +/// engaged. The record keeps a finished sweep for that pass (`owner_late`). A pass egui will not run again gets a +/// repaint, which runs the owner's check in the next frame. +fn rerun_for_owner(ctx: &Context) { + if sizing::discardable(ctx) { + sizing::request_discard(ctx, sizing::Rerun::Edit); + } else { + ctx.request_repaint(); + } +} + pub(crate) struct ToggleTarget { pub id: Id, pub layer: areas::Layer, @@ -159,25 +254,36 @@ pub(crate) fn value(ctx: &Context, target: ToggleTarget, group: Id, on: Option::with(ctx, viewport, |record| { record.advance(pass, &input, cancelled); + record.asked.insert(id); let finished = record.completed.as_ref().filter(|finished| eligible(&finished.sweep))?; let sweep = &finished.sweep; if sweep.owner == id { - return Some((sweep.on, None)); + // A sweep that finished with the next press never ran its owner's check, so it runs now, over the finished path. + return Some(Ready::Owner { on: sweep.on, replay: false, gives: Gives::of(sweep) }); } - (!sweep.visited.contains(&id)).then(|| (sweep.on, Some(Arc::clone(&finished.path)))) + (!sweep.visited.contains(&id)).then(|| Ready::Sibling { on: sweep.on, path: Arc::clone(&finished.path) }) }) - .and_then(|(on, path)| { - if let Some(path) = path { - if !crosses_visible(ctx, layer, visible, &path) { + .and_then(|ready| match ready { + Ready::Owner { on, gives, .. } => { + if !gives.takes(ctx, layer, visible) { return None; } PerViewport::::with(ctx, viewport, |record| { - if let Some(finished) = &mut record.completed { - finished.sweep.visited.insert(id); + if let Some(finished) = record.completed.as_mut().filter(|finished| finished.sweep.owner == id) { + finished.sweep.engaged = true; } }); + Some(on) + } + Ready::Sibling { on, path } => { + if !crosses_visible(ctx, layer, visible, &path) { + return None; + } + if PerViewport::::with(ctx, viewport, |record| record.completed_taken(id)) { + rerun_for_owner(ctx); + } + Some(on) } - Some(on) }); let ready = PerViewport::::with(ctx, viewport, |record| { match press { @@ -189,26 +295,36 @@ pub(crate) fn value(ctx: &Context, target: ToggleTarget, group: Id, on: Option::with(ctx, viewport, |record| { - if let Some(sweep) = &mut record.sweep { - sweep.visited.insert(id); + match ready { + Ready::Owner { on, replay, gives } => { + if !gives.takes(ctx, layer, visible) { + return completed; } - }); + PerViewport::::with(ctx, viewport, |record| { + if let Some(sweep) = record.sweep.as_mut().filter(|sweep| sweep.owner == id) { + sweep.engaged = true; + } + }); + if replay { + ctx.request_repaint(); + } + Some(on) + } + Ready::Sibling { on, path } => { + if !crosses_visible(ctx, layer, visible, &path) { + return completed; + } + if PerViewport::::with(ctx, viewport, |record| record.accept(id)) { + rerun_for_owner(ctx); + } + Some(on) + } } - Some(on) } /// Keep the entire part of the path inside the rect: a floating layer may cover only part of it. diff --git a/crates/ui-contract/src/runtime/wheel.rs b/crates/ui-contract/src/runtime/wheel.rs index 5563d9a6c9..dc0720d782 100644 --- a/crates/ui-contract/src/runtime/wheel.rs +++ b/crates/ui-contract/src/runtime/wheel.rs @@ -13,6 +13,13 @@ use craft_behavior::{ }; use craft_keymap::Mods; use egui::{Context, Id, IdMap, Pos2, Vec2}; +use std::sync::atomic::{AtomicU64, Ordering}; + +/// The process-unique identity of a wheel share that can be claimed. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ClaimToken(u64); + +static NEXT_CLAIM_TOKEN: AtomicU64 = AtomicU64::new(0); pub(crate) struct State { this: Vec>, @@ -23,6 +30,7 @@ pub(crate) struct State { /// The last-pressed gated control while the pointer has stayed inside it since. armed: Option, shares: Vec<(Id, Wheel)>, + recipients: Vec, /// The wheel gesture the split tracks across passes. gesture: WheelGesture, /// The running gesture's gathered scroll in its owner's points, reset when the gesture closes. @@ -37,6 +45,14 @@ pub(crate) struct State { modal: bool, /// The time of the last wheel event a modal held; −∞ before the first. modal_last: f64, + /// The owner's claims on the running gesture, reset when the gesture closes. + claim: Claim, + /// The owner, token and motion of the running gesture's last share, which a claim in the same pass takes. + last_share: Option<(Id, ClaimToken, Vec2, Vec2)>, + /// This pass's claim of the last share, with the motion it spent; it joins `claim` when the next share gathers. + pending: Option<(Vec2, Vec2, Vec2)>, + /// Each registered owner remains here until it reads the cancellation of its claimed motion. + cancellations: IdMap<()>, /// The last gesture the device ended, which a momentum run of the same owner within `GESTURE_GAP` resumes. device_ended: Option, /// The wheel ease each owner holds. @@ -52,6 +68,7 @@ impl Default for State { last_layers: IdMap::default(), armed: None, shares: Vec::new(), + recipients: Vec::new(), gesture: WheelGesture::default(), gathered: Vec2::ZERO, zoom_gathered: Vec2::ZERO, @@ -59,6 +76,10 @@ impl Default for State { held: Mods::NONE, modal: false, modal_last: f64::NEG_INFINITY, + claim: Claim::default(), + last_share: None, + pending: None, + cancellations: IdMap::default(), device_ended: None, eases: IdMap::default(), } @@ -75,6 +96,32 @@ struct Ended { moved: bool, held: Mods, modal: bool, + claim: Claim, +} + +/// What the owner of a gesture claimed of it: whether it claimed a share, the claimed shares' scroll and zoom lines, +/// and the motion it said it spent. +#[derive(Clone, Copy, Default)] +struct Claim { + claimed: bool, + gathered: Vec2, + zoom_gathered: Vec2, + spent: Vec2, +} + +impl Claim { + /// Gives `share` the claims made before it. + fn give(self, share: &mut Wheel) { + share.claimed = self.claimed; + share.claimed_gathered = self.gathered; + share.claimed_zoom_gathered = self.zoom_gathered; + share.claimed_spent = self.spent; + } + + /// These claims and one more, of a share of `scroll` and `zoom_lines` that spent `spent`. + fn with(self, scroll: Vec2, zoom_lines: Vec2, spent: Vec2) -> Self { + Claim { claimed: true, gathered: self.gathered + scroll, zoom_gathered: self.zoom_gathered + zoom_lines, spent: self.spent + spent } + } } /// The modifiers held in `a` or in `b`. @@ -95,6 +142,70 @@ pub(crate) fn mark_moved(ctx: &Context, id: Id) { }); } +/// The token for the share `id` can claim in the running pass, including after it reads the share. +pub fn claim_token(ctx: &Context, id: Id) -> Option { + let running = crate::runtime::frame::running(ctx)?; + PerViewport::::with(ctx, running.viewport, |state| state.last_share.filter(|(owner, _, _, _)| *owner == id).map(|share| share.1)) +} + +/// Claims for `id` this pass's share of the wheel gesture it owns, and records `spent`, the part of the claimed motion +/// it used up, in its own unit, returning whether the claim succeeded. The shares that follow in the gesture carry +/// `claimed` and the claimed motion (`Wheel::claimed_gathered`, `claimed_zoom_gathered` and `claimed_spent`); a share +/// the owner does not claim is not counted in them. A second claim in the same pass replaces the first, so a body +/// that runs twice claims once. Without a share for `id` in the running pass, or if `id` does not own the gesture, +/// it returns `false` without changing the claims. `token` must identify the share being claimed. +pub fn claim(ctx: &Context, id: Id, token: ClaimToken, spent: Vec2) -> bool { + if !spent.is_finite() { + return false; + } + let Some(running) = crate::runtime::frame::running(ctx) else { return false }; + PerViewport::::with(ctx, running.viewport, |state| { + let Some((owner, shared_token, scroll, zoom_lines)) = state.last_share else { return false }; + if owner != id || shared_token != token { + return false; + } + if state.gesture.owner != Some(id) { + return false; + } + state.pending = Some((scroll, zoom_lines, spent)); + state.cancellations.insert(id, ()); + // The eased wheel's owed motion stops with the claim: the owner's view moves no further by the gesture. + state.eases.remove(&id); + let now = crate::runtime::frame::clock(ctx); + // The swipe the device ended in this pass goes on in its momentum run, which must see the claim too. + let claimed = state.claim.with(scroll, zoom_lines, spent); + if let Some(ended) = state.device_ended.as_mut().filter(|ended| ended.owner == id && ended.at == now) { + ended.claim = claimed; + } + true + }) +} + +/// Returns whether `id` claimed the running gesture or has an unread cancellation from a claim, and consumes that +/// cancellation. A cancellation persists after the gesture closes until the owner reads it or stops registering. +pub fn claimed(ctx: &Context, id: Id) -> bool { + PerViewport::::with(ctx, pass::current_viewport(ctx), |state| { + let canceled = state.cancellations.remove(&id).is_some(); + canceled || (state.gesture.owner == Some(id) && (state.claim.claimed || state.pending.is_some())) + }) +} + +/// Marks the wheel gesture `id` owns or received a share of in this pass as begun or gone on under an app's own +/// modal window that the wheel service does not see as a modal layer. The gesture's later shares carry +/// `Wheel::modal` until it ends. +pub fn mark_modal(ctx: &Context, id: Id) { + PerViewport::::with(ctx, pass::current_viewport(ctx), |state| { + let received = state.recipients.contains(&id); + if state.gesture.owner == Some(id) || received { + state.modal = true; + } + let now = crate::runtime::frame::clock(ctx); + if let Some(ended) = state.device_ended.as_mut().filter(|ended| ended.owner == id || (received && ended.at == now)) { + ended.modal = true; + } + }); +} + /// Feeds `pan` to the wheel ease of `id` and returns this pass's eased step. The step is paid by the clock, so a /// later pass of the same frame pays zero. pub(crate) fn ease(ctx: &Context, id: Id, pan: Vec2) -> Vec2 { @@ -142,6 +253,7 @@ impl State { } let last = &self.last; self.eases.retain(|id, _| last.iter().any(|taker| taker.owner == *id)); + self.cancellations.retain(|id, _| last.iter().any(|taker| taker.owner == *id)); let open = self.gesture.last.is_finite(); let ended = self.gesture.end(if pressed { f64::INFINITY } else { now }); if open && !self.gesture.last.is_finite() { @@ -150,6 +262,7 @@ impl State { self.moved = false; self.held = Mods::NONE; self.modal = false; + self.clear_claim(Claim::default()); } ended } @@ -166,9 +279,25 @@ impl State { swipe.map_or((Vec2::ZERO, Vec2::ZERO, false, Mods::NONE), |ended| (ended.gathered, ended.zoom_gathered, ended.moved, ended.held)); // A turn that went on under a modal until just now goes on under it after the modal closes. self.modal = swipe.is_some_and(|ended| ended.modal) || now - self.modal_last < GESTURE_GAP; + self.clear_claim(swipe.map_or(Claim::default(), |ended| ended.claim)); swipe.map(|ended| ended.owner) } + /// Starts the running gesture's claims at `claim`, with no claim pending. + fn clear_claim(&mut self, claim: Claim) { + self.claim = claim; + self.last_share = None; + self.pending = None; + } + + /// Adds this pass's claim, if any, to the running gesture's claims. + fn settle_claim(&mut self) { + if let Some((scroll, zoom_lines, spent)) = self.pending.take() { + self.claim = self.claim.with(scroll, zoom_lines, spent); + } + self.last_share = None; + } + /// Adds `share`, in its owner's points, to the gesture it belongs to and gives it the gesture's gathered scroll, /// mark and held modifiers; a share of another owner than the gesture's gathers only itself. Every share carries /// whether the gesture went on under a modal. A point share cancels its owner's @@ -181,6 +310,12 @@ impl State { } share.modal = self.modal; if self.gesture.owner == Some(owner) { + self.claim.give(share); + if self.last_share.is_none() + && let Ok(token) = NEXT_CLAIM_TOKEN.try_update(Ordering::Relaxed, Ordering::Relaxed, |next| next.checked_add(1)) + { + self.last_share = Some((owner, ClaimToken(token), share.scroll, share.zoom_lines)); + } self.gathered += share.scroll; self.zoom_gathered += share.zoom_lines; share.gathered = self.gathered; @@ -280,10 +415,18 @@ pub(crate) fn begin(ctx: &Context, pointer_scoped_field_wheel: bool) { let modal_family = crate::runtime::overlay::top_modal_in(ctx, viewport) .filter(|_| !hover.is_some_and(|at| hole.as_ref().is_some_and(|hole| hole.answers(at)))) .map(|modal| crate::runtime::overlay::family(ctx, modal.id)); + // The layer under the pointer, read only in a pass that carries wheel, pinch or touch input. + let wheel_like = wheel_in.is_some() + || pinched + || zoom_lines != Vec2::ZERO + || frame.as_ref().is_some_and(|frame| frame.multi_touch.is_some() || frame.zoom != 1.0 || frame.rotation != 0.0); + let under = hover.filter(|_| wheel_like).and_then(|at| crate::runtime::overlay::layer_under(ctx, at)); let wake = PerViewport::::with(ctx, viewport, |state| { state.last = std::mem::take(&mut state.this); state.last_layers = std::mem::take(&mut state.this_layers); state.shares.clear(); + // Last pass's claim joins the gesture's; a claim in this pass takes only a share of this pass. + state.settle_claim(); if let Some(winner) = pressed_on { state.armed = winner.filter(|id| state.last.iter().any(|taker| taker.gated && taker.owner == *id)); } @@ -306,6 +449,7 @@ pub(crate) fn begin(ctx: &Context, pointer_scoped_field_wheel: bool) { let held_before = if closing_press { either(state.held, press_mods) } else { state.held }; // A wheel a modal held in the pass before that press arrived during the gesture too. let modal_before = state.modal || (closing_press && wheel_before_press && (blocked || modal_family.is_some())); + let claim_before = state.claim; let ended = state.close_gesture(pressed_on.is_some(), now); let ended = ended.filter(|owner| state.last.iter().any(|taker| taker.owner == *owner && taker.value)); // A key tapped between the running gesture's wheel events counts as held for the rest of it, and one tapped @@ -325,6 +469,7 @@ pub(crate) fn begin(ctx: &Context, pointer_scoped_field_wheel: bool) { // The end carries the metadata of the gesture it ends. let mut end = Wheel::new(Vec2::ZERO, mods, WheelUnit::Point, WheelPhase::End); (end.held, end.modal) = (held_before, modal_before); + claim_before.give(&mut end); state.shares.push((owner, end)); } if let (Some(frame), Some(at)) = (&frame, hover) @@ -362,22 +507,33 @@ pub(crate) fn begin(ctx: &Context, pointer_scoped_field_wheel: bool) { let held_mods = if state.gesture.runs(now) { pass_mods } else { wheel_mods }; let swipe = state.open_gesture(source, now); // A point over a modal admits its own wheel takers, not a canvas below the modal. + // A point over a layer admits the takers of that layer, not those of a floating panel or the canvas + // below it. The focused field and the owner of the running gesture keep the wheel wherever the + // pointer is, as the split has it. + let layer_of = |taker: &WheelTaker| state.last_layers.get(&taker.owner).copied().flatten(); + let running_owner = state.gesture.owner.filter(|_| state.gesture.runs(now)); let eligible: Vec<_> = state .last .iter() .copied() + .filter(|taker| modal_family.as_ref().is_none_or(|family| layer_of(taker).is_some_and(|layer| family.contains(&layer)))) .filter(|taker| { - modal_family.as_ref().is_none_or(|family| { - state.last_layers.get(&taker.owner).and_then(|layer| *layer).is_some_and(|layer| family.contains(&layer)) + under.as_ref().is_none_or(|under| { + under.holds(layer_of(taker)) || running_owner == Some(taker.owner) || (taker.field && focused == Some(taker.owner)) }) }) .collect(); - let (previous_owner, held, modal) = (state.gesture.owner, state.held, state.modal); + let (previous_owner, held, modal, claimed) = (state.gesture.owner, state.held, state.modal, state.claim); let shares = split(&eligible, at, share, focus, state.armed, &mut state.gesture, now); // A momentum run resumes its swipe only on the swipe's owner; any split drops the ended swipe. if swipe.is_some() && state.gesture.owner != swipe { (state.gathered, state.zoom_gathered, state.moved, state.held) = (Vec2::ZERO, Vec2::ZERO, false, Mods::NONE); state.modal = now - state.modal_last < GESTURE_GAP; + state.clear_claim(Claim::default()); + } + // A running gesture the split hands to another owner starts its claims again: the new owner claimed none. + if previous_owner.is_some() && state.gesture.owner != previous_owner { + state.clear_claim(Claim::default()); } state.held = either(state.held, either(mods, held_mods)); state.device_ended = None; @@ -393,12 +549,15 @@ pub(crate) fn begin(ctx: &Context, pointer_scoped_field_wheel: bool) { state.gather(owner, &mut share); if share.phase == WheelPhase::End && Some(owner) == previous_owner && state.gesture.owner != previous_owner { (share.held, share.modal) = (held, modal); + claimed.give(&mut share); } state.shares.push((owner, share)); } if device_end { - let (gathered, zoom_gathered, moved, held, modal) = (state.gathered, state.zoom_gathered, state.moved, state.held, state.modal); - state.device_ended = state.gesture.owner.map(|owner| Ended { owner, at: now, gathered, zoom_gathered, moved, held, modal }); + let (gathered, zoom_gathered, moved, held, modal, claim) = + (state.gathered, state.zoom_gathered, state.moved, state.held, state.modal, state.claim); + state.device_ended = + state.gesture.owner.map(|owner| Ended { owner, at: now, gathered, zoom_gathered, moved, held, modal, claim }); } } } @@ -410,6 +569,8 @@ pub(crate) fn begin(ctx: &Context, pointer_scoped_field_wheel: bool) { state.shares.remove(0); state.shares[at].1.phase = WheelPhase::Start; } + state.recipients.clear(); + state.recipients.extend(state.shares.iter().map(|(owner, _)| *owner)); // A value control that owns the running gesture hears its end without a timer of its own: a pass at the gap. // An owed ease pays in the passes that follow. state.wake(now) diff --git a/crates/ui-contract/src/runtime/windows/hit.rs b/crates/ui-contract/src/runtime/windows/hit.rs index 5a5ba18a21..de8938eca8 100644 --- a/crates/ui-contract/src/runtime/windows/hit.rs +++ b/crates/ui-contract/src/runtime/windows/hit.rs @@ -248,11 +248,17 @@ fn regions_of(ctx: &Context, viewport: ViewportId, parts: &[ExclusivePart]) -> O /// clipped to the band: each interactive egui widget of the running pass that egui's hit test puts above the /// component's widgets, and each of the component's own shapes that a press there goes to instead of the band (a /// member over it, a higher part). The component's widgets resolve as the component (8.3), so they are not hits -/// over the band themselves. +/// over the band themselves. Another component's widget resolves the same way: only its parts that take a press +/// cover the band, so a dialog's title row covers it with its close button and not with its whole row, whose title +/// leaves the press to the band (photocraft: Preferences in its own window did not move by its title row). fn covers_of(ctx: &Context, viewport: ViewportId, owner: Id, part: PartRef, band: Rect) -> Vec { let over = pointer::over_part(ctx, viewport, owner, part); widgets::above(ctx, owner, &over.widgets) .into_iter() + .flat_map(|(widget, rect)| match pointer::press_shapes_of_widget(ctx, viewport, widget) { + Some(shapes) => shapes.into_iter().map(|shape| shape.intersect(rect)).collect(), + None => vec![rect], + }) .chain(over.above) .map(|cover| cover.intersect(band)) .filter(|cover| cover.is_positive()) diff --git a/crates/ui-contract/src/testing/fixture.rs b/crates/ui-contract/src/testing/fixture.rs index f662509a07..ada546df7e 100644 --- a/crates/ui-contract/src/testing/fixture.rs +++ b/crates/ui-contract/src/testing/fixture.rs @@ -528,11 +528,12 @@ impl Fixture { let Some(mut paint) = self.frames.take_paint() else { return out }; // Only the shapes are asked for: the texture changes since the first recorded frame go unrendered. paint.textures_delta.clear(); + let mut shapes = Vec::new(); + let options = self.ctx().tessellation_options(|options| *options); for clipped in paint.shapes { - let mut shapes = Vec::new(); - fixture::flatten(clipped.shape, &mut shapes); - out.extend(shapes.into_iter().map(|shape| (clipped.clip_rect, shape))); + fixture::flatten(clipped, paint.pixels_per_point, options, &mut shapes); } + out.extend(shapes.into_iter().map(|(shape, clip)| (clip, shape))); out } @@ -541,14 +542,15 @@ impl Fixture { pub fn frame_shapes_with(&mut self, events: Vec) -> Vec { self.frames.record_paint(); self.frame(events); - let mut shapes = Vec::new(); - let Some(mut paint) = self.frames.take_paint() else { return shapes }; + let Some(mut paint) = self.frames.take_paint() else { return Vec::new() }; // Only the shapes are asked for: the texture changes since the first recorded frame go unrendered. paint.textures_delta.clear(); + let mut shapes = Vec::new(); + let options = self.ctx().tessellation_options(|options| *options); for clipped in paint.shapes { - fixture::flatten(clipped.shape, &mut shapes); + fixture::flatten(clipped, paint.pixels_per_point, options, &mut shapes); } - shapes + shapes.into_iter().map(|(shape, _)| shape).collect() } /// `n` frames with no events. diff --git a/crates/ui-contract/src/testing/host_key_trials.rs b/crates/ui-contract/src/testing/host_key_trials.rs index ee407f6589..5995592607 100644 --- a/crates/ui-contract/src/testing/host_key_trials.rs +++ b/crates/ui-contract/src/testing/host_key_trials.rs @@ -20,7 +20,7 @@ use crate::testing::input::{key_press, key_reached, slop}; use crate::testing::pointer::{self, moved, press, release}; use crate::testing::sensing::{self, ProbeRoot}; use crate::testing::{Frames, trial}; -use craft_behavior::{EditCommand, Input, Intent, Metrics, Sense}; +use craft_behavior::{EditCommand, EditorInput, Input, Intent, Metrics, Sense}; use egui::{Event, Id, ImeEvent, Key, Modifiers, Pos2, Rect, Response, Ui, ViewportId}; use std::cell::{Cell, RefCell}; use std::rc::Rc; @@ -440,6 +440,52 @@ fn an_app_editor_s_reset_asked_at_the_press_on_it_while_a_framework_field_compos assert_eq!(editor.borrow().text, "X", "the field's late commit is fenced and the editor takes the commit after the completion"); } +/// The app's editor asks for its own reset while a framework field keeps the focus and composes, so the field's +/// composition is interrupted and fenced on the app's request. When the late commit, the completion and a new commit +/// arrive in one frame, the field receives only the commit after the completion. +#[trial] +fn an_app_editor_s_reset_completing_while_a_framework_field_keeps_the_focus_drops_the_late_commit_before_it() { + let edits = Rc::new(RefCell::new(Vec::new())); + let log = Rc::clone(&edits); + let editor = Rc::new(RefCell::new(fixture::ResettingEditor::default())); + let held = Rc::clone(&editor); + let rect = Rect::from_min_size(Pos2::new(100.0, 100.0), egui::vec2(200.0, 30.0)); + let framework = named_id("framework field"); + let mut show = move |ui: &mut Ui| { + let field = widget(ui, framework); + register_stop(ui.ctx(), Stop::new(framework, KeyUse::of(Input::Text)).text()); + log.borrow_mut().extend(ime::take(ui.ctx(), framework, false)); + ime::note_caret(ui.ctx(), framework, field, field, false); + fixture::host_resetting_ime_editor(ui, host_editor_id(), rect, &mut held.borrow_mut()); + }; + let mut frames = Frames::new(); + frames.idle(2, &mut show); + request(&frames.ctx, FocusTarget::Id(framework)); + frames.frame(Vec::new(), &mut show); + frames.frame(vec![Event::Ime(ImeEvent::Preedit { text: "k".to_owned(), active_range_chars: None })], &mut show); + assert_eq!(frames.ime().map(|ime| ime.owner), Some(framework), "the framework field composes"); + editor.borrow_mut().ask = true; + frames.frame(Vec::new(), &mut show); + let own = editor.borrow().reset; + assert!(own.is_some(), "the editor asked for its own reset"); + let ime = frames.ime().cloned(); + assert!(ime.as_ref().is_some_and(|ime| ime.owner == framework && ime.interrupt), "the request interrupts the field's composition"); + let Some(own) = own else { return }; + edits.borrow_mut().clear(); + frames.frame( + vec![ + Event::Ime(ImeEvent::Commit("Q".to_owned())), + Event::ImeResetCompleted { request_id: own }, + Event::Ime(ImeEvent::Commit("X".to_owned())), + ], + &mut show, + ); + assert_eq!(frames.ime().map(|ime| ime.owner), Some(framework), "the field keeps the IME"); + let texts: Vec<_> = + edits.borrow().iter().filter_map(|edit| if let EditorInput::Text(text) = edit { Some(text.to_string()) } else { None }).collect(); + assert_eq!(texts, ["X"], "the late commit before the completion is fenced, and the commit after it reaches the field"); +} + #[trial] fn a_focused_egui_field_keeps_escape_and_the_clipboard_and_tabs_on_through_the_one_order() { let (host, mut show) = host_window(); diff --git a/crates/ui-contract/tests/it/paint/chunk_members.rs b/crates/ui-contract/tests/it/paint/chunk_members.rs new file mode 100644 index 0000000000..06fa1b0019 --- /dev/null +++ b/crates/ui-contract/tests/it/paint/chunk_members.rs @@ -0,0 +1,1155 @@ +//! The test fixtures read a paint chunk's members where egui draws them: each member moves by its own transform after +//! the chunk's and shows only inside its own clip rect within the chunk's. + +use craft_ui::testing::{Fixture, Frames, trial}; +use egui::emath::TSTransform; +use egui::epaint::{ClippedShape, PaintCallback}; +use egui::{Color32, FontId, Rect, Shape, Ui, Vec2, pos2, vec2}; +use std::cell::Cell; +use std::rc::Rc; +use std::sync::Arc; + +const FILL: Color32 = Color32::from_rgb(200, 40, 40); +const BOX: Rect = Rect { min: pos2(10.0, 10.0), max: pos2(30.0, 20.0) }; +/// The member's own clip rect, narrower than the window on the left. +const MEMBER_CLIP: Rect = Rect { min: pos2(80.0, 0.0), max: pos2(390.0, 290.0) }; +const TEXT_AT: egui::Pos2 = pos2(10.0, 30.0); + +thread_local! { + /// The text run's size as laid out, before the member's transform. + static LAID_OUT: Cell = const { Cell::new(Vec2::ZERO) }; +} + +fn moved() -> TSTransform { + TSTransform::new(vec2(40.0, 30.0), 2.0) +} + +/// Paints one chunk whose members, a filled box and a text run, carry their own transform and clip rect. +fn paint_chunk(ui: &mut Ui) { + let galley = ui.painter().layout_no_wrap("chunk".to_owned(), FontId::proportional(14.0), Color32::WHITE); + LAID_OUT.set(galley.rect.size()); + let members = [Shape::rect_filled(BOX, 0.0, FILL), Shape::galley(TEXT_AT, galley, Color32::WHITE)].map(|shape| ClippedShape { + clip_rect: MEMBER_CLIP, + shape, + transform_after_tessellation: moved(), + }); + ui.painter().add(Shape::PaintChunk(Arc::from(members))); +} + +/// Where the box is drawn: moved, then cut to the member's clip rect. +fn drawn_box() -> Rect { + (moved() * BOX).intersect(MEMBER_CLIP) +} + +fn the_box(shapes: &[Shape]) -> Rect { + let boxes: Vec = + shapes.iter().filter(|shape| matches!(shape, Shape::Rect(rect) if rect.fill == FILL)).map(Shape::visual_bounding_rect).collect(); + assert_eq!(boxes.len(), 1, "one box is painted: {boxes:?}"); + boxes[0] +} + +#[trial] +fn a_fixture_reads_a_chunk_member_through_its_own_transform_and_clip() { + let mut fixture = Fixture::new(paint_chunk); + fixture.settle(); + + let clipped = fixture.frame_clipped_shapes(); + let boxes: Vec<(Rect, Rect)> = clipped + .iter() + .filter(|(_, shape)| matches!(shape, Shape::Rect(rect) if rect.fill == FILL)) + .map(|(clip, shape)| (*clip, shape.visual_bounding_rect())) + .collect(); + assert_eq!(boxes.len(), 1, "one box is painted: {boxes:?}"); + let (clip, bounds) = boxes[0]; + assert_eq!(bounds, moved() * BOX, "frame_clipped_shapes: the box moves by the member's transform"); + assert!(MEMBER_CLIP.contains_rect(clip), "frame_clipped_shapes: the clip {clip:?} is within the member's"); + + assert_eq!(the_box(&fixture.frame_shapes()), moved() * BOX, "frame_shapes: the box moves by the member's transform"); + + fixture.frame(Vec::new()); + assert!(fixture.shape_bounds().contains(&drawn_box()), "shape_bounds holds the drawn box {:?}: {:?}", drawn_box(), fixture.shape_bounds()); + let text = fixture.texts().iter().find(|text| text.text == "chunk").expect("the text run is painted"); + assert_eq!(text.rect.min, moved() * TEXT_AT, "texts: the run moves by the member's transform"); + assert_eq!(text.rect.size(), LAID_OUT.get() * moved().scaling, "texts: the run scales by the member's transform"); + assert!( + text.baseline > text.rect.min.y && text.baseline < text.rect.max.y, + "texts: the baseline {} lies in the run {:?}", + text.baseline, + text.rect + ); + assert!(MEMBER_CLIP.contains_rect(text.clip), "texts: the clip {:?} is within the member's", text.clip); +} + +#[trial] +fn frames_read_a_chunk_member_through_its_own_transform() { + let mut frames = Frames::new(); + let shapes = frames.frame_shapes(paint_chunk); + assert_eq!(the_box(&shapes), moved() * BOX, "the box moves by the member's transform"); +} + +/// The clip rect of the outer chunk that holds the nested one, inside the window. It cuts the drawn box on the right, +/// and the member's clip cuts it on the left. +const PARENT_CLIP: Rect = Rect { min: pos2(50.0, 20.0), max: pos2(140.0, 250.0) }; + +fn parent() -> TSTransform { + TSTransform::new(vec2(5.0, 8.0), 1.5) +} + +/// Paints the chunk of [`paint_chunk`] as the only member of an outer chunk with its own transform and clip rect. +fn paint_nested_chunk(ui: &mut Ui) { + let galley = ui.painter().layout_no_wrap("chunk".to_owned(), FontId::proportional(14.0), Color32::WHITE); + LAID_OUT.set(galley.rect.size()); + let members = [Shape::rect_filled(BOX, 0.0, FILL), Shape::galley(TEXT_AT, galley, Color32::WHITE)].map(|shape| ClippedShape { + clip_rect: MEMBER_CLIP, + shape, + transform_after_tessellation: moved(), + }); + let inner = ClippedShape { clip_rect: PARENT_CLIP, shape: Shape::PaintChunk(Arc::from(members)), transform_after_tessellation: parent() }; + ui.painter().add(Shape::PaintChunk(Arc::from([inner]))); +} + +/// The nested members' transform: the member's first, then the outer chunk's. +fn composed() -> TSTransform { + parent() * moved() +} + +/// The nested members' clip: the member's clip, moved by the outer chunk's transform, within the outer chunk's clip. +fn composed_clip() -> Rect { + PARENT_CLIP.intersect(parent() * MEMBER_CLIP) +} + +#[trial] +fn a_fixture_reads_a_nested_chunk_member_through_both_transforms_and_clips() { + let mut fixture = Fixture::new(paint_nested_chunk); + fixture.settle(); + + let clipped = fixture.frame_clipped_shapes(); + let boxes: Vec<(Rect, Rect)> = clipped + .iter() + .filter(|(_, shape)| matches!(shape, Shape::Rect(rect) if rect.fill == FILL)) + .map(|(clip, shape)| (*clip, shape.visual_bounding_rect())) + .collect(); + assert_eq!(boxes.len(), 1, "one box is painted: {boxes:?}"); + let (clip, bounds) = boxes[0]; + assert_eq!(bounds, composed() * BOX, "frame_clipped_shapes: the box moves by the member's transform, then the outer chunk's"); + assert_eq!(clip, composed_clip(), "frame_clipped_shapes: the clip is the member's within the outer chunk's"); + + assert_eq!(the_box(&fixture.frame_shapes()), composed() * BOX, "frame_shapes: the box moves by both transforms"); + + fixture.frame(Vec::new()); + let drawn = (composed() * BOX).intersect(composed_clip()); + assert!(fixture.shape_bounds().contains(&drawn), "shape_bounds holds the drawn box {drawn:?}: {:?}", fixture.shape_bounds()); + let text = fixture.texts().iter().find(|text| text.text == "chunk").expect("the text run is painted"); + assert_eq!(text.rect.min, composed() * TEXT_AT, "texts: the run moves by both transforms"); + assert_eq!(text.rect.size(), LAID_OUT.get() * composed().scaling, "texts: the run scales by both transforms"); + assert_eq!(text.clip, composed_clip(), "texts: the clip is the member's within the outer chunk's"); +} + +#[trial] +fn nested_chunk_members_under_negative_parent_scales_are_not_reported() { + let parent = TSTransform::new(vec2(180.0, 160.0), -2.0); + let parent_clip = Rect::from_min_max(pos2(115.0, 105.0), pos2(160.0, 145.0)); + let member_clip = Rect::from_min_max(pos2(15.0, 5.0), pos2(45.0, 40.0)); + let transformed_clip = Rect::from_two_pos(parent * member_clip.min, parent * member_clip.max); + let expected_clip = parent_clip.intersect(transformed_clip); + for (member_scale, member_at) in [(-0.5, vec2(40.0, 30.0)), (0.5, vec2(15.0, 10.0))] { + let member = TSTransform::new(member_at, member_scale); + let composed = parent * member; + let bounds = Rect::from_two_pos(composed * BOX.min, composed * BOX.max); + let overlap = bounds.intersect(expected_clip); + assert!(overlap.is_positive(), "the composed box {bounds:?} overlaps the clip {expected_clip:?}"); + let paint = move |ui: &mut Ui| { + let galley = ui.painter().layout_no_wrap("chunk".to_owned(), FontId::proportional(14.0), Color32::WHITE); + let members = [Shape::rect_filled(BOX, 0.0, FILL), Shape::galley(TEXT_AT, galley, Color32::WHITE)].map(|shape| ClippedShape { + clip_rect: member_clip, + shape, + transform_after_tessellation: member, + }); + let inner = ClippedShape { clip_rect: parent_clip, shape: Shape::PaintChunk(Arc::from(members)), transform_after_tessellation: parent }; + ui.painter().add(Shape::PaintChunk(Arc::from([inner]))); + }; + let mut fixture = Fixture::new(paint); + fixture.settle(); + + assert!(expected_clip.is_positive()); + assert!(!fixture.shape_bounds().iter().any(|reported| reported.intersects(overlap)), "{:?}", fixture.shape_bounds()); + assert!(!fixture.texts().iter().any(|text| text.text == "chunk")); + + for shapes in + [fixture.frame_shapes(), fixture.frame_clipped_shapes().into_iter().map(|(_, shape)| shape).collect(), Frames::new().frame_shapes(paint)] + { + assert!(!shapes.iter().any(|shape| matches!(shape, Shape::Rect(rect) if rect.fill == FILL))); + assert!(!shapes.iter().any(|shape| matches!(shape, Shape::Text(text) if text.galley.job.text == "chunk"))); + } + } +} + +#[trial] +fn chunk_members_with_empty_effective_clips_are_not_reported() { + let parent_clip = Rect::from_min_max(pos2(20.0, 20.0), pos2(120.0, 120.0)); + for member_clip in [ + Rect::NOTHING, + Rect::from_min_max(pos2(120.0, 20.0), pos2(200.0, 200.0)), + Rect::from_min_max(pos2(20.0, 120.0), pos2(200.0, 200.0)), + Rect::from_min_max(pos2(120.0, 120.0), pos2(200.0, 200.0)), + Rect::from_min_max(pos2(130.0, 20.0), pos2(200.0, 200.0)), + ] { + let hidden_bounds = parent_clip.intersect(member_clip); + let mut fixture = Fixture::new(move |ui| { + let galley = ui.painter().layout_no_wrap("hidden".to_owned(), FontId::proportional(14.0), Color32::WHITE); + let members = [ + Shape::rect_filled(Rect::from_min_max(egui::Pos2::ZERO, pos2(200.0, 200.0)), 0.0, FILL), + Shape::galley(TEXT_AT, galley, Color32::WHITE), + ] + .map(|shape| ClippedShape { clip_rect: member_clip, shape, transform_after_tessellation: TSTransform::IDENTITY }); + let inner = ClippedShape { + clip_rect: parent_clip, + shape: Shape::PaintChunk(Arc::from(members)), + transform_after_tessellation: TSTransform::IDENTITY, + }; + ui.painter().add(Shape::PaintChunk(Arc::from([inner]))); + ui.painter().text(pos2(30.0, 40.0), egui::Align2::LEFT_TOP, "visible", FontId::proportional(14.0), Color32::WHITE); + }); + fixture.settle(); + + assert!(!fixture.shape_bounds().contains(&hidden_bounds)); + assert!(!fixture.texts().iter().any(|text| text.text == "hidden")); + assert!(fixture.texts().iter().any(|text| text.text == "visible")); + for shapes in [fixture.frame_shapes(), fixture.frame_clipped_shapes().into_iter().map(|(_, shape)| shape).collect()] { + assert!(!shapes.iter().any(|shape| matches!(shape, Shape::Rect(rect) if rect.fill == FILL))); + assert!(!shapes.iter().any(|shape| matches!(shape, Shape::Text(text) if text.galley.job.text == "hidden"))); + assert!(shapes.iter().any(|shape| matches!(shape, Shape::Text(text) if text.galley.job.text == "visible"))); + } + } +} + +#[trial] +fn positively_scaled_chunk_members_outside_their_clip_are_not_reported() { + let transform = TSTransform::new(vec2(400.0, 0.0), 2.0); + let paint = move |ui: &mut Ui| { + let member = ClippedShape { clip_rect: MEMBER_CLIP, shape: Shape::rect_filled(BOX, 0.0, FILL), transform_after_tessellation: transform }; + ui.painter().add(Shape::PaintChunk(Arc::from([member]))); + ui.painter().text(pos2(30.0, 40.0), egui::Align2::LEFT_TOP, "visible", FontId::proportional(14.0), Color32::WHITE); + }; + let mut fixture = Fixture::new(paint); + fixture.settle(); + + assert!(!fixture.shape_bounds().contains(&(transform * BOX))); + assert!(fixture.texts().iter().any(|text| text.text == "visible")); + for shapes in + [fixture.frame_shapes(), fixture.frame_clipped_shapes().into_iter().map(|(_, shape)| shape).collect(), Frames::new().frame_shapes(paint)] + { + assert!(!shapes.iter().any(|shape| matches!(shape, Shape::Rect(rect) if rect.fill == FILL))); + assert!(shapes.iter().any(|shape| matches!(shape, Shape::Text(text) if text.galley.job.text == "visible"))); + } +} + +#[trial] +fn inverted_source_bounds_are_not_reported() { + for bounds in [ + Rect::from_min_max(pos2(140.0, 100.0), pos2(100.0, 140.0)), + Rect::from_min_max(pos2(100.0, 140.0), pos2(140.0, 100.0)), + Rect::from_min_max(pos2(140.0, 140.0), pos2(100.0, 100.0)), + ] { + let mut fixture = Fixture::new(move |ui| { + ui.painter().add(Shape::rect_filled(bounds, 0.0, FILL)); + ui.painter().add(Shape::rect_filled(BOX, 0.0, FILL)); + }); + fixture.settle(); + + assert!(fixture.shape_bounds().contains(&BOX)); + assert!(!fixture.shape_bounds().contains(&Rect::from_two_pos(bounds.min, bounds.max))); + } + + let bounds = Rect::from_min_max(pos2(140.0, 140.0), pos2(100.0, 100.0)); + let transform = TSTransform::new(vec2(300.0, 300.0), -1.0); + let clip = Rect::from_min_max(pos2(150.0, 150.0), pos2(210.0, 210.0)); + let drawn = transform * bounds; + let paint = move |ui: &mut Ui| { + let member = ClippedShape { clip_rect: clip, shape: Shape::rect_filled(bounds, 0.0, FILL), transform_after_tessellation: transform }; + ui.painter().add(Shape::PaintChunk(Arc::from([member]))); + ui.painter().add(Shape::rect_filled(BOX, 0.0, FILL)); + }; + let mut fixture = Fixture::new(paint); + fixture.settle(); + + assert!(drawn.is_positive()); + assert!(clip.contains_rect(drawn)); + assert!(fixture.shape_bounds().contains(&BOX)); + assert!(!fixture.shape_bounds().contains(&drawn)); + for shapes in + [fixture.frame_shapes(), fixture.frame_clipped_shapes().into_iter().map(|(_, shape)| shape).collect(), Frames::new().frame_shapes(paint)] + { + assert_eq!(the_box(&shapes), BOX); + } +} + +#[trial] +fn positively_transformed_text_outside_its_clip_is_not_reported() { + for transform in [TSTransform::from_translation(vec2(400.0, 0.0)), TSTransform::from_scaling(20.0)] { + let mut fixture = Fixture::new(move |ui| { + let galley = ui.painter().layout_no_wrap("shared".to_owned(), FontId::proportional(14.0), Color32::WHITE); + let hidden = ClippedShape { + clip_rect: MEMBER_CLIP, + shape: Shape::galley(TEXT_AT, galley.clone(), Color32::WHITE), + transform_after_tessellation: transform, + }; + assert!(tessellated(hidden.clone()).is_empty()); + ui.painter().add(Shape::PaintChunk(Arc::from([hidden]))); + ui.painter().galley(TEXT_AT, galley, Color32::WHITE); + }); + fixture.settle(); + + let texts: Vec<_> = fixture.texts().iter().filter(|text| text.text == "shared").collect(); + assert_eq!(texts.len(), 1); + assert_eq!(texts[0].rect.min, TEXT_AT); + for shapes in [fixture.frame_shapes(), fixture.frame_clipped_shapes().into_iter().map(|(_, shape)| shape).collect()] { + let texts: Vec<_> = shapes.iter().filter_map(|shape| if let Shape::Text(text) = shape { Some(text) } else { None }).collect(); + assert_eq!(texts.len(), 1); + assert_eq!(texts[0].pos, TEXT_AT); + } + } +} + +#[trial] +fn transformed_meshes_outside_the_clip_are_not_reported_without_coarse_culling() { + let options = egui::epaint::TessellationOptions { coarse_tessellation_culling: false, ..Default::default() }; + let transform = TSTransform::from_translation(vec2(400.0, 0.0)); + let member = ClippedShape { clip_rect: MEMBER_CLIP, shape: Shape::rect_filled(BOX, 0.0, FILL), transform_after_tessellation: transform }; + let expected = tessellated_with_options(member.clone(), options); + assert_eq!(expected.len(), 1, "egui produces a mesh before renderer clipping"); + assert!(!expected[0].is_positive()); + let paint = move |ui: &mut Ui| { + ui.ctx().tessellation_options_mut(|current| *current = options); + ui.painter().add(Shape::PaintChunk(Arc::from([member.clone()]))); + }; + let mut fixture = Fixture::new(paint.clone()); + fixture.settle(); + + assert!(!fixture.shape_bounds().contains(&expected[0])); + for shapes in + [fixture.frame_shapes(), fixture.frame_clipped_shapes().into_iter().map(|(_, shape)| shape).collect(), Frames::new().frame_shapes(paint)] + { + assert!(!shapes.iter().any(|shape| matches!(shape, Shape::Rect(rect) if rect.fill == FILL))); + } +} + +#[trial] +fn mirrored_bands_keep_ordered_samples_and_vertical_ranges() { + let transform = TSTransform::new(vec2(300.0, 300.0), -1.0); + let clip = Rect::from_min_max(pos2(100.0, 100.0), pos2(260.0, 260.0)); + let source = egui::epaint::BandShape::filled( + vec![ + egui::epaint::BandPoint::new(80.0, 80.0..=140.0), + egui::epaint::BandPoint::new(120.0, 90.0..=160.0), + egui::epaint::BandPoint::new(160.0, 100.0..=150.0), + ], + FILL, + ); + let options = egui::epaint::TessellationOptions { coarse_tessellation_culling: false, feathering: false, ..Default::default() }; + let member = ClippedShape { clip_rect: clip, shape: Shape::Band(source.clone()), transform_after_tessellation: transform }; + let expected = tessellated_with_options(member.clone(), options); + assert_eq!(expected.len(), 1); + assert!(expected[0].is_positive()); + let paint = move |ui: &mut Ui| { + ui.ctx().tessellation_options_mut(|current| *current = options); + ui.painter().add(Shape::PaintChunk(Arc::from([member.clone()]))); + }; + let mut fixture = Fixture::new(paint.clone()); + fixture.settle(); + + for shapes in + [fixture.frame_shapes(), fixture.frame_clipped_shapes().into_iter().map(|(_, shape)| shape).collect(), Frames::new().frame_shapes(paint)] + { + let bands: Vec<_> = shapes.iter().filter_map(|shape| if let Shape::Band(band) = shape { Some(band) } else { None }).collect(); + assert_eq!(bands.len(), 1); + let band = bands[0]; + assert!(band.points.windows(2).all(|pair| pair[0].x < pair[1].x)); + for (point, original) in band.points.iter().zip(source.points.iter().rev()) { + assert!(point.y.min <= point.y.max); + assert_eq!(pos2(point.x, point.y.min), transform * pos2(original.x, original.y.max)); + assert_eq!(pos2(point.x, point.y.max), transform * pos2(original.x, original.y.min)); + } + assert_eq!(band.visual_bounding_rect().intersect(clip), expected[0]); + assert_eq!(tessellated_with_options(ClippedShape::new(clip, Shape::Band(band.clone())), options), expected); + } +} + +#[trial] +fn mirrored_text_has_ordered_layout_bounds_and_preserves_glyph_positions() { + let transform = TSTransform::new(vec2(300.0, 300.0), -2.0); + let clip = Rect::from_min_max(pos2(0.0, 0.0), pos2(400.0, 300.0)); + let options = egui::epaint::TessellationOptions { coarse_tessellation_culling: false, round_text_to_pixels: false, ..Default::default() }; + let mut fixture = Fixture::new(move |ui| { + ui.ctx().tessellation_options_mut(|current| *current = options); + let galley = ui.painter().layout_no_wrap("first\nsecond".to_owned(), FontId::proportional(14.0), Color32::WHITE); + let members = [TSTransform::IDENTITY, transform].map(|transform| ClippedShape { + clip_rect: clip, + shape: Shape::galley(TEXT_AT, galley.clone(), Color32::WHITE), + transform_after_tessellation: transform, + }); + ui.painter().add(Shape::PaintChunk(Arc::from(members))); + }); + fixture.settle(); + + for shapes in [fixture.frame_shapes(), fixture.frame_clipped_shapes().into_iter().map(|(_, shape)| shape).collect()] { + let texts: Vec<_> = shapes.iter().filter_map(|shape| if let Shape::Text(text) = shape { Some(text) } else { None }).collect(); + assert_eq!(texts.len(), 2); + let (original, mirrored) = (texts[0], texts[1]); + let expected = tessellated_with_options( + ClippedShape { clip_rect: clip, shape: Shape::Text(original.clone()), transform_after_tessellation: transform }, + options, + ); + assert_eq!(expected.len(), 1); + assert!(expected[0].is_positive()); + assert!(mirrored.galley.rect.is_positive()); + assert_eq!(mirrored.galley.size(), original.galley.size() * transform.scaling.abs()); + let reported = fixture.texts().iter().find(|text| text.rect.max == mirrored.pos).expect("the mirrored text is reported"); + assert_eq!(mirrored.galley.rect.translate(mirrored.pos.to_vec2()), reported.rect); + for (row, source) in mirrored.galley.rows.iter().zip(&original.galley.rows) { + for (glyph, original_glyph) in row.row.glyphs.iter().zip(&source.row.glyphs) { + let expected = transform.scaling * original_glyph.logical_rect().translate(source.pos.to_vec2()); + let actual = glyph.logical_rect().translate(row.pos.to_vec2()); + assert!(actual.min.distance(expected.max) < 0.001); + assert!(actual.max.distance(expected.min) < 0.001); + } + for (vertex, original_vertex) in row.visuals.mesh.vertices.iter().zip(&source.visuals.mesh.vertices) { + let expected = (source.pos + original_vertex.pos.to_vec2()) * transform.scaling; + assert!((row.pos + vertex.pos.to_vec2()).distance(expected) < 0.001); + } + } + assert_eq!(tessellated_with_options(ClippedShape::new(clip, Shape::Text(mirrored.clone())), options), expected); + } +} + +#[trial] +fn mirrored_rectangles_move_asymmetric_radii_to_opposite_corners() { + let transform = TSTransform::new(vec2(300.0, 300.0), -1.0); + let clip = Rect::from_min_max(pos2(100.0, 100.0), pos2(260.0, 260.0)); + let radius = egui::CornerRadius { nw: 24, ne: 0, sw: 0, se: 0 }; + let source = Shape::rect_filled(Rect::from_min_max(pos2(80.0, 80.0), pos2(160.0, 160.0)), radius, FILL); + let member = ClippedShape { clip_rect: clip, shape: source, transform_after_tessellation: transform }; + let options = egui::epaint::TessellationOptions { coarse_tessellation_culling: false, feathering: false, ..Default::default() }; + let positions = |shape| { + egui::epaint::Tessellator::new(1.0, options, [1, 1], Vec::new()) + .tessellate_shapes(vec![shape]) + .into_iter() + .flat_map(|primitive| match primitive.primitive { + egui::epaint::Primitive::Mesh(mesh) => mesh.vertices.into_iter().map(|vertex| vertex.pos).collect::>(), + egui::epaint::Primitive::Callback(_) => Vec::new(), + }) + .collect::>() + }; + let expected = positions(member.clone()); + assert!(!expected.is_empty()); + let paint = move |ui: &mut Ui| { + ui.ctx().tessellation_options_mut(|current| *current = options); + ui.painter().add(Shape::PaintChunk(Arc::from([member.clone()]))); + }; + let mut fixture = Fixture::new(paint.clone()); + fixture.settle(); + + for shapes in + [fixture.frame_shapes(), fixture.frame_clipped_shapes().into_iter().map(|(_, shape)| shape).collect(), Frames::new().frame_shapes(paint)] + { + let rects: Vec<_> = shapes.iter().filter_map(|shape| if let Shape::Rect(rect) = shape { Some(rect) } else { None }).collect(); + assert_eq!(rects.len(), 1); + let rect = rects[0]; + assert_eq!(rect.corner_radius, egui::CornerRadius { nw: radius.se, ne: radius.sw, sw: radius.ne, se: radius.nw }); + let actual = positions(ClippedShape::new(clip, Shape::Rect(rect.clone()))); + assert_eq!(actual.len(), expected.len()); + for point in &expected { + assert!(actual.iter().any(|actual| actual.distance(*point) < 0.001), "the transformed outline contains {point:?}"); + } + } +} + +#[trial] +fn negatively_scaled_callbacks_with_inverted_source_bounds_are_reported() { + let bounds = Rect::from_min_max(pos2(140.0, 140.0), pos2(100.0, 100.0)); + let transform = TSTransform::new(vec2(300.0, 300.0), -1.0); + let clip = Rect::from_min_max(pos2(170.0, 150.0), pos2(210.0, 210.0)); + let drawn = transform * bounds; + let paint = move |ui: &mut Ui| { + let member = ClippedShape { + clip_rect: clip, + shape: Shape::Callback(PaintCallback { rect: bounds, callback: Arc::new(()) }), + transform_after_tessellation: transform, + }; + ui.painter().add(Shape::PaintChunk(Arc::from([member]))); + }; + let mut fixture = Fixture::new(paint); + fixture.settle(); + + assert!(drawn.is_positive()); + let callbacks: Vec<_> = fixture + .frame_clipped_shapes() + .into_iter() + .filter_map(|(clip, shape)| if let Shape::Callback(callback) = shape { Some((clip, callback.rect)) } else { None }) + .collect(); + assert_eq!(callbacks.len(), 1); + let (actual_clip, actual_bounds) = callbacks[0]; + assert_eq!(actual_bounds, drawn); + assert_eq!(actual_clip, clip); + + fixture.frame(Vec::new()); + assert!(fixture.shape_bounds().contains(&actual_bounds.intersect(actual_clip))); + for shapes in [fixture.frame_shapes(), Frames::new().frame_shapes(paint)] { + let callbacks: Vec<_> = + shapes.iter().filter_map(|shape| if let Shape::Callback(callback) = shape { Some(callback.rect) } else { None }).collect(); + assert_eq!(callbacks, vec![drawn]); + } +} + +#[trial] +fn negatively_scaled_chunk_members_are_not_reported_in_shape_bounds() { + let transform = TSTransform::new(vec2(180.0, 160.0), -2.0); + let clip = Rect::from_min_max(pos2(130.0, 0.0), pos2(170.0, 180.0)); + let stroke = egui::Stroke::new(3.0, FILL); + let box_shape = Shape::rect_stroke(BOX, 0.0, stroke, egui::StrokeKind::Outside); + let bounds = box_shape.visual_bounding_rect(); + let drawn = Rect::from_two_pos(transform * bounds.min, transform * bounds.max).intersect(clip); + let paint = move |ui: &mut Ui| { + let galley = ui.painter().layout_no_wrap("hidden".to_owned(), FontId::proportional(14.0), Color32::WHITE); + let members = [box_shape.clone(), Shape::galley(TEXT_AT, galley, Color32::WHITE)].map(|shape| ClippedShape { + clip_rect: clip, + shape, + transform_after_tessellation: transform, + }); + ui.painter().add(Shape::PaintChunk(Arc::from(members))); + ui.painter().add(Shape::rect_filled(BOX, 0.0, FILL)); + }; + let mut fixture = Fixture::new(paint.clone()); + fixture.settle(); + + assert!(drawn.is_positive()); + assert!(fixture.shape_bounds().contains(&BOX)); + assert!(!fixture.shape_bounds().contains(&drawn)); + assert!(!fixture.texts().iter().any(|text| text.text == "hidden")); + for shapes in + [fixture.frame_shapes(), fixture.frame_clipped_shapes().into_iter().map(|(_, shape)| shape).collect(), Frames::new().frame_shapes(paint)] + { + assert_eq!(the_box(&shapes), BOX); + assert!(!shapes.iter().any(|shape| matches!(shape, Shape::Rect(rect) if rect.stroke == stroke))); + assert!(!shapes.iter().any(|shape| matches!(shape, Shape::Text(text) if text.galley.job.text == "hidden"))); + } +} + +/// The rects egui's tessellator fills for `shape`, each cut to its primitive's clip rect. +fn tessellated(shape: ClippedShape) -> Vec { + tessellated_with_options(shape, egui::epaint::TessellationOptions::default()) +} + +fn tessellated_with_options(shape: ClippedShape, options: egui::epaint::TessellationOptions) -> Vec { + let mut tessellator = egui::epaint::Tessellator::new(1.0, options, [1, 1], Vec::new()); + tessellator + .tessellate_shapes(vec![shape]) + .into_iter() + .filter_map(|primitive| match primitive.primitive { + egui::epaint::Primitive::Mesh(mesh) => Some(mesh.calc_bounds().intersect(primitive.clip_rect)), + egui::epaint::Primitive::Callback(_) => None, + }) + .collect() +} + +#[trial] +fn mirrored_chunk_members_preserve_radii_and_stroke_widths() { + let transform = TSTransform::new(vec2(480.0, 480.0), -2.0); + let clip = Rect::from_min_max(pos2(200.0, 200.0), pos2(240.0, 240.0)); + for source in [ + Shape::circle_filled(pos2(120.0, 120.0), 80.0, FILL), + Shape::line_segment([pos2(80.0, 80.0), pos2(160.0, 160.0)], egui::Stroke::new(3.0, FILL)), + ] { + let chunk = Shape::PaintChunk(Arc::from([ClippedShape { clip_rect: clip, shape: source.clone(), transform_after_tessellation: transform }])); + let expected = + tessellated(ClippedShape { clip_rect: Rect::EVERYTHING, shape: chunk.clone(), transform_after_tessellation: TSTransform::IDENTITY }); + assert_eq!(expected, vec![clip], "egui draws the mirrored member"); + let paint = move |ui: &mut Ui| { + ui.painter().add(chunk.clone()); + }; + let mut fixture = Fixture::new(paint.clone()); + fixture.settle(); + assert!(fixture.shape_bounds().contains(&expected[0])); + for shapes in [ + fixture.frame_shapes(), + fixture.frame_clipped_shapes().into_iter().map(|(_, shape)| shape).collect(), + Frames::new().frame_shapes(paint.clone()), + ] { + let members: Vec<_> = shapes + .iter() + .filter(|shape| { + matches!(shape, Shape::Circle(circle) if circle.fill == FILL) + || matches!(shape, Shape::LineSegment { stroke, .. } if stroke.color == FILL) + }) + .collect(); + assert_eq!(members.len(), 1); + let member = members[0]; + match (&source, member) { + (Shape::Circle(source), Shape::Circle(circle)) => { + assert_eq!(circle.center, transform * source.center); + assert_eq!(circle.radius, source.radius * transform.scaling.abs()); + assert!(circle.radius > 0.0); + } + (Shape::LineSegment { points: source_points, stroke: source_stroke }, Shape::LineSegment { points, stroke }) => { + assert_eq!(*points, source_points.map(|point| transform * point)); + assert_eq!(stroke.width, source_stroke.width * transform.scaling.abs()); + assert!(stroke.width > 0.0); + } + _ => panic!("the fixture preserves the member's shape type"), + } + assert!(member.visual_bounding_rect().is_positive()); + assert_eq!(member.visual_bounding_rect().intersect(clip), expected[0]); + } + let members: Vec<_> = fixture + .frame_clipped_shapes() + .into_iter() + .filter(|(_, shape)| { + matches!(shape, Shape::Circle(circle) if circle.fill == FILL) + || matches!(shape, Shape::LineSegment { stroke, .. } if stroke.color == FILL) + }) + .map(|(clip, shape)| (clip, shape.visual_bounding_rect().intersect(clip))) + .collect(); + assert_eq!(members, vec![(clip, expected[0])]); + } +} + +#[trial] +fn mirrored_rotated_ellipses_follow_chunk_culling_with_parallel_tessellation() { + let transform = TSTransform::new(vec2(300.0, 300.0), -1.0); + let clip = Rect::from_min_max(pos2(150.0, 150.0), pos2(210.0, 210.0)); + for parallel in [false, true] { + for (radius, visible) in [(vec2(80.0, 10.0), false), (vec2(80.0, 80.0), true)] { + let ellipse = egui::epaint::EllipseShape { + center: pos2(120.0, 120.0), + radius, + fill: FILL, + stroke: egui::Stroke::NONE, + angle: std::f32::consts::FRAC_PI_2, + }; + let chunk = Shape::PaintChunk(Arc::from([ClippedShape { + clip_rect: clip, + shape: Shape::Ellipse(ellipse), + transform_after_tessellation: transform, + }])); + let options = egui::epaint::TessellationOptions { parallel_tessellation: parallel, ..Default::default() }; + let expected = tessellated_with_options( + ClippedShape { clip_rect: Rect::EVERYTHING, shape: chunk.clone(), transform_after_tessellation: TSTransform::IDENTITY }, + options, + ); + assert_eq!(!expected.is_empty(), visible, "egui chunk culling with parallel tessellation {parallel}"); + let paint = move |ui: &mut Ui| { + ui.ctx().tessellation_options_mut(|options| options.parallel_tessellation = parallel); + ui.painter().add(chunk.clone()); + }; + let mut fixture = Fixture::new(paint.clone()); + fixture.settle(); + let bounds = Rect::from_two_pos(transform * ellipse.visual_bounding_rect().min, transform * ellipse.visual_bounding_rect().max); + assert_eq!(fixture.shape_bounds().contains(&bounds.intersect(clip)), visible); + for shapes in [ + fixture.frame_shapes(), + fixture.frame_clipped_shapes().into_iter().map(|(_, shape)| shape).collect(), + Frames::new().frame_shapes(paint.clone()), + ] { + let ellipses: Vec<_> = shapes.iter().filter(|shape| matches!(shape, Shape::Ellipse(ellipse) if ellipse.fill == FILL)).collect(); + assert_eq!(!ellipses.is_empty(), visible, "fixture chunk culling with parallel tessellation {parallel}"); + if visible { + assert_eq!(ellipses.len(), 1); + assert_eq!(ellipses[0].visual_bounding_rect().intersect(clip), expected[0]); + } + } + } + } +} + +#[trial] +fn negatively_scaled_members_that_egui_draws_are_reported_where_egui_draws_them() { + let enclosing = Rect::from_min_max(pos2(80.0, 80.0), pos2(160.0, 160.0)); + let flip = TSTransform::new(vec2(300.0, 300.0), -1.0); + let clip = Rect::from_min_max(pos2(150.0, 150.0), pos2(210.0, 210.0)); + // A member whose bounds enclose its clip mapped back through its negative scale, and a nested member whose inverted + // clip the parent's negative scale turns into the whole plane. + for (parent, parent_clip, member, member_clip) in + [(TSTransform::IDENTITY, Rect::EVERYTHING, flip, clip), (flip, clip, TSTransform::IDENTITY, Rect::NOTHING)] + { + let chunk = move || { + let inner = + ClippedShape { clip_rect: member_clip, shape: Shape::rect_filled(enclosing, 0.0, FILL), transform_after_tessellation: member }; + let outer = ClippedShape { clip_rect: parent_clip, shape: Shape::PaintChunk(Arc::from([inner])), transform_after_tessellation: parent }; + Shape::PaintChunk(Arc::from([outer])) + }; + let window = Rect::from_min_max(pos2(0.0, 0.0), pos2(400.0, 300.0)); + let expected = tessellated(ClippedShape { clip_rect: window, shape: chunk(), transform_after_tessellation: TSTransform::IDENTITY }); + assert_eq!(expected, vec![clip], "egui draws the member inside the clip"); + let paint = move |ui: &mut Ui| { + ui.painter().add(chunk()); + }; + let mut fixture = Fixture::new(paint); + fixture.settle(); + + assert!(fixture.shape_bounds().contains(&clip), "{:?}", fixture.shape_bounds()); + for shapes in [fixture.frame_shapes(), Frames::new().frame_shapes(paint)] { + let boxes: Vec = + shapes.iter().filter(|shape| matches!(shape, Shape::Rect(rect) if rect.fill == FILL)).map(Shape::visual_bounding_rect).collect(); + assert_eq!(boxes.len(), 1, "the member is painted: {boxes:?}"); + assert_eq!(boxes[0].intersect(clip), clip); + } + let boxes: Vec<_> = fixture + .frame_clipped_shapes() + .into_iter() + .filter(|(_, shape)| matches!(shape, Shape::Rect(rect) if rect.fill == FILL)) + .map(|(clip, shape)| (clip, shape.visual_bounding_rect().intersect(clip))) + .collect(); + assert_eq!(boxes, vec![(clip, clip)]); + } +} + +#[trial] +fn chunk_members_with_invalid_transforms_are_not_reported() { + for scale in [0.0, -0.0, f32::NAN, f32::INFINITY, f32::NEG_INFINITY] { + let transform = TSTransform::new(vec2(100.0, 100.0), scale); + let mut fixture = + Fixture::new(move |ui| { + let galley = ui.painter().layout_no_wrap("shared".to_owned(), FontId::proportional(14.0), Color32::WHITE); + let members = [Shape::rect_filled(BOX, 0.0, FILL), Shape::galley(TEXT_AT, galley.clone(), Color32::WHITE)] + .map(|shape| ClippedShape { clip_rect: MEMBER_CLIP, shape, transform_after_tessellation: transform }); + ui.painter().add(Shape::PaintChunk(Arc::from(members))); + ui.painter().galley(TEXT_AT, galley, Color32::WHITE); + }); + fixture.settle(); + + let texts: Vec<_> = fixture.texts().iter().filter(|text| text.text == "shared").collect(); + assert_eq!(texts.len(), 1, "only the later valid run is reported for scale {scale}"); + assert_eq!(texts[0].rect.min, TEXT_AT); + let hidden = Rect::from_min_max(pos2(100.0, 100.0), pos2(100.0, 100.0)); + assert!(!fixture.shape_bounds().contains(&hidden)); + for shapes in [fixture.frame_shapes(), fixture.frame_clipped_shapes().into_iter().map(|(_, shape)| shape).collect()] { + assert!(!shapes.iter().any(|shape| matches!(shape, Shape::Rect(rect) if rect.fill == FILL))); + let texts: Vec<_> = shapes.iter().filter_map(|shape| if let Shape::Text(text) = shape { Some(text) } else { None }).collect(); + assert_eq!(texts.len(), 1); + assert_eq!(texts[0].pos, TEXT_AT); + } + } +} + +#[trial] +fn identity_chunk_members_outside_their_clip_are_not_reported() { + let clip = Rect::from_min_max(pos2(200.0, 100.0), pos2(300.0, 200.0)); + for nested in [false, true] { + for coarse_culling in [false, true] { + let paint = move |ui: &mut Ui| { + ui.ctx().tessellation_options_mut(|options| options.coarse_tessellation_culling = coarse_culling); + let galley = ui.painter().layout_no_wrap("hidden identity".to_owned(), FontId::proportional(14.0), Color32::WHITE); + let parent = if nested { TSTransform::new(vec2(40.0, 20.0), 2.0) } else { TSTransform::IDENTITY }; + let members = [Shape::rect_filled(BOX, 0.0, FILL), Shape::galley(TEXT_AT, galley, Color32::WHITE)].map(|shape| ClippedShape { + clip_rect: parent.inverse() * clip, + shape: Shape::Vec(vec![shape]), + transform_after_tessellation: parent.inverse(), + }); + let chunk = Shape::PaintChunk(Arc::from(members)); + let chunk = if nested { + Shape::PaintChunk(Arc::from([ClippedShape { clip_rect: clip, shape: chunk, transform_after_tessellation: parent }])) + } else { + chunk + }; + let expected = tessellated_with_options(ClippedShape::new(clip, chunk.clone()), ui.ctx().tessellation_options(|options| *options)); + assert!(expected.iter().all(|bounds| !bounds.is_positive())); + ui.painter().add(chunk); + }; + let mut fixture = Fixture::new(paint); + fixture.settle(); + assert!(!fixture.texts().iter().any(|text| text.text == "hidden identity")); + assert!(!fixture.shape_bounds().contains(&BOX)); + for shapes in [ + fixture.frame_shapes(), + fixture.frame_clipped_shapes().into_iter().map(|(_, shape)| shape).collect(), + Frames::new().frame_shapes(paint), + ] { + assert!(!shapes.iter().any(|shape| matches!(shape, Shape::Rect(rect) if rect.fill == FILL))); + assert!(!shapes.iter().any(|shape| matches!(shape, Shape::Text(text) if text.galley.job.text == "hidden identity"))); + } + } + } +} + +#[trial] +fn positively_transformed_culled_ellipses_are_excluded_from_bounds() { + let transform = TSTransform::new(vec2(20.0, 10.0), 1.5); + let source_clip = Rect::from_min_max(pos2(115.0, 170.0), pos2(125.0, 180.0)); + let clip = transform * source_clip; + let ellipse = egui::epaint::EllipseShape { + center: pos2(120.0, 120.0), + radius: vec2(80.0, 10.0), + fill: FILL, + stroke: egui::Stroke::NONE, + angle: std::f32::consts::FRAC_PI_2, + }; + let bounds = (transform * ellipse.visual_bounding_rect()).intersect(clip); + assert!(bounds.is_positive()); + let member = ClippedShape { clip_rect: clip, shape: Shape::Ellipse(ellipse), transform_after_tessellation: transform }; + assert!(tessellated(member.clone()).is_empty()); + for in_chunk in [false, true] { + let member = member.clone(); + let paint = move |ui: &mut Ui| { + if in_chunk { + ui.painter().add(Shape::PaintChunk(Arc::from([member.clone()]))); + } else { + let layer = egui::LayerId::new(egui::Order::Foreground, egui::Id::unique("culled ellipse")); + let painter = egui::Painter::new(ui.ctx().clone(), layer, source_clip); + painter.add(member.shape.clone()); + ui.ctx().transform_layer_shapes_after_rounding(layer, transform); + } + }; + let mut fixture = Fixture::new(paint.clone()); + fixture.settle(); + assert!(!fixture.shape_bounds().contains(&bounds)); + for shapes in + [fixture.frame_shapes(), fixture.frame_clipped_shapes().into_iter().map(|(_, shape)| shape).collect(), Frames::new().frame_shapes(paint)] + { + assert!(!shapes.iter().any(|shape| matches!(shape, Shape::Ellipse(ellipse) if ellipse.fill == FILL))); + } + } +} + +#[trial] +fn mirrored_textured_rectangles_preserve_tessellated_positions_and_uvs() { + let transform = TSTransform::new(vec2(300.0, 300.0), -1.0); + let clip = Rect::from_min_max(pos2(100.0, 100.0), pos2(260.0, 260.0)); + let uv = Rect::from_min_max(pos2(0.125, 0.25), pos2(0.75, 0.875)); + let source = egui::epaint::RectShape::filled(Rect::from_min_max(pos2(80.0, 80.0), pos2(160.0, 160.0)), 0.0, Color32::WHITE) + .with_texture(egui::TextureId::User(7), uv); + let member = ClippedShape { clip_rect: clip, shape: Shape::Rect(source), transform_after_tessellation: transform }; + let options = egui::epaint::TessellationOptions { coarse_tessellation_culling: false, feathering: false, ..Default::default() }; + let vertices = |shape| { + egui::epaint::Tessellator::new(1.0, options, [1, 1], Vec::new()) + .tessellate_shapes(vec![shape]) + .into_iter() + .flat_map(|primitive| match primitive.primitive { + egui::epaint::Primitive::Mesh(mesh) => mesh.vertices.into_iter().map(|vertex| (vertex.pos, vertex.uv)).collect::>(), + egui::epaint::Primitive::Callback(_) => Vec::new(), + }) + .collect::>() + }; + let expected = vertices(member.clone()); + assert!(!expected.is_empty()); + let paint = move |ui: &mut Ui| { + ui.ctx().tessellation_options_mut(|current| *current = options); + ui.painter().add(Shape::PaintChunk(Arc::from([member.clone()]))); + }; + let mut fixture = Fixture::new(paint.clone()); + fixture.settle(); + for shapes in + [fixture.frame_shapes(), fixture.frame_clipped_shapes().into_iter().map(|(_, shape)| shape).collect(), Frames::new().frame_shapes(paint)] + { + let rects: Vec<_> = shapes.iter().filter_map(|shape| if let Shape::Rect(rect) = shape { Some(rect) } else { None }).collect(); + assert_eq!(rects.len(), 1); + let actual = vertices(ClippedShape::new(clip, Shape::Rect(rects[0].clone()))); + assert_eq!(actual.len(), expected.len()); + for vertex in &expected { + assert!(actual.contains(vertex), "the mirrored rectangle preserves position and UV {vertex:?}"); + } + } +} + +#[trial] +fn mirrored_text_rows_have_ordered_rects_and_unchanged_tessellation() { + let transform = TSTransform::new(vec2(300.0, 300.0), -2.0); + let clip = Rect::from_min_max(pos2(0.0, 0.0), pos2(400.0, 300.0)); + let options = egui::epaint::TessellationOptions { coarse_tessellation_culling: false, round_text_to_pixels: false, ..Default::default() }; + let paint = move |ui: &mut Ui| { + ui.ctx().tessellation_options_mut(|current| *current = options); + let galley = ui.painter().layout_no_wrap("first\n\nsecond\n".to_owned(), FontId::proportional(14.0), Color32::WHITE); + let members = [TSTransform::IDENTITY, transform].map(|transform| ClippedShape { + clip_rect: clip, + shape: Shape::galley(TEXT_AT, galley.clone(), Color32::WHITE), + transform_after_tessellation: transform, + }); + ui.painter().add(Shape::PaintChunk(Arc::from(members))); + }; + let mut fixture = Fixture::new(paint); + fixture.settle(); + for shapes in + [fixture.frame_shapes(), fixture.frame_clipped_shapes().into_iter().map(|(_, shape)| shape).collect(), Frames::new().frame_shapes(paint)] + { + let texts: Vec<_> = shapes.iter().filter_map(|shape| if let Shape::Text(text) = shape { Some(text) } else { None }).collect(); + assert_eq!(texts.len(), 2); + let (original, mirrored) = (texts[0], texts[1]); + assert_eq!(mirrored.galley.rows.len(), original.galley.rows.len()); + for (row, source) in mirrored.galley.rows.iter().zip(&original.galley.rows) { + let expected = transform.scaling * source.rect(); + assert_eq!(row.rect(), Rect::from_two_pos(expected.min, expected.max)); + assert!(row.rect().min.x <= row.rect().max.x && row.rect().min.y <= row.rect().max.y); + assert_eq!(row.glyphs.len(), source.glyphs.len()); + assert_eq!(row.visuals.mesh.vertices.len(), source.visuals.mesh.vertices.len()); + for (glyph, source_glyph) in row.glyphs.iter().zip(&source.glyphs) { + let expected = transform.scaling * source_glyph.logical_rect().translate(source.pos.to_vec2()); + let actual = glyph.logical_rect().translate(row.pos.to_vec2()); + assert!(actual.min.distance(expected.max) < 0.001); + assert!(actual.max.distance(expected.min) < 0.001); + } + for (vertex, source_vertex) in row.visuals.mesh.vertices.iter().zip(&source.visuals.mesh.vertices) { + let expected = (source.pos + source_vertex.pos.to_vec2()) * transform.scaling; + assert!((row.pos + vertex.pos.to_vec2()).distance(expected) < 0.001); + assert_eq!(vertex.uv, source_vertex.uv); + } + } + let expected = tessellated_with_options( + ClippedShape { clip_rect: clip, shape: Shape::Text(original.clone()), transform_after_tessellation: transform }, + options, + ); + assert!(!expected.is_empty()); + assert_eq!(tessellated_with_options(ClippedShape::new(clip, Shape::Text(mirrored.clone())), options), expected); + } +} + +#[trial] +fn transformed_text_shapes_and_bounds_snap_the_source_origin() { + let origin = pos2(10.4, 30.4); + let transform = TSTransform::new(vec2(0.3, 0.3), 1.5); + let pixels_per_point = 1.0; + let snapped = egui::emath::GuiRounding::round_to_pixels(origin, pixels_per_point); + let expected_bounds = Rc::new(Cell::new(Rect::NOTHING)); + let recorded = expected_bounds.clone(); + let paint = move |ui: &mut Ui| { + ui.ctx().tessellation_options_mut(|options| options.round_text_to_pixels = true); + let galley = ui.painter().layout_no_wrap("source snapping".to_owned(), FontId::proportional(14.0), Color32::WHITE); + let text = egui::epaint::TextShape::new(snapped, galley.clone(), Color32::WHITE); + recorded.set(transform * text.visual_bounding_rect()); + let members = [TSTransform::IDENTITY, transform].map(|transform| ClippedShape { + clip_rect: Rect::EVERYTHING, + shape: Shape::galley(origin, galley.clone(), Color32::WHITE), + transform_after_tessellation: transform, + }); + ui.painter().add(Shape::PaintChunk(Arc::from(members))); + }; + let mut fixture = Fixture::new(paint.clone()); + fixture.pixels_per_point(pixels_per_point); + fixture.settle(); + assert!(fixture.shape_bounds().contains(&expected_bounds.get()), "{:?}", fixture.shape_bounds()); + + for shapes in + [fixture.frame_shapes(), fixture.frame_clipped_shapes().into_iter().map(|(_, shape)| shape).collect(), Frames::new().frame_shapes(paint)] + { + let texts: Vec<_> = shapes.iter().filter_map(|shape| if let Shape::Text(text) = shape { Some(text) } else { None }).collect(); + assert_eq!(texts.len(), 2); + assert_eq!(texts[0].pos, origin); + assert_eq!(texts[1].pos, transform * snapped); + } +} + +#[trial] +fn mirrored_glyph_logical_rects_are_ordered_and_cover_the_transformed_source() { + for scale in [-1.0, -1.5, -2.0] { + let transform = TSTransform::new(vec2(300.0, 250.0), scale); + let paint = move |ui: &mut Ui| { + ui.ctx().tessellation_options_mut(|options| { + options.coarse_tessellation_culling = false; + options.round_text_to_pixels = false; + }); + let galley = ui.painter().layout_no_wrap("first\nsecond".to_owned(), FontId::proportional(14.0), Color32::WHITE); + let members = [TSTransform::IDENTITY, transform].map(|transform| ClippedShape { + clip_rect: Rect::EVERYTHING, + shape: Shape::galley(TEXT_AT, galley.clone(), Color32::WHITE), + transform_after_tessellation: transform, + }); + ui.painter().add(Shape::PaintChunk(Arc::from(members))); + }; + let mut fixture = Fixture::new(paint); + fixture.settle(); + for shapes in + [fixture.frame_shapes(), fixture.frame_clipped_shapes().into_iter().map(|(_, shape)| shape).collect(), Frames::new().frame_shapes(paint)] + { + let texts: Vec<_> = shapes.iter().filter_map(|shape| if let Shape::Text(text) = shape { Some(text) } else { None }).collect(); + assert_eq!(texts.len(), 2); + let (original, mirrored) = (texts[0], texts[1]); + assert_eq!(mirrored.galley.rows.len(), original.galley.rows.len()); + assert!(mirrored.galley.rect.min.x <= mirrored.galley.rect.max.x && mirrored.galley.rect.min.y <= mirrored.galley.rect.max.y); + for (row, source) in mirrored.galley.rows.iter().zip(&original.galley.rows) { + assert!(!row.glyphs.is_empty()); + assert_eq!(row.glyphs.len(), source.glyphs.len()); + for (glyph, source_glyph) in row.glyphs.iter().zip(&source.glyphs) { + assert!(glyph.advance_width >= 0.0 && glyph.line_height >= 0.0 && glyph.font_ascent >= 0.0); + assert!(glyph.font_height >= 0.0 && glyph.font_face_ascent >= 0.0 && glyph.font_face_height >= 0.0); + let rect = glyph.logical_rect(); + assert!(rect.min.x <= rect.max.x && rect.min.y <= rect.max.y); + let actual = rect.translate(mirrored.pos.to_vec2() + row.pos.to_vec2()); + let expected = transform * source_glyph.logical_rect().translate(original.pos.to_vec2() + source.pos.to_vec2()); + assert!(actual.min.distance(expected.max) < 0.001, "{actual:?} versus {expected:?}"); + assert!(actual.max.distance(expected.min) < 0.001, "{actual:?} versus {expected:?}"); + assert!(glyph.uv_rect.size.x >= 0.0 && glyph.uv_rect.size.y >= 0.0, "{:?}", glyph.uv_rect); + assert_eq!((glyph.uv_rect.min, glyph.uv_rect.max), (source_glyph.uv_rect.min, source_glyph.uv_rect.max)); + let uv_at = |glyph: &egui::epaint::text::Glyph, at: egui::Pos2| { + Rect::from_min_size(at + glyph.pos.to_vec2() + glyph.uv_rect.offset, glyph.uv_rect.size) + }; + let actual = uv_at(glyph, mirrored.pos + row.pos.to_vec2()); + let source_uv = uv_at(source_glyph, original.pos + source.pos.to_vec2()); + let expected = Rect::from_two_pos(transform * source_uv.min, transform * source_uv.max); + assert!(actual.min.distance(expected.min) < 0.001 && actual.max.distance(expected.max) < 0.001, "{actual:?} versus {expected:?}"); + } + assert!(row.size.x >= 0.0 && row.size.y >= 0.0, "{:?}", row.size); + assert!(!row.visuals.mesh.vertices.is_empty()); + assert_eq!(row.visuals.mesh.vertices.len(), source.visuals.mesh.vertices.len()); + for (vertex, source_vertex) in row.visuals.mesh.vertices.iter().zip(&source.visuals.mesh.vertices) { + let actual = mirrored.pos + row.pos.to_vec2() + vertex.pos.to_vec2(); + let expected = transform * (original.pos + source.pos.to_vec2() + source_vertex.pos.to_vec2()); + assert!(actual.distance(expected) < 0.001); + assert_eq!(vertex.uv, source_vertex.uv); + } + } + } + } +} + +#[trial] +fn painted_text_origins_are_snapped_before_the_paint_transform() { + let origin = pos2(10.2, 30.2); + let pixels_per_point = 1.5; + for round_text_to_pixels in [false, true] { + for scale in [1.0, 2.0, -2.0] { + let transform = TSTransform::new(vec2(200.25, 150.25), scale); + let expected = Rc::new(Cell::new((Rect::NOTHING, 0.0))); + let recorded = expected.clone(); + let mut fixture = Fixture::new(move |ui| { + let options = egui::epaint::TessellationOptions { coarse_tessellation_culling: false, round_text_to_pixels, ..Default::default() }; + ui.ctx().tessellation_options_mut(|current| *current = options); + let galley = ui.painter().layout_no_wrap("snapped origin".to_owned(), FontId::proportional(14.0), Color32::WHITE); + let pos = if round_text_to_pixels { egui::emath::GuiRounding::round_to_pixels(origin, pixels_per_point) } else { origin }; + let moved = transform * galley.rect.translate(pos.to_vec2()); + let row = &galley.rows[0]; + let baseline = transform * pos2(0.0, pos.y + (row.pos.y + row.glyphs[0].pos.y)); + recorded.set((Rect::from_two_pos(moved.min, moved.max), baseline.y)); + let shape = Shape::galley(origin, galley.clone(), Color32::WHITE); + let member = ClippedShape { clip_rect: Rect::EVERYTHING, shape, transform_after_tessellation: transform }; + let snapped = ClippedShape { + clip_rect: Rect::EVERYTHING, + shape: Shape::galley(pos, galley, Color32::WHITE), + transform_after_tessellation: transform, + }; + let vertices = |shape, options| { + egui::epaint::Tessellator::new(pixels_per_point, options, [1, 1], Vec::new()) + .tessellate_shapes(vec![shape]) + .into_iter() + .flat_map(|primitive| match primitive.primitive { + egui::epaint::Primitive::Mesh(mesh) => mesh.vertices.into_iter().map(|vertex| vertex.pos).collect::>(), + egui::epaint::Primitive::Callback(_) => Vec::new(), + }) + .collect::>() + }; + let actual = vertices(member.clone(), options); + assert!(!actual.is_empty()); + assert_eq!(actual, vertices(snapped, egui::epaint::TessellationOptions { round_text_to_pixels: false, ..options })); + ui.painter().add(Shape::PaintChunk(Arc::from([member]))); + }); + fixture.pixels_per_point(pixels_per_point); + fixture.settle(); + let text = fixture.texts().iter().find(|text| text.text == "snapped origin").expect("the text is painted"); + let (rect, baseline) = expected.get(); + assert_eq!(text.rect, rect, "rounding {round_text_to_pixels}, scale {scale}"); + assert_eq!(text.baseline, baseline, "rounding {round_text_to_pixels}, scale {scale}"); + } + } +} + +#[trial] +fn mirrored_text_underlines_match_egui_vertices() { + let clip = Rect::from_min_max(pos2(0.0, 0.0), pos2(400.0, 300.0)); + for scale in [-1.0, -2.0] { + for angle in [0.0, 0.35] { + let transform = TSTransform::new(vec2(300.0, 250.0), scale); + let options = egui::epaint::TessellationOptions { + coarse_tessellation_culling: false, + feathering: true, + round_line_segments_to_pixels: scale == -1.0, + ..Default::default() + }; + let underline_vertices = |shapes| { + egui::epaint::Tessellator::new(1.0, options, [1, 1], Vec::new()) + .tessellate_shapes(shapes) + .into_iter() + .flat_map(|primitive| match primitive.primitive { + egui::epaint::Primitive::Mesh(mesh) => { + mesh.vertices.into_iter().filter(|vertex| vertex.color == FILL).map(|vertex| vertex.pos).collect::>() + } + egui::epaint::Primitive::Callback(_) => Vec::new(), + }) + .collect::>() + }; + let source = Rc::new(std::cell::RefCell::new(Vec::new())); + let recorded = source.clone(); + let paint = move |ui: &mut Ui| { + ui.ctx().tessellation_options_mut(|current| *current = options); + let galley = ui.painter().layout_no_wrap("first\n\nsecond".to_owned(), FontId::proportional(14.0), Color32::WHITE); + let mut text = egui::epaint::TextShape::new(TEXT_AT, galley, Color32::WHITE).with_underline(egui::Stroke::new(2.0, FILL)); + text.angle = angle; + let member = ClippedShape { clip_rect: clip, shape: Shape::Text(text), transform_after_tessellation: transform }; + *recorded.borrow_mut() = vec![member.clone()]; + ui.painter().add(Shape::PaintChunk(Arc::from([member]))); + }; + let mut fixture = Fixture::new(paint.clone()); + fixture.settle(); + let expected = underline_vertices(source.borrow().clone()); + assert!(!expected.is_empty()); + let clipped = fixture.frame_clipped_shapes(); + let text_index = clipped.iter().position(|(_, shape)| matches!(shape, Shape::Text(_))).expect("the text is returned"); + assert!(matches!(&clipped[text_index].1, Shape::Text(text) if text.underline == egui::Stroke::NONE)); + for (line_clip, line) in &clipped[text_index + 1..text_index + 3] { + assert_eq!(*line_clip, clipped[text_index].0); + assert!(matches!(line, Shape::Mesh(mesh) if mesh.vertices.iter().any(|vertex| vertex.color == FILL))); + } + for shapes in [ + fixture.frame_shapes().into_iter().map(|shape| ClippedShape::new(clip, shape)).collect(), + clipped.into_iter().map(|(clip, shape)| ClippedShape::new(clip, shape)).collect(), + Frames::new().frame_shapes(paint).into_iter().map(|shape| ClippedShape::new(clip, shape)).collect(), + ] { + let actual = underline_vertices(shapes); + assert_eq!(actual.len(), expected.len()); + for vertex in &expected { + assert!(actual.iter().any(|actual| actual.distance(*vertex) < 0.001), "missing underline vertex {vertex:?}"); + } + } + } + } +} + +#[trial] +fn scaled_chunk_text_glyphs_match_reported_baselines() { + let mut fixture = Fixture::new(|ui| { + let galley = ui.painter().layout_no_wrap("first\nsecond".to_owned(), FontId::proportional(14.0), Color32::WHITE); + let members = [TSTransform::IDENTITY, composed()].map(|transform| ClippedShape { + clip_rect: Rect::EVERYTHING, + shape: Shape::galley(TEXT_AT, galley.clone(), Color32::WHITE), + transform_after_tessellation: transform, + }); + ui.painter().add(Shape::PaintChunk(Arc::from(members))); + }); + fixture.settle(); + + for shapes in [fixture.frame_shapes(), fixture.frame_clipped_shapes().into_iter().map(|(_, shape)| shape).collect()] { + let texts: Vec<_> = shapes.iter().filter_map(|shape| if let Shape::Text(text) = shape { Some(text) } else { None }).collect(); + assert_eq!(texts.len(), 2); + let (original, scaled) = (texts[0], texts[1]); + let scale = composed().scaling; + assert_eq!(scaled.pos, composed() * original.pos); + assert_eq!(scaled.galley.rows.len(), original.galley.rows.len()); + for (row, source) in scaled.galley.rows.iter().zip(&original.galley.rows) { + assert_eq!(row.row.glyphs.len(), source.row.glyphs.len()); + assert!(!row.row.glyphs.is_empty()); + for (glyph, source) in row.row.glyphs.iter().zip(&source.row.glyphs) { + assert_eq!(glyph.pos, source.pos * scale); + assert_eq!(glyph.advance_width, source.advance_width * scale); + assert_eq!(glyph.line_height, source.line_height * scale); + assert_eq!(glyph.font_ascent, source.font_ascent * scale); + assert_eq!(glyph.font_height, source.font_height * scale); + assert_eq!(glyph.font_face_ascent, source.font_face_ascent * scale); + assert_eq!(glyph.font_face_height, source.font_face_height * scale); + assert_eq!(glyph.uv_rect.offset, source.uv_rect.offset * scale); + assert_eq!(glyph.uv_rect.size, source.uv_rect.size * scale); + assert_eq!(glyph.uv_rect.min, source.uv_rect.min); + assert_eq!(glyph.uv_rect.max, source.uv_rect.max); + } + } + let first = &scaled.galley.rows[0]; + let baseline = scaled.pos.y + first.pos.y + first.row.glyphs[0].pos.y; + let reported = fixture.texts().iter().find(|text| text.rect.min == scaled.pos).expect("the scaled text is reported"); + assert!((baseline - reported.baseline).abs() < 0.001); + } +} diff --git a/crates/ui-contract/tests/it/paint/mod.rs b/crates/ui-contract/tests/it/paint/mod.rs index 97f1508135..22c98b1b62 100644 --- a/crates/ui-contract/tests/it/paint/mod.rs +++ b/crates/ui-contract/tests/it/paint/mod.rs @@ -1,5 +1,7 @@ pub(crate) mod backdrop; +pub(crate) mod chunk_members; + pub(crate) mod draw_place; pub(crate) mod painters; diff --git a/crates/ui-contract/tests/it/runtime/alt_code.rs b/crates/ui-contract/tests/it/runtime/alt_code.rs index 22154bf8f5..5a5fa8faac 100644 --- a/crates/ui-contract/tests/it/runtime/alt_code.rs +++ b/crates/ui-contract/tests/it/runtime/alt_code.rs @@ -10,7 +10,7 @@ use craft_ui::runtime::focus::{FocusTarget, KeyUse, host_canvas, request}; use craft_ui::runtime::frame::take_output; use craft_ui::style::StyleCx; use craft_ui::testing::focus::{named_id, widget}; -use craft_ui::testing::input::{key_press, key_repeat, text}; +use craft_ui::testing::input::{key_press, text}; use craft_ui::testing::pointer::click; use craft_ui::testing::{Frames, trial}; use craft_ui_test_kit::contract::PlainStyle; @@ -129,24 +129,13 @@ impl Session { self.frames.idle(1, &mut show); } - /// Plays `frames` of input with their digits on the keypad, each frame running two passes, then a frame with none; - /// returns what they typed. + /// Plays `frames` of input, each frame running two passes, then a frame with none; returns what they typed. fn send(&mut self, frames: Vec>) -> Typed { - self.play(frames, true) - } - - /// `send` with the digits on the main row. - fn send_main_row(&mut self, frames: Vec>) -> Typed { - self.play(frames, false) - } - - fn play(&mut self, frames: Vec>, keypad: bool) -> Typed { let mut show = self.show(); take_output(&self.frames.ctx); self.typed.borrow_mut().clear(); self.rerun.set(true); for events in frames { - let events = if keypad { on_keypad(events) } else { events }; let passes = self.frames.frame(events, &mut show); assert_eq!(passes, 2, "each input frame runs a second pass, which gets none of the frame's events"); } @@ -158,30 +147,18 @@ impl Session { const ALT: Modifiers = Modifiers::ALT; -const DIGITS: [Key; 10] = [Key::Num0, Key::Num1, Key::Num2, Key::Num3, Key::Num4, Key::Num5, Key::Num6, Key::Num7, Key::Num8, Key::Num9]; - -/// The digit key of `digit`; egui names keypad and main-row digits alike as logical keys, and the physical key tells -/// them apart (`on_keypad`). +/// The logical key of `digit`; egui names keypad and top-row digits alike. fn digit_key(digit: char) -> Key { + const DIGITS: [Key; 10] = [Key::Num0, Key::Num1, Key::Num2, Key::Num3, Key::Num4, Key::Num5, Key::Num6, Key::Num7, Key::Num8, Key::Num9]; DIGITS[digit.to_digit(10).expect("a decimal digit") as usize] } -const KEYPAD: [Key; 10] = - [Key::Numpad0, Key::Numpad1, Key::Numpad2, Key::Numpad3, Key::Numpad4, Key::Numpad5, Key::Numpad6, Key::Numpad7, Key::Numpad8, Key::Numpad9]; - -/// `events` with each digit key on the numeric keypad: its physical key is the keypad's, as egui-winit and the web -/// backend report a keypad digit. -fn on_keypad(events: Vec) -> Vec { - events - .into_iter() - .map(|event| match event { - Event::Key { key, pressed, repeat, modifiers, .. } if DIGITS.contains(&key) => { - let at = DIGITS.iter().position(|d| *d == key).expect("a digit key"); - Event::Key { key, physical_key: Some(KEYPAD[at]), pressed, repeat, modifiers } - } - other => other, - }) - .collect() +/// A keypad digit's press, auto-repeat or release with Alt held: its physical key is the keypad one. +fn keypad(digit: char, pressed: bool, repeat: bool) -> Event { + const KEYPAD: [Key; 10] = + [Key::Numpad0, Key::Numpad1, Key::Numpad2, Key::Numpad3, Key::Numpad4, Key::Numpad5, Key::Numpad6, Key::Numpad7, Key::Numpad8, Key::Numpad9]; + let physical = KEYPAD[digit.to_digit(10).expect("a decimal digit") as usize]; + Event::Key { key: digit_key(digit), physical_key: Some(physical), pressed, repeat, modifiers: ALT } } fn key_release(key: Key, modifiers: Modifiers) -> Event { @@ -193,17 +170,28 @@ fn alt(down: bool) -> Event { Event::ModifiersChanged(if down { ALT } else { Modifiers::NONE }) } -/// The frame of one digit typed with Alt held: its press with the digit's own text (Linux sends it), then its release. +/// The frame of one keypad digit typed with Alt held: its press with the digit's own text (Linux sends it), then its +/// release. fn digit(d: char) -> Vec { + vec![keypad(d, true, false), text(&d.to_string()), keypad(d, false, false)] +} + +/// The frame of one top-row digit typed with Alt held. +fn top_row_digit(d: char) -> Vec { let key = digit_key(d); vec![key_press(key, ALT), text(&d.to_string()), key_release(key, ALT)] } -/// The frames of an Alt code: Alt down, each digit in a frame of its own, then Alt up. +/// The frames of an Alt code: Alt down, each keypad digit in a frame of its own, then Alt up. fn code(digits: &str) -> Vec> { std::iter::once(vec![alt(true)]).chain(digits.chars().map(digit)).chain([vec![alt(false)]]).collect() } +/// `code(digits)` typed on the top row, which Windows does not compose. +fn top_row_code(digits: &str) -> Vec> { + std::iter::once(vec![alt(true)]).chain(digits.chars().map(top_row_digit)).chain([vec![alt(false)]]).collect() +} + /// `code(digits)`, then a frame in which the platform sends `composed`, the character it made of the code itself. fn code_then(digits: &str, composed: &str) -> Vec> { let mut frames = code(digits); @@ -234,13 +222,10 @@ fn an_alt_numpad_code_types_its_character_once() { assert_eq!(lone, Typed { text: String::new(), lone_alt: true }, "{os:?}: a lone Alt in the field alerts"); assert_eq!(session.send(code("0233")), typed("é"), "{os:?}: a leading 0 reads the ANSI page, the digits type nothing"); - // Alt with main-row digits is a shortcut, never a code: egui names those digits as it names the keypad's. - let main_row = session.send_main_row(code("0233")); - assert!(main_row.text.is_empty(), "{os:?}: main-row digits enter no code and type nothing: {main_row:?}"); assert_eq!(session.send(code("233")), typed("Θ"), "{os:?}: no leading 0 reads the OEM page"); assert_eq!(session.send(code("8364")), typed("€"), "{os:?}: above 255 the code is the Unicode character"); // With the repeat counted the code would be 02333, U+091D. - let held = vec![key_press(Key::Num3, ALT), text("3"), key_repeat(Key::Num3, ALT), text("3"), key_release(Key::Num3, ALT)]; + let held = vec![keypad('3', true, false), text("3"), keypad('3', true, true), text("3"), keypad('3', false, false)]; let held_digit = vec![vec![alt(true)], digit('0'), digit('2'), held, digit('3'), vec![alt(false)]]; assert_eq!(session.send(held_digit), typed("é"), "{os:?}: a digit's auto-repeat adds nothing and types nothing"); // Eight digits are kept: 00000233 is é, where all nine (2334) would be U+091E. @@ -260,6 +245,10 @@ fn an_alt_numpad_code_types_its_character_once() { assert_eq!(other_echo, typed("€¬"), "{os:?}: a different text after a code is typed as normal"); } } + // Windows composes keypad codes only: after a top-row code, a different text is what was typed next. + let mut top_row_then = top_row_code("0233"); + top_row_then.push(vec![text("й")]); + assert_eq!(session.send(top_row_then), typed("éй"), "{os:?}: the text after a top-row code is typed as normal"); // Focus going to another window ends the code: its Alt release types nothing and is no lone Alt. let away = vec![vec![alt(true)], digit('0'), digit('2'), vec![Event::WindowFocused(false)], vec![Event::WindowFocused(true), alt(false)]]; @@ -284,14 +273,140 @@ fn an_alt_numpad_code_types_its_character_once() { assert!(!option.lone_alt, "macOS has no lone Alt either"); } +/// The press, text and release that winit on Windows reports a composed Alt code's character with: the press has no +/// physical key, and its key is the one egui names the character by. +fn composed_on_key(key: Key, composed: &str) -> Vec { + let event = |pressed| Event::Key { key, physical_key: None, pressed, repeat: false, modifiers: Modifiers::NONE }; + vec![event(true), text(composed), event(false)] +} + +/// On Windows the platform's character for a code can come on a key press of its own, with no physical key, after +/// the Alt release: in the release's frame or in the next one. For a character egui has a key for (`\` is +/// `Key::Backslash`, `A` is `Key::A`), that press is the platform's carrier of the character, not a key the user +/// pressed: the character is typed once and the press does not reach egui, where a single-key shortcut could take +/// it. Above 255 the carried character is the one of the byte Windows reduces the code to, and ours stays. A key the +/// user presses after a code still types as normal, also one with no physical key in egui. +#[trial] +fn a_composed_character_on_a_key_press_of_its_own_is_typed_once() { + let typed = Rc::new(RefCell::new(String::new())); + let reached = Rc::new(RefCell::new(Vec::<(Key, bool)>::new())); + let mut show = { + let (typed, reached) = (Rc::clone(&typed), Rc::clone(&reached)); + move |ui: &mut egui::Ui| { + let keys: Vec<(Key, bool)> = ui.input(|input| { + input + .events + .iter() + .filter_map(|event| match event { + Event::Key { key, pressed, .. } => Some((*key, *pressed)), + _ => None, + }) + .collect() + }); + reached.borrow_mut().extend(keys); + Probe::new(&typed).label("Text").id_salt("alt_code_field").show_at(ui, AT); + } + }; + let mut frames = Frames::new(); + craft_ui::testing::windows::set_os(&frames.ctx, Os::Windows); + frames.root(RootEnv::default().alt_code_pages(AltCodePages::new(1252, 437))); + frames.idle(3, &mut show); + // Plays `sequence`, then a frame with none; returns the field's text and the key events that reached egui, each + // with whether it is a press. + let send = |frames: &mut Frames, show: &mut dyn FnMut(&mut egui::Ui), sequence: Vec>| { + reached.borrow_mut().clear(); + typed.borrow_mut().clear(); + for events in sequence { + frames.frame(events, &mut *show); + } + frames.frame(Vec::new(), &mut *show); + (typed.take(), reached.take()) + }; + let next_frame = || { + let mut frames = code("0092"); + frames.push(composed_on_key(Key::Backslash, "\\")); + frames + }; + let same_frame = || { + let mut frames = code("65"); + if let Some(release) = frames.last_mut() { + release.extend(composed_on_key(Key::A, "A")); + } + frames + }; + let then_pressed = || { + let mut frames = code("0233"); + frames.push(vec![key_press(Key::A, Modifiers::NONE), text("a"), key_release(Key::A, Modifiers::NONE)]); + frames + }; + // Above 255 Windows reduces the code to a byte: 321 is 65, `A`, while ours is U+0141. + let reduced = || { + let mut frames = code("321"); + frames.push(composed_on_key(Key::A, "A")); + frames + }; + // A key egui has no physical key for (a JIS key typing `\`) pressed after a code whose character is `A`. + let unmapped = || { + let mut frames = code("65"); + frames.push(composed_on_key(Key::Backslash, "\\")); + frames + }; + + // With nothing focused, egui's input holds every key event no component took. The digits' releases reach it too. + let of = |keys: Vec<(Key, bool)>, key: Key| keys.into_iter().filter(|(k, _)| *k == key).collect::>(); + let (_, keys) = send(&mut frames, &mut show, next_frame()); + assert_eq!(of(keys, Key::Backslash), [], "a carrier press and its release in the next frame do not reach egui"); + let (_, keys) = send(&mut frames, &mut show, same_frame()); + assert_eq!(of(keys, Key::A), [], "a carrier press and its release in the release's frame do not reach egui"); + let (_, keys) = send(&mut frames, &mut show, then_pressed()); + assert_eq!(of(keys, Key::A), [(Key::A, true), (Key::A, false)], "a key the user presses after a code reaches egui"); + let (_, keys) = send(&mut frames, &mut show, reduced()); + assert_eq!(of(keys, Key::A), [], "the carrier of the byte a code above 255 reduces to does not reach egui"); + let (_, keys) = send(&mut frames, &mut show, unmapped()); + assert_eq!(of(keys, Key::Backslash), [(Key::Backslash, true), (Key::Backslash, false)], "another key with no physical key reaches egui"); + // The carrier's release never comes (the platform drops it with a held backslash key's), then the user presses + // that key with no physical key in egui: its release reaches egui with its press. + let mut lost_release = code("0092"); + lost_release.push(composed_on_key(Key::Backslash, "\\")[..2].to_vec()); + lost_release.push(composed_on_key(Key::Backslash, "\\")); + let (_, keys) = send(&mut frames, &mut show, lost_release); + assert_eq!(of(keys, Key::Backslash), [(Key::Backslash, true), (Key::Backslash, false)], "a carrier with no release keeps no later release"); + // A code the platform sends nothing after, then focus leaves the window and comes back: a key with no physical key + // in egui that types the code's character is the user's. + let mut refocused = code("0092"); + refocused.push(vec![Event::WindowFocused(false)]); + refocused.push(vec![Event::WindowFocused(true)]); + refocused.push(composed_on_key(Key::Backslash, "\\")); + let (_, keys) = send(&mut frames, &mut show, refocused); + assert_eq!(of(keys, Key::Backslash), [(Key::Backslash, true), (Key::Backslash, false)], "a focus loss ends the code's echo"); + // Windows composes nothing for a top-row code: a key with no physical key in egui that types the code's character + // right after it, with no focus change, is the user's. + let top_row = || { + let mut frames = top_row_code("0092"); + frames.push(composed_on_key(Key::Backslash, "\\")); + frames + }; + let (_, keys) = send(&mut frames, &mut show, top_row()); + assert_eq!(of(keys, Key::Backslash), [(Key::Backslash, true), (Key::Backslash, false)], "a press after a top-row code reaches egui"); + + click(&mut frames, AT.center(), &mut show); + frames.idle(1, &mut show); + assert_eq!(send(&mut frames, &mut show, reduced()).0, "\u{141}", "above 255 ours stays and the carried byte is dropped"); + assert_eq!(send(&mut frames, &mut show, unmapped()).0, "A\\", "another key with no physical key types as normal"); + assert_eq!(send(&mut frames, &mut show, next_frame()).0, "\\", "a carrier press in the next frame types nothing more"); + assert_eq!(send(&mut frames, &mut show, same_frame()).0, "A", "a carrier press in the release's frame types nothing more"); + assert_eq!(send(&mut frames, &mut show, then_pressed()).0, "éa", "a key the user presses after a code types as normal"); + assert_eq!(send(&mut frames, &mut show, top_row()).0, "\\\\", "a key pressed after a top-row code types as normal"); +} + /// Alt with the digit 3, which the host canvas of the next trial claims. const ALT_3: craft_keymap::Chord = craft_keymap::Chord::new(craft_keymap::Mods::ALT, craft_keymap::Key::Num3); /// An app's Alt+digit shortcut on Windows and Linux: the app's own egui canvas (`host_canvas`) claims Alt+3. With /// nothing focused the canvas is the window's key target, so Alt-code entry leaves the claimed press and egui's input -/// keeps it for the app, while an unclaimed keypad Alt+5 still folds into a code; a main-row Alt+5 is never a code, so -/// it reaches the app claimed or not (egui names both digits `Num5`). With the canvas focused, the claimed press -/// still reaches egui. A focused text field types Alt codes again, with the claimed digit among them. +/// keeps it for the app, on the keypad or the top row (egui names both digits `Num3`), while an unclaimed Alt+5 still +/// folds into a code. With the canvas focused, the claimed press still reaches egui. A focused text field types Alt +/// codes again, with the claimed digit among them. #[trial] fn an_alt_digit_a_host_canvas_claims_reaches_the_app_and_a_field_still_types_codes() { for os in [Os::Windows, Os::Linux] { @@ -321,33 +436,31 @@ fn an_alt_digit_a_host_canvas_claims_reaches_the_app_and_a_field_still_types_cod craft_ui::testing::windows::set_os(&frames.ctx, os); frames.root(RootEnv::default().alt_code_pages(AltCodePages::new(1252, 437))); frames.idle(3, &mut show); - // Plays `sequence` with its digits on the keypad, or on the main row, then a frame with none; returns the Alt - // presses that reached egui and the field's text. - let play = |frames: &mut Frames, show: &mut dyn FnMut(&mut egui::Ui), sequence: Vec>, keypad: bool| { + // Plays `sequence`, then a frame with none; returns the Alt presses that reached egui and the field's text. + let send = |frames: &mut Frames, show: &mut dyn FnMut(&mut egui::Ui), sequence: Vec>| { reached.borrow_mut().clear(); typed.borrow_mut().clear(); for events in sequence { - let events = if keypad { on_keypad(events) } else { events }; frames.frame(events, &mut *show); } frames.frame(Vec::new(), &mut *show); (reached.take(), typed.take()) }; - let (keys, _) = play(&mut frames, &mut show, code("3"), true); + let (keys, _) = send(&mut frames, &mut show, code("3")); assert!(keys.contains(&Key::Num3), "{os:?}: with nothing focused, the canvas's claimed Alt+3 reaches egui: {keys:?}"); - let (keys, _) = play(&mut frames, &mut show, code("5"), true); - assert!(!keys.contains(&Key::Num5), "{os:?}: an unclaimed keypad Alt+5 folds into an Alt code: {keys:?}"); - let (keys, _) = play(&mut frames, &mut show, code("5"), false); - assert!(keys.contains(&Key::Num5), "{os:?}: an unclaimed main-row Alt+5 is no code and reaches egui: {keys:?}"); + let (keys, _) = send(&mut frames, &mut show, top_row_code("3")); + assert!(keys.contains(&Key::Num3), "{os:?}: the canvas's claimed top-row Alt+3 reaches egui too: {keys:?}"); + let (keys, _) = send(&mut frames, &mut show, code("5")); + assert!(!keys.contains(&Key::Num5), "{os:?}: an unclaimed Alt+5 folds into an Alt code: {keys:?}"); request(&frames.ctx, FocusTarget::Id(canvas)); - let (keys, _) = play(&mut frames, &mut show, code("3"), true); + let (keys, _) = send(&mut frames, &mut show, code("3")); assert!(keys.contains(&Key::Num3), "{os:?}: the focused canvas's claimed Alt+3 reaches egui: {keys:?}"); click(&mut frames, AT.center(), &mut show); frames.idle(1, &mut show); - let (keys, text) = play(&mut frames, &mut show, code("0233"), true); + let (keys, text) = send(&mut frames, &mut show, code("0233")); assert_eq!(text, "é", "{os:?}: the focused field types the code, its 3 included"); assert!(keys.is_empty(), "{os:?}: no digit of the code reaches egui: {keys:?}"); } diff --git a/crates/ui-contract/tests/it/runtime/fork.rs b/crates/ui-contract/tests/it/runtime/fork.rs index 439e5aa648..8b1922f4e7 100644 --- a/crates/ui-contract/tests/it/runtime/fork.rs +++ b/crates/ui-contract/tests/it/runtime/fork.rs @@ -6,7 +6,7 @@ use craft_host::{AppInfo, Host, Jobs, ManualJobs}; use craft_ui::contract::{ContainerProps, Job, Pending, Props as _, Remember as _, Scroll, Show as _, ShowContainer as _}; use craft_ui::runtime::memory::{ForkError, fork_into}; use craft_ui::testing::layout::{Block, in_region}; -use craft_ui::testing::memory::{Stage, global, slot_records}; +use craft_ui::testing::memory::{Stage, dispose_evicted, forget, global, slot_records}; use craft_ui::testing::{Frames, pointer, trial}; use craft_ui_test_kit::body::Slab; use egui::{Pos2, Rect, Ui, Vec2}; @@ -156,3 +156,74 @@ fn a_fork_takes_the_copied_slots_registry_records_too() { assert!(copied > 0, "the destination holds the copied scroll slot's record"); assert_eq!(copied, slot_records(&window.ctx), "every copied slot has a record, none left behind"); } + +/// The fork replaces the destination's remembered slots, including the records that make their lifetimes work. +#[trial] +fn copied_slots_follow_destination_lifetimes_after_forking_into_a_used_context() { + let mut window = Frames::new(); + let mut shadow = Frames::new(); + let (copied, stale) = (global("fork.lifetime", "copied"), global("fork.lifetime", "stale")); + shadow.frame(vec![], |ui| { + let mut stage = Stage::open(ui.ctx(), stale); + *stage.keep::() = 8; + stage.finish(); + }); + window.frame(vec![], |ui| { + let mut stage = Stage::open(ui.ctx(), copied); + *stage.keep::() = 5; + *stage.memory::() = 7; + stage.finish(); + }); + fork_into(&window.ctx, &shadow.ctx).expect("the shadow is idle"); + assert_eq!(slot_records(&shadow.ctx), slot_records(&window.ctx), "the replaced context has no stale slot records"); + + // Never show the copied owner in the shadow during the whole eviction grace. + shadow.idle(60, |_| {}); + dispose_evicted(&shadow.ctx); + shadow.frame(vec![], |ui| { + let mut stage = Stage::open(ui.ctx(), copied); + assert_eq!(*stage.memory::(), 0, "the owner that never drew in the shadow was evicted"); + assert_eq!(*stage.keep::(), 5, "the copied session entry survives shown eviction"); + stage.finish(); + }); + forget(&shadow.ctx, copied); + shadow.frame(vec![], |ui| { + let mut stage = Stage::open(ui.ctx(), copied); + assert_eq!(*stage.keep::(), 0, "the copied session entry can be forgotten"); + stage.finish(); + }); + window.frame(vec![], |ui| { + let mut stage = Stage::open(ui.ctx(), copied); + assert_eq!(*stage.keep::(), 5, "the window's session entry is unchanged"); + assert_eq!(*stage.memory::(), 7, "the window's shown entry is unchanged"); + stage.finish(); + }); +} + +#[trial] +fn copied_appearance_marks_start_on_the_destinations_frame_timeline() { + let mut window = Frames::new(); + let mut shadow = Frames::new(); + let id = global("fork.appeared", ()); + window.idle(12, |ui| { + let mut stage = Stage::open(ui.ctx(), id); + *stage.memory::() = 7; + stage.finish(); + }); + fork_into(&window.ctx, &shadow.ctx).expect("the shadow is idle"); + let show = |expected| { + move |ui: &mut Ui| { + let mut stage = Stage::open(ui.ctx(), id); + assert_eq!(stage.appeared(), expected, "appearances follow the fork's own frame history"); + assert_eq!(*stage.memory::(), 7, "the copied value stays through an appearance"); + stage.finish(); + } + }; + // First showing need not be in the first frame of the shadow. + shadow.frame(vec![], |_| {}); + shadow.frame(vec![], show(true)); + shadow.frame(vec![], show(false)); + shadow.frame(vec![], |_| {}); + shadow.frame(vec![], show(true)); + shadow.frame(vec![], show(false)); +} diff --git a/crates/ui-contract/tests/it/runtime/wheel.rs b/crates/ui-contract/tests/it/runtime/wheel.rs index 642847972f..c5de7bda0c 100644 --- a/crates/ui-contract/tests/it/runtime/wheel.rs +++ b/crates/ui-contract/tests/it/runtime/wheel.rs @@ -327,16 +327,15 @@ fn a_wheel_over_an_open_popup_goes_to_the_popup_and_not_to_the_region_under_it() if open.get() { let overlay = Overlay::popover().place(Place::anchored(Anchor::Rect(anchor), Side::Below, Align::Start)); let props = ContainerProps::new().mount(Mount::Layer(overlay)).sizing(Sizing::Content); + // The popup's scroll region registers inside the popup's body, as a region in a layer does. let out = Popup { common: Common::new(), props }.id_salt("wheel_popup_layer").show(ui, |ui, _| { Probe::new(&popup_seen).size(Vec2::new(120.0, 60.0)).show(ui); + register(ui.ctx(), WheelTaker::new(popup, popup_rect.get()).vertical(true).scrolls(true)); }); popup_rect.set(out.output.rect); } register(&ctx, WheelTaker::new(panel, Rect::from_min_size(Pos2::ZERO, Vec2::splat(400.0))).vertical(true).scrolls(true)); register(&ctx, WheelTaker::new(field.get(), field_rect).vertical(true).field(true)); - if open.get() { - register(&ctx, WheelTaker::new(popup, popup_rect.get()).vertical(true).scrolls(true)); - } for id in [panel, field.get(), popup] { if let Some(share) = take_share(&ctx, id) { shares.borrow_mut().push((id, share)); @@ -369,6 +368,117 @@ fn a_wheel_over_an_open_popup_goes_to_the_popup_and_not_to_the_region_under_it() ); } +/// A floating panel with no scroll region of its own does not pass the wheel to the canvas under it, and one with a +/// scroll region takes the wheel itself. A wheel gesture begun on the canvas goes on there when the pointer crosses +/// into the panel. +#[trial] +fn a_wheel_over_a_floating_panel_does_not_reach_the_canvas_under_it() { + const PANEL_AT: Rect = Rect { min: Pos2::new(100.0, 100.0), max: Pos2::new(260.0, 220.0) }; + let canvas = Id::unique("floating_wheel_canvas"); + let region = Id::unique("floating_wheel_region"); + let (panel_seen, field_seen) = (RefCell::new(Seen::default()), RefCell::new(Seen::default())); + let field = Cell::new(Id::NULL); + let field_rect = Rect::from_min_size(Pos2::ZERO, Vec2::new(100.0, 20.0)); + let panel_rect = Cell::new(Rect::NOTHING); + let scrolls = Cell::new(false); + let shares: RefCell> = RefCell::new(Vec::new()); + let mut show_frame = |ui: &mut Ui| { + let ctx = ui.ctx().clone(); + field.set(Probe::new(&field_seen).size(field_rect.size()).sense(Sense::CLICK | Sense::FOCUS | Sense::TAKE_FOCUS).show(ui).id); + register(&ctx, WheelTaker::new(canvas, Rect::from_min_size(Pos2::ZERO, Vec2::splat(600.0))).vertical(true).zoom(true)); + register(&ctx, WheelTaker::new(field.get(), field_rect).vertical(true).field(true)); + let props = ContainerProps::new().mount(Mount::Layer(Overlay::floating().placed(PANEL_AT))).sizing(Sizing::Content); + let out = Popup { common: Common::new(), props }.id_salt("floating_wheel_panel").show(ui, |ui, _| { + Probe::new(&panel_seen).size(PANEL_AT.size()).show(ui); + if scrolls.get() { + register(ui.ctx(), WheelTaker::new(region, panel_rect.get()).vertical(true).scrolls(true)); + } + }); + panel_rect.set(out.output.rect); + for id in [canvas, region, field.get()] { + if take_share(&ctx, id).is_some() { + shares.borrow_mut().push(id); + } + } + }; + let mut frames = Frames::new(); + frames.idle(4, &mut show_frame); + assert!(panel_rect.get().is_positive(), "the panel shows: {:?}", panel_rect.get()); + let (on_panel, on_canvas) = (panel_rect.get().center(), Pos2::new(500.0, 500.0)); + assert!(!panel_rect.get().contains(on_canvas), "the second point is on the canvas, away from the panel"); + let turn = |frames: &mut Frames, at: Pos2, show_frame: &mut dyn FnMut(&mut Ui)| -> Vec { + frames.frame(vec![pointer::moved(at)], &mut *show_frame); + shares.borrow_mut().clear(); + frames.frame(vec![pointer::wheel(-30.0)], &mut *show_frame); + shares.borrow().clone() + }; + + frames.advance(GESTURE_GAP); + assert_eq!(turn(&mut frames, on_canvas, &mut show_frame), [canvas], "the canvas takes the wheel over itself"); + frames.advance(GESTURE_GAP); + assert_eq!(turn(&mut frames, on_panel, &mut show_frame), Vec::::new(), "over the panel the canvas takes no share"); + + // A gesture begun on the canvas keeps its owner while it runs. + frames.advance(GESTURE_GAP); + assert_eq!(turn(&mut frames, on_canvas, &mut show_frame), [canvas], "a gesture begins on the canvas"); + assert_eq!(turn(&mut frames, on_panel, &mut show_frame), [canvas], "the running gesture goes on on the canvas"); + + scrolls.set(true); + frames.advance(GESTURE_GAP); + frames.idle(2, &mut show_frame); + assert_eq!(turn(&mut frames, on_panel, &mut show_frame), [region], "a scroll region in the panel takes the wheel"); + + // A focused field takes the wheel wherever the pointer is, over the panel too. + scrolls.set(false); + frames.advance(GESTURE_GAP); + pointer::click(&mut frames, field_rect.center(), &mut show_frame); + frames.advance(GESTURE_GAP); + assert_eq!(turn(&mut frames, on_panel, &mut show_frame), [field.get()], "the focused field takes the wheel over the panel"); +} + +/// A body shown through a transform on its own sublayer inside a floating panel belongs to the panel: a scroll region +/// of the panel takes the wheel over it, not the canvas under the panel. +#[trial] +fn a_wheel_over_a_transformed_body_in_a_floating_panel_stays_in_the_panel() { + use craft_behavior::CanvasTransform; + const PANEL_AT: Rect = Rect { min: Pos2::new(100.0, 100.0), max: Pos2::new(300.0, 260.0) }; + let canvas = Id::unique("transformed_wheel_canvas"); + let region = Id::unique("transformed_wheel_region"); + let body_rect = Rect::from_min_size(PANEL_AT.min + Vec2::splat(20.0), Vec2::new(120.0, 80.0)); + let root = ProbeRoot::new("transformed_wheel_body", body_rect, Sense::HOVER) + .arena() + .transformed(CanvasTransform::new(1.0, Vec2::ZERO)) + .blocker(body_rect.size()); + let shares: RefCell> = RefCell::new(Vec::new()); + let mut show_frame = |ui: &mut Ui| { + let ctx = ui.ctx().clone(); + register(&ctx, WheelTaker::new(canvas, Rect::from_min_size(Pos2::ZERO, Vec2::splat(600.0))).vertical(true).zoom(true)); + let props = ContainerProps::new().mount(Mount::Layer(Overlay::floating().placed(PANEL_AT))).sizing(Sizing::Content); + Popup { common: Common::new(), props }.id_salt("transformed_wheel_panel").show(ui, |ui, _| { + show(ui, std::slice::from_ref(&root)); + register(ui.ctx(), WheelTaker::new(region, body_rect).vertical(true).scrolls(true)); + }); + for id in [canvas, region] { + if take_share(&ctx, id).is_some() { + shares.borrow_mut().push(id); + } + } + }; + let mut frames = Frames::new(); + frames.idle(4, &mut show_frame); + let on_body = body_rect.center(); + assert_ne!( + frames.ctx.layer_id_at(on_body), + frames.ctx.layer_id_at(PANEL_AT.max - Vec2::splat(5.0)), + "the body shows on a layer of its own inside the panel" + ); + frames.advance(GESTURE_GAP); + frames.frame(vec![pointer::moved(on_body)], &mut show_frame); + shares.borrow_mut().clear(); + frames.frame(vec![pointer::wheel(-30.0)], &mut show_frame); + assert_eq!(*shares.borrow(), [region], "the panel's region takes the wheel over its transformed body"); +} + /// A modal layer with an empty body. #[derive(craft_ui::contract::Component)] #[component(container, unregistered)] @@ -448,6 +558,118 @@ fn a_wheel_gesture_carries_the_keys_held_during_it_and_whether_it_began_under_a_ assert!(!fresh.modal, "a turn begun after the gap: {fresh:?}"); } +#[trial] +fn a_wheel_gesture_counts_only_the_shares_its_owner_claimed_and_an_app_modal_marks_it() { + let canvas = Id::unique("claim_canvas"); + let rect = Rect::from_min_size(Pos2::ZERO, Vec2::splat(400.0)); + // What the body does with this pass's share: claim it with this much spent, and mark the turn modal. + let claim: Cell> = Cell::new(None); + let modal = Cell::new(false); + let last: Cell> = Cell::new(None); + let last_token = Cell::new(None); + let mut show_frame = |ui: &mut Ui| { + register(ui.ctx(), WheelTaker::new(canvas, rect).vertical(true).scrolls(true)); + if let Some(share) = take_share(ui.ctx(), canvas) { + last.set(Some(share)); + let token = craft_ui::runtime::wheel::claim_token(ui.ctx(), canvas).expect("a claimable share"); + last_token.set(Some(token)); + for invalid in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] { + for spent in [Vec2::new(invalid, 0.0), Vec2::new(0.0, invalid)] { + assert!(!craft_ui::runtime::wheel::claim(ui.ctx(), canvas, token, spent), "a claim of {spent:?} is refused"); + } + } + if let Some(spent) = claim.get() { + // A body that runs twice in a pass claims once. + assert!(craft_ui::runtime::wheel::claim(ui.ctx(), canvas, token, spent)); + assert!(craft_ui::runtime::wheel::claim(ui.ctx(), canvas, token, spent)); + } + if modal.get() { + craft_ui::runtime::wheel::mark_modal(ui.ctx(), canvas); + } + } + }; + let mut frames = Frames::new(); + frames.idle(2, &mut show_frame); + frames.frame(vec![pointer::moved(Pos2::new(200.0, 200.0))], &mut show_frame); + let turn = |frames: &mut Frames, show_frame: &mut dyn FnMut(&mut Ui), take: Option| { + claim.set(take); + last.set(None); + frames.frame(vec![pointer::wheel(-30.0)], &mut *show_frame); + last.take().expect("the canvas takes the wheel") + }; + + // The first share is not claimed: the claims count nothing of it. + let first = turn(&mut frames, &mut show_frame, None); + assert!(!first.claimed && first.claimed_gathered == Vec2::ZERO, "nothing claimed yet: {first:?}"); + assert!( + !craft_ui::runtime::wheel::claim(&frames.ctx, canvas, last_token.get().expect("the last share's token"), Vec2::new(0.0, 10.0)), + "a share cannot be claimed between passes" + ); + assert!(!craft_ui::runtime::wheel::claimed(&frames.ctx, canvas), "a rejected claim does not cancel navigation"); + let second = turn(&mut frames, &mut show_frame, Some(Vec2::new(0.0, 1.0))); + assert!(!second.claimed && second.claimed_gathered == Vec2::ZERO, "the first share was left unclaimed: {second:?}"); + assert!( + !craft_ui::runtime::wheel::claim(&frames.ctx, canvas, last_token.get().expect("the last share's token"), Vec2::new(0.0, 10.0)), + "a late claim cannot replace the body's spent motion" + ); + let third = turn(&mut frames, &mut show_frame, Some(Vec2::new(0.0, -1.0))); + assert!(third.claimed, "the second share was claimed: {third:?}"); + assert_eq!((third.claimed_gathered, third.claimed_spent), (second.scroll, Vec2::new(0.0, 1.0)), "one claim of the second share: {third:?}"); + assert_eq!(third.gathered, first.scroll + second.scroll + third.scroll, "the gesture still gathers every share: {third:?}"); + let fourth = turn(&mut frames, &mut show_frame, None); + assert_eq!((fourth.claimed_gathered, fourth.claimed_spent), (second.scroll + third.scroll, Vec2::ZERO), "{fourth:?}"); + + // An app's own modal marks the rest of the turn, and a new turn starts with no claims and no mark. + modal.set(true); + let marked = turn(&mut frames, &mut show_frame, None); + assert!(!marked.modal, "the mark comes after the share: {marked:?}"); + modal.set(false); + let after = turn(&mut frames, &mut show_frame, None); + assert!(after.modal && after.claimed, "the rest of the turn is marked: {after:?}"); + frames.advance(GESTURE_GAP); + frames.idle(2, &mut show_frame); + let fresh = turn(&mut frames, &mut show_frame, None); + assert!(!fresh.modal && !fresh.claimed && fresh.claimed_gathered == Vec2::ZERO && fresh.claimed_spent == Vec2::ZERO, "{fresh:?}"); +} + +/// An unread cancellation survives gesture close while its owner registers and is released when that owner leaves. +#[trial] +fn unread_claim_cancellations_follow_registered_owners() { + for discarded in [false, true] { + let canvas = Id::unique("discarded_claim_canvas"); + let rect = Rect::from_min_size(Pos2::ZERO, Vec2::splat(400.0)); + let registered = Cell::new(true); + let consume = Cell::new(false); + let claimed = Cell::new(false); + let canceled = Cell::new(None); + let mut show_frame = |ui: &mut Ui| { + if registered.get() { + register(ui.ctx(), WheelTaker::new(canvas, rect).vertical(true).scrolls(true)); + if take_share(ui.ctx(), canvas).is_some() { + let token = craft_ui::runtime::wheel::claim_token(ui.ctx(), canvas).expect("a claimable share"); + craft_ui::runtime::wheel::claim(ui.ctx(), canvas, token, Vec2::ZERO); + claimed.set(true); + } + if consume.take() { + canceled.set(Some(craft_ui::runtime::wheel::claimed(ui.ctx(), canvas))); + } + } + }; + let mut frames = Frames::new(); + frames.idle(2, &mut show_frame); + frames.frame(vec![pointer::moved(rect.center())], &mut show_frame); + frames.frame(vec![pointer::wheel(-30.0)], &mut show_frame); + assert!(claimed.get(), "the owner claimed its share"); + frames.advance(GESTURE_GAP); + registered.set(!discarded); + frames.idle(2, &mut show_frame); + registered.set(true); + consume.set(true); + frames.frame(Vec::new(), &mut show_frame); + assert_eq!(canceled.get(), Some(!discarded), "discarded {discarded}: only a registered owner retains its cancellation"); + } +} + #[trial] fn the_end_share_of_a_pressed_wheel_gesture_carries_a_key_tapped_before_the_press_in_its_pass() { let slider = Id::unique("press_held_slider"); diff --git a/crates/ui-contract/tests/it/runtime/windows.rs b/crates/ui-contract/tests/it/runtime/windows.rs index 49153a2259..f8a3aebe1b 100644 --- a/crates/ui-contract/tests/it/runtime/windows.rs +++ b/crates/ui-contract/tests/it/runtime/windows.rs @@ -644,6 +644,32 @@ fn a_popup_window_stays_after_the_press_in_another_window_that_opened_it() { assert_eq!(closed.borrow().first(), Some(&CloseReason::Outside), "a later press in the main window closes it"); } +/// A scroll region in the body of a tool window takes the wheel over it: the body is the base of the window's own +/// viewport, not a layer above it. +#[trial] +fn a_scroll_region_in_a_tool_window_takes_the_wheel() { + use craft_behavior::WheelTaker; + use craft_ui::testing::wheel::{register, take}; + let windows = Windows::new(); + let view = egui::Id::unique("tool_window_view"); + let taken = Cell::new(None); + let frame = |child: Vec| { + windows.frame(vec![], child, |ui| { + Palette::new("tool", Some(WindowSpec::tool())).show(ui, |ui, _| { + register(ui.ctx(), WheelTaker::new(view, Rect::from_min_size(Pos2::ZERO, Vec2::splat(400.0))).vertical(true).scrolls(true)); + if let Some(scroll) = take(ui.ctx(), view) { + taken.set(Some(scroll)); + } + }); + }) + }; + for _ in 0..4 { + frame(vec![moved(Pos2::new(20.0, 20.0))]); + } + frame(vec![wheel(-30.0)]); + assert!(taken.get().is_some(), "the region in the tool window takes the wheel"); +} + /// A window that a modal in another window blocks takes no wheel, as it takes no press or key: what is under the /// pointer there does not scroll. #[trial] diff --git a/crates/ui-panels/src/dialog/modal.rs b/crates/ui-panels/src/dialog/modal.rs index 8c9e9b2cba..7dda6ad543 100644 --- a/crates/ui-panels/src/dialog/modal.rs +++ b/crates/ui-panels/src/dialog/modal.rs @@ -133,10 +133,10 @@ impl<'a> Dialog<'a> { Dialog::on(title, overlay, HEADER.band(DragBand::Move)) } - /// A prompt titled `title`: a dialog centred with its content capped, fixed in place and - /// not remembered. + /// A prompt titled `title`: a dialog centred with its content capped and not remembered. It moves by its title band, + /// as every dialog does, so it can be moved off what the user needs to see while answering it. pub fn prompt(title: impl Into