diff --git a/Cargo.lock b/Cargo.lock index 5c5036c9af..c0e3142ebd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5414,7 +5414,9 @@ dependencies = [ "craft-cms", "craft-flags", "craft-image-codecs", + "craft-svg", "craft-update", + "craft-xml", "dispatch2", "eframe", "egui", @@ -5438,10 +5440,8 @@ dependencies = [ "photocraft-tablet", "photocraft-ui-egui", "plist", - "resvg 0.45.1", "rfd", "ron", - "roxmltree 0.21.2", "rustix 1.1.5", "serde", "serde_json", @@ -5479,7 +5479,6 @@ dependencies = [ "cap-std", "clap", "craft-ai-agents", - "craft-file-formats", "craft-flags", "craft-image-codecs", "craft-psd", @@ -5705,10 +5704,8 @@ dependencies = [ "photocraft-text", "photocraft-vector", "proptest", - "roxmltree 0.21.2", "serde_json", "thiserror 2.0.21", - "tiff", "ttf-parser", "zune-core", "zune-jpegxl", @@ -5775,11 +5772,11 @@ dependencies = [ name = "photocraft-raw" version = "0.23.1" dependencies = [ + "craft-image-codecs", "craft-raw", "flate2", "image", "photocraft-raw", - "png 0.18.1", "rayon", "zune-core", "zune-jpegxl", diff --git a/Cargo.toml b/Cargo.toml index bf7ca911a7..1ec3fe6b37 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -82,9 +82,8 @@ bytemuck = { version = "1", features = ["derive"] } flate2 = { version = "1.1.10", default-features = false, features = ["zlib-rs", "runtime_detection"] } encoding_rs = { version = "0.8", default-features = false, features = ["alloc"] } image = { version = "0.25", default-features = false } -# Baseline-JPEG decode of lossy DNG tiles (compression 34892), shared with zune-jpeg. +# Baseline-JPEG decode of lossy DNG tiles (compression 34892). zune-core = "0.5" -zune-jpeg = "0.5" proptest = "1" eframe = { version = "0.37", default-features = false } # Without `default_fonts`, which embeds egui's fonts uncompressed: ui-egui ships them deflated diff --git a/apps/photocraft/Cargo.toml b/apps/photocraft/Cargo.toml index a864529767..0ed338bb97 100644 --- a/apps/photocraft/Cargo.toml +++ b/apps/photocraft/Cargo.toml @@ -42,7 +42,7 @@ thiserror = { workspace = true } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] tempfile = "=3.27.0" -roxmltree = "0.21" +craft-xml = { workspace = true } craft-update = { workspace = true } rfd = { workspace = true } arboard = { version = "3.7", features = ["wayland-data-control"] } @@ -94,8 +94,8 @@ wl-clipboard-rs = { version = "=0.9.4", default-features = false } # Wayland desktop color selection through the existing XDG portal transport. zbus = "=5.19.0" # Caption button glyphs from the desktop's icon theme (`caption_style.rs`): SVG paths only, no -# text or images. Already in Cargo.lock (photocraft-io); pinned exactly. -resvg = { version = "=0.45.1", default-features = false } +# text or images. Already in Cargo.lock (photocraft-io). +craft-svg = { workspace = true } # Already used by the portal stack; bounded waits let cancelling close the OS request. futures-lite = "=2.6.1" async-io = "=2.6.0" diff --git a/apps/photocraft/src/icon_theme.rs b/apps/photocraft/src/icon_theme.rs index 66647cd1db..16cd47c7cb 100644 --- a/apps/photocraft/src/icon_theme.rs +++ b/apps/photocraft/src/icon_theme.rs @@ -200,7 +200,7 @@ impl IconTheme { /// An SVG's coverage (alpha) as a `px` × `px` mask, the drawing fitted and centred. `None` for an /// unreadable SVG or an absurd size. pub fn rasterize_mask(svg: &[u8], px: u32) -> Option> { - use resvg::{tiny_skia, usvg}; + use craft_svg::tree::{draw, draw::tiny_skia, usvg}; // usvg inflates gzip (`.svgz`) input without a decoded-size limit, and icons are plain `.svg`. if !(1..=256).contains(&px) || svg.starts_with(&[0x1f, 0x8b]) { return None; @@ -221,8 +221,7 @@ pub fn rasterize_mask(svg: &[u8], px: u32) -> Option> { } let s = px as f32 / side; let (dx, dy) = ((px as f32 - size.width() * s) / 2.0, (px as f32 - size.height() * s) / 2.0); - let mut pixmap = tiny_skia::Pixmap::new(px, px)?; - resvg::render(&tree, tiny_skia::Transform::from_scale(s, s).post_translate(dx, dy), &mut pixmap.as_mut()); + let pixmap = draw::render(&tree, tiny_skia::Transform::from_scale(s, s).post_translate(dx, dy), px, px, 0, 64 * 1024 * 1024).ok()?; Some(pixmap.data().as_chunks::<4>().0.iter().map(|[_, _, _, a]| *a).collect()) })) .ok() diff --git a/apps/photocraft/src/vector_conversion.rs b/apps/photocraft/src/vector_conversion.rs index ce473a1b95..f2787511a1 100644 --- a/apps/photocraft/src/vector_conversion.rs +++ b/apps/photocraft/src/vector_conversion.rs @@ -147,9 +147,9 @@ fn export_commands(input: &Path, output: &Path, format: &str) -> Result<[(u8, &' fn source_svg(bytes: &[u8], size: Option<(f64, f64)>) -> Result, String> { let text = std::str::from_utf8(bytes).map_err(|_| "Converted SVG is not UTF-8")?; photocraft_io::svg::import_svg_bounded_with_work("Artwork.svg", bytes, 96_000_000).map_err(|e| format!("Converted SVG is unsupported: {e}"))?; - let doc = roxmltree::Document::parse(text).map_err(|e| format!("Invalid converted SVG: {e}"))?; - let root = doc.root_element(); - if root.tag_name().name() != "svg" { + let root = craft_xml::parse(text.as_bytes()).map_err(|e| format!("Invalid converted SVG: {e}"))?; + let local_name = root.name.rsplit_once(':').map_or(root.name.as_str(), |(_, l)| l); + if local_name != "svg" { return Err("VectorCraft did not return SVG".into()); } let Some((w, h)) = size else { @@ -161,12 +161,12 @@ fn source_svg(bytes: &[u8], size: Option<(f64, f64)>) -> Result, String> // The nested root keeps its own width/height, so the outer viewBox must use the same CSS // pixels: `612pt` is 816 user units at SVG's 96 dpi. Other units are rejected below. let dimension = |key| { - let value = root.attribute(key)?; + let value = root.attr(key)?; let (number, scale) = value.strip_suffix("pt").map_or((value, 1.0), |number| (number, 4.0 / 3.0)); number.parse::().ok().map(|v| v * scale).filter(|v| v.is_finite() && *v > 0.0) }; let (iw, ih) = dimension("width").zip(dimension("height")).ok_or("Converted SVG has no finite dimensions")?; - let inner = text.get(root.range()).ok_or("Invalid SVG root range")?; + let inner = root.to_xml(); let result = format!(r#"{inner}"#) .into_bytes(); diff --git a/crates/automation/Cargo.toml b/crates/automation/Cargo.toml index 63991e8044..034bf01e70 100644 --- a/crates/automation/Cargo.toml +++ b/crates/automation/Cargo.toml @@ -23,7 +23,6 @@ photocraft-doc = { workspace = true } photocraft-raster = { workspace = true } photocraft-compose = { workspace = true } photocraft-codecs = { workspace = true } -photocraft-formats = { workspace = true } photocraft-io = { workspace = true } photocraft-format = { path = "../format" } photocraft-engine = { workspace = true } diff --git a/crates/automation/src/workspace.rs b/crates/automation/src/workspace.rs index e36ad16989..176541f258 100644 --- a/crates/automation/src/workspace.rs +++ b/crates/automation/src/workspace.rs @@ -248,23 +248,25 @@ impl Drop for TempRemoval<'_> { } } -/// Whether `name`'s extension is one of the formats PhotoCraft saves or exports. +/// Whether `name`'s extension is one of the formats PhotoCraft saves or exports. The image codec +/// registry, not `photocraft_formats`: that one also names text and office files PhotoCraft only +/// reads (`txt`, `md`, `csv`, `rtf`…), and notes must never be replaced (#14355). A codec counts +/// only if this build writes it: PCX, XPM, DICOM and HEIF are read-only. fn written_kind(name: &str) -> bool { let Some((_, ext)) = name.rsplit_once('.') else { return false }; let ext = ext.to_ascii_lowercase(); - // The shared file registry also recognizes notes and source formats. Only - // raster codecs and PhotoCraft's document outputs authorize replacement. - ["psd", "psb", "ora", "pdf", photocraft_format::EXTENSION].contains(&ext.as_str()) || photocraft_codecs::from_extension(&ext).is_some() + ["psd", "psb", "ora", "pdf", photocraft_format::EXTENSION].contains(&ext.as_str()) + || photocraft_codecs::from_extension(&ext).is_some_and(|format| format.caps().write) } -/// Whether the file at `relative` starts like an image PhotoCraft reads (PSD/PSB or a codec's -/// magic). Containers that also hold other things (zip, PDF) are judged by name only. +/// Whether the file at `relative` starts like an image PhotoCraft writes (PSD/PSB or a writable +/// codec's magic). Containers that also hold other things (zip, PDF) are judged by name only. fn holds_image(dir: &Dir, relative: &Path) -> bool { let mut head = [0u8; 64]; let Ok(mut file) = dir.open(relative) else { return false }; let Ok(n) = file.read(&mut head) else { return false }; let head = &head[..n]; - head.starts_with(b"8BPS") || photocraft_formats::detect("", head).is_some() + head.starts_with(b"8BPS") || photocraft_codecs::detect(head).is_some_and(|format| format.caps().write) } fn read_to_observed_length(reader: &mut impl Read, observed_length: u64) -> Result, AutomationError> { diff --git a/crates/automation/src/workspace/tests.rs b/crates/automation/src/workspace/tests.rs index 257d8d8c71..d7ff20a3ed 100644 --- a/crates/automation/src/workspace/tests.rs +++ b/crates/automation/src/workspace/tests.rs @@ -152,6 +152,32 @@ fn write_stream_seeks_back_and_keeps_the_original_on_failure() { assert_eq!(std::fs::read(inside.join("notes.txt")).unwrap(), b"keep"); } +/// #14355: files PhotoCraft can read but never writes (notes, data, rich text, read-only image +/// formats such as XPM or DICOM) are not "a kind PhotoCraft writes", by name or by their bytes (#9439). +#[test] +fn write_refuses_to_replace_files_photocraft_reads_but_does_not_write() { + let (inside, _, workspace) = roots("read-only-kinds"); + let files: [(&str, &[u8]); 7] = [ + ("notes.md", b"# keep"), + ("data.csv", b"a,b\n1,2\n"), + ("letter.rtf", b"{\\rtf1 keep}"), + ("README", b"{\\rtf1 keep}"), + ("icon.xpm", b"/* XPM */ keep"), + ("scan.dcm", b"keep"), + ("TODO", b"/* XPM */ keep"), + ]; + let replaced: Vec<&str> = files + .into_iter() + .filter(|(name, bytes)| { + std::fs::write(inside.join(name), bytes).unwrap(); + workspace.write(name, b"\x89PNG\r\n\x1a\n").is_ok() || std::fs::read(inside.join(name)).unwrap() != *bytes + }) + .map(|(name, _)| name) + .collect(); + assert!(replaced.is_empty(), "replaced: {replaced:?}"); + assert!(temp_files(&inside).is_empty()); +} + /// A writer that panics leaves the original and no temporary file behind. #[test] fn write_stream_cleans_up_after_a_panicking_writer() { diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 8cc159e9c9..99bf586b28 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -68,7 +68,7 @@ photocraft-io = { workspace = true, features = ["testgen"] } # Synthetic camera raw files for the open tests. photocraft-raw = { workspace = true, features = ["testgen"] } photocraft-testkit = { workspace = true } +exr = { version = "1.73", default-features = false } # WebAssembly text -> binary for plug-in test modules (Apache-2.0 WITH LLVM-exception). wat = "1.228" # Synthetic multi-part EXR fixtures for the parts-commands tests. -exr = { version = "1.73", default-features = false } diff --git a/crates/engine/src/cmd/lens_batch_gray_tests.rs b/crates/engine/src/cmd/lens_batch_gray_tests.rs new file mode 100644 index 0000000000..218caf2e88 --- /dev/null +++ b/crates/engine/src/cmd/lens_batch_gray_tests.rs @@ -0,0 +1,66 @@ +//! File › Automate › Lens Correction hands back a Grayscale 8-bit source as RGB 8-bit, as +//! Photoshop does; other modes and depths keep today's behaviour (#13990). +#![cfg(not(target_arch = "wasm32"))] + +use std::path::{Path, PathBuf}; + +use photocraft_color::{ColorMode, SampleType}; +use serde_json::json; + +use super::LENS_BATCH; +use crate::Session; + +fn temp_dir(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("pc-lens-gray-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("in")).unwrap(); + dir +} + +/// Writes a 40 x 30 source in `mode` and `depth` to `/in/`. +fn source(dir: &Path, file: &str, mode: &str, depth: u32) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 40, "height": 30, "mode": mode, "depth": depth})).unwrap(); + let path = dir.join("in").join(file); + crate::file_cmds::save_doc(&s.active().unwrap().doc, path.to_str().unwrap(), None).unwrap(); +} + +/// Runs the batch on `/in` with `format` and returns the mode and depth of `/out/`. +fn run(dir: &Path, format: &str, file: &str) -> (ColorMode, SampleType) { + let mut s = Session::new(); + let r = s.execute(LENS_BATCH, json!({"input": dir.join("in").to_str().unwrap(), "output": dir.join("out").to_str().unwrap(), "format": format})).unwrap(); + assert!(r["errors"].as_array().unwrap().is_empty(), "{r}"); + let path = dir.join("out").join(file); + let doc = photocraft_io::import(file, &std::fs::read(&path).unwrap()).unwrap().document; + (doc.mode, doc.depth) +} + +#[test] +fn a_grayscale_8_bit_source_comes_out_rgb_8_bit_in_every_file_type() { + for format in ["psd", "tif", "png", "jpg"] { + let dir = temp_dir(format); + source(&dir, "gray.psd", "grayscale", 8); + assert_eq!(run(&dir, format, &format!("gray.{format}")), (ColorMode::Rgb, SampleType::U8), "{format}"); + let _ = std::fs::remove_dir_all(&dir); + } +} + +#[test] +fn rgb_sources_keep_their_depth() { + for (format, depth, sample) in [("psd", 8, SampleType::U8), ("psd", 16, SampleType::U16), ("tif", 8, SampleType::U8), ("tif", 16, SampleType::U16)] { + let dir = temp_dir(&format!("rgb{depth}-{format}")); + source(&dir, "rgb.psd", "rgb", depth); + assert_eq!(run(&dir, format, &format!("rgb.{format}")), (ColorMode::Rgb, sample), "{format} {depth}"); + let _ = std::fs::remove_dir_all(&dir); + } +} + +#[test] +fn other_modes_and_depths_keep_their_mode() { + for (mode, depth, expected) in [("grayscale", 16, (ColorMode::Grayscale, SampleType::U16)), ("cmyk", 8, (ColorMode::Cmyk, SampleType::U8))] { + let dir = temp_dir(&format!("{mode}{depth}")); + source(&dir, "src.psd", mode, depth); + assert_eq!(run(&dir, "psd", "src.psd"), expected, "{mode} {depth}"); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/engine/src/cmd/lens_cmds.rs b/crates/engine/src/cmd/lens_cmds.rs index 5c0d7544d1..8ce6d4c689 100644 --- a/crates/engine/src/cmd/lens_cmds.rs +++ b/crates/engine/src/cmd/lens_cmds.rs @@ -438,6 +438,10 @@ fn lens_batch(s: &mut Session, p: &Value) -> Result { if scratch.active().is_some_and(|d| d.doc.layers.len() > 1) { scratch.execute("layer.flattenImage", json!({}))?; } + // Photoshop's batch hands back a Grayscale 8-bit source as RGB 8-bit, whatever the File Type. + if scratch.active().is_some_and(|d| d.doc.mode == ColorMode::Grayscale && d.doc.depth == SampleType::U8) { + scratch.execute("image.mode.rgb", json!({}))?; + } scratch.execute(LENS, params.clone())?; Ok(()) }); @@ -491,6 +495,9 @@ pub fn specs() -> Vec { ] } +#[cfg(test)] +#[path = "lens_batch_gray_tests.rs"] +mod lens_batch_gray_tests; #[cfg(test)] mod tests { diff --git a/crates/io/Cargo.toml b/crates/io/Cargo.toml index b3de2eeaf5..7280fa576e 100644 --- a/crates/io/Cargo.toml +++ b/crates/io/Cargo.toml @@ -64,8 +64,6 @@ kurbo = { version = "0.13", optional = true } [dev-dependencies] lopdf = { version = "0.38", default-features = false } -# PDF XMP serialization assertions parse output XML in tests. -roxmltree = "0.21" miniz_oxide = "0.9" crc32fast = "1.5" craft-affinity = { workspace = true, features = ["synth"] } @@ -77,4 +75,3 @@ proptest = { workspace = true } # Lossless JPEG XL encoder for the JPEG XL DNG preview test (tests only), as in photocraft-raw. zune-jpegxl = { version = "=0.5.2", default-features = false, features = ["std"] } zune-core = { workspace = true } -tiff = { version = "0.11", default-features = false, features = ["deflate", "lzw"] } diff --git a/crates/io/src/pdf/tests.rs b/crates/io/src/pdf/tests.rs index 37575545e8..3dd6322c88 100644 --- a/crates/io/src/pdf/tests.rs +++ b/crates/io/src/pdf/tests.rs @@ -442,15 +442,24 @@ fn the_plate_description_joins_the_rdf_element_however_the_packet_spells_it() { d.channels.push(spot("Varnish", photocraft_color::Color::rgb(0.9, 0.9, 0.6), &[1.0; 8])); // The packet must parse as namespaced XML with the plates a description inside its RDF element. let plates_in_rdf = |xmp: &str| { - let tree = roxmltree::Document::parse(xmp.trim_start_matches('\u{feff}')).unwrap_or_else(|e| panic!("{e}: {xmp}")); - let plates = tree - .descendants() - .find(|n| n.tag_name().namespace() == Some(crate::pdf::SPOT_PLATES_NS) && n.tag_name().name() == "plates") - .unwrap_or_else(|| panic!("no pcsp:plates: {xmp}")); - let description = plates.parent_element().unwrap(); - assert_eq!((description.tag_name().namespace(), description.tag_name().name()), (Some(RDF), "Description"), "{xmp}"); - let rdf = description.parent_element().unwrap(); - assert_eq!((rdf.tag_name().namespace(), rdf.tag_name().name()), (Some(RDF), "RDF"), "{xmp}"); + let canon = craft_xml::Canonical::new(&[("rdf", RDF), ("pcsp", crate::pdf::SPOT_PLATES_NS)]); + let tree = craft_xml::Options::canonical(&canon).parse(xmp.trim_start_matches('\u{feff}').as_bytes()).unwrap_or_else(|e| panic!("{e}: {xmp}")); + fn child_els(el: &craft_xml::El) -> impl Iterator { + el.children.iter().filter_map(|n| match n { + craft_xml::Node::El(e) => Some(e), + _ => None, + }) + } + let mut stack = vec![&tree]; + let mut found = false; + while let Some(el) = stack.pop() { + if el.name == "rdf:RDF" && child_els(el).any(|d| d.name == "rdf:Description" && child_els(d).any(|p| p.name == "pcsp:plates")) { + found = true; + break; + } + stack.extend(child_els(el)); + } + assert!(found, "no rdf:RDF/rdf:Description/pcsp:plates: {xmp}"); assert_eq!(xmp.matches("\n\n"; diff --git a/crates/io/tests/it/tiff_layers.rs b/crates/io/tests/it/tiff_layers.rs index 5eb2020e42..e2e3a5b67a 100644 --- a/crates/io/tests/it/tiff_layers.rs +++ b/crates/io/tests/it/tiff_layers.rs @@ -412,44 +412,27 @@ fn damaged_layer_data_opens_flattened_part(part: u64) { /// the file is retagged MinIsBlack first. The result is then a multiband image of every sample, /// which is what libtiff's `TIFFReadScanline` returns and what a RIP walks. fn independent_samples(bytes: &[u8]) -> (u16, Vec, Vec, u32, Vec) { - let mut tags = tiff::decoder::Decoder::new(std::io::Cursor::new(bytes)).expect("tiff tags"); - let spp: u16 = tags.get_tag_unsigned(tiff::tags::Tag::SamplesPerPixel).expect("spp"); - let bps = tags.get_tag_u16_vec(tiff::tags::Tag::BitsPerSample).expect("bps"); - let extra = tags.get_tag_u16_vec(tiff::tags::Tag::ExtraSamples).unwrap_or_default(); - let rows = tags.find_tag_unsigned::(tiff::tags::Tag::RowsPerStrip).ok().flatten().unwrap_or(0); - let patched = photometric_min_is_black(bytes); - let mut dec = tiff::decoder::Decoder::new(std::io::Cursor::new(patched.as_slice())).expect("tiff decode"); - let tiff::decoder::DecodingResult::U8(samples) = dec.read_image().expect("read image") else { - panic!("expected 8-bit samples"); - }; - (spp, bps, extra, rows, samples) -} - -/// Classic-TIFF photometric tag 262 → 1 (MinIsBlack), value stored inline in the IFD entry. -fn photometric_min_is_black(src: &[u8]) -> Vec { - let mut bytes = src.to_vec(); - let le = bytes.first().copied() == Some(b'I'); - let ru16 = |b: &[u8], i: usize| -> Option { - let s = b.get(i..i + 2)?; - Some(if le { u16::from_le_bytes([s[0], s[1]]) } else { u16::from_be_bytes([s[0], s[1]]) }) - }; - let ru32 = |b: &[u8], i: usize| -> Option { - let s = b.get(i..i + 4)?; - Some(if le { u32::from_le_bytes(s.try_into().ok()?) } else { u32::from_be_bytes(s.try_into().ok()?) }) - }; - let Some(ifd) = ru32(&bytes, 4) else { return bytes }; - let Some(n) = ru16(&bytes, ifd as usize) else { return bytes }; - for e in 0..n as usize { - let at = ifd as usize + 2 + e * 12; - if ru16(&bytes, at) == Some(262) { - let value = if le { 1u16.to_le_bytes() } else { 1u16.to_be_bytes() }; - if let Some(slot) = bytes.get_mut(at + 8..at + 10) { - slot.copy_from_slice(&value); + use std::io::Read; + let tiff = craft_tiff::Tiff::parse(bytes).expect("tiff tags"); + let ifd = tiff.ifds.first().expect("ifd0"); + let spp = ifd.u16(craft_tiff::tags::SAMPLES_PER_PIXEL).expect("spp"); + let bps: Vec = ifd.value(craft_tiff::tags::BITS_PER_SAMPLE).expect("bps").to_u64_vec().into_iter().map(|v| v as u16).collect(); + let extra: Vec = ifd.value(craft_tiff::tags::EXTRA_SAMPLES).map(|v| v.to_u64_vec().into_iter().map(|x| x as u16).collect()).unwrap_or_default(); + let rows = ifd.u32(craft_tiff::tags::ROWS_PER_STRIP).unwrap_or(0); + let info = craft_tiff::image::ImageInfo::from_ifd(ifd).expect("tiff info"); + let comp = ifd.u16(craft_tiff::tags::COMPRESSION).unwrap_or(1); + let mut samples = Vec::new(); + for chunk in info.chunks(bytes.len() as u64) { + let raw = craft_tiff::image::chunk_bytes(bytes, &chunk).expect("chunk bytes"); + match comp { + 1 => samples.extend_from_slice(raw), + 8 | 32946 => { + flate2::read::ZlibDecoder::new(raw).read_to_end(&mut samples).expect("deflate"); } - break; + other => panic!("unexpected compression {other} in tiff_layers test"), } } - bytes + (spp, bps, extra, rows, samples) } fn assert_plane(samples: &[u8], spp: usize, plane: usize, expected: &[u8]) { @@ -616,8 +599,8 @@ fn transparent_tiff_without_channels_keeps_image_alpha() { let img = photocraft_codecs::decode(&r.bytes).unwrap(); assert!(img.layout().has_alpha(), "{layers}"); assert!(img.meta.extra_samples.is_empty(), "{layers}"); - let mut dec = tiff::decoder::Decoder::new(std::io::Cursor::new(r.bytes.as_slice())).unwrap(); - let extra = dec.get_tag_u16_vec(tiff::tags::Tag::ExtraSamples).unwrap(); + let parsed = craft_tiff::Tiff::parse(&r.bytes).unwrap(); + let extra: Vec = parsed.ifds[0].value(craft_tiff::tags::EXTRA_SAMPLES).unwrap().to_u64_vec().into_iter().map(|x| x as u16).collect(); assert_eq!(extra, vec![2], "{layers}"); assert!(!r.warnings.iter().any(|w| w.contains("Save Transparency")), "{layers}: {:?}", r.warnings); if layers { diff --git a/crates/io/tests/it/tiff_save_options.rs b/crates/io/tests/it/tiff_save_options.rs index 3bdedc71a3..d3329bf1aa 100644 --- a/crates/io/tests/it/tiff_save_options.rs +++ b/crates/io/tests/it/tiff_save_options.rs @@ -33,8 +33,12 @@ fn save(doc: &Document, layers: bool, transparency: Option) -> ExportResul } fn extra_samples_tag(bytes: &[u8]) -> Vec { - let mut dec = tiff::decoder::Decoder::new(std::io::Cursor::new(bytes)).unwrap(); - dec.get_tag_u16_vec(tiff::tags::Tag::ExtraSamples).unwrap_or_default() + let tiff = craft_tiff::Tiff::parse(bytes).unwrap(); + tiff.ifds + .first() + .and_then(|ifd| ifd.value(craft_tiff::tags::EXTRA_SAMPLES)) + .map(|v| v.to_u64_vec().into_iter().map(|x| x as u16).collect()) + .unwrap_or_default() } /// A TIFF's channel resources: the names in 1006, and the byte lengths of DisplayInfo (1077) diff --git a/crates/raw/Cargo.toml b/crates/raw/Cargo.toml index 462847468b..76410f1340 100644 --- a/crates/raw/Cargo.toml +++ b/crates/raw/Cargo.toml @@ -27,7 +27,7 @@ rayon = { workspace = true } [dev-dependencies] photocraft-raw = { path = ".", features = ["testgen"] } # Writes sRGB PNG previews in the `rawinfo` example. -png = "0.18" +photocraft-codecs = { workspace = true } # JPEG XL encoder used by legacy test fixtures only. zune-jpegxl = { version = "=0.5.2", default-features = false, features = ["std"] } zune-core = "0.5" diff --git a/crates/raw/examples/rawinfo.rs b/crates/raw/examples/rawinfo.rs index dd32a7f8cf..26f4f501c7 100644 --- a/crates/raw/examples/rawinfo.rs +++ b/crates/raw/examples/rawinfo.rs @@ -236,11 +236,13 @@ fn write_png(path: &str, dev: &photocraft_raw::Developed) { } } } - let Ok(f) = std::fs::File::create(path) else { return eprintln!("{path}: cannot create") }; - let mut enc = png::Encoder::new(std::io::BufWriter::new(f), ow as u32, oh as u32); - enc.set_color(png::ColorType::Rgb); - enc.set_depth(png::BitDepth::Eight); - if let Err(e) = enc.write_header().and_then(|mut w| w.write_image_data(&out)) { - eprintln!("{path}: {e}"); + let img = photocraft_codecs::Image::from_u8(ow as u32, oh as u32, photocraft_codecs::ChannelLayout::Rgb, out).unwrap(); + match photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()) { + Ok(png) => { + if let Err(e) = std::fs::write(path, png) { + eprintln!("{path}: {e}"); + } + } + Err(e) => eprintln!("{path}: {e}"), } } diff --git a/crates/raw/src/look.rs b/crates/raw/src/look.rs index 7da47df1bb..19d7c2e931 100644 --- a/crates/raw/src/look.rs +++ b/crates/raw/src/look.rs @@ -850,9 +850,8 @@ mod tests { let data = crate::testgen::mosaic(&cam, w, [0, 1, 1, 2], 0, 4095); let b = crate::testgen::tiff_ep("NIKON CORPORATION", w, h, &data, [0, 1, 1, 2], 12, vec![]); let mut s = crate::decode(&b, &crate::Limits::default()).unwrap(); - // Repeated synthetic patches can look like a saturation plateau to the - // metadata-free NEF white-level estimator. This fixture has a known - // 12-bit saturation level, matching the JPEG generated below. + // The fixture uses a 12-bit encoding scale. craft-raw's NEF reader takes no WhiteLevel + // tag and reads the brightest flat, noiseless patch as a saturation plateau. s.white = [4095.0; 3]; let to_srgb = color::invert(&color::srgb_to_xyz_d50()).unwrap(); let pro_to_srgb = color::mul(&to_srgb, &color::rgb_to_xyz(color::ROMM, color::D50_XY)); diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index 3b0e71ffa8..1fa6b5ec16 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -97,8 +97,9 @@ impl PhotocraftApp { // A PSD and a magic-detected TIFF both go through the typed IO path: only it carries // `PsdApprovalRequired` (and, for a PSD, the structured damaged flag), so a layered // TIFF's high-memory decision can raise its prompt instead of becoming a terminal - // string. Every other format keeps the shell's import service. - let typed_open = photocraft_io::is_psd(bytes) || photocraft_formats::detect(name, bytes) == Some(photocraft_formats::Format::Tiff); + // string. Every other format keeps the shell's import service. `detect` gets no name: + // given one it falls back to the extension, and a `.tif` name alone is no TIFF. + let typed_open = photocraft_io::is_psd(bytes) || photocraft_formats::detect("", bytes) == Some(photocraft_formats::Format::Tiff); let (mut doc, warnings, damaged) = if typed_open { // Read PSD damage as structured information in the same decode, not by // retrying an error or matching the text of a compatibility warning. A TIFF never diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index 1b51f3aaba..b64e04d94a 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -1,8 +1,8 @@ use super::{ - PhotocraftApp, analysis_ui, brush_panel, brush_picker, camera_raw_ui, canvas, dds_options_ui, dialogs, discard_ui, distort_ui, field_wheel, gpu_canvas, - gpu_status, gradient_ui, i18n, jobs_ui, jpeg_options_ui, kys_import, last_brush, layers_panel_ui, monitor_status, native_menu, notices, paint_mouse, - palette, panels, prefs_ui, preset_panels, rasterize_prompt, screen_picker, shape_stroke_ui, shortcuts, smart_svg_ui, targa_options_ui, text_field_menu, - theme, tiff_options_ui, timeline_ui, titlebar, tool_cursor, tool_memory, transform_tool, type_panels_ui, type_tool, updates_ui, vector_ui, view_cmds, + PhotocraftApp, analysis_ui, brush_panel, brush_picker, camera_raw_ui, canvas, dds_options_ui, dialogs, discard_ui, distort_ui, gpu_canvas, gpu_status, + gradient_ui, i18n, jobs_ui, jpeg_options_ui, kys_import, last_brush, layers_panel_ui, monitor_status, native_menu, notices, paint_mouse, palette, panels, + prefs_ui, preset_panels, rasterize_prompt, screen_picker, shape_stroke_ui, shortcuts, smart_svg_ui, targa_options_ui, text_field_menu, theme, + tiff_options_ui, timeline_ui, titlebar, tool_cursor, tool_memory, transform_tool, type_panels_ui, type_tool, updates_ui, vector_ui, view_cmds, wide_angle_ui, work_area, workspace_ui, }; @@ -252,8 +252,6 @@ impl PhotocraftApp { titlebar::note_os_pointer(self, &ctx); // A text field's right-click menu, before any field is drawn (text_field_menu.rs). text_field_menu::show(&ctx); - // The wheel goes to a focused value field before the canvas or a panel sees it (#5473). - field_wheel::begin_frame(&ctx); // Each painting tool keeps its own brush (#218), so switch the active tool's brush in // before anything this frame reads it (the cursor, the options bar, a stroke). // Preferences ▸ Type ▸ Recent Fonts: a smaller cap (or 0) trims the existing list at diff --git a/crates/ui-egui/src/app/prefs.rs b/crates/ui-egui/src/app/prefs.rs index f1a111f190..8f70519889 100644 --- a/crates/ui-egui/src/app/prefs.rs +++ b/crates/ui-egui/src/app/prefs.rs @@ -1,4 +1,4 @@ -use super::{PhotocraftApp, dock, panel_docking, single_line_drag, text_field_menu, theme, tool_cursor, wheel_nav}; +use super::{PhotocraftApp, dock, field_wheel, panel_docking, single_line_drag, text_field_menu, theme, tool_cursor, wheel_nav}; impl PhotocraftApp { /// Records a picked type family for the font menu's Recent group, capped by @@ -54,6 +54,9 @@ impl PhotocraftApp { Self::install_type_reset_hooks(ctx); ctx.add_plugin(tool_cursor::CursorLifecycle); ctx.add_plugin(single_line_drag::SingleLineDrag::default()); + // The wheel goes to a focused value field before the canvas or a panel sees it (#5473), in + // every window: a floated panel's window has input of its own (#11353). + ctx.add_plugin(field_wheel::FieldWheel); theme::install_fonts(ctx); egui_extras::install_image_loaders(ctx); theme::apply(ctx, kind); diff --git a/crates/ui-egui/src/panels/layer_props_ui.rs b/crates/ui-egui/src/panels/layer_props_ui.rs index 677b332503..2f350a59f5 100644 --- a/crates/ui-egui/src/panels/layer_props_ui.rs +++ b/crates/ui-egui/src/panels/layer_props_ui.rs @@ -416,7 +416,6 @@ mod tests { PhotocraftApp::setup_context(ui.ctx(), crate::theme::ThemeKind::ProMedium); return; } - crate::field_wheel::begin_frame(ui.ctx()); let state = app.session.active().unwrap(); let layer = state.doc.layer(state.active_layer.unwrap()).unwrap().clone(); properties(app, ui, &layer); @@ -474,7 +473,6 @@ mod tests { PhotocraftApp::setup_context(ui.ctx(), crate::theme::ThemeKind::ProMedium); return; } - crate::field_wheel::begin_frame(ui.ctx()); let state = app.session.active().unwrap(); let layer = state.doc.layer(state.active_layer.unwrap()).unwrap().clone(); properties(app, ui, &layer); @@ -530,7 +528,6 @@ mod tests { PhotocraftApp::setup_context(ui.ctx(), crate::theme::ThemeKind::ProMedium); return; } - crate::field_wheel::begin_frame(ui.ctx()); if ui.data(|d| d.get_temp::(hide)).unwrap_or(false) { return; } @@ -592,7 +589,6 @@ mod tests { PhotocraftApp::setup_context(ui.ctx(), crate::theme::ThemeKind::ProMedium); return; } - crate::field_wheel::begin_frame(ui.ctx()); let state = app.session.active().unwrap(); let layer = state.doc.layer(state.active_layer.unwrap()).unwrap().clone(); properties(app, ui, &layer); @@ -641,7 +637,6 @@ mod tests { PhotocraftApp::setup_context(ui.ctx(), crate::theme::ThemeKind::ProMedium); return; } - crate::field_wheel::begin_frame(ui.ctx()); let state = app.session.active().unwrap(); let layer = state.doc.layer(state.active_layer.unwrap()).unwrap().clone(); properties(app, ui, &layer); @@ -693,7 +688,6 @@ mod tests { PhotocraftApp::setup_context(ui.ctx(), crate::theme::ThemeKind::ProMedium); return; } - crate::field_wheel::begin_frame(ui.ctx()); let state = app.session.active().unwrap(); let layer = state.doc.layer(state.active_layer.unwrap()).unwrap().clone(); properties(app, ui, &layer); diff --git a/crates/ui-egui/src/panels/panel_state.rs b/crates/ui-egui/src/panels/panel_state.rs index d384bbfa98..b90dcab826 100644 --- a/crates/ui-egui/src/panels/panel_state.rs +++ b/crates/ui-egui/src/panels/panel_state.rs @@ -1,5 +1,7 @@ // ----------------------------------------------------------------------------- panel state +use std::sync::LazyLock; + /// The persisted [`egui::PanelState`] key for the panel named `salt` in this context's root UI. /// /// egui 0.37 derives a panel's id from its parent [`egui::Ui`]: @@ -12,7 +14,7 @@ pub fn panel_state_id(ctx: &egui::Context, salt: impl egui::AsIdSalt) -> egui::I } /// The panels whose saved sizes moved to a parent-scoped key in 0.37. -const PANEL_STATE_KEYS: &[&str] = &["dock", "title_bar", "options_bar", "status_bar", "toolbar", "rail", "shared-panel-dock"]; +const PANEL_STATE_KEYS: [&str; 7] = ["dock", "title_bar", "options_bar", "status_bar", "toolbar", "rail", "shared-panel-dock"]; /// What the two keys held when this build last looked at a panel, so a later startup can tell /// which one a 0.36 rollback or a 0.37 session wrote last. @@ -27,9 +29,11 @@ fn rect_key(state: egui::containers::panel::PanelState) -> [f32; 4] { [r.min.x, r.min.y, r.max.x, r.max.y] } -fn stamp_id(name: &str) -> egui::Id { - egui::Id::unique(format!("photocraft-panel-state-stamp:{name}")) -} +/// The persisted stamp id of each [`PANEL_STATE_KEYS`] entry, in the same order. Built once because +/// [`remember_panel_state`] reads the stamps every frame. The stamps are saved, so the ids must keep +/// hashing this exact string: a tuple salt hashes differently and would lose them. +static STAMP_IDS: LazyLock<[egui::Id; PANEL_STATE_KEYS.len()]> = + LazyLock::new(|| PANEL_STATE_KEYS.map(|name| egui::Id::unique(format!("photocraft-panel-state-stamp:{name}")))); /// Copy 0.36 `PanelState` entries to their 0.37 parent-scoped keys. /// @@ -45,10 +49,9 @@ pub fn migrate_panel_state(ctx: &egui::Context) { if ctx.data(|d| d.get_temp::(done).unwrap_or(false)) { return; } - for name in PANEL_STATE_KEYS { + for (name, &id) in PANEL_STATE_KEYS.iter().zip(STAMP_IDS.iter()) { let old_id = egui::Id::unique(*name); let new_id = panel_state_id(ctx, *name); - let id = stamp_id(name); let old = PanelState::load(ctx, old_id); let new = PanelState::load(ctx, new_id); let stamp = ctx.data_mut(|d| d.get_persisted::(id)); @@ -84,9 +87,8 @@ pub fn migrate_panel_state(ctx: &egui::Context) { /// old-key values can be recognized. Cheap when nothing changed (no write). pub fn remember_panel_state(ctx: &egui::Context) { use egui::containers::panel::PanelState; - for name in PANEL_STATE_KEYS { + for (name, &id) in PANEL_STATE_KEYS.iter().zip(STAMP_IDS.iter()) { let Some(new) = PanelState::load(ctx, panel_state_id(ctx, *name)) else { continue }; - let id = stamp_id(name); let Some(stamp) = ctx.data_mut(|d| d.get_persisted::(id)) else { continue }; let new_key = rect_key(new); if new_key != stamp.new { @@ -94,3 +96,17 @@ pub fn remember_panel_state(ctx: &egui::Context) { } } } + +#[cfg(test)] +mod tests { + use super::{PANEL_STATE_KEYS, STAMP_IDS}; + + /// The stamps are persisted: the cached ids must be the ones earlier builds saved them under. + #[test] + fn the_cached_stamp_ids_hash_like_the_saved_ones() { + for (name, id) in PANEL_STATE_KEYS.iter().zip(STAMP_IDS.iter()) { + assert_eq!(*id, egui::Id::unique(format!("photocraft-panel-state-stamp:{name}")), "{name}"); + } + assert_eq!(STAMP_IDS[0], egui::Id::unique("photocraft-panel-state-stamp:dock".to_owned())); + } +} diff --git a/crates/ui-egui/src/tools/analysis_ui.rs b/crates/ui-egui/src/tools/analysis_ui.rs index 6da8b1fe5a..eb61716f51 100644 --- a/crates/ui-egui/src/tools/analysis_ui.rs +++ b/crates/ui-egui/src/tools/analysis_ui.rs @@ -706,20 +706,45 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo // the colon (main's captions), so the colon follows the translation. let caption = |ui: &mut egui::Ui, text: &str| crate::panels::opt_label(ui, &format!("{text}:")); // Each caption names its field (the scrub link), so a screen reader reads what is shown. + // A value typed past the range becomes the closest one, and leaving the field opens the + // reference's alert (#11768). + let (marker_name, label_name) = (format!("{}:", tl!("Marker Size")), format!("{}:", tl!("Label Size"))); caption(ui, tl!("Marker Size")); - let a = crate::widgets::value_field_whole(ui, &mut ms, 1.0..=10.0, "", 40.0); + // Read before the fields: they consume the arrow keys and the wheel they step with. + let stepped = + ui.input(|i| i.key_pressed(egui::Key::ArrowUp) || i.key_pressed(egui::Key::ArrowDown)) || crate::field_wheel::focused_field_wheeled(ui.ctx()); + let (marker_slot, label_slot) = + (ui.make_persistent_id(egui::IdSalt::new("count-marker-size")), ui.make_persistent_id(egui::IdSalt::new("count-label-size"))); + drop_decimal_points(ui, marker_slot); + let (a, marker_out) = crate::widgets::value_field_whole_alerting(ui, &marker_name, &mut ms, 1.0..=10.0, "", 40.0); + ui.data_mut(|d| d.insert_temp(marker_slot, a.id)); caption(ui, tl!("Label Size")); - let b = crate::widgets::value_field_whole(ui, &mut ls, 8.0..=72.0, "", 44.0); - // One undo step per scrub (of a field or its caption), as the Gradient tool's Opacity. - let drag = |r: &egui::Response| { - let key = r.id.with("count-size-drag"); - if r.drag_started() { + drop_decimal_points(ui, label_slot); + let (b, label_out) = crate::widgets::value_field_whole_alerting(ui, &label_name, &mut ls, 8.0..=72.0, "", 44.0); + ui.data_mut(|d| d.insert_temp(label_slot, b.id)); + // One undo step per scrub (of a field or its caption), as the Gradient tool's Opacity, + // and per typed entry (each keystroke applies while typing). An arrow or wheel step is + // a step of its own, as before. + let edit = |r: &egui::Response| { + let key = r.id.with("count-size-edit"); + if r.drag_started() || r.gained_focus() { let n = ui.ctx().cumulative_pass_nr(); ui.data_mut(|d| d.insert_temp(key, n)); } - if r.changed() && r.dragged() { ui.data(|d| d.get_temp::(key)).map(|n| format!("count-size:{}:{n}", key.value())) } else { None } + let typed = (r.has_focus() || r.lost_focus()) && !stepped; + if r.changed() && (r.dragged() || typed) { + ui.data(|d| d.get_temp::(key)).map(|n| format!("count-size:{}:{n}", key.value())) + } else { + None + } }; - let coalesce = drag(&a).or(drag(&b)); + let coalesce = edit(&a).or(edit(&b)); + if marker_out { + open_alert_once(app, MARKER_SIZE_RANGE_ALERT); + } + if label_out { + open_alert_once(app, LABEL_SIZE_RANGE_ALERT); + } if (a.changed() || b.changed()) && group.is_some() { let mut p = count_size_params(ms, ls); if let Some(k) = coalesce { @@ -777,6 +802,36 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo // ------------------------------------------------------------------ panels and dialogs +/// The reference's alerts for a Marker Size or Label Size typed out of range (#11768). +pub(crate) const MARKER_SIZE_RANGE_ALERT: &str = "An integer between 1 and 10 is required. Closest value inserted."; +pub(crate) const LABEL_SIZE_RANGE_ALERT: &str = "An integer between 8 and 72 is required. Closest value inserted."; + +/// Opens the alert with `message` (English, translated here) unless it is already up. +fn open_alert_once(app: &mut PhotocraftApp, message: &str) { + let message = tl!(message).to_owned(); + let shown = app.ui.dialogs.iter().any(|d| d.kind == DialogKind::Error && d.fields.get("message").and_then(|m| m.as_str()) == Some(message.as_str())); + if !shown { + app.ui.open_dialog(DialogKind::Error, json!({ "message": message }).as_object().cloned().unwrap_or_default()); + } +} + +/// The Count tool's size fields take digits only, as the reference's do (#11768): a `.` or `,` +/// typed, pasted or committed by an IME into the field whose id was saved under `slot` last frame +/// is dropped, so "2.6" reads as 26. An IME commit left empty stays: it ends the composition. +fn drop_decimal_points(ui: &mut egui::Ui, slot: egui::Id) { + let focused = ui.data(|d| d.get_temp::(slot)).is_some_and(|id| ui.memory(|m| m.has_focus(id))); + if focused { + ui.input_mut(|i| { + for e in &mut i.events { + if let egui::Event::Text(t) | egui::Event::Paste(t) | egui::Event::Ime(egui::ImeEvent::Commit(t)) = e { + t.retain(|c| c != '.' && c != ','); + } + } + i.events.retain(|e| !matches!(e, egui::Event::Text(t) | egui::Event::Paste(t) if t.is_empty())); + }); + } +} + /// `count.setGroup` params for the options bar's Marker Size and Label Size fields, sent as JSON /// integers (the fields edit `f32`s; `8.0` is a float on the wire). fn count_size_params(marker: f32, label: f32) -> Value { @@ -1321,3 +1376,7 @@ mod analysis_ruler_escape_tests; #[cfg(test)] #[path = "count_options_bar_tests.rs"] mod count_options_bar_tests; + +#[cfg(test)] +#[path = "count_size_alert_tests.rs"] +mod count_size_alert_tests; diff --git a/crates/ui-egui/src/tools/count_size_alert_tests.rs b/crates/ui-egui/src/tools/count_size_alert_tests.rs new file mode 100644 index 0000000000..a9b134bc28 --- /dev/null +++ b/crates/ui-egui/src/tools/count_size_alert_tests.rs @@ -0,0 +1,181 @@ +//! #11768: the Count tool's Marker Size (1..10) and Label Size (8..72) take digits only; a value +//! typed past the range becomes the closest one and, once the field is left, the reference's alert +//! with OK says so. One typed entry is one History step. + +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; + +use super::{LABEL_SIZE_RANGE_ALERT, MARKER_SIZE_RANGE_ALERT}; +use crate::PhotocraftApp; +use crate::state::{DialogKind, Tool}; + +const MARKER: &str = "Marker Size:"; +const LABEL: &str = "Label Size:"; + +/// The whole app on a 100 × 100 document with the Count tool and one count group. +fn app_harness() -> Harness<'static, PhotocraftApp> { + let mut h = Harness::builder().with_size(vec2(1600.0, 900.0)).with_step_dt(1.0 / 60.0).build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("count.add", json!({"x": 10, "y": 10})).unwrap(); + app.ui.tool = Tool::Count; + app + }); + h.run_steps(5); + h +} + +/// Types `text` into the field named `field`, then Tabs out of it. +fn type_into(h: &mut Harness<'static, PhotocraftApp>, field: &str, text: &str) { + h.query_all_by_role(egui::accesskit::Role::SpinButton) + .find(|n| n.accesskit_node().label().as_deref() == Some(field)) + .unwrap_or_else(|| panic!("the {field} field")) + .click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.event(egui::Event::Text(text.into())); + h.run_steps(1); + h.key_press(egui::Key::Tab); + h.run_steps(3); +} + +fn alerts(h: &Harness<'static, PhotocraftApp>) -> Vec { + h.state() + .ui + .dialogs + .iter() + .filter(|d| d.kind == DialogKind::Error) + .filter_map(|d| d.fields.get("message").and_then(|m| m.as_str()).map(str::to_owned)) + .collect() +} + +/// The current group's (Marker Size, Label Size). +fn sizes(h: &Harness<'static, PhotocraftApp>) -> (u32, u32) { + let g = &h.state().session.active().unwrap().doc.measurement.count_groups[0]; + (g.marker_size, g.label_size) +} + +fn steps(h: &Harness<'static, PhotocraftApp>) -> usize { + h.state().session.active().unwrap().history.past_len() +} + +#[test] +fn an_out_of_range_size_alerts_and_takes_the_closest_value() { + let cases = [(MARKER, "0", 1, MARKER_SIZE_RANGE_ALERT), (MARKER, "-4", 1, MARKER_SIZE_RANGE_ALERT), (MARKER, "20", 10, MARKER_SIZE_RANGE_ALERT)] + .into_iter() + .chain([(LABEL, "4", 8, LABEL_SIZE_RANGE_ALERT), (LABEL, "100", 72, LABEL_SIZE_RANGE_ALERT)]); + for (field, typed, want, message) in cases { + let mut h = app_harness(); + type_into(&mut h, field, typed); + let got = if field == MARKER { sizes(&h).0 } else { sizes(&h).1 }; + assert_eq!(got, want, "{field} {typed}"); + assert_eq!(alerts(&h), vec![message.to_owned()], "{field} {typed}: one alert"); + h.get_by_label("OK").click(); + h.run_steps(4); + assert!(alerts(&h).is_empty(), "{field} {typed}: OK closes the alert"); + let kept = if field == MARKER { sizes(&h).0 } else { sizes(&h).1 }; + assert_eq!(kept, want, "{field} {typed}: the closest value stays"); + } +} + +#[test] +fn the_size_fields_take_digits_only() { + let mut h = app_harness(); + type_into(&mut h, MARKER, "2.6"); + assert_eq!(sizes(&h).0, 10, "2.6 reads as 26, which ends as 10"); + assert_eq!(alerts(&h), vec![MARKER_SIZE_RANGE_ALERT.to_owned()]); + h.get_by_label("OK").click(); + h.run_steps(4); + type_into(&mut h, LABEL, "1,2"); + assert_eq!(sizes(&h).1, 12, "a comma is no decimal point either"); + assert!(alerts(&h).is_empty(), "12 is in range"); +} + +#[test] +fn an_ime_commit_takes_digits_only_too() { + let mut h = app_harness(); + h.query_all_by_role(egui::accesskit::Role::SpinButton) + .find(|n| n.accesskit_node().label().as_deref() == Some(MARKER)) + .expect("the Marker Size field") + .click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.event(egui::Event::Ime(egui::ImeEvent::Commit("2.6".into()))); + h.run_steps(1); + h.key_press(egui::Key::Tab); + h.run_steps(3); + assert_eq!(sizes(&h).0, 10, "a committed 2.6 reads as 26, which ends as 10, not 3"); + assert_eq!(alerts(&h), vec![MARKER_SIZE_RANGE_ALERT.to_owned()]); +} + +#[test] +fn in_range_sizes_are_set_without_an_alert() { + let mut h = app_harness(); + type_into(&mut h, MARKER, "7"); + type_into(&mut h, LABEL, "30"); + assert_eq!(sizes(&h), (7, 30)); + assert!(alerts(&h).is_empty()); + type_into(&mut h, MARKER, "10"); + type_into(&mut h, LABEL, "8"); + assert_eq!(sizes(&h), (10, 8), "the ends of the ranges are in them"); + assert!(alerts(&h).is_empty()); +} + +#[test] +fn a_typed_size_is_one_history_step() { + let mut h = app_harness(); + let before = steps(&h); + // Key by key, so each keystroke applies on its own: 2, then 20 (clamped to 10). + h.query_all_by_role(egui::accesskit::Role::SpinButton) + .find(|n| n.accesskit_node().label().as_deref() == Some(MARKER)) + .expect("the Marker Size field") + .click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + for c in ["2", "0"] { + h.event(egui::Event::Text(c.into())); + h.run_steps(2); + } + h.key_press(egui::Key::Tab); + h.run_steps(3); + assert_eq!(sizes(&h).0, 10); + assert_eq!(steps(&h), before + 1, "one entry, one Undo step"); + h.get_by_label("OK").click(); + h.run_steps(4); + type_into(&mut h, MARKER, "4"); + assert_eq!(steps(&h), before + 2, "a second entry is a step of its own"); +} + +#[test] +fn the_alert_shows_once_not_once_per_frame() { + let mut h = app_harness(); + type_into(&mut h, LABEL, "100"); + h.run_steps(10); + assert_eq!(alerts(&h).len(), 1); +} + +#[test] +fn an_arrow_step_after_typing_is_a_step_of_its_own_and_never_alerts() { + let mut h = app_harness(); + h.query_all_by_role(egui::accesskit::Role::SpinButton) + .find(|n| n.accesskit_node().label().as_deref() == Some(LABEL)) + .expect("the Label Size field") + .click(); + h.run_steps(1); + let before = steps(&h); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.event(egui::Event::Text("30".into())); + h.run_steps(2); + assert_eq!(steps(&h), before + 1, "the typed entry"); + // Still in the field: an arrow step is not part of the typed entry. + h.key_press(egui::Key::ArrowUp); + h.run_steps(2); + h.key_press(egui::Key::Tab); + h.run_steps(3); + assert_eq!(sizes(&h).1, 31); + assert_eq!(steps(&h), before + 2, "the arrow step is one Undo step of its own, as before"); + assert!(alerts(&h).is_empty()); +} diff --git a/crates/ui-egui/src/tools/type_tool/font_picker_tests.rs b/crates/ui-egui/src/tools/type_tool/font_picker_tests.rs index 7144b2dcfc..881194a040 100644 --- a/crates/ui-egui/src/tools/type_tool/font_picker_tests.rs +++ b/crates/ui-egui/src/tools/type_tool/font_picker_tests.rs @@ -41,16 +41,21 @@ fn harness_sized(preview: FontPreview, recents: Vec, size: egui::Vec2) - let mut families: Vec = (0..60).map(|i| format!("Family {i:02}")).collect(); families.push("Zeta Sans".into()); let state = State { current: "Family 00".into(), families, button: egui::Id::NULL, popup: egui::Id::NULL, preview, recents }; - let mut h = Harness::builder().with_size(size).with_max_steps(SETTLE_STEPS).build_ui_state( - |ui, s: &mut State| { - s.button = ui.make_persistent_id(egui::IdSalt::new("type-font")); - s.popup = s.button.with("popup"); - let fams = s.families.clone(); - let recents = s.recents.clone(); - font_picker_in(ui, &mut s.current, 170.0, &fams, s.preview, &recents); - }, - state, - ); + // As the app does: the wheel is a gesture over the field or past it (#11353). + let mut h = Harness::builder() + .with_size(size) + .with_max_steps(SETTLE_STEPS) + .with_context_setup(|ctx| ctx.add_plugin(crate::field_wheel::FieldWheel)) + .build_ui_state( + |ui, s: &mut State| { + s.button = ui.make_persistent_id(egui::IdSalt::new("type-font")); + s.popup = s.button.with("popup"); + let fams = s.families.clone(); + let recents = s.recents.clone(); + font_picker_in(ui, &mut s.current, 170.0, &fams, s.preview, &recents); + }, + state, + ); h.run(); h } @@ -1264,6 +1269,105 @@ fn wheel_over_the_closed_font_button_steps_through_the_families() { assert_eq!(h.state().current, "Family 00", "stops at the first family"); } +/// The closed font field (on "Family 03" of ten) 100 pt down a scroll area 200 pt tall over a large +/// filler, as in a panel: (the family, the panel's vertical offset). +fn font_field_in_a_panel() -> Harness<'static, (String, f32)> { + let families: Vec = (0..10).map(|i| format!("Family {i:02}")).collect(); + let mut h = Harness::builder().with_size(vec2(400.0, 300.0)).with_step_dt(1.0 / 30.0).build_ui_state( + move |ui, s: &mut (String, f32)| { + crate::field_wheel::begin_frame(ui.ctx()); + let out = egui::ScrollArea::vertical().max_height(200.0).show(ui, |ui| { + ui.add_space(100.0); + font_picker_in(ui, &mut s.0, 170.0, &families, FontPreview::Medium, &[]); + ui.allocate_space(vec2(300.0, 1000.0)); + }); + s.1 = out.state.clamped_offset().y; + }, + ("Family 03".to_string(), 0.0), + ); + h.run(); + h +} + +/// #11353: a trackpad scrolling a panel past the closed font field keeps scrolling the panel and +/// leaves the family alone. +#[test] +fn a_gesture_that_starts_over_the_panel_keeps_scrolling_it_over_the_font_field() { + let mut h = font_field_in_a_panel(); + let field = |h: &Harness<'static, (String, f32)>| h.query_all_by_role(Role::TextInput).next().unwrap().rect(); + h.hover_at(field(&h).center() + vec2(0.0, 50.0)); + h.run_steps(1); + let down = || egui::Event::MouseWheel { + source: egui::MouseWheelSource::Unknown, + unit: egui::MouseWheelUnit::Point, + delta: vec2(0.0, -12.0), + phase: egui::TouchPhase::Move, + modifiers: Modifiers::NONE, + }; + h.event(down()); + h.run_steps(1); + // Still the same gesture as the pointer reaches the field, a few notches' worth. + for _ in 0..6 { + let over = field(&h); + assert!(over.top() > 0.0, "the field is still in view"); + h.hover_at(over.center()); + h.event(down()); + h.run_steps(1); + } + assert_eq!(h.state().0, "Family 03", "the field passing under the pointer is not stepped"); + assert!(h.state().1 > 12.0, "the panel kept scrolling"); +} + +/// #11353: a trackpad gesture that starts over the font field scrolls the panel and leaves the +/// family alone. +#[test] +fn a_trackpad_gesture_that_starts_over_the_font_field_scrolls_the_panel() { + let mut h = font_field_in_a_panel(); + let over = h.query_all_by_role(Role::TextInput).next().unwrap().rect().center(); + h.hover_at(over); + h.run_steps(1); + for _ in 0..4 { + h.event(egui::Event::MouseWheel { + source: egui::MouseWheelSource::Trackpad, + unit: egui::MouseWheelUnit::Point, + delta: vec2(0.0, -12.0), + phase: egui::TouchPhase::Move, + modifiers: Modifiers::NONE, + }); + h.run_steps(1); + } + assert_eq!(h.state().0, "Family 03", "the family is not stepped"); + assert!(h.state().1 > 0.0, "the panel scrolled"); +} + +/// #11353: a gesture that steps the font field, then wheels on with the pointer off it, is the +/// panel's from then on: coming back over the field in the same gesture doesn't step it again. +#[test] +fn a_gesture_that_wheels_off_the_font_field_does_not_step_it_on_coming_back() { + let mut h = font_field_in_a_panel(); + let over = h.query_all_by_role(Role::TextInput).next().unwrap().rect().center(); + h.hover_at(over); + h.run_steps(1); + // Up, so the panel (already at the top) doesn't move the field. + let up = || egui::Event::MouseWheel { + source: egui::MouseWheelSource::Unknown, + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, 1.0), + phase: egui::TouchPhase::Move, + modifiers: Modifiers::NONE, + }; + h.event(up()); + h.run_steps(1); + assert_eq!(h.state().0, "Family 02", "the start of the gesture steps it"); + h.hover_at(over + vec2(0.0, 50.0)); + h.event(up()); + h.run_steps(1); + h.hover_at(over); + h.event(up()); + h.run_steps(4); + assert_eq!(h.state().0, "Family 02", "the field was stepped once, by the start of the gesture"); +} + #[test] fn wheel_over_the_closed_button_keeps_a_stable_order_with_recents() { let mut h = harness_with_recents(FontPreview::Medium, vec![]); diff --git a/crates/ui-egui/src/tools/type_tool/fonts.rs b/crates/ui-egui/src/tools/type_tool/fonts.rs index 022b978f8b..2b1091ffa7 100644 --- a/crates/ui-egui/src/tools/type_tool/fonts.rs +++ b/crates/ui-egui/src/tools/type_tool/fonts.rs @@ -796,11 +796,9 @@ pub(crate) fn family_picker_in( } if !open && !escape && ui.is_enabled() { let notches = if had_focus { f32::from(u8::from(up)) - f32::from(u8::from(down)) } else { 0.0 }; - let hovered = input.hovered() || arrow.hovered(); - if hovered { - ui.input_mut(|i| i.smooth_scroll_delta = egui::Vec2::ZERO); - } - let notches = notches + crate::widgets::wheel_notches_of(ui, field.with("family-wheel"), hovered, 1.0); + // A gesture that started over the field, not one scrolling the panel past it (#11353). + let wheel = crate::field_wheel::hover_notches(ui, field.with("family-wheel"), rect, 1.0); + let notches = notches + wheel; // Closed-field navigation stays alphabetical, independent of recent picks (#3350, #7407). let (rows, _) = font_menu_rows(families, labels, "", &[]); if let Some(i) = rows.iter().position(|(f, _)| *f == current) diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index f41c064d26..5e22305dce 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -66,8 +66,8 @@ pub(crate) use scrub::scrub_label_within; pub use scrub::{scrub_label, scrub_option_icon, scrub_option_label}; #[cfg(test)] use slider::DOUBLE_CLICK_S; +pub(crate) use slider::count_notches; pub use slider::{RowGestures, row_label, second_click, slider, slider_line, slider_row, slider_row_prec, slider_row_with}; -pub(crate) use slider::{count_notches, wheel_notches_of}; #[cfg(test)] pub(crate) use slider::{curve_fraction, curve_value}; pub use text_field::{ diff --git a/crates/ui-egui/src/widgets/dropdown.rs b/crates/ui-egui/src/widgets/dropdown.rs index 96052a4327..8f8a6c5ba4 100644 --- a/crates/ui-egui/src/widgets/dropdown.rs +++ b/crates/ui-egui/src/widgets/dropdown.rs @@ -1,6 +1,5 @@ use super::panel::chevron_icon; use super::scrub::take_label_scrub_name; -use super::slider::wheel_notches_of; use super::{Align2, Pos2, Rect, Response, Sense, Stroke, StrokeKind, Tokens, Ui, Vec2, pos2, type_ahead, vec2}; /// A compact labelled dropdown in the studio style. @@ -45,8 +44,9 @@ pub fn dropdown_hovered(ui: &mut Ui, id: &str, name: &str, /// [`dropdown_hovered`] whose value also steps with the wheel over its button or open list: down /// picks the next option, up the previous one, one per notch (Shift too), stopping at the ends -/// (Photoshop's Layers panel blend modes, #1747). The wheel then scrolls neither the list, which -/// follows the value instead, nor what the dropdown is in. Returns every option chosen this frame +/// (Photoshop's Layers panel blend modes, #1747), for a wheel gesture that starts over either +/// (#11353). The wheel then scrolls neither the list, which follows the value instead, nor what +/// the dropdown is in. Returns every option chosen this frame /// in order (one per notch; the last is `current`) and the option under the pointer in the open /// list, none while the pointer rests where the wheel last stepped. pub fn dropdown_wheel_hovered( @@ -131,10 +131,12 @@ fn dropdown_with( reveal = true; keyed = true; } - // Over the open list the wheel steps the value too, instead of scrolling the list. + // Over the open list the wheel steps the value too, instead of scrolling the list: a + // gesture that started over the list or the button, not one scrolling the panel that + // carried the list under the pointer (#11353). over_list = wheel && ui.rect_contains_pointer(ui.clip_rect()); if over_list { - let stepped = wheel_steps(ui, wheel_id, true, current, options, enabled); + let stepped = wheel_steps(crate::field_wheel::hover_notches(ui, wheel_id, ui.clip_rect(), 1.0), current, options, enabled); wheeled = !stepped.is_empty(); reveal |= wheeled; chosen.extend(stepped); @@ -189,7 +191,10 @@ fn dropdown_with( chosen.push(current.clone()); } if wheel && !over_list { - let stepped = wheel_steps(ui, wheel_id, response.hovered(), current, options, enabled); + // A gesture that started over the button or the open list, not one scrolling the panel + // past it (#11353). Asked off them too, so a gesture that leaves them is the panel's. + let notches = crate::field_wheel::hover_notches(ui, wheel_id, response.rect, 1.0); + let stepped = wheel_steps(notches, current, options, enabled); wheeled = !stepped.is_empty(); if wheeled && craft_ui::ComboBox::is_open(ui.ctx(), response.id) { ui.data_mut(|d| d.insert_temp(reveal_id, true)); @@ -237,15 +242,10 @@ fn wheel_rests(ui: &Ui, id: egui::Id, wheeled: bool) -> bool { rests } -/// The options the wheel over dropdown `id` (while `hovered`) steps `current` through this frame, -/// one per notch, in order; the last is the new `current`. A notch goes to the next option -/// `enabled` accepts, so a greyed one costs no notch. While the pointer is over it the wheel -/// scrolls nothing else. -fn wheel_steps(ui: &mut Ui, id: egui::Id, hovered: bool, current: &mut T, options: &[(T, &str)], enabled: &dyn Fn(&T) -> bool) -> Vec { - if hovered { - ui.input_mut(|i| i.smooth_scroll_delta = Vec2::ZERO); - } - let notches = wheel_notches_of(ui, id, hovered, 1.0); +/// The options `notches` wheel notches step `current` through, one per notch, in order; the last +/// is the new `current`. A notch goes to the next option `enabled` accepts, so a greyed one costs +/// no notch. +fn wheel_steps(notches: f32, current: &mut T, options: &[(T, &str)], enabled: &dyn Fn(&T) -> bool) -> Vec { let Some(mut index) = options.iter().position(|(v, _)| v == current) else { return Vec::new() }; let mut chosen = Vec::new(); // Down (negative) is the next option. No more steps than there are options. diff --git a/crates/ui-egui/src/widgets/field_wheel.rs b/crates/ui-egui/src/widgets/field_wheel.rs index 21d37e1bd7..1d0c188b98 100644 --- a/crates/ui-egui/src/widgets/field_wheel.rs +++ b/crates/ui-egui/src/widgets/field_wheel.rs @@ -7,8 +7,16 @@ //! - Over a field without focus, the wheel steps it too, but only a gesture that starts over it: //! a panel being scrolled keeps scrolling when a field passes under the pointer. A gesture that //! leaves the field is the view's from then on. +//! - Dropdowns, sliders and the font list that the wheel steps follow the same rule +//! ([`hover_notches`]). +//! - A trackpad (macOS says when it is one; other systems don't) steps only a field with focus: +//! over anything else its gesture scrolls the panel, wherever it starts (#11353). +//! - Each window keeps its own record (a panel floated into a window of its own has input of its +//! own), and its own fractions of a notch; [`FieldWheel`] starts every window's pass with +//! [`begin_frame`]. The app installs it; a widget drawn without the app's setup installs it the +//! first time it asks for the wheel, so it steps there as it always has. -use egui::{Context, Event, Id, MouseWheelUnit, Rect, Ui, Vec2}; +use egui::{Context, Event, Id, MouseWheelSource, MouseWheelUnit, Rect, Ui, Vec2}; /// Wheel events this close together (seconds) are one gesture. pub(crate) const GESTURE_GAP: f64 = 0.3; @@ -29,33 +37,56 @@ struct Gesture { owner: Owner, } -fn gesture_id() -> Id { - Id::unique("pc-field-wheel-gesture") +// Each window (egui viewport) has its own input, so its own records: a panel floated into a +// window of its own follows the gestures made there, not the main window's. + +fn gesture_id(ctx: &Context) -> Id { + Id::unique("pc-field-wheel-gesture").with(ctx.viewport_id()) } -fn focused_id() -> Id { - Id::unique("pc-field-wheel-focused") +fn focused_id(ctx: &Context) -> Id { + Id::unique("pc-field-wheel-focused").with(ctx.viewport_id()) } -fn taken_id() -> Id { - Id::unique("pc-field-wheel-taken") +fn taken_id(ctx: &Context) -> Id { + Id::unique("pc-field-wheel-taken").with(ctx.viewport_id()) +} + +fn pass_id(ctx: &Context) -> Id { + Id::unique("pc-field-wheel-pass").with(ctx.viewport_id()) } /// A wheel event a field takes: plain or Shift, not the view's Alt or Ctrl/Cmd zoom, nor a plain /// sideways scroll (a trackpad swipe pans the view; Shift+wheel can arrive sideways). An event -/// with no delta at all counts: macOS starts a trackpad gesture with one, and it is what lets a -/// field under the pointer claim the gesture. +/// with no delta at all counts: a gesture can start with one, and it is what lets a field under +/// the pointer claim the gesture. fn for_field(e: &Event) -> bool { matches!(e, Event::MouseWheel { delta, modifiers, .. } if (delta.y != 0.0 || delta.x == 0.0 || modifiers.shift) && !modifiers.alt && !modifiers.ctrl && !modifiers.command && !modifiers.mac_cmd) } +/// Fingers on a trackpad or the glide they leave, where the system says so (macOS): they scroll +/// what is under the pointer, and step only a field with focus (#11353). A system that doesn't +/// say counts as a wheel. +fn from_fingers(e: &Event) -> bool { + matches!(e, Event::MouseWheel { source: MouseWheelSource::Trackpad | MouseWheelSource::Momentum, .. }) +} + /// Before this frame's UI is laid out: hand the wheel to the focused value field, if any, and -/// follow which gesture the wheel is in. +/// follow which gesture the wheel is in. The app runs it through [`FieldWheel`]. Once a pass: +/// a second call in the same pass does nothing, since running again would drop the wheel the +/// first kept for a focused field and count a new gesture as one that no field took. pub fn begin_frame(ctx: &Context) { - ctx.data_mut(|d| d.remove::>(taken_id())); + // (outside the closures below: the viewport id is read under the context's lock) + let (gesture_key, taken_key, pass_key, pass) = (gesture_id(ctx), taken_id(ctx), pass_id(ctx), ctx.cumulative_pass_nr()); + if ctx.data(|d| d.get_temp::(pass_key)) == Some(pass) { + return; + } + ctx.data_mut(|d| d.insert_temp(pass_key, pass)); + ctx.data_mut(|d| d.remove::>(taken_key)); // (the field's widget id, its slot id): focus is the widget's, a gesture the slot's. - let focused = ctx.data(|d| d.get_temp::<(Id, Id)>(focused_id())).filter(|(id, _)| ctx.memory(|m| m.has_focus(*id))); + let focused_key = focused_id(ctx); + let focused = ctx.data(|d| d.get_temp::<(Id, Id)>(focused_key)).filter(|(id, _)| ctx.memory(|m| m.has_focus(*id))); let (now, wheel) = ctx.input(|i| (i.time, i.events.iter().any(|e| matches!(e, Event::MouseWheel { .. })))); if let Some((_, field)) = focused { let (taken, view_wheel): (Vec, bool) = ctx.input_mut(|i| { @@ -66,14 +97,14 @@ pub fn begin_frame(ctx: &Context) { if wheel { // The latest wheel is the view's when any of it was left to the view (Alt, Ctrl/Cmd). let owner = if view_wheel { Owner::Elsewhere } else { Owner::Field(field) }; - ctx.data_mut(|d| d.insert_temp(gesture_id(), Gesture { last: now, owner })); + ctx.data_mut(|d| d.insert_temp(gesture_key, Gesture { last: now, owner })); } if !taken.is_empty() { - ctx.data_mut(|d| d.insert_temp(taken_id(), taken)); + ctx.data_mut(|d| d.insert_temp(taken_key, taken)); } // egui spreads each notch over a few frames: the tail of the field's own notches scrolls // nothing, while the view's keeps all of its own. - if ctx.data(|d| d.get_temp::(gesture_id())).is_some_and(|g| g.owner == Owner::Field(field)) { + if ctx.data(|d| d.get_temp::(gesture_key)).is_some_and(|g| g.owner == Owner::Field(field)) { ctx.input_mut(|i| i.smooth_scroll_delta = Vec2::ZERO); } return; @@ -81,7 +112,7 @@ pub fn begin_frame(ctx: &Context) { if !wheel { return; } - let gesture = ctx.data(|d| d.get_temp::(gesture_id())); + let gesture = ctx.data(|d| d.get_temp::(gesture_key)); let owner = match gesture { Some(g) if now - g.last <= GESTURE_GAP => match g.owner { // No field took it when it started. @@ -90,72 +121,127 @@ pub fn begin_frame(ctx: &Context) { }, _ => Owner::New, }; - ctx.data_mut(|d| d.insert_temp(gesture_id(), Gesture { last: now, owner })); + ctx.data_mut(|d| d.insert_temp(gesture_key, Gesture { last: now, owner })); +} + +/// Runs [`begin_frame`] at the start of every pass of every window (egui viewport), the main +/// window's and each floated panel's, before anything in it is laid out. +pub(crate) struct FieldWheel; + +impl egui::plugin::Plugin for FieldWheel { + fn debug_name(&self) -> &'static str { + "PhotoCraft field wheel" + } + + fn on_begin_pass(&mut self, ui: &mut Ui) { + begin_frame(ui.ctx()); + } +} + +/// Install [`FieldWheel`] where it isn't yet: a widget drawn without the app's setup (another +/// app, a test) steps with the wheel as it did before the wheel followed gestures. Its hook +/// starts the next pass; this one, already under way, gets [`begin_frame`] now. +fn install(ctx: &Context) { + if ctx.plugin_opt::().is_none() { + ctx.add_plugin(FieldWheel); + begin_frame(ctx); + } } /// Whether a wheel gesture stepping a value field is still running: its last notch came less than /// [`GESTURE_GAP`] ago. A field that applies each value as a new edit holds the wheeled value until /// this turns false, so a burst of notches is one edit (#9898). pub fn field_gesture_running(ctx: &Context) -> bool { - let now = ctx.input(|i| i.time); - ctx.data(|d| d.get_temp::(gesture_id())).is_some_and(|g| matches!(g.owner, Owner::Field(_)) && now - g.last <= GESTURE_GAP) + // This window's gesture; the key is read outside the closure, as in `begin_frame`. + let (now, gesture_key) = (ctx.input(|i| i.time), gesture_id(ctx)); + ctx.data(|d| d.get_temp::(gesture_key)).is_some_and(|g| matches!(g.owner, Owner::Field(_)) && now - g.last <= GESTURE_GAP) } /// Whether [`begin_frame`] handed wheel notches to the focused value field this frame: they step /// it as the arrow keys do, though the frame's scroll delta no longer shows them. pub(crate) fn focused_field_wheeled(ctx: &Context) -> bool { - ctx.data(|d| d.get_temp::>(taken_id())).is_some_and(|e| !e.is_empty()) + let taken_key = taken_id(ctx); + ctx.data(|d| d.get_temp::>(taken_key)).is_some_and(|e| !e.is_empty()) } /// Record that value field `id` (whose slot is `field`, as given to [`notches`]) has keyboard /// focus this frame, so the wheel is its next frame. pub fn set_focused(ctx: &Context, id: Id, field: Id) { - ctx.data_mut(|d| d.insert_temp(focused_id(), (id, field))); + let key = focused_id(ctx); + ctx.data_mut(|d| d.insert_temp(key, (id, field))); } /// Wheel notches for the value field `field` in `rect` this frame (up positive, Shift ×10): /// all of the wheel while it is `focused`, else a gesture that started with the pointer over it. pub fn notches(ui: &Ui, field: Id, focused: bool, rect: Rect) -> f32 { + install(ui.ctx()); let events: Vec = if focused { - ui.data_mut(|d| d.remove_temp::>(taken_id())).unwrap_or_default() + let taken_key = taken_id(ui.ctx()); + ui.data_mut(|d| d.remove_temp::>(taken_key)).unwrap_or_default() } else { - if !ui.is_enabled() { - return 0.0; - } - let Some(mut g) = ui.data(|d| d.get_temp::(gesture_id())) else { return 0.0 }; - let (events, wheel): (Vec, bool) = - ui.input(|i| (i.events.iter().filter(|e| for_field(e)).cloned().collect(), i.events.iter().any(|e| matches!(e, Event::MouseWheel { .. })))); - // Wheel the field doesn't take (a sideways swipe after a zero-delta start), or any wheel - // with the pointer off the field, hands the rest of the gesture to the view: coming back - // over the field in the same gesture doesn't step it. - if g.owner == Owner::Field(field) && wheel && (events.is_empty() || !ui.rect_contains_pointer(rect)) { - g.owner = Owner::Elsewhere; - ui.data_mut(|d| d.insert_temp(gesture_id(), g)); - return 0.0; - } - if !ui.rect_contains_pointer(rect) { - return 0.0; - } - match g.owner { - Owner::New if !events.is_empty() => { - g.owner = Owner::Field(field); - ui.data_mut(|d| d.insert_temp(gesture_id(), g)); - } - Owner::Field(id) if id == field => {} - _ => return 0.0, - } - // Nothing under the field scrolls with the wheel that steps it, smoothed tail included. - ui.ctx().input_mut(|i| i.smooth_scroll_delta = Vec2::ZERO); - events + hovered_events(ui, field, rect, for_field) }; - let wheel: Vec<(MouseWheelUnit, Vec2, bool)> = events + crate::widgets::count_notches(ui, field.with("wheel-acc"), &wheel_of(&events), 10.0) +} + +/// Wheel notches for another control the wheel steps while the pointer is over it (a dropdown +/// and its open list, a slider, the font field), `id` naming it and `rect` its area, a notch with +/// Shift counting `shift_notches`: the same rule as a value field without focus, so a panel being +/// scrolled keeps scrolling when the control passes under the pointer (#11353). Ask every frame +/// the control is shown, the pointer over it or not, as [`notches`] is: a gesture that wheels on +/// off the control is the view's from then on. Unlike a value field, it takes the wheel with any +/// modifier (Photoshop's dialog sliders step one a notch with Ctrl or Alt). +pub fn hover_notches(ui: &Ui, id: Id, rect: Rect, shift_notches: f32) -> f32 { + install(ui.ctx()); + let events = hovered_events(ui, id, rect, |e| matches!(e, Event::MouseWheel { .. })); + crate::widgets::count_notches(ui, id.with("wheel-acc"), &wheel_of(&events), shift_notches) +} + +/// This frame's wheel events that `takes` for control `field` in `rect` without keyboard focus: +/// those of a gesture that started with the pointer over it, none otherwise, and never a +/// trackpad's. +fn hovered_events(ui: &Ui, field: Id, rect: Rect, takes: fn(&Event) -> bool) -> Vec { + if !ui.is_enabled() { + return Vec::new(); + } + let gesture_key = gesture_id(ui.ctx()); + let Some(mut g) = ui.data(|d| d.get_temp::(gesture_key)) else { return Vec::new() }; + let (events, wheel): (Vec, bool) = ui.input(|i| { + (i.events.iter().filter(|e| takes(e) && !from_fingers(e)).cloned().collect(), i.events.iter().any(|e| matches!(e, Event::MouseWheel { .. }))) + }); + // Wheel the field doesn't take (a sideways swipe after a zero-delta start), or any wheel + // with the pointer off the field, hands the rest of the gesture to the view: coming back + // over the field in the same gesture doesn't step it. + if g.owner == Owner::Field(field) && wheel && (events.is_empty() || !ui.rect_contains_pointer(rect)) { + g.owner = Owner::Elsewhere; + ui.data_mut(|d| d.insert_temp(gesture_key, g)); + return Vec::new(); + } + if !ui.rect_contains_pointer(rect) { + return Vec::new(); + } + match g.owner { + Owner::New if !events.is_empty() => { + g.owner = Owner::Field(field); + ui.data_mut(|d| d.insert_temp(gesture_key, g)); + } + Owner::Field(id) if id == field => {} + _ => return Vec::new(), + } + // Nothing under the field scrolls with the wheel that steps it, smoothed tail included. + ui.ctx().input_mut(|i| i.smooth_scroll_delta = Vec2::ZERO); + events +} + +/// The wheel in `events`: (unit, delta, Shift held). +fn wheel_of(events: &[Event]) -> Vec<(MouseWheelUnit, Vec2, bool)> { + events .iter() .filter_map(|e| match e { - Event::MouseWheel { unit, delta, modifiers, .. } if for_field(e) => Some((*unit, *delta, modifiers.shift)), + Event::MouseWheel { unit, delta, modifiers, .. } => Some((*unit, *delta, modifiers.shift)), _ => None, }) - .collect(); - crate::widgets::count_notches(ui, field.with("wheel-acc"), &wheel, 10.0) + .collect() } #[cfg(test)] @@ -263,6 +349,351 @@ mod tests { assert!(h.state().1 > 0.0, "the panel scrolled"); } + /// A wheel dropdown (0–3) and a wheel slider row (0–100) below a gap, at the top of a scroll + /// area 200 pt tall over a large filler: (the dropdown's index, the slider's value, the + /// scroll area's vertical offset). + fn controls_harness() -> Harness<'static, (usize, f32, f32)> { + const MODES: [(usize, &str); 4] = [(0, "Normal"), (1, "Dissolve"), (2, "Darken"), (3, "Multiply")]; + let mut h = Harness::builder().with_size(vec2(300.0, 300.0)).with_step_dt(1.0 / 30.0).build_ui_state( + |ui, s: &mut (usize, f32, f32)| { + super::begin_frame(ui.ctx()); + let out = egui::ScrollArea::vertical().max_height(200.0).show(ui, |ui| { + ui.add_space(100.0); + crate::widgets::dropdown_wheel_hovered(ui, "blend-mode", "Blend Mode", &mut s.0, &MODES, 120.0); + let g = crate::widgets::RowGestures { wheel_step: Some(1.0), ..Default::default() }; + crate::widgets::slider_row_with(ui, "Amount", &mut s.1, 0.0..=100.0, "", None, g); + ui.allocate_space(vec2(200.0, 1000.0)); + }); + s.2 = out.state.clamped_offset().y; + }, + (1, 50.0, 0.0), + ); + h.run(); + h + } + + /// #11353: the same for a dropdown and a slider the wheel steps (a trackpad scrolling the + /// Properties or Character panel past them). + #[test] + fn a_gesture_that_starts_over_the_panel_keeps_scrolling_it_over_a_dropdown_or_slider() { + for role in [Role::ComboBox, Role::Slider] { + let mut h = controls_harness(); + let below = h.get_by_role(Role::Slider).rect().center() + vec2(0.0, 40.0); + h.hover_at(below); + h.run_steps(1); + let down = || egui::Event::MouseWheel { + source: egui::MouseWheelSource::Unknown, + unit: egui::MouseWheelUnit::Point, + delta: vec2(0.0, -12.0), + phase: egui::TouchPhase::Move, + modifiers: Modifiers::NONE, + }; + h.event(down()); + h.run_steps(1); + // Still the same gesture as the pointer reaches the control, a few notches' worth. + for _ in 0..6 { + let over = h.get_by_role(role).rect(); + assert!(over.top() > 0.0, "{role:?} still in view"); + h.hover_at(over.center()); + h.event(down()); + h.run_steps(1); + } + assert_eq!((h.state().0, h.state().1), (1, 50.0), "{role:?} passing under the pointer is not stepped"); + assert!(h.state().2 > 12.0, "{role:?}: the panel kept scrolling"); + } + } + + /// A gesture that starts over a dropdown or slider still steps it, and the panel stays put. + #[test] + fn a_gesture_that_starts_over_a_dropdown_or_slider_steps_it() { + for role in [Role::ComboBox, Role::Slider] { + let mut h = controls_harness(); + h.hover_at(h.get_by_role(role).rect().center()); + h.run_steps(1); + h.event(egui::Event::MouseWheel { + source: egui::MouseWheelSource::Unknown, + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, -1.0), + phase: egui::TouchPhase::Move, + modifiers: Modifiers::NONE, + }); + h.run_steps(4); + let want = if role == Role::ComboBox { (2, 50.0) } else { (1, 49.0) }; + assert_eq!((h.state().0, h.state().1), want, "{role:?}"); + assert_eq!(h.state().2, 0.0, "{role:?}: the panel didn't scroll"); + } + } + + /// A slider drawn without the app's setup, neither [`super::FieldWheel`] nor + /// [`super::begin_frame`], still steps with the wheel over it, as it did before the wheel + /// followed gestures: the widget installs what it needs the first time it asks. + #[test] + fn a_slider_drawn_without_the_apps_setup_steps_with_the_wheel() { + let mut h = Harness::builder().with_size(vec2(300.0, 100.0)).build_ui_state( + |ui, v: &mut f32| { + let g = crate::widgets::RowGestures { wheel_step: Some(1.0), ..Default::default() }; + crate::widgets::slider_row_with(ui, "Amount", v, 0.0..=100.0, "", None, g); + }, + 50.0, + ); + h.run(); + h.hover_at(h.get_by_role(Role::Slider).rect().center()); + h.run_steps(1); + h.event(egui::Event::MouseWheel { + source: egui::MouseWheelSource::Unknown, + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, -1.0), + phase: egui::TouchPhase::Move, + modifiers: Modifiers::NONE, + }); + h.run_steps(4); + assert_eq!(*h.state(), 49.0); + } + + /// #11353: fingers on a trackpad, and the glide they leave, scroll the panel even when the + /// gesture starts over a control without focus (macOS says which input it is). A physical + /// wheel still steps it. + #[test] + fn a_trackpad_gesture_that_starts_over_a_control_scrolls_the_panel() { + use egui::{MouseWheelSource as Source, TouchPhase as Phase}; + let ev = + |source, phase, y| egui::Event::MouseWheel { source, unit: egui::MouseWheelUnit::Point, delta: vec2(0.0, y), phase, modifiers: Modifiers::NONE }; + for role in [Role::ComboBox, Role::Slider] { + let mut h = controls_harness(); + h.hover_at(h.get_by_role(role).rect().center()); + h.run_steps(1); + // As macOS sends it: a start with no movement, then the fingers, then the glide. + h.event(ev(Source::Trackpad, Phase::Start, 0.0)); + h.run_steps(1); + for _ in 0..4 { + h.event(ev(Source::Trackpad, Phase::Move, -12.0)); + h.run_steps(1); + } + h.event(ev(Source::Momentum, Phase::Move, -12.0)); + h.run_steps(4); + assert_eq!((h.state().0, h.state().1), (1, 50.0), "{role:?}: no step"); + assert!(h.state().2 > 0.0, "{role:?}: the panel scrolled"); + } + let mut h = harness(100.0); + h.hover_at(field(&h).center()); + h.run_steps(1); + h.event(ev(Source::Trackpad, Phase::Start, 0.0)); + h.run_steps(1); + for _ in 0..4 { + h.event(ev(Source::Trackpad, Phase::Move, -12.0)); + h.run_steps(1); + } + h.run_steps(4); + assert_eq!(h.state().0, 100.0, "the value field isn't stepped"); + assert!(h.state().1 > 0.0, "the panel scrolled"); + + let mut h = controls_harness(); + h.hover_at(h.get_by_role(Role::Slider).rect().center()); + h.run_steps(1); + h.event(egui::Event::MouseWheel { + source: Source::Wheel, + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, -1.0), + phase: Phase::Move, + modifiers: Modifiers::NONE, + }); + h.run_steps(4); + assert_eq!(h.state().1, 49.0, "a physical wheel steps it"); + } + + /// A field with keyboard focus keeps a trackpad's wheel, as it keeps a mouse's. + #[test] + fn a_focused_field_takes_a_trackpad_gesture() { + let mut h = harness(100.0); + h.get_by_role(Role::SpinButton).click(); + h.run_steps(2); + let at = field(&h).center(); + h.hover_at(at); + h.run_steps(1); + h.event(egui::Event::MouseWheel { + source: egui::MouseWheelSource::Trackpad, + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, 2.0), + phase: egui::TouchPhase::Move, + modifiers: Modifiers::NONE, + }); + h.run_steps(4); + assert_eq!(h.state().0, 102.0); + } + + /// A gesture that steps a dropdown or slider, then wheels on with the pointer off it, is the + /// panel's from then on: coming back over the control in the same gesture doesn't step it + /// again, as for a value field. + #[test] + fn a_gesture_that_wheels_off_a_dropdown_or_slider_does_not_step_it_on_coming_back() { + for role in [Role::ComboBox, Role::Slider] { + let mut h = controls_harness(); + // Room to step up from. + h.state_mut().0 = 3; + h.run(); + let over = h.get_by_role(role).rect().center(); + h.hover_at(over); + h.run_steps(1); + // Up, so the panel (already at the top) doesn't move the controls. + let up = || egui::Event::MouseWheel { + source: egui::MouseWheelSource::Unknown, + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, 1.0), + phase: egui::TouchPhase::Move, + modifiers: Modifiers::NONE, + }; + h.event(up()); + h.run_steps(1); + let once = if role == Role::ComboBox { (2, 50.0) } else { (3, 51.0) }; + assert_eq!((h.state().0, h.state().1), once, "{role:?}: the start of the gesture steps it"); + h.hover_at(h.get_by_role(Role::Slider).rect().center() + vec2(0.0, 40.0)); + h.event(up()); + h.run_steps(1); + h.hover_at(over); + h.event(up()); + h.run_steps(4); + assert_eq!((h.state().0, h.state().1), once, "{role:?} was stepped once, by the start of the gesture"); + } + } + + /// The list of `harness`'s open dropdown (`None` while closed). + fn open_list(h: &Harness<'static, S>) -> Option { + h.ctx.memory(|m| m.layer_ids().filter(|l| l.order == egui::Order::Foreground).find_map(|l| m.area_rect(l.id))) + } + + /// An open dropdown list stays open as the panel scrolls, carried along with its button, so a + /// gesture scrolling the panel can bring the pointer over it: that doesn't step it either. + #[test] + fn a_gesture_that_starts_over_the_panel_does_not_step_an_open_dropdown_list() { + let mut h = controls_harness(); + h.get_by_role(Role::ComboBox).click(); + h.run_steps(4); + let Some(list) = open_list(&h) else { panic!("the list is open") }; + // Beside the list, over the panel: below the slider's row, which would take the gesture. + let slider = h.get_by_role(Role::Slider).rect(); + h.hover_at(egui::pos2(list.right() + 20.0, slider.bottom() + 10.0)); + h.run_steps(1); + let down = || egui::Event::MouseWheel { + source: egui::MouseWheelSource::Unknown, + unit: egui::MouseWheelUnit::Point, + delta: vec2(0.0, -12.0), + phase: egui::TouchPhase::Move, + modifiers: Modifiers::NONE, + }; + h.event(down()); + h.run_steps(1); + assert!(h.state().2 > 0.0, "the panel scrolled"); + // Still the same gesture as the pointer moves onto the list, a few notches' worth. + for _ in 0..6 { + let Some(list) = open_list(&h) else { panic!("the list stays open as the panel scrolls") }; + h.hover_at(list.center()); + h.event(down()); + h.run_steps(1); + } + assert_eq!(h.state().0, 1, "the open list under the pointer is not stepped"); + // A gesture that starts over the list still steps it. + h.run_steps(20); + let Some(list) = open_list(&h) else { panic!("the list is open") }; + h.hover_at(list.center()); + h.run_steps(1); + h.event(egui::Event::MouseWheel { + source: egui::MouseWheelSource::Unknown, + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, -1.0), + phase: egui::TouchPhase::Move, + modifiers: Modifiers::NONE, + }); + h.run_steps(4); + assert_eq!(h.state().0, 2, "a gesture over the list steps it"); + } + + /// One pass of window `viewport` (an egui viewport: the main window, or a panel floated into + /// a window of its own) at `time`, with [`super::FieldWheel`] installed as the app does: a + /// wheel dropdown over a large filler. The dropdown keeps its id from one window to another, + /// as a panel's widgets do when it is floated. The dropdown's rect. + fn window_pass(ctx: &egui::Context, viewport: egui::ViewportId, time: f64, events: Vec, selected: &mut usize) -> egui::Rect { + const MODES: [(usize, &str); 4] = [(0, "Normal"), (1, "Dissolve"), (2, "Darken"), (3, "Multiply")]; + let input = egui::RawInput { + viewport_id: viewport, + viewports: std::iter::once((viewport, egui::ViewportInfo::default())).collect(), + time: Some(time), + screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(300.0, 200.0))), + events, + ..Default::default() + }; + let mut rect = egui::Rect::NOTHING; + let mut out = ctx.run_ui(input, |ui| { + ui.scope_builder(egui::UiBuilder::new().scope_id(egui::Id::unique("panel-body")), |ui| { + crate::widgets::dropdown_wheel_hovered(ui, "blend-mode", "Blend Mode", selected, &MODES, 120.0); + rect = ui.min_rect(); + }); + ui.allocate_space(vec2(200.0, 1000.0)); + }); + out.textures_delta.clear(); + rect + } + + /// Half a notch left over in one window doesn't add up with half a notch in another: a panel + /// floated into a window of its own takes no step from the wheel of the window it left. + #[test] + fn a_half_notch_stays_in_its_window() { + let ctx = egui::Context::default(); + ctx.add_plugin(super::FieldWheel); + let floated = egui::ViewportId::from_hash_of("floated-panel"); + let mut selected = 1; + let half = || egui::Event::MouseWheel { + source: egui::MouseWheelSource::Unknown, + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, -0.5), + phase: egui::TouchPhase::Move, + modifiers: Modifiers::NONE, + }; + // Half a notch over the dropdown in the main window. + let over = window_pass(&ctx, egui::ViewportId::ROOT, 0.0, Vec::new(), &mut selected).center(); + window_pass(&ctx, egui::ViewportId::ROOT, 0.01, vec![egui::Event::PointerMoved(over), half()], &mut selected); + window_pass(&ctx, egui::ViewportId::ROOT, 0.02, Vec::new(), &mut selected); + assert_eq!(selected, 1, "half a notch"); + // The panel, floated, gets half a notch in its own window. + let over = window_pass(&ctx, floated, 1.0, Vec::new(), &mut selected).center(); + window_pass(&ctx, floated, 1.01, vec![egui::Event::PointerMoved(over), half()], &mut selected); + window_pass(&ctx, floated, 1.02, Vec::new(), &mut selected); + assert_eq!(selected, 1, "two halves in two windows are no notch"); + // Another half in the same window makes a whole one. + window_pass(&ctx, floated, 2.0, vec![half()], &mut selected); + window_pass(&ctx, floated, 2.01, Vec::new(), &mut selected); + assert_eq!(selected, 2); + } + + /// #11353: a panel floated into a window of its own has input of its own. A gesture there + /// that starts over its dropdown steps it, though the main window is in the middle of + /// scrolling a panel, and the main window's record isn't the floated window's. + #[test] + fn a_floated_panels_window_follows_its_own_wheel_gestures() { + let ctx = egui::Context::default(); + ctx.add_plugin(super::FieldWheel); + let floated = egui::ViewportId::from_hash_of("floated-panel"); + let (mut main_sel, mut floated_sel) = (1, 1); + let wheel = || egui::Event::MouseWheel { + source: egui::MouseWheelSource::Unknown, + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, -1.0), + phase: egui::TouchPhase::Move, + modifiers: Modifiers::NONE, + }; + // The main window scrolls a panel, its pointer below its dropdown. + let below = window_pass(&ctx, egui::ViewportId::ROOT, 0.0, Vec::new(), &mut main_sel).center() + vec2(0.0, 130.0); + window_pass(&ctx, egui::ViewportId::ROOT, 0.01, vec![egui::Event::PointerMoved(below), wheel()], &mut main_sel); + // Meanwhile a gesture in the floated window starts with its pointer on its dropdown. (Its + // passes come after the main window's: egui forgets a window the main window's pass + // didn't show, and the dock shows its floated panels in every pass.) + let over = window_pass(&ctx, floated, 0.02, Vec::new(), &mut floated_sel).center(); + window_pass(&ctx, floated, 0.03, vec![egui::Event::PointerMoved(over)], &mut floated_sel); + window_pass(&ctx, floated, 0.04, vec![wheel()], &mut floated_sel); + window_pass(&ctx, floated, 0.06, Vec::new(), &mut floated_sel); + assert_eq!(floated_sel, 2, "the floated panel's dropdown is stepped"); + assert_eq!(main_sel, 1, "the main window's dropdown isn't"); + } + /// A plain sideways scroll (a trackpad swipe) is the view's, focused or hovered; Shift+wheel /// that the system turned sideways still steps by ten. #[test] @@ -290,10 +721,10 @@ mod tests { } } - /// A trackpad gesture that macOS starts with a zero-delta event, then moves a frame later, - /// steps the field under the pointer. + /// A gesture from a system that doesn't say what drives it, starting with a zero-delta event + /// and moving a frame later, steps the field under the pointer. #[test] - fn a_trackpad_gesture_that_starts_with_no_delta_steps_a_hovered_field() { + fn a_gesture_that_starts_with_no_delta_steps_a_hovered_field() { let mut h = harness(100.0); h.hover_at(field(&h).center()); h.run_steps(1); diff --git a/crates/ui-egui/src/widgets/slider.rs b/crates/ui-egui/src/widgets/slider.rs index 9a4ff47dd2..0a4922e03b 100644 --- a/crates/ui-egui/src/widgets/slider.rs +++ b/crates/ui-egui/src/widgets/slider.rs @@ -50,33 +50,19 @@ pub(crate) fn curve_fraction(v: f32, lo: f32, hi: f32, curve: Option) -> f3 } } -/// Wheel notches this frame while the pointer is over `resp` (Shift ×10). Wheel lines add up in -/// egui memory until they make whole notches (high-resolution wheels report fractions of one); -/// smooth (point) deltas count `line_scroll_speed` points per notch, like the canvas wheel. +/// Wheel notches this frame while the pointer is over `resp` (Shift ×10), of a gesture that +/// started over it: a panel being scrolled past the slider keeps scrolling (#11353). fn wheel_notches(ui: &Ui, resp: &Response) -> f32 { - wheel_notches_of(ui, resp.id, resp.hovered(), 10.0) -} - -/// [`wheel_notches`] of widget `id` while `hovered`, a notch with Shift counting `shift_notches`. -pub(crate) fn wheel_notches_of(ui: &Ui, id: egui::Id, hovered: bool, shift_notches: f32) -> f32 { - if !hovered { - return 0.0; - } - let wheel: Vec<(egui::MouseWheelUnit, Vec2, bool)> = ui.input(|i| { - i.events - .iter() - .filter_map(|e| match e { - egui::Event::MouseWheel { unit, delta, modifiers, .. } => Some((*unit, *delta, modifiers.shift)), - _ => None, - }) - .collect() - }); - count_notches(ui, id.with("wheel-acc"), &wheel, shift_notches) + crate::field_wheel::hover_notches(ui, resp.id, resp.rect, 10.0) } /// Whole notches in `wheel` (unit, delta, Shift held), a notch with Shift counting -/// `shift_notches`; fractions carry over in egui memory under `acc_id`. +/// `shift_notches`. Wheel lines add up in egui memory under `acc_id` until they make whole +/// notches (high-resolution wheels report fractions of one), each window's apart: a fraction +/// doesn't follow a panel floated into a window of its own (#11353). Smooth (point) deltas count +/// `line_scroll_speed` points per notch, like the canvas wheel. pub(crate) fn count_notches(ui: &Ui, acc_id: egui::Id, wheel: &[(egui::MouseWheelUnit, Vec2, bool)], shift_notches: f32) -> f32 { + let acc_id = acc_id.with(ui.ctx().viewport_id()); let mut acc: f32 = ui.data(|d| d.get_temp(acc_id)).unwrap_or(0.0); let per_line = ui.ctx().options(|o| o.input_options.line_scroll_speed); let per_line = if per_line.is_finite() && per_line > 0.0 { per_line } else { 40.0 }; diff --git a/docs/ui-parity.md b/docs/ui-parity.md index c527284369..a239c1871e 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity: tools, handles, modifiers and feel -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (painting tools' options bar shows Opacity right after Mode in every theme, #9784; Column Size drives the Columns width unit, #6214: 8 of 199 preferences do nothing; Warp mode edits Photoshop's Cylinder warp with its five handles, #4112; Hue/Saturation range zones drag, #9252; a click on the image centres a filter dialog's preview window, #9648; a gradient stop dragged off the bar is removed in every stop editor, Gradient Map and Layer Style included, #10742; Image › Adjustments › Photo Filter… keeps Preserve Luminosity from its last OK and opens at Warming Filter (85), 25 %, as the reference application does, #9879; foreground/background swatches and exact CMYK picks restored across launches, #8485; Layer ▸ Smart Objects ▸ Reset Transform and the Layers panel row-menu item for a smart object layer: 100 % again in place with the Warp cleared and centred on the corners' average, #11662; each toolbar slot and tool key keeps its last tool across launches, #3569; Image › Adjustments › Selective Color keeps each colour's own values and applies all nine, #11463; History Options snapshot options, #3634; Channels panel menu: New Channel…, Duplicate Channel, Delete Channel, New Spot Channel…, Merge Spot Channel, Channel Options…, Split Channels, Merge Channels…, #11451; a Color Picker for another dialog's colour or the Crop shield shows the picked colour there before OK, #9886; Edit › Transform › Distort side handles move their edge, Perspective side handles skew, #10085; Ctrl + Alt + wheel zooms the canvas like ⌥ + wheel on Windows and Linux, where winit reports a held Ctrl as both ctrl and command, #10488; Layers panel filter by Color, #5898; 11 of 183 preferences do nothing: startup reads Graphics Adapter through the typed Performance section, so the scorecard audit sees it; Shape Fill/Stroke popover as Photoshop's, every colour swatch opens the full Color Picker with a live preview; the text and gradient stop Color Pickers show the picked colour on the canvas before OK, #5530; selected colour sets edit drawing, tone and supported filters; geometry remains open; a paragraph box that can't hold its text enlarges its lower-right handle and shows a black + in it, as the reference application; Free Transform of several selected layers, #6501; Path Operations fixes: the first component keeps combining, a hidden component selection is left alone, a dragged live shape stays live, a refused Pen draft ends once; Pen, Freeform Pen, Curvature Pen and Path Selection Path Operations menu, which changes selected components, `+` / `-` keys, #1397; the Pen carries on an open shape or vector mask path; selection-aware font controls, pending caret fonts and focused commit, plus direct font-name editing with a compact no-match message, #9338; New Group dialog and button modifiers; new layers go into an open active group and join a clipping mask, except that type, shapes, pastes and placed files go above a group whose lock would refuse them; Color panel Hue and Brightness Cube show the out-of-gamut ⚠ and nearest printable colour when the field is at least 53 pt tall, #8672; Art History Brush in the History group of the Y flyout, partial, TOOL-213-20, #1610; Histogram panel: Compact / Expanded / All Channels views, Luminosity and Colors channels, Source, range statistics, Uncached Refresh, live adjustment overlay, Cache Levels preference; the font menu opens on the current family, marked in the recent group when it is a recent one, #9160; Type options bar alignment and direction follow the target paragraph; a swatch click recolours selected type and shape layers with any tool, #9238; UI scale presets done: 105–120% steps, #3222; ⇧⌥ blend mode letters; painting tool Mode menus; ⌥ + an adjustment's shortcut reopens it at its last settings, ⌥⌘L / ⌥⌘M, #8900; Crop default mode: moving the image under the box snaps the frame's edges and centre, #8580; View › Extras hides the Move transform controls, #6699; adjustment clipping stays visible in compact Properties, #5231; Color panel modes from its panel menu, the same in every theme, UI-217-17, #6000; a picked colour recolours the selected type and shapes; Hand tool ⌘ / ⌥ are Zoom In / Zoom Out while held, #6434; the wheel steps value fields, #5473; a dragged guide shows its X or Y beside the pointer, #7680; Type options bar "T" icon scrubs the font size, #6437; Move tool: dragged selected pixels take their own outline as the selection, #7538; artboard backgrounds remain below child Free Transform previews; ⌫/Delete removes the selected smart filter, #4751; Object Finder foreground/background discrimination (#6548); rounded triangle, polygon and star corners; shape Fill/Stroke popovers accept hex RGB values, #6176; a guide let go over either ruler is removed, #6286; Crop rows corrected: saved crop presets and Delete Cropped Pixels off are done, #6562; marching ants in device pixels, #7489; Animated Zoom: holding the Zoom tool zooms continuously, #6210; shape Density and Feather, TOOL-214-12, #5846; Pen Auto Add/Delete on the path being drawn, #6140; Show Transform Controls frames every selected layer; guide keys and clicks; menu bar from the keyboard, #4988; Crop tool Content-Aware Fill; on-canvas corner radius widgets, TOOL-214-12; Curvature Pen edits the active path; Clip Thumbnails to Layer Bounds; Pen ⇧ 45°; last selected tool restored at launch; Layers panel filter-type dropdown with Kind, Name and Mode, #5048; Free Transform box and marching ants follow the selection, #5297; History: the trash deletes the selected snapshot, rows drag onto the trash, #5324; smart filter reordering by drag; smart object perspective row corrected to done, #426; Free Transform H/V skew fields; toolbar tool shortcuts can be reassigned; ⇧-dragged guides land on ruler ticks; layer and selection keys; tool keys; spring-loaded tool letters; type formatting keys; Pen Auto Add/Delete, #4144; smart filter rows; stale missing-tool rows corrected: Color Replacement, Red Eye and the Add/Delete Anchor Point pair are live toolbar tools, Frame landed; no percentage changed; selection-modifier and ⌥-wheel rows match their tests; Properties › Transform shows a shape's path geometry, without its stroke) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (the wheel steps a dropdown, a slider or the font field only for a gesture that starts over it, so a panel scrolled past them keeps scrolling, and a trackpad on macOS scrolls the panel over any control without focus, #11353; painting tools' options bar shows Opacity right after Mode in every theme, #9784; Column Size drives the Columns width unit, #6214: 8 of 199 preferences do nothing; Warp mode edits Photoshop's Cylinder warp with its five handles, #4112; Hue/Saturation range zones drag, #9252; a click on the image centres a filter dialog's preview window, #9648; a gradient stop dragged off the bar is removed in every stop editor, Gradient Map and Layer Style included, #10742; Image › Adjustments › Photo Filter… keeps Preserve Luminosity from its last OK and opens at Warming Filter (85), 25 %, as the reference application does, #9879; foreground/background swatches and exact CMYK picks restored across launches, #8485; Layer ▸ Smart Objects ▸ Reset Transform and the Layers panel row-menu item for a smart object layer: 100 % again in place with the Warp cleared and centred on the corners' average, #11662; each toolbar slot and tool key keeps its last tool across launches, #3569; Image › Adjustments › Selective Color keeps each colour's own values and applies all nine, #11463; History Options snapshot options, #3634; Channels panel menu: New Channel…, Duplicate Channel, Delete Channel, New Spot Channel…, Merge Spot Channel, Channel Options…, Split Channels, Merge Channels…, #11451; a Color Picker for another dialog's colour or the Crop shield shows the picked colour there before OK, #9886; Edit › Transform › Distort side handles move their edge, Perspective side handles skew, #10085; Ctrl + Alt + wheel zooms the canvas like ⌥ + wheel on Windows and Linux, where winit reports a held Ctrl as both ctrl and command, #10488; Layers panel filter by Color, #5898; 11 of 183 preferences do nothing: startup reads Graphics Adapter through the typed Performance section, so the scorecard audit sees it; Shape Fill/Stroke popover as Photoshop's, every colour swatch opens the full Color Picker with a live preview; the text and gradient stop Color Pickers show the picked colour on the canvas before OK, #5530; selected colour sets edit drawing, tone and supported filters; geometry remains open; a paragraph box that can't hold its text enlarges its lower-right handle and shows a black + in it, as the reference application; Free Transform of several selected layers, #6501; Path Operations fixes: the first component keeps combining, a hidden component selection is left alone, a dragged live shape stays live, a refused Pen draft ends once; Pen, Freeform Pen, Curvature Pen and Path Selection Path Operations menu, which changes selected components, `+` / `-` keys, #1397; the Pen carries on an open shape or vector mask path; selection-aware font controls, pending caret fonts and focused commit, plus direct font-name editing with a compact no-match message, #9338; New Group dialog and button modifiers; new layers go into an open active group and join a clipping mask, except that type, shapes, pastes and placed files go above a group whose lock would refuse them; Color panel Hue and Brightness Cube show the out-of-gamut ⚠ and nearest printable colour when the field is at least 53 pt tall, #8672; Art History Brush in the History group of the Y flyout, partial, TOOL-213-20, #1610; Histogram panel: Compact / Expanded / All Channels views, Luminosity and Colors channels, Source, range statistics, Uncached Refresh, live adjustment overlay, Cache Levels preference; the font menu opens on the current family, marked in the recent group when it is a recent one, #9160; Type options bar alignment and direction follow the target paragraph; a swatch click recolours selected type and shape layers with any tool, #9238; UI scale presets done: 105–120% steps, #3222; ⇧⌥ blend mode letters; painting tool Mode menus; ⌥ + an adjustment's shortcut reopens it at its last settings, ⌥⌘L / ⌥⌘M, #8900; Crop default mode: moving the image under the box snaps the frame's edges and centre, #8580; View › Extras hides the Move transform controls, #6699; adjustment clipping stays visible in compact Properties, #5231; Color panel modes from its panel menu, the same in every theme, UI-217-17, #6000; a picked colour recolours the selected type and shapes; Hand tool ⌘ / ⌥ are Zoom In / Zoom Out while held, #6434; the wheel steps value fields, #5473; a dragged guide shows its X or Y beside the pointer, #7680; Type options bar "T" icon scrubs the font size, #6437; Move tool: dragged selected pixels take their own outline as the selection, #7538; artboard backgrounds remain below child Free Transform previews; ⌫/Delete removes the selected smart filter, #4751; Object Finder foreground/background discrimination (#6548); rounded triangle, polygon and star corners; shape Fill/Stroke popovers accept hex RGB values, #6176; a guide let go over either ruler is removed, #6286; Crop rows corrected: saved crop presets and Delete Cropped Pixels off are done, #6562; marching ants in device pixels, #7489; Animated Zoom: holding the Zoom tool zooms continuously, #6210; shape Density and Feather, TOOL-214-12, #5846; Pen Auto Add/Delete on the path being drawn, #6140; Show Transform Controls frames every selected layer; guide keys and clicks; menu bar from the keyboard, #4988; Crop tool Content-Aware Fill; on-canvas corner radius widgets, TOOL-214-12; Curvature Pen edits the active path; Clip Thumbnails to Layer Bounds; Pen ⇧ 45°; last selected tool restored at launch; Layers panel filter-type dropdown with Kind, Name and Mode, #5048; Free Transform box and marching ants follow the selection, #5297; History: the trash deletes the selected snapshot, rows drag onto the trash, #5324; smart filter reordering by drag; smart object perspective row corrected to done, #426; Free Transform H/V skew fields; toolbar tool shortcuts can be reassigned; ⇧-dragged guides land on ruler ticks; layer and selection keys; tool keys; spring-loaded tool letters; type formatting keys; Pen Auto Add/Delete, #4144; smart filter rows; stale missing-tool rows corrected: Color Replacement, Red Eye and the Add/Delete Anchor Point pair are live toolbar tools, Frame landed; no percentage changed; selection-modifier and ⌥-wheel rows match their tests; Properties › Transform shows a shape's path geometry, without its stroke) · **Target:** Adobe Photoshop 2026 How PhotoCraft's direct manipulation compares with Photoshop 2026 (27.11.0): the toolbox, the handles and modifier keys of each gesture, nudging, snapping, numeric precision, navigation, @@ -179,7 +179,7 @@ Triangle and Curvature Pen (minus legacy Rounded Rectangle and Targeted Adjustme | Guides stored as f64 | done | `Vec`, kept through .pcraft and PSD (UI-217-20) | | Geometry precision | partial | `geom::Point` f64, paths f64; paint internals mostly f32 | | Numeric fields: arithmetic, scrubby labels | done | arithmetic with units, scrubby labels, double-click reset (UI-217-13, #3099) | -| Wheel steps a value field, ⇧ ×10: clicked into, wherever the pointer is; not clicked, a gesture that starts over it | partial | `field_wheel.rs` (#5473, #4061). Photoshop: a field takes the wheel once clicked into (shortcut guides, user reports); whether the pointer must stay over it is unconfirmed. Stepping on hover alone is Photopea's, kept deliberately | +| Wheel steps a value field, ⇧ ×10: clicked into, wherever the pointer is; not clicked, a gesture that starts over it | partial | `field_wheel.rs` (#5473, #4061); dropdowns, sliders and the font field step only for a gesture that starts over them too, and a trackpad on macOS steps only a clicked-into field, scrolling the panel wherever it starts (#11353; other systems don't say what's a trackpad). Photoshop: a field takes the wheel once clicked into (shortcut guides, user reports); whether the pointer must stay over it is unconfirmed. Stepping on hover alone is Photopea's, kept deliberately | | Font-name field: click selects the full name; typing searches in place | done | `type_tool.rs` `family_picker_in`, `type_font_picker_tests.rs` (#9338): one editable name above the list; unmatched queries show a compact message; Enter or a row applies to the selected characters even when the family matches their representative; both controls show the selected span and leave mixed families blank; caret font choices affect subsequent typing; Ctrl/Cmd+Enter accepts a valid pending font query and commits from a focused field; Escape/outside click discards pending text; existing navigation and previews retained | | Type options bar: drag the "T" icon to change the font size | done | `type_tool.rs` `options_bar`: the icon scrubs the size field like the Character panel's icons (Shift x10, Alt fine), at layer or selection scope, one history step per drag, within 1–1296 pt (#6437) | @@ -279,6 +279,7 @@ Paragraph; the rest open as in-app floating windows. | Date | Change | Summary | |---|---|---| +| 2026-11-06 | minor | A trackpad or wheel scrolling a panel keeps scrolling it when a wheel dropdown (blend modes, Color Lookup…), a dialog slider or the font field passes under the pointer: they step only for a gesture that starts over them, as value fields not clicked into already did; a trackpad on macOS scrolls the panel even when the gesture starts over a control without focus; a panel floated into a window of its own follows that window's gestures (#11353); no percentage changed | | 2026-10-28 | minor | Brush and Eraser options bar outside the Pro themes: Hardness moved beside Size, so Opacity follows Mode in every theme, as in Photoshop and the Pro bar (#9784). Scores unchanged. | | 2026-11-08 | minor | Actions panel: an action or step row dragged onto the trash is deleted, and one dragged onto Create new action is duplicated right after itself (#12373) | | 2026-11-08 | minor | ⇧ while moving a guide already placed lands it on the nearest ruler tick too, as a guide dragged out of a ruler does (#3770); a ⇧-click still only selects it, and a guide ⌥ turns snaps along its new axis. In a pixel ruler ⇧ snaps guides and the zero point to whole pixels at least, also deep in, where the minor ticks are fractions of a pixel |