diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 0e6b69b3f0a..7981035a5d8 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -17,6 +17,7 @@ next to them. | `assets/icons/{arrow-left-right,circle-dashed,ellipsis,file-plus,folder-plus,grid-2x2,house,link-2,message-square,panel-left,pipette,rectangle-horizontal,rectangle-vertical,redo-2,square-dashed,square-dashed-mouse-pointer,triangle-alert,type,x}.svg` | Lucide icons | Lucide Icons and Contributors | (`icons/.svg`) | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) | | `assets/icons/{link-2,type,x}.svg` | Lucide icons derived from Feather (subset of the row above) | Cole Bemis (Feather), Lucide Contributors | via Lucide | MIT (Feather) and ISC (Lucide), [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) | | `assets/icons/vector-shape.svg` | Vector path shape-layer glyph with four anchor points | @superplay2021 | Original work for PhotoCraft | MIT OR Apache-2.0 | +| `assets/icons/gradient-tool.svg` | Gradient tool glyph with a horizontal opacity ramp | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | | `assets/icons/spirit-level.svg` | Straighten tool glyph: a spirit level with its vial and bubble under a dotted arc | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | | `assets/icons/type-vertical.svg` | Vertical Type tool glyph: Lucide `type`'s T, drawn narrower to make room for a downward arrow of our own at its left | Lucide Icons and Contributors; arrow by PhotoCraft contributors | Derived from `icons/type.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) | | `assets/icons/quick-mask-{off,masked-areas,selected-areas}.svg` | Quick Mask toolbar glyphs showing the inactive mode and the two overlay meanings | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | @@ -28,6 +29,7 @@ next to them. | `assets/app-icon/photocraft-nightly.png`, `photocraft-nightly-1024.png`, `photocraft-nightly.ico`, `photocraft-nightly.icns` | PhotoCraft nightly deep-background derivatives | @skylartaylor | Original project-owned256 and padded1024 masters at the revision and hashes in [`nightly-provenance.json`](assets/app-icon/nightly-provenance.json); code-generated background-contribution change only, preserving foreground/alpha; no badge or crescent | MIT OR Apache-2.0, [`assets/app-icon/LICENSE.txt`](assets/app-icon/LICENSE.txt) | | `packaging/nightly-archive-tests.py` (runtime-generated temporary files) | Synthetic flat-archive inventory and exclusive-output fixtures; regular-file payloads, not real image/executable validity | @skylartaylor | Original test-generated strings/files and symlinks from the committed script; no external media or user documents | MIT OR Apache-2.0 | | `packaging/macos/dmg/` (all files) | PhotoCraft DMG window background and layout | @XusBadia, from the PhotoCraft app icon | Original work, see [`packaging/macos/dmg/README.md`](packaging/macos/dmg/README.md) | MIT OR Apache-2.0, like the code | +| `crates/ui-egui/src/dialogs/adjust_editors/black_white_presets.rs` | Built-in Black & White tonal and filter mixes | PhotoCraft contributors (@Bobderto) | Original weights chosen to produce the named tonal and color-filter effects, from [PhotoCraft `2b1afe637`](https://github.com/storytold/photocraft/commit/2b1afe637cabe3eba622c8edd3e92b279aa8dfe4) | MIT OR Apache-2.0 | | `crates/ui-egui/src/theme.rs` (Solarized Dark palette) | Solarized colour scheme used by the Solarized Dark theme | Ethan Schoonover | | MIT, [`LICENSE-solarized.txt`](crates/ui-egui/src/LICENSE-solarized.txt) | | `crates/ui-egui/src/theme.rs` (Breeze Light and Breeze Dark themes) | The Breeze Light and Breeze Dark themes are original colour values on PhotoCraft's Studio layout, chosen to look close to KDE Plasma's Breeze (cool blue-greys, blue accent, 5 px frame radius) so the app blends into a Plasma desktop. None of Breeze's colour values, files or code are copied; the values are a few levels away from its schemes and tuned for text contrast | PhotoCraft contributors | Inspired by the look of KDE Breeze, (its colour schemes are LGPL-2.0-or-later) | Original work | | `crates/ui-egui/src/theme.rs` (Soft Dark and Soft Light themes) | Original colour values and radii for two low-contrast themes on PhotoCraft's Studio layout; no third-party palette, file or code is used | PhotoCraft contributors | Original | Original work | diff --git a/Cargo.lock b/Cargo.lock index 980c2438d55..3f47ef1ed5a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7103,6 +7103,7 @@ version = "0.23.1" dependencies = [ "base64 0.23.1", "chrono", + "core-graphics", "craft", "craft-file-formats", "craft-i18n", @@ -7141,6 +7142,7 @@ dependencies = [ "toml", "web-time", "winsafe", + "x11rb", ] [[package]] diff --git a/assets/icons/gradient-tool.svg b/assets/icons/gradient-tool.svg new file mode 100644 index 00000000000..94516fd712c --- /dev/null +++ b/assets/icons/gradient-tool.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/crates/algo/src/relight.rs b/crates/algo/src/relight.rs index d36454d238e..efa96684e8d 100644 --- a/crates/algo/src/relight.rs +++ b/crates/algo/src/relight.rs @@ -532,9 +532,21 @@ mod tests { assert!(read_radius(sigma(25.0, bounds)) > 97); let area = output_area(&p, s.content_bounds(), bounds, None); let full = apply_tiled(&s, &p, area, bounds, None, 4096, None); - let tiled = apply_tiled(&s, &p, area, bounds, None, 128, None); - let inner = Rect::new(0, 0, size, size); - let d = max_diff(&full.read_region(inner), &tiled.read_region(inner)); + // Keep every tile that contributes checked pixels, including each edge tile's + // original rectangle and halo. The remaining tiles lie wholly outside the canvas. + let tile = 128; + let tile_start = |pixel: i32, origin: i32| origin + (pixel - origin).div_euclid(tile) * tile; + let visible_tiles = Rect::new( + tile_start(bounds.x0, area.x0), + tile_start(bounds.y0, area.y0), + tile_start(bounds.x1 - 1, area.x0) + tile, + tile_start(bounds.y1 - 1, area.y0) + tile, + ) + .intersect(&area); + let tiled = apply_tiled(&s, &p, visible_tiles, bounds, None, tile, None); + let center = size / 2; + assert!(max_diff(&full.pixel(center, center), &s.pixel(center, center)) > 1e-4, "the full frame must be relit"); + let d = max_diff(&full.read_region(bounds), &tiled.read_region(bounds)); assert!(d <= 1e-4, "tile seam {d}"); } diff --git a/crates/engine-core/src/cmd.rs b/crates/engine-core/src/cmd.rs index fa15aaeb673..e931a08f0cb 100644 --- a/crates/engine-core/src/cmd.rs +++ b/crates/engine-core/src/cmd.rs @@ -87,6 +87,8 @@ pub mod layer_label_cmds; pub mod layer_list_cmds; pub mod layer_mask_props_cmds; pub mod layer_menu_cmds; +#[cfg(test)] +mod layer_merge_clipping_mask_tests; pub mod layer_multi_cmds; pub mod layer_nav_cmds; mod layer_params; diff --git a/crates/engine-core/src/cmd/analysis_cmds.rs b/crates/engine-core/src/cmd/analysis_cmds.rs index 6e65c4f0a0a..c20e3c5ddfb 100644 --- a/crates/engine-core/src/cmd/analysis_cmds.rs +++ b/crates/engine-core/src/cmd/analysis_cmds.rs @@ -296,8 +296,10 @@ fn set_scale(s: &mut Session, p: &Value) -> Result { other => return Err(bad(CMD, format!("unknown preset `{other}` (default|custom)"))), }; if next != cur { + // The reference names the step after the submenu entry that made it (#17410). + let label = if preset == "default" { "Set Default Measurement Scale" } else { "Custom Measurement Scale" }; let n = next.clone(); - s.edit("Set Measurement Scale", move |d, _| { + s.edit(label, move |d, _| { d.measurement.scale = n; Ok(()) })?; @@ -1460,4 +1462,6 @@ mod data_points_one_list_tests; #[cfg(test)] mod record_no_data_points_tests; #[cfg(test)] +mod scale_history_names_tests; +#[cfg(test)] mod tests; diff --git a/crates/engine-core/src/cmd/analysis_cmds/scale_history_names_tests.rs b/crates/engine-core/src/cmd/analysis_cmds/scale_history_names_tests.rs new file mode 100644 index 00000000000..de5298f1b3e --- /dev/null +++ b/crates/engine-core/src/cmd/analysis_cmds/scale_history_names_tests.rs @@ -0,0 +1,60 @@ +//! History step names of Image › Analysis › Set Measurement Scale, measured against the reference +//! application (#17410): Custom (the dialog, a preset, a script set) adds one step "Custom +//! Measurement Scale", Default adds one step "Set Default Measurement Scale", and a call that +//! leaves the scale as it is adds no step. + +use super::*; + +const CMD: &str = "image.analysis.setMeasurementScale"; + +fn session() -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 40, "height": 30, "background": "white"})).unwrap(); + s +} + +fn steps(s: &Session) -> usize { + s.active().unwrap().history.past_len() +} + +fn last_step(s: &Session) -> String { + s.active().unwrap().history.entries().last().cloned().unwrap_or_default() +} + +#[test] +fn custom_and_bare_values_add_one_custom_step() { + for p in [ + json!({"preset": "custom", "pixelLength": 100, "logicalLength": 2.5, "units": "cm"}), + json!({"pixelLength": 100, "logicalLength": 2.5, "units": "cm"}), + json!({"units": "mm"}), + ] { + let mut s = session(); + let before = steps(&s); + s.execute(CMD, p.clone()).unwrap(); + assert_eq!(steps(&s), before + 1, "{p}"); + assert_eq!(last_step(&s), "Custom Measurement Scale", "{p}"); + } +} + +#[test] +fn default_adds_one_default_step() { + let mut s = session(); + s.execute(CMD, json!({"pixelLength": 10, "logicalLength": 1, "units": "cm"})).unwrap(); + let before = steps(&s); + s.execute(CMD, json!({"preset": "default"})).unwrap(); + assert_eq!(steps(&s), before + 1); + assert_eq!(last_step(&s), "Set Default Measurement Scale"); +} + +#[test] +fn unchanged_scale_adds_no_step() { + let mut s = session(); + let before = steps(&s); + s.execute(CMD, json!({"preset": "default"})).unwrap(); + assert_eq!(steps(&s), before, "Default on a default scale"); + let p = json!({"pixelLength": 10, "logicalLength": 1, "units": "cm"}); + s.execute(CMD, p.clone()).unwrap(); + let before = steps(&s); + s.execute(CMD, p).unwrap(); + assert_eq!(steps(&s), before, "the same custom values again"); +} diff --git a/crates/engine-core/src/cmd/background_cmds.rs b/crates/engine-core/src/cmd/background_cmds.rs index 90ed98c578d..4976894bc87 100644 --- a/crates/engine-core/src/cmd/background_cmds.rs +++ b/crates/engine-core/src/cmd/background_cmds.rs @@ -86,6 +86,13 @@ fn background_from_layer(s: &mut Session, p: &Value) -> Result { } let l = doc.layer(id).ok_or(EngineError::NoLayer(id))?; convertible(l).map_err(EngineError::Other)?; + // Keep the one measured clipped sibling with its top-level base. Leave nested + // targets and stacks with several clipped layers on the existing path. + let mut above = doc.layers.iter().skip_while(|layer| layer.id != id).skip(1); + let clipped = match (above.next(), above.next()) { + (Some(layer), next) if !l.clipped && layer.clipped && !next.is_some_and(|layer| layer.clipped) => Some(layer.id), + _ => None, + }; // Render the layer alone, as it looks (mask, opacity and effects applied), over the // background colour: the Background is opaque and plain. let mut only = l.clone(); @@ -104,6 +111,10 @@ fn background_from_layer(s: &mut Session, p: &Value) -> Result { *crate::pixels_mut(&mut out)? = pixels; doc.remove(id).ok_or(EngineError::NoLayer(id))?; doc.layers.insert(0, out); + if let Some(clipped) = clipped { + let layer = doc.remove(clipped).ok_or(EngineError::NoLayer(clipped))?; + doc.layers.insert(1, layer); + } *active = Some(id); Ok(()) })?; diff --git a/crates/engine-core/src/cmd/edit_menu_cmds.rs b/crates/engine-core/src/cmd/edit_menu_cmds.rs index 3633d630a10..f8ffa52811a 100644 --- a/crates/engine-core/src/cmd/edit_menu_cmds.rs +++ b/crates/engine-core/src/cmd/edit_menu_cmds.rs @@ -370,7 +370,7 @@ pub fn specs() -> Vec { ["Edit"], None, r##"{"name":text}"##, - |s| if s.is_enabled("brush.defineFromSelection") { Ok(()) } else { Err("select pixels to define a brush from".into()) }, + |s| s.disabled_reason("brush.defineFromSelection").map_or(Ok(()), Err), define_brush_preset ), spec!( diff --git a/crates/engine-core/src/cmd/edit_menu_cmds/presets.rs b/crates/engine-core/src/cmd/edit_menu_cmds/presets.rs index a40737910f5..8a2e9fe9719 100644 --- a/crates/engine-core/src/cmd/edit_menu_cmds/presets.rs +++ b/crates/engine-core/src/cmd/edit_menu_cmds/presets.rs @@ -5,14 +5,20 @@ use photocraft_doc::vector::PathOp; // ------------------------------------------------------------------ Define Brush / Custom Shape pub(super) fn define_brush_preset(s: &mut Session, p: &Value) -> Result { - let name = match p.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()) { - Some(n) => n.to_string(), - None => { - let n = s.tools.presets.iter().filter(|b| b.name.starts_with("Sampled Brush")).count() + 1; - format!("Sampled Brush {n}") - } - }; - s.execute("brush.defineFromSelection", json!({"name": name})) + let typed = p.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()); + // The default counts the defaults stored this session; presets that merely share the name don't raise it (#18228). A + // number a preset already uses is skipped, since storing under that name would replace that preset; the store matches + // names ignoring ASCII case, so this does too. + let mut number = s.tools.sampled_brushes.saturating_add(1); + while typed.is_none() && s.tools.presets.iter().any(|b| b.name.eq_ignore_ascii_case(&format!("Sampled Brush {number}"))) { + number = number.saturating_add(1); + } + let name = typed.map_or_else(|| format!("Sampled Brush {number}"), str::to_string); + let defined = s.execute("brush.defineFromSelection", json!({"name": name}))?; + if typed.is_none() { + s.tools.sampled_brushes = number; + } + Ok(defined) } /// The path Define Custom Shape uses: `"work"`, a saved path name, else the work path, the diff --git a/crates/engine-core/src/cmd/layer_merge_clipping_mask_tests.rs b/crates/engine-core/src/cmd/layer_merge_clipping_mask_tests.rs new file mode 100644 index 00000000000..4455a9811dc --- /dev/null +++ b/crates/engine-core/src/cmd/layer_merge_clipping_mask_tests.rs @@ -0,0 +1,145 @@ +//! #18481: `Ctrl+E` (`layer.mergeLayers`) with the base of a clip group alone selected is Merge Clipping Mask: the base +//! and the layers clipped to it become one layer with the base's identity, name, place, blend mode and opacity; the +//! composite does not change, and clipped pixels outside the base are gone. Other layers, and the cases the issue did +//! not measure, keep Merge Down. + +use photocraft_doc::{BlendMode, LayerId}; +use photocraft_geom::Rect; +use serde_json::json; + +use crate::Session; + +/// `Top` (blue, wider than `Red`) clipped onto `Red`, `Masked` below, on a white Background; `Red` active. +fn clip_group() -> (Session, LayerId) { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 60, "height": 40, "background": "#ffffff"})).unwrap(); + let fill = |s: &mut Session, name: &str, rect: Rect, color: [f32; 4]| { + s.execute("layer.new.layer", json!({"name": name})).unwrap(); + s.edit("Paint", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(rect, &color); + Ok(()) + }) + .unwrap(); + s.active().unwrap().active_layer.unwrap() + }; + fill(&mut s, "Masked", Rect::new(0, 20, 60, 40), [0.0, 0.6, 0.0, 1.0]); + let red = fill(&mut s, "Red", Rect::new(10, 10, 30, 30), [1.0, 0.0, 0.0, 1.0]); + fill(&mut s, "Top", Rect::new(20, 0, 50, 25), [0.0, 0.0, 1.0, 0.7]); + s.execute("layer.createClippingMask", json!({})).unwrap(); + s.execute("layer.select", json!({"layer": red.0})).unwrap(); + (s, red) +} + +fn names(s: &Session) -> Vec { + s.active().unwrap().doc.walk().into_iter().map(|(_, _, l)| l.name.clone()).collect() +} + +fn flat(s: &Session) -> Vec<[f32; 4]> { + photocraft_compose::flatten(&s.active().unwrap().doc).into_px() +} + +fn max_diff(a: &[[f32; 4]], b: &[[f32; 4]]) -> f32 { + a.iter().zip(b).flat_map(|(p, q)| (0..4).map(move |c| (p[c] - q[c]).abs())).fold(0.0, f32::max) +} + +fn undo_label(s: &Session) -> String { + s.active().unwrap().history.undo_label().unwrap_or_default().to_string() +} + +/// The merged layer's pixel at canvas `(x, y)`. +fn pixel(s: &Session, id: LayerId, x: i32, y: i32) -> Vec { + s.active().unwrap().doc.layer(id).unwrap().surface().unwrap().pixel(x, y) +} + +#[test] +fn ctrl_e_on_a_clip_base_merges_the_clipped_layers_into_it() { + let (mut s, red) = clip_group(); + let before = flat(&s); + let steps = s.active().unwrap().history.past_len(); + + s.execute("layer.mergeLayers", json!({})).unwrap(); + + assert!(!names(&s).contains(&"Top".to_string()), "Top is merged: {:?}", names(&s)); + assert!(names(&s).contains(&"Masked".to_string()), "Masked is untouched: {:?}", names(&s)); + let d = s.active().unwrap(); + let merged = d.doc.layer(red).expect("the result keeps the base's id"); + assert_eq!(merged.name, "Red"); + assert!(!merged.clipped); + assert_eq!(d.active_layer, Some(red)); + assert_eq!(d.history.past_len(), steps + 1, "one History state"); + assert_eq!(undo_label(&s), "Merge Clipping Mask"); + assert!(max_diff(&before, &flat(&s)) < 1e-3, "the composite does not change"); + + // Inside the base the blue is blended over the red; outside the base the clipped blue is gone. + let inside = pixel(&s, red, 25, 15); + assert!(inside[2] > inside[0] && inside[3] > 0.99, "{inside:?}"); + assert!(pixel(&s, red, 40, 5)[3] < 1e-3, "clipped pixels outside the base are dropped"); +} + +#[test] +fn the_result_keeps_the_bases_blend_mode_and_opacity() { + let (mut s, red) = clip_group(); + s.execute("layer.setProps", json!({"blend": "Multiply", "opacity": 0.6})).unwrap(); + let before = flat(&s); + + s.execute("layer.mergeLayers", json!({})).unwrap(); + + let merged = s.active().unwrap().doc.layer(red).unwrap().clone(); + assert_eq!(merged.blend, BlendMode::Multiply); + assert!((merged.opacity - 0.6).abs() < 1e-3, "{}", merged.opacity); + assert!(max_diff(&before, &flat(&s)) < 1e-3, "the composite does not change"); +} + +#[test] +fn a_layer_that_is_not_a_clip_base_still_merges_down() { + // The clipped layer itself, and a layer with nothing clipped to it. + for name in ["Top", "Masked"] { + let (mut s, _) = clip_group(); + let id = s.active().unwrap().doc.walk().into_iter().find(|(_, _, l)| l.name == name).unwrap().2.id; + s.execute("layer.select", json!({"layer": id.0})).unwrap(); + s.execute("layer.mergeLayers", json!({})).unwrap(); + assert_eq!(undo_label(&s), "Merge Down", "{name}"); + } +} + +/// Not measured in the issue: these keep today's Merge Down. +#[test] +fn a_base_with_a_layer_mask_or_inside_a_group_keeps_merge_down() { + let (mut s, _) = clip_group(); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + s.execute("layer.mergeLayers", json!({})).unwrap(); + assert_eq!(undo_label(&s), "Merge Down", "a base with a layer mask"); + + let (mut s, red) = clip_group(); + let masked = s.active().unwrap().doc.walk().into_iter().find(|(_, _, l)| l.name == "Masked").unwrap().2.id; + let top = s.active().unwrap().doc.walk().into_iter().find(|(_, _, l)| l.name == "Top").unwrap().2.id; + s.execute("layer.select", json!({"layers": [masked.0, red.0, top.0]})).unwrap(); + s.execute("layer.groupLayers", json!({})).unwrap(); + assert!(s.active().unwrap().doc.layer(top).unwrap().clipped, "Top is still clipped inside the group"); + s.execute("layer.select", json!({"layer": red.0})).unwrap(); + s.execute("layer.mergeLayers", json!({})).unwrap(); + assert_eq!(undo_label(&s), "Merge Down", "a base inside a group"); +} + +/// A base whose Fill, Blend If, Advanced Blending or excluded channels the merged layer could not carry keeps Merge +/// Down, so the composite is never changed by Merge Clipping Mask. +#[test] +fn a_base_with_settings_the_result_cannot_carry_keeps_merge_down() { + type Set = fn(&mut photocraft_doc::Layer); + let cases: [(&str, Set); 4] = [ + ("Fill 50 %", |l| l.fill_opacity = 0.5), + ("Blend If", |l| l.blend_if.ranges = vec![[photocraft_doc::BlendRange { black: [0, 0], white: [128, 128] }, photocraft_doc::BlendRange::FULL]]), + ("Blend Clipped Layers as Group off", |l| l.advanced.blend_clipped = false), + ("an excluded channel", |l| l.excluded_channels = 1), + ]; + for (case, set) in cases { + let (mut s, red) = clip_group(); + s.edit("Set", |doc, _| { + set(doc.layer_mut(red).unwrap()); + Ok(()) + }) + .unwrap(); + s.execute("layer.mergeLayers", json!({})).unwrap(); + assert_eq!(undo_label(&s), "Merge Down", "{case}"); + } +} diff --git a/crates/engine-core/src/cmd/layer_multi_cmds.rs b/crates/engine-core/src/cmd/layer_multi_cmds.rs index 4ce80a67f4f..bdc21ec4665 100644 --- a/crates/engine-core/src/cmd/layer_multi_cmds.rs +++ b/crates/engine-core/src/cmd/layer_multi_cmds.rs @@ -31,9 +31,9 @@ pub use selection::top_level; use selection::{doc_state, find_layers, select_all_layers, select_linked}; pub(crate) use selection::{mask_targets, recorded_step, reselect}; pub use selection::{select, selected, set_selection}; -pub use structure::deletion_neighbours; pub(crate) use structure::{check_group_depth, relink_copies}; pub use structure::{delete_selected, duplicate_selected, group_layers, set_visible_selected}; +pub use structure::{deletion_neighbours, merges_clipping_mask}; use structure::{link_layers, lock_layers, merge_layers, rename_layer, reverse}; // ---------- enabled predicates ---------- diff --git a/crates/engine-core/src/cmd/layer_multi_cmds/structure.rs b/crates/engine-core/src/cmd/layer_multi_cmds/structure.rs index 60ee42e5dbc..0adca724513 100644 --- a/crates/engine-core/src/cmd/layer_multi_cmds/structure.rs +++ b/crates/engine-core/src/cmd/layer_multi_cmds/structure.rs @@ -228,7 +228,13 @@ fn group_layers_with(s: &mut Session, p: &Value, ids: &[LayerId], from_layers: b pub(super) fn merge_layers(s: &mut Session) -> Result { let sel = selected(s); if sel.len() < 2 { - // ⌘E on a lone group is Photoshop's Merge Group (#3832); on a layer, Merge Down. + // ⌘E on a lone clip base is Merge Clipping Mask (#18481); on a lone group, Photoshop's Merge Group (#3832); on a + // layer, Merge Down. + if let Some(&id) = sel.first() + && s.active().is_some_and(|d| merges_clipping_mask(&d.doc, id)) + { + return merge_clipping_mask(s, id); + } if let Some(&id) = sel.first() && s.active().and_then(|d| d.doc.layer(id)).is_some_and(|l| matches!(l.content, LayerContent::Group(_))) { @@ -298,6 +304,66 @@ pub(super) fn merge_layers(s: &mut Session) -> Result { Ok(json!({ "layer": mid.0 })) } +/// `⌘E` on `id` alone is Merge Clipping Mask: a visible pixel-bearing top-level layer with layers clipped to it. A base +/// inside a group, with a layer or vector mask or effects, a group or an adjustment layer as the base, and a hidden base +/// were not measured (#18481) and keep Merge Down or Merge Group. So does a base whose Fill, Blend If, Advanced Blending +/// or excluded channels the merged layer could not carry without changing the composite (review of #18858). +pub fn merges_clipping_mask(doc: &Document, id: LayerId) -> bool { + let Some(l) = doc.layer(id) else { return false }; + doc.path_of(id).is_some_and(|p| p.len() == 1) + && l.visible + && l.mask.is_none() + && l.vector_mask.is_none() + && l.effects.items.is_empty() + && l.fill_opacity >= 1.0 + && l.blend_if.is_default() + && l.advanced.is_default() + && l.excluded_channels == 0 + && !matches!(l.content, LayerContent::Group(_) | LayerContent::Adjustment(_)) + && !crate::clip_group::clipped_to(doc, id).is_empty() +} + +/// Merge Clipping Mask: the base and the layers clipped to it become one layer with the base's id, name, place, blend mode, +/// opacity, locks, colour label and link. Clipped pixels are blended inside the base's pixels and dropped outside it, so +/// the composite does not change; hidden clipped layers are discarded, as Merge Layers does. +fn merge_clipping_mask(s: &mut Session, base_id: LayerId) -> Result { + s.edit("Merge Clipping Mask", |doc, active| { + let clipped = crate::clip_group::clipped_to(doc, base_id); + let base = doc.layer(base_id).ok_or(EngineError::NoLayer(base_id))?.clone(); + let format = doc.pixel_format(); + // The group alone, the base drawn plainly: its blend mode and opacity stay on the result. + let mut plain = base.clone(); + plain.blend = photocraft_doc::BlendMode::Normal; + plain.opacity = 1.0; + let mut solo = Document::new("merge", doc.size, format.mode, format.sample); + solo.icc_profile = doc.icc_profile.clone(); + let mut stack = vec![plain]; + stack.extend(clipped.iter().filter_map(|id| doc.layer(*id)).filter(|l| l.visible).cloned()); + solo.layers = stack.into(); + // A Background stays canvas-sized and opaque; any other layer keeps its pixels outside the canvas. + let pixels = if doc.is_background(base_id) { + crate::pixels::composite_layers(&solo, format, None) + } else { + crate::pixels::composite_layers_uncropped(&solo, PixelFormat::new(format.mode, format.sample, true)) + }; + let mut merged = Layer::new(base.name.clone(), LayerContent::Raster(pixels)); + merged.id = base_id; + merged.blend = base.blend; + merged.opacity = base.opacity; + merged.locks = base.locks; + merged.label = base.label; + merged.link_group = base.link_group; + for id in &clipped { + doc.remove(*id); + } + *doc.layer_mut(base_id).ok_or(EngineError::NoLayer(base_id))? = merged; + *active = Some(base_id); + Ok(()) + })?; + reselect(s, vec![base_id], Some(base_id)); + Ok(json!({ "layer": base_id.0 })) +} + /// Next visible layer row below the deleted target, then rows above in reverse order. /// Group headers precede their children in the UI, unlike Document::walk's storage order. pub fn deletion_neighbours(doc: &Document, target: LayerId) -> Vec { diff --git a/crates/engine-core/src/cmd/pattern_cmds.rs b/crates/engine-core/src/cmd/pattern_cmds.rs index 8a6e108e7e0..4ba1488a978 100644 --- a/crates/engine-core/src/cmd/pattern_cmds.rs +++ b/crates/engine-core/src/cmd/pattern_cmds.rs @@ -456,6 +456,33 @@ fn for_each_band(p: &Pattern, w: u32, h: u32, mut f: impl FnMut(&[[f32; 4]])) { } } +/// A layer mask is the edit target: the active pixel layer's or group's mask is targeted, the active layer is an +/// adjustment layer with a mask, which is what it edits, or every colour channel is hidden with no alpha channel shown, so +/// the mask is the picture (as the desktop's target rule reads it). A shown filter mask is not the layer mask. Define +/// Pattern and Define Brush Preset are greyed then (#18232). +pub fn layer_mask_targeted(s: &Session) -> bool { + let Some(st) = s.active() else { return false }; + let Some(layer) = st.active_layer.and_then(|id| st.doc.layer(id)).filter(|l| l.mask.is_some()) else { return false }; + if crate::mask_view_cmds::current(st).is_some_and(|v| v.filter) { + return false; + } + match st.channel_view.target { + crate::channel_cmds::ChannelTarget::LayerMask => true, + crate::channel_cmds::ChannelTarget::Composite if st.doc.quick_mask.is_none() => { + let view = &st.channel_view; + let colors_off = view.visible_colors(crate::channel_cmds::color_count(&st.doc)) == 0; + let alpha_on = (0..st.doc.channels.len()).any(|i| view.alpha_shown(i)); + matches!(layer.content, LayerContent::Adjustment(_)) || (colors_off && !alpha_on) + } + _ => false, + } +} + +fn can_define(s: &Session) -> std::result::Result<(), String> { + has_doc(s)?; + if layer_mask_targeted(s) { Err("a layer mask is the target".into()) } else { Ok(()) } +} + pub fn specs() -> Vec { vec![ CommandSpec { @@ -464,7 +491,7 @@ pub fn specs() -> Vec { menu: &["Edit"], shortcut: None, params: r##"{"name":text,"rect":[x0,y0,x1,y1]?} → {"pattern":id} (name: default the document's name numbered past the library's names; rect: default the selection bounds or else the canvas; added to the library from the visible composite)"##, - enabled: has_doc, + enabled: can_define, journal: true, run: define, }, diff --git a/crates/engine-core/src/doc_state.rs b/crates/engine-core/src/doc_state.rs index 836c5837b6e..8a5f7604c6e 100644 --- a/crates/engine-core/src/doc_state.rs +++ b/crates/engine-core/src/doc_state.rs @@ -412,6 +412,9 @@ pub struct ToolState { /// The pair Quick Mask put aside, with its CMYK roles: the Quick Mask pair outside Quick /// Mask, the pixel (or layer mask) pair inside it (#17490). pub quick_mask_aside: ([[f32; 4]; 2], CmykPair), + /// How many "Sampled Brush N" defaults Define Brush Preset stored in this session, which gives the next N. Deleting + /// or renaming those presets doesn't lower it, and is not saved to settings (#18228). + pub sampled_brushes: u32, } /// Native CMYK inks associated with each color role. @@ -565,6 +568,7 @@ impl Default for ToolState { cmyk_roles: [[None; 2]; 2], quick_mask_on: false, quick_mask_aside: (Self::MASK_COLORS, [None; 2]), + sampled_brushes: 0, } } } diff --git a/crates/engine-core/src/lib.rs b/crates/engine-core/src/lib.rs index d3aa9a715a7..2e4ee4c4139 100644 --- a/crates/engine-core/src/lib.rs +++ b/crates/engine-core/src/lib.rs @@ -309,6 +309,9 @@ pub struct Session { next_pending_preflight: u64, /// Shared native memory supervision, owned and stopped by the last session using it. scratch_runtime: Option, + /// The scratch disk and memory settings [`Session::apply_prefs`] last configured: an edit of + /// other preferences configures nothing again. + scratch_applied: Option, /// [`photocraft_raster::spill::epoch`] when History's byte limits were last applied: a /// scratch disk that pauses or resumes changes the limit ([`Session::sync_scratch_state`]). scratch_epoch: u64, diff --git a/crates/engine-core/src/prefs.rs b/crates/engine-core/src/prefs.rs index 76d893ed933..8d56154bb35 100644 --- a/crates/engine-core/src/prefs.rs +++ b/crates/engine-core/src/prefs.rs @@ -1902,7 +1902,11 @@ impl Session { /// missing-glyph protection. pub fn apply_prefs(&mut self) { self.scratch_runtime.get_or_insert_with(crate::scratch::Runtime::default); - crate::scratch::configure(self.prefs()); + let scratch = crate::scratch::Settings::of(self.prefs()); + if self.scratch_applied.as_ref() != Some(&scratch) { + crate::scratch::configure(&scratch); + self.scratch_applied = Some(scratch); + } self.scratch_epoch = photocraft_raster::spill::epoch(); let n = self.prefs().performance.history_states.max(1) as usize; let bytes = self.prefs().performance.history_cap_bytes(); diff --git a/crates/engine-core/src/scratch.rs b/crates/engine-core/src/scratch.rs index 9133f76f03b..6c46f158838 100644 --- a/crates/engine-core/src/scratch.rs +++ b/crates/engine-core/src/scratch.rs @@ -129,42 +129,101 @@ mod native { // If configure uses this query even once, it pauses for lack of room. This catches an // override that is missing or is installed after configuring the scratch directory. photocraft_raster::spill::set_volume_space_for_tests(|_| Some((0, 64 << 30))); - super::super::configure(&crate::prefs::Preferences::default()); + super::super::configure(&super::super::Settings::of(&crate::prefs::Preferences::default())); assert!(!photocraft_raster::spill::paused()); let room = (32_u64 << 30) - (64_u64 << 30) / 20; assert_eq!(photocraft_raster::spill::scratch_capacity(), Some(room - room / 64)); } + + /// A preference edit that changes neither Memory Usage nor the scratch disks configures + /// neither again: a dragged dialog remembers its place through a preference edit every + /// frame, and configuring took milliseconds each time. + #[test] + fn unrelated_preference_edits_leave_the_scratch_disk_alone() { + const CHILD: &str = "PHOTOCRAFT_SCRATCH_UNRELATED_EDIT_TEST_CHILD"; + if std::env::var_os(CHILD).is_none() { + let status = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "scratch::native::tests::unrelated_preference_edits_leave_the_scratch_disk_alone"]) + .env(CHILD, "1") + .status() + .unwrap(); + assert!(status.success(), "isolated scratch test failed: {status}"); + return; + } + + let mut session = crate::Session::new(); + // As at startup (`prefs_ui::startup`). + session.apply_prefs(); + let configured = photocraft_raster::memory::configuration_generation; + let before = configured(); + session.edit_prefs(|p| { + p.sections.insert("photocraft.test.window".into(), serde_json::json!({"x": 1})); + }); + assert_eq!(configured(), before, "a section edit configured the scratch disk again"); + session.edit_prefs(|p| p.performance.memory_usage_percent = Some(p.performance.memory_usage_percent.unwrap_or(70) - 10)); + assert!(configured() > before, "a Memory Usage edit must reach the memory budgets"); + } } } -pub(crate) fn configure(prefs: &Preferences) { +/// What [`configure`] reads from the preferences. An edit that leaves it the same leaves the +/// scratch disk and the memory budgets as they are ([`crate::Session::apply_prefs`]): configuring +/// them again re-measures memory, probes the scratch folder and restarts a paused disk's backoff, +/// which takes milliseconds, and preference edits come once per frame while a remembered window +/// is dragged. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct Settings { + percent: Option, + absolute_mb: u32, + /// The first enabled scratch disk. + #[cfg(not(target_arch = "wasm32"))] + dir: Option, + #[cfg(not(target_arch = "wasm32"))] + size_limit_mb: u32, + /// The tile budget's override (`PHOTOCRAFT_TILE_BUDGET_MB`), when set. + #[cfg(not(target_arch = "wasm32"))] + tile_override: Option, +} + +impl Settings { + pub(crate) fn of(prefs: &Preferences) -> Self { + Settings { + percent: prefs.performance.memory_usage_percent, + // The web build's cap applies here too (effective_memory_usage_mb). + absolute_mb: prefs.performance.effective_memory_usage_mb(), + #[cfg(not(target_arch = "wasm32"))] + dir: prefs + .scratch_disks + .disks + .iter() + .find(|d| d.enabled && !d.path.trim().is_empty()) + .map(|d| if d.path.trim() == "(system temp)" { std::env::temp_dir() } else { std::path::PathBuf::from(d.path.trim()) }), + #[cfg(not(target_arch = "wasm32"))] + size_limit_mb: prefs.scratch_disks.size_limit_mb, + #[cfg(not(target_arch = "wasm32"))] + tile_override: std::env::var_os("PHOTOCRAFT_TILE_BUDGET_MB").is_some().then(|| prefs.performance.tile_budget_bytes()), + } + } +} + +/// Configures the memory budgets and the scratch disk as `settings` say. +pub(crate) fn configure(settings: &Settings) { #[cfg(all(test, not(target_arch = "wasm32")))] photocraft_raster::spill::use_test_volume_space(); let budget = photocraft_raster::memory::configure(photocraft_raster::memory::Policy { - percent: prefs.performance.memory_usage_percent, - // The web build's cap applies here too (effective_memory_usage_mb). - absolute_bytes: u64::from(prefs.performance.effective_memory_usage_mb()).saturating_mul(1 << 20), + percent: settings.percent, + absolute_bytes: u64::from(settings.absolute_mb).saturating_mul(1 << 20), }); #[cfg(not(target_arch = "wasm32"))] { - let dir = prefs - .scratch_disks - .disks - .iter() - .find(|d| d.enabled && !d.path.trim().is_empty()) - .map(|d| if d.path.trim() == "(system temp)" { std::env::temp_dir() } else { std::path::PathBuf::from(d.path.trim()) }); // An unusable or full directory pauses eviction without dropping resident pixels and // is retried with backoff; History's byte limit applies meanwhile (sync_scratch_state). // The reason is exposed in ui.inspect and the application's status bar. - let tiles = if std::env::var_os("PHOTOCRAFT_TILE_BUDGET_MB").is_some() { - prefs.performance.tile_budget_bytes() - } else { - usize::try_from(budget.tile_bytes).unwrap_or(usize::MAX) - }; - let limit = prefs.scratch_disks.size_limit_mb; + let tiles = settings.tile_override.unwrap_or_else(|| usize::try_from(budget.tile_bytes).unwrap_or(usize::MAX)); + let limit = settings.size_limit_mb; photocraft_raster::spill::set_size_cap((limit > 0).then(|| u64::from(limit).saturating_mul(1 << 20))); - let _ = photocraft_raster::spill::configure(dir.as_deref(), tiles); + let _ = photocraft_raster::spill::configure(settings.dir.as_deref(), tiles); } #[cfg(target_arch = "wasm32")] - let _ = (prefs, budget); + let _ = budget; } diff --git a/crates/engine-core/src/shell_commands.rs b/crates/engine-core/src/shell_commands.rs index 718454fba30..08dc7b21df9 100644 --- a/crates/engine-core/src/shell_commands.rs +++ b/crates/engine-core/src/shell_commands.rs @@ -58,6 +58,7 @@ pub const SHELL_COMMANDS: &[(&str, &str, &[&str], Option<&str>)] = &[ ("view.zoomOut", "Zoom Out", &["View"], Some("Cmd+-")), ("view.fitOnScreen", "Fit on Screen", &["View"], Some("Cmd+0")), ("view.actualPixels", "100%", &["View"], Some("Cmd+1")), + ("view.actualSize", "Actual Size", &["View"], None), ("view.rotateView", "Rotate View", &[], None), ("view.rotateLeft", "Rotate View Left", &["View"], Some("Alt+Shift+,")), ("view.rotateRight", "Rotate View Right", &["View"], Some("Alt+Shift+.")), diff --git a/crates/engine-paint/src/cmd.rs b/crates/engine-paint/src/cmd.rs index 757472f0ae0..6d653b80628 100644 --- a/crates/engine-paint/src/cmd.rs +++ b/crates/engine-paint/src/cmd.rs @@ -19,6 +19,8 @@ mod gradient_alpha_method_tests; mod gradient_behind_mode_tests; #[cfg(test)] mod gradient_mask_history_name_tests; +#[cfg(test)] +mod gradient_mask_opacity_half_tests; pub mod paint_cmds; pub mod pick_cmds; pub mod redeye_cmds; diff --git a/crates/engine-paint/src/cmd/brush_cmds.rs b/crates/engine-paint/src/cmd/brush_cmds.rs index e07b0102ede..6cc12942b3b 100644 --- a/crates/engine-paint/src/cmd/brush_cmds.rs +++ b/crates/engine-paint/src/cmd/brush_cmds.rs @@ -1166,6 +1166,9 @@ fn presets_set_current(s: &mut Session, p: &Value) -> Result { fn has_selection_and_pixels(s: &Session) -> std::result::Result<(), String> { let d = s.active().ok_or("no document")?; + if crate::pattern_cmds::layer_mask_targeted(s) { + return Err("a layer mask is the target".into()); + } // The area the command reads (selection, else canvas) is limited, not just the painted // extent, like Photoshop (#14275). let area = d.doc.selection.as_ref().map_or_else(|| d.doc.bounds(), |sel| sel.content_bounds().intersect(&d.doc.bounds())); @@ -1706,3 +1709,6 @@ mod filter_mask_stroke_tests; #[cfg(test)] mod define_brush_size_limit_tests; + +#[cfg(test)] +mod define_brush_mask_target_tests; diff --git a/crates/engine-paint/src/cmd/brush_cmds/define_brush_mask_target_tests.rs b/crates/engine-paint/src/cmd/brush_cmds/define_brush_mask_target_tests.rs new file mode 100644 index 00000000000..76a76fdecab --- /dev/null +++ b/crates/engine-paint/src/cmd/brush_cmds/define_brush_mask_target_tests.rs @@ -0,0 +1,150 @@ +//! #18232: Define Brush Preset (and the brush command it runs) and Define Pattern are greyed and refused while a layer +//! mask is the edit target: a pixel layer's or a group's mask targeted, or an adjustment layer with its mask. Targeting +//! the composite again, or deleting the adjustment layer's mask, makes them available. Other targets and layer kinds +//! keep today's gates. + +use super::*; + +const COMMANDS: [&str; 3] = ["edit.defineBrushPreset", "brush.defineFromSelection", "edit.definePattern"]; + +/// A white 60 x 40 document with a new layer holding a black rectangle, the layer active. +fn document() -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 60, "height": 40, "background": "#ffffff"})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Tip"})).unwrap(); + s.edit("BrushSrc", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(10, 10, 30, 25), &[0.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + s +} + +fn target(s: &mut Session, channel: Value) { + s.execute("channel.target", json!({"channel": channel})).unwrap(); +} + +/// The brush, the brush presets, the pattern library and the document, to show that a refusal changes none of them. +fn snapshot(s: &Session) -> (BrushSettings, Vec, usize, usize) { + let patterns = s.patterns.items.len(); + ((*s.tools.brush).clone(), s.tools.presets.to_vec(), patterns, s.active().unwrap().history.past_len()) +} + +fn assert_refused(s: &mut Session, case: &str) { + for command in COMMANDS { + assert!(s.disabled_reason(command).is_some(), "{case}: {command} stays enabled"); + let before = snapshot(s); + assert!(s.execute(command, json!({"name": "Refused"})).is_err(), "{case}: {command} ran"); + assert!(snapshot(s) == before, "{case}: {command} changed the brush, the presets, the patterns or the History"); + } +} + +fn assert_enabled(s: &mut Session, case: &str) { + for command in COMMANDS { + assert_eq!(s.disabled_reason(command), None, "{case}: {command}"); + } +} + +#[test] +fn a_pixel_layers_targeted_mask_greys_them() { + for enabled in [true, false] { + let mut s = document(); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + if !enabled { + s.execute("layer.layerMask.enabled", json!({"enabled": false})).unwrap(); + } + target(&mut s, json!("mask")); + assert_refused(&mut s, if enabled { "a pixel layer's mask" } else { "a pixel layer's disabled mask" }); + } +} + +#[test] +fn a_groups_targeted_mask_greys_them() { + let mut s = document(); + s.execute("layer.groupLayers", json!({})).unwrap(); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + target(&mut s, json!("mask")); + assert_refused(&mut s, "a group's mask"); +} + +#[test] +fn a_new_adjustment_layer_greys_them_until_its_mask_is_deleted() { + let mut s = document(); + s.execute("layer.newAdjustmentLayer.invert", json!({})).unwrap(); + assert_refused(&mut s, "a new adjustment layer"); + s.execute("layer.layerMask.delete", json!({})).unwrap(); + assert_enabled(&mut s, "the adjustment layer without its mask"); +} + +/// Back on the composite, the items work as before and make the same tip as a document that never targeted a mask. +#[test] +fn targeting_the_composite_again_enables_them_with_the_same_tip() { + let mut plain = document(); + plain.execute("layer.layerMask.revealAll", json!({})).unwrap(); + target(&mut plain, json!("composite")); + plain.execute("brush.defineFromSelection", json!({"name": "Tip"})).unwrap(); + + let mut s = document(); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + target(&mut s, json!("mask")); + assert_refused(&mut s, "the mask"); + target(&mut s, json!("composite")); + assert_enabled(&mut s, "the composite again"); + s.execute("brush.defineFromSelection", json!({"name": "Tip"})).unwrap(); + assert!(s.tools.brush.tip == plain.tools.brush.tip, "the tip is the one made without a mask target"); + s.execute("edit.definePattern", json!({"name": "Pattern"})).unwrap(); +} + +/// With every colour channel hidden and no alpha channel shown, the mask is the picture and the target; showing a colour +/// channel or an alpha channel again makes the items available. +#[test] +fn hiding_every_colour_channel_greys_them_on_a_masked_layer() { + let mut s = document(); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + target(&mut s, json!("composite")); + s.execute("channel.setVisible", json!({"channel": "composite", "visible": false})).unwrap(); + assert_refused(&mut s, "every colour channel hidden"); + s.execute("channel.setVisible", json!({"channel": {"color": 0}, "visible": true})).unwrap(); + assert_enabled(&mut s, "one colour channel shown again"); + + s.execute("channel.new", json!({})).unwrap(); + target(&mut s, json!("composite")); + s.execute("channel.setVisible", json!({"channel": "composite", "visible": false})).unwrap(); + s.execute("channel.setVisible", json!({"channel": {"alpha": 0}, "visible": true})).unwrap(); + assert_enabled(&mut s, "an alpha channel shown"); + + // Without a mask there is nothing else to target. + let mut s = document(); + s.execute("channel.setVisible", json!({"channel": "composite", "visible": false})).unwrap(); + assert_enabled(&mut s, "no mask, every colour channel hidden"); +} + +/// Not a layer mask target: these keep today's gates. +#[test] +fn other_targets_and_layer_kinds_stay_enabled() { + // A pixel layer with a mask, the composite targeted. + let mut s = document(); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + assert_enabled(&mut s, "a masked pixel layer, composite targeted"); + + // An alpha channel, and Quick Mask. + s.execute("channel.new", json!({})).unwrap(); + target(&mut s, json!({"alpha": 0})); + assert_enabled(&mut s, "an alpha channel"); + target(&mut s, json!("composite")); + s.execute("select.editInQuickMaskMode", json!({})).unwrap(); + assert_enabled(&mut s, "Quick Mask"); + + // A locked layer, a group, the Background and a Solid Color fill layer with its mask. + let mut s = document(); + s.execute("layer.setProps", json!({"locks": {"all": true}})).unwrap(); + assert_enabled(&mut s, "a locked layer"); + let mut s = document(); + s.execute("layer.groupLayers", json!({})).unwrap(); + assert_enabled(&mut s, "a group"); + let background = s.active().unwrap().doc.layers[0].id; + s.execute("layer.select", json!({"layer": background.0})).unwrap(); + assert_enabled(&mut s, "the Background"); + s.execute("layer.newFillLayer.solidColor", json!({"color": "#336699"})).unwrap(); + assert_enabled(&mut s, "a Solid Color fill layer"); +} diff --git a/crates/engine-paint/src/cmd/gradient_mask_opacity_half_tests.rs b/crates/engine-paint/src/cmd/gradient_mask_opacity_half_tests.rs new file mode 100644 index 00000000000..fce981d0ef3 --- /dev/null +++ b/crates/engine-paint/src/cmd/gradient_mask_opacity_half_tests.rs @@ -0,0 +1,85 @@ +//! #18669: at 50% opacity a gradient covers 128/255 of a layer mask. + +use photocraft_raster::Surface; +use serde_json::{Value, json}; + +use crate::Session; + +fn document(mode: &str, depth: u32) -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 64, "height": 8, "mode": mode, "depth": depth, "background": "transparent"})).unwrap(); + s +} + +fn gradient(opacity: f64, target: Value, method: Option<&str>) -> Value { + let mut p = json!({"from": [8, 4], "to": [56, 4], "colors": ["#000000", "#ffffff"], "opacity": opacity, "target": target, "dither": false}); + if let Some(method) = method { + p["method"] = json!(method); + } + p +} + +fn target<'a>(s: &'a Session, p: &Value) -> &'a Surface { + let state = s.active().unwrap(); + crate::channel_cmds::read_target_surface(&state.doc, state.active_layer, p).unwrap() +} + +fn layer_mask_row(mode: &str, depth: u32, opacity: f64, method: Option<&str>) -> [f32; 3] { + let mut s = document(mode, depth); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + let p = gradient(opacity, json!("mask"), method); + s.execute("paint.gradient", p.clone()).unwrap(); + [4, 32, 60].map(|x| target(&s, &p).pixel(x, 4)[0]) +} + +#[test] +fn half_opacity_leaves_127_levels_of_white_on_the_layer_mask() { + for (mode, depth, step) in [ + ("rgb", 8, 1.0 / 255.0), + ("rgb", 16, 1.0 / 65535.0), + ("rgb", 32, 0.0), + ("gray", 8, 1.0 / 255.0), + ("gray", 16, 1.0 / 65535.0), + ("gray", 32, 0.0), + ("cmyk", 8, 1.0 / 255.0), + ("lab", 8, 1.0 / 255.0), + ] { + // The desktop dispatches the Classic gradient without a method. The report used Smooth. + for method in [None, Some("smooth")] { + let case = format!("{mode}/{depth} {method:?}"); + let [black, middle, white] = layer_mask_row(mode, depth, 50.0, method); + let [full_black, full_middle, full_white] = layer_mask_row(mode, depth, 100.0, method); + assert_eq!(full_black, 0.0, "{case} at full opacity"); + assert!((full_white - 1.0).abs() <= 0.00001, "{case}: white end at full opacity {full_white}"); + assert!((black - 127.0 / 255.0).abs() <= 0.5 * step + 0.00001, "{case}: black end left {black} white"); + let expected_middle = 1.0 - (1.0 - full_middle) * (128.0 / 255.0); + assert!((middle - expected_middle).abs() <= step + 0.00001, "{case}: ramp midpoint {middle}, expected {expected_middle}"); + assert!((white - 1.0).abs() <= 0.00001, "{case}: white end left {white} white"); + } + } +} + +#[test] +fn other_opacity_and_non_layer_mask_targets_keep_the_requested_coverage() { + // Include a value that rounds to 50% after the command converts to f32. + for opacity in [49.9, 50.000_000_1] { + let [black, _, _] = layer_mask_row("rgb", 32, opacity, Some("smooth")); + assert!((f64::from(black) - (1.0 - opacity / 100.0)).abs() < 0.00001, "{opacity}% opacity left {black} white"); + } + + let mut s = document("rgb", 32); + let pixels = gradient(50.0, json!("pixels"), Some("smooth")); + s.execute("paint.gradient", pixels.clone()).unwrap(); + assert!((target(&s, &pixels).pixel(4, 4)[3] - 0.5).abs() < 0.00001, "pixel coverage"); + + s.execute("channel.new", json!({"fill": "white"})).unwrap(); + let alpha = gradient(50.0, json!({"channel": 0}), Some("smooth")); + s.execute("paint.gradient", alpha.clone()).unwrap(); + assert!((target(&s, &alpha).pixel(4, 4)[0] - 0.5).abs() < 0.00001, "saved alpha channel"); + + s.execute("select.all", json!({})).unwrap(); + s.execute("select.editInQuickMaskMode", json!({"on": true})).unwrap(); + let quick_mask = gradient(50.0, json!("quickMask"), Some("smooth")); + s.execute("paint.gradient", quick_mask.clone()).unwrap(); + assert!((target(&s, &quick_mask).pixel(4, 4)[0] - 0.5).abs() < 0.00001, "Quick Mask"); +} diff --git a/crates/engine-paint/src/cmd/gradient_opacity_step_tests.rs b/crates/engine-paint/src/cmd/gradient_opacity_step_tests.rs index 25c7f82dab0..2f4e353fef8 100644 --- a/crates/engine-paint/src/cmd/gradient_opacity_step_tests.rs +++ b/crates/engine-paint/src/cmd/gradient_opacity_step_tests.rs @@ -80,12 +80,12 @@ fn only_explicit_classic_uses_the_half_opacity_step() { } #[test] -fn the_half_opacity_pixel_step_does_not_change_layer_masks() { - let mut s = document("rgb", 32); +fn the_half_opacity_pixel_step_does_not_change_deep_cmyk_layer_masks() { + let mut s = document("cmyk", 16); s.execute("layer.layerMask.revealAll", json!({})).unwrap(); s.execute("paint.gradient", json!({"from": [2, 3], "to": [9, 3], "colors": ["#000000", "#ffffff"], "opacity": 50, "target": "mask", "dither": false})) .unwrap(); let state = s.active().unwrap(); let mask = &state.doc.layer(state.active_layer.unwrap()).unwrap().mask.as_ref().unwrap().surface; - assert_eq!((mask.pixel(2, 3)[0] * 255.0).round(), 128.0); + assert_eq!((mask.pixel(2, 3)[0] * 65535.0).round(), 32768.0); } diff --git a/crates/engine-paint/src/cmd/paint_cmds.rs b/crates/engine-paint/src/cmd/paint_cmds.rs index 73a42f4eeb9..53a8ca04183 100644 --- a/crates/engine-paint/src/cmd/paint_cmds.rs +++ b/crates/engine-paint/src/cmd/paint_cmds.rs @@ -221,12 +221,18 @@ fn gradient(s: &mut Session, p: &Value) -> Result { let dither = b(p, "dither", true); // Photoshop dithers gradients by default (reduces banding). let layer = if p.get("layer").is_some() { Some(crate::commands::layer_param(s, p)?) } else { s.active().and_then(|st| st.active_layer) }; s.edit(step_name(p), |doc, _| { - // At the measured Classic 50% setting, deep RGB and 16-bit CMYK pixels use 8-bit source coverage. - let opacity = if target == crate::channel_cmds::Target::Pixels - && (method_param.is_none() || method == Some(photocraft_io::GradientMethod::Classic)) - && p.get("opacity").and_then(Value::as_f64) == Some(50.0) - && matches!((doc.mode, doc.depth), (ColorMode::Rgb, SampleType::U16 | SampleType::F32) | (ColorMode::Cmyk, SampleType::U16)) - { + // The measured 50% setting uses 8-bit source coverage for these layer masks and Classic pixel gradients. + let opacity = if p.get("opacity").and_then(Value::as_f64) == Some(50.0) + && match target { + crate::channel_cmds::Target::Mask => { + matches!((doc.mode, doc.depth), (ColorMode::Rgb | ColorMode::Grayscale, _) | (ColorMode::Cmyk | ColorMode::Lab, SampleType::U8)) + } + crate::channel_cmds::Target::Pixels => { + (method_param.is_none() || method == Some(photocraft_io::GradientMethod::Classic)) + && matches!((doc.mode, doc.depth), (ColorMode::Rgb, SampleType::U16 | SampleType::F32) | (ColorMode::Cmyk, SampleType::U16)) + } + _ => false, + } { 128.0 / 255.0 } else { opacity diff --git a/crates/engine/tests/it/background_from_layer_clip_base.rs b/crates/engine/tests/it/background_from_layer_clip_base.rs new file mode 100644 index 00000000000..151eacc7160 --- /dev/null +++ b/crates/engine/tests/it/background_from_layer_clip_base.rs @@ -0,0 +1,80 @@ +//! Background from Layer keeps a single clipped layer on its original base (#17307). + +use photocraft_doc::LayerId; +use photocraft_engine::Session; +use serde_json::json; + +const CONVERT: &str = "layer.new.backgroundFromLayer"; + +fn active(session: &Session) -> LayerId { + session.active().unwrap().active_layer.unwrap() +} + +fn order(session: &Session) -> Vec { + session.active().unwrap().doc.layers.iter().map(|layer| layer.id).collect() +} + +fn stack() -> (Session, [LayerId; 7]) { + let mut session = Session::new(); + session.execute("file.new", json!({"width": 200, "height": 150, "background": "transparent"})).unwrap(); + let base = active(&session); + session.execute("select.rect", json!({"x": 0, "y": 0, "width": 16, "height": 150})).unwrap(); + session.execute("edit.fill", json!({"color": "#808080"})).unwrap(); + session.execute("select.deselect", json!({})).unwrap(); + session.execute("layer.new.layer", json!({"name": "SO"})).unwrap(); + session.execute("select.rect", json!({"x": 20, "y": 20, "width": 40, "height": 40})).unwrap(); + session.execute("edit.fill", json!({"color": "#c81e1e"})).unwrap(); + session.execute("select.deselect", json!({})).unwrap(); + session.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + let smart = active(&session); + session.execute("layer.new.layer", json!({"name": "Clipped"})).unwrap(); + let clipped = active(&session); + session.execute("edit.fill", json!({"color": "#1e1ec8"})).unwrap(); + session.execute("layer.setProps", json!({"layer": clipped.0, "clipped": true})).unwrap(); + session.execute("layer.newAdjustmentLayer.levels", json!({})).unwrap(); + let adjustment = active(&session); + session.execute("layer.newFillLayer.solidColor", json!({"color": "#4080c0"})).unwrap(); + let fill = active(&session); + session.execute("layer.setProps", json!({"layer": fill.0, "opacity": 0.5})).unwrap(); + let shape = session.execute("shape.create", json!({"kind": "rect", "rect": [80, 60, 100, 80], "fill": "#308020"})).unwrap(); + let shape = LayerId(shape["layer"].as_u64().unwrap()); + session.execute("layer.select", json!({"layer": shape.0})).unwrap(); + session.execute("layer.new.layer", json!({"name": "Off"})).unwrap(); + let off = active(&session); + let ids = [base, smart, clipped, adjustment, fill, shape, off]; + assert_eq!(order(&session), ids); + (session, ids) +} + +#[test] +fn converting_a_clipping_base_moves_its_clip_and_one_undo_restores_the_tree() { + let (mut session, [base, smart, clip, adjustment, fill, shape, off]) = stack(); + session.execute("layer.select", json!({"layer": smart.0})).unwrap(); + let before = session.active().unwrap().history.past_len(); + session.execute(CONVERT, json!({})).unwrap(); + assert_eq!(order(&session), [smart, clip, base, adjustment, fill, shape, off]); + let doc = &session.active().unwrap().doc; + assert!(doc.is_background(smart)); + assert!(doc.layer(clip).unwrap().clipped); + assert_eq!(active(&session), smart); + assert_eq!(session.active().unwrap().history.past_len(), before + 1); + session.execute("history.undo", json!({})).unwrap(); + assert_eq!(order(&session), [base, smart, clip, adjustment, fill, shape, off]); + let doc = &session.active().unwrap().doc; + assert!(doc.background().is_none()); + assert!(doc.layer(clip).unwrap().clipped); +} + +#[test] +fn converting_an_unclipped_layer_or_the_clip_itself_keeps_other_layers_in_order() { + for convert_clip in [false, true] { + let (mut session, [base, smart, clip, adjustment, fill, shape, off]) = stack(); + let target = if convert_clip { clip } else { fill }; + session.execute(CONVERT, json!({"layer": target.0})).unwrap(); + let expected = if convert_clip { [clip, base, smart, adjustment, fill, shape, off] } else { [fill, base, smart, clip, adjustment, shape, off] }; + assert_eq!(order(&session), expected); + let doc = &session.active().unwrap().doc; + assert!(doc.is_background(target)); + assert_eq!(doc.layer(clip).unwrap().clipped, !convert_clip); + } +} diff --git a/crates/engine/tests/it/define_brush_sampled_number.rs b/crates/engine/tests/it/define_brush_sampled_number.rs new file mode 100644 index 00000000000..d082a662820 --- /dev/null +++ b/crates/engine/tests/it/define_brush_sampled_number.rs @@ -0,0 +1,97 @@ +//! #18228 (Edit › Define Brush Preset runs the brush command of `photocraft-engine-paint`, so this runs here): Define Brush Preset's "Sampled Brush N" default counts the defaults stored in this session. Deleting or +//! renaming presets does not lower N, and a preset with such a name from elsewhere (a typed name, an imported set) does +//! not raise it, but N skips a number such a preset already uses instead of replacing that preset. A call that stores +//! nothing leaves N as it is. + +use serde_json::{Value, json}; + +use photocraft_engine::Session; + +const DEFINE: &str = "edit.defineBrushPreset"; + +/// Opens a new white document with a black rectangle on a layer, ready for Define Brush Preset. +fn new_document(s: &mut Session) { + s.execute("file.new", json!({"width": 40, "height": 30, "background": "#ffffff"})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.edit("BrushSrc", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(5, 5, 20, 15), &[0.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); +} + +/// Defines a brush with `params` and returns the name it was stored under. +fn define(s: &mut Session, params: Value) -> String { + s.execute(DEFINE, params).unwrap(); + s.tools.current_preset.clone().expect("the new preset is the current brush") +} + +fn session() -> Session { + let mut s = Session::new(); + new_document(&mut s); + s +} + +#[test] +fn each_stored_default_raises_the_number() { + let mut s = session(); + let mut names = vec![define(&mut s, json!({}))]; + for _ in 0..2 { + new_document(&mut s); + names.push(define(&mut s, json!({}))); + } + assert_eq!(names, ["Sampled Brush 1", "Sampled Brush 2", "Sampled Brush 3"]); +} + +#[test] +fn deleting_or_renaming_the_presets_does_not_lower_it() { + let mut s = session(); + let names: Vec = (0..3).map(|_| define(&mut s, json!({}))).collect(); + for name in &names { + s.execute("brush.presets.delete", json!({"name": name})).unwrap(); + } + assert_eq!(define(&mut s, json!({})), "Sampled Brush 4", "after deleting presets 1-3"); + + let mut s = session(); + let first = define(&mut s, json!({})); + s.execute("brush.presets.rename", json!({"name": first, "newName": "Renamed"})).unwrap(); + assert_eq!(define(&mut s, json!({})), "Sampled Brush 2", "after renaming preset 1"); +} + +/// A preset named "Sampled Brush …" that the default did not make, such as a typed name, does not raise the number. +#[test] +fn a_typed_sampled_brush_name_does_not_raise_it() { + let mut s = session(); + assert_eq!(define(&mut s, json!({"name": "Sampled Brush 7"})), "Sampled Brush 7"); + assert_eq!(define(&mut s, json!({})), "Sampled Brush 1", "the first default"); +} + +/// The default never takes a name a preset already has: storing under it would replace that preset's tip. +#[test] +fn a_taken_number_is_skipped_and_the_preset_is_kept() { + let mut s = session(); + let user_presets = |s: &Session| s.tools.presets.iter().filter(|b| !b.builtin).map(|b| b.name.clone()).collect::>(); + define(&mut s, json!({"name": "Sampled Brush 1"})); + let first = define(&mut s, json!({})); + assert_ne!(first, "Sampled Brush 1", "the typed preset's name"); + assert_eq!(user_presets(&s).len(), 2, "both presets are kept: {:?}", user_presets(&s)); + let second = define(&mut s, json!({})); + assert!(![first.as_str(), "Sampled Brush 1"].contains(&second.as_str()), "{second}"); + assert_eq!(user_presets(&s).len(), 3, "{:?}", user_presets(&s)); + + // The store matches names ignoring case, so a typed "sampled brush 1" is taken too. + let mut s = session(); + define(&mut s, json!({"name": "sampled brush 1"})); + let first = define(&mut s, json!({})); + assert!(!first.eq_ignore_ascii_case("sampled brush 1"), "{first}"); + assert_eq!(user_presets(&s).len(), 2, "{:?}", user_presets(&s)); +} + +/// A call that stores no preset leaves the number as it is. +#[test] +fn a_refused_call_does_not_raise_it() { + let mut s = Session::new(); + assert!(s.execute(DEFINE, json!({})).is_err(), "no document"); + new_document(&mut s); + assert_eq!(define(&mut s, json!({})), "Sampled Brush 1"); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 74e8fba6dd7..fee7cd48973 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -37,6 +37,7 @@ mod atn_video_frames; mod auto_blend_layer_kinds; mod average_smart; mod background_and_mask_depth; +mod background_from_layer_clip_base; mod background_from_layer_grayscale; mod background_from_layer_history_name; mod background_from_layer_multi_select; @@ -66,6 +67,7 @@ mod crop_content_aware_layers; mod crop_delete_off_background; mod csh_import; mod current_affinity_artboards; +mod define_brush_sampled_number; mod duplicate_layer_comps; mod duplicate_slices; mod duplicate_variables; diff --git a/crates/format/tests/it/autosave.rs b/crates/format/tests/it/autosave.rs index f6fb88343a2..7627348743d 100644 --- a/crates/format/tests/it/autosave.rs +++ b/crates/format/tests/it/autosave.rs @@ -340,43 +340,38 @@ fn a_listing_during_an_autosave_sees_the_entry_exactly_once() { let dir = temp_dir("listing-during-autosave"); let doc = Document::new("Busy", photocraft_doc::Size { width: 4, height: 4 }, ColorMode::Rgb, SampleType::U8); save_once(&dir, "busy", doc.clone()); - let done = Arc::new(std::sync::atomic::AtomicBool::new(false)); - let writer = { - let (dir, done) = (dir.clone(), done.clone()); - std::thread::spawn(move || { - // Sets `done` however the thread ends, so a failing writer stops the listing loop - // and `join` reports its panic instead of the test hanging. - struct SetOnDrop(Arc); - impl Drop for SetOnDrop { - fn drop(&mut self) { - self.0.store(true, std::sync::atomic::Ordering::SeqCst); - } - } - let _done = SetOnDrop(done); - let saver = Autosaver::new(&dir, "busy"); - for revision in 2..=200 { - saver.request(Arc::new(doc.clone()), revision, None, SaveOptions::default()); - // Wait for this write, so every revision replaces the sidecar once. - let completed = loop { - let completed = saver.take_completed(); - if !completed.is_empty() { - break completed; - } - std::thread::yield_now(); - }; - assert!(completed.iter().all(|(_, result)| result.is_ok()), "revision {revision}: {completed:?}"); - } - saver.flush() - }) - }; - let mut listings = 0u32; - while !done.load(std::sync::atomic::Ordering::SeqCst) { + let doc = Arc::new(doc); + let saver = Autosaver::new(&dir, "busy"); + let listed_revision = || { let entries = list_recovery(&dir); - let keys: Vec<&str> = entries.iter().map(|e| e.info.key.as_str()).collect(); - assert_eq!(keys, ["busy"], "listing {listings} during an autosave: {entries:?}"); - listings += 1; + let [entry] = entries.as_slice() else { panic!("expected one entry during autosave: {entries:?}") }; + assert_eq!(entry.info.key, "busy"); + entry.info.revision + }; + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5 * 60); + // Each replacement is another opportunity to observe a transient missing sidecar. + for revision in 2..=200 { + saver.request_checked(doc.clone(), revision, None, SaveOptions::default()).unwrap(); + loop { + let completed = saver.take_completed(); + // List on this thread while the autosave worker writes. The preceding sidecar or + // its replacement supplies the revision. A sidecar-less fallback reports zero. + let listed = listed_revision(); + match completed.as_slice() { + [] => { + assert!((revision - 1..=revision).contains(&listed), "listed revision {listed} while writing {revision}"); + assert!(std::time::Instant::now() < deadline, "autosave did not complete revision {revision}"); + } + [(written, result)] => { + assert_eq!(*written, revision); + result.as_ref().unwrap(); + assert_eq!(listed, revision, "the completed replacement is visible"); + break; + } + _ => panic!("expected one completed write: {completed:?}"), + } + } } - assert!(writer.join().unwrap().is_some_and(|r| r.is_ok())); - assert!(listings > 0); + assert!(saver.flush().is_some_and(|r| r.is_ok())); std::fs::remove_dir_all(dir).unwrap(); } diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 647e7decb93..68e4fb0815b 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -69,7 +69,14 @@ sys-locale = "=0.3.2" # symbol (`i18n::decimal_separator`, a registry read): the safe binding the desktop app already # uses, pinned to the same version. [target.'cfg(target_os = "windows")'.dependencies] -winsafe = { version = "=0.0.29", default-features = false, features = ["kernel", "dxgi", "advapi"] } +winsafe = { version = "=0.0.29", default-features = false, features = ["kernel", "dxgi", "advapi", "user"] } + +# Safe physical display dimensions for View > Actual Size. Both are already in the lockfile. +[target.'cfg(target_os = "macos")'.dependencies] +core-graphics = "=0.23.2" + +[target.'cfg(target_os = "linux")'.dependencies] +x11rb = { version = "=0.13.2", features = ["randr"] } [dev-dependencies] photocraft-io = { workspace = true, features = ["testgen"] } diff --git a/crates/ui-egui/src/app/framework.rs b/crates/ui-egui/src/app/framework.rs index 744e8358f8a..ea8e63a4868 100644 --- a/crates/ui-egui/src/app/framework.rs +++ b/crates/ui-egui/src/app/framework.rs @@ -831,8 +831,11 @@ impl PrefSections { .filter_map(|key| Some((key.clone(), serde_json::to_value(t.tables.get(key)?).ok()?))) .filter(|(key, value)| session.prefs().sections.get(key) != Some(value)) .collect(); + // Remembered, not a settings edit: no view reads the sections back from the preferences (the components + // read them here), so the panels keep their versions and the engine applies nothing. A dialog that + // remembers its place writes on every frame of a drag. if !changed.is_empty() { - session.edit_prefs(|p| p.sections.extend(changed)); + session.prefs.remember(|p| p.sections.extend(changed)); } for key in written { let rev = session.section_rev(&key); @@ -986,6 +989,19 @@ mod tests { assert_eq!(store.read("one"), None); } + /// A component's section write is saved, but is no settings edit: the panels' versions hold the settings revision, + /// so an edit would rebuild every panel on each frame a dialog that remembers its place is dragged. + #[test] + fn a_section_write_is_saved_without_a_settings_edit() { + let store = PrefSections::default(); + let mut session = Session::new(); + let (saved, settings) = (session.prefs.rev(), session.prefs.settings_rev()); + store.write("one", table(1)); + store.sync(&mut session); + assert_ne!(session.prefs.rev(), saved, "the write reaches the saved preferences"); + assert_eq!(session.prefs.settings_rev(), settings, "the panels keep their versions"); + } + /// Every theme PhotoCraft has a palette for names a framework built-in. #[test] fn every_palette_theme_is_a_builtin() { diff --git a/crates/ui-egui/src/canvas/blend_viewport_gpu_tests.rs b/crates/ui-egui/src/canvas/blend_viewport_gpu_tests.rs index e3297baeee4..ec81aeb9956 100644 --- a/crates/ui-egui/src/canvas/blend_viewport_gpu_tests.rs +++ b/crates/ui-egui/src/canvas/blend_viewport_gpu_tests.rs @@ -36,24 +36,23 @@ fn blend_hover_pattern_tiles_and_multiple_views_reuse_current_pixels() { let Some(rs) = render_state() else { return }; let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); app.set_wgpu(rs); - // Half the 1024 × 768 canvas these views were first written for (see `check_blend_viewport`): `a` still runs off - // the right edge and `b` still lies apart from it. - app.run("file.new", json!({"width":512,"height":384,"background":"#336699"})).unwrap(); + // One view crosses the right edge; the other sits apart from it. The + // intervening pixels still have to be refreshed when Pattern Preview opens. + app.run("file.new", json!({"width":256,"height":192,"background":"#336699"})).unwrap(); let layer = app.run("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap(); app.run("edit.fill", json!({"color":"#cc8844"})).unwrap(); let ctx = app.ctx().clone(); - let a = DRect::new(362, 100, 662, 250); - let b = DRect::new(0, 100, 150, 250); + let a = DRect::new(181, 50, 331, 125); + let b = DRect::new(0, 50, 75, 125); assert!(ensure_gpu(&mut app, &ctx, 0, a, None)); app.ui.view.pattern_preview = true; crate::blend_preview::hover(&mut app, &[photocraft_doc::LayerId(layer)], Some(BlendMode::Multiply)); assert!(ensure_gpu(&mut app, &ctx, 0, a, None)); - assert_visible_pixels(&mut app, b); let bounds = app.session.active().unwrap().doc.bounds(); - assert_visible_pixels(&mut app, bounds); + assert_visible_pixels(&mut app, &[bounds]); crate::blend_preview::hover(&mut app, &[photocraft_doc::LayerId(layer)], None); assert!(ensure_gpu(&mut app, &ctx, 0, a, None)); - assert_visible_pixels(&mut app, bounds); + assert_visible_pixels(&mut app, &[bounds]); app.ui.view.pattern_preview = false; for mode in [BlendMode::Multiply, BlendMode::Screen] { @@ -64,16 +63,16 @@ fn blend_hover_pattern_tiles_and_multiple_views_reuse_current_pixels() { app.perf.last_refresh_px = 0; assert!(ensure_gpu(&mut app, &ctx, 0, visible, None)); assert_eq!(app.perf.last_refresh_px, 0, "unchanged views must retain coverage together"); - assert_visible_pixels(&mut app, visible.intersect(&bounds)); + assert_visible_pixels(&mut app, &[visible.intersect(&bounds)]); } } // Enabling periodic display during an existing hover must catch up the unseen gap too. app.ui.view.pattern_preview = true; assert!(ensure_gpu(&mut app, &ctx, 0, a, None)); - assert_visible_pixels(&mut app, bounds); + assert_visible_pixels(&mut app, &[bounds]); crate::blend_preview::hover(&mut app, &[photocraft_doc::LayerId(layer)], None); assert!(ensure_gpu(&mut app, &ctx, 0, a, None)); - assert_visible_pixels(&mut app, bounds); + assert_visible_pixels(&mut app, &[bounds]); } #[test] @@ -96,12 +95,12 @@ fn blend_hover_during_background_redraw_restores_committed_pixels() { let panned = DRect::new(2048, 1024, 2304, 1280); assert!(ensure_gpu(&mut app, &ctx, 0, panned, None)); settle_redraw(&mut app); - assert_visible_pixels(&mut app, panned); + assert_visible_pixels(&mut app, &[panned]); crate::blend_preview::hover(&mut app, &[photocraft_doc::LayerId(layer)], None); assert!(ensure_gpu(&mut app, &ctx, 0, panned, None)); settle_redraw(&mut app); let bounds = app.session.active().unwrap().doc.bounds(); - assert_visible_pixels(&mut app, bounds); + assert_visible_pixels(&mut app, &[bounds]); } fn settle_redraw(app: &mut PhotocraftApp) { @@ -115,19 +114,33 @@ fn settle_redraw(app: &mut PhotocraftApp) { } } -fn assert_visible_pixels(app: &mut PhotocraftApp, visible: DRect) { +fn assert_visible_pixels(app: &mut PhotocraftApp, regions: &[DRect]) { let (doc, _) = display_doc(app, 0); let gpu = app.gpu.clone().unwrap(); - let reference = doc.id.0 ^ (1u64 << 60); let (display, _) = canvas_display(app, &doc, None); - gpu.upload_composite(reference, &doc, display.as_deref()); - let (_, size, shown) = gpu.read_texels(doc.id.0).unwrap(); - let (_, _, want) = gpu.read_texels(reference).unwrap(); - for y in visible.y0..visible.y1 { - for x in visible.x0..visible.x1 { - let index = y as usize * size[0] as usize + x as usize; - for channel in 0..4 { - assert!((shown[index][channel] - want[index][channel]).abs() <= 2.0 / 255.0, "preview differs at ({x},{y}) channel{channel}"); + let format = eframe::wgpu::TextureFormat::Rgba8Unorm; + // Prepare the CPU reference while the GPU can still be drawing. Each requested + // region is compared to the same captured canvas texture. + let references: Vec<_> = regions + .iter() + .map(|®ion| { + assert!(doc.bounds().contains_rect(®ion)); + let reference = photocraft_compose::render(&doc, region); + (region, gpu_canvas::display_texels(format, display.as_deref(), &reference)) + }) + .collect(); + let (actual_format, size, shown) = gpu.read_texels(doc.id.0).expect("read visible canvas"); + assert_eq!(actual_format, format); + assert_eq!(size, [doc.size.width, doc.size.height]); + for (region, expected) in references { + let expected = expected.as_chunks::<4>().0; + for y in region.y0..region.y1 { + for x in region.x0..region.x1 { + let actual = shown[y as usize * size[0] as usize + x as usize]; + let index = ((y - region.y0) as usize) * region.width() as usize + (x - region.x0) as usize; + for (channel, (actual, expected)) in actual.into_iter().zip(expected[index]).enumerate() { + assert!((actual - f32::from(expected) / 255.0).abs() <= 2.0 / 255.0, "preview differs at ({x},{y}) channel {channel}"); + } } } } @@ -138,11 +151,9 @@ fn check_blend_viewport(cpu_fallback: bool, multiple_layers: bool) { let Some(rs) = render_state() else { return }; let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); app.set_wgpu(rs); - // Every view and count below is half of the 1024 × 768 fixture first used: the clip to the view - // (`blend_preview::clip_damage`) and the catch-up (`blend_preview::uncovered`) are rectangle arithmetic with no - // size threshold, and the canvas stays far below the background redraw's (that case is - // `blend_hover_during_background_redraw_restores_committed_pixels`). The whole-canvas pixel checks cost a quarter. - app.run("file.new", json!({"width":512,"height":384,"background":"#336699"})).unwrap(); + // View clipping and catch-up use rectangles at any size. The visible, + // expanded and disjoint views below still require different refreshes. + app.run("file.new", json!({"width":256,"height":192,"background":"#336699"})).unwrap(); let layer = app.run("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap(); app.run("edit.fill", json!({"color":"#cc8844"})).unwrap(); if cpu_fallback { @@ -156,7 +167,7 @@ fn check_blend_viewport(cpu_fallback: bool, multiple_layers: bool) { layers.push(photocraft_doc::LayerId(other)); } let ctx = app.ctx().clone(); - let visible = DRect::new(128, 128, 256, 256); + let visible = DRect::new(64, 64, 128, 128); assert!(ensure_gpu(&mut app, &ctx, 0, visible, None)); assert!(app.redraws.is_empty(), "small fixture must finish synchronously"); if cpu_fallback { @@ -167,25 +178,24 @@ fn check_blend_viewport(cpu_fallback: bool, multiple_layers: bool) { let original = gpu.read_texels(id.0).unwrap(); crate::blend_preview::hover(&mut app, &layers, Some(BlendMode::Multiply)); assert!(ensure_gpu(&mut app, &ctx, 0, visible, None)); - println!("BLEND_VIEWPORT kind={} pixels={} expected={} adapter={:?}", app.perf.last_refresh, app.perf.last_refresh_px, 128 * 128, app.perf.gpu_info); - assert_eq!(app.perf.last_refresh_px, 128 * 128, "hover must not recomposite offscreen pixels of a full-canvas layer"); - assert_visible_pixels(&mut app, visible); + println!("BLEND_VIEWPORT kind={} pixels={} expected={} adapter={:?}", app.perf.last_refresh, app.perf.last_refresh_px, 64 * 64, app.perf.gpu_info); + assert_eq!(app.perf.last_refresh_px, 64 * 64, "hover must not recomposite offscreen pixels of a full-canvas layer"); + assert_visible_pixels(&mut app, &[visible]); app.perf.last_refresh_px = 0; assert!(ensure_gpu(&mut app, &ctx, 0, visible, None)); assert_eq!(app.perf.last_refresh_px, 0, "unchanged view and mode must reuse the texture"); - let zoomed_out = DRect::new(64, 64, 320, 320); + let zoomed_out = DRect::new(32, 32, 160, 160); assert!(ensure_gpu(&mut app, &ctx, 0, zoomed_out, None)); - assert_eq!(app.perf.last_refresh_px, 256 * 256, "zooming out catches up the larger visible area"); - let panned = DRect::new(320, 128, 448, 256); + assert_eq!(app.perf.last_refresh_px, 128 * 128, "zooming out catches up the larger visible area"); + let panned = DRect::new(160, 64, 224, 128); assert!(ensure_gpu(&mut app, &ctx, 0, panned, None)); - assert_eq!(app.perf.last_refresh_px, 128 * 128, "newly exposed pixels must catch up without a mode change"); + assert_eq!(app.perf.last_refresh_px, 64 * 64, "newly exposed pixels must catch up without a mode change"); crate::blend_preview::hover(&mut app, &layers, Some(BlendMode::Screen)); assert!(ensure_gpu(&mut app, &ctx, 0, panned, None)); - assert_eq!(app.perf.last_refresh_px, 128 * 128); + assert_eq!(app.perf.last_refresh_px, 64 * 64); assert!(ensure_gpu(&mut app, &ctx, 0, visible, None)); - assert_eq!(app.perf.last_refresh_px, 128 * 128, "returning view must show the current mode"); - assert_visible_pixels(&mut app, visible); - assert_visible_pixels(&mut app, panned); + assert_eq!(app.perf.last_refresh_px, 64 * 64, "returning view must show the current mode"); + assert_visible_pixels(&mut app, &[visible, panned]); crate::blend_preview::hover(&mut app, &layers, None); assert!(ensure_gpu(&mut app, &ctx, 0, visible, None)); assert_eq!(gpu.read_texels(id.0).unwrap(), original, "cancel must restore the whole texture, including previously previewed offscreen pixels"); @@ -194,11 +204,11 @@ fn check_blend_viewport(cpu_fallback: bool, multiple_layers: bool) { app.run("layer.setProps", json!({"layer":layer,"blend":"Multiply"})).unwrap(); assert!(ensure_gpu(&mut app, &ctx, 0, visible, None)); let bounds = app.session.active().unwrap().doc.bounds(); - assert_visible_pixels(&mut app, bounds); - app.run("file.new", json!({"width":512,"height":384,"background":"white"})).unwrap(); + assert_visible_pixels(&mut app, &[bounds]); + app.run("file.new", json!({"width":256,"height":192,"background":"white"})).unwrap(); assert!(ensure_gpu(&mut app, &ctx, 1, visible, None)); app.session.set_active(0); app.sync_views(); assert!(ensure_gpu(&mut app, &ctx, 0, visible, None)); - assert_visible_pixels(&mut app, bounds); + assert_visible_pixels(&mut app, &[bounds]); } diff --git a/crates/ui-egui/src/canvas/document_display.rs b/crates/ui-egui/src/canvas/document_display.rs index e0c6df2c2ec..08e063d974f 100644 --- a/crates/ui-egui/src/canvas/document_display.rs +++ b/crates/ui-egui/src/canvas/document_display.rs @@ -28,6 +28,10 @@ use photocraft_geom::Rect as DRect; #[path = "layer_edges_drawing_tests.rs"] mod layer_edges_drawing_tests; +#[cfg(test)] +#[path = "hand_scroll_all_windows_tests.rs"] +mod hand_scroll_all_windows_tests; + impl View { /// This view as the framework's canvas view of `rect` at `ppp` device pixels per point, mirrored by View › Flip /// Horizontal and stretched by View › Pixel Aspect Ratio Correction. @@ -146,7 +150,7 @@ pub(crate) fn view_follows_pointer(app: &PhotocraftApp, idx: usize) -> bool { crate::crop_ui::moves_view(app) && app.session.active_index() == Some(idx) } -/// The user's navigation choices from Preferences (General, Tools, Enhanced Controls). +/// The user's navigation preferences and Hand tool option. pub(crate) fn navigation(app: &PhotocraftApp) -> NavigationOptions { let p = app.session.prefs(); let mut options = NavigationOptions::default(); @@ -154,6 +158,7 @@ pub(crate) fn navigation(app: &PhotocraftApp) -> NavigationOptions { options.animated_zoom = p.general.animated_zoom; options.zoom_clicked_point_to_center = p.tools.zoom_clicked_point_to_center; options.flick_panning = p.tools.enable_flick_panning; + options.scroll_all_windows = app.ui.tool_options.hand_scroll_all; options.overscroll = p.tools.overscroll; options.pinch_zooms = p.enhanced_controls.zoom_with_trackpad_pinch; options.trackpad_rotate = p.enhanced_controls.rotate_view_with_trackpad; diff --git a/crates/ui-egui/src/canvas/gpu_canvas/mip_gpu_tests.rs b/crates/ui-egui/src/canvas/gpu_canvas/mip_gpu_tests.rs index 33dca070fe4..851a1ee455e 100644 --- a/crates/ui-egui/src/canvas/gpu_canvas/mip_gpu_tests.rs +++ b/crates/ui-egui/src/canvas/gpu_canvas/mip_gpu_tests.rs @@ -14,37 +14,48 @@ fn read_mips(gpu: &GpuCanvas, key: u64) -> Vec> { let tile = &doc.tiles[0]; let (device, queue) = (&gpu.rs.device, &gpu.rs.queue); let bpp = texel_bytes(doc.format) as usize; - (0..tile.levels.len()) + // Each level starts after a whole number of padded rows, so each copy offset has + // room for its own texels and meets the copy alignment for both canvas formats. + let mut size = 0; + let levels: Vec<_> = (0..tile.levels.len()) .map(|level| { let (w, h) = ((doc.size[0] >> level).max(1), (doc.size[1] >> level).max(1)); let row = (w as usize * bpp).next_multiple_of(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT as usize); - let buffer = device.create_buffer(&wgpu::BufferDescriptor { - label: Some("mip_test_readback"), - size: (row * h as usize) as u64, - usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, - mapped_at_creation: false, - }); - let mut encoder = device.create_command_encoder(&Default::default()); - encoder.copy_texture_to_buffer( - wgpu::TexelCopyTextureInfo { texture: &tile.texture, mip_level: level as u32, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, - wgpu::TexelCopyBufferInfo { - buffer: &buffer, - layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(row as u32), rows_per_image: Some(h) }, - }, - wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 }, - ); - queue.submit([encoder.finish()]); - buffer.slice(..).map_async(wgpu::MapMode::Read, |result| result.unwrap()); - assert!(gpu.health.wait(device, None)); - let data = buffer.slice(..).get_mapped_range().unwrap(); - let mut pixels = Vec::new(); - for y in 0..h as usize { - for x in 0..w as usize { - let offset = y * row + x * bpp; - pixels.push(texel_to_f32(doc.format, &data[offset..offset + bpp])); - } - } - pixels + let offset = size; + size += row * h as usize; + (w, h, row, offset) + }) + .collect(); + let buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("mip_test_readback"), + size: size as u64, + usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, + mapped_at_creation: false, + }); + let mut encoder = device.create_command_encoder(&Default::default()); + for (level, &(w, h, row, offset)) in levels.iter().enumerate() { + encoder.copy_texture_to_buffer( + wgpu::TexelCopyTextureInfo { texture: &tile.texture, mip_level: level as u32, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, + wgpu::TexelCopyBufferInfo { + buffer: &buffer, + layout: wgpu::TexelCopyBufferLayout { offset: offset as u64, bytes_per_row: Some(row as u32), rows_per_image: Some(h) }, + }, + wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 }, + ); + } + let submission = queue.submit([encoder.finish()]); + let slice = buffer.slice(..); + slice.map_async(wgpu::MapMode::Read, |result| result.expect("map mip readback")); + assert!(gpu.health.wait_idle(device, Some(submission))); + let data = slice.get_mapped_range().expect("read mip snapshot"); + levels + .into_iter() + .map(|(w, h, row, offset)| { + data[offset..offset + row * h as usize] + .chunks_exact(row) + .flat_map(|line| line[..w as usize * bpp].chunks_exact(bpp)) + .map(|texel| texel_to_f32(doc.format, texel)) + .collect() }) .collect() } @@ -124,40 +135,44 @@ fn canvas_textures_the_gpu_refuses_leave_it_working(gpu: &GpuCanvas) { } fn check_mips(gpu: &GpuCanvas) { - for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { - // 767 × 431 is a single tile (`DEFAULT_TILE`) with odd sides down the chain (767, 383, 191, 95 and 431, - // 215, 107, 53), and its levels 1 and 2 are over `WHOLE_MIP_SIDE` (128), so the patch below redraws two - // levels by their damage (`mip_damage`) before the chain is redrawn whole: the paths 1791 × 1083 took, at - // a sixth of the pixels. The larger driver case stays in `partial_updates_match_a_full_rebuild_at_every_mip_level`. - for (w, h) in [(767, 431), (513, 1), (1, 513)] { - let mut full = Buffer::filled(Rect::from_xywh(0, 0, w, h), [0.25, 0.5, 0.75, 1.0]); - // Reusing the key also covers replacing textures after a size or depth change. - gpu.upload_buffer_full(1, &full, depth); - for (level, pixels) in read_mips(gpu, 1).iter().enumerate() { - for pixel in pixels { - assert!((pixel[3] - 1.0).abs() < 0.001, "{depth:?} {w}x{h} mip {level}: {pixel:?}"); - for (actual, expected) in pixel.iter().zip([0.25, 0.5, 0.75, 1.0]) { - assert!((actual - expected).abs() < 0.005, "{depth:?} {w}x{h} mip {level}: {pixel:?}"); - } + use SampleType::{F32, U8, U16}; + // 519 is odd and still gives two damage-redrawn levels above WHOLE_MIP_SIDE + // (259 and 129), followed by whole levels. Both stored formats use this path + // on each backend, and the thin horizontal and vertical cases reach 1 × 1. + // U16 and F32 use the same float texture and mip pipeline for these values. + let depths_and_sizes: &[(SampleType, u32, u32)] = if photocraft_testkit::full_sweep() { + &[(U8, 767, 431), (U8, 513, 1), (U8, 1, 513), (U16, 767, 431), (U16, 513, 1), (U16, 1, 513), (F32, 767, 431), (F32, 513, 1), (F32, 1, 513)] + } else { + &[(U8, 519, 267), (U16, 519, 267), (F32, 1, 513), (U8, 513, 1)] + }; + for &(depth, w, h) in depths_and_sizes { + let mut full = Buffer::filled(Rect::from_xywh(0, 0, w, h), [0.25, 0.5, 0.75, 1.0]); + // Reusing the key also covers replacing textures after a size or depth change. + gpu.upload_buffer_full(1, &full, depth); + for (level, pixels) in read_mips(gpu, 1).iter().enumerate() { + for pixel in pixels { + assert!((pixel[3] - 1.0).abs() < 0.001, "{depth:?} {w}x{h} mip {level}: {pixel:?}"); + for (actual, expected) in pixel.iter().zip([0.25, 0.5, 0.75, 1.0]) { + assert!((actual - expected).abs() < 0.005, "{depth:?} {w}x{h} mip {level}: {pixel:?}"); } } - let patch = Rect::from_xywh((w / 2) as i32, (h / 2) as i32, (w / 3).max(1), (h / 3).max(1)); - let changed = Buffer::filled(patch, [1.0, 0.0, 0.0, 1.0]); - assert!(gpu.upload_buffer_rect(1, &changed)); - for y in patch.y0..patch.y1 { - for x in patch.x0..patch.x1 { - full.px[y as usize * w as usize + x as usize] = [1.0, 0.0, 0.0, 1.0]; - } + } + let patch = Rect::from_xywh((w / 2) as i32, (h / 2) as i32, (w / 3).max(1), (h / 3).max(1)); + let changed = Buffer::filled(patch, [1.0, 0.0, 0.0, 1.0]); + assert!(gpu.upload_buffer_rect(1, &changed)); + for y in patch.y0..patch.y1 { + for x in patch.x0..patch.x1 { + full.px[y as usize * w as usize + x as usize] = [1.0, 0.0, 0.0, 1.0]; } - gpu.upload_buffer_full(2, &full, depth); - let partial = read_mips(gpu, 1); - let rebuilt = read_mips(gpu, 2); - for (level, (actual, expected)) in partial.iter().zip(&rebuilt).enumerate() { - for (a, b) in actual.iter().zip(expected) { - assert!((a[3] - 1.0).abs() < 0.001, "partial {depth:?} mip {level}: {a:?}"); - for (a, b) in a.iter().zip(b) { - assert!((a - b).abs() < 0.005, "partial/full mismatch {depth:?} {w}x{h} mip {level}: {a} != {b}"); - } + } + gpu.upload_buffer_full(2, &full, depth); + let partial = read_mips(gpu, 1); + let rebuilt = read_mips(gpu, 2); + for (level, (actual, expected)) in partial.iter().zip(&rebuilt).enumerate() { + for (a, b) in actual.iter().zip(expected) { + assert!((a[3] - 1.0).abs() < 0.001, "partial {depth:?} mip {level}: {a:?}"); + for (a, b) in a.iter().zip(b) { + assert!((a - b).abs() < 0.005, "partial/full mismatch {depth:?} {w}x{h} mip {level}: {a} != {b}"); } } } @@ -177,7 +192,17 @@ fn partial_updates_match_a_full_rebuild_at_every_mip_level() { return; }; let gpu = GpuCanvas::new(&rs); - for (depth, w, h) in [(SampleType::U8, 255, 255), (SampleType::U8, 1024, 768), (SampleType::F32, 512, 512), (SampleType::F32, 1791, 1083)] { + let adapter = rs.adapter.get_info(); + // Keep the allocation/layout sweep on physical Vulkan devices, where the + // scissor regression was observed, and in the full sweep. Software adapters + // still exercise both texture formats, whole and partial redraws, and both dabs. + let sizes: &[(SampleType, u32, u32)] = + if photocraft_testkit::full_sweep() || (adapter.backend == wgpu::Backend::Vulkan && adapter.device_type != wgpu::DeviceType::Cpu) { + &[(SampleType::U8, 255, 255), (SampleType::U8, 1024, 768), (SampleType::F32, 512, 512), (SampleType::F32, 1791, 1083)] + } else { + &[(SampleType::U8, 255, 255), (SampleType::F32, 519, 267)] + }; + for &(depth, w, h) in sizes { let mut full = Buffer::filled(Rect::from_xywh(0, 0, w, h), [0.0; 4]); for (i, px) in full.px.iter_mut().enumerate() { let (x, y) = (i as u32 % w, i as u32 / w); @@ -232,8 +257,9 @@ fn background_compositor_switch_preserves_pixels(gpu: &GpuCanvas) { } let second = gpu.refresh(key, &doc, Some(damage), None); assert_eq!(second.kind, "gpu-rect", "{:?}", second.fallback); - let actual = read_mips(gpu, key).remove(0); + let (_, _, actual) = gpu.read_texels(key).expect("read updated canvas"); let expected = photocraft_compose::render(&doc, doc.bounds()); + assert_eq!(actual.len(), expected.px.len()); for (got, want) in actual.iter().zip(expected.px.iter()) { for (g, w) in got.iter().zip(want.iter()) { assert!((g - w).abs() < 0.02, "{got:?} != {want:?}"); diff --git a/crates/ui-egui/src/canvas/hand_scroll_all_windows_tests.rs b/crates/ui-egui/src/canvas/hand_scroll_all_windows_tests.rs new file mode 100644 index 00000000000..15888b21ccf --- /dev/null +++ b/crates/ui-egui/src/canvas/hand_scroll_all_windows_tests.rs @@ -0,0 +1,145 @@ +//! #12023 exercises the Hand options and gestures through the application window. + +use craft::ui::canvas::ToolHost; +use egui::accesskit::{Role, Toggled}; +use egui::{Event, Modifiers, PointerButton, Vec2, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; + +use super::CanvasHost; +use crate::state::{Tool, ToolOptions}; +use crate::{PhotocraftApp, Services}; + +type Window = Harness<'static, Box>; + +/// Two shown 3000 × 2000 documents, at 100% and 50%, with the second one active. +fn window() -> Window { + let mut window = Harness::builder().with_size(vec2(1400.0, 900.0)).with_pixels_per_point(1.0).build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), photocraft_engine::Session::new(), Services::default()); + app.background_jobs = false; + for name in ["oracle", "second"] { + app.run("file.new", json!({"width": 3000, "height": 2000, "name": name})).unwrap(); + } + app.ui.tool = Tool::Hand; + app.session.prefs.edit(|prefs| { + prefs.tools.enable_flick_panning = false; + prefs.general.animated_zoom = false; + }); + app + }); + window.run_steps(6); + let ctx = window.ctx.clone(); + crate::menus::invoke(window.state_mut(), &ctx, "window.arrange.twoUpVertical", json!({})).unwrap(); + window.run_steps(6); + for (view, zoom) in window.state_mut().ui.views.iter_mut().zip([1.0, 0.5]) { + view.zoom = zoom; + view.center = [1500.0, 1000.0]; + view.clear_pending(); + } + window.run_steps(4); + assert_eq!(window.state().session.active_index(), Some(1)); + assert_eq!(window.ctx.pixels_per_point(), 1.0); + window +} + +fn cameras(window: &Window) -> Vec<(f32, [f32; 2])> { + window.state().ui.views.iter().map(|view| (view.zoom, view.center)).collect() +} + +fn history_lengths(window: &Window) -> Vec { + window.state().session.documents().iter().map(|state| state.history.entries().len()).collect() +} + +fn enable_scroll_all(window: &mut Window) { + let checkbox = window.get_by_role_and_label(Role::CheckBox, "Scroll All Windows"); + assert_eq!(checkbox.accesskit_node().toggled(), Some(Toggled::False)); + checkbox.click(); + window.run_steps(3); + assert!(window.state().ui.tool_options.hand_scroll_all); + assert_eq!(window.get_by_role_and_label(Role::CheckBox, "Scroll All Windows").accesskit_node().toggled(), Some(Toggled::True)); +} + +/// A fixed screen-space gesture, so following a changing camera cannot add a second movement. +fn drag_second(window: &mut Window, modifiers: Modifiers) { + let source = ToolHost::shown_space(&window.ctx, CanvasHost::main(1).canvas_id()).expect("the active tile is shown").view; + let start = source.rect.center(); + let delta = vec2(-100.0, -50.0); + window.event(Event::ModifiersChanged(modifiers)); + window.hover_at(start); + window.run_steps(2); + window.event(Event::PointerButton { pos: start, button: PointerButton::Primary, pressed: true, modifiers }); + window.run_steps(2); + for fraction in [0.25, 0.5, 0.75, 1.0] { + window.event(Event::ModifiersChanged(modifiers)); + window.hover_at(start + delta * fraction); + window.run_steps(1); + } + window.event(Event::PointerButton { pos: start + delta, button: PointerButton::Primary, pressed: false, modifiers }); + window.run_steps(3); + window.event(Event::ModifiersChanged(Modifiers::NONE)); + window.run_steps(1); +} + +fn assert_moved(before: (f32, [f32; 2]), after: (f32, [f32; 2]), expected: Vec2) { + assert_eq!(after.0, before.0, "a Hand drag keeps each view's zoom"); + let delta = vec2(after.1[0] - before.1[0], after.1[1] - before.1[1]); + assert!((delta - expected).length() < 1e-3, "expected {expected:?} document pixels, got {delta:?}"); +} + +#[test] +fn checkbox_is_saved_without_history_and_pans_both_views_in_image_pixels() { + let mut window = window(); + assert!(!window.state().ui.tool_options.hand_scroll_all); + let history = history_lengths(&window); + enable_scroll_all(&mut window); + let saved = serde_json::to_value(&*window.state().ui.tool_options).unwrap(); + let restored: ToolOptions = serde_json::from_value(saved).unwrap(); + assert!(restored.hand_scroll_all, "the option persists with the other tool options"); + assert_eq!(history_lengths(&window), history, "ticking the checkbox adds no history state"); + let before = cameras(&window); + drag_second(&mut window, Modifiers::NONE); + let after = cameras(&window); + assert_moved(before[1], after[1], vec2(200.0, 100.0)); + assert_moved(before[0], after[0], vec2(200.0, 100.0)); + assert_eq!(history_lengths(&window), history, "panning adds no history state"); +} + +#[test] +fn shift_drag_pans_both_views_by_the_same_image_distance() { + let mut window = window(); + let before = cameras(&window); + drag_second(&mut window, Modifiers::SHIFT); + let after = cameras(&window); + assert_moved(before[1], after[1], vec2(200.0, 100.0)); + assert_moved(before[0], after[0], vec2(200.0, 100.0)); + assert!(!window.state().ui.tool_options.hand_scroll_all); +} + +#[test] +fn checkbox_off_without_shift_pans_only_the_dragged_view() { + let mut window = window(); + let before = cameras(&window); + drag_second(&mut window, Modifiers::NONE); + let after = cameras(&window); + assert_moved(before[1], after[1], vec2(200.0, 100.0)); + assert_eq!(after[0], before[0]); +} + +#[test] +fn hand_zoom_buttons_change_only_the_active_view_with_scroll_all_on() { + for label in ["100%", "Fit Screen", "Fill Screen"] { + let mut window = window(); + enable_scroll_all(&mut window); + let before = cameras(&window); + let history = history_lengths(&window); + window.get_by_role_and_label(Role::Button, label).click(); + window.run_steps(5); + let after = cameras(&window); + assert_eq!(after[0], before[0], "{label} leaves the other view unchanged"); + assert_ne!(after[1].0, before[1].0, "{label} changes the active view's zoom"); + assert_eq!(history_lengths(&window), history, "{label} adds no history state"); + assert!(window.state().ui.tool_options.hand_scroll_all); + } +} diff --git a/crates/ui-egui/src/dialogs/adjust_editors.rs b/crates/ui-egui/src/dialogs/adjust_editors.rs index 7558da5ea03..25daf7c2b3d 100644 --- a/crates/ui-egui/src/dialogs/adjust_editors.rs +++ b/crates/ui-egui/src/dialogs/adjust_editors.rs @@ -17,9 +17,9 @@ use craft::behavior::{EditEvent, EditEvents, Mixed}; use craft::color_ui::ui::gradient::{ColorStop, GradientStops}; use craft::draw::ui::gradient::{GradientGroup, GradientItem, GradientMap, GradientMapEditor, GradientMapOutput}; use craft::imaging::ui::adjust::{ - AdjustDialogCx, AdjustField, AdjustSliders, AdjustWords, BlackWhite, BlackWhiteEditor, BrightnessContrast, BrightnessContrastEditor, ChannelMixer, - ChannelMixerEditor, ColorBalance, ColorBalanceEditor, ColorBalanceTone, CurvesPanel, HueSaturation, HueSaturationEditor, Levels, LevelsClip, LevelsPanel, - PhotoFilter, PhotoFilterEditor, SelectiveColor, SelectiveColorEditor, ThresholdEditor, ToneChannels, ToneCurves, ToneSpace, + AdjustDialogCx, AdjustField, AdjustSliders, AdjustWords, BlackWhite, BrightnessContrast, BrightnessContrastEditor, ChannelMixer, ChannelMixerEditor, + ColorBalance, ColorBalanceEditor, ColorBalanceTone, CurvesPanel, HueSaturation, HueSaturationEditor, Levels, LevelsClip, LevelsPanel, PhotoFilter, + PhotoFilterEditor, SelectiveColor, SelectiveColorEditor, ThresholdEditor, ToneChannels, ToneCurves, ToneSpace, }; use craft::imaging::ui::histogram::{ChannelColor, HistogramData}; use craft::theme::Srgba; @@ -35,6 +35,7 @@ use serde_json::{Value, json}; use crate::PhotocraftApp; +pub(crate) mod black_white_presets; mod session; pub mod values; @@ -320,11 +321,7 @@ fn show(kind: &str, setup: &EditorSetup, ui: &mut Ui, value: &mut AdjustValue, c let out = editor.show(ui); AdjustOut { tone: Some(out.tone), ..lifted(out.edit.events, |value| AdjustValue::ColorBalance { value }) } } - ("blackWhite", AdjustValue::BlackWhite { value }) => { - let out = BlackWhiteEditor::new("Black & White", Bind::bound(value)).context(context).show(ui); - let ask = if out.auto { Some(AdjustAsk::Auto) } else { out.pick_color.map(AdjustAsk::PickColor) }; - AdjustOut { ask, edit: out.edit.events.map(|value| AdjustValue::BlackWhite { value }), tone: None } - } + ("blackWhite", AdjustValue::BlackWhite { value }) => black_white_presets::show(ui, value, context), ("photoFilter", AdjustValue::PhotoFilter { value }) => { let out = PhotoFilterEditor::new("Photo Filter", Bind::bound(value)).context(context).show(ui); AdjustOut { ask: out.pick_color.map(AdjustAsk::PickColor), edit: out.edit.events.map(|value| AdjustValue::PhotoFilter { value }), tone: None } diff --git a/crates/ui-egui/src/dialogs/adjust_editors/black_white_presets.rs b/crates/ui-egui/src/dialogs/adjust_editors/black_white_presets.rs new file mode 100644 index 00000000000..ec3456bc83c --- /dev/null +++ b/crates/ui-egui/src/dialogs/adjust_editors/black_white_presets.rs @@ -0,0 +1,105 @@ +//! Original Black & White recipes for tonal shifts and the effect of color filters. + +use std::sync::Arc; + +use craft::behavior::{EditEvent, EditEvents, Mixed}; +use craft::imaging::ui::adjust::{AdjustContext, AdjustWords, BlackWhite, BlackWhiteEditor}; +use craft::ui::contract::{Bind, Entry, Show as _, ShowContainer as _}; +use craft::ui::form::Field; +use craft::ui::pickers::Select; +use craft::ui::runtime::env::Env; +use egui::Ui; + +use super::{AdjustAsk, AdjustOut, AdjustValue}; + +type Mix = [f64; 6]; + +/// The presets change the grayscale mix and keep the layer's tint settings. +fn entries() -> [Entry>; 16] { + [ + Entry::new(Some(BlackWhite::DEFAULT_WEIGHTS), tl!("Default")), + Entry::separator(), + Entry::new(Some([22.0, 38.0, 25.0, 36.0, 10.0, 50.0]), tl!("Darker")), + Entry::new(Some([60.0, 77.0, 64.0, 78.0, 47.0, 92.0]), tl!("Lighter")), + Entry::new(Some([8.0; 6]), tl!("Deep Shadows")), + Entry::new(Some([92.0; 6]), tl!("Bright Highlights")), + Entry::new(Some([48.0; 6]), tl!("Even Color Weights")), + Entry::new(Some([86.0, 65.0, 33.0, 23.0, 15.0, 72.0]), tl!("Red Filter")), + Entry::new(Some([64.0, 91.0, 64.0, 41.0, 13.0, 53.0]), tl!("Yellow Filter")), + Entry::new(Some([28.0, 67.0, 91.0, 74.0, 17.0, 45.0]), tl!("Green Filter")), + Entry::new(Some([24.0, 35.0, 45.0, 77.0, 92.0, 53.0]), tl!("Blue Filter")), + Entry::new(Some([100.0, 73.0, 24.0, 7.0, 5.0, 64.0]), tl!("Strong Red Filter")), + Entry::new(Some([4.0, 12.0, 27.0, 71.0, 100.0, 44.0]), tl!("Strong Blue Filter")), + Entry::new(Some([58.0, 89.0, 97.0, 38.0, 8.0, 33.0]), tl!("Infrared Foliage")), + Entry::separator(), + Entry::new(None, tl!("Custom")), + ] +} + +/// A manual edit can land on exactly the weights of a named recipe. Remember that edit locally +/// so its value still shows as Custom. The Properties inspector scopes this memory to its target. +#[derive(Clone, Copy, PartialEq)] +struct ManualValue { + weights: Mix, + tint: Option<[u8; 3]>, +} + +impl From for ManualValue { + fn from(value: BlackWhite) -> Self { + let [r, g, b, _] = value.tint_color.to_rgba().0; + Self { weights: value.weights, tint: value.tint.then_some([r, g, b]) } + } +} + +fn manual_id(ui: &Ui) -> egui::Id { + ui.make_persistent_id("black-white-manual-value") +} + +pub(crate) fn clear_custom(ui: &Ui) { + ui.data_mut(|d| d.remove::(manual_id(ui))); + ui.ctx().request_repaint(); +} + +/// The Properties host applies accepted Color Picker colors and Auto outside the editor's pass. +pub(super) fn mark_custom(ui: &Ui, value: &AdjustValue) { + if let AdjustValue::BlackWhite { value } = value { + ui.data_mut(|d| d.insert_temp(manual_id(ui), ManualValue::from(*value))); + } +} + +pub(super) fn show(ui: &mut Ui, value: &mut BlackWhite, context: AdjustContext) -> AdjustOut { + let id = manual_id(ui); + let mut manual = ui.data(|d| d.get_temp::(id)); + let entries = entries(); + let shown = (manual != Some((*value).into()) && entries.iter().any(|entry| entry.value() == Some(&Some(value.weights)))).then_some(value.weights); + let label = tl!("Preset"); + let picked = Field::new(label).show(ui, |ui, _| Select::new(label, Bind::given(shown), &entries).show(ui).events.committed().copied()).inner.flatten(); + let mut edit = EditEvents::new(); + if let Some(picked) = picked { + manual = picked.is_none().then(|| (*value).into()); + if let Some(weights) = picked + && weights != value.weights + { + let before = *value; + value.weights = weights; + edit.push(EditEvent::set(Mixed::Same(before), *value, Arc::from(label), None)); + } + } + + let out = BlackWhiteEditor::new("Black & White", Bind::bound(&mut *value)).context(context).show(ui); + if let Some(after) = out.edit.events.committed() { + let words = Env::of(ui).words::(); + let reset = matches!(out.edit.events.ended(), Some(EditEvent::Set { label, .. }) if label.as_ref() == words.default_button.as_str()); + manual = (!reset).then(|| (*after).into()); + } + ui.data_mut(|d| match manual { + Some(value) => { + d.insert_temp(id, value); + } + None => d.remove::(id), + }); + + let ask = if out.auto { Some(AdjustAsk::Auto) } else { out.pick_color.map(AdjustAsk::PickColor) }; + edit.extend(out.edit.events); + AdjustOut { ask, edit: edit.map(|value| AdjustValue::BlackWhite { value }), tone: None } +} diff --git a/crates/ui-egui/src/dialogs/adjust_editors/session.rs b/crates/ui-egui/src/dialogs/adjust_editors/session.rs index 6fda7a035e7..2739288577f 100644 --- a/crates/ui-egui/src/dialogs/adjust_editors/session.rs +++ b/crates/ui-egui/src/dialogs/adjust_editors/session.rs @@ -13,7 +13,7 @@ use photocraft_engine::adjust_params; use serde_json::{Value, json}; use super::values::{self, ValueCx}; -use super::{AdjustAsk, AdjustValue, EditorSetup, answer_color, black_white_auto, editor, gradient_presets, is_gray, swatches}; +use super::{AdjustAsk, AdjustValue, EditorSetup, answer_color, black_white_auto, black_white_presets, editor, gradient_presets, is_gray, swatches}; use crate::PhotocraftApp; use crate::color_picker_ui::PickWindow; use crate::theme::Tokens; @@ -192,7 +192,7 @@ pub fn layer_editor(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: LayerId, adj // put while it shows this layer, replays included. record.session.track(session_target(doc, id), app.properties_hidden, &committed); } - follow_color_pick(app, id, &mut record, &committed, &vcx); + follow_color_pick(app, ui, id, &mut record, &committed, &vcx); let mut value = match &app.live_adjust { Some((layer, params)) if *layer == id => values::from_params(kind, params, &vcx).unwrap_or_else(|_| committed.clone()), _ => committed.clone(), @@ -246,7 +246,12 @@ pub fn layer_editor(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: LayerId, adj target.extend(weights); } match values::from_params(kind, ¶ms, &vcx) { - Ok(auto) => commit(app, id, &mut record, &committed, &auto, &vcx, None), + Ok(auto) => { + if auto != committed { + black_white_presets::mark_custom(ui, &auto); + } + commit(app, id, &mut record, &committed, &auto, &vcx, None); + } Err(err) => app.ui.status = err, } } @@ -294,7 +299,7 @@ fn commit( /// A colour well's Color Picker while it is open: its colour previews on the layer. Once it /// closed, OK's colour is one edit and Cancel (or OK without a colour) leaves the layer as it was. -fn follow_color_pick(app: &mut PhotocraftApp, id: LayerId, record: &mut PropertiesAdjust, committed: &AdjustValue, vcx: &ValueCx) { +fn follow_color_pick(app: &mut PhotocraftApp, ui: &egui::Ui, id: LayerId, record: &mut PropertiesAdjust, committed: &AdjustValue, vcx: &ValueCx) { let Some(pick) = record.pick.take() else { return }; match app.framework.dialogs.get_by_id::(pick.dialog).map(ColorPickerDialog::current) { Some(current) => { @@ -310,6 +315,9 @@ fn follow_color_pick(app: &mut PhotocraftApp, id: LayerId, record: &mut Properti Some((key, color)) if key == pick.key && Some(color) != pick.opened => { let mut answered = pick.before; if answer_color(&mut answered, &key, color) { + if answered != *committed { + black_white_presets::mark_custom(ui, &answered); + } commit(app, id, record, committed, &answered, vcx, None); } else { app.live_adjust = None; diff --git a/crates/ui-egui/src/dialogs/adjust_editors/ui_tests.rs b/crates/ui-egui/src/dialogs/adjust_editors/ui_tests.rs index fa23887d654..87493748f58 100644 --- a/crates/ui-egui/src/dialogs/adjust_editors/ui_tests.rs +++ b/crates/ui-egui/src/dialogs/adjust_editors/ui_tests.rs @@ -492,3 +492,154 @@ fn black_white_auto_button_sets_the_weights() { assert_ne!(after, before, "the red and blue are told apart"); assert_eq!(history_len(&h), steps + 1); } + +#[track_caller] +fn assert_black_white_preset(h: &Harness<'_, Box>, name: &str) { + assert_eq!(h.get_by_role_and_label(Role::ComboBox, "Preset").accesskit_node().value().as_deref(), Some(name)); +} + +#[test] +fn black_white_presets_apply_the_authored_weights_and_keep_tint() { + let mut h = app_harness("blackWhite", "rgb", 8); + // Leave enough vertical space for the complete dropdown to be visible at once. + h.set_size(vec2(1440.0, 1350.0)); + let (id, _) = layer(&h); + h.state_mut().run("layer.setAdjustment", json!({"layer": id.0, "tint": true, "tintColor": "#336699"})).unwrap(); + h.run_steps(4); + let (_, original) = layer(&h); + let Adjustment::BlackWhite { tint: original_tint, .. } = &original else { panic!("{original:?}") }; + + for (name, expected) in [ + ("Darker", [22.0, 38.0, 25.0, 36.0, 10.0, 50.0]), + ("Lighter", [60.0, 77.0, 64.0, 78.0, 47.0, 92.0]), + ("Deep Shadows", [8.0; 6]), + ("Bright Highlights", [92.0; 6]), + ("Even Color Weights", [48.0; 6]), + ("Red Filter", [86.0, 65.0, 33.0, 23.0, 15.0, 72.0]), + ("Yellow Filter", [64.0, 91.0, 64.0, 41.0, 13.0, 53.0]), + ("Green Filter", [28.0, 67.0, 91.0, 74.0, 17.0, 45.0]), + ("Blue Filter", [24.0, 35.0, 45.0, 77.0, 92.0, 53.0]), + ("Strong Red Filter", [100.0, 73.0, 24.0, 7.0, 5.0, 64.0]), + ("Strong Blue Filter", [4.0, 12.0, 27.0, 71.0, 100.0, 44.0]), + ("Infrared Foliage", [58.0, 89.0, 97.0, 38.0, 8.0, 33.0]), + ("Default", [40.0, 60.0, 40.0, 60.0, 20.0, 80.0]), + ] { + let history = history_len(&h); + h.get_by_role_and_label(Role::ComboBox, "Preset").click(); + h.run_steps(3); + h.get_by_role_and_label(Role::ListBoxOption, name).click(); + h.run_steps(4); + + let (_, applied) = layer(&h); + let Adjustment::BlackWhite { weights, tint } = applied else { panic!("{applied:?}") }; + assert_eq!(weights, expected, "{name} applies the authored mix"); + assert_black_white_preset(&h, name); + assert_eq!(&tint, original_tint, "{name} preserves Tint"); + assert_eq!(history_len(&h), history + 1, "{name} is one history step"); + assert!(h.state().live_adjust.is_none(), "{name} finishes the preview"); + } + assert_eq!(layer(&h).1, original, "Default restores the original mix"); +} + +#[test] +fn black_white_presets_apply_through_properties_and_undo() { + let mut h = app_harness("blackWhite", "rgb", 8); + let (id, _) = layer(&h); + h.state_mut().run("layer.setAdjustment", json!({"layer": id.0, "tint": true, "tintColor": "#336699"})).unwrap(); + h.run_steps(4); + let (_, before) = layer(&h); + let Adjustment::BlackWhite { weights: original, tint: original_tint } = &before else { panic!("{before:?}") }; + let history = history_len(&h); + let pixel = h.state_mut().run("document.pixel", json!({"x": 10, "y": 10})).unwrap(); + assert_black_white_preset(&h, "Default"); + + h.get_by_role_and_label(Role::ComboBox, "Preset").click(); + h.run_steps(3); + h.get_by_role_and_label(Role::ListBoxOption, "Darker").click(); + h.run_steps(4); + assert_black_white_preset(&h, "Darker"); + let (_, after) = layer(&h); + let Adjustment::BlackWhite { weights, tint } = &after else { panic!("{after:?}") }; + assert!(weights.iter().zip(original).all(|(weight, original)| weight < original)); + assert_eq!(tint, original_tint); + assert_ne!(h.state_mut().run("document.pixel", json!({"x": 10, "y": 10})).unwrap(), pixel); + assert_eq!(history_len(&h), history + 1); + assert!(h.state().live_adjust.is_none()); + + let ctx = h.ctx.clone(); + let picker = open_picker(&mut h, "Tint Color"); + show_in_picker(&mut h, picker, "#ad632a"); + h.state_mut().framework.dialogs.cancel_by_id(&ctx, picker); + h.run_steps(4); + assert_black_white_preset(&h, "Darker"); + assert_eq!(layer(&h).1, after); + assert_eq!(history_len(&h), history + 1); + + let picker = open_picker(&mut h, "Tint Color"); + show_in_picker(&mut h, picker, "#ad632a"); + crate::dialogs::confirm(h.state_mut(), &ctx, picker).expect("OK is enabled"); + h.run_steps(4); + assert_black_white_preset(&h, "Custom"); + assert_eq!(history_len(&h), history + 2); + + h.state_mut().run("edit.undo", json!({})).unwrap(); + h.run_steps(4); + assert_eq!(layer(&h).1, after); + assert_black_white_preset(&h, "Darker"); + h.state_mut().run("edit.undo", json!({})).unwrap(); + h.run_steps(4); + assert_eq!(layer(&h).1, before); + assert_black_white_preset(&h, "Default"); +} + +#[test] +fn black_white_presets_distinguish_manual_edits_from_named_choices() { + let mut h = app_harness("blackWhite", "rgb", 8); + // Opening the dropdown on Custom reveals the last row, so leave room for Default too. + h.set_size(vec2(1440.0, 1350.0)); + let (id, defaults) = layer(&h); + let Adjustment::BlackWhite { weights, .. } = &defaults else { panic!("{defaults:?}") }; + let red = weights[0]; + let type_default = |h: &mut Harness<'_, Box>| { + h.state_mut().run("layer.setAdjustment", json!({"layer": id.0, "reds": red + 7.0})).unwrap(); + h.run_steps(4); + assert_black_white_preset(h, "Custom"); + h.get_by_role_and_label(Role::SpinButton, "Reds").click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.event(egui::Event::Text(red.to_string())); + h.run_steps(1); + h.key_press(egui::Key::Tab); + h.run_steps(4); + assert_eq!(layer(h).1, defaults); + assert_black_white_preset(h, "Custom"); + }; + + type_default(&mut h); + + h.state_mut().run("layer.newAdjustmentLayer.blackWhite", json!({})).unwrap(); + h.run_steps(4); + assert_black_white_preset(&h, "Default"); + h.state_mut().run("layer.select", json!({"layer": id.0})).unwrap(); + // Layer selection can keep the mask targeted. Return to the adjustment's controls. + h.state_mut().run("channel.target.composite", json!({})).unwrap(); + h.run_steps(4); + assert_black_white_preset(&h, "Custom"); + + let history = history_len(&h); + h.get_by_role_and_label(Role::ComboBox, "Preset").click(); + h.run_steps(3); + h.get_by_role_and_label(Role::ListBoxOption, "Default").click(); + h.run_steps(4); + assert_black_white_preset(&h, "Default"); + assert_eq!(layer(&h).1, defaults); + assert_eq!(history_len(&h), history); + + type_default(&mut h); + h.get_by_role_and_label(Role::Button, "Reset to defaults").scroll_to_me(); + h.run_steps(2); + h.get_by_role_and_label(Role::Button, "Reset to defaults").click(); + h.run_steps(4); + assert_black_white_preset(&h, "Default"); + assert_eq!(layer(&h).1, defaults); +} diff --git a/crates/ui-egui/src/gradient_mask_target_greyed_modes_tests.rs b/crates/ui-egui/src/gradient_mask_target_greyed_modes_tests.rs new file mode 100644 index 00000000000..5e033dc4691 --- /dev/null +++ b/crates/ui-egui/src/gradient_mask_target_greyed_modes_tests.rs @@ -0,0 +1,64 @@ +//! #18634: with a layer mask targeted, the Classic gradient's Mode list greys Behind, Darker Color, Lighter Color, Hue, +//! Saturation, Color and Luminosity, the modes that need colour or transparency; every other entry stays enabled. With +//! the layer's pixels targeted again, this rule greys nothing. + +use photocraft_doc::BlendMode; +use serde_json::json; + +use super::mode_entries; +use crate::PhotocraftApp; +use crate::state::Tool; + +const GREYED_ON_A_MASK: [BlendMode; 6] = + [BlendMode::DarkerColor, BlendMode::LighterColor, BlendMode::Hue, BlendMode::Saturation, BlendMode::Color, BlendMode::Luminosity]; + +fn app() -> Box { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 80, "height": 60, "background": "white"})).unwrap(); + app.ui.tool = Tool::Gradient; + app.ui.tool_options.gradient_classic = true; + app +} + +/// The greyed entries of the Mode list: `None` is Behind. +fn greyed(app: &PhotocraftApp) -> Vec> { + mode_entries(app).iter().filter(|e| !e.is_enabled()).filter_map(|e| e.value().copied()).collect() +} + +fn expected_on_a_mask() -> Vec> { + let mut v: Vec> = vec![None]; + v.extend(GREYED_ON_A_MASK.map(Some)); + v.sort_by_key(|m| format!("{m:?}")); + v +} + +fn sorted(mut v: Vec>) -> Vec> { + v.sort_by_key(|m| format!("{m:?}")); + v +} + +#[test] +fn a_targeted_layer_mask_greys_the_seven_modes() { + let cases: [(&str, &[(&str, serde_json::Value)]); 3] = [ + ("a pixel layer's mask", &[("layer.new.layer", json!({})), ("layer.layerMask.revealAll", json!({})), ("channel.target", json!({"channel": "mask"}))]), + ("a solid colour fill layer's mask", &[("layer.newFillLayer.solidColor", json!({"color": "#336699"})), ("channel.target", json!({"channel": "mask"}))]), + ("a Curves adjustment layer's mask", &[("layer.newAdjustmentLayer.curves", json!({})), ("channel.target", json!({"channel": "mask"}))]), + ]; + for (case, steps) in cases { + let mut app = app(); + for (id, params) in steps { + app.run(id, params.clone()).unwrap_or_else(|e| panic!("{case}: {id}: {e}")); + } + assert_eq!(sorted(greyed(&app)), expected_on_a_mask(), "{case}"); + } +} + +#[test] +fn the_layers_pixels_targeted_again_grey_none_of_them() { + let mut app = app(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("layer.layerMask.revealAll", json!({})).unwrap(); + app.run("channel.target", json!({"channel": "mask"})).unwrap(); + app.run("channel.target", json!({"channel": "composite"})).unwrap(); + assert!(greyed(&app).is_empty(), "{:?}", greyed(&app)); +} diff --git a/crates/ui-egui/src/icon_data.rs b/crates/ui-egui/src/icon_data.rs index 6e791460ba0..e1fdaba2c06 100644 --- a/crates/ui-egui/src/icon_data.rs +++ b/crates/ui-egui/src/icon_data.rs @@ -23,6 +23,7 @@ pub static ICONS: &[(&str, &[u8])] = &[ ("ellipsis", include_bytes!("../../../assets/icons/ellipsis.svg")), ("file-plus", include_bytes!("../../../assets/icons/file-plus.svg")), ("folder-plus", include_bytes!("../../../assets/icons/folder-plus.svg")), + ("gradient-tool", include_bytes!("../../../assets/icons/gradient-tool.svg")), ("grid-2x2", include_bytes!("../../../assets/icons/grid-2x2.svg")), ("history-brush", include_bytes!("../../../assets/icons/history-brush.svg")), ("house", include_bytes!("../../../assets/icons/house.svg")), diff --git a/crates/ui-egui/src/menu_catalog.rs b/crates/ui-egui/src/menu_catalog.rs index 479e8e03689..731634301e9 100644 --- a/crates/ui-egui/src/menu_catalog.rs +++ b/crates/ui-egui/src/menu_catalog.rs @@ -693,6 +693,7 @@ pub static CATALOG: &[(&[&str], &str, Option<&str>, &str)] = &[ (&["View"], "100%", Some("Cmd+1"), "view.actualPixels"), (&["View"], "200%", None, "view.twoHundredPercent"), (&["View"], "Print Size", None, "view.printSize"), + (&["View"], "Actual Size", None, "view.actualSize"), (&["View"], "---", None, "---"), (&["View"], "Flip Horizontal", None, "view.flipHorizontal"), (&["View", "Screen Mode"], "Standard Screen Mode", None, "view.screenMode.standard"), diff --git a/crates/ui-egui/src/menus/enable_rules.rs b/crates/ui-egui/src/menus/enable_rules.rs index 7bd46578ce7..30b4203b467 100644 --- a/crates/ui-egui/src/menus/enable_rules.rs +++ b/crates/ui-egui/src/menus/enable_rules.rs @@ -129,9 +129,47 @@ pub fn disabled_for_selection(doc: &Document, selected: &[LayerId], active: Opti !any } +/// Puppet Warp, Perspective Warp and Content-Aware Scale work on one layer: with two or more +/// layers selected the reference greys them (#18501). Measured on layers at the top of the stack; +/// a group among them, or layers inside a group, keep the engine's own rule. +const ONE_LAYER_DISTORTS: [&str; 3] = ["edit.puppetWarp", "edit.perspectiveWarp", "edit.contentAwareScale"]; + +fn several_layers_block(doc: &Document, selected: &[LayerId], id: &str) -> bool { + ONE_LAYER_DISTORTS.contains(&id) + && selected.len() > 1 + && selected.iter().all(|l| doc.layer(*l).is_some_and(|layer| !layer.is_group()) && doc.layers.index().parent(*l).is_none()) +} + +/// Why a menu item that [`disabled`] greys for the layer selection is refused when it is invoked +/// anyway (a shortcut, the control channel's `ui.menu.invoke`), before any session opens. A +/// control call (`{"ui": …}`) for a Puppet Warp or Perspective Warp already open is not refused: it +/// commits, cancels or edits that session, opened on one layer, whatever is selected since. +pub fn refusal(app: &crate::PhotocraftApp, id: &str, params: &serde_json::Value) -> Option { + let open = match id { + "edit.puppetWarp" => app.distort.puppet.is_some(), + "edit.perspectiveWarp" => app.distort.perspective.is_some(), + _ => false, + }; + if open && params.get("ui").is_some() { + return None; + } + let st = app.session.active()?; + several_layers_block(&st.doc, st.selected_layers(), id).then(|| { + let name = match id { + "edit.puppetWarp" => "Puppet Warp", + "edit.perspectiveWarp" => "Perspective Warp", + _ => "Content-Aware Scale", + }; + format!("{name} works on one layer at a time: select a single layer") + }) +} + pub fn disabled(app: &crate::PhotocraftApp, id: &str) -> bool { let Some(st) = app.session.active() else { return false }; let active = st.active_layer.and_then(|a| st.doc.layer(a)); + if several_layers_block(&st.doc, st.selected_layers(), id) { + return true; + } // The split warps edit the open Warp box's grid: with none they are greyed, also on a smart // object with a stored warp, as the reference greys them there (#12494, #12942). if matches!( @@ -521,3 +559,7 @@ mod tests { #[cfg(test)] #[path = "warp_split_enable_tests.rs"] mod warp_split_enable_tests; + +#[cfg(test)] +#[path = "several_layers_distort_greyed_tests.rs"] +mod several_layers_distort_greyed_tests; diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index 8515d08a01a..1ebbf0be889 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -60,6 +60,7 @@ fn keeps_box_drag(id: &str) -> bool { "view.zoomOut", "view.fitOnScreen", "view.actualPixels", + "view.actualSize", "view.rotateView", "view.resetView", "view.darkenInterface", @@ -86,6 +87,10 @@ pub fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: Va if !keeps_box_drag(id) { crate::type_box_preview::end_drag(app); } + // An item the menu greys for the layer selection opens nothing when invoked anyway (#18501). + if let Some(why) = crate::enable_rules::refusal(app, id, ¶ms) { + return Err(why); + } if crate::discard_ui::intercept(app, id, ¶ms) { return Ok(Value::Null); } diff --git a/crates/ui-egui/src/menus/items.rs b/crates/ui-egui/src/menus/items.rs index 83357c6dc95..117cf2ab86f 100644 --- a/crates/ui-egui/src/menus/items.rs +++ b/crates/ui-egui/src/menus/items.rs @@ -240,6 +240,14 @@ pub fn base_rows(app: &PhotocraftApp) -> Vec { { item.label = "Merge Group".into(); } + // And Merge Clipping Mask with just the base of a clip group selected (#18481). + if let Some(st) = app.session.active() + && st.selected_layers().len() <= 1 + && st.active_layer.is_some_and(|id| photocraft_engine::layer_multi_cmds::merges_clipping_mask(&st.doc, id)) + && let Some(item) = find(&mut rows, "layer.mergeLayers") + { + item.label = "Merge Clipping Mask".into(); + } // Edit › Fade names the step it fades (#13803). if let Some(item) = find(&mut rows, "edit.fade") { item.label = photocraft_engine::edit_menu_cmds::fade_menu_label(&app.session); diff --git a/crates/ui-egui/src/menus/several_layers_distort_greyed_tests.rs b/crates/ui-egui/src/menus/several_layers_distort_greyed_tests.rs new file mode 100644 index 00000000000..c04e0efe735 --- /dev/null +++ b/crates/ui-egui/src/menus/several_layers_distort_greyed_tests.rs @@ -0,0 +1,181 @@ +//! Puppet Warp, Perspective Warp and Content-Aware Scale with several layers selected (#18501): +//! greyed in the Edit menu and in `ui.menu.list`, refused when invoked anyway (no session opens, +//! nothing changes); one pixel layer keeps all three, and the cases not measured keep today's state. + +use photocraft_doc::LayerId; +use serde_json::{Value, json}; + +use crate::PhotocraftApp; +use crate::control::{ControlRequest, Reply}; + +const THREE: [&str; 3] = ["edit.puppetWarp", "edit.perspectiveWarp", "edit.contentAwareScale"]; + +fn layer_of(v: Value) -> LayerId { + LayerId(v["layer"].as_u64().unwrap()) +} + +/// A 100 × 100 white document with a new pixel layer holding a block of colour, active. +fn painted_layer(app: &mut PhotocraftApp, name: &str, x: i64, color: &str) -> LayerId { + let layer = layer_of(app.run("layer.new.layer", json!({ "name": name })).unwrap()); + app.run("select.rect", json!({"x": x, "y": 10, "width": 30, "height": 30})).unwrap(); + app.run("edit.fill", json!({"contents": "color", "color": color})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + layer +} + +fn app_with_two_layers() -> (Box, LayerId, LayerId) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 100, "height": 100, "background": "white"})).unwrap(); + app.sync_views(); + let a = painted_layer(&mut app, "A", 10, "#ff0000"); + let b = painted_layer(&mut app, "B", 50, "#0000ff"); + (app, a, b) +} + +/// The Edit menu row's state as the menu builds it. +fn in_menu(app: &PhotocraftApp, id: &str) -> bool { + let rows = crate::menus::menu_rows(app); + let row = crate::menus::items::row(&rows, id).map(|r| (r.path.clone(), r.enabled)); + let (path, enabled) = row.unwrap_or_else(|| panic!("{id} is in the menu")); + assert_eq!(path.first().map(String::as_str), Some("Edit"), "{id}"); + enabled +} + +fn control(app: &mut PhotocraftApp, method: &str, params: Value) -> Result { + let ctx = app.ctx().clone(); + let (request, _reply) = ControlRequest::new(method, params); + match crate::control::handle(app, &ctx, &request) { + Reply::Done(reply) if reply["ok"] == true => Ok(reply), + Reply::Done(reply) => Err(reply["error"].as_str().unwrap_or_default().to_owned()), + _ => panic!("expected an immediate reply to {method}"), + } +} + +/// `enabled` of `id` in `ui.menu.list`. +fn listed(app: &mut PhotocraftApp, id: &str) -> bool { + let list = control(app, "ui.menu.list", json!({})).unwrap(); + let row = list["result"].as_array().unwrap().iter().find(|row| row["id"] == id).cloned(); + row.unwrap_or_else(|| panic!("{id} is listed"))["enabled"].as_bool().unwrap() +} + +fn no_session(app: &PhotocraftApp) -> bool { + app.distort.puppet.is_none() && app.distort.perspective.is_none() && app.ui.transform.is_none() +} + +fn history_len(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().history.entries().len() +} + +#[test] +fn two_selected_pixel_layers_grey_the_three_and_invoking_them_opens_nothing() { + let (mut app, a, b) = app_with_two_layers(); + app.run("layer.select", json!({"layers": [a.0, b.0]})).unwrap(); + assert_eq!(app.session.active().unwrap().selected_layers().len(), 2); + for id in THREE { + assert!(!in_menu(&app, id), "{id} is greyed in the Edit menu with two layers selected"); + assert!(!listed(&mut app, id), "{id} is disabled in ui.menu.list with two layers selected"); + } + let steps = history_len(&app); + for id in THREE { + let refused = control(&mut app, "ui.menu.invoke", json!({ "id": id })); + let why = refused.expect_err(&format!("{id} is refused with two layers selected")); + assert!(why.contains("one layer at a time"), "{id}: {why}"); + assert!(no_session(&app), "{id} opened a session"); + let ctx = app.ctx().clone(); + assert!(crate::menus::invoke(&mut app, &ctx, id, json!({})).is_err(), "{id} through the menu's own invoke"); + assert!(no_session(&app), "{id} opened a session"); + } + assert_eq!(history_len(&app), steps, "nothing changed"); + assert_eq!(app.session.active().unwrap().selected_layers(), [a, b], "the selection stays"); +} + +#[test] +fn free_transform_and_edit_transform_stay_enabled_with_two_layers() { + let (mut app, a, b) = app_with_two_layers(); + app.run("layer.select", json!({"layers": [a.0, b.0]})).unwrap(); + for id in [ + "edit.freeTransform", + "edit.transform.scale", + "edit.transform.rotate", + "edit.transform.skew", + "edit.transform.distort", + "edit.transform.perspective", + "edit.transform.rotate180", + "edit.transform.rotate90Cw", + "edit.transform.rotate90Ccw", + "edit.transform.flipHorizontal", + "edit.transform.flipVertical", + ] { + assert!(in_menu(&app, id), "{id} stays enabled with two layers selected"); + } +} + +#[test] +fn one_pixel_layer_keeps_all_three() { + let (mut app, _, b) = app_with_two_layers(); + app.run("layer.select", json!({"layer": b.0})).unwrap(); + for id in THREE { + assert!(in_menu(&app, id), "{id} is enabled for one pixel layer"); + assert!(listed(&mut app, id), "{id} is listed enabled for one pixel layer"); + } + control(&mut app, "ui.menu.invoke", json!({"id": "edit.puppetWarp"})).expect("Puppet Warp opens on one layer"); + assert!(app.distort.puppet.is_some(), "the pin mesh is open"); +} + +#[test] +fn the_cases_not_measured_keep_todays_state() { + // Two layers inside a group. + let (mut app, a, b) = app_with_two_layers(); + app.run("layer.select", json!({"layers": [a.0, b.0]})).unwrap(); + app.run("layer.groupLayers", json!({})).unwrap(); + app.run("layer.select", json!({"layers": [a.0, b.0]})).unwrap(); + assert_eq!(app.session.active().unwrap().selected_layers().len(), 2); + for id in THREE { + assert!(in_menu(&app, id), "{id}: two layers inside a group keep today's state"); + } + + // A group and a layer, the layer active. + let (mut app, a, b) = app_with_two_layers(); + app.run("layer.select", json!({"layer": a.0})).unwrap(); + let group = layer_of(app.run("layer.groupLayers", json!({})).unwrap()); + app.run("layer.select", json!({"layers": [group.0, b.0]})).unwrap(); + app.run("layer.select", json!({"layer": b.0, "mode": "add"})).unwrap(); + assert_eq!(app.session.active().unwrap().active_layer, Some(b)); + for id in THREE { + assert!(in_menu(&app, id), "{id}: a group and a layer keep today's state"); + } + + // A linked layer: one layer selected, its partner not. + let (mut app, a, b) = app_with_two_layers(); + app.run("layer.select", json!({"layers": [a.0, b.0]})).unwrap(); + app.run("layer.linkLayers", json!({})).unwrap(); + app.run("layer.select", json!({"layer": b.0})).unwrap(); + for id in THREE { + assert!(in_menu(&app, id), "{id}: a linked layer keeps today's state"); + } +} + +/// A Puppet Warp or Perspective Warp opened on one layer still takes its control calls (commit, cancel) when two +/// layers are selected afterwards: the refusal is for opening a new session only. +#[test] +fn an_open_warp_still_commits_and_cancels_with_two_layers_selected() { + for (id, how) in [("edit.puppetWarp", "commit"), ("edit.puppetWarp", "cancel"), ("edit.perspectiveWarp", "commit"), ("edit.perspectiveWarp", "cancel")] { + let (mut app, a, b) = app_with_two_layers(); + app.run("layer.select", json!({"layer": b.0})).unwrap(); + control(&mut app, "ui.menu.invoke", json!({ "id": id })).unwrap_or_else(|e| panic!("{id} opens on one layer: {e}")); + assert!(!no_session(&app), "{id}: a session is open"); + app.run("layer.select", json!({"layers": [a.0, b.0]})).unwrap(); + assert_eq!(app.session.active().unwrap().selected_layers().len(), 2); + let reply = control(&mut app, "ui.menu.invoke", json!({ "id": id, "params": { "ui": { how: true } } })); + reply.unwrap_or_else(|e| panic!("{id} {how} with two layers selected: {e}")); + assert!(no_session(&app), "{id}: {how} closes the session"); + } + // Opening a new session with two layers selected is still refused, also with control params. + let (mut app, a, b) = app_with_two_layers(); + app.run("layer.select", json!({"layers": [a.0, b.0]})).unwrap(); + for id in ["edit.puppetWarp", "edit.perspectiveWarp"] { + let refused = control(&mut app, "ui.menu.invoke", json!({ "id": id, "params": { "ui": { "commit": true } } })); + assert!(refused.is_err_and(|why| why.contains("one layer at a time")), "{id}: no session, so it is refused"); + assert!(no_session(&app), "{id} opened a session"); + } +} diff --git a/crates/ui-egui/src/menus/view_cmds.rs b/crates/ui-egui/src/menus/view_cmds.rs index 7aed10a9462..c1660827636 100644 --- a/crates/ui-egui/src/menus/view_cmds.rs +++ b/crates/ui-egui/src/menus/view_cmds.rs @@ -13,6 +13,7 @@ use serde_json::{Map, Value, json}; use crate::PhotocraftApp; +mod actual_size; mod arrange; pub(crate) mod dialogs; mod dispatch; @@ -218,3 +219,7 @@ mod save_a_copy_name_tests; #[cfg(test)] #[path = "view_cmds/file_info_title_labels_tests.rs"] mod file_info_title_labels_tests; + +#[cfg(test)] +#[path = "view_cmds/actual_size_tests.rs"] +mod actual_size_tests; diff --git a/crates/ui-egui/src/menus/view_cmds/actual_size.rs b/crates/ui-egui/src/menus/view_cmds/actual_size.rs new file mode 100644 index 00000000000..191c16a0038 --- /dev/null +++ b/crates/ui-egui/src/menus/view_cmds/actual_size.rs @@ -0,0 +1,253 @@ +//! Physical-size viewing. Logical UI scaling is deliberately absent from the PPI calculation. + +use craft::behavior::{canvas::ZoomScheme, kurbo::Size}; +use serde_json::{Value, json}; + +use crate::PhotocraftApp; + +pub(super) fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, params: &Value) -> Result { + let physical_ppi = display_ppi(ctx); + apply(app, physical_ppi, params) +} + +pub(super) fn apply(app: &mut PhotocraftApp, physical_ppi: Option, params: &Value) -> Result { + if !params.as_object().is_some_and(|object| object.is_empty()) { + return Err("Actual Size takes an empty parameter object".into()); + } + let index = app.session.active_index().ok_or("Actual Size needs an open document")?; + let doc = &app.session.documents().get(index).ok_or("no document")?.doc; + let document_ppi = f64::from(doc.resolution_dpi); + if !document_ppi.is_finite() || document_ppi <= 0.0 { + return Err("Actual Size needs a positive document resolution".into()); + } + let physical_ppi = physical_ppi.filter(|ppi| ppi.is_finite() && *ppi >= 1.0).map(f64::floor); + let fallback = physical_ppi.is_none(); + let preferred = app.session.prefs().units_and_rulers.screen_resolution; + let screen_ppi = physical_ppi.unwrap_or(if preferred >= 1.0 { preferred.floor() } else { preferred }); + let zoom = screen_ppi / document_ppi; + if !zoom.is_finite() || zoom <= 0.0 { + return Err("Actual Size needs a positive screen resolution".into()); + } + let size = Size::new(f64::from(doc.size.width), f64::from(doc.size.height)); + let zoom = ZoomScheme::PHOTOSHOP.clamp(zoom, size) as f32; + app.sync_views(); + let animate = app.session.prefs().general.animated_zoom; + let view = app.ui.views.get_mut(index).ok_or("no document view")?; + view.request_zoom_animation(animate); + view.clear_pending(); + view.zoom = zoom; + let message = if fallback { + tl!("Actual Size uses Screen Resolution because the display's physical size is unavailable").to_string() + } else { + tl!("Actual Size uses the display's physical resolution").to_string() + }; + app.ui.status = message.clone(); + app.ui.status_error = false; + crate::panels::actions::runner::journal_view(app, "view.actualSize", params.clone()); + Ok(json!({"zoom": zoom, "screenPpi": screen_ppi, "fallback": fallback, "status": message})) +} + +/// Invalid or absent device metrics must use the explicit Screen Resolution fallback. +#[cfg(any(test, target_os = "windows", target_os = "macos", target_os = "linux"))] +pub(super) fn physical_ppi(pixels: f64, millimeters: f64) -> Option { + if !pixels.is_finite() || !millimeters.is_finite() || pixels <= 0.0 || millimeters <= 0.0 { + return None; + } + let ppi = pixels * 25.4 / millimeters; + (ppi.is_finite() && (1.0..=10000.0).contains(&ppi)).then_some(ppi.floor()) +} + +#[cfg(target_os = "windows")] +fn display_ppi(ctx: &egui::Context) -> Option { + use winsafe::{HDC, prelude::*}; + + let rect = ctx.input(|input| input.viewport().outer_rect)?; + let scale = f64::from(ctx.pixels_per_point()); + let window = [f64::from(rect.left()) * scale, f64::from(rect.top()) * scale, f64::from(rect.right()) * scale, f64::from(rect.bottom()) * scale]; + if !window.iter().all(|value| value.is_finite()) { + return None; + } + let mut best = (0.0, None); + HDC::NULL + .EnumDisplayMonitors(None, |monitor, _, rect| { + let width = (window[2].min(f64::from(rect.right)) - window[0].max(f64::from(rect.left))).max(0.0); + let height = (window[3].min(f64::from(rect.bottom)) - window[1].max(f64::from(rect.top))).max(0.0); + let area = width * height; + if area > best.0 { + let ppi = monitor + .GetMonitorInfo() + .ok() + .and_then(|info| windows_monitor_width(&info.szDevice())) + .and_then(|millimeters| physical_ppi(f64::from(rect.right) - f64::from(rect.left), millimeters)); + best = (area, ppi); + } + true + }) + .ok()?; + best.1 +} + +/// GDI's HORZSIZE can be synthesized from 96 DPI on WDDM. Read the monitor's EDID instead. +#[cfg(target_os = "windows")] +fn windows_monitor_width(device: &str) -> Option { + use winsafe::{HKEY, RegistryValue, co}; + + // Without a current orientation, a rotated desktop width cannot be paired with an EDID axis safely. + let mut mode = winsafe::DEVMODE::default(); + if !winsafe::EnumDisplaySettingsEx(Some(device), winsafe::GmidxEnum::Enum(co::ENUM_SETTINGS::CURRENT), &mut mode, co::EDS::default()).ok()? + || !mode.dmFields.has(co::DM::DISPLAYORIENTATION) + { + return None; + } + let mut result = None; + for monitor in winsafe::EnumDisplayDevices(Some(device), Some(co::EDD::GET_DEVICE_INTERFACE_NAME)).take(64) { + let monitor = monitor.ok()?; + let path = monitor_registry_path(&monitor.DeviceID())?; + let key = HKEY::LOCAL_MACHINE.RegOpenKeyEx(Some(&path), co::REG_OPTION::default(), co::KEY::READ).ok()?; + let override_key = key.RegOpenKeyEx(Some("EDID_OVERRIDE"), co::REG_OPTION::default(), co::KEY::READ).ok(); + let value = match override_key.as_ref().map(|override_key| windows_edid_value(override_key, "0")) { + Some(Ok(value)) => value, + Some(Err(error)) if error != co::ERROR::FILE_NOT_FOUND => return None, + _ => windows_edid_value(&key, "EDID").ok()?, + }; + let RegistryValue::Binary(edid) = value else { return None }; + let width = oriented_width(edid_size(&edid)?, mode.dmDisplayOrientation().raw())?; + // Mirrored outputs must agree on physical size before one scale can describe both. + if result.is_some_and(|previous: f64| (previous - width).abs() > 0.5) { + return None; + } + result = Some(width); + } + result +} + +#[cfg(target_os = "windows")] +fn windows_edid_value(key: &winsafe::HKEY, value: &str) -> Result { + // Registry EDIDs are small. Bound the safe binding's allocation before asking for the value. + let mut maximum = 0; + key.RegQueryInfoKey(None, None, None, None, None, None, Some(&mut maximum), None, None)?; + if maximum > 32768 { + return Err(winsafe::co::ERROR::INVALID_DATA); + } + key.RegQueryValueEx(Some(value)) +} + +#[cfg(any(test, target_os = "windows"))] +pub(super) fn monitor_registry_path(interface: &str) -> Option { + let mut parts = interface.strip_prefix(r"\\?\")?.split('#'); + if !parts.next()?.eq_ignore_ascii_case("DISPLAY") { + return None; + } + let model = parts.next()?; + let instance = parts.next()?; + let class = parts.next()?; + if parts.next().is_some() || !class.eq_ignore_ascii_case("{e6f07b5f-ee97-4a90-b076-33f57bf4eaa7}") { + return None; + } + let safe_component = + |value: &str| !value.is_empty() && value.len() <= 256 && value.bytes().all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'&' | b'_' | b'-')); + if !safe_component(model) || !safe_component(instance) { + return None; + } + Some(format!(r"SYSTEM\CurrentControlSet\Enum\DISPLAY\{model}\{instance}\Device Parameters")) +} + +#[cfg(any(test, target_os = "windows"))] +pub(super) fn edid_size(edid: &[u8]) -> Option<[f64; 2]> { + let base = edid.get(..128)?; + if base.get(..8)? != [0, 255, 255, 255, 255, 255, 255, 0] || base.iter().fold(0u8, |sum, value| sum.wrapping_add(*value)) != 0 { + return None; + } + // EDID detailed timing descriptors carry millimetres, with the high bits shared at byte 14. + for timing in base.get(54..126)?.as_chunks::<18>().0.iter() { + if timing.get(..2)? == [0, 0] { + continue; + } + let width = u16::from(*timing.get(12)?) | (u16::from(*timing.get(14)? & 0xf0) << 4); + let height = u16::from(*timing.get(13)?) | (u16::from(*timing.get(14)? & 0x0f) << 8); + if width > 0 && height > 0 { + return Some([f64::from(width), f64::from(height)]); + } + } + let width = *base.get(21)?; + let height = *base.get(22)?; + (width > 0 && height > 0).then_some([f64::from(width) * 10.0, f64::from(height) * 10.0]) +} + +/// EDID describes the unrotated panel; desktop horizontal pixels follow the current display orientation. +#[cfg(any(test, target_os = "windows"))] +pub(super) fn oriented_width(size: [f64; 2], quarter_turns: u32) -> Option { + if !size.iter().all(|value| value.is_finite() && *value > 0.0) { + return None; + } + match quarter_turns { + 0 | 2 => Some(size[0]), + 1 | 3 => Some(size[1]), + _ => None, + } +} + +/// Missing backing-mode metrics must fall back, rather than substitute a logical display width. +#[cfg(any(test, target_os = "macos"))] +pub(super) fn backing_mode_ppi(width: Option, millimeters: f64) -> Option { + physical_ppi(width? as f64, millimeters) +} + +#[cfg(target_os = "macos")] +fn display_ppi(ctx: &egui::Context) -> Option { + use core_graphics::display::CGDisplay; + + let window = ctx.input(|input| input.viewport().outer_rect)?; + let native = ctx.native_pixels_per_point().filter(|scale| scale.is_finite() && *scale > 0.0)?; + let factor = f64::from(ctx.pixels_per_point() / native); + let mut best = (0.0, None); + for id in CGDisplay::active_displays().ok()? { + let display = CGDisplay::new(id); + let bounds = display.bounds(); + let width = (f64::from(window.right()) * factor).min(bounds.origin.x + bounds.size.width) - (f64::from(window.left()) * factor).max(bounds.origin.x); + let height = (f64::from(window.bottom()) * factor).min(bounds.origin.y + bounds.size.height) - (f64::from(window.top()) * factor).max(bounds.origin.y); + let area = width.max(0.0) * height.max(0.0); + if area > best.0 { + best = (area, backing_mode_ppi(display.display_mode().map(|mode| mode.pixel_width()), display.screen_size().width)); + } + } + best.1 +} + +#[cfg(target_os = "linux")] +fn display_ppi(ctx: &egui::Context) -> Option { + use x11rb::{connection::Connection, protocol::randr::ConnectionExt}; + + // Xwayland's virtual outputs do not describe the native Wayland display's physical size. + if std::env::var_os("WAYLAND_DISPLAY").is_some() { + return None; + } + let window = ctx.input(|input| input.viewport().outer_rect)?; + let factor = f64::from(ctx.pixels_per_point()); + let (connection, screen) = x11rb::connect(None).ok()?; + let root = connection.setup().roots.get(screen)?.root; + let resources = connection.randr_get_screen_resources_current(root).ok()?.reply().ok()?; + let mut best = (0.0, None); + for output in resources.outputs { + let output = connection.randr_get_output_info(output, resources.config_timestamp).ok()?.reply().ok()?; + if output.crtc == 0 { + continue; + } + let crtc = connection.randr_get_crtc_info(output.crtc, resources.config_timestamp).ok()?.reply().ok()?; + let x = f64::from(crtc.x); + let y = f64::from(crtc.y); + let width = (f64::from(window.right()) * factor).min(x + f64::from(crtc.width)) - (f64::from(window.left()) * factor).max(x); + let height = (f64::from(window.bottom()) * factor).min(y + f64::from(crtc.height)) - (f64::from(window.top()) * factor).max(y); + let area = width.max(0.0) * height.max(0.0); + if area > best.0 { + let mode = resources.modes.iter().find(|mode| mode.id == crtc.mode)?; + best = (area, physical_ppi(f64::from(mode.width), f64::from(output.mm_width))); + } + } + best.1 +} + +#[cfg(not(any(target_os = "windows", target_os = "macos", target_os = "linux")))] +fn display_ppi(_ctx: &egui::Context) -> Option { + None +} diff --git a/crates/ui-egui/src/menus/view_cmds/actual_size_tests.rs b/crates/ui-egui/src/menus/view_cmds/actual_size_tests.rs new file mode 100644 index 00000000000..eff9979c72e --- /dev/null +++ b/crates/ui-egui/src/menus/view_cmds/actual_size_tests.rs @@ -0,0 +1,166 @@ +use super::actual_size::{apply, backing_mode_ppi, edid_size, monitor_registry_path, oriented_width, physical_ppi}; +use crate::{PhotocraftApp, Services}; +use photocraft_engine::Session; +use serde_json::json; + +#[test] +fn actual_size_uses_whole_physical_ppi_and_keeps_the_document() { + let mut app = PhotocraftApp::new(Session::new(), Services::default()); + app.run("file.new", json!({"width": 3000, "height": 2000})).unwrap(); + app.sync_views(); + for (document_ppi, expected) in [(72.0, 95.0 / 72.0), (300.0, 95.0 / 300.0), (150.0, 95.0 / 150.0), (96.0, 95.0 / 96.0), (36.0, 95.0 / 36.0)] { + app.run("image.imageSize", json!({"resolution": document_ppi, "resample": "none"})).unwrap(); + for screen_ppi in [72.0, 96.0] { + app.run("prefs.set", json!({"path": "unitsAndRulers.screenResolution", "value": screen_ppi})).unwrap(); + app.ui.views[0].center = [126.75, 636.25]; + let before = app.session.active().unwrap().doc.clone(); + let history = app.session.active().unwrap().history.entries().len(); + let dirty = app.session.active().unwrap().is_dirty(); + let result = apply(&mut app, physical_ppi(1920.0, 509.0), &json!({})).unwrap(); + assert!((app.ui.views[0].zoom - expected).abs() < 1e-6); + assert_eq!(app.ui.views[0].center, [126.75, 636.25]); + assert_eq!(result["fallback"], false); + assert_eq!(result["screenPpi"], 95.0); + assert_eq!(app.session.active().unwrap().doc, before); + assert_eq!(app.session.active().unwrap().history.entries().len(), history); + assert_eq!(app.session.active().unwrap().is_dirty(), dirty); + } + } +} + +#[test] +fn actual_size_fallback_is_reported_by_menu_and_automation() { + let mut app = PhotocraftApp::new(Session::new(), Services::default()); + let ctx = app.ctx().clone(); + assert!(!crate::menus::is_enabled(&app, "view.actualSize")); + assert!(crate::menus::invoke(&mut app, &ctx, "view.actualSize", json!({})).is_err()); + app.run("file.new", json!({"width": 320, "height": 240})).unwrap(); + app.run("prefs.set", json!({"path": "unitsAndRulers.screenResolution", "value": 96.5})).unwrap(); + assert!(crate::menus::is_live("view.actualSize")); + assert!(crate::menus::is_enabled(&app, "view.actualSize")); + assert_eq!(super::checked(&app, "view.actualSize"), None); + let result = crate::menus::invoke(&mut app, &ctx, "view.actualSize", json!({})).unwrap(); + assert_eq!(result["fallback"], true, "a headless context has no physical monitor"); + assert_eq!(result["screenPpi"], 96.0); + assert!((app.ui.views[0].zoom - 96.0 / 72.0).abs() < 1e-6); + assert_eq!(result["status"], app.ui.status); + assert!(app.ui.status.contains("Screen Resolution")); + let (request, _receiver) = crate::control::ControlRequest::new("engine.execute", json!({"command": "view.actualSize", "params": {}})); + match crate::control::handle(&mut app, &ctx, &request) { + crate::control::Reply::Done(reply) => { + assert_eq!(reply["result"]["fallback"], true); + assert_eq!(reply["result"]["status"], app.ui.status); + } + _ => panic!("Actual Size should return its fallback result immediately"), + } + let rows = crate::menus::menu_rows(&app); + let positions: Vec<_> = + ["view.printSize", "view.actualSize", "view.flipHorizontal"].map(|id| rows.iter().position(|row| row.command.id == id).unwrap()).into(); + assert!(positions[0] < positions[1] && positions[1] < positions[2]); + let registration = crate::menus::UI_COMMANDS.iter().find(|row| row.0 == "view.actualSize").unwrap(); + assert_eq!(registration.3, None); +} + +#[test] +fn actual_size_rejects_bad_parameters_and_unusable_metrics() { + let mut app = PhotocraftApp::new(Session::new(), Services::default()); + app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); + for params in [json!(null), json!([]), json!({"ppi": 95})] { + assert!(apply(&mut app, Some(95.0), ¶ms).is_err()); + } + for (pixels, mm) in [(0.0, 509.0), (1920.0, 0.0), (f64::NAN, 509.0), (1920.0, f64::INFINITY), (1920.0, 0.001)] { + assert_eq!(physical_ppi(pixels, mm), None); + } + for ppi in [None, Some(f64::NAN), Some(-1.0)] { + assert_eq!(apply(&mut app, ppi, &json!({})).unwrap()["fallback"], true); + } +} + +#[test] +fn actual_size_remains_unsnapped_on_the_canvas_then_uses_the_next_zoom_rung() { + let mut app = PhotocraftApp::new(Session::new(), Services::default()); + app.run("file.new", json!({"width": 3000, "height": 2000})).unwrap(); + crate::canvas::testing::frame(&mut app); + app.ui.views[0].center = [1500.0, 1000.0]; + apply(&mut app, Some(95.8), &json!({})).unwrap(); + crate::canvas::testing::frame(&mut app); + assert!((app.ui.views[0].zoom - 95.0 / 72.0).abs() < 1e-6); + assert_eq!(app.ui.views[0].center, [1500.0, 1000.0]); + let ctx = app.ctx().clone(); + crate::menus::invoke(&mut app, &ctx, "view.zoomIn", json!({})).unwrap(); + crate::canvas::testing::frame(&mut app); + assert_eq!(app.ui.views[0].zoom, 2.0); +} + +#[test] +fn actual_size_reads_validated_edid_physical_dimensions() { + let mut edid = [0u8; 128]; + edid[..8].copy_from_slice(&[0, 255, 255, 255, 255, 255, 255, 0]); + edid[21] = 51; + edid[22] = 29; + edid[54] = 1; + edid[66] = 253; + edid[67] = 30; + edid[68] = 0x11; + edid[127] = 0u8.wrapping_sub(edid.iter().copied().fold(0u8, u8::wrapping_add)); + assert_eq!(edid_size(&edid), Some([509.0, 286.0])); + assert_eq!(physical_ppi(1920.0, oriented_width(edid_size(&edid).unwrap(), 0).unwrap()), Some(95.0)); + for length in 0..128 { + assert_eq!(edid_size(&edid[..length]), None); + } + edid[54] = 0; + edid[127] = edid[127].wrapping_add(1); + assert_eq!(edid_size(&edid), Some([510.0, 290.0]), "centimetres when detailed dimensions are absent"); + edid[21] = 0; + edid[127] = edid[127].wrapping_add(51); + assert_eq!(edid_size(&edid), None, "an aspect ratio has no physical width"); + edid[1] = 0; + assert_eq!(edid_size(&edid), None, "corrupt headers are unavailable"); +} + +#[test] +fn actual_size_matches_the_edid_axis_to_all_four_windows_orientations() { + let size = [600.0, 337.0]; + for (orientation, pixels, millimeters) in [(0, 1920.0, 600.0), (1, 1080.0, 337.0), (2, 1920.0, 600.0), (3, 1080.0, 337.0)] { + let width = oriented_width(size, orientation).unwrap(); + assert_eq!(width, millimeters); + assert_eq!(physical_ppi(pixels, width), Some(81.0)); + } + assert_eq!(oriented_width(size, 4), None); + for invalid in [[0.0, 337.0], [600.0, f64::NAN], [f64::INFINITY, 337.0]] { + assert_eq!(oriented_width(invalid, 1), None); + } +} + +#[test] +fn actual_size_uses_backing_mode_pixels_and_falls_back_without_a_usable_mode() { + let mut app = PhotocraftApp::new(Session::new(), Services::default()); + app.run("file.new", json!({"width": 640, "height": 480})).unwrap(); + let physical = backing_mode_ppi(Some(3024), 344.0); + assert_eq!(physical, Some(223.0), "backing width rather than a 1512-point logical mode"); + assert_eq!(physical_ppi(1512.0, 344.0), Some(111.0)); + assert_eq!(apply(&mut app, physical, &json!({})).unwrap()["fallback"], false); + for mode in [None, Some(0)] { + let missing = backing_mode_ppi(mode, 344.0); + assert_eq!(missing, None); + let fallback = apply(&mut app, missing, &json!({})).unwrap(); + assert_eq!(fallback["fallback"], true); + assert!(fallback["status"].as_str().unwrap().contains("Screen Resolution")); + } +} + +#[test] +fn actual_size_maps_only_recognized_monitor_interfaces_to_edid_keys() { + assert_eq!( + monitor_registry_path(r"\\?\DISPLAY#MODEL01#5&0000&0&UID1#{e6f07b5f-ee97-4a90-b076-33f57bf4eaa7}"), + Some(r"SYSTEM\CurrentControlSet\Enum\DISPLAY\MODEL01\5&0000&0&UID1\Device Parameters".into()) + ); + for interface in [ + "", + r"\\?\DISPLAY#MODEL01", + r"\\?\OTHER#MODEL01#INSTANCE#{e6f07b5f-ee97-4a90-b076-33f57bf4eaa7}", + r"\\?\DISPLAY#..\MODEL01#INSTANCE#{e6f07b5f-ee97-4a90-b076-33f57bf4eaa7}", + ] { + assert_eq!(monitor_registry_path(interface), None); + } +} diff --git a/crates/ui-egui/src/menus/view_cmds/dispatch.rs b/crates/ui-egui/src/menus/view_cmds/dispatch.rs index 95eeffd079a..dbcab116d5a 100644 --- a/crates/ui-egui/src/menus/view_cmds/dispatch.rs +++ b/crates/ui-egui/src/menus/view_cmds/dispatch.rs @@ -78,7 +78,13 @@ pub fn handles(id: &str) -> bool { || is_options_bar(id) || matches!( id, - "view.extras" | "view.flipHorizontal" | "view.pixelAspectRatioCorrection" | "view.patternPreview" | "view.pixelArtPreview" | "view.rotateView" + "view.extras" + | "view.flipHorizontal" + | "view.pixelAspectRatioCorrection" + | "view.patternPreview" + | "view.pixelArtPreview" + | "view.rotateView" + | "view.actualSize" ) } @@ -98,7 +104,7 @@ pub(super) fn is_enabled_with_engine(app: &PhotocraftApp, id: &str, engine_enabl // Standard again before the next pass (`leave_full_screen_without_document`). "view.screenMode.cycle" | "view.screenMode.cycleBack" => app.ui.text_edit.is_none() && doc, "view.screenMode.fullScreen" | "view.screenMode.fullScreenWithMenuBar" => doc, - "view.rotateView" => doc, + "view.rotateView" | "view.actualSize" => doc, i if i.starts_with("window.arrange.") => arrange_command(&i["window.arrange.".len()..]).is_some_and(|command| { let windows = &app.ui.document_windows; command.arrangement().enabled(app.session.documents().len(), windows.docked.len(), windows.floating.len()) @@ -274,6 +280,9 @@ pub(super) fn no_params(p: &Value) -> bool { /// Run a View/Window/Type shell command, or front an engine command with its dialog. `None` when /// `id` isn't ours. pub fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &Value) -> Option> { + if id == "view.actualSize" { + return Some(super::actual_size::invoke(app, ctx, params)); + } if let Some(result) = crate::panel_docking::command(app, id, params) { return Some(result); } diff --git a/crates/ui-egui/src/panels/layer_menu_ui.rs b/crates/ui-egui/src/panels/layer_menu_ui.rs index 5aa0be8933a..fed63c8cf18 100644 --- a/crates/ui-egui/src/panels/layer_menu_ui.rs +++ b/crates/ui-egui/src/panels/layer_menu_ui.rs @@ -64,14 +64,22 @@ pub(crate) fn layer_count_label(command: &str, multi: bool) -> Option<&'static s /// The context menu entries for a layer's row: [`entries`], led on the Background's row /// (`background`, [`photocraft_doc::Document::is_background`]) by Layer from Background… and a -/// separator, the Layer › New entry (#16764). A multi-selection keeps the plain entries. -pub fn row_entries(l: &Layer, multi: bool, has_selection: bool, background: bool) -> Vec { +/// separator, the Layer › New entry (#16764). A multi-selection keeps the plain entries. The base of a clip group +/// (`clip_base`, [`photocraft_engine::layer_multi_cmds::merges_clipping_mask`]) reads Merge Clipping Mask in place of +/// Merge Down (#18481). +pub fn row_entries(l: &Layer, multi: bool, has_selection: bool, background: bool, clip_base: bool) -> Vec { let mut v: Vec = Vec::new(); if background && !multi { v.push(Some((tl!("Layer from Background…"), "layer.new.layerFromBackground"))); v.push(None); } v.extend(entries(l, multi, has_selection)); + if clip_base + && !multi + && let Some(merge) = v.iter_mut().flatten().find(|e| e.1 == "layer.mergeDown") + { + *merge = (tl!("Merge Clipping Mask"), "layer.mergeLayers"); + } v } diff --git a/crates/ui-egui/src/panels/layers_tree.rs b/crates/ui-egui/src/panels/layers_tree.rs index 904c5ff127d..756b3ffa836 100644 --- a/crates/ui-egui/src/panels/layers_tree.rs +++ b/crates/ui-egui/src/panels/layers_tree.rs @@ -774,7 +774,8 @@ pub(crate) fn row_menu(app: &PhotocraftApp, tree: &PhotoLayers, target: &MenuTar MenuKind::Layer(id) => { let Some(l) = tree.layer(&id) else { return Vec::new() }; let background = tree.doc().is_background(id); - let mut out = commands(crate::layer_menu_ui::row_entries(l, target.on_selection, has_selection, background), target.on_selection); + let clip_base = photocraft_engine::layer_multi_cmds::merges_clipping_mask(tree.doc(), id); + let mut out = commands(crate::layer_menu_ui::row_entries(l, target.on_selection, has_selection, background, clip_base), target.on_selection); out.push(Entry::separator()); out.push(Entry::new(RENAME.to_string(), tl!("Rename Layer…").to_string())); out diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index e49b0666d84..c883be58aaf 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -159,6 +159,9 @@ fn adjustment_controls(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: LayerId, let params = crate::adjust_editors::layer_reset(app, id, adj); let _ = app.run("layer.setAdjustment", params); app.live_adjust = None; + if matches!(adj, photocraft_doc::Adjustment::BlackWhite { .. }) { + crate::adjust_editors::black_white_presets::clear_custom(ui); + } } } diff --git a/crates/ui-egui/src/panels/tool_commands.rs b/crates/ui-egui/src/panels/tool_commands.rs index d70707bee80..429c0a6842d 100644 --- a/crates/ui-egui/src/panels/tool_commands.rs +++ b/crates/ui-egui/src/panels/tool_commands.rs @@ -63,7 +63,7 @@ pub(crate) enum ToolCommand { BackgroundEraser, #[command(label = "Magic Eraser Tool", icon = "eraser_magic", kind = "tool", group = "E", default = "E", alias = "tools.select.magicEraser")] MagicEraser, - #[command(label = "Gradient Tool", icon = "gradient", kind = "tool", group = "G", default = "G", alias = "tools.select.gradient")] + #[command(label = "Gradient Tool", icon = "gradient-tool", kind = "tool", group = "G", default = "G", alias = "tools.select.gradient")] Gradient, #[command(label = "Paint Bucket Tool", icon = "paint_bucket", kind = "tool", group = "G", default = "G", alias = "tools.select.paintBucket")] PaintBucket, diff --git a/crates/ui-egui/src/panels/toolbar.rs b/crates/ui-egui/src/panels/toolbar.rs index 88cd4519597..6751d8c2def 100644 --- a/crates/ui-egui/src/panels/toolbar.rs +++ b/crates/ui-egui/src/panels/toolbar.rs @@ -27,6 +27,9 @@ mod toolbar_flyout_mark_tests; #[path = "toolbar_quick_mask_icon_tests.rs"] mod toolbar_quick_mask_icon_tests; #[cfg(test)] +#[path = "toolbar_rotate_view_reset_tests.rs"] +mod toolbar_rotate_view_reset_tests; +#[cfg(test)] #[path = "toolbar_tab_reveal_tests.rs"] mod toolbar_tab_reveal_tests; @@ -349,7 +352,7 @@ pub fn toolbar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { if let Some(tool) = out.select { crate::tool_memory::select(app, tool); } - // A double click on Hand fits the image on screen, on Zoom shows it at 100% (Photoshop); with no document open there + // A double click on Hand fits the image on screen, Rotate View resets its angle, and Zoom shows it at 100%; with no document open there // is nothing to do. The framework reports no double click after a modified click. match out.double_clicked { Some(Tool::Hand) => { @@ -358,6 +361,9 @@ pub fn toolbar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { Some(Tool::Zoom) => { let _ = crate::menus::invoke(app, &ctx, "view.actualPixels", json!({})); } + Some(Tool::RotateView) => { + let _ = crate::menus::invoke(app, &ctx, "view.resetView", json!({})); + } _ => {} } if let Some(next) = &out.last_used { diff --git a/crates/ui-egui/src/panels/toolbar_rotate_view_reset_tests.rs b/crates/ui-egui/src/panels/toolbar_rotate_view_reset_tests.rs new file mode 100644 index 00000000000..2cc3991808a --- /dev/null +++ b/crates/ui-egui/src/panels/toolbar_rotate_view_reset_tests.rs @@ -0,0 +1,102 @@ +//! Double-clicking the Rotate View icon in the Hand slot runs Reset View (#18744). + +use super::*; +use egui::{Modifiers, PointerButton}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; + +/// Use 60 Hz frames so two clicks fall inside the double-click interval. +fn harness(documents: usize) -> Harness<'static, Box> { + let mut h = Harness::builder().with_step_dt(1.0 / 60.0).with_size(egui::vec2(1200.0, 1100.0)).with_max_steps(64).build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, crate::theme::AppTheme::pro()); + let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), photocraft_engine::Session::new(), crate::Services::default()); + app.run("prefs.set", json!({"values": {"general.animatedZoom": false}})).expect("disable zoom animation"); + // Home hides the toolbar, so the empty-document case uses the workspace. + app.session.edit_prefs(|prefs| prefs.general.auto_show_home_screen = false); + for _ in 0..documents { + app.run("file.new", json!({"width": 3000, "height": 2000})).expect("new document"); + } + app.ui.tool = Tool::RotateView; + app.ui.remember_group_tool(Tool::RotateView); + app + }); + h.run_steps(4); + h +} + +/// The shown tool's rail button, excluding the options-bar button and the flyout corner. +fn slot(h: &Harness<'static, Box>, label: &str) -> egui::Pos2 { + h.query_all_by_label(label).rfind(|node| node.rect().width() >= 16.0).expect("the toolbar shows the tool").rect().center() +} + +fn click(h: &mut Harness<'static, Box>, at: egui::Pos2) { + h.event(egui::Event::PointerMoved(at)); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + h.run_steps(1); + } +} + +#[test] +fn double_click_on_the_rotate_view_slot_resets_only_the_active_angle() { + let mut h = harness(2); + h.state_mut().ui.views[0].rotation = -23.0; + let active = &mut h.state_mut().ui.views[1]; + active.rotation = 37.0; + active.zoom = 0.75; + active.center = [1400.0, 900.0]; + h.run_steps(4); + let before = h.state().ui.views[1].clone(); + let other = h.state().ui.views[0].clone(); + let doc = h.state().session.active().expect("active document").doc.clone(); + let history = h.state().session.active().expect("active document").history.past_len(); + let at = slot(&h, "Rotate View Tool"); + click(&mut h, at); + assert_eq!(h.state().ui.views[1].rotation, 37.0, "one click only selects Rotate View"); + click(&mut h, at); + h.run_steps(4); + let after = &h.state().ui.views[1]; + assert_eq!(after.rotation, 0.0, "the second click runs Reset View"); + assert_eq!((after.zoom, after.center), (before.zoom, before.center)); + assert_eq!(h.state().ui.views[0], other, "the other document keeps its view"); + assert_eq!(h.state().ui.tool, Tool::RotateView); + let session = h.state().session.active().expect("active document"); + assert!(std::sync::Arc::ptr_eq(&session.doc, &doc)); + assert_eq!(session.history.past_len(), history); +} + +#[test] +fn double_click_on_rotate_view_without_a_document_keeps_the_tool_selected() { + let mut h = harness(0); + let at = slot(&h, "Rotate View Tool"); + click(&mut h, at); + click(&mut h, at); + h.run_steps(4); + assert_eq!(h.state().ui.tool, Tool::RotateView); + assert!(h.state().ui.views.is_empty()); + assert!(h.state().session.active().is_none()); +} + +#[test] +fn hand_and_zoom_keep_their_double_click_actions() { + for (tool, label) in [(Tool::Hand, "Hand Tool"), (Tool::Zoom, "Zoom Tool")] { + let mut h = harness(1); + h.state_mut().ui.tool = tool; + h.state_mut().ui.remember_group_tool(tool); + let view = &mut h.state_mut().ui.views[0]; + view.zoom = 0.75; + view.center = [1400.0, 900.0]; + h.run_steps(4); + let at = slot(&h, label); + click(&mut h, at); + click(&mut h, at); + h.run_steps(4); + let view = &h.state().ui.views[0]; + if tool == Tool::Hand { + assert!(view.zoom > 0.0 && view.zoom < 0.75, "Hand fits the large document on screen"); + assert_eq!(view.center, [1500.0, 1000.0]); + } else { + assert_eq!(view.zoom, 1.0, "Zoom shows actual pixels"); + } + } +} diff --git a/crates/ui-egui/src/tools/gradient_ui/bar.rs b/crates/ui-egui/src/tools/gradient_ui/bar.rs index 71027229739..a971b1de93c 100644 --- a/crates/ui-egui/src/tools/gradient_ui/bar.rs +++ b/crates/ui-egui/src/tools/gradient_ui/bar.rs @@ -22,12 +22,18 @@ use super::{fill_layer_active, options_changed, stops}; use crate::state::Tool; use crate::{PhotocraftApp, panel_docking}; +/// The modes a layer mask has no use for: they need colour (#18634). The reference greys them, with Behind, while a +/// layer mask is the target. +const COLOUR_MODES: [BlendMode; 6] = + [BlendMode::DarkerColor, BlendMode::LighterColor, BlendMode::Hue, BlendMode::Saturation, BlendMode::Color, BlendMode::Luminosity]; + /// The modes the Classic gradient lists, with a rule above each group: `None` is Behind, third /// after Normal and Dissolve, and greyed where `behind_enabled` is false (the Background, as the -/// Paint Bucket's). The list has no Clear (#12011). -fn blend_modes(behind_enabled: bool) -> Vec>> { - static CACHE: crate::i18n::LangCache>>> = crate::i18n::LangCache::new(); - CACHE.get_or_build(behind_enabled, || { +/// Paint Bucket's). The list has no Clear (#12011). With `on_mask` (a layer mask targeted) the +/// [`COLOUR_MODES`] are greyed too. +fn blend_modes(behind_enabled: bool, on_mask: bool) -> Vec>> { + static CACHE: crate::i18n::LangCache<(bool, bool), Vec>>> = crate::i18n::LangCache::new(); + CACHE.get_or_build((behind_enabled, on_mask), || { let mut keys: Vec>> = crate::blend_keys::tool_modes(Tool::Gradient) .unwrap_or_default() .into_iter() @@ -38,11 +44,23 @@ fn blend_modes(behind_enabled: bool) -> Vec>> { keys.insert(at, BlendKeyEntry::behind(None)); blend_entries(&keys, |entry| Label::from(tl!(entry.key.map_or("Behind", BlendMode::label)).to_string())) .into_iter() - .map(|entry| if entry.value() == Some(&None) { entry.enabled(behind_enabled) } else { entry }) + .map(|entry| match entry.value().copied() { + Some(None) => entry.enabled(behind_enabled), + Some(Some(mode)) if on_mask && COLOUR_MODES.contains(&mode) => entry.enabled(false), + _ => entry, + }) .collect() }) } +/// The Classic gradient's Mode list for the current target. +pub(crate) fn mode_entries(app: &PhotocraftApp) -> Vec>> { + // Behind paints under a layer's pixels: greyed on a mask, a channel or Quick Mask, as the engine refuses it there. + let target = crate::canvas::paint_target(app); + let pixels = target == serde_json::json!("pixels"); + blend_modes(pixels && crate::brush_mode_menu::enabled(app, crate::brush_mode_menu::Item::Behind), target == serde_json::json!("mask")) +} + /// `add` captioned `label` as a field of the bar. fn labelled(ui: &mut egui::Ui, label: &str, mut add: impl FnMut(&mut egui::Ui)) { Field::new(label.to_owned()).show(ui, |ui, _| add(ui)); @@ -60,9 +78,8 @@ pub(crate) fn bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let words = Env::of(ui).words::(); let styles: Vec> = GradientStyle::ALL.iter().map(|style| Entry::new(*style, style.label(&words)).icon(style.icon())).collect(); let modes = [Entry::new(false, tl!("Gradient").to_owned()), Entry::new(true, tl!("Classic gradient").to_owned())]; - // Behind paints under a layer's pixels: greyed on a mask, a channel or Quick Mask, as the engine refuses it there. let pixels = crate::canvas::paint_target(app) == serde_json::json!("pixels"); - let blends = blend_modes(pixels && crate::brush_mode_menu::enabled(app, crate::brush_mode_menu::Item::Behind)); + let blends = mode_entries(app); let open_editor; let presets; { @@ -185,3 +202,7 @@ fn preset_picker(app: &mut PhotocraftApp, ui: &mut egui::Ui, at: egui::Pos2) { keep_popup(ui, PresetPopup { open: false, ..popup }); } } + +#[cfg(test)] +#[path = "../../gradient_mask_target_greyed_modes_tests.rs"] +mod gradient_mask_target_greyed_modes_tests; diff --git a/crates/ui-egui/tests/it/camera_raw_histogram.rs b/crates/ui-egui/tests/it/camera_raw_histogram.rs index f90da8ef974..e6c2af6106e 100644 --- a/crates/ui-egui/tests/it/camera_raw_histogram.rs +++ b/crates/ui-egui/tests/it/camera_raw_histogram.rs @@ -11,13 +11,13 @@ fn described(h: &Harness<'_, Box>) -> Value { /// Runs the app's frames until the develop of the settings in force has landed, and returns the dialog's /// description. The develop waits on the framework's queue until a request finishes it, as the agent entry /// point's `waitPreview` does. -fn settled(h: &mut Harness<'_, Box>) -> Value { - h.run_steps(2); +fn settled(h: &mut Harness<'_, Box>, previous_revision: u64) -> Value { for _ in 0..2000 { craft::ui::runtime::pending::finish_jobs(&h.ctx, std::time::Duration::from_secs(30)); h.run_steps(1); let now = described(h); - if now["previewPending"] == false && !now["histogram"].is_null() { + let advanced = now["previewRevision"].as_u64().is_some_and(|revision| revision > previous_revision); + if advanced && now["previewPending"] == false && !now["histogram"].is_null() { return now; } std::thread::sleep(std::time::Duration::from_millis(5)); @@ -25,35 +25,32 @@ fn settled(h: &mut Harness<'_, Box>) -> Value { panic!("the Camera Raw preview never finished"); } -/// A control request, then the develop it asks for. -fn request(h: &mut Harness<'_, Box>, params: Value) -> Value { +fn request(h: &mut Harness<'_, Box>, params: Value) { let ctx = h.ctx.clone(); - let reply = camera_raw_ui::menu(h.state_mut(), &ctx, "filter.cameraRaw", ¶ms).unwrap().unwrap(); - if described(h).is_null() { - return reply; - } - settled(h) + camera_raw_ui::menu(h.state_mut(), &ctx, "filter.cameraRaw", ¶ms).unwrap().unwrap(); } #[test] fn histogram_matches_visible_preview_at_all_supported_depths_and_cancel_commit_are_reversible() { + let mut h = Harness::builder().with_step_dt(1.0 / 60.0).with_size(egui::vec2(1200.0, 800.0)).build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, AppTheme::pro()); + PhotocraftApp::with_context(cc.egui_ctx.clone(), photocraft_engine::Session::new(), Default::default()) + }); for mode in ["rgb", "grayscale"] { for depth in [8, 16, 32] { - let mut h = Harness::builder().with_step_dt(1.0 / 60.0).with_size(egui::vec2(1200.0, 800.0)).build_eframe(move |cc| { - PhotocraftApp::setup_context(&cc.egui_ctx, AppTheme::pro()); - let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), photocraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": 16, "height": 8, "mode": mode, "depth": depth})).unwrap(); - app.run("layer.new.layer", json!({})).unwrap(); - app.run("edit.fill", json!({"color": "#808080"})).unwrap(); - app - }); - h.run_steps(3); + let app = h.state_mut(); + app.run("file.new", json!({"width": 16, "height": 8, "mode": mode, "depth": depth})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("edit.fill", json!({"color": "#808080"})).unwrap(); + h.run_steps(1); let original = h.state().session.active().unwrap().doc.clone(); let steps = h.state().session.active().unwrap().history.past_len(); - let initial = request(&mut h, json!({})); + request(&mut h, json!({})); + let initial = settled(&mut h, 0); assert_eq!(initial["histogram"]["samples"], 128); - let changed = request(&mut h, json!({"ui": {"set": {"exposure": 1.0}}})); - assert_ne!(changed["histogram"]["red"], initial["histogram"]["red"]); + request(&mut h, json!({"ui": {"set": {"exposure": 1.0}}})); + let changed = settled(&mut h, initial["previewRevision"].as_u64().unwrap()); + assert_ne!(changed["histogram"]["red"], initial["histogram"]["red"], "{mode}/{depth}: exposure must change the histogram"); assert_eq!(h.state().session.active().unwrap().history.past_len(), steps); request(&mut h, json!({"ui": {"cancel": true}})); assert!(std::sync::Arc::ptr_eq(&h.state().session.active().unwrap().doc, &original), "Cancel leaves the document alone"); @@ -62,8 +59,13 @@ fn histogram_matches_visible_preview_at_all_supported_depths_and_cancel_commit_a h.state_mut().run("edit.undo", json!({})).unwrap(); assert!(std::sync::Arc::ptr_eq(&h.state().session.active().unwrap().doc, &original)); h.state_mut().run("edit.redo", json!({})).unwrap(); - let committed = request(&mut h, json!({})); + request(&mut h, json!({})); + let committed = settled(&mut h, 0); assert_eq!(committed["histogram"]["red"], changed["histogram"]["red"], "{mode}/{depth}: graph and committed pixels disagree"); + request(&mut h, json!({"ui": {"cancel": true}})); + assert!(described(&h).is_null(), "{mode}/{depth}: Camera Raw must close"); + h.state_mut().run("file.close", json!({"discard": true})).unwrap(); + assert!(h.state().session.active().is_none(), "{mode}/{depth}: the next case needs a fresh document"); } } } diff --git a/crates/ui-egui/tests/it/free_transform_preview_canvas.rs b/crates/ui-egui/tests/it/free_transform_preview_canvas.rs index f5890874b7f..050549e99cc 100644 --- a/crates/ui-egui/tests/it/free_transform_preview_canvas.rs +++ b/crates/ui-egui/tests/it/free_transform_preview_canvas.rs @@ -90,12 +90,14 @@ fn button(h: &mut Harness, at: Pos2, pressed: bool) { h.step(); } -/// The rendered frame's RGB at document point `(x, y)`. -fn rgb_at(h: &mut Harness, x: f64, y: f64) -> [u8; 3] { - let p = screen(h, x, y); +/// Sample all points in the same rendered frame. +fn rgb_at(h: &mut Harness, points: [[f64; 2]; N]) -> [[u8; 3]; N] { + let points = points.map(|[x, y]| screen(h, x, y)); let img = h.render().expect("render"); - let px = img.get_pixel(p.x.floor() as u32, p.y.floor() as u32); - [px[0], px[1], px[2]] + points.map(|p| { + let px = img.get_pixel(p.x.floor() as u32, p.y.floor() as u32); + [px[0], px[1], px[2]] + }) } fn is_red(c: [u8; 3]) -> bool { @@ -110,11 +112,12 @@ fn shows_the_layer_inside_the_box(gpu_canvas: bool) { let _gpu = photocraft_testkit::gpu_lock(); let Some(mut h) = harness(gpu_canvas) else { return }; setup(&mut h); - assert!(is_red(rgb_at(&mut h, 150.5, 150.5)), "the layer shows before the transform"); + let [before] = rgb_at(&mut h, [[150.5, 150.5]]); + assert!(is_red(before), "the layer shows before the transform"); control(&mut h, "ui.menu.invoke", json!({"id": "edit.freeTransform"})); assert!(h.state().ui.transform.is_some(), "Free Transform is open"); - let inside = rgb_at(&mut h, 150.5, 150.5); + let [inside] = rgb_at(&mut h, [[150.5, 150.5]]); assert!(is_red(inside), "the layer shows inside the box once Free Transform opens, not the background: {inside:?}"); // Drag the box 60 px right from its middle and hold: the preview follows the pointer. The samples sit off the @@ -125,12 +128,11 @@ fn shows_the_layer_inside_the_box(gpu_canvas: bool) { for i in 1..=6 { pointer_move(&mut h, from + (to - from) * (i as f32 / 6.0)); } - let moved = rgb_at(&mut h, 230.5, 130.5); + let [moved, vacated] = rgb_at(&mut h, [[230.5, 130.5], [120.5, 130.5]]); assert!(is_red(moved), "the moved square shows where the drag took it: {moved:?}"); - let vacated = rgb_at(&mut h, 120.5, 130.5); assert!(is_white(vacated), "the place the square left shows the background: {vacated:?}"); button(&mut h, to, false); - let released = rgb_at(&mut h, 230.5, 130.5); + let [released] = rgb_at(&mut h, [[230.5, 130.5]]); assert!(is_red(released), "the moved square still shows after the release: {released:?}"); } @@ -158,14 +160,14 @@ fn cancelling_shows_no_moved_pixels(gpu_canvas: bool) { pointer_move(&mut h, from + (to - from) * (i as f32 / 6.0)); } button(&mut h, to, false); - assert!(is_red(rgb_at(&mut h, 230.5, 130.5)), "the box moved the square"); + let [before] = rgb_at(&mut h, [[230.5, 130.5]]); + assert!(is_red(before), "the box moved the square"); h.event(egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }); h.step(); assert!(h.state().ui.transform.is_none(), "Escape ended Free Transform"); - let moved = rgb_at(&mut h, 230.5, 130.5); + let [moved, back] = rgb_at(&mut h, [[230.5, 130.5], [150.5, 130.5]]); assert!(is_white(moved), "the cancelling frame shows no moved pixels: {moved:?}"); - let back = rgb_at(&mut h, 150.5, 130.5); assert!(is_red(back), "the square is back in its place: {back:?}"); } diff --git a/crates/ui-egui/tests/it/gpu_tests/adjust_preview_gpu.rs b/crates/ui-egui/tests/it/gpu_tests/adjust_preview_gpu.rs index f8f56bb371d..43790c4a406 100644 --- a/crates/ui-egui/tests/it/gpu_tests/adjust_preview_gpu.rs +++ b/crates/ui-egui/tests/it/gpu_tests/adjust_preview_gpu.rs @@ -162,15 +162,22 @@ fn pm(p: &[f32; 4]) -> [f32; 4] { [p[0] * p[3], p[1] * p[3], p[2] * p[3], p[3]] } -fn diffs(a: &[[f32; 4]], b: &[[f32; 4]]) -> Vec { - a.iter().zip(b).map(|(x, y)| (0..4).map(|c| (pm(x)[c] - pm(y)[c]).abs()).fold(0.0, f32::max)).collect() -} - /// Largest difference, ignoring up to `skip` outliers. fn max_diff(a: &[[f32; 4]], b: &[[f32; 4]], skip: usize) -> f32 { - let mut d = diffs(a, b); - d.sort_by(|x, y| y.total_cmp(x)); - d.get(skip).copied().unwrap_or(0.0) + assert_eq!(a.len(), b.len()); + let diffs = a.iter().zip(b).map(|(x, y)| { + let (x, y) = (pm(x), pm(y)); + x.into_iter().zip(y).map(|(x, y)| (x - y).abs()).fold(0.0, f32::max) + }); + if skip == 0 { + diffs.fold(0.0, f32::max) + } else { + let mut diffs = diffs.collect::>(); + if skip >= diffs.len() { + return 0.0; + } + *diffs.select_nth_unstable_by(skip, |x, y| y.total_cmp(x)).1 + } } #[test] @@ -181,11 +188,18 @@ fn preview_layer_composites_on_the_gpu_like_the_command() { // command's CPU result (adds the command's rounding to the layer depth). let (tol_gpu, tol_cmd) = (2.0 / 255.0, 2.5 / 255.0); let mut worst = 0.0f32; + let full_sweep = photocraft_testkit::full_sweep(); for mode in [ColorMode::Rgb, ColorMode::Grayscale] { - for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { + for (depth_index, depth) in [SampleType::U8, SampleType::U16, SampleType::F32].into_iter().enumerate() { for selection in [false, true] { let (doc, target) = document(mode, depth, selection); - for kind in photocraft_ui_egui::adjust_editors::KINDS { + for (kind_index, kind) in photocraft_ui_egui::adjust_editors::KINDS.into_iter().enumerate() { + // Keep every shader at every mode and depth, sampling both mask + // paths. The CPU test preview_composite_matches_the_destructive_command + // already compares all combinations; the full GPU sweep keeps them too. + if !full_sweep && selection != (kind_index + depth_index).is_multiple_of(2) { + continue; + } let params = sample(kind); let preview = match preview_document(&doc, target, kind, ¶ms) { Ok(p) => p, @@ -209,7 +223,7 @@ fn preview_layer_composites_on_the_gpu_like_the_command() { let mut s = photocraft_engine::Session::new(); s.add_document(doc.clone(), None); s.select_layer(target).unwrap(); - s.execute(&format!("image.adjustments.{kind}"), params.clone()).unwrap(); + s.execute(&format!("image.adjustments.{kind}"), params).unwrap(); let cmd = photocraft_compose::render(&s.active().unwrap().doc, b).into_px(); let d = max_diff(&on_gpu, &cmd, skip); worst = worst.max(d); @@ -284,7 +298,7 @@ fn proxy_preview_composites_on_the_gpu() { let (doc, target) = document(ColorMode::Rgb, SampleType::U8, selection); let proxy = proxy_base(&base_document(&doc, target).unwrap(), 2); // Render the full document too, so both share the compositor's resident textures. - render_to_vec(&mut comp, &device, &queue, &doc, doc.bounds()).unwrap(); + comp.render(&device, &queue, &doc, doc.bounds(), |_, _| {}).unwrap(); for kind in photocraft_ui_egui::adjust_editors::KINDS { let p = proxy_with_settings(&proxy, kind, &sample(kind)).unwrap(); let on_gpu = render_to_vec(&mut comp, &device, &queue, &p, p.bounds()).unwrap(); diff --git a/crates/ui-egui/tests/it/gpu_tests/arbitrary_rotation_preview.rs b/crates/ui-egui/tests/it/gpu_tests/arbitrary_rotation_preview.rs index 97ad7528ac3..88d506e0107 100644 --- a/crates/ui-egui/tests/it/gpu_tests/arbitrary_rotation_preview.rs +++ b/crates/ui-egui/tests/it/gpu_tests/arbitrary_rotation_preview.rs @@ -39,22 +39,29 @@ fn harness() -> Option { } } -fn control(h: &mut Harness, method: &str, params: Value) -> Value { +fn request(h: &mut Harness, method: &str, params: Value) -> Value { let ctx = h.ctx.clone(); let (req, _rx) = ControlRequest::new(method, params); let Reply::Done(value) = handle(h.state_mut(), &ctx, &req) else { panic!("{method} did not finish") }; assert_eq!(value["ok"], true, "{method}: {value}"); - h.run_steps(4); value["result"].clone() } +fn control(h: &mut Harness, method: &str, params: Value) -> Value { + let result = request(h, method, params); + h.run_steps(4); + result +} + fn setup(h: &mut Harness, width: u32, height: u32, zoom: f32, center: [f32; 2]) { + // Settle once after the document is filled and positioned. The fixture does not + // need a canvas frame for the old tab, the empty editor or the temporary white fill. while h.state().session.active().is_some() { - control(h, "engine.execute", json!({"command":"file.close","params":{"discard":true}})); + request(h, "engine.execute", json!({"command":"file.close","params":{"discard":true}})); } - control(h, "engine.execute", json!({"command":"prefs.set","params":{"path":"interface.language","value":"en"}})); - control(h, "engine.execute", json!({"command":"file.new","params":{"width":width,"height":height,"background":"white"}})); - control(h, "engine.execute", json!({"command":"edit.fill","params":{"color":"#2266dd"}})); + request(h, "engine.execute", json!({"command":"prefs.set","params":{"path":"interface.language","value":"en"}})); + request(h, "engine.execute", json!({"command":"file.new","params":{"width":width,"height":height,"background":"white"}})); + request(h, "engine.execute", json!({"command":"edit.fill","params":{"color":"#2266dd"}})); control(h, "ui.set", json!({"zoom":zoom,"center":center})); assert!(h.state().perf.gpu, "the fixture must use the GPU canvas"); } @@ -129,18 +136,18 @@ fn size_changing_rotation_preview_is_visible_and_preserves_the_panned_center() { setup(&mut h, width, height, zoom, center); assert_eq!(photocraft_ui_egui::proxy::factor(&h.state().session.active().unwrap().doc), factor); let id = open_previewing(&mut h); - let source = blue(&mut h, &format!("{width}x{height}-{degrees}-zero")).0; - assert!(source > 5_000, "the unrotated blue image must be visible outside the dialog"); angle(&mut h, &id, degrees); h.get_by_label("Preview").click(); h.run_steps(4); assert!(!preview_on(&h)); - assert!(blue(&mut h, &format!("{width}x{height}-{degrees}-off")).0 > 5_000, "Preview off shows the original image"); + let (original, original_top, original_bottom) = blue(&mut h, &format!("{width}x{height}-{degrees}-off")); + assert!(original > 5_000, "Preview off shows the original image"); h.get_by_label("Preview").click(); h.run_steps(4); assert!(preview_on(&h)); let (count, top, bottom) = blue(&mut h, &format!("{width}x{height}-{degrees}-on")); assert!(count > 5_000, "{width}x{height}, {degrees}°, factor {factor}: rotated blue pixels disappeared ({count} remain)"); + assert!(bottom - top > original_bottom - original_top, "{degrees}°: the rotated preview should be taller"); let rect = photocraft_ui_egui::canvas::active_view(h.state()).expect("a shown view").rect; let expected_y = rect.center().y + (height as f32 / 2.0 - center[1]) * zoom; let actual_y = (top + bottom) as f32 / 2.0; diff --git a/crates/ui-egui/tests/it/gpu_tests/canvas_16f.rs b/crates/ui-egui/tests/it/gpu_tests/canvas_16f.rs index fcdd436f7d1..8193a546e6d 100644 --- a/crates/ui-egui/tests/it/gpu_tests/canvas_16f.rs +++ b/crates/ui-egui/tests/it/gpu_tests/canvas_16f.rs @@ -227,9 +227,10 @@ fn screens(cases: Vec>) -> Option> { } harness.run_steps(6); let img = harness.render().expect("render"); - let out = std::env::temp_dir().join(name); - let _ = img.save(&out); - eprintln!("screen: {}", out.display()); + if let Some(dir) = std::env::var_os("PHOTOCRAFT_CANVAS_16F_EVIDENCE_DIR") { + std::fs::create_dir_all(&dir).expect("evidence directory"); + img.save(std::path::Path::new(&dir).join(name)).expect("save UI frame"); + } shown.push(Screen { w: img.width(), h: img.height(), px: img.into_raw() }); if let Some((doc, setup, name)) = cases.next() { harness.state_mut().session.open_document(doc, None); @@ -252,7 +253,9 @@ fn screen_levels(img: &Screen, y: u32, x0: u32, x1: u32) -> (usize, i32) { fn sixteen_bit_gradient_on_screen() { let _gpu = gpu_lock(); // A 16-bit ramp drawn by the app's canvas: smooth, monotonic, no visible steps. - let doc = gradient(SampleType::U16, 2048, 1024, 0.0, 1.0); + // The document still fits down to the same viewport and has more source levels than + // the screen can display. The extra source pixels aren't needed to spot banding. + let doc = gradient(SampleType::U16, 1024, 512, 0.0, 1.0); let Some(img) = screen(doc, &[], "photocraft-canvas-16f-gradient.png") else { return }; let (n, step) = screen_levels(&img, img.h / 2, 150, 600); assert!(n > 100 && step <= 3, "{n} levels, max step {step}"); @@ -263,7 +266,7 @@ fn thirty_two_bit_preview_exposes_values_above_one() { let _gpu = gpu_lock(); // A dark 32-bit ramp brightened +4 stops by View › 32-bit Preview Options: with an 8-bit // canvas texture its 0..1/16 range has 16 codes (banding); the float texture keeps it smooth. - let doc = gradient(SampleType::F32, 2048, 1024, 0.0, 1.0 / 16.0); + let doc = gradient(SampleType::F32, 1024, 512, 0.0, 1.0 / 16.0); // Values above 1.0 are brought into range by a negative exposure instead of clipped: 2.0 // at −3 stops shows as sRGB(lin(2.0) / 8) rather than sRGB(lin(1.0) / 8). let mut flat = Document::new("hdr", Size::new(512, 512), ColorMode::Rgb, SampleType::F32); diff --git a/crates/ui-egui/tests/it/gpu_tests/checker_canvas.rs b/crates/ui-egui/tests/it/gpu_tests/checker_canvas.rs index e3708e45920..ae99576baa8 100644 --- a/crates/ui-egui/tests/it/gpu_tests/checker_canvas.rs +++ b/crates/ui-egui/tests/it/gpu_tests/checker_canvas.rs @@ -1,13 +1,17 @@ -//! The transparency checker is made of 8 screen pixel cells (the Medium preference) at every zoom, +//! The transparency checker is made of 8 screen point cells (the Medium preference) at every zoom, //! anchored to the document's top-left corner so the pattern moves with the image. The pixel grid shows above 500% zoom, //! over pixels with content only, never over empty checker. //! //! These tests render the real app offscreen and read pixels back. They skip when no GPU adapter //! is available. The CPU canvas (no wgpu handed to the app) has its own pixel grid tests at the end. +use photocraft_color::{ColorMode, PixelFormat, SampleType}; +use photocraft_doc::{Document, Layer, LayerContent, Size}; +use photocraft_geom::Rect; +use photocraft_raster::Surface; use photocraft_ui_egui::PhotocraftApp; -use photocraft_ui_egui::control::{ControlRequest, handle}; -use serde_json::{Value, json}; +use photocraft_ui_egui::control::{ControlRequest, Reply, handle}; +use serde_json::json; type Harness = egui_kittest::Harness<'static, Box>; @@ -24,8 +28,18 @@ fn harness_with(gpu: bool) -> Option { } fn harness_with_scale(gpu: bool, ppp: f32) -> Option { + // At 2× the same document pixels take half as many points. Keep the samples + // inside the viewport without reading back a 2800 × 1600 frame. + let size = if ppp > 1.0 { + egui::vec2(820.0, 570.0) + } else if photocraft_testkit::full_sweep() { + // The full sweep also samples a 730 px wide document at 1×. + egui::vec2(1400.0, 800.0) + } else { + egui::vec2(900.0, 640.0) + }; let built = std::panic::catch_unwind(|| { - egui_kittest::Harness::builder().with_size(egui::vec2(1400.0, 800.0)).with_pixels_per_point(ppp).with_max_steps(64).wgpu().build_eframe(|cc| { + egui_kittest::Harness::builder().with_size(size).with_pixels_per_point(ppp).with_max_steps(64).wgpu().build_eframe(|cc| { PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), photocraft_engine::Session::new(), Default::default()); if let Some(rs) = cc.wgpu_render_state.as_ref().filter(|_| gpu) { @@ -43,10 +57,11 @@ fn harness_with_scale(gpu: bool, ppp: f32) -> Option { } } -fn control(h: &mut Harness, method: &str, params: Value) { +fn set_view(h: &mut Harness, zoom: f32, center: [f32; 2]) { let ctx = h.ctx.clone(); - let (req, _rx) = ControlRequest::new(method, params); - handle(h.state_mut(), &ctx, &req); + let (req, _rx) = ControlRequest::new("ui.set", json!({"zoom": zoom, "center": center})); + let Reply::Done(reply) = handle(h.state_mut(), &ctx, &req) else { panic!("setting the view did not finish") }; + assert_eq!(reply["ok"], true, "{reply}"); h.run_steps(4); } @@ -87,30 +102,23 @@ impl Shot { } } -/// Opens a `doc` px square document at `zoom` (transparent, or filled black when `black`), renders -/// it with the pixel grid on or off, and returns the screenshot with the document's left and top -/// screen edge and its width in screen pixels. -fn render(h: &mut Harness, zoom: f32, doc: u32, black: bool, grid: bool) -> (Shot, u32, u32, u32) { - render_on(h, true, zoom, doc, black, grid) +fn open_document(h: &mut Harness, doc: u32, black: bool, grid: bool) { + let app = h.state_mut(); + while app.session.active().is_some() { + app.run("file.close", json!({"discard": true})).expect("close"); + } + let background = if black { "white" } else { "transparent" }; + app.run("file.new", json!({"width": doc, "height": doc, "background": background})).expect("new"); + if black { + app.run("edit.fill", json!({"color": "#000000"})).expect("fill"); + } + app.sync_views(); + app.ui.view.show.pixel_grid = grid; } -/// [`render`] on the GPU canvas (`gpu`) or the CPU canvas. -fn render_on(h: &mut Harness, gpu: bool, zoom: f32, doc: u32, black: bool, grid: bool) -> (Shot, u32, u32, u32) { - { - let app = h.state_mut(); - while app.session.active().is_some() { - app.run("file.close", json!({"discard": true})).expect("close"); - } - let background = if black { "white" } else { "transparent" }; - app.run("file.new", json!({"width": doc, "height": doc, "background": background})).expect("new"); - if black { - app.run("edit.fill", json!({"color": "#000000"})).expect("fill"); - } - app.sync_views(); - app.ui.view.show.pixel_grid = grid; - } - control(h, "ui.set", json!({"zoom": zoom, "center": [doc as f32 / 2.0, doc as f32 / 2.0]})); - h.run_steps(3); +/// Zooms the current document and returns the screenshot and the document's physical-pixel bounds. +fn render_on(h: &mut Harness, gpu: bool, zoom: f32, doc: u32, black: bool) -> (Shot, u32, u32, u32) { + set_view(h, zoom, [doc as f32 / 2.0; 2]); assert_eq!(h.state().perf.gpu, gpu, "zoom {zoom}: expected the {} canvas", if gpu { "GPU" } else { "CPU" }); let rendered = h.render().expect("render"); let (width, height) = (rendered.width(), rendered.height()); @@ -122,7 +130,8 @@ fn render_on(h: &mut Harness, gpu: bool, zoom: f32, doc: u32, black: bool, grid: return (img, origin.x.round() as u32, origin.y.round() as u32, (doc as f32 * zoom).round() as u32); } let r = h.state().last_canvas_rect; - let (cx, cy) = (r.center().x as u32, r.center().y as u32); + let center = r.center() * h.ctx.pixels_per_point(); + let (cx, cy) = (center.x as u32, center.y as u32); let (x0, w) = longest_run((0..width).map(|x| is_checker_grey(img.at(x, cy)))); let (y0, hgt) = longest_run((0..height).map(|y| is_checker_grey(img.at(cx, y)))); let doc_px = (doc as f32 * zoom).round() as i64; @@ -135,14 +144,33 @@ fn checker_cells_are_8_screen_pixels_at_every_zoom() { let _gpu = photocraft_testkit::gpu_lock(); let Some(mut h) = harness() else { return }; h.run_steps(4); - // The 8 px cell never changes with the zoom. - for (zoom, doc) in [(0.5, 64), (1.0, 64), (1.1, 64), (2.0, 32), (3.3, 32), (5.5, 32), (8.0, 32), (13.0, 32), (32.0, 12)] { - let (img, x0, y0, _) = render(&mut h, zoom, doc, false, false); - let n = ((doc as f32 * zoom) / 8.0) as u32; + // The checker draws in screen points, independent of the document zoom. + // Sample reduced, 1:1, fractional and magnified views, including 2× displays. + let zooms_1x: &[(f32, u32)] = if photocraft_testkit::full_sweep() { + &[(0.5, 64), (1.0, 64), (1.1, 64), (2.0, 32), (3.3, 32), (5.5, 32), (8.0, 32), (13.0, 32), (32.0, 12)] + } else { + &[(0.5, 64), (1.0, 64), (1.1, 64)] + }; + let zooms_2x = [(8.0, 32), (32.0, 12)]; + let cases = zooms_1x.iter().map(|&(zoom, doc)| (1.0, zoom, doc)).chain(zooms_2x.into_iter().map(|(zoom, doc)| (2.0, zoom, doc))); + let mut current_size = 0; + for (ppp, zoom, doc) in cases { + if h.ctx.pixels_per_point() != ppp { + h.input_mut().viewports.get_mut(&egui::ViewportId::ROOT).expect("root viewport").native_pixels_per_point = Some(ppp); + h.run_steps(4); + } + assert_eq!(h.ctx.pixels_per_point(), ppp); + if current_size != doc { + open_document(&mut h, doc, false, false); + current_size = doc; + } + let (img, x0, y0, _) = render_on(&mut h, true, zoom, doc, false); + let cell = (8.0 * ppp) as u32; + let n = (doc as f32 * zoom) as u32 / cell; assert!(n >= 2, "zoom {zoom}: test needs at least two cells"); for row in 0..n.min(4) { for col in 0..n.min(6) { - let (sx, sy) = (x0 + col * 8 + 4, y0 + row * 8 + 4); + let (sx, sy) = (x0 + col * cell + cell / 2, y0 + row * cell + cell / 2); let got = img.at(sx, sy); let want = if (col + row) % 2 == 0 { LIGHT } else { DARK }; assert!( @@ -152,8 +180,8 @@ fn checker_cells_are_8_screen_pixels_at_every_zoom() { } } // Crisp: every pixel of the row is exactly one of the two greys, no blended edges. - let y = y0 + 4; - for x in x0..x0 + (n * 8).min(48) { + let y = y0 + cell / 2; + for x in x0..x0 + n.min(6) * cell { let v = img.at(x, y)[0]; assert!(v == LIGHT || v == DARK, "zoom {zoom}: blended pixel {v} at ({x}, {y})"); } @@ -170,10 +198,11 @@ fn pixel_grid_shows_above_500_percent_and_lightens_a_dark_pixel_by_about_a_quart let _gpu = photocraft_testkit::gpu_lock(); let Some(mut h) = harness() else { return }; h.run_steps(4); - let (flat, x0, y0, _) = render(&mut h, 5.0, 48, true, true); + open_document(&mut h, 24, true, true); + let (flat, x0, y0, _) = render_on(&mut h, true, 5.0, 24, true); assert!(lit_columns(&flat, x0, y0 + 20, 100).is_empty(), "no grid at 500%"); for zoom in [6.0f32, 8.0, 12.0] { - let (img, x0, y0, _) = render(&mut h, zoom, 48, true, true); + let (img, x0, y0, _) = render_on(&mut h, true, zoom, 24, true); let lit = lit_columns(&img, x0, y0 + (zoom * 3.5) as u32, (zoom * 10.0) as u32); assert_eq!(lit.len(), 10, "zoom {zoom}: grid columns {lit:?}"); assert!(lit.windows(2).all(|p| p[1] - p[0] == zoom as u32), "zoom {zoom}: spacing of {lit:?}"); @@ -187,8 +216,9 @@ fn pixel_grid_is_not_drawn_over_empty_checker() { let _gpu = photocraft_testkit::gpu_lock(); let Some(mut h) = harness() else { return }; h.run_steps(4); + open_document(&mut h, 24, false, true); for zoom in [8.0f32, 16.0] { - let (img, x0, y0, _) = render(&mut h, zoom, 24, false, true); + let (img, x0, y0, _) = render_on(&mut h, true, zoom, 24, false); for y in y0..y0 + 64 { for x in x0..x0 + 64 { let v = img.at(x, y)[0]; @@ -204,10 +234,11 @@ fn cpu_pixel_grid_shows_above_500_percent_over_content() { for ppp in [1.0, 2.0] { let Some(mut h) = harness_with_scale(false, ppp) else { return }; h.run_steps(4); - let (flat, x0, y0, _) = render_on(&mut h, false, 5.0, 48, true, true); + open_document(&mut h, 24, true, true); + let (flat, x0, y0, _) = render_on(&mut h, false, 5.0, 24, true); assert!(lit_columns(&flat, x0, y0 + 20, 100).is_empty(), "no grid at 500%"); for zoom in [6.0f32, 8.0, 12.0] { - let (img, x0, y0, _) = render_on(&mut h, false, zoom, 48, true, true); + let (img, x0, y0, _) = render_on(&mut h, false, zoom, 24, true); let y = y0 + (zoom * 3.5) as u32; let lit = lit_columns(&img, x0, y, (zoom * 10.0) as u32); assert_eq!(lit.len(), 10, "scale {ppp}, zoom {zoom}: one physical pixel per line, columns {lit:?}"); @@ -224,9 +255,12 @@ fn cpu_pixel_grid_is_not_drawn_over_empty_checker() { let Some(mut h) = harness_with(false) else { return }; h.run_steps(4); // The CPU checker has soft cell edges of its own, so compare with and without the grid. + open_document(&mut h, 24, false, false); for zoom in [8.0f32, 16.0] { - let (without, x0, y0, _) = render_on(&mut h, false, zoom, 24, false, false); - let (with, x1, y1, _) = render_on(&mut h, false, zoom, 24, false, true); + h.state_mut().ui.view.show.pixel_grid = false; + let (without, x0, y0, _) = render_on(&mut h, false, zoom, 24, false); + h.state_mut().ui.view.show.pixel_grid = true; + let (with, x1, y1, _) = render_on(&mut h, false, zoom, 24, false); assert_eq!((x0, y0), (x1, y1), "zoom {zoom}: the document moved"); for y in y0..y0 + 64 { for x in x0..x0 + 64 { @@ -236,56 +270,48 @@ fn cpu_pixel_grid_is_not_drawn_over_empty_checker() { } } -/// The pixel grid over a flat `grey` document at 800%: the largest difference, in 8-bit levels, -/// between a grid line and the pixel interior beside it. -fn grid_line_contrast_over_grey(h: &mut Harness, grey: u8) -> i32 { - { - let app = h.state_mut(); - while app.session.active().is_some() { - app.run("file.close", json!({"discard": true})).expect("close"); - } - app.run("file.new", json!({"width": 48, "height": 48, "background": "white"})).expect("new"); - app.run("edit.fill", json!({"color": format!("#{grey:02x}{grey:02x}{grey:02x}")})).expect("fill"); - app.sync_views(); - app.ui.view.show.pixel_grid = true; - } - control(h, "ui.set", json!({"zoom": 8.0, "center": [24.0, 24.0]})); - h.run_steps(3); - assert!(h.state().perf.gpu, "expected the GPU canvas"); - let rendered = h.render().expect("render"); - let img = Shot { w: rendered.width(), px: rendered.into_raw() }; - let r = h.state().last_canvas_rect; - let (cx, cy) = (r.center().x as u32, r.center().y as u32); - // The median of an 8 px block is a pixel interior whichever line the block straddles. - let mut block: Vec = (0..64).map(|i| img.at(cx + i % 8, cy + i / 8)[0] as i32).collect(); - block.sort_unstable(); - let interior = block[32]; - // Walk out to the document edge: the pasteboard is far darker than any grid line. - let near = |x: u32, y: u32| (img.at(x, y)[0] as i32 - interior).abs() < 50; - let x0 = (0..=cx).rev().take_while(|x| near(*x, cy)).last().unwrap_or(cx); - let y0 = (0..=cy).rev().take_while(|y| near(cx, *y)).last().unwrap_or(cy); - // Pixel (col, row) owns the grid line on its left and top edge, 8 screen px apart. - let y = y0 + 8 * 3 + 4; - (2..6).map(|col| (img.at(x0 + 8 * col, y)[0] as i32 - img.at(x0 + 8 * col + 4, y)[0] as i32).abs()).max().unwrap_or(0) -} - #[test] fn pixel_grid_does_not_flip_colour_across_mid_tones() { let _gpu = photocraft_testkit::gpu_lock(); let Some(mut h) = harness() else { return }; h.run_steps(4); - // 0x87 and 0x90 sit either side of luma 0.55, where the line used to switch from a full white - // line to a full black one. Both now give a faint line, so neighbouring cells match. - for grey in [0x87u8, 0x90] { - let c = grid_line_contrast_over_grey(&mut h, grey); - assert!(c <= 14, "grey {grey:#04x}: grid line differs from its pixel by {c} levels, want a faint line"); + // Put both sides of the old luma cutoff and the stronger dark/light lines in one frame. + // Sample inside each swatch so an edge between swatches cannot pass as a grid line. + let greys = [0x87u8, 0x90, 0x60, 0xd0, 0xff]; + let mut doc = Document::new("grid midtones", Size::new(40, 16), ColorMode::Rgb, SampleType::U8); + let mut surface = Surface::new(doc.pixel_format()); + for (i, grey) in greys.into_iter().enumerate() { + let x = i as i32 * 8; + let v = f32::from(grey) / 255.0; + surface.fill_rect(Rect::new(x, 0, x + 8, 16), &[v, v, v, 1.0]); } - // The fade must not remove the grid where it is needed: dark and light pixels keep a clear - // line (white over 0x60, black over 0xd0 and white; black itself is in the unit tests, as the - // dark pasteboard defeats this walk to the document edge). - for grey in [0x60u8, 0xd0, 0xff] { - let c = grid_line_contrast_over_grey(&mut h, grey); - assert!(c >= 20, "grey {grey:#04x}: grid line differs from its pixel by only {c} levels"); + doc.layers.push(Layer::new("swatches", LayerContent::Raster(surface))); + let app = h.state_mut(); + app.session.add_document(doc, None); + app.sync_views(); + app.ui.view.show.pixel_grid = true; + set_view(&mut h, 8.0, [20.0, 8.0]); + assert!(h.state().perf.gpu); + let img = h.render().expect("render swatches"); + let center = h.state().last_canvas_rect.center(); + let x0 = (center.x - 20.0 * 8.0).round() as u32; + let y = (center.y + 3.5 * 8.0).round() as u32; + for (i, grey) in greys.into_iter().enumerate() { + let x = x0 + i as u32 * 64; + let contrast = (2..6) + .map(|col| { + let edge = x + 8 * col; + let inside = img.get_pixel(edge + 4, y)[0]; + assert!(inside.abs_diff(grey) <= 1, "wrong swatch at {edge}: {inside} vs {grey}"); + (edge - 1..=edge + 1).map(|sx| img.get_pixel(sx, y)[0].abs_diff(inside)).max().expect("grid line") + }) + .max() + .expect("swatch columns"); + if i < 2 { + assert!(contrast <= 14, "grey {grey:#04x}: grid line differs from its pixel by {contrast} levels, want a faint line"); + } else { + assert!(contrast >= 20, "grey {grey:#04x}: grid line differs from its pixel by only {contrast} levels"); + } } } @@ -296,8 +322,7 @@ fn pixel_grid_does_not_flip_colour_across_mid_tones() { /// it, which the `inside` assertion reads: on the GPU canvas its texture (`Rgba8Unorm` for 8-bit, `Rgba16Float` for /// 16/32-bit, see `canvas_16f.rs`). So every canvas and scale runs 8-bit, and the GPU canvas adds 16-bit at 1x and /// 32-bit at 2x. -fn grid_depths(gpu: bool, ppp: f32) -> Vec { - use photocraft_color::SampleType; +fn grid_depths(gpu: bool, ppp: f32) -> Vec { match (gpu, ppp > 1.0) { (true, false) => vec![SampleType::U8, SampleType::U16], (true, true) => vec![SampleType::U8, SampleType::F32], @@ -307,36 +332,49 @@ fn grid_depths(gpu: bool, ppp: f32) -> Vec { fn pixel_grid_is_solid_and_visible_at_scale(gpu: bool, ppp: f32) { let _gpu = photocraft_testkit::gpu_lock(); - use photocraft_color::{ColorMode, PixelFormat}; - use photocraft_doc::{Document, Layer, LayerContent, Size}; - use photocraft_geom::Rect; - use photocraft_raster::Surface; let Some(mut h) = harness_with_scale(gpu, ppp) else { return }; for depth in grid_depths(gpu, ppp) { - for v in [0.0, 1.0] { - let mut doc = Document::new("grid contrast", Size::new(32, 16), ColorMode::Rgb, depth); - let mut surface = Surface::new(PixelFormat::new(ColorMode::Rgb, depth, true)); - surface.fill_rect(Rect::new(0, 0, 32, 16), &[v, v, v, 1.0]); - doc.layers.push(Layer::new("opaque", LayerContent::Raster(surface))); - let app = h.state_mut(); - app.session.add_document(doc, None); - app.sync_views(); - app.ui.view.show.pixel_grid = true; - for zoom in [7.119, 8.0, 22.825] { - control(&mut h, "ui.set", json!({"zoom": zoom, "center": [16.0, 8.0]})); - assert_eq!(h.state().perf.gpu, gpu); - let img = h.render().expect("render opaque grid"); - let center = h.state().last_canvas_rect.center() * ppp; - let x0 = center.x - 16.0 * zoom; - let y = (center.y + 3.25 * zoom).floor() as u32; + let mut doc = Document::new("grid contrast", Size::new(32, 16), ColorMode::Rgb, depth); + let mut surface = Surface::new(PixelFormat::new(ColorMode::Rgb, depth, true)); + // Both neutral fills take the same grid draw path, with opposite line contrast. + // Separate rows let them share one readback at each depth and zoom. + surface.fill_rect(Rect::new(0, 0, 32, 8), &[0.0, 0.0, 0.0, 1.0]); + surface.fill_rect(Rect::new(0, 8, 32, 16), &[1.0; 4]); + doc.layers.push(Layer::new("opaque", LayerContent::Raster(surface))); + let app = h.state_mut(); + app.session.add_document(doc, None); + app.sync_views(); + app.ui.view.show.pixel_grid = true; + // Keep the 500% cutoff at each scale. Across the two scales, sample both + // fractional and integer grid alignment, including the largest zoom. + let visible_zooms: &[f32] = if photocraft_testkit::full_sweep() { + &[7.119, 8.0, 22.825] + } else if ppp == 1.0 { + &[7.119] + } else { + &[8.0, 22.825] + }; + for zoom in (depth == SampleType::U8).then_some(5.0).into_iter().chain(visible_zooms.iter().copied()) { + set_view(&mut h, zoom, [16.0, 8.0]); + assert_eq!(h.state().perf.gpu, gpu); + assert_eq!(h.ctx.pixels_per_point(), ppp); + let img = h.render().expect("render opaque grid"); + let center = h.state().last_canvas_rect.center() * ppp; + let x0 = center.x - 16.0 * zoom; + for (v, dy) in [(0, -2.75), (255, 3.25)] { + let y = (center.y + dy * zoom).floor() as u32; for x in 2..30 { let edge = (x0 + x as f32 * zoom).floor() as u32; for sy in y..y + 3 { let inside = img.get_pixel((x0 + (x as f32 + 0.5) * zoom).floor() as u32, sy)[0]; - assert_eq!(inside, (v * 255.0) as u8); + assert_eq!(inside, v); let contrast = (edge - 1..=edge + 1).map(|sx| img.get_pixel(sx, sy)[0].abs_diff(inside)).max().expect("line"); - assert!(contrast >= 28, "{gpu:?}/{depth:?}, scale {ppp}, zoom {zoom}, fill {v}, ({x}, {sy}): invisible grid ({contrast})"); + if zoom == 5.0 { + assert_eq!(contrast, 0, "grid visible at 500%, {gpu:?}/{depth:?}, scale {ppp}, fill {v}"); + } else { + assert!(contrast >= 28, "{gpu:?}/{depth:?}, scale {ppp}, zoom {zoom}, fill {v}, ({x}, {sy}): invisible grid ({contrast})"); + } } } } diff --git a/crates/ui-egui/tests/it/gpu_tests/drag_preview_canvas.rs b/crates/ui-egui/tests/it/gpu_tests/drag_preview_canvas.rs index 208dac9e950..03030efc629 100644 --- a/crates/ui-egui/tests/it/gpu_tests/drag_preview_canvas.rs +++ b/crates/ui-egui/tests/it/gpu_tests/drag_preview_canvas.rs @@ -197,17 +197,22 @@ fn marquee_previews_show_while_dragging_on_white_and_black_at_1x_and_2x() { // which the marquee tool paints through `ToolContext::marching_ants`). White on white (#253) hid the light ants // and black would hide the dark ones; over grey the test sees both inks at once, so an outline missing either // colour fails here as it failed on one of the two documents. (The name is the one CI's slow-test order lists.) - // One harness for both scales: the app derives its scale from the window's native one every frame - // (`prefs_ui/appearance.rs` `interface_zoom`), so the 2x pass sets that, as a move to a HiDPI display does. + // Both shapes paint through the same scale-aware marching-ants painter. + // Sample the rectangle at 1× and the curve at 2× by default; the full + // sweep also covers each shape at the other scale. + let full_sweep = photocraft_testkit::full_sweep(); let Some(mut h) = harness(1.0) else { return }; h.run_steps(4); - for ppp in [1.0f32, 2.0] { + for (ppp, primary) in [(1.0f32, "rectMarquee"), (2.0, "ellipseMarquee")] { if let Some(root) = h.input_mut().viewports.get_mut(&egui::ViewportId::ROOT) { root.native_pixels_per_point = Some(ppp); } h.run_steps(4); assert_eq!(h.ctx.pixels_per_point(), ppp, "the harness runs at {ppp}x"); for tool in ["rectMarquee", "ellipseMarquee"] { + if tool != primary && !full_sweep { + continue; + } setup(&mut h, GREY, tool); let (a, b) = ([100.0, 80.0], [300.0, 220.0]); let before = render(&mut h); @@ -246,8 +251,8 @@ fn marquee_previews_show_while_dragging_on_white_and_black_at_1x_and_2x() { } // Each move's frame shows the outline where the pointer is now (no stale frame). pointer_move(&mut h, 340.0, 250.0); - let img = render(&mut h); if tool == "rectMarquee" { + let img = render(&mut h); let [top, right, ..] = edges(&h, a, [340.0, 250.0]); for (ink, test) in inks() { assert!(coverage(&img, ppp, top.0, top.1, test) > 0.3, "{tool} @{ppp}x: top edge follows the pointer ({ink})"); diff --git a/crates/ui-egui/tests/it/gpu_tests/live_stroke_canvas.rs b/crates/ui-egui/tests/it/gpu_tests/live_stroke_canvas.rs index 1556fb0e04c..bf92a75c034 100644 --- a/crates/ui-egui/tests/it/gpu_tests/live_stroke_canvas.rs +++ b/crates/ui-egui/tests/it/gpu_tests/live_stroke_canvas.rs @@ -141,7 +141,6 @@ fn frames(h: &mut Harness, c: Case) -> (Pixels, Pixels, Pixels, bool) { // The smoothing tool option syncs on the first frame with the Brush: set it after. h.state_mut().session.tools.brush.smoothing.amount = c.smoothing; let canvas = |h: &mut Harness| { - h.run_steps(3); let r = h.state().last_canvas_rect.shrink(4.0); let img = h.render().expect("render"); let mut px = Vec::new(); @@ -152,10 +151,13 @@ fn frames(h: &mut Harness, c: Case) -> (Pixels, Pixels, Pixels, bool) { } px }; + h.run_steps(3); let before = canvas(h); let pressure = |t: f64| if c.pressure { 0.3 + 0.7 * t } else { 1.0 }; control(h, "ui.pointer", json!({"events": [{"kind": "down", "x": 100, "y": 100, "pressure": pressure(0.0)}]})); - let n = 14; + // Keep the whole curved path and both ends of the pressure ramp. The full + // sweep also exercises the original denser sequence of pointer events. + let n = if photocraft_testkit::full_sweep() { 14 } else { 8 }; let mut last = (100.0, 100.0); for i in 1..=n { let t = f64::from(i) / f64::from(n); @@ -168,11 +170,12 @@ fn frames(h: &mut Harness, c: Case) -> (Pixels, Pixels, Pixels, bool) { // The pointer stays held at its last point, as a mouse held still repeats its position. let held = |h: &mut Harness| { control(h, "ui.pointer", json!({"events": [{"kind": "move", "x": last.0, "y": last.1, "pressure": pressure(1.0)}]})); - canvas(h) + h.run_steps(3); }; - let drawing = settled(h, held); + let drawing = settled(h, held, canvas); let gpu = h.state().perf.gpu && !c.flip; control(h, "ui.pointer", json!({"events": [{"kind": "up", "x": last.0, "y": last.1}]})); + h.run_steps(3); let done = canvas(h); (before, drawing, done, gpu) } @@ -180,22 +183,28 @@ fn frames(h: &mut Harness, c: Case) -> (Pixels, Pixels, Pixels, bool) { /// The canvas once the live stroke has stopped changing (#13477). The stroke paints on its own /// thread and a frame waits only a few real ms for it, so on a slow machine its newest step /// arrives late, and only a later pointer event shows it; release would then paint the rest. -/// `picture` holds the pointer still and takes a picture, with short real waits between them, -/// until the stroke is idle and three pictures in a row match (matching pixels alone don't prove -/// a slow step has finished): at most `TRIES` times, so a canvas that never settles fails -/// instead of hanging or comparing an unsettled picture. -fn settled(h: &mut Harness, picture: impl Fn(&mut Harness) -> Pixels) -> Pixels { +/// Keep feeding the held pointer until the stroke is idle and three pictures in a row match. +/// A busy stroke can't be stable, so advance those frames without a GPU readback. +fn settled(h: &mut Harness, held: impl Fn(&mut Harness), picture: impl Fn(&mut Harness) -> Pixels) -> Pixels { const TRIES: usize = 80; - let mut last = picture(h); + let mut last = None; let mut unchanged = 0; - for _ in 0..TRIES { - std::thread::sleep(std::time::Duration::from_millis(25)); - let next = picture(h); - unchanged = if next == last { unchanged + 1 } else { 0 }; - last = next; - if unchanged >= 2 && !h.state().live_stroke_busy() { - return last; + for attempt in 0..=TRIES { + if attempt != 0 { + std::thread::sleep(std::time::Duration::from_millis(25)); } + held(h); + if h.state().live_stroke_busy() { + last = None; + unchanged = 0; + continue; + } + let next = picture(h); + unchanged = if last.as_ref() == Some(&next) { unchanged + 1 } else { 0 }; + if unchanged >= 2 { + return next; + } + last = Some(next); } panic!("the live stroke did not settle before release"); } diff --git a/crates/ui-egui/tests/it/gpu_tests/ui_scale_canvas.rs b/crates/ui-egui/tests/it/gpu_tests/ui_scale_canvas.rs index c661370ea64..3ff626b86ce 100644 --- a/crates/ui-egui/tests/it/gpu_tests/ui_scale_canvas.rs +++ b/crates/ui-egui/tests/it/gpu_tests/ui_scale_canvas.rs @@ -86,26 +86,20 @@ fn assert_document_size_is_physical(gpu: bool) { let Some(mut h) = harness(gpu) else { return }; h.run_steps(4); const DOC: u32 = 60; + let app = h.state_mut(); + app.run("file.new", json!({"width": DOC, "height": DOC, "background": "white"})).expect("new"); + app.run("edit.fill", json!({"color": "#000000"})).expect("fill"); + app.sync_views(); // A fractional and an integer UI scale: the canvas sees the scale only as `pixels_per_point` (device px per doc px // = zoom x ppp), and its sampling branches on that product being below 1, whole (or 2 and up) or fractional // (`gpu_canvas::callback::filter_mode`). 125% gives 1.25 and 2.5 at the two zooms, as 150% would; 200% gives 2 and // 4, covering 100%'s 1 and 2, where a dropped ppp could not show anyway (#15652). for ui_scale in ["125", "200"] { - { - let app = h.state_mut(); - while app.session.active().is_some() { - app.run("file.close", json!({"discard": true})).expect("close"); - } - app.run("prefs.set", json!({"values": {"interface.uiScale": ui_scale}})).expect("ui scale"); - app.run("file.new", json!({"width": DOC, "height": DOC, "background": "white"})).expect("new"); - app.run("edit.fill", json!({"color": "#000000"})).expect("fill"); - app.sync_views(); - } + h.state_mut().run("prefs.set", json!({"values": {"interface.uiScale": ui_scale}})).expect("ui scale"); h.run_steps(6); assert_eq!(h.state().perf.gpu, gpu, "UI Scale {ui_scale}: expected the {} canvas", if gpu { "GPU" } else { "CPU" }); for zoom in [1.0f32, 2.0] { control(&mut h, "ui.set", json!({"zoom": zoom, "center": [DOC as f32 / 2.0, DOC as f32 / 2.0]})); - h.run_steps(4); let (w, hgt) = document_physical_size(&mut h); let want = (DOC as f32 * zoom).round() as i64; assert!(