From 41e0348f157e097de40bc2c757343919fc2ab551 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hartmut=20N=C3=B6renberg?= Date: Sat, 7 Nov 2026 20:37:03 +0100 Subject: [PATCH 01/42] fix(ui): the Arbitrary rotation dialog keeps the ruler's two decimals (#12035) straighten_defaults put the ruler's straightening angle into the image.rotation.arbitrary dialog at full precision, but every number field whose range spans more than 10 rounds to one decimal as the dialog draws (filter_dialog.rs:930): the Angle range is -359.99..359.99 (mode_cmds.rs:684), so a ruler from 100,100 to 400,300 opened the Rotate Canvas dialog at 33.7, Counter clockwise, and OK ran the rotation at 33.7 degrees. The reference application keeps the ruler's angle to two decimals there: it opens at 33.69 degrees, Counter clockwise. The rounding rule gains a per-field precision beside the angle dial's list: only the Arbitrary angle field keeps hundredths, both in the value the field writes back and in the places it shows. It follows the existing slider_row_prec idiom (Exposure's stops, #4164), so the field's arrow and drag step follow its shown precision like theirs. Small ranges keep their two decimals, every other wide field its one; how the reference rounds a third decimal is not measured, so it still rounds half away from zero like today. A drawn 318 px square says 441 px across at 33.69 degrees and 442 at 33.7, which is what pins OK to the two-decimal angle end to end. Tests go in the new crates/ui-egui/src/dialogs/arbitrary_ruler_prefill_tests.rs (the measured pre-fill, the clockwise default pair, OK's angle, and a pin that Gaussian Blur's radius, Twirl's angle and a 0..1 centre keep the precision they have today); dialogs.rs only gains the mod line it needs. Fixes #12035 --- crates/ui-egui/src/dialogs.rs | 2 + .../dialogs/arbitrary_ruler_prefill_tests.rs | 99 +++++++++++++++++++ crates/ui-egui/src/dialogs/filter_dialog.rs | 27 ++++- 3 files changed, 125 insertions(+), 3 deletions(-) create mode 100644 crates/ui-egui/src/dialogs/arbitrary_ruler_prefill_tests.rs diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 82a1b6a0939..003b09ab5d8 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -1225,6 +1225,8 @@ pub fn open_command_dialog(app: &mut PhotocraftApp, command: &str, label: &str) pub mod adjust_dialog; pub mod adjust_editors; pub mod adjust_preview; +#[cfg(test)] +mod arbitrary_ruler_prefill_tests; pub(crate) mod bitmap_dialog; pub mod blur_pins; pub mod brush_preset_dialog; diff --git a/crates/ui-egui/src/dialogs/arbitrary_ruler_prefill_tests.rs b/crates/ui-egui/src/dialogs/arbitrary_ruler_prefill_tests.rs new file mode 100644 index 00000000000..cb947d0b0b3 --- /dev/null +++ b/crates/ui-egui/src/dialogs/arbitrary_ruler_prefill_tests.rs @@ -0,0 +1,99 @@ +//! #12035: Image Rotation › Arbitrary pre-fills the ruler's straightening angle at the +//! precision the reference application shows. A ruler from 100,100 to 400,300 (A -33.7° on +//! the Info panel) opens the Rotate Canvas dialog at 33.69°, Counter clockwise, and OK runs +//! `image.rotation.arbitrary` with that two-decimal angle, not the field's old one-decimal +//! round. The Angle range is -359.99..359.99, wide, so today's wide-range rounding to one +//! decimal decided the dialog's value; only this field now keeps hundredths. + +use super::filter_dialog::{body, open, params_of}; +use crate::PhotocraftApp; +use serde_json::{Map, Value, json}; + +/// Draw a dialog body once, as a live dialog does every frame: the drawn fields are what +/// the dialog shows and what OK sends. +fn drawn(f: &mut Map) { + egui::Context::default().run_ui(Default::default(), |ui| body(ui, f)).textures_delta.clear(); +} + +/// A 318 px square document (the size `ok_runs_the_two_decimal_angle` measures on), a ruler +/// from 100,100 to `end`, the opened Arbitrary dialog and its fields after one drawn frame. +fn ruler_dialog(end: [i32; 2]) -> (PhotocraftApp, u64, Map) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 318, "height": 318})).unwrap(); + app.run("image.analysis.rulerTool", json!({"start": [100, 100], "end": end})).unwrap(); + let id = open(&mut app, "image.rotation.arbitrary").unwrap(); + let mut f = app.ui.dialog_mut(id).unwrap().fields.clone(); + drawn(&mut f); + (app, id, f) +} + +/// The measured case: the Rotate Canvas dialog opens at 33.69°, Counter clockwise — the +/// angle keeps two decimals where the wide-range rule used to round it to 33.7. +#[test] +fn ruler_prefill_keeps_the_measured_two_decimal_angle() { + let (_app, _id, f) = ruler_dialog([400, 300]); + let a = f["angle"].as_f64().unwrap(); + assert!((a - 33.69).abs() < 1e-3, "the dialog opens at {a}, want the measured 33.69"); + assert_eq!(crate::widgets::fmt_num2(a), "33.69", "the Angle field shows the measured string"); + assert_eq!(f["direction"], json!("ccw"), "a ruler falling to the right straightens counter-clockwise"); +} + +/// A ruler that needs a clockwise turn pre-fills Clockwise, at the same two decimals; +/// with no ruler the dialog opens at today's default (0, Clockwise). +#[test] +fn clockwise_ruler_prefills_clockwise_and_no_ruler_keeps_the_default() { + // (100,100) → (400,50) rises to the right: a 9.46° clockwise turn. + let (_app, _id, f) = ruler_dialog([400, 50]); + let a = f["angle"].as_f64().unwrap(); + assert_eq!(f["direction"], json!("cw"), "a rising ruler pre-fills Clockwise"); + assert!((a - 9.46).abs() < 1e-3, "the clockwise pre-fill is {a}, want 9.46 to two decimals"); + // No ruler: today's default, unchanged. + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 318, "height": 318})).unwrap(); + let id = open(&mut app, "image.rotation.arbitrary").unwrap(); + let mut f = app.ui.dialog_mut(id).unwrap().fields.clone(); + drawn(&mut f); + assert_eq!(f["angle"], json!(0.0), "without a ruler the dialog opens at today's 0"); + assert_eq!(f["direction"], json!("cw"), "without a ruler the dialog opens Clockwise"); +} + +/// OK runs `image.rotation.arbitrary` with the two-decimal angle: a 318 px square rotated by +/// 33.69° measures 441 px across, by 33.7° 442 px — the dialog's rounding must not decide. +#[test] +fn ok_runs_the_two_decimal_angle() { + let (mut app, id, f) = ruler_dialog([400, 300]); + let params = params_of(&f); + assert!((params["angle"].as_f64().unwrap() - 33.69).abs() < 1e-3, "OK sends {params}"); + app.ui.dialog_mut(id).unwrap().fields = f; + let r = crate::dialogs::confirm(&mut app, id).unwrap(); + assert_eq!((r["width"].as_u64(), r["height"].as_u64()), (Some(441), Some(441)), "442 would mean the 33.7 round ran"); +} + +/// The fix is per-field: unrelated number fields keep the precision they have today — +/// wide ranges round to one decimal (in another dialog, and under the same key name), +/// small ranges keep their two. +#[test] +fn other_number_fields_keep_their_precision() { + // A wide range in another dialog: Gaussian Blur's radius (0.1..1000) rounds to one decimal. + let mut f = Map::new(); + f.insert("__command".into(), json!("filter.blur.gaussianBlur")); + f.insert("radius".into(), json!(7.26)); + drawn(&mut f); + let r = f["radius"].as_f64().unwrap(); + assert!((r - 7.3).abs() < 1e-5, "the Gaussian Blur radius {r} must stay at one decimal"); + // The same key the fix touches, in another dialog: Twirl's angle (-999..999) rounds to one. + let mut f = Map::new(); + f.insert("__command".into(), json!("filter.distort.twirl")); + f.insert("angle".into(), json!(33.69)); + drawn(&mut f); + let a = f["angle"].as_f64().unwrap(); + assert!((a - 33.7).abs() < 1e-5, "Twirl's angle {a} keeps the one-decimal round"); + // A small range keeps its two decimals (Radial Blur spins, so the centre fields stay plain). + let mut f = Map::new(); + f.insert("__command".into(), json!("filter.blur.radialBlur")); + f.insert("method".into(), json!("spin")); + f.insert("centerX".into(), json!(0.123)); + drawn(&mut f); + let x = f["centerX"].as_f64().unwrap(); + assert!((x - 0.12).abs() < 1e-5, "the Radial Blur centre {x} keeps its two decimals"); +} diff --git a/crates/ui-egui/src/dialogs/filter_dialog.rs b/crates/ui-egui/src/dialogs/filter_dialog.rs index 540c1bb3b97..1aa350d53ba 100644 --- a/crates/ui-egui/src/dialogs/filter_dialog.rs +++ b/crates/ui-egui/src/dialogs/filter_dialog.rs @@ -763,6 +763,26 @@ fn uses_angle_dial(command: &str, key: &str) -> bool { key == "angle" && ANGLE_DIAL.contains(&command) } +/// Wide-range number fields that still show two decimals: the Rotate Canvas angle keeps +/// hundredths of a degree, so the ruler's straightening angle reaches the dialog as 33.69 and +/// not 33.7 (#12035). The arrow and drag step follow the shown precision, as elsewhere. +fn wide_field_decimals(command: &str, key: &str) -> Option { + match (command, key) { + ("image.rotation.arbitrary", "angle") => Some(2), + _ => None, + } +} + +/// The scale a drawn number field rounds to: two decimals for small ranges (0–1 thresholds and +/// centres) and for the wide fields that show them (#12035), one decimal for the other wide ones. +fn field_scale(command: &str, key: &str, min: f32, max: f32) -> f32 { + match wide_field_decimals(command, key) { + Some(d) => 10f32.powi(d.min(6) as i32), + None if max - min <= 10.0 => 100.0, + None => 10.0, + } +} + /// Replace Color (#4143): the dialog's "From" colour, sampled from the image with a canvas /// eyedropper like Photoshop's. While armed, the next click on the image writes the merged /// composite colour into the `color` field (the same sampler the Color Picker uses). @@ -924,11 +944,12 @@ pub fn body(ui: &mut egui::Ui, f: &mut Map) { } else { // A double-click on the slider puts it back to the filter's default. let gestures = crate::widgets::RowGestures { reset: Some(default), wheel_step: None, ..Default::default() }; - crate::widgets::slider_row_with(ui, &label(&p.key), &mut v, min..=max, unit, None, gestures); + crate::widgets::slider_row_prec(ui, &label(&p.key), &mut v, min..=max, unit, None, gestures, wide_field_decimals(&cmd, &p.key)); } }); - // Small ranges (0–1 thresholds and centres) keep the two decimals their field shows. - let scale = if max - min <= 10.0 { 100.0 } else { 10.0 }; + // The field's shown precision: small ranges keep their two decimals, and so + // does the Arbitrary angle; the other wide fields round to one (#12035). + let scale = field_scale(&cmd, &p.key, min, max); f.insert(p.key, json!((v * scale).round() / scale)); } Kind::Choice { options, default } => { From 647dd7254236c59ad931e1ef833d37c18a1b98b5 Mon Sep 17 00:00:00 2001 From: DuBearte <130190089+DuBearte@users.noreply.github.com> Date: Sat, 7 Nov 2026 14:51:59 -0500 Subject: [PATCH 02/42] Airbrush: about ten dabs a second while held, and a click lays two dabs Fixes #11886. Co-Authored-By: Claude Opus 5.5 --- crates/paint/src/airbrush_rate_tests.rs | 47 +++++++++++++++++++++++++ crates/paint/src/brush.rs | 3 +- crates/paint/src/brush_tests.rs | 9 ++--- crates/paint/src/dynamics.rs | 13 +++++-- crates/paint/src/lib.rs | 2 ++ 5 files changed, 67 insertions(+), 7 deletions(-) create mode 100644 crates/paint/src/airbrush_rate_tests.rs diff --git a/crates/paint/src/airbrush_rate_tests.rs b/crates/paint/src/airbrush_rate_tests.rs new file mode 100644 index 00000000000..0b6b3e45c96 --- /dev/null +++ b/crates/paint/src/airbrush_rate_tests.rs @@ -0,0 +1,47 @@ +//! #11886: with Airbrush on, a brush held still builds up at about ten dabs a second and a plain +//! click lays two dabs, as in Photoshop. Measured there with the default 13 px soft brush at Flow +//! 10 %, black on white: the dab centre reads 205 after a click and 26 after a 2 s hold, and 229 +//! with Airbrush off however long the button is held. + +use photocraft_color::PixelFormat; +use photocraft_raster::Surface; + +use crate::{BrushSettings, StrokePoint, render_stroke}; + +fn brush(build_up: bool) -> BrushSettings { + BrushSettings { size: 13.0, hardness: 0.0, flow: 0.1, pressure_size: false, build_up, color: [0.0, 0.0, 0.0, 1.0], ..BrushSettings::default() } +} + +/// The 0–255 value at the dab centre over white after holding the button still for `ms`. +fn centre_after_hold(b: &BrushSettings, ms: f64) -> f32 { + let a = StrokePoint { time: 0.0, ..StrokePoint::new(30.0, 30.0, 1.0) }; + let z = StrokePoint { time: ms, ..a }; + let mut s = Surface::new(PixelFormat::RGBA32F); + render_stroke(&mut s, b, &[a, z], None, false, 1.0); + 255.0 * (1.0 - s.rgba(30, 30)[3]) +} + +#[test] +fn the_default_rate_is_ten_dabs_a_second() { + assert_eq!(BrushSettings::default().build_up_rate, 10.0); +} + +#[test] +fn a_click_lays_two_dabs() { + let v = centre_after_hold(&brush(true), 0.0); + assert!((v - 205.0).abs() <= 5.0, "{v}"); +} + +#[test] +fn a_two_second_hold_builds_up_to_the_reference_value() { + let v = centre_after_hold(&brush(true), 2000.0); + assert!((v - 26.0).abs() <= 8.0, "{v}"); +} + +#[test] +fn airbrush_off_keeps_one_dab_however_long_it_is_held() { + for ms in [0.0, 500.0, 2000.0] { + let v = centre_after_hold(&brush(false), ms); + assert!((v - 229.0).abs() <= 3.0, "{ms} ms: {v}"); + } +} diff --git a/crates/paint/src/brush.rs b/crates/paint/src/brush.rs index fb062934f80..5f1a2523338 100644 --- a/crates/paint/src/brush.rs +++ b/crates/paint/src/brush.rs @@ -656,7 +656,8 @@ impl Default for BrushSettings { noise: false, wet_edges: false, build_up: false, - build_up_rate: 20.0, + // About ten dabs a second while held still, Photoshop's Airbrush rate (#11886). + build_up_rate: 10.0, smoothing: Smoothing::default(), protect_texture: false, locks: SectionLocks::default(), diff --git a/crates/paint/src/brush_tests.rs b/crates/paint/src/brush_tests.rs index 268ca52b95b..1e596150e78 100644 --- a/crates/paint/src/brush_tests.rs +++ b/crates/paint/src/brush_tests.rs @@ -607,7 +607,8 @@ fn build_up_accumulates_over_time() { let (n0, a0) = hold(0.0); let (n1, a1) = hold(500.0); let (n2, a2) = hold(2000.0); - assert_eq!((n0, n1, n2), (1, 11, 41)); + // A click lays two dabs with the airbrush on (#11886), then one per 50 ms at this rate. + assert_eq!((n0, n1, n2), (2, 12, 42)); assert!(a0 < a1 && a1 < a2, "{a0} {a1} {a2}"); // Without build-up, lingering adds nothing. let nb = BrushSettings { build_up: false, ..b }; @@ -622,15 +623,15 @@ fn huge_airbrush_time_gap_emits_bounded_catch_up() { let b = BrushSettings { build_up: true, build_up_rate: 1000.0, ..brush() }; let a = StrokePoint { time: 0.0, ..StrokePoint::new(20.0, 20.0, 1.0) }; let brief_pause = StrokePoint { time: 200.0, ..a }; - assert_eq!(dabs_of(&b, &[a, brief_pause]).len(), 201, "a 200 ms pause should retain its airbrush build-up"); + assert_eq!(dabs_of(&b, &[a, brief_pause]).len(), 202, "a 200 ms pause should retain its airbrush build-up (after the click's two dabs)"); let z = StrokePoint { time: f64::MAX, ..a }; let d = dabs_of(&b, &[a, z]); - assert!(d.len() <= 2, "a huge pause should resume with one dab, not replay its time backlog: {}", d.len()); + assert!(d.len() <= 3, "a huge pause should resume with one dab, not replay its time backlog: {}", d.len()); assert_eq!(d.last().map(|dab| dab.center), Some(Point::new(20.0, 20.0))); let infinite = StrokePoint { time: f64::INFINITY, ..a }; - assert!(dabs_of(&b, &[a, infinite]).len() <= 1); + assert!(dabs_of(&b, &[a, infinite]).len() <= 2, "the click's two dabs, no backlog"); } #[test] diff --git a/crates/paint/src/dynamics.rs b/crates/paint/src/dynamics.rs index b3411b7a0bb..3a5fc824890 100644 --- a/crates/paint/src/dynamics.rs +++ b/crates/paint/src/dynamics.rs @@ -338,6 +338,15 @@ impl PathWalker { self } + /// The stroke's first point. With the airbrush on it lays two dabs, so a plain click builds + /// up as Photoshop's does (#11886). + fn emit_first(&mut self, point: StrokePoint, out: &mut impl FnMut(StepInput)) { + self.emit(point, out); + if self.interval.is_some() { + self.emit(point, out); + } + } + fn emit(&mut self, point: StrokePoint, out: &mut impl FnMut(StepInput)) { if let Some(g) = self.grid { self.cell = Some((grid_cell(point.x, g), grid_cell(point.y, g))); @@ -363,7 +372,7 @@ impl PathWalker { } } if let Some(f) = self.pending_first.take() { - self.emit(f, out); + self.emit_first(f, out); } if len > 1e-9 { // Speed spacing needs the segment's duration; without timestamps (a straight ⇧-click @@ -426,7 +435,7 @@ impl PathWalker { pub fn finish(&mut self, out: &mut impl FnMut(StepInput)) { if let Some(f) = self.pending_first.take() { - self.emit(f, out); + self.emit_first(f, out); } } } diff --git a/crates/paint/src/lib.rs b/crates/paint/src/lib.rs index 7054e11492a..eb67461a36a 100644 --- a/crates/paint/src/lib.rs +++ b/crates/paint/src/lib.rs @@ -406,5 +406,7 @@ mod tests { } } +#[cfg(test)] +mod airbrush_rate_tests; #[cfg(test)] mod brush_tests; From d98291984be9ec47bb96da2d33a9692497a092da Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sat, 7 Nov 2026 14:32:53 -0600 Subject: [PATCH 03/42] Eyedropper: at 100 % zoom and below an N by N Average covers (N+1) x (N+1) screen pixels (#11751) --- crates/engine/src/cmd.rs | 2 + crates/engine/src/cmd/sample_cmds.rs | 53 +++++- .../engine/src/cmd/sample_zoom_box_tests.rs | 162 ++++++++++++++++++ crates/ui-egui/src/canvas/cursors.rs | 4 +- crates/ui-egui/src/lib.rs | 4 +- crates/ui-egui/src/panels/info.rs | 13 +- crates/ui-egui/src/tools/eyedropper_ui.rs | 23 ++- 7 files changed, 249 insertions(+), 12 deletions(-) create mode 100644 crates/engine/src/cmd/sample_zoom_box_tests.rs diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index c4addf4c22f..6b37c23d8bb 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -131,6 +131,8 @@ pub mod redeye_cmds; pub mod render_cmds; pub mod retouch_cmds; pub mod sample_cmds; +#[cfg(test)] +mod sample_zoom_box_tests; pub mod sampler_cmds; pub mod select_extra_cmds; pub mod selection_cmds; diff --git a/crates/engine/src/cmd/sample_cmds.rs b/crates/engine/src/cmd/sample_cmds.rs index 9c941a18962..13ebc7cc0bc 100644 --- a/crates/engine/src/cmd/sample_cmds.rs +++ b/crates/engine/src/cmd/sample_cmds.rs @@ -76,6 +76,32 @@ pub fn sample_rect(x: f64, y: f64, size: u32, canvas: Rect) -> Option { Some(square.intersect(&canvas)) } +/// The widest box, in document pixels, a zoomed-out average reads (#11751): at 1 % zoom a +/// 101 by 101 Average would otherwise composite a 10 200-pixel square on every pointer move. +pub const MAX_ZOOM_BOX: u32 = 4096; + +/// [`sample_rect`] for the Eyedropper at view `zoom` (screen pixels per document pixel, 1.0 is +/// 100 %), as in Photoshop (#11751). Above 100 % it is the centred `size` × `size` square. At 100 % +/// and below an N by N Average covers (N+1) × (N+1) *screen* pixels: at 100 % the document pixels +/// x−N/2 to x+N/2+1 (N/2 rounded down), at 50 % 3 by 3 covers 8 × 8 document pixels. Point +/// Sample is one pixel at every zoom; no zoom is today's centred square. +pub fn sample_rect_at(x: f64, y: f64, size: u32, zoom: Option, canvas: Rect) -> Option { + let centred = sample_rect(x, y, size, canvas)?; + let Some(zoom) = zoom.filter(|z| z.is_finite() && *z > 0.0 && *z <= 1.0) else { return Some(centred) }; + if size == 1 { + return Some(centred); + } + let (px, py) = (x.floor() as i32, y.floor() as i32); + // (N+1) screen pixels in document pixels, at least N+1. + let side = (f64::from(size + 1) / zoom).round().clamp(f64::from(size + 1), f64::from(MAX_ZOOM_BOX)) as i32; + // The pixel sits just left of the box's middle: x−N/2 … x+N/2+1 at 100 %. + let before = (side + 1) / 2 - 1; + let x0 = px.saturating_sub(before); + let y0 = py.saturating_sub(before); + let square = Rect::new(x0, y0, x0.saturating_add(side), y0.saturating_add(side)); + Some(square.intersect(&canvas)) +} + /// Round `v` to what a channel of `depth` can store (32 bit keeps the float). fn quantize(v: f32, depth: SampleType) -> f32 { let mut b = [0u8; 4]; @@ -166,7 +192,13 @@ fn sampled_document(doc: &Document, active: Option, which: SampleLayers /// the canvas. Transparent black off the canvas, over transparency, or when `which` needs an /// active layer and there is none. pub fn sample_color(doc: &Document, active: Option, x: f64, y: f64, size: u32, which: SampleLayers) -> [f32; 4] { - let Some(rect) = sample_rect(x, y, size, doc.bounds()) else { return [0.0; 4] }; + sample_color_at(doc, active, x, y, size, None, which) +} + +/// [`sample_color`] over the box the Eyedropper reads at view `zoom` ([`sample_rect_at`]); `None` +/// is the centred square, as the Color Sampler always uses (#11751). +pub fn sample_color_at(doc: &Document, active: Option, x: f64, y: f64, size: u32, zoom: Option, which: SampleLayers) -> [f32; 4] { + let Some(rect) = sample_rect_at(x, y, size, zoom, doc.bounds()) else { return [0.0; 4] }; let Some(src) = sampled_document(doc, active, which) else { return [0.0; 4] }; let buf = photocraft_compose::render(&src, rect); if size == 1 { @@ -203,6 +235,20 @@ pub fn size_param(cmd: &str, p: &Value) -> Result { } } +/// The optional `zoom` param (#11751): the view zoom the Eyedropper samples at, screen pixels per +/// document pixel (1.0 = 100 %). Missing or null: the centred box. Anything but a finite positive +/// number is an error. +pub fn zoom_param(cmd: &str, p: &Value) -> Result> { + match p.get("zoom") { + None | Some(Value::Null) => Ok(None), + Some(v) => v + .as_f64() + .filter(|z| z.is_finite() && *z > 0.0) + .map(Some) + .ok_or_else(|| bad(cmd, format!("`zoom` = {v} must be a positive number (screen pixels per document pixel, 1 = 100 %)"))), + } +} + /// The `sampleLayer` param (default `all`). pub fn layers_param(cmd: &str, p: &Value) -> Result { match p.get("sampleLayer") { @@ -225,15 +271,16 @@ pub fn specs() -> Vec { label: "Sample Color", menu: &[], shortcut: None, - params: r##"{"x":f64,"y":f64,"size":"point"|1|3|5|11|31|51|101=1,"sampleLayer":"current"|"currentAndBelow"|"all"|"allNoAdjustments"|"currentAndBelowNoAdjustments"="all"} → [r,g,b,a] (the Eyedropper's Sample Size and Sample: the composite pixel, or the average of the size×size square centred on it, clipped to the canvas; transparent off the canvas)"##, + params: r##"{"x":f64,"y":f64,"size":"point"|1|3|5|11|31|51|101=1,"sampleLayer":"current"|"currentAndBelow"|"all"|"allNoAdjustments"|"currentAndBelowNoAdjustments"="all","zoom":f64? (the view zoom, 1 = 100 %: at 100 % and below an N by N Average covers (N+1)×(N+1) screen pixels, as in Photoshop; missing: the centred square)} → [r,g,b,a] (the Eyedropper's Sample Size and Sample: the composite pixel, or the average of the size×size square centred on it, clipped to the canvas; transparent off the canvas)"##, enabled: |s| s.active().map(|_| ()).ok_or_else(|| "no document open".into()), run: |s: &mut Session, p: &Value| { const CMD: &str = "document.sampleColor"; let (x, y) = (coord(CMD, p, "x")?, coord(CMD, p, "y")?); let size = size_param(CMD, p)?; + let zoom = zoom_param(CMD, p)?; let which = layers_param(CMD, p)?; let d = s.active().ok_or(EngineError::NoDocument)?; - Ok(json!(sample_color(&d.doc, d.active_layer, x, y, size, which))) + Ok(json!(sample_color_at(&d.doc, d.active_layer, x, y, size, zoom, which))) }, journal: false, }] diff --git a/crates/engine/src/cmd/sample_zoom_box_tests.rs b/crates/engine/src/cmd/sample_zoom_box_tests.rs new file mode 100644 index 00000000000..20fbcc08b07 --- /dev/null +++ b/crates/engine/src/cmd/sample_zoom_box_tests.rs @@ -0,0 +1,162 @@ +//! #11751: the Eyedropper's N by N Average box depends on the view zoom, as in Photoshop. Above +//! 100 % it is the centred N × N square of document pixels; at 100 % and below it covers +//! (N+1) × (N+1) screen pixels (at 100 % the document pixels x−N/2 … x+N/2+1). Without a zoom +//! `document.sampleColor` keeps the centred square. + +use serde_json::{Value, json}; + +use crate::Session; + +/// The issue's test document: 800 × 600 RGB/8 white; on a pixel layer a red (220,30,30) block at +/// 100,100–300,250, 2 px black / 2 px white stripes at 350,100–450,200 (black at x 350–351, +/// 354–355, …) and a grey ramp of ten 40 px blocks from x 100, values 100, 105, …, 145, at +/// y 350–450. +fn test_document() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 800, "height": 600, "background": "white"})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Pixels"})).unwrap(); + let fill = |s: &mut Session, x: i32, y: i32, w: i32, h: i32, grey_or_hex: String| { + s.execute("select.rect", json!({"x": x, "y": y, "width": w, "height": h})).unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": grey_or_hex})).unwrap(); + }; + fill(&mut s, 100, 100, 200, 150, "#dc1e1e".into()); + fill(&mut s, 350, 100, 100, 100, "#ffffff".into()); + for x in (350..450).step_by(4) { + fill(&mut s, x, 100, 2, 100, "#000000".into()); + } + for i in 0..10 { + let v = 100 + 5 * i; + fill(&mut s, 100 + 40 * i, 350, 40, 100, format!("#{v:02x}{v:02x}{v:02x}")); + } + s.execute("select.deselect", json!({})).unwrap(); + s +} + +/// A black 400 × 400 document with one white pixel at 200,200 (the issue's probe). +fn probe() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 400, "height": 400, "background": "white"})).unwrap(); + s.execute("select.all", json!({})).unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": "#000000"})).unwrap(); + s.execute("select.rect", json!({"x": 200, "y": 200, "width": 1, "height": 1})).unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": "#ffffff"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + s +} + +/// The 8-bit RGB read at document pixel (x, y). +fn read(s: &mut Session, x: i32, y: i32, size: u32, zoom: Option) -> [i64; 3] { + let mut p = json!({"x": f64::from(x) + 0.5, "y": f64::from(y) + 0.5, "size": size}); + if let Some(z) = zoom { + p["zoom"] = json!(z); + } + let v = s.execute("document.sampleColor", p).unwrap(); + let c = |i: usize| (v[i].as_f64().unwrap() * 255.0).round() as i64; + [c(0), c(1), c(2)] +} + +fn grey(v: i64) -> [i64; 3] { + [v, v, v] +} + +#[test] +fn at_100_percent_the_test_document_reads_the_measured_table() { + // Sample Size: stripes x 351, stripes x 352 (y 150), grey x 139 (y 400), red left edge x 100 (y 150). + // The reference application's table, except grey x 139 up to 51 by 51: that box is exactly + // half 100 and half 105, a mean of 102.5, which the reference reads 102 and PhotoCraft's shared + // `average` rounds to 103 (half up, as every Sample Size average does today). The box is right + // (101 by 101, whose mean is no tie, reads 122 in both). + const TIE: i64 = 103; + let measured: [(u32, [[i64; 3]; 4]); 6] = [ + (3, [grey(128), grey(128), grey(TIE), [229, 86, 86]]), + (5, [grey(128), grey(85), grey(TIE), [232, 105, 105]]), + (11, [grey(170), grey(149), grey(TIE), [235, 124, 124]]), + (31, [grey(175), grey(175), grey(TIE), [236, 135, 135]]), + (51, [grey(186), grey(181), grey(TIE), [237, 138, 138]]), + (101, [grey(189), grey(186), grey(122), [237, 140, 140]]), + ]; + let mut s = test_document(); + for (size, want) in measured { + let got = [ + read(&mut s, 351, 150, size, Some(1.0)), + read(&mut s, 352, 150, size, Some(1.0)), + read(&mut s, 139, 400, size, Some(1.0)), + read(&mut s, 100, 150, size, Some(1.0)), + ]; + assert_eq!(got, want, "{size} by {size} at 100 %"); + } +} + +#[test] +fn without_a_zoom_the_box_stays_the_centred_square() { + // Today's values from the issue: 3 by 3 at stripes x 351 reads 85, red edge 232,105,105. + let mut s = test_document(); + assert_eq!(read(&mut s, 351, 150, 3, None), grey(85)); + assert_eq!(read(&mut s, 352, 150, 3, None), grey(170)); + assert_eq!(read(&mut s, 100, 150, 3, None), [232, 105, 105]); + assert_eq!(read(&mut s, 351, 150, 11, None), grey(162)); +} + +#[test] +fn the_probe_at_100_percent_reads_16_for_3_by_3_and_7_for_5_by_5() { + let mut s = probe(); + // 3 by 3 is 4 × 4 from x−1 to x+2: clicks at 198–201 (both axes) catch the white pixel. + for x in 197..=202 { + let want = if (198..=201).contains(&x) { 16 } else { 0 }; + assert_eq!(read(&mut s, x, 200, 3, Some(1.0)), grey(want), "3 by 3, x {x}"); + assert_eq!(read(&mut s, 200, x, 3, Some(1.0)), grey(want), "3 by 3, y {x}"); + } + // 5 by 5 is 6 × 6 from x−2 to x+3. + for x in 196..=203 { + let want = if (197..=202).contains(&x) { 7 } else { 0 }; + assert_eq!(read(&mut s, x, 200, 5, Some(1.0)), grey(want), "5 by 5, x {x}"); + } +} + +#[test] +fn at_50_percent_3_by_3_covers_8_by_8_document_pixels() { + let mut s = probe(); + assert_eq!(read(&mut s, 200, 200, 3, Some(0.5)), grey(4), "255 / 64"); +} + +#[test] +fn above_100_percent_it_is_the_centred_square() { + let mut s = probe(); + for zoom in [2.0, 3.125, 128.0] { + for x in 198..=202 { + let want = if (199..=201).contains(&x) { 28 } else { 0 }; + assert_eq!(read(&mut s, x, 200, 3, Some(zoom)), grey(want), "{zoom}: x {x}"); + } + } +} + +#[test] +fn point_sample_is_one_pixel_at_every_zoom() { + let mut s = probe(); + for zoom in [None, Some(0.05), Some(0.5), Some(1.0), Some(4.0)] { + assert_eq!(read(&mut s, 200, 200, 1, zoom), grey(255), "{zoom:?}"); + assert_eq!(read(&mut s, 201, 200, 1, zoom), grey(0), "{zoom:?}"); + } +} + +#[test] +fn a_far_zoomed_out_box_is_capped_and_clipped_not_a_panic() { + let mut s = probe(); + // At 1 % a 101 by 101 box would be 10 200 px wide: capped, and clipped to the canvas. + let v = read(&mut s, 0, 0, 101, Some(0.01)); + assert!(v.iter().all(|c| (0..=1).contains(c)), "one white pixel in a canvas-wide average: {v:?}"); + let rect = super::sample_cmds::sample_rect_at(200.5, 200.5, 101, Some(0.01), photocraft_geom::Rect::new(0, 0, 100_000, 100_000)).unwrap(); + assert!(rect.width() <= super::sample_cmds::MAX_ZOOM_BOX && rect.height() <= super::sample_cmds::MAX_ZOOM_BOX, "{rect:?}"); +} + +#[test] +fn a_bad_zoom_is_an_error_not_a_panic() { + let mut s = probe(); + for bad in [json!(0), json!(-1.0), json!("fast"), json!([1]), json!(-1e300)] { + let r = s.execute("document.sampleColor", json!({"x": 10, "y": 10, "size": 3, "zoom": bad})); + assert!(r.is_err(), "zoom {bad}: {r:?}"); + } + // A huge zoom is above 100 %: the centred square. + let v: Value = s.execute("document.sampleColor", json!({"x": 200.5, "y": 200.5, "size": 3, "zoom": 1e300})).unwrap(); + assert!((v[0].as_f64().unwrap() * 255.0 - 28.3).abs() < 1.0, "{v}"); +} diff --git a/crates/ui-egui/src/canvas/cursors.rs b/crates/ui-egui/src/canvas/cursors.rs index e692c4fe070..c3996024446 100644 --- a/crates/ui-egui/src/canvas/cursors.rs +++ b/crates/ui-egui/src/canvas/cursors.rs @@ -258,7 +258,9 @@ fn sample_color(app: &mut PhotocraftApp, x: f64, y: f64, sample_layer: &str) -> return None; } let size = app.ui.tool_options.eyedropper_size; - let v = app.run("document.sampleColor", json!({"x": x, "y": y, "size": size, "sampleLayer": sample_layer})).ok()?; + // The box depends on the view zoom at 100 % and below, as in Photoshop (#11751). + let zoom = f64::from(app.current_zoom()); + let v = app.run("document.sampleColor", json!({"x": x, "y": y, "size": size, "sampleLayer": sample_layer, "zoom": zoom})).ok()?; match serde_json::from_value::>(v).ok()?[..] { [r, g, b, a] if a > 0.0 => Some([r, g, b]), _ => None, diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index f19ec41da94..885a436d2ef 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -339,8 +339,8 @@ use widgets::tab_strip; pub use widgets::text_field_menu; pub use widgets::tone; -/// The Info panel's cached sample: pixel x, y, document revision and Eyedropper Sample Size. -type InfoSampleKey = (i32, i32, u64, u32); +/// The Info panel's cached sample: pixel x, y, document revision, Eyedropper Sample Size and the view zoom's bits. +type InfoSampleKey = (i32, i32, u64, u32, u32); pub struct PhotocraftApp { pub session: Session, diff --git a/crates/ui-egui/src/panels/info.rs b/crates/ui-egui/src/panels/info.rs index eeca9db7e39..daf68c2a941 100644 --- a/crates/ui-egui/src/panels/info.rs +++ b/crates/ui-egui/src/panels/info.rs @@ -7,19 +7,22 @@ pub(crate) fn hover_pixel(app: &PhotocraftApp) -> Option<(i32, i32)> { } /// The colour the Info panel reads at document pixel `(x, y)`, straight RGBA 0..1: averaged over -/// the Eyedropper's Sample Size, as in Photoshop (#1649), and cached per pixel and revision. +/// the Eyedropper's Sample Size over the box it reads at the view zoom, as in Photoshop (#1649, +/// #11751), and cached per pixel, revision, size and zoom. pub(crate) fn pointer_sample(app: &mut PhotocraftApp, (x, y): (i32, i32)) -> Option<[f32; 4]> { let rev = app.session.active()?.revision; let sample_size = app.ui.tool_options.eyedropper_size; - if let Some(((cx, cy, cr, cs), v)) = app.info_sample - && (cx, cy, cr, cs) == (x, y, rev, sample_size) + let zoom = app.current_zoom(); + let key = (x, y, rev, sample_size, zoom.to_bits()); + if let Some((k, v)) = app.info_sample + && k == key { return Some(v); } - let params = json!({"x": f64::from(x) + 0.5, "y": f64::from(y) + 0.5, "size": sample_size}); + let params = json!({"x": f64::from(x) + 0.5, "y": f64::from(y) + 0.5, "size": sample_size, "zoom": f64::from(zoom)}); let v: Vec = serde_json::from_value(app.session.execute("document.sampleColor", params).ok()?).ok()?; let v = [*v.first()?, *v.get(1)?, *v.get(2)?, *v.get(3)?]; - app.info_sample = Some(((x, y, rev, sample_size), v)); + app.info_sample = Some((key, v)); Some(v) } diff --git a/crates/ui-egui/src/tools/eyedropper_ui.rs b/crates/ui-egui/src/tools/eyedropper_ui.rs index 4e4c3d71c45..1c70f0d789c 100644 --- a/crates/ui-egui/src/tools/eyedropper_ui.rs +++ b/crates/ui-egui/src/tools/eyedropper_ui.rs @@ -120,9 +120,26 @@ mod tests { } } + /// View the document at 200 %, where an N by N Average is the centred N × N square (#11751: + /// at 100 % and below it covers (N+1) × (N+1) screen pixels). + fn zoomed_in(app: &mut PhotocraftApp) { + app.sync_views(); + for v in &mut app.ui.views { + v.zoom = 2.0; + } + } + #[test] fn a_click_samples_the_average_of_the_sample_size() { let mut app = app(); + // At 100 % a 3 by 3 Average is the 4 × 4 box from (2, 2): one black pixel of sixteen (#11751). + app.sync_views(); + app.ui.tool_options.eyedropper_size = 3; + click(&mut app, 3.5, 3.5, egui::Modifiers::NONE); + let want = (255.0f32 * 15.0 / 16.0).round() / 255.0; + assert_eq!(fg(&app), [want, want, want, 1.0], "3 by 3 at 100 %"); + app.ui.tool_options.eyedropper_size = 1; + zoomed_in(&mut app); // Point Sample at (3, 3): white. click(&mut app, 3.5, 3.5, egui::Modifiers::NONE); assert_eq!(fg(&app), [1.0; 4]); @@ -200,7 +217,11 @@ mod tests { } crate::panels::options_bar(app, ui); }, - app(), + { + let mut a = app(); + zoomed_in(&mut a); + a + }, ); PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio); h.run_steps(4); From 526d0cd494d7a5b71c9031aea9f1a92a3dd0ed72 Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sat, 7 Nov 2026 15:32:35 -0600 Subject: [PATCH 04/42] Count tool: arrow cursors with 1+, 1 over a marker and 1- with Alt (#11773) --- crates/ui-egui/src/canvas.rs | 7 ++ crates/ui-egui/src/canvas/tool_cursor.rs | 48 +++++++++++ .../src/canvas/tool_cursor/count_tests.rs | 84 +++++++++++++++++++ crates/ui-egui/src/tools/analysis_ui.rs | 8 ++ 4 files changed, 147 insertions(+) create mode 100644 crates/ui-egui/src/canvas/tool_cursor/count_tests.rs diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index ac471a9269d..e4f4a80e7fa 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1654,6 +1654,13 @@ fn draw_default_tool_cursor(app: &mut PhotocraftApp, ui: &mut egui::Ui, input: & pipette_cursor(ui.ctx(), p) } } + // The Count tool (#11773): an arrow with "1+", "1" over a marker (the click's own hit + // test) or "1−" with ⌥ there. Precise Other Cursors keeps today's crosshair. + Tool::Count if !precise_other_cursor(app) => { + let alt = crate::workspace_ui::sticky_mods(app, ui.input(|i| i.modifiers)).alt; + let over = crate::analysis_ui::count_marker_at(app, xf.to_doc(p)).is_some(); + crate::tool_cursor::count(ui.ctx(), p, crate::tool_cursor::CountCursor::pick(over, alt)) + } // The Color Sampler: a pipette, or the crosshair for precise Other Cursors. Tool::ColorSampler => { if precise_other_cursor(app) { diff --git a/crates/ui-egui/src/canvas/tool_cursor.rs b/crates/ui-egui/src/canvas/tool_cursor.rs index 84b69b26cf8..41b26afa134 100644 --- a/crates/ui-egui/src/canvas/tool_cursor.rs +++ b/crates/ui-egui/src/canvas/tool_cursor.rs @@ -85,6 +85,51 @@ impl egui::plugin::Plugin for CursorLifecycle { } /// The bucket artwork and its exact fill crosshair move as one native cursor or painted image. +/// The Count tool's cursor (#11773): an arrow with "1+" (a click adds a marker), "1" (over a +/// marker: a click or drag moves it) or "1−" (⌥ over a marker: a click deletes it). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum CountCursor { + Add, + Move, + Delete, +} + +impl CountCursor { + /// The cursor for a pointer `over` a marker or not, with ⌥ held or not. Shift changes nothing, + /// and ⌥ off a marker is still "1+" (an ⌥-click there does nothing). + pub(crate) fn pick(over: bool, alt: bool) -> Self { + match (over, alt) { + (false, _) => Self::Add, + (true, false) => Self::Move, + (true, true) => Self::Delete, + } + } + + /// The badge drawn below right of the arrow. + pub(crate) fn label(self) -> &'static str { + match self { + Self::Add => "1+", + Self::Move => "1", + Self::Delete => "1\u{2212}", + } + } +} + +/// Draw the Count cursor `kind` at `at`: the OS arrow (hotspot at its tip) with its badge below right +/// of it, dark digits on a light halo so they read on any pixel. PhotoCraft's own artwork. +pub(crate) fn count(ctx: &egui::Context, at: Pos2, kind: CountCursor) -> CursorIcon { + let pos = at + vec2(12.0, 16.0); + // Painted straight onto a tooltip-order layer, above the canvas and its overlays: an Area + // would be invisible on the frame it first appears. + let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::unique("pc-count-cursor"))); + let font = egui::FontId::proportional(11.0); + for (dx, dy) in [(-1.0, 0.0), (1.0, 0.0), (0.0, -1.0), (0.0, 1.0)] { + painter.text(pos + vec2(dx, dy), egui::Align2::LEFT_TOP, kind.label(), font.clone(), egui::Color32::WHITE); + } + painter.text(pos, egui::Align2::LEFT_TOP, kind.label(), font, egui::Color32::BLACK); + CursorIcon::Default +} + pub(crate) fn bucket(painter: &Painter, at: Pos2) -> Result { bucket::show(painter, at) } @@ -666,3 +711,6 @@ fn rasterize(shape: &Shape, scale: f32) -> Option { #[cfg(test)] mod tests; + +#[cfg(test)] +mod count_tests; diff --git a/crates/ui-egui/src/canvas/tool_cursor/count_tests.rs b/crates/ui-egui/src/canvas/tool_cursor/count_tests.rs new file mode 100644 index 00000000000..aaf49baea7b --- /dev/null +++ b/crates/ui-egui/src/canvas/tool_cursor/count_tests.rs @@ -0,0 +1,84 @@ +//! #11773: the Count tool's cursors. An arrow with "1+" off a marker, "1" on one and "1−" with ⌥ +//! on one; Shift changes nothing, Ctrl is the Move tool's cursor. "On a marker" is the click's own +//! hit test, so the cursor never promises what the click won't do. + +use serde_json::json; + +use super::{CountCursor, count}; +use crate::PhotocraftApp; +use crate::canvas::ToolEvent; +use crate::state::Tool; + +/// A 200 × 100 document with the Count tool and one marker at 50,40. +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run("count.add", json!({"x": 50, "y": 40})).unwrap(); + app.ui.tool = Tool::Count; + app +} + +fn markers(app: &PhotocraftApp) -> Vec<[f64; 2]> { + app.session.active().unwrap().doc.measurement.count_groups.iter().flat_map(|g| g.points.clone()).collect() +} + +#[test] +fn the_cursor_kind_follows_the_marker_and_alt() { + assert_eq!(CountCursor::pick(false, false), CountCursor::Add, "empty canvas or pasteboard"); + assert_eq!(CountCursor::pick(true, false), CountCursor::Move, "over a marker"); + assert_eq!(CountCursor::pick(true, true), CountCursor::Delete, "⌥ over a marker"); + assert_eq!(CountCursor::pick(false, true), CountCursor::Add, "⌥ off a marker: still 1+"); + assert_eq!([CountCursor::Add, CountCursor::Move, CountCursor::Delete].map(CountCursor::label), ["1+", "1", "1\u{2212}"], "the badges (a real minus sign)"); +} + +#[test] +fn over_a_marker_is_the_clicks_own_hit_test() { + // Walk a click away from the marker: wherever the cursor says "1" the click grabs and moves the + // marker, and wherever it says "1+" the click adds a new one. + for dx in [0.0, 2.0, 4.0, 6.0, 6.9, 7.1, 8.0, 15.0] { + let mut app = app(); + let at = [50.0 + dx, 40.0]; + let kind = CountCursor::pick(crate::analysis_ui::count_marker_at(&app, at).is_some(), false); + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: at[0], y: at[1], pressure: 1.0 }, egui::Modifiers::NONE); + crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 150.0, y: 80.0, pressure: 1.0 }, egui::Modifiers::NONE); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 150.0, y: 80.0 }, egui::Modifiers::NONE); + let m = markers(&app); + match kind { + CountCursor::Move => assert_eq!(m, vec![[150.0, 80.0]], "{dx} px off: \"1\" and the press moved the marker"), + CountCursor::Add => assert_eq!(m.len(), 2, "{dx} px off: \"1+\" and the click added a marker: {m:?}"), + CountCursor::Delete => assert_ne!(kind, CountCursor::Delete, "{dx} px off: no ⌥ is held"), + } + } +} + +#[test] +fn ctrl_makes_the_count_tool_the_move_tool() { + // Holding Ctrl turns the Count tool into the temporary Move tool, so the canvas shows the Move + // tool's cursor instead of these. + assert!(crate::hold_keys::cmd_moves(Tool::Count)); +} + +#[test] +fn the_cursor_is_the_os_arrow_with_its_badge() { + // The OS arrow keeps its hotspot at the tip; the badge is drawn beside it. + let ctx = egui::Context::default(); + let mut got = Vec::new(); + let mut o = ctx.run_ui(egui::RawInput::default(), |ui| { + for kind in [CountCursor::Add, CountCursor::Move, CountCursor::Delete] { + got.push(count(ui.ctx(), egui::pos2(100.0, 60.0), kind)); + } + }); + o.textures_delta.clear(); + assert_eq!(got, [egui::CursorIcon::Default; 3]); + let texts: Vec = o + .shapes + .into_iter() + .filter_map(|c| match c.shape { + egui::Shape::Text(t) => Some(t.galley.text().to_owned()), + _ => None, + }) + .collect(); + for label in ["1+", "1", "1\u{2212}"] { + assert!(texts.iter().any(|t| t == label), "badge {label} drawn: {texts:?}"); + } +} diff --git a/crates/ui-egui/src/tools/analysis_ui.rs b/crates/ui-egui/src/tools/analysis_ui.rs index ed113909a6b..de023485625 100644 --- a/crates/ui-egui/src/tools/analysis_ui.rs +++ b/crates/ui-egui/src/tools/analysis_ui.rs @@ -400,6 +400,14 @@ fn status_on_err(app: &mut PhotocraftApp, r: Result) { } } +/// The count marker a Count tool click at document point `at` would grab (the click's own hit +/// test, with its tolerance), or `None`. The cursor uses it too, so it never says "1" where a click +/// adds a marker (#11773). +pub(crate) fn count_marker_at(app: &PhotocraftApp, at: [f64; 2]) -> Option<(usize, usize)> { + let doc = app.session.active().map(|d| d.doc.clone())?; + nearest_marker(&doc, at, tolerance(app)) +} + fn nearest_marker(d: &Document, at: [f64; 2], tol: f64) -> Option<(usize, usize)> { let mut best: Option<(f64, usize, usize)> = None; for (gi, g) in d.measurement.count_groups.iter().enumerate().filter(|(_, g)| g.visible) { From 5f44e7c2b4b32a9264dd97984f251a2655123f7e Mon Sep 17 00:00:00 2001 From: DuBearte <130190089+DuBearte@users.noreply.github.com> Date: Sat, 7 Nov 2026 16:40:54 -0500 Subject: [PATCH 05/42] Pencil Auto Erase: the start pixel must be exactly the foreground colour Fixes #11966. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/brush_cmds.rs | 10 ++- crates/engine/src/lib.rs | 2 + .../src/pencil_auto_erase_exact_tests.rs | 80 +++++++++++++++++++ 3 files changed, 90 insertions(+), 2 deletions(-) create mode 100644 crates/engine/src/pencil_auto_erase_exact_tests.rs diff --git a/crates/engine/src/cmd/brush_cmds.rs b/crates/engine/src/cmd/brush_cmds.rs index e09ff2098ca..f590ce04177 100644 --- a/crates/engine/src/cmd/brush_cmds.rs +++ b/crates/engine/src/cmd/brush_cmds.rs @@ -336,11 +336,17 @@ fn stroke_with(s: &mut Session, cmd: &str, p: &Value, label: &str, brush: BrushS } /// Pencil Auto Erase: a stroke that starts on a pixel of the foreground colour paints the -/// background colour instead (Photoshop). +/// background colour instead (Photoshop). The match is exact (#11966): the foreground as the +/// layer would store it (its mode and depth) against the pixel, its alpha aside, so one level +/// off paints the foreground. fn apply_auto_erase(brush: &mut BrushSettings, surf: &Surface, start: Option<&StrokePoint>, fg: [f32; 4], bg: [f32; 4]) { let Some(p0) = start else { return }; let c = surf.rgba(p0.x.floor() as i32, p0.y.floor() as i32); - if c[3] > 0.0 && (0..3).all(|i| (c[i] - fg[i]).abs() < 1.5 / 255.0) { + let mut probe = Surface::new(surf.format()); + probe.write_pixel(0, 0, &photocraft_raster::from_rgba(&surf.format(), [fg[0], fg[1], fg[2], 1.0])); + let stored = probe.rgba(0, 0); + // Far below one 8-bit level: only the float noise of the conversion. + if c[3] > 0.0 && (0..3).all(|i| (c[i] - stored[i]).abs() < 1e-5) { brush.color = bg; } } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 8f281472172..32cfb2e4e6d 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -356,3 +356,5 @@ mod tests; mod fx_mode_tests; pub mod command_hints; +#[cfg(test)] +mod pencil_auto_erase_exact_tests; diff --git a/crates/engine/src/pencil_auto_erase_exact_tests.rs b/crates/engine/src/pencil_auto_erase_exact_tests.rs new file mode 100644 index 00000000000..7588c0c38ad --- /dev/null +++ b/crates/engine/src/pencil_auto_erase_exact_tests.rs @@ -0,0 +1,80 @@ +//! #11966: Pencil Auto Erase paints the background colour only when the start pixel is exactly +//! the foreground colour (its alpha aside); one level off paints the foreground. The live preview +//! agrees, and at 16 and 32 bits a foreground equal to the pixel still counts. + +use serde_json::{Value, json}; + +use crate::Session; +use crate::brush_cmds::LiveStroke; + +const WHITE: [f32; 4] = [1.0, 1.0, 1.0, 1.0]; + +/// A document of `depth` bits with a pixel layer filled with `fill`, the background colour white. +fn session(depth: u32, fill: [f32; 4]) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 24, "height": 24, "depth": depth, "background": "white"})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": fill})).unwrap(); + s.tools.background = WHITE; + s +} + +fn pencil(fg: &str) -> Value { + json!({"points": [[12, 12]], "size": 3, "color": fg, "autoErase": true}) +} + +fn active_pixel(s: &Session) -> [f32; 4] { + let st = s.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().rgba(12, 12) +} + +fn preview_pixel(s: &Session, p: &Value) -> [f32; 4] { + let preview = LiveStroke::begin_with(s, "paint.pencil", p).unwrap(); + let id = s.active().unwrap().active_layer.unwrap(); + preview.doc.layer(id).unwrap().surface().unwrap().rgba(12, 12) +} + +fn level(v: f32) -> u8 { + (v * 255.0).round() as u8 +} + +const RED: [f32; 4] = [220.0 / 255.0, 30.0 / 255.0, 30.0 / 255.0, 1.0]; + +#[test] +fn one_level_off_paints_the_foreground() { + let mut s = session(8, RED); + let p = pencil("#dd1e1e"); // 221, 30, 30 + let preview = preview_pixel(&s, &p); + s.execute("paint.pencil", p).unwrap(); + let px = active_pixel(&s); + assert_eq!([level(px[0]), level(px[1]), level(px[2]), level(px[3])], [221, 30, 30, 255]); + assert_eq!(preview, px, "the live preview agrees"); +} + +#[test] +fn the_exact_foreground_paints_the_background_colour() { + let mut s = session(8, RED); + let p = pencil("#dc1e1e"); // 220, 30, 30 + assert_eq!(preview_pixel(&s, &p), WHITE); + s.execute("paint.pencil", p).unwrap(); + assert_eq!(active_pixel(&s), WHITE); +} + +#[test] +fn alpha_is_ignored_for_the_match() { + let mut s = session(8, [RED[0], RED[1], RED[2], 0.5]); + s.execute("paint.pencil", pencil("#dc1e1e")).unwrap(); + assert_eq!(active_pixel(&s), WHITE, "opaque background colour"); +} + +#[test] +fn deeper_documents_still_match_an_equal_foreground() { + for depth in [16, 32] { + let mut s = session(depth, RED); + s.execute("paint.pencil", pencil("#dc1e1e")).unwrap(); + assert_eq!(active_pixel(&s), WHITE, "{depth} bits"); + let mut s = session(depth, RED); + s.execute("paint.pencil", pencil("#dd1e1e")).unwrap(); + assert_ne!(active_pixel(&s), WHITE, "{depth} bits: one level off paints the foreground"); + } +} From a362c98abcb4a0cb5793d0502c392c3f297337e1 Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sat, 7 Nov 2026 15:41:31 -0600 Subject: [PATCH 06/42] Eyedropper: the document.sampleColor params say the centred square applies without zoom (CodeRabbit review on sample_cmds.rs:274) Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/sample_cmds.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/sample_cmds.rs b/crates/engine/src/cmd/sample_cmds.rs index 13ebc7cc0bc..5baa7f14f2b 100644 --- a/crates/engine/src/cmd/sample_cmds.rs +++ b/crates/engine/src/cmd/sample_cmds.rs @@ -271,7 +271,7 @@ pub fn specs() -> Vec { label: "Sample Color", menu: &[], shortcut: None, - params: r##"{"x":f64,"y":f64,"size":"point"|1|3|5|11|31|51|101=1,"sampleLayer":"current"|"currentAndBelow"|"all"|"allNoAdjustments"|"currentAndBelowNoAdjustments"="all","zoom":f64? (the view zoom, 1 = 100 %: at 100 % and below an N by N Average covers (N+1)×(N+1) screen pixels, as in Photoshop; missing: the centred square)} → [r,g,b,a] (the Eyedropper's Sample Size and Sample: the composite pixel, or the average of the size×size square centred on it, clipped to the canvas; transparent off the canvas)"##, + params: r##"{"x":f64,"y":f64,"size":"point"|1|3|5|11|31|51|101=1,"sampleLayer":"current"|"currentAndBelow"|"all"|"allNoAdjustments"|"currentAndBelowNoAdjustments"="all","zoom":f64? (the view zoom, 1 = 100 %: at 100 % and below an N by N Average covers (N+1)×(N+1) screen pixels, as in Photoshop; missing: the centred square)} → [r,g,b,a] (the Eyedropper's Sample Size and Sample: the composite pixel, or the average of the size×size square centred on it (without `zoom`; with it, the zoom-dependent box above), clipped to the canvas; transparent off the canvas)"##, enabled: |s| s.active().map(|_| ()).ok_or_else(|| "no document open".into()), run: |s: &mut Session, p: &Value| { const CMD: &str = "document.sampleColor"; From fe6399312f0d96525e603c16d1616f250f028aba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hartmut=20N=C3=B6renberg?= Date: Sun, 8 Nov 2026 00:46:26 +0100 Subject: [PATCH 07/42] fix(ui): round the ruler angle before the field narrows to f32 (#12035) A 43x27 ruler line is 32.1249984 degrees. straighten_defaults hands that full-precision value to the dialog, the Angle field reads it into an f32 that lands exactly on 32.125, and the f32 write-back round (half away from zero) turned it into 32.13: the dialog showed, and OK ran, an angle the ruler never was. The hundredths are a f64 question, so a field that shows two decimals now rounds the f64 value the field holds and only then narrows to f32; a value the user typed or dragged is f32 already and keeps today's arithmetic, so every other field is untouched. The review's 43x27 case is pinned in the test file: red shows the dialog opening at 32.130001, green at 32.12 (Counter clockwise), with the shown string asserted as "32.12". --- .../dialogs/arbitrary_ruler_prefill_tests.rs | 14 ++++++++++++++ crates/ui-egui/src/dialogs/filter_dialog.rs | 19 ++++++++++++++++--- 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/dialogs/arbitrary_ruler_prefill_tests.rs b/crates/ui-egui/src/dialogs/arbitrary_ruler_prefill_tests.rs index cb947d0b0b3..c139a4e1e52 100644 --- a/crates/ui-egui/src/dialogs/arbitrary_ruler_prefill_tests.rs +++ b/crates/ui-egui/src/dialogs/arbitrary_ruler_prefill_tests.rs @@ -69,6 +69,20 @@ fn ok_runs_the_two_decimal_angle() { assert_eq!((r["width"].as_u64(), r["height"].as_u64()), (Some(441), Some(441)), "442 would mean the 33.7 round ran"); } +/// The f32 double-rounding the review caught: a 43x27 ruler line (here 100,100 to 143,127) +/// is 32.1249984 degrees, and the f32 cast of that full-precision pre-fill lands exactly on +/// 32.125 - rounding the widened value half away from zero opened the dialog at 32.13. The +/// hundredths round in f64 before the field narrows, so it opens at 32.12, Counter clockwise. +#[test] +fn the_ruler_angle_rounds_at_full_precision_before_the_field_narrows() { + let (_app, _id, f) = ruler_dialog([143, 127]); + let a = f["angle"].as_f64().unwrap(); + assert!((a - 32.12).abs() < 1e-3, "the 43x27 ruler opens at {a}, want 32.12"); + assert_eq!(crate::widgets::fmt_num2(a), "32.12", "the Angle field shows 32.12, not the 32.13 the f32 round gives"); + assert!((a - 32.13).abs() > 1e-3, "the f32 double-round must not reach the dialog: {a}"); + assert_eq!(f["direction"], json!("ccw")); +} + /// The fix is per-field: unrelated number fields keep the precision they have today — /// wide ranges round to one decimal (in another dialog, and under the same key name), /// small ranges keep their two. diff --git a/crates/ui-egui/src/dialogs/filter_dialog.rs b/crates/ui-egui/src/dialogs/filter_dialog.rs index 1aa350d53ba..ce2198d22c1 100644 --- a/crates/ui-egui/src/dialogs/filter_dialog.rs +++ b/crates/ui-egui/src/dialogs/filter_dialog.rs @@ -901,7 +901,10 @@ pub fn body(ui: &mut egui::Ui, f: &mut Map) { } match p.kind { Kind::Range { min, max, default } => { - let mut v = f.get(&p.key).and_then(Value::as_f64).unwrap_or(default as f64) as f32; + let src = f.get(&p.key).and_then(Value::as_f64); + let mut v = src.unwrap_or(default as f64) as f32; + // A widget edit this frame makes the field's f32 value authoritative (#12035). + let mut edited = false; if cmd == "image.mode.indexedColor" && p.key == "colors" { let mut count = v.round().clamp(2.0, 256.0) as u32; crate::widgets::color_count_row(ui, &label(&p.key), &mut count); @@ -944,13 +947,23 @@ pub fn body(ui: &mut egui::Ui, f: &mut Map) { } else { // A double-click on the slider puts it back to the filter's default. let gestures = crate::widgets::RowGestures { reset: Some(default), wheel_step: None, ..Default::default() }; - crate::widgets::slider_row_prec(ui, &label(&p.key), &mut v, min..=max, unit, None, gestures, wide_field_decimals(&cmd, &p.key)); + edited = + crate::widgets::slider_row_prec(ui, &label(&p.key), &mut v, min..=max, unit, None, gestures, wide_field_decimals(&cmd, &p.key)) + .changed(); } }); // The field's shown precision: small ranges keep their two decimals, and so // does the Arbitrary angle; the other wide fields round to one (#12035). let scale = field_scale(&cmd, &p.key, min, max); - f.insert(p.key, json!((v * scale).round() / scale)); + // A field showing two decimals rounds while the value is still f64: a 43x27 + // ruler is 32.1249984°, whose f32 cast lands exactly on 32.125, and rounding + // that widened value half-away shows 32.13 where the pre-fill says 32.12. + // Values the user typed or dragged are f32 already, so they round as before. + let w = match (wide_field_decimals(&cmd, &p.key), src) { + (Some(_), Some(raw)) if !edited => ((raw * f64::from(scale)).round() / f64::from(scale)) as f32, + _ => (v * scale).round() / scale, + }; + f.insert(p.key, json!(w)); } Kind::Choice { options, default } => { ui.horizontal(|ui| { From 0f8481e6fbcd414cc51ab0a38a28b8fcf421662d Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sat, 7 Nov 2026 12:38:40 -0600 Subject: [PATCH 08/42] Magic Wand: a New-mode click inside the selection deselects, a drag moves the outline (#11782) --- crates/ui-egui/src/canvas/tool_input.rs | 21 +++- crates/ui-egui/src/lib.rs | 3 + .../src/wand_press_inside_selection_tests.rs | 113 ++++++++++++++++++ 3 files changed, 136 insertions(+), 1 deletion(-) create mode 100644 crates/ui-egui/src/wand_press_inside_selection_tests.rs diff --git a/crates/ui-egui/src/canvas/tool_input.rs b/crates/ui-egui/src/canvas/tool_input.rs index f148b8dfa5c..b5b7e4ae35b 100644 --- a/crates/ui-egui/src/canvas/tool_input.rs +++ b/crates/ui-egui/src/canvas/tool_input.rs @@ -479,6 +479,9 @@ pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) Tool::MagicWand => { let o = app.ui.tool_options.clone(); let mode = selection_mode(app, mods); + if wand_pasteboard_click(app, x, y, mode) { + return; + } let _ = app.run("select.magicWand", json!({"x": x.floor(), "y": y.floor(), "tolerance": o.tolerance, "contiguous": o.contiguous, "antiAlias": o.anti_alias, "sampleAllLayers": o.sample_all.magic_wand, "mode": mode})); return; } @@ -692,6 +695,19 @@ fn covers(sel: &photocraft_raster::Surface, p: [f64; 2]) -> bool { v[0] > 0.0 } +/// A New-mode Magic Wand click on the pasteboard deselects, as Photoshop's step "Deselect" +/// (#11782), instead of a "Magic Wand" step that selects nothing. True when it handled the click. +fn wand_pasteboard_click(app: &mut PhotocraftApp, x: f64, y: f64, mode: &str) -> bool { + let on_canvas = app.session.active().is_some_and(|st| st.doc.bounds().contains(x.floor() as i32, y.floor() as i32)); + if mode != "replace" || on_canvas { + return false; + } + if app.session.is_enabled("select.deselect") { + let _ = app.run("select.deselect", json!({})); + } + true +} + /// Does a press with `tool` at `p` drag the selection rather than draw a new one? `Some(true)` /// moves the floating piece (⌘ cuts one first, ⌘⌥ copies; the Polygonal Lasso and Magic Wand need /// ⌘, as a plain press there places or samples), `Some(false)` just the outline (no ⇧ / ⌥ and the @@ -730,7 +746,10 @@ pub fn selection_drag_kind(app: &PhotocraftApp, tool: Tool, p: [f64; 2], mods: e if cut { return Some(true); } - (!clicky && !mods.command && selection_mode(app, mods) == "replace").then_some(false) + // The Magic Wand in New mode drags the outline like a marquee: a click deselects, a drag + // moves the outline (#11782). + let outline = !clicky || tool == Tool::MagicWand; + (outline && !mods.command && selection_mode(app, mods) == "replace").then_some(false) } /// The tool a pointer event with `mods` goes to: ⌘ held is the Move tool (`hold_keys::cmd_moves`). diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 7d5d2a90e86..1567fe44369 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -882,6 +882,9 @@ mod move_auto_select_tests; #[cfg(test)] mod move_target_default_tests; +#[cfg(test)] +mod wand_press_inside_selection_tests; + #[cfg(test)] mod move_history_names_tests; #[cfg(test)] diff --git a/crates/ui-egui/src/wand_press_inside_selection_tests.rs b/crates/ui-egui/src/wand_press_inside_selection_tests.rs new file mode 100644 index 00000000000..964f9a6240c --- /dev/null +++ b/crates/ui-egui/src/wand_press_inside_selection_tests.rs @@ -0,0 +1,113 @@ +//! The Magic Wand pressed inside its selection (#11782), as measured in the reference +//! application: in New mode a click deselects and a drag moves the outline (the pixels stay), +//! the pointer shows the move-selection cursor, and a click on the pasteboard deselects. Add mode +//! and ⌘ drags keep today's behaviour. + +use egui::Modifiers; +use photocraft_geom::Rect; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::canvas::{SelCursor, ToolEvent, selection_cursor, tool_event}; +use crate::state::Tool; + +/// A 500 x 400 document with an opaque red block at 100,100–300,250 on its own layer, selected +/// with the wand. +fn selected() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 500, "height": 400})).unwrap(); + app.sync_views(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("select.rect", json!({"x": 100, "y": 100, "width": 200, "height": 150})).unwrap(); + app.run("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + app.ui.tool = Tool::MagicWand; + app.ui.tool_options.anti_alias = false; + click(&mut app, [150.0, 150.0], Modifiers::NONE); + assert_eq!(selection(&app), Some(Rect::new(100, 100, 300, 250)), "the wand selected the block"); + app +} + +fn click(app: &mut PhotocraftApp, p: [f64; 2], mods: Modifiers) { + tool_event(app, ToolEvent::Down { x: p[0], y: p[1], pressure: 1.0 }, mods); + tool_event(app, ToolEvent::Up { x: p[0], y: p[1] }, mods); +} + +fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2], mods: Modifiers) { + tool_event(app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, mods); + tool_event(app, ToolEvent::Move { x: (from[0] + to[0]) / 2.0, y: (from[1] + to[1]) / 2.0, pressure: 1.0 }, mods); + tool_event(app, ToolEvent::Move { x: to[0], y: to[1], pressure: 1.0 }, mods); + tool_event(app, ToolEvent::Up { x: to[0], y: to[1] }, mods); +} + +fn selection(app: &PhotocraftApp) -> Option { + let st = app.session.active()?; + st.doc.selection.as_ref().map(|s| s.content_bounds()).filter(|b| !b.is_empty()) +} + +fn last_step(app: &PhotocraftApp) -> Option { + app.session.active()?.history.entries().last().map(ToString::to_string) +} + +fn alpha_at(app: &PhotocraftApp, x: i32, y: i32) -> f32 { + let st = app.session.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().pixel(x, y)[3] +} + +#[test] +fn a_new_mode_click_inside_the_selection_deselects() { + let mut app = selected(); + click(&mut app, [200.0, 200.0], Modifiers::NONE); + assert_eq!(selection(&app), None, "nothing is selected"); + assert_eq!(last_step(&app).as_deref(), Some("Deselect")); +} + +#[test] +fn a_new_mode_drag_inside_the_selection_moves_the_outline_not_the_pixels() { + let mut app = selected(); + drag(&mut app, [200.0, 200.0], [300.0, 250.0], Modifiers::NONE); + assert_eq!(selection(&app), Some(Rect::new(200, 150, 400, 300)), "the outline moved by +100,+50"); + assert_eq!(last_step(&app).as_deref(), Some("Move Selection")); + assert_eq!(alpha_at(&app, 150, 150), 1.0, "the pixels stay where they are"); + assert_eq!(alpha_at(&app, 350, 280), 0.0); +} + +#[test] +fn the_pointer_over_the_selection_shows_the_move_selection_cursor_in_new_mode_only() { + let mut app = selected(); + assert_eq!(selection_cursor(&app, Tool::MagicWand, [200.0, 200.0], Modifiers::NONE), Some(SelCursor::Outline)); + assert_eq!(selection_cursor(&app, Tool::MagicWand, [400.0, 350.0], Modifiers::NONE), None, "outside: the wand"); + assert_eq!(selection_cursor(&app, Tool::MagicWand, [200.0, 200.0], Modifiers::SHIFT), None, "Shift adds"); + app.ui.selection_mode = 1; + assert_eq!(selection_cursor(&app, Tool::MagicWand, [200.0, 200.0], Modifiers::NONE), None, "Add mode"); +} + +#[test] +fn a_click_on_the_pasteboard_deselects() { + let mut app = selected(); + click(&mut app, [-30.0, -30.0], Modifiers::NONE); + assert_eq!(selection(&app), None); + assert_eq!(last_step(&app).as_deref(), Some("Deselect")); +} + +#[test] +fn add_mode_and_shift_keep_the_selection_and_move_nothing() { + for (bar, mods) in [(1, Modifiers::NONE), (0, Modifiers::SHIFT)] { + let mut app = selected(); + app.ui.selection_mode = bar; + click(&mut app, [200.0, 200.0], mods); + assert_eq!(selection(&app), Some(Rect::new(100, 100, 300, 250)), "mode {bar}, {mods:?}: click"); + drag(&mut app, [200.0, 200.0], [300.0, 250.0], mods); + assert_eq!(selection(&app), Some(Rect::new(100, 100, 300, 250)), "mode {bar}, {mods:?}: drag"); + assert_eq!(alpha_at(&app, 150, 150), 1.0); + } +} + +#[test] +fn a_new_mode_click_outside_the_selection_selects_that_region() { + let mut app = selected(); + click(&mut app, [450.0, 350.0], Modifiers::NONE); + let b = selection(&app).expect("the transparent area is selected"); + assert!(!b.contains(150, 150) || b.width() == 500, "a new selection of the clicked region: {b:?}"); + assert_eq!(last_step(&app).as_deref(), Some("Magic Wand")); +} From afb7f3ef59ec2f8f60e185094a7496f65c9ca4fc Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sat, 7 Nov 2026 18:32:10 -0600 Subject: [PATCH 09/42] Count cursor badge: halo on all eight sides (eliets2 review on crates/ui-egui/src/canvas/tool_cursor.rs, count()) Only the four cardinal copies were drawn, leaving the digits' diagonal corners without the light halo on dark or busy pixels. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas/tool_cursor.rs | 3 +- .../src/canvas/tool_cursor/count_tests.rs | 29 +++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/canvas/tool_cursor.rs b/crates/ui-egui/src/canvas/tool_cursor.rs index 41b26afa134..4229b23e54e 100644 --- a/crates/ui-egui/src/canvas/tool_cursor.rs +++ b/crates/ui-egui/src/canvas/tool_cursor.rs @@ -123,7 +123,8 @@ pub(crate) fn count(ctx: &egui::Context, at: Pos2, kind: CountCursor) -> CursorI // would be invisible on the frame it first appears. let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::unique("pc-count-cursor"))); let font = egui::FontId::proportional(11.0); - for (dx, dy) in [(-1.0, 0.0), (1.0, 0.0), (0.0, -1.0), (0.0, 1.0)] { + // The halo: a white copy one point off on every side, diagonals too. + for (dx, dy) in [(-1.0, -1.0), (0.0, -1.0), (1.0, -1.0), (-1.0, 0.0), (1.0, 0.0), (-1.0, 1.0), (0.0, 1.0), (1.0, 1.0)] { painter.text(pos + vec2(dx, dy), egui::Align2::LEFT_TOP, kind.label(), font.clone(), egui::Color32::WHITE); } painter.text(pos, egui::Align2::LEFT_TOP, kind.label(), font, egui::Color32::BLACK); diff --git a/crates/ui-egui/src/canvas/tool_cursor/count_tests.rs b/crates/ui-egui/src/canvas/tool_cursor/count_tests.rs index aaf49baea7b..1b25791144b 100644 --- a/crates/ui-egui/src/canvas/tool_cursor/count_tests.rs +++ b/crates/ui-egui/src/canvas/tool_cursor/count_tests.rs @@ -82,3 +82,32 @@ fn the_cursor_is_the_os_arrow_with_its_badge() { assert!(texts.iter().any(|t| t == label), "badge {label} drawn: {texts:?}"); } } + +#[test] +fn the_badge_halo_surrounds_the_digits_on_all_eight_sides() { + // White copies one point off in every direction, diagonals too, so the dark digits read on + // dark and busy pixels. + let ctx = egui::Context::default(); + let mut o = ctx.run_ui(egui::RawInput::default(), |ui| { + count(ui.ctx(), egui::pos2(100.0, 60.0), CountCursor::Add); + }); + o.textures_delta.clear(); + let texts: Vec<(egui::Pos2, egui::Color32)> = o + .shapes + .into_iter() + .filter_map(|c| match c.shape { + egui::Shape::Text(t) => Some((t.pos, t.fallback_color)), + _ => None, + }) + .collect(); + let digits = texts.iter().find(|(_, c)| *c == egui::Color32::BLACK).expect("the dark digits").0; + for dx in [-1.0, 0.0, 1.0] { + for dy in [-1.0, 0.0, 1.0] { + if (dx, dy) == (0.0, 0.0) { + continue; + } + let want = digits + egui::vec2(dx, dy); + assert!(texts.iter().any(|&(p, c)| c == egui::Color32::WHITE && p == want), "a halo copy at {dx},{dy}: {texts:?}"); + } + } +} From 83049a019b02a5678a74ffbfd7af7a31bfad6d42 Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sat, 7 Nov 2026 18:32:16 -0600 Subject: [PATCH 10/42] Count cursor: borrow the document for the hit test, no clone per frame (eliets2 review on crates/ui-egui/src/tools/analysis_ui.rs, count_marker_at) Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/tools/analysis_ui.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/crates/ui-egui/src/tools/analysis_ui.rs b/crates/ui-egui/src/tools/analysis_ui.rs index de023485625..77dfca5aec8 100644 --- a/crates/ui-egui/src/tools/analysis_ui.rs +++ b/crates/ui-egui/src/tools/analysis_ui.rs @@ -404,8 +404,7 @@ fn status_on_err(app: &mut PhotocraftApp, r: Result) { /// test, with its tolerance), or `None`. The cursor uses it too, so it never says "1" where a click /// adds a marker (#11773). pub(crate) fn count_marker_at(app: &PhotocraftApp, at: [f64; 2]) -> Option<(usize, usize)> { - let doc = app.session.active().map(|d| d.doc.clone())?; - nearest_marker(&doc, at, tolerance(app)) + nearest_marker(&app.session.active()?.doc, at, tolerance(app)) } fn nearest_marker(d: &Document, at: [f64; 2], tol: f64) -> Option<(usize, usize)> { From f72e3bdc7f908c5e0ae7ace61921fd5320366d31 Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sat, 7 Nov 2026 18:32:16 -0600 Subject: [PATCH 11/42] Tool cursors: put bucket()'s doc comment back on bucket() (eliets2 review on crates/ui-egui/src/canvas/tool_cursor.rs, CountCursor) The Count cursor was inserted between bucket()'s comment and bucket(), so that line documented CountCursor instead. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas/tool_cursor.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/canvas/tool_cursor.rs b/crates/ui-egui/src/canvas/tool_cursor.rs index 4229b23e54e..b647bf8d571 100644 --- a/crates/ui-egui/src/canvas/tool_cursor.rs +++ b/crates/ui-egui/src/canvas/tool_cursor.rs @@ -84,7 +84,6 @@ impl egui::plugin::Plugin for CursorLifecycle { } } -/// The bucket artwork and its exact fill crosshair move as one native cursor or painted image. /// The Count tool's cursor (#11773): an arrow with "1+" (a click adds a marker), "1" (over a /// marker: a click or drag moves it) or "1−" (⌥ over a marker: a click deletes it). #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -131,6 +130,7 @@ pub(crate) fn count(ctx: &egui::Context, at: Pos2, kind: CountCursor) -> CursorI CursorIcon::Default } +/// The bucket artwork and its exact fill crosshair move as one native cursor or painted image. pub(crate) fn bucket(painter: &Painter, at: Pos2) -> Result { bucket::show(painter, at) } From 9f3cbcb87a410bc612d699af882760f859c0f708 Mon Sep 17 00:00:00 2001 From: DuBearte <130190089+DuBearte@users.noreply.github.com> Date: Sat, 7 Nov 2026 22:31:30 -0500 Subject: [PATCH 12/42] Ruler: a plain click keeps the current ruler (#11980) A press away from the ruler still starts a new one, but a release without movement now puts back the ruler that was there instead of clearing it. Co-Authored-By: Claude Opus 5.5 --- .../src/tools/analysis_ruler_click_tests.rs | 71 +++++++++++++++++++ crates/ui-egui/src/tools/analysis_ui.rs | 24 +++++-- crates/ui-egui/src/tools/analysis_ui/tests.rs | 5 +- 3 files changed, 93 insertions(+), 7 deletions(-) create mode 100644 crates/ui-egui/src/tools/analysis_ruler_click_tests.rs diff --git a/crates/ui-egui/src/tools/analysis_ruler_click_tests.rs b/crates/ui-egui/src/tools/analysis_ruler_click_tests.rs new file mode 100644 index 00000000000..014ae021669 --- /dev/null +++ b/crates/ui-egui/src/tools/analysis_ruler_click_tests.rs @@ -0,0 +1,71 @@ +//! #11980: a plain click with the Ruler leaves the current ruler alone; a drag still replaces it. + +use super::{PhotocraftApp, Ruler, Tool, ToolEvent, json}; + +/// A 600 × 400 document with the Ruler from 100,100 to 300,250 and the Ruler tool active. +fn ruler_app(protractor: Option<[f64; 2]>) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 600, "height": 400})).unwrap(); + app.run("image.analysis.rulerTool", json!({"start": [100, 100], "end": [300, 250], "protractor": protractor})).unwrap(); + app.ui.tool = Tool::Ruler; + app +} + +fn ruler(app: &PhotocraftApp) -> Option { + app.session.active().unwrap().doc.measurement.ruler +} + +fn history(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().history.past_len() +} + +/// A press at `from` and a release at `to`, moving between them when they differ. +fn gesture(app: &mut PhotocraftApp, [x, y]: [f64; 2], [end_x, end_y]: [f64; 2]) { + crate::canvas::tool_event(app, ToolEvent::Down { x, y, pressure: 1.0 }, egui::Modifiers::NONE); + if [x, y] != [end_x, end_y] { + crate::canvas::tool_event(app, ToolEvent::Move { x: end_x, y: end_y, pressure: 1.0 }, egui::Modifiers::NONE); + } + crate::canvas::tool_event(app, ToolEvent::Up { x: end_x, y: end_y }, egui::Modifiers::NONE); +} + +#[test] +fn a_click_away_from_the_ruler_keeps_it() { + for protractor in [None, Some([150.0, 50.0])] { + let mut app = ruler_app(protractor); + let before = ruler(&app); + let steps = history(&app); + gesture(&mut app, [500.0, 350.0], [500.0, 350.0]); + assert_eq!(ruler(&app), before, "protractor {protractor:?}"); + assert_eq!(history(&app), steps); + } +} + +#[test] +fn a_click_on_an_end_point_keeps_the_ruler() { + let mut app = ruler_app(None); + let before = ruler(&app); + let steps = history(&app); + gesture(&mut app, [300.0, 250.0], [300.0, 250.0]); + gesture(&mut app, [100.0, 100.0], [100.0, 100.0]); + assert_eq!(ruler(&app), before); + assert_eq!(history(&app), steps); +} + +#[test] +fn a_drag_away_from_the_ruler_replaces_it() { + let mut app = ruler_app(Some([150.0, 50.0])); + let steps = history(&app); + gesture(&mut app, [400.0, 300.0], [550.0, 320.0]); + assert_eq!(ruler(&app), Some(Ruler { start: [400.0, 300.0], end: [550.0, 320.0], protractor: None })); + assert_eq!(history(&app), steps); +} + +/// Not measured, so as today: a click with no ruler yet leaves none. +#[test] +fn a_click_with_no_ruler_leaves_none() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 600, "height": 400})).unwrap(); + app.ui.tool = Tool::Ruler; + gesture(&mut app, [500.0, 350.0], [500.0, 350.0]); + assert_eq!(ruler(&app), None); +} diff --git a/crates/ui-egui/src/tools/analysis_ui.rs b/crates/ui-egui/src/tools/analysis_ui.rs index a3b9826acb9..5b364e9427a 100644 --- a/crates/ui-egui/src/tools/analysis_ui.rs +++ b/crates/ui-egui/src/tools/analysis_ui.rs @@ -21,8 +21,8 @@ use crate::theme::Tokens; /// What a pointer drag is doing (not serialised). #[derive(Clone, Copy, Debug, PartialEq)] pub enum Drag { - /// New ruler line from a point. - RulerNew, + /// New ruler line from a point; the ruler it replaces comes back if the press doesn't move (#11980). + RulerNew(Option), /// Moving a ruler handle: 0 start, 1 end, 2 protractor end. RulerHandle(u8), /// Moving count marker (group, index) from where it was. @@ -234,6 +234,10 @@ fn set_ruler(app: &mut PhotocraftApp, r: Ruler) { let _ = app.run("image.analysis.rulerTool", json!({"start": r.start, "end": r.end, "protractor": r.protractor})); } +#[cfg(test)] +#[path = "analysis_ruler_click_tests.rs"] +mod analysis_ruler_click_tests; + #[cfg(test)] #[path = "note_show_on_new_tests.rs"] mod note_show_on_new_tests; @@ -287,14 +291,14 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> Some(r) if near(r.start) => app.ui.analysis.drag = Some(Drag::RulerHandle(0)), _ => { set_ruler(app, Ruler { start: p, end: p, protractor: None }); - app.ui.analysis.drag = Some(Drag::RulerNew); + app.ui.analysis.drag = Some(Drag::RulerNew(cur)); } } } (Tool::Ruler, ToolEvent::Move { x, y, .. }) => { let (Some(drag), Some(mut r)) = (app.ui.analysis.drag, doc.measurement.ruler) else { return true }; match drag { - Drag::RulerNew | Drag::RulerHandle(1) => r.end = constrain(r.start, [x, y], mods.shift), + Drag::RulerNew(_) | Drag::RulerHandle(1) => r.end = constrain(r.start, [x, y], mods.shift), Drag::RulerHandle(0) => r.start = constrain(r.end, [x, y], mods.shift), Drag::RulerHandle(_) => r.protractor = Some(constrain(r.start, [x, y], mods.shift)), _ => return true, @@ -303,8 +307,16 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> } (Tool::Ruler, ToolEvent::Up { .. }) => { let drag = app.ui.analysis.drag.take(); - if drag == Some(Drag::RulerNew) && doc.measurement.ruler.is_some_and(|r| dist(r.start, r.end) < 0.5) { - let _ = app.run("image.analysis.rulerTool", json!({"clear": true})); + if let Some(Drag::RulerNew(before)) = drag + && doc.measurement.ruler.is_some_and(|r| dist(r.start, r.end) < 0.5) + { + // A click leaves the ruler that was there; with none, it leaves none. + match before { + Some(r) => set_ruler(app, r), + None => { + let _ = app.run("image.analysis.rulerTool", json!({"clear": true})); + } + } } } (Tool::Count, ToolEvent::Down { x, y, .. }) => { diff --git a/crates/ui-egui/src/tools/analysis_ui/tests.rs b/crates/ui-egui/src/tools/analysis_ui/tests.rs index 3ed65a3ffd7..af8684108c4 100644 --- a/crates/ui-egui/src/tools/analysis_ui/tests.rs +++ b/crates/ui-egui/src/tools/analysis_ui/tests.rs @@ -92,9 +92,12 @@ fn ruler_drag_protractor_and_clear() { up(&mut app, 60.0, 10.0); let info = photocraft_engine::analysis_cmds::ruler_info(&ruler(&app).unwrap(), &Default::default()); assert!((info["angle"].as_f64().unwrap() - 90.0).abs() < 1e-6, "{info}"); - // A click without a drag far away starts a new line and clears it. + // A click without a drag far away keeps the ruler (#11980); Clear removes it. + let before = ruler(&app); down(&mut app, 150.0, 80.0, none); up(&mut app, 150.0, 80.0); + assert_eq!(ruler(&app), before); + app.run("image.analysis.rulerTool", json!({"clear": true})).unwrap(); assert!(ruler(&app).is_none()); assert_eq!(app.session.active().unwrap().history.past_len(), 0, "the ruler adds no history"); } From 5fa708967f3108c0cae384815a43eb4640678a26 Mon Sep 17 00:00:00 2001 From: "Eng. Mahmoud Bek ElNemer" Date: Mon, 9 Nov 2026 05:07:35 +0200 Subject: [PATCH 13/42] fix(engine): drop selection after masking a live Gradient Fill layer Fixes #12196 --- crates/engine/src/cmd/gradient_fill_cmds.rs | 7 +- .../src/cmd/gradient_fill_selection_tests.rs | 86 +++++++++++++++++++ crates/engine/tests/it/layer_mask_depth.rs | 5 +- 3 files changed, 94 insertions(+), 4 deletions(-) create mode 100644 crates/engine/src/cmd/gradient_fill_selection_tests.rs diff --git a/crates/engine/src/cmd/gradient_fill_cmds.rs b/crates/engine/src/cmd/gradient_fill_cmds.rs index 41f91f8bbb3..39a61de8f48 100644 --- a/crates/engine/src/cmd/gradient_fill_cmds.rs +++ b/crates/engine/src/cmd/gradient_fill_cmds.rs @@ -287,7 +287,7 @@ pub fn apply_set(layer: &Layer, f: &Fill, canvas: Rect, p: &Value, fg: [f32; 4], /// The Gradient Fill layer `gradient.fill.create` adds to `doc` for `p` (also the canvas's live /// preview of a Gradient tool drag): laid out on the canvas, so the handles land exactly where -/// the drag was, and masked by the selection (Photoshop keeps the selection, as a mask). +/// the drag was, and masked by the selection (`create` then drops the selection, #12196). pub fn new_layer(s: &Session, doc: &Document, p: &Value) -> Result { const CMD: &str = CREATE; let from = point(CMD, p, "from")?.ok_or_else(|| bad(CMD, "missing `from` [x, y]"))?; @@ -322,6 +322,7 @@ fn create(s: &mut Session, p: &Value) -> Result { new_layer(s, &d.doc, p)? }; let id = s.edit("New Gradient Fill Layer", |doc, active| { + doc.selection = None; let id = crate::layer_place::insert_new(doc, *active, layer, crate::layer_place::Place::AutoEditable); *active = Some(id); Ok(id) @@ -596,3 +597,7 @@ pub fn specs() -> Vec { #[cfg(test)] mod tests; + +#[cfg(test)] +#[path = "gradient_fill_selection_tests.rs"] +mod gradient_fill_selection_tests; diff --git a/crates/engine/src/cmd/gradient_fill_selection_tests.rs b/crates/engine/src/cmd/gradient_fill_selection_tests.rs new file mode 100644 index 00000000000..838b2163974 --- /dev/null +++ b/crates/engine/src/cmd/gradient_fill_selection_tests.rs @@ -0,0 +1,86 @@ +//! #12196: a live Gradient drag (`gradient.fill.create`) masks the new fill layer with the +//! selection and drops the selection in the same History step, while `new_layer` (used by the +//! canvas preview during the drag) masks the preview without mutating the document's selection. + +use photocraft_geom::Rect; +use serde_json::json; + +use super::{CREATE, LayerId, new_layer}; +use crate::Session; + +/// Creates an 800x600 white-background test session at the given bit depth. +fn session(depth: u32) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 800, "height": 600, "depth": depth, "background": "white"})).unwrap(); + s +} + +/// Verifies that `new_layer` previews a selection-masked gradient without dropping the selection, +/// `gradient.fill.create` masks the new layer and drops the selection, and `edit.undo` restores it. +#[test] +fn create_masks_with_the_selection_drops_it_and_undo_restores_it() { + let bounds = Rect::new(200, 200, 600, 400); + let drag = json!({"from": [200, 200], "to": [600, 400], "stops": [[0, "#000000"], [1, "#000000"]]}); + for depth in [8, 16, 32] { + let mut s = session(depth); + s.execute("select.rect", json!({"x": 200, "y": 200, "width": 400, "height": 200})).unwrap(); + + // The live drag preview calls `new_layer`: it is masked by the selection, renders only + // inside the selection, and leaves the document's selection intact while dragging. + let preview = new_layer(&s, &s.active().unwrap().doc, &drag).unwrap(); + let preview_mask = preview.mask.as_ref().expect("preview is masked by the selection"); + assert_eq!(preview_mask.surface.content_bounds(), bounds, "{depth}-bit preview mask bounds"); + let mut preview_doc = (*s.active().unwrap().doc).clone(); + preview_doc.layers.push(preview); + let flat = photocraft_compose::flatten(&preview_doc); + assert_eq!(flat.px[300 * 800 + 300], [0.0, 0.0, 0.0, 1.0], "{depth}-bit preview inside selection"); + assert_eq!(flat.px[100 * 800 + 100], [1.0, 1.0, 1.0, 1.0], "{depth}-bit preview outside selection"); + assert!(s.active().unwrap().doc.selection.is_some(), "{depth}-bit preview keeps selection"); + + let r = s.execute(CREATE, drag.clone()).unwrap(); + let id = LayerId(r["layer"].as_u64().unwrap()); + let d = s.active().unwrap(); + let l = d.doc.layer(id).unwrap(); + assert_eq!(l.name, "Gradient Fill 1", "{depth}-bit"); + let mask = l.mask.as_ref().expect("selection becomes the fill layer's mask"); + assert_eq!(mask.surface.content_bounds(), bounds, "{depth}-bit mask bounds"); + assert_eq!(mask.value(300, 300), 1.0, "{depth}-bit inside selection"); + assert_eq!(mask.value(100, 100), 0.0, "{depth}-bit outside selection"); + assert!(d.doc.selection.is_none(), "{depth}-bit selection is dropped"); + + // One undo removes the layer and brings the selection back. + s.execute("edit.undo", json!({})).unwrap(); + let d = s.active().unwrap(); + assert!(d.doc.layer(id).is_none(), "{depth}-bit undo removes the layer"); + let sel = d.doc.selection.as_ref().expect("undo brings the selection back"); + assert_eq!(sel.content_bounds(), bounds, "{depth}-bit restored selection bounds"); + + // A soft/feathered selection's fractional coverage goes into the mask and survives undo. + s.execute("select.rect", json!({"x": 200, "y": 200, "width": 400, "height": 200, "feather": 5.0})).unwrap(); + let canvas = s.active().unwrap().doc.bounds(); + let before_sel = s.active().unwrap().doc.selection.as_ref().unwrap().read_region(canvas); + assert!(before_sel.iter().any(|&v| v > 0.0 && v < 1.0), "{depth}-bit has fractional coverage"); + let r = s.execute(CREATE, drag.clone()).unwrap(); + let feathered_id = LayerId(r["layer"].as_u64().unwrap()); + let feathered_mask = s.active().unwrap().doc.layer(feathered_id).unwrap().mask.as_ref().unwrap(); + assert_eq!(feathered_mask.surface.read_region(canvas), before_sel, "{depth}-bit mask carries fractional coverage"); + assert!(s.active().unwrap().doc.selection.is_none(), "{depth}-bit feathered selection dropped"); + s.execute("edit.undo", json!({})).unwrap(); + let after_sel = s.active().unwrap().doc.selection.as_ref().unwrap().read_region(canvas); + assert_eq!(after_sel, before_sel, "{depth}-bit undo restores fractional selection coverage"); + } +} + +/// Verifies that `gradient.fill.create` without an active selection leaves the new layer unmasked. +#[test] +fn create_without_a_selection_adds_an_unmasked_fill_layer() { + for depth in [8, 16, 32] { + let mut s = session(depth); + let r = s.execute(CREATE, json!({"from": [100, 100], "to": [700, 500]})).unwrap(); + let id = LayerId(r["layer"].as_u64().unwrap()); + let d = s.active().unwrap(); + let l = d.doc.layer(id).unwrap(); + assert!(l.mask.is_none(), "{depth}-bit without selection has no mask"); + assert!(d.doc.selection.is_none(), "{depth}-bit still has no selection"); + } +} diff --git a/crates/engine/tests/it/layer_mask_depth.rs b/crates/engine/tests/it/layer_mask_depth.rs index cbe41385325..bfae78bf0e8 100644 --- a/crates/engine/tests/it/layer_mask_depth.rs +++ b/crates/engine/tests/it/layer_mask_depth.rs @@ -135,9 +135,8 @@ fn mask_creation_preserves_selection_coverage_and_existing_masks() { before.selection.as_ref().unwrap().read_region(before.bounds()), "{depth}-bit coverage is unchanged" ); - // The selection went into the mask, except for the Gradient tool's fill layer. - let kept = if command == "gradient.fill.create" { before.selection.clone() } else { None }; - assert_eq!(after.selection, kept, "{command}"); + // The selection went into the mask, so it is dropped (#8801, #12196). + assert!(after.selection.is_none(), "{command}"); assert_eq!(after.layers[0].mask, before.layers[0].mask, "creating a mask does not requantize an existing mask"); } } From 81a3465846d29e9ce650c1514c04eb8c940206e3 Mon Sep 17 00:00:00 2001 From: rmsff <17902130+rmsff@users.noreply.github.com> Date: Sun, 8 Nov 2026 15:11:42 +0300 Subject: [PATCH 14/42] fix(engine): new vertical text is the history state "New Vertical Type Layer" (#12058) type.create recorded "New Type Layer" for every new text layer. As in the reference application, text created with "orientation":"vertical" (a click, a drag for paragraph text, an Alt+drag with the Vertical Type tool) is now one history state named "New Vertical Type Layer"; horizontal text keeps "New Type Layer". A committed Type Mask session is still one "Type Mask" state. --- crates/engine/src/cmd/type_cmds.rs | 10 ++- .../cmd/type_vertical_history_name_tests.rs | 71 +++++++++++++++++++ 2 files changed, 79 insertions(+), 2 deletions(-) create mode 100644 crates/engine/src/cmd/type_vertical_history_name_tests.rs diff --git a/crates/engine/src/cmd/type_cmds.rs b/crates/engine/src/cmd/type_cmds.rs index f1f8aa53c4f..af29d168787 100644 --- a/crates/engine/src/cmd/type_cmds.rs +++ b/crates/engine/src/cmd/type_cmds.rs @@ -937,7 +937,8 @@ pub(crate) fn new_text_layer(s: &Session, p: &Value, cmd: &str) -> Result Vec { let mut t = new_text_layer(s, p, "type.create")?; let given = p.get("name").and_then(Value::as_str).map(str::to_string); let name = given.clone().unwrap_or_else(|| layer_name(&t.text)); - let id = s.edit(NEW_TYPE_LAYER_LABEL, |doc, active| { + // The reference application names new vertical text after its tool (#12058). + let label = if t.orientation == Orientation::Vertical { "New Vertical Type Layer" } else { NEW_TYPE_LAYER_LABEL }; + let id = s.edit(label, |doc, active| { refresh(doc, &mut t); let id = crate::layer_place::insert_new(doc, *active, Layer::new(name, LayerContent::Text(t)), crate::layer_place::Place::AutoEditable); *active = Some(id); @@ -1287,3 +1290,6 @@ fn step_size(s: &mut Session, p: &Value, up: bool, default_by: f32) -> Result Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 300, "height": 300})).unwrap(); + s +} + +fn entries(s: &Session) -> Vec { + s.active().unwrap().history.entries() +} + +/// The history states `type.create` adds with `params`, and the layer it makes. +fn create(params: Value) -> (Vec, u64) { + let mut s = session(); + let before = entries(&s).len(); + let layer = s.execute("type.create", params).unwrap()["layer"].as_u64().unwrap(); + (entries(&s)[before..].to_vec(), layer) +} + +#[test] +fn vertical_text_is_a_new_vertical_type_layer() { + for (what, params) in [ + ("point", json!({"text": "AB", "x": 150, "y": 40, "orientation": "vertical"})), + ("paragraph", json!({"text": "AB", "box": [100, 20, 60, 200], "orientation": "vertical"})), + ] { + assert_eq!(create(params).0, ["New Vertical Type Layer"], "{what}"); + } +} + +#[test] +fn horizontal_text_is_still_a_new_type_layer() { + for (what, params) in [ + ("point", json!({"text": "AB", "x": 40, "y": 120})), + ("point, horizontal", json!({"text": "AB", "x": 40, "y": 120, "orientation": "horizontal"})), + ("paragraph", json!({"text": "AB", "box": [20, 20, 200, 60]})), + ("paragraph, horizontal", json!({"text": "AB", "box": [20, 20, 200, 60], "orientation": "horizontal"})), + ] { + assert_eq!(create(params).0, ["New Type Layer"], "{what}"); + } +} + +/// The Type Mask tools' commands: a hidden working layer from `type.create`, then +/// `type.createSelection` removing it, all coalesced into the session's one step. +#[test] +fn a_type_mask_session_is_still_one_type_mask_state() { + for orientation in ["horizontal", "vertical"] { + let mut s = session(); + let before = entries(&s).len(); + let key = json!("type-mask-session"); + let created = json!({"text": "", "x": 150, "y": 40, "orientation": orientation, "coalesce": key}); + let layer = s.execute("type.create", created).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.setProps", json!({"layer": layer, "visible": false, "coalesce": key})).unwrap(); + s.execute("type.edit", json!({"layer": layer, "text": "AB", "coalesce": key})).unwrap(); + s.execute("type.createSelection", json!({"layer": layer, "removeLayer": true, "coalesce": key})).unwrap(); + assert_eq!(entries(&s)[before..], ["Type Mask"], "{orientation}"); + } + // Without a layer, `type.createSelection` makes its text itself: the same one state. + for orientation in ["horizontal", "vertical"] { + let mut s = session(); + let before = entries(&s).len(); + s.execute("type.createSelection", json!({"text": "AB", "x": 150, "y": 40, "size": 48, "orientation": orientation})).unwrap(); + assert_eq!(entries(&s)[before..], ["Type Mask"], "{orientation}, no layer"); + } +} From 489409fa2e1687eb0484dd8ad4ca92664ac3d975 Mon Sep 17 00:00:00 2001 From: rmsff <17902130+rmsff@users.noreply.github.com> Date: Sun, 8 Nov 2026 17:02:37 +0300 Subject: [PATCH 15/42] fix(engine): a Type Mask keeps the part of its selection past the canvas edge (#12074) --- crates/engine/src/cmd/type_mask_cmds.rs | 58 +++---- .../src/cmd/type_mask_off_canvas_tests.rs | 148 ++++++++++++++++++ 2 files changed, 169 insertions(+), 37 deletions(-) create mode 100644 crates/engine/src/cmd/type_mask_off_canvas_tests.rs diff --git a/crates/engine/src/cmd/type_mask_cmds.rs b/crates/engine/src/cmd/type_mask_cmds.rs index f09cc801224..5332076357e 100644 --- a/crates/engine/src/cmd/type_mask_cmds.rs +++ b/crates/engine/src/cmd/type_mask_cmds.rs @@ -39,38 +39,28 @@ fn antialias(p: &Value) -> Result> { }) } -/// Glyph coverage of `t` (0..=1 per pixel) over its rendered bounds inside the canvas. The text -/// colour's own alpha doesn't thin the selection: every run renders opaque. -fn coverage(doc: &Document, t: &TextLayer) -> (Vec, Rect) { +/// Glyph coverage of `t` (0..=1 per pixel) over its rendered bounds, past the canvas edge too: the +/// reference application keeps a Type Mask's off-canvas part (#12074). The text colour's own alpha +/// doesn't thin the selection: every run renders opaque. +fn coverage(doc: &Document, t: &TextLayer) -> Result<(Vec, Rect)> { let mut t = t.clone(); for r in &mut t.runs { r.style.color.alpha = 1.0; } let mut eng = photocraft_text::shared().lock().unwrap_or_else(|e| e.into_inner()); let surface = eng.render(&t, doc.resolution_dpi, doc.pixel_format()).1.surface; - let area = surface.content_bounds().intersect(&doc.bounds()); + let area = surface.content_bounds(); if area.is_empty() { - return (Vec::new(), Rect::EMPTY); + return Ok((Vec::new(), Rect::EMPTY)); } - let mut px = vec![[0.0f32; 4]; area.width() as usize * area.height() as usize]; + // No longer bounded by the canvas: a very large text must fail as an error, not abort. + const PURPOSE: &str = "the Type Mask selection"; + let len = (area.width() as usize).checked_mul(area.height() as usize).ok_or_else(|| crate::allocation::error(PURPOSE, "requested size overflowed"))?; + let mut px = crate::allocation::filled(len, [0.0f32; 4], PURPOSE)?; surface.read_rgba_into(area, &mut px); - (px.iter().map(|p| p[3]).collect(), area) -} - -/// Coverage of `area`'s mask spread over `to` (which contains `area`), zero elsewhere. -fn widen(m: &[f32], area: Rect, to: Rect) -> Vec { - if area == to { - return m.to_vec(); - } - let (w, aw) = (to.width() as usize, area.width() as usize); - let mut out = vec![0.0; w * to.height() as usize]; - for (y, row) in m.chunks_exact(aw.max(1)).enumerate() { - let start = (area.y0 - to.y0) as usize * w + y * w + (area.x0 - to.x0) as usize; - if let Some(dst) = out.get_mut(start..start + aw) { - dst.copy_from_slice(row); - } - } - out + let mut alpha = crate::allocation::capacity(len, PURPOSE)?; + alpha.extend(px.iter().map(|p| p[3])); + Ok((alpha, area)) } fn create_selection(s: &mut Session, p: &Value) -> Result { @@ -101,21 +91,11 @@ fn create_selection(s: &mut Session, p: &Value) -> Result { if let Some(aa) = aa { t.antialias = aa; } - let (mask, text_area) = coverage(&doc, &t); + let (mask, text_area) = coverage(&doc, &t)?; let selected = s.edit("Type Mask", |doc, active| { - let old = doc.selection.as_ref().map(|o| o.content_bounds().intersect(&doc.bounds())).unwrap_or(Rect::EMPTY); - // Replace and Intersect leave nothing outside the text; Add and Subtract keep the rest. - let area = match mode { - SelectionMode::Add | SelectionMode::Subtract if !old.is_empty() => { - if text_area.is_empty() { - old - } else { - old.union(&text_area) - } - } - _ => text_area, - }; - doc.selection = if area.is_empty() { None } else { sel::combine(doc.selection.as_ref(), &widen(&mask, text_area, area), area, mode) }; + // Replace and Intersect leave nothing outside the text; Add and Subtract keep the rest of + // the selection as it is, its part past the canvas too, without a buffer spanning both. + doc.selection = sel::combine_band(doc.selection.as_ref(), &mask, text_area, mode); if let (true, Some(id)) = (remove, layer) { let neighbours = crate::layer_multi_cmds::deletion_neighbours(doc, id); doc.remove(id).ok_or(EngineError::NoLayer(id))?; @@ -148,6 +128,10 @@ pub fn specs() -> Vec { }] } +#[cfg(test)] +#[path = "type_mask_off_canvas_tests.rs"] +mod off_canvas_tests; + #[cfg(test)] mod tests { use super::*; diff --git a/crates/engine/src/cmd/type_mask_off_canvas_tests.rs b/crates/engine/src/cmd/type_mask_off_canvas_tests.rs new file mode 100644 index 00000000000..58b10772d2f --- /dev/null +++ b/crates/engine/src/cmd/type_mask_off_canvas_tests.rs @@ -0,0 +1,148 @@ +//! #12074: a Type Mask that runs past the canvas edge keeps the off-canvas part of its selection, +//! as the reference application does; masks fully on the canvas select exactly as before. + +use photocraft_doc::{LayerContent, LayerId}; +use photocraft_geom::Rect; +use photocraft_raster::Surface; +use serde_json::{Value, json}; + +use crate::Session; + +fn session(width: u32, height: u32) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": width, "height": height})).unwrap(); + s +} + +fn selection(s: &Session) -> Option { + s.active().unwrap().doc.selection.clone() +} + +fn bounds(s: &Session) -> Rect { + selection(s).map_or(Rect::EMPTY, |m| m.content_bounds()) +} + +fn mask(s: &mut Session, params: Value) -> Rect { + s.execute(super::CMD, params).unwrap(); + bounds(s) +} + +/// The rendered bounds of the same text as a type layer, which the canvas doesn't clip. +fn layer_bounds(width: u32, height: u32, params: Value) -> Rect { + let mut s = session(width, height); + let r = s.execute("type.create", params).unwrap(); + let b: Vec = r["bounds"].as_array().unwrap().iter().map(|v| i32::try_from(v.as_i64().unwrap()).unwrap()).collect(); + Rect::new(b[0], b[1], b[2], b[3]) +} + +#[test] +fn a_mask_started_on_the_pasteboard_selects_the_glyphs_left_of_the_canvas() { + let text = json!({"text": "MASK", "x": -129, "y": 300, "size": 48}); + let mut s = session(600, 400); + let b = mask(&mut s, text.clone()); + assert!(b.x0 < 0, "{b:?}"); + assert!(b.x1 > 0, "the text reaches onto the canvas: {b:?}"); + assert_eq!(b, layer_bounds(600, 400, text), "the whole outline, as the type layer renders it"); +} + +#[test] +fn a_vertical_mask_keeps_the_part_below_the_canvas() { + let text = json!({"text": "MASKMASKMASK", "x": 500, "y": 450, "size": 48, "orientation": "vertical"}); + let mut s = session(800, 600); + let b = mask(&mut s, text.clone()); + assert!(b.y0 < 600 && b.y1 > 600, "{b:?}"); + assert_eq!(b, layer_bounds(800, 600, text)); +} + +/// Moving the selection onto the canvas shows the whole outline: it equals a mask of the same text +/// started there. +#[test] +fn moving_the_selection_onto_the_canvas_shows_the_whole_outline() { + let mut s = session(600, 400); + mask(&mut s, json!({"text": "MASK", "x": -129, "y": 300, "size": 48})); + s.execute("select.transformSelection", json!({"dx": 200, "stepName": "Move Selection"})).unwrap(); + let moved = selection(&s).unwrap(); + let mut s = session(600, 400); + mask(&mut s, json!({"text": "MASK", "x": 71, "y": 300, "size": 48})); + let there = selection(&s).unwrap(); + assert_eq!(moved.content_bounds(), there.content_bounds()); + let b = there.content_bounds(); + assert!(b.x0 >= 0, "now fully on the canvas: {b:?}"); + assert_eq!(moved.read_region(b), there.read_region(b), "pixel for pixel"); +} + +/// Adding a mask to, or subtracting it from, a selection that runs past the canvas keeps that part. +#[test] +fn add_and_subtract_keep_an_off_canvas_previous_selection() { + for operation in ["add", "subtract"] { + let mut s = session(600, 400); + // A rectangle dragged half off the left edge. + s.execute("select.rect", json!({"x": 10, "y": 50, "width": 100, "height": 70})).unwrap(); + s.execute("select.transformSelection", json!({"dx": -60, "stepName": "Move Selection"})).unwrap(); + let first = bounds(&s); + assert_eq!(first, Rect::new(-50, 50, 50, 120), "precondition"); + let off = Rect::new(-50, 50, 0, 120); + let before = selection(&s).unwrap().read_region(off); + mask(&mut s, json!({"text": "I", "x": 400, "y": 300, "size": 48, "operation": operation})); + assert_eq!(bounds(&s).x0, -50, "{operation}: the off-canvas part stays"); + assert_eq!(selection(&s).unwrap().read_region(off), before, "{operation}: unchanged left of the canvas"); + } +} + +/// The glyph buffers are no longer bounded by the canvas, so running out of memory for either of +/// them is an error that changes nothing, not an abort. +#[test] +fn a_failed_coverage_allocation_is_an_error_that_changes_nothing() { + for skip in [0, 1] { + let mut s = session(600, 400); + s.execute("select.rect", json!({"x": 400, "y": 50, "width": 100, "height": 70})).unwrap(); + let (before, steps) = (selection(&s), s.active().unwrap().history.entries().len()); + crate::allocation::fail_after_for_test(skip); + let err = s.execute(super::CMD, json!({"text": "MASK", "x": -129, "y": 300, "size": 48})).unwrap_err().to_string(); + assert!(err.contains("not enough memory for the Type Mask selection"), "allocation {skip}: {err}"); + assert_eq!(selection(&s), before, "allocation {skip}"); + assert_eq!(s.active().unwrap().history.entries().len(), steps, "allocation {skip}: no history step"); + } +} + +/// The expected selection at one pixel from the rectangle's and the glyphs' coverage. +type Combine = fn(f32, f32) -> f32; + +/// A mask fully on the canvas selects what it did before: the glyphs' coverage, which is the alpha +/// of the same text rasterized, and new / add / subtract / intersect with a rectangle over part of +/// the text combine the two pixel by pixel. +#[test] +fn masks_on_the_canvas_select_as_before() { + let text = json!({"text": "MASK", "x": 100, "y": 200, "size": 48, "color": "#000000"}); + let outline = layer_bounds(600, 400, text.clone()); + assert!(outline.x0 >= 0 && outline.y0 >= 0 && outline.x1 <= 600 && outline.y1 <= 400, "{outline:?}"); + let rect = Rect::new(outline.x0 + 20, outline.y0 - 10, outline.x0 + 80, outline.y1 + 10); + let area = outline.union(&rect); + let glyphs: Vec = { + let mut s = session(600, 400); + let id = s.execute("type.create", text.clone()).unwrap()["layer"].as_u64().unwrap(); + s.execute("type.rasterize", json!({"layer": id})).unwrap(); + match &s.active().unwrap().doc.layer(LayerId(id)).unwrap().content { + LayerContent::Raster(px) => px.read_region(area).as_chunks::<4>().0.iter().map(|p| p[3]).collect(), + other => panic!("{}", other.kind_name()), + } + }; + assert!(glyphs.iter().any(|&a| a > 0.0 && a < 1.0), "anti-aliased edges are compared too"); + let inside = |i: usize| { + let (x, y) = (area.x0 + (i % area.width() as usize) as i32, area.y0 + (i / area.width() as usize) as i32); + rect.contains(x, y) + }; + let cases: [(&str, Combine); 4] = [("new", |_, g| g), ("add", |r, g| r.max(g)), ("subtract", |r, g| (r - g).max(0.0)), ("intersect", |r, g| r.min(g))]; + for (operation, expected) in cases { + let mut s = session(600, 400); + s.execute("select.rect", json!({"x": rect.x0, "y": rect.y0, "width": rect.width(), "height": rect.height()})).unwrap(); + let mut p = text.clone(); + p["operation"] = json!(operation); + s.execute(super::CMD, p).unwrap(); + let got = selection(&s).map_or_else(|| vec![0.0; glyphs.len()], |m| m.read_region(area)); + for (i, (&v, &g)) in got.iter().zip(&glyphs).enumerate() { + let want = expected(if inside(i) { 1.0 } else { 0.0 }, g); + assert!((v - want).abs() <= 1.5 / 255.0, "{operation}: pixel {i} is {v}, expected {want}"); + } + } +} From afe22a961598abefe6b7d49bc72f5c68a24fcf16 Mon Sep 17 00:00:00 2001 From: rmsff <17902130+rmsff@users.noreply.github.com> Date: Sun, 8 Nov 2026 20:28:29 +0300 Subject: [PATCH 16/42] fix(engine): check memory before a Type Mask combines with a non-grey selection; test empty text, Replace, Intersect and a vertical move (#12074) --- crates/engine/src/cmd/type_mask_cmds.rs | 17 +++- .../src/cmd/type_mask_off_canvas_tests.rs | 79 +++++++++++++++++++ 2 files changed, 95 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/type_mask_cmds.rs b/crates/engine/src/cmd/type_mask_cmds.rs index 5332076357e..0157175ba08 100644 --- a/crates/engine/src/cmd/type_mask_cmds.rs +++ b/crates/engine/src/cmd/type_mask_cmds.rs @@ -16,6 +16,8 @@ use crate::commands::CommandSpec; use crate::{EngineError, Result, Session}; const CMD: &str = "type.createSelection"; +/// What an allocation failure names: the buffers are no longer bounded by the canvas. +const PURPOSE: &str = "the Type Mask selection"; fn bad(msg: impl Into) -> EngineError { EngineError::BadParams { cmd: CMD.into(), msg: msg.into() } @@ -54,7 +56,6 @@ fn coverage(doc: &Document, t: &TextLayer) -> Result<(Vec, Rect)> { return Ok((Vec::new(), Rect::EMPTY)); } // No longer bounded by the canvas: a very large text must fail as an error, not abort. - const PURPOSE: &str = "the Type Mask selection"; let len = (area.width() as usize).checked_mul(area.height() as usize).ok_or_else(|| crate::allocation::error(PURPOSE, "requested size overflowed"))?; let mut px = crate::allocation::filled(len, [0.0f32; 4], PURPOSE)?; surface.read_rgba_into(area, &mut px); @@ -92,6 +93,20 @@ fn create_selection(s: &mut Session, p: &Value) -> Result { t.antialias = aa; } let (mask, text_area) = coverage(&doc, &t)?; + // With an unusual earlier selection (not 8-bit grey), `combine_band` keeps its format through + // buffers spanning the text, made where running out of memory aborts: check first that they + // fit, so a text too big for them is an error that changes nothing. Per pixel that is up to: + // the combined grey tiles and their float copy (1 + 4), the copy widened to every channel and + // its growth while collected (8 per channel), and the earlier selection's own new tiles. An + // Intersect reads the earlier selection over the band the same way. + if mode != SelectionMode::Replace + && let Some(old) = doc.selection.as_ref().filter(|o| o.format() != photocraft_color::PixelFormat::GRAY8) + { + let per_pixel = 5 + 8 * old.channels() + old.format().bytes_per_pixel(); + let bytes = (text_area.width() as usize).checked_mul(text_area.height() as usize).and_then(|n| n.checked_mul(per_pixel)); + let bytes = bytes.ok_or_else(|| crate::allocation::error(PURPOSE, "requested size overflowed"))?; + drop(crate::allocation::capacity::(bytes, PURPOSE)?); + } let selected = s.edit("Type Mask", |doc, active| { // Replace and Intersect leave nothing outside the text; Add and Subtract keep the rest of // the selection as it is, its part past the canvas too, without a buffer spanning both. diff --git a/crates/engine/src/cmd/type_mask_off_canvas_tests.rs b/crates/engine/src/cmd/type_mask_off_canvas_tests.rs index 58b10772d2f..fea7cc5998f 100644 --- a/crates/engine/src/cmd/type_mask_off_canvas_tests.rs +++ b/crates/engine/src/cmd/type_mask_off_canvas_tests.rs @@ -52,6 +52,16 @@ fn a_vertical_mask_keeps_the_part_below_the_canvas() { let b = mask(&mut s, text.clone()); assert!(b.y0 < 600 && b.y1 > 600, "{b:?}"); assert_eq!(b, layer_bounds(800, 600, text)); + + // Moved up, the rows that were below the canvas are there: it equals the text masked there. + s.execute("select.transformSelection", json!({"dy": -300, "stepName": "Move Selection"})).unwrap(); + let moved = selection(&s).unwrap(); + let mut s = session(800, 600); + mask(&mut s, json!({"text": "MASKMASKMASK", "x": 500, "y": 150, "size": 48, "orientation": "vertical"})); + let there = selection(&s).unwrap(); + let b = there.content_bounds(); + assert_eq!(moved.content_bounds(), b); + assert_eq!(moved.read_region(b), there.read_region(b), "pixel for pixel"); } /// Moving the selection onto the canvas shows the whole outline: it equals a mask of the same text @@ -146,3 +156,72 @@ fn masks_on_the_canvas_select_as_before() { } } } + +/// Text with no glyphs selects nothing: Add and Subtract leave an earlier selection as it is, +/// Replace and Intersect clear it, as before the combine step changed. +#[test] +fn a_mask_with_no_glyphs_keeps_or_clears_as_before() { + for operation in ["new", "add", "subtract", "intersect"] { + for earlier in [false, true] { + let mut s = session(600, 400); + if earlier { + s.execute("select.rect", json!({"x": 400, "y": 50, "width": 100, "height": 70})).unwrap(); + } + let before = selection(&s); + let r = s.execute(super::CMD, json!({"text": " ", "x": 100, "y": 200, "size": 48, "operation": operation})).unwrap(); + let kept = earlier && matches!(operation, "add" | "subtract"); + assert_eq!(selection(&s), if kept { before } else { None }, "{operation}, earlier selection {earlier}"); + assert_eq!(r["selected"], json!(kept), "{operation}, earlier selection {earlier}"); + } + } +} + +/// Replace and Intersect keep nothing of an earlier selection outside the text, its part past the +/// canvas included. +#[test] +fn replace_and_intersect_drop_an_off_canvas_previous_selection() { + // A new mask keeps nothing of the earlier rectangle (it ends at x 50, the text starts at 400); + // an intersection keeps only its on-canvas part under the text. + for (operation, x, left, right) in [("new", 400, 50, i32::MAX), ("intersect", 10, 0, 50)] { + let mut s = session(600, 400); + s.execute("select.rect", json!({"x": 10, "y": 50, "width": 100, "height": 70})).unwrap(); + s.execute("select.transformSelection", json!({"dx": -60, "stepName": "Move Selection"})).unwrap(); + assert_eq!(bounds(&s), Rect::new(-50, 50, 50, 120), "precondition"); + let b = mask(&mut s, json!({"text": "I", "x": x, "y": 110, "size": 48, "operation": operation})); + assert!(!b.is_empty() && b.x0 >= left && b.x1 <= right, "{operation}: only the text's part is left: {b:?}"); + } +} + +/// Adding to an unusual earlier selection (not 8-bit grey) keeps its format; when its buffers over +/// the text can't be had, that's an error that changes nothing, not an abort. +#[test] +fn an_unusual_earlier_selection_keeps_its_format_or_fails_cleanly() { + use photocraft_color::{PixelFormat, SampleType}; + let format = PixelFormat::GRAY8.with_sample(SampleType::F32); + let earlier = Rect::new(-50, 50, 50, 120); + let mut old = Surface::new(format); + old.write_region(earlier, &vec![1.0; (earlier.width() * earlier.height()) as usize]); + let mut s = session(600, 400); + std::sync::Arc::make_mut(&mut s.active_mut().unwrap().doc).selection = Some(old.clone()); + let text = json!({"text": "I", "x": 400, "y": 300, "size": 48, "operation": "add"}); + + // The two glyph buffers are had; the third allocation is the room for combining. + crate::allocation::fail_after_for_test(2); + let steps = s.active().unwrap().history.entries().len(); + let err = s.execute(super::CMD, text.clone()).unwrap_err().to_string(); + assert!(err.contains("not enough memory for the Type Mask selection"), "{err}"); + assert_eq!(selection(&s), Some(old.clone()), "unchanged"); + assert_eq!(s.active().unwrap().history.entries().len(), steps, "no history step"); + + s.execute(super::CMD, text.clone()).unwrap(); + let now = selection(&s).unwrap(); + assert_eq!(now.format(), format); + assert_eq!(now.read_region(earlier), old.read_region(earlier), "the earlier part stays, past the canvas too"); + + // The third attempt is that check: an 8-bit grey earlier selection needs none, so the same + // failure point is never reached and the mask goes through. + let mut s = session(600, 400); + s.execute("select.rect", json!({"x": 10, "y": 50, "width": 100, "height": 70})).unwrap(); + crate::allocation::fail_after_for_test(2); + s.execute(super::CMD, text).unwrap(); +} From c3efacb333bc4f0954aca5827bc129eaeb52fc28 Mon Sep 17 00:00:00 2001 From: rmsff <17902130+rmsff@users.noreply.github.com> Date: Sun, 8 Nov 2026 23:46:12 +0300 Subject: [PATCH 17/42] fix(engine): check memory before a Type Mask builds any selection over the text's band (#12074) --- crates/engine/src/cmd/type_mask_cmds.rs | 25 ++++++++----------- .../src/cmd/type_mask_off_canvas_tests.rs | 22 ++++++++++------ 2 files changed, 25 insertions(+), 22 deletions(-) diff --git a/crates/engine/src/cmd/type_mask_cmds.rs b/crates/engine/src/cmd/type_mask_cmds.rs index 0157175ba08..2aa4739e877 100644 --- a/crates/engine/src/cmd/type_mask_cmds.rs +++ b/crates/engine/src/cmd/type_mask_cmds.rs @@ -93,20 +93,17 @@ fn create_selection(s: &mut Session, p: &Value) -> Result { t.antialias = aa; } let (mask, text_area) = coverage(&doc, &t)?; - // With an unusual earlier selection (not 8-bit grey), `combine_band` keeps its format through - // buffers spanning the text, made where running out of memory aborts: check first that they - // fit, so a text too big for them is an error that changes nothing. Per pixel that is up to: - // the combined grey tiles and their float copy (1 + 4), the copy widened to every channel and - // its growth while collected (8 per channel), and the earlier selection's own new tiles. An - // Intersect reads the earlier selection over the band the same way. - if mode != SelectionMode::Replace - && let Some(old) = doc.selection.as_ref().filter(|o| o.format() != photocraft_color::PixelFormat::GRAY8) - { - let per_pixel = 5 + 8 * old.channels() + old.format().bytes_per_pixel(); - let bytes = (text_area.width() as usize).checked_mul(text_area.height() as usize).and_then(|n| n.checked_mul(per_pixel)); - let bytes = bytes.ok_or_else(|| crate::allocation::error(PURPOSE, "requested size overflowed"))?; - drop(crate::allocation::capacity::(bytes, PURPOSE)?); - } + // `combine_band` builds the new selection over the text's band where running out of memory + // aborts, and the band is no longer bounded by the canvas: check first that it fits, so a text + // too big for it is an error that changes nothing. Per pixel that is the new 8-bit grey tiles. + // With an unusual earlier selection (not 8-bit grey) that the mode reads, it keeps its format + // through more: the combined grey tiles and their float copy (1 + 4), the copy widened to every + // channel and its growth while collected (8 per channel), and its own new tiles. + let unusual = doc.selection.as_ref().filter(|o| mode != SelectionMode::Replace && o.format() != photocraft_color::PixelFormat::GRAY8); + let per_pixel = unusual.map_or(1, |old| 5 + 8 * old.channels() + old.format().bytes_per_pixel()); + let bytes = (text_area.width() as usize).checked_mul(text_area.height() as usize).and_then(|n| n.checked_mul(per_pixel)); + let bytes = bytes.ok_or_else(|| crate::allocation::error(PURPOSE, "requested size overflowed"))?; + drop(crate::allocation::capacity::(bytes, PURPOSE)?); let selected = s.edit("Type Mask", |doc, active| { // Replace and Intersect leave nothing outside the text; Add and Subtract keep the rest of // the selection as it is, its part past the canvas too, without a buffer spanning both. diff --git a/crates/engine/src/cmd/type_mask_off_canvas_tests.rs b/crates/engine/src/cmd/type_mask_off_canvas_tests.rs index fea7cc5998f..7b2aa1adff3 100644 --- a/crates/engine/src/cmd/type_mask_off_canvas_tests.rs +++ b/crates/engine/src/cmd/type_mask_off_canvas_tests.rs @@ -192,8 +192,9 @@ fn replace_and_intersect_drop_an_off_canvas_previous_selection() { } } -/// Adding to an unusual earlier selection (not 8-bit grey) keeps its format; when its buffers over -/// the text can't be had, that's an error that changes nothing, not an abort. +/// Adding to an unusual earlier selection (not 8-bit grey) keeps its format; when the buffers that +/// combining makes over the text can't be had, for any selection, that's an error that changes +/// nothing, not an abort. #[test] fn an_unusual_earlier_selection_keeps_its_format_or_fails_cleanly() { use photocraft_color::{PixelFormat, SampleType}; @@ -218,10 +219,15 @@ fn an_unusual_earlier_selection_keeps_its_format_or_fails_cleanly() { assert_eq!(now.format(), format); assert_eq!(now.read_region(earlier), old.read_region(earlier), "the earlier part stays, past the canvas too"); - // The third attempt is that check: an 8-bit grey earlier selection needs none, so the same - // failure point is never reached and the mask goes through. - let mut s = session(600, 400); - s.execute("select.rect", json!({"x": 10, "y": 50, "width": 100, "height": 70})).unwrap(); - crate::allocation::fail_after_for_test(2); - s.execute(super::CMD, text).unwrap(); + // An 8-bit grey earlier selection, in every mode, gets the same check for its new tiles. + for operation in ["add", "subtract", "new", "intersect"] { + let mut s = session(600, 400); + s.execute("select.rect", json!({"x": 10, "y": 50, "width": 100, "height": 70})).unwrap(); + let (before, steps) = (selection(&s), s.active().unwrap().history.entries().len()); + crate::allocation::fail_after_for_test(2); + let err = s.execute(super::CMD, json!({"text": "I", "x": 400, "y": 300, "size": 48, "operation": operation})).unwrap_err().to_string(); + assert!(err.contains("not enough memory for the Type Mask selection"), "{operation}: {err}"); + assert_eq!(selection(&s), before, "{operation}: unchanged"); + assert_eq!(s.active().unwrap().history.entries().len(), steps, "{operation}: no history step"); + } } From 7bc71a86de9639c9db038f73e61efac0d332c91d Mon Sep 17 00:00:00 2001 From: "Eng. Mahmoud Bek ElNemer" Date: Tue, 10 Nov 2026 02:37:47 +0200 Subject: [PATCH 18/42] feat(ui): add Content-Aware Move canvas selection context menus (#12194) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Open the selection context menus on canvas right-click when the Content-Aware Move tool is active: - With no selection or outside an active selection, open the selection menus matching Tool::Lasso. - Inside an active selection, open Color Range… and Load Selection…, greying Load Selection… until a non-spot alpha channel is saved. - Keep Bitmap, Duotone, Multichannel, and empty-session states on their existing no-menu path while releasing any non-held color HUD. Fixes #12194 --- crates/ui-egui/src/canvas/canvas_tool_menu.rs | 65 +++++++- .../canvas/canvas_tool_menu/cam_menu_tests.rs | 142 ++++++++++++++++++ crates/ui-egui/src/transform_type_tests.rs | 1 + 3 files changed, 204 insertions(+), 4 deletions(-) create mode 100644 crates/ui-egui/src/canvas/canvas_tool_menu/cam_menu_tests.rs diff --git a/crates/ui-egui/src/canvas/canvas_tool_menu.rs b/crates/ui-egui/src/canvas/canvas_tool_menu.rs index 7231c565613..1c047b77b44 100644 --- a/crates/ui-egui/src/canvas/canvas_tool_menu.rs +++ b/crates/ui-egui/src/canvas/canvas_tool_menu.rs @@ -3,7 +3,7 @@ //! pasteboard (outside the image), a guide and a pending crop. use egui::Context; -use photocraft_doc::LayerContent; +use photocraft_doc::{ColorMode, LayerContent}; use photocraft_engine::prefs::{self, CanvasColor}; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; @@ -59,6 +59,9 @@ pub struct CanvasToolMenu { /// the Sample Size, which its Copy Color rows put on the clipboard. `None` over transparency. #[serde(default)] pub color: Option<[f32; 3]>, + /// Opened with the Content-Aware Move tool inside the active selection (#12194). + #[serde(default)] + pub inside_selection: bool, } /// A misspelled word in the type layer being edited (`edit.checkSpelling`'s `list` entry). @@ -319,6 +322,7 @@ pub fn open_crop(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, pos: [f32; sampler: None, sampler_at: None, color: None, + inside_selection: false, }); crate::canvas_popup::mark_open(ctx, menu_id()); true @@ -435,6 +439,9 @@ pub const NO_SELECTION_MENU: &[Row] = &[ Some(("Load Selection…", "select.loadSelection")), ]; +/// Right-click with the Content-Aware Move tool inside an active selection (#12194). +pub const CAM_INSIDE_SELECTION_MENU: &[Row] = &[Some(("Color Range…", "select.colorRange")), Some(("Load Selection…", "select.loadSelection"))]; + /// The Eyedropper's copy rows (#11747). pub const EYEDROPPER_COPY_HTML: &str = "canvasMenu.eyedropper.copyHtml"; pub const EYEDROPPER_COPY_HEX: &str = "canvasMenu.eyedropper.copyHex"; @@ -548,8 +555,26 @@ fn sampler_menu(menu: &CanvasToolMenu) -> bool { menu.tool == Tool::ColorSampler && !menu.transform && !menu.pasteboard && !menu.guide && menu.crop.is_none() && menu.anchor.is_none() } -/// Tools whose plain canvas right-click opens a menu: the selection tools' actions, the path -/// menu and the Color Sampler's. +/// Is `menu` the Content-Aware Move tool's menu opened inside the active selection (#12194)? +pub fn inside_selection(menu: &CanvasToolMenu) -> bool { + menu.tool == Tool::ContentAwareMove + && menu.has_selection + && menu.inside_selection + && !menu.transform + && !menu.pasteboard + && !menu.guide + && menu.crop.is_none() + && menu.anchor.is_none() +} + +/// Content-Aware Move's canvas context menu requires an open document and leaves Bitmap, Duotone +/// and Multichannel documents on their existing no-menu path (#12194). +fn cam_allowed(app: &PhotocraftApp) -> bool { + app.session.active().is_some_and(|s| !matches!(s.doc.mode, ColorMode::Bitmap | ColorMode::Duotone | ColorMode::Multichannel)) +} + +/// Tools whose plain canvas right-click opens a menu: the selection tools' actions, the +/// Content-Aware Move menu, the path menu and the Color Sampler's. pub fn applies(tool: Tool) -> bool { matches!( tool, @@ -568,6 +593,7 @@ pub fn applies(tool: Tool) -> bool { | Tool::ColorSampler // Sample Size and Copy Color (#11747). | Tool::Eyedropper + | Tool::ContentAwareMove ) || path_menu(tool) } @@ -621,6 +647,8 @@ pub fn rows(menu: &CanvasToolMenu) -> &'static [Row] { SAMPLER_MENU } else if menu.tool == Tool::Eyedropper { EYEDROPPER_MENU + } else if inside_selection(menu) { + CAM_INSIDE_SELECTION_MENU } else { selection_rows(menu.has_selection) } @@ -766,6 +794,7 @@ pub fn open_transform(app: &mut PhotocraftApp, ctx: &Context, pos: [f32; 2]) -> sampler: None, sampler_at: None, color: None, + inside_selection: false, }); crate::canvas_popup::mark_open(ctx, menu_id()); true @@ -823,7 +852,7 @@ pub fn pasteboard_at(app: &PhotocraftApp, tool: Tool, doc: [f64; 2]) -> bool { let Some(st) = app.session.active() else { return false }; let (w, h) = (f64::from(st.doc.size.width), f64::from(st.doc.size.height)); let outside = doc.iter().all(|v| v.is_finite()) && (doc[0] < 0.0 || doc[1] < 0.0 || doc[0] >= w || doc[1] >= h); - outside && !path_menu(tool) && !crate::paint_mouse::has_brush_picker(tool) && !crate::paint_mouse::right_erases(app, tool) && app.ui.text_edit.is_none() + outside && !path_menu(tool) && !crate::paint_mouse::has_brush_picker(tool) && !crate::paint_mouse::right_erases(app, tool) && !editing_text(app, tool) } /// Right-click on the pasteboard: its colour menu at screen point `pos`. @@ -850,6 +879,7 @@ pub fn open_pasteboard(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, pos: sampler: None, sampler_at: None, color: None, + inside_selection: false, }); crate::canvas_popup::mark_open(ctx, menu_id()); true @@ -884,6 +914,7 @@ pub fn open_guide(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, mods: egui sampler: None, sampler_at: None, color: None, + inside_selection: false, }); crate::canvas_popup::mark_open(ctx, menu_id()); true @@ -943,6 +974,11 @@ pub fn entry_enabled(app: &PhotocraftApp, menu: &CanvasToolMenu, command: &str) if sampler_menu(menu) { return command == SAMPLER_DELETE && menu.sampler.is_some() && sampler_current(app, menu); } + // Inside the Content-Aware Move selection menu (#12194), Load Selection… stays greyed until a + // selection channel (non-spot alpha channel) has been saved. + if inside_selection(menu) && command == "select.loadSelection" { + return app.session.active().is_some_and(|st| st.doc.channels.iter().any(|c| c.spot.is_none())) && crate::menus::is_enabled(app, command); + } if menu.transform || !path_menu(menu.tool) { return crate::menus::is_enabled(app, command); } @@ -997,12 +1033,29 @@ pub fn open_at(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, pos: [f32; 2] if !(applies(tool) || text || type_layer) { return false; } + // Without an active document or in Bitmap/Duotone/Multichannel modes, Content-Aware Move opens + // no menu (#12194); release any non-held control-channel HUD that would otherwise stay open. + if tool == Tool::ContentAwareMove && !cam_allowed(app) { + crate::color_hud::release(&mut app.ui); + return false; + } app.ui.brush_picker = None; app.ui.layer_menu = None; let has_selection = app.session.active().is_some_and(|s| s.doc.selection.is_some()); let has_path = crate::vector_ui::active_path_name(app).is_some() || app.ui.pen.as_ref().is_some_and(|p| p.knots.len() >= 2); let path_name = crate::vector_ui::active_path_name(app); let spelling = if text { doc.and_then(|d| spelling_at(app, d)) } else { None }; + let inside_selection = tool == Tool::ContentAwareMove + && doc.is_some_and(|d| { + d.iter().all(|v| v.is_finite()) + && d[0] >= 0.0 + && d[1] >= 0.0 + && app.session.active().is_some_and(|s| { + d[0] < f64::from(s.doc.size.width) + && d[1] < f64::from(s.doc.size.height) + && s.doc.selection.as_ref().is_some_and(|sel| sel.sample_channel(d[0].floor() as i32, d[1].floor() as i32, 0) >= 0.5) + }) + }); let sampler = if tool == Tool::ColorSampler { doc.and_then(|d| crate::analysis_ui::sampler_at(app, d)) } else { None }; let sampler_at = sampler.and_then(|i| Some((app.session.active_index()?, *app.session.active()?.color_samplers.get(i)?))); // The Eyedropper reads the colour now, under the right-click: all layers, with the Sample @@ -1025,6 +1078,7 @@ pub fn open_at(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, pos: [f32; 2] sampler, sampler_at, color, + inside_selection, }); crate::canvas_popup::mark_open(ctx, menu_id()); true @@ -1055,6 +1109,7 @@ pub fn open_view(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, pos: [f32; sampler: None, sampler_at: None, color: None, + inside_selection: false, }); crate::canvas_popup::mark_open(ctx, menu_id()); true @@ -1407,6 +1462,8 @@ pub fn menu_rect_if_open(app: &PhotocraftApp, ctx: &Context) -> Option PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); + app.ui.tool = Tool::ContentAwareMove; + app +} + +fn harness(mut app: PhotocraftApp) -> Harness<'static, PhotocraftApp> { + app.sync_views(); + let mut h = Harness::builder().with_size(vec2(1000.0, 700.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let ctx = ui.ctx().clone(); + if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::default()); + h.run_steps(4); + h +} + +fn right_click(h: &mut Harness<'static, PhotocraftApp>, p: Pos2) { + h.event(egui::Event::PointerMoved(p)); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Secondary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Secondary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(2); +} + +#[test] +fn content_aware_move_outside_and_without_selection_matches_lasso_menus() { + let mut h = harness(app()); + assert!(applies(Tool::ContentAwareMove)); + let center = h.state().last_canvas_rect.center(); + + // With no selection, a canvas right-click opens NO_SELECTION_MENU, matching Tool::Lasso. + right_click(&mut h, center); + let menu = h.state().ui.canvas_tool_menu.clone().expect("no-selection menu opened"); + assert!(!menu.has_selection && !inside_selection(&menu) && menu.sampler.is_none()); + assert_eq!(rows(&menu), NO_SELECTION_MENU); + let ctx = h.ctx.clone(); + choose(h.state_mut(), &ctx, "select.all"); + assert!(h.state().session.active().unwrap().doc.selection.is_some()); + + // Outside an active selection, a canvas right-click opens SELECTION_MENU, matching Tool::Lasso. + h.state_mut().run("select.rect", json!({"x": 2, "y": 2, "width": 6, "height": 6})).unwrap(); + right_click(&mut h, center); + let menu = h.state().ui.canvas_tool_menu.clone().expect("outside-selection menu opened"); + assert!(menu.has_selection && !inside_selection(&menu) && menu.sampler.is_none()); + assert_eq!(rows(&menu), SELECTION_MENU); + choose(h.state_mut(), &ctx, "select.deselect"); + assert!(h.state().session.active().unwrap().doc.selection.is_none()); +} + +#[test] +fn content_aware_move_inside_selection_opens_color_range_and_load_selection_only() { + let mut app = app(); + app.run("select.rect", json!({"x": 4, "y": 4, "width": 24, "height": 24})).unwrap(); + let mut h = harness(app); + let center = h.state().last_canvas_rect.center(); + right_click(&mut h, center); + + let menu = h.state().ui.canvas_tool_menu.clone().expect("inside-selection menu opened"); + assert!(menu.has_selection && inside_selection(&menu) && menu.sampler.is_none() && menu.sampler_at.is_none()); + assert_eq!(rows(&menu), &[Some(("Color Range…", "select.colorRange")), Some(("Load Selection…", "select.loadSelection"))]); + + // Color Range… is enabled; Load Selection… is greyed out when no selection channel is saved. + assert!(entry_enabled(h.state(), &menu, "select.colorRange")); + assert!(!entry_enabled(h.state(), &menu, "select.loadSelection")); + assert!(!available(h.state(), &menu, "select.deselect"), "full selection menu rows are not available inside selection"); + + // A spot channel does not count as a saved selection channel. + let ctx = h.ctx.clone(); + h.state_mut().run("channel.newSpot", json!({"name": "Spot 1"})).unwrap(); + assert!(!entry_enabled(h.state(), &menu, "select.loadSelection")); + + // Once a selection channel is saved, Load Selection… becomes enabled and renders cleanly with no samplers. + h.state_mut().run("select.saveSelection", json!({"name": "Alpha 1"})).unwrap(); + assert!(open_at(h.state_mut(), &ctx, Tool::ContentAwareMove, [10.0, 10.0], Some([16.0, 16.0]))); + h.run_steps(1); + let menu = h.state().ui.canvas_tool_menu.clone().unwrap(); + assert!(entry_enabled(h.state(), &menu, "select.loadSelection")); + + // Even with a saved channel, Load Selection… greys out when menus::is_enabled blocks it (e.g. a pending crop). + h.state_mut().ui.tool = Tool::Crop; + h.state_mut().ui.crop_rect = Some([0.0, 0.0, 16.0, 16.0]); + h.state_mut().crop.default_frame = false; + assert!(!entry_enabled(h.state(), &menu, "select.loadSelection")); + h.state_mut().ui.crop_rect = None; + h.state_mut().ui.tool = Tool::ContentAwareMove; + assert!(entry_enabled(h.state(), &menu, "select.loadSelection")); + + // Choosing Color Range… opens the Color Range dialog. + choose(h.state_mut(), &ctx, "select.colorRange"); + assert!(!h.state().ui.dialogs.is_empty()); + h.state_mut().ui.dialogs.clear(); + + // Choosing Load Selection… opens the Load Selection dialog. + assert!(open_at(h.state_mut(), &ctx, Tool::ContentAwareMove, [10.0, 10.0], Some([16.0, 16.0]))); + choose(h.state_mut(), &ctx, "select.loadSelection"); + assert!(!h.state().ui.dialogs.is_empty()); +} + +#[test] +fn content_aware_move_boundary_modes_and_overlay_guards() { + let ctx = Context::default(); + let mut empty = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + empty.ui.tool = Tool::ContentAwareMove; + crate::color_hud::open(&mut empty, [12.0, 12.0], false); + assert!(!open_at(&mut empty, &ctx, Tool::ContentAwareMove, [10.0, 10.0], Some([8.0, 8.0]))); + assert!(empty.ui.color_hud.is_none()); + + let mut app = app(); + app.run("select.rect", json!({"x": 4, "y": 4, "width": 8, "height": 8})).unwrap(); + // Boundary, negative, and non-finite coordinates. + for (pt, expected) in [([4.0, 4.0], true), ([11.9, 11.9], true), ([3.9, 4.0], false), ([12.0, 12.0], false), ([-1.0, 4.0], false), ([f64::NAN, 4.0], false)] + { + assert!(open_at(&mut app, &ctx, Tool::ContentAwareMove, [10.0, 10.0], Some(pt))); + let m = app.ui.canvas_tool_menu.clone().unwrap(); + assert_eq!(inside_selection(&m), expected, "point {pt:?}"); + } + // Transform/pasteboard/guide/crop/anchor menus are not replaced by CAM_INSIDE_SELECTION_MENU. + let mut tmenu = app.ui.canvas_tool_menu.clone().unwrap(); + tmenu.transform = true; + assert!(!inside_selection(&tmenu) && rows(&tmenu) == TRANSFORM_MENU); + + // Excluded color modes return false and release a non-held color HUD. + for mode in [ColorMode::Bitmap, ColorMode::Duotone, ColorMode::Multichannel] { + std::sync::Arc::make_mut(&mut app.session.active_mut().unwrap().doc).mode = mode; + crate::color_hud::open(&mut app, [12.0, 12.0], false); + assert!(!open_at(&mut app, &ctx, Tool::ContentAwareMove, [10.0, 10.0], Some([6.0, 6.0]))); + assert!(app.ui.color_hud.is_none()); + } +} diff --git a/crates/ui-egui/src/transform_type_tests.rs b/crates/ui-egui/src/transform_type_tests.rs index b6bcfc21984..b1d674d5dc4 100644 --- a/crates/ui-egui/src/transform_type_tests.rs +++ b/crates/ui-egui/src/transform_type_tests.rs @@ -59,6 +59,7 @@ fn type_layers_offer_free_transform_but_not_distort_or_perspective() { sampler: None, sampler_at: None, color: None, + inside_selection: false, }; assert!(crate::canvas_tool_menu::available(&app, &menu, "edit.freeTransform")); assert!(!crate::canvas_tool_menu::available(&app, &menu, "edit.transform.distort")); From 184cc1d9128b2ea338611a9884fb9b485fd8b0fa Mon Sep 17 00:00:00 2001 From: Raghav Krishna Date: Tue, 10 Nov 2026 17:34:37 +0530 Subject: [PATCH 19/42] fix(engine): Object Selection finds objects on a transparent layer (#12852) Object Finder's click sampled the layer composited over 50 % grey, so a fully transparent pixel read as mid grey. A mid-grey object then sat within the growth's colour distance of the empty area, the region reached the canvas edge, and object_in rejected it as background. Red and blue are far from 0.5 grey, which is why only they were found. Sampler gains rgba_scaled, which keeps alpha at working resolution. object_in reads through it once, never grows into a non-opaque working pixel, and gives transparency hard background in the trimap; a click on a transparent pixel finds nothing. rgb_scaled is untouched, so Quick Selection, Select Subject, sky, focus and the rectangle mode keep their results. Tests: the issue's 800x600 document and the Grayscale one in a new test file; both fail without the fix. --- crates/algo/src/segment.rs | 60 ++++++++ crates/algo/src/segment/grabcut.rs | 29 +++- crates/engine/src/cmd/smartselect_cmds.rs | 2 + .../object_transparent_layer_tests.rs | 143 ++++++++++++++++++ 4 files changed, 227 insertions(+), 7 deletions(-) create mode 100644 crates/engine/src/cmd/smartselect_cmds/object_transparent_layer_tests.rs diff --git a/crates/algo/src/segment.rs b/crates/algo/src/segment.rs index 958d3d0f6ae..17d7f24b027 100644 --- a/crates/algo/src/segment.rs +++ b/crates/algo/src/segment.rs @@ -147,6 +147,66 @@ pub trait Sampler: Sync { } RgbImage { w: ow, h: oh, px } } + + /// Straight RGBA (`0..=1`) over `r`, box-downsampled by `step` like [`Self::rgb_scaled`], read + /// in the same strips. Unlike [`Self::rgb`], alpha survives, so a transparent working pixel + /// stays transparent instead of becoming mid grey: Object Finder needs that to stop at the + /// edge of a transparent layer (#12852). + fn rgba_scaled(&self, r: Rect, step: usize) -> Vec<[f32; 4]> { + if step <= 1 { + return self.rgba(r); + } + let (w, h) = (r.width() as usize, r.height() as usize); + let (ow, oh) = (w.div_ceil(step), h.div_ceil(step)); + let rows_per = (64usize.div_ceil(step)).max(1); + let strips: Vec = (0..oh.div_ceil(rows_per)).collect(); + let run = |si: &usize| -> Vec<[f32; 4]> { + let oy0 = si * rows_per; + let oy1 = (oy0 + rows_per).min(oh); + let y0 = r.y0 + (oy0 * step) as i32; + let y1 = (r.y0 + (oy1 * step) as i32).min(r.y1); + let strip = self.rgba(Rect::new(r.x0, y0, r.x1, y1)); + downsample_rgba(&strip, w, (y1 - y0) as usize, step) + }; + #[cfg(not(target_arch = "wasm32"))] + let parts: Vec> = { + use rayon::prelude::*; + strips.par_iter().map(run).collect() + }; + #[cfg(target_arch = "wasm32")] + let parts: Vec> = strips.iter().map(run).collect(); + let mut px = Vec::with_capacity(ow * oh); + for p in parts { + px.extend(p); + } + px + } +} + +/// Box-average straight RGBA by an integer `step` (`ceil(w/step) × ceil(h/step)`). +fn downsample_rgba(px: &[[f32; 4]], w: usize, h: usize, step: usize) -> Vec<[f32; 4]> { + let (ow, oh) = (w.div_ceil(step), h.div_ceil(step)); + let mut out = vec![[0.0f32; 4]; ow * oh]; + for oy in 0..oh { + for ox in 0..ow { + let mut acc = [0.0f32; 4]; + let mut n = 0.0f32; + for y in oy * step..((oy + 1) * step).min(h) { + for x in ox * step..((ox + 1) * step).min(w) { + if let Some(p) = px.get(y * w + x) { + for c in 0..4 { + acc[c] += p[c]; + } + n += 1.0; + } + } + } + if let Some(o) = out.get_mut(oy * ow + ox) { + *o = acc.map(|v| v / n.max(1.0)); + } + } + } + out } /// Samples a raster surface (any format; converted to straight RGBA). diff --git a/crates/algo/src/segment/grabcut.rs b/crates/algo/src/segment/grabcut.rs index 249763ad497..4bebd9e5613 100644 --- a/crates/algo/src/segment/grabcut.rs +++ b/crates/algo/src/segment/grabcut.rs @@ -182,16 +182,23 @@ pub fn object_at(sampler: &dyn Sampler, canvas: Rect, x: f32, y: f32, work_px: u /// One [`object_at`] pass over `canvas` (the document or a window of it) at working step `step`; /// `(px, py)` lies inside `canvas`. fn object_in(sampler: &dyn Sampler, canvas: Rect, px: i32, py: i32, step: usize) -> Option { - let img = sampler.rgb_scaled(canvas, step); - let (w, h) = (img.w, img.h); - if w < 2 || h < 2 { + // Alpha is kept, so a transparent pixel is a boundary rather than the mid grey `from_rgba` + // would composite it to: a mid-grey object on a transparent layer stays an object (#12852). + let rgba = sampler.rgba_scaled(canvas, step); + let (w, h) = ((canvas.width() as usize).div_ceil(step), (canvas.height() as usize).div_ceil(step)); + if w < 2 || h < 2 || rgba.len() < w * h { return None; } + let opaque: Vec = rgba.iter().take(w * h).map(|p| p[3] >= 0.5).collect(); + let img = RgbImage::from_rgba(&rgba, w, h); // Lightly smoothed, so noise and texture don't stop the growth; edges survive. let lab: Vec<[f32; 3]> = box3(&box3(&img.px, w, h), w, h).iter().map(|c| super::slic::rgb_to_lab(*c)).collect(); let sx = (((px - canvas.x0) as usize) / step).min(w - 1); let sy = (((py - canvas.y0) as usize) / step).min(h - 1); - let grown = grow_similar(&lab, w, h, sx, sy); + if !opaque[sy * w + sx] { + return None; + } + let grown = grow_similar(&lab, w, h, sx, sy, &opaque); let count = grown.iter().filter(|g| **g).count(); let boundary = grown.iter().enumerate().filter(|(i, on)| **on && (i % w == 0 || i % w + 1 == w || i / w == 0 || i / w + 1 == h)).count(); // shortcut: cropped objects covering most of the frame need a semantic segmenter (#2788). @@ -215,6 +222,10 @@ fn object_in(sampler: &dyn Sampler, canvas: Rect, px: i32, py: i32, step: usize) let inside = xx >= bx0 && xx < bx1 && yy >= by0 && yy < by1; trimap[i] = if grown[i] { PR_FG + } else if !opaque[i] { + // Transparency is background, whatever it was composited to. + any_bg = true; + BG } else if inside { PR_BG } else { @@ -250,13 +261,17 @@ fn object_in(sampler: &dyn Sampler, canvas: Rect, px: i32, py: i32, step: usize) /// Region growing (4-connected) from `(sx, sy)` over pixels whose CIELAB colour is within a /// distance of the seed area's running mean and whose step from the neighbour it was reached -/// from is small, so it stops at edges. -fn grow_similar(lab: &[[f32; 3]], w: usize, h: usize, sx: usize, sy: usize) -> Vec { +/// from is small, so it stops at edges. A pixel that is not `opaque` is never entered, so +/// transparency stops the growth too. +fn grow_similar(lab: &[[f32; 3]], w: usize, h: usize, sx: usize, sy: usize, opaque: &[bool]) -> Vec { const MEAN_DIST: f32 = 32.0; const EDGE_STEP: f32 = 10.0; let d = |a: [f32; 3], b: [f32; 3]| ((a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2) + (a[2] - b[2]).powi(2)).sqrt(); let mut out = vec![false; w * h]; let Some(&seed) = lab.get(sy * w + sx) else { return out }; + if !opaque.get(sy * w + sx).copied().unwrap_or(false) { + return out; + } let (mut sum, mut n) = ([seed[0] as f64, seed[1] as f64, seed[2] as f64], 1.0f64); let mut stack = vec![(sx, sy)]; out[sy * w + sx] = true; @@ -269,7 +284,7 @@ fn grow_similar(lab: &[[f32; 3]], w: usize, h: usize, sx: usize, sy: usize) -> V continue; } let i = ny * w + nx; - if out[i] { + if out[i] || !opaque.get(i).copied().unwrap_or(true) { continue; } let q = lab[i]; diff --git a/crates/engine/src/cmd/smartselect_cmds.rs b/crates/engine/src/cmd/smartselect_cmds.rs index a8a3e64d369..d8d4b771b19 100644 --- a/crates/engine/src/cmd/smartselect_cmds.rs +++ b/crates/engine/src/cmd/smartselect_cmds.rs @@ -573,5 +573,7 @@ pub fn specs() -> Vec { ] } +#[cfg(test)] +mod object_transparent_layer_tests; #[cfg(test)] mod tests; diff --git a/crates/engine/src/cmd/smartselect_cmds/object_transparent_layer_tests.rs b/crates/engine/src/cmd/smartselect_cmds/object_transparent_layer_tests.rs new file mode 100644 index 00000000000..749ccdc65ac --- /dev/null +++ b/crates/engine/src/cmd/smartselect_cmds/object_transparent_layer_tests.rs @@ -0,0 +1,143 @@ +//! Object Selection's Object Finder click on a transparent layer (#12852): a mid-grey object is +//! an object of its own, and transparency stops the growth instead of reading as 50 % grey. +//! +//! The documents are the ones the issue measured against the reference application. + +use super::*; + +const W: u32 = 800; +const H: u32 = 600; + +/// The issue's document: white Background, then a transparent pixel layer holding a red +/// rectangle, a blue disc and a ten-block grey ramp (100, 105, …, 145 from x 100). +fn issue_document() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": W, "height": H, "depth": 8})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + paint_new_layer(&mut s, W, H, |x, y| { + let (x, y) = (x as i32, y as i32); + if (100..300).contains(&x) && (100..250).contains(&y) { + return [220.0 / 255.0, 30.0 / 255.0, 30.0 / 255.0, 1.0]; + } + let (dx, dy) = (x as f32 + 0.5 - 500.0, y as f32 + 0.5 - 175.0); + if dx * dx + dy * dy <= 75.0 * 75.0 { + return [30.0 / 255.0, 30.0 / 255.0, 220.0 / 255.0, 1.0]; + } + if (100..500).contains(&x) && (350..450).contains(&y) { + let v = (100 + 5 * ((x - 100) / 40)) as f32 / 255.0; + return [v, v, v, 1.0]; + } + [0.0, 0.0, 0.0, 0.0] + }); + s +} + +/// A Grayscale 8-bit document with a grey-87 rectangle on a transparent layer. +fn gray_document() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 400, "height": 300, "mode": "gray", "depth": 8})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + paint_new_layer(&mut s, 400, 300, |x, y| { + let (x, y) = (x as i32, y as i32); + if (100..300).contains(&x) && (100..250).contains(&y) { [87.0 / 255.0, 0.0, 0.0, 1.0] } else { [0.0; 4] } + }); + s +} + +/// Writes `px` (straight RGBA) over the whole surface of the last layer, which `file.new` plus +/// `layer.new.layer` leaves transparent. +fn paint_new_layer(s: &mut Session, w: u32, h: u32, px: impl Fn(u32, u32) -> [f32; 4]) { + s.edit("paint", |doc, _| { + let Some(surf) = doc.layers.last_mut().and_then(Layer::surface_mut) else { + return Err(EngineError::Other("the new layer has no surface".into())); + }; + let n = surf.channels(); + let mut data = Vec::with_capacity((w * h) as usize * n); + for y in 0..h { + for x in 0..w { + let c = px(x, y); + if n >= 4 { + data.extend_from_slice(&c); + } else if n == 2 { + data.extend_from_slice(&[c[0], c[3]]); + } else { + data.extend_from_slice(&c[..n.min(3)]); + } + } + } + surf.write_region(Rect::new(0, 0, w as i32, h as i32), &data); + Ok(()) + }) + .unwrap(); +} + +fn cov(s: &Session, x: i32, y: i32) -> f32 { + s.active().unwrap().doc.selection.as_ref().map_or(0.0, |m| m.sample_channel(x, y, 0)) +} + +/// `[left, top, right, bottom]` of the selection, as the issue writes bounds. +fn bounds(s: &Session) -> [i32; 4] { + let b = s.active().unwrap().doc.selection.as_ref().unwrap().content_bounds(); + [b.x0, b.y0, b.x1, b.y1] +} + +#[test] +fn a_grey_ramp_on_a_transparent_layer_is_found_at_both_points() { + for (x, y) in [(120, 400), (300, 400)] { + let mut s = issue_document(); + let before = s.active().unwrap().history.past_len(); + let r = s.execute("select.object", json!({"point": [x, y]})).unwrap(); + assert_eq!(r["changed"], true, "click at {x},{y}"); + assert_eq!(bounds(&s), [99, 349, 501, 451], "click at {x},{y}"); + // The whole ramp, and nothing around it. + assert!(cov(&s, 120, 400) >= 0.5 && cov(&s, 480, 440) >= 0.5); + assert!(cov(&s, 20, 20) < 0.5 && cov(&s, 700, 500) < 0.5); + // One "Object Selection" step, undone in one go. + assert_eq!(s.active().unwrap().history.past_len(), before + 1); + assert_eq!(s.active().unwrap().history.undo_label(), Some("Object Selection")); + s.execute("edit.undo", json!({})).unwrap(); + assert!(s.active().unwrap().doc.selection.is_none()); + } +} + +#[test] +fn a_grey_rectangle_on_a_transparent_gray_layer_is_found() { + let mut s = gray_document(); + let r = s.execute("select.object", json!({"point": [150, 150]})).unwrap(); + assert_eq!(r["changed"], true); + assert_eq!(bounds(&s), [99, 99, 301, 251]); + assert!(cov(&s, 150, 150) >= 0.5 && cov(&s, 20, 20) < 0.5); +} + +#[test] +fn clicking_transparency_selects_nothing() { + let mut s = issue_document(); + // Transparent pixels inside the layer's own content: between the rectangle and the disc, and + // between the rectangle and the ramp. + for (x, y) in [(350, 150), (200, 300)] { + let r = s.execute("select.object", json!({"point": [x, y]})).unwrap(); + assert_eq!(r["changed"], false, "click at {x},{y}"); + assert!(s.active().unwrap().doc.selection.is_none()); + } +} + +#[test] +fn red_and_blue_still_select_their_own_objects() { + let mut s = issue_document(); + for (x, y) in [(200, 150), (500, 175)] { + let r = s.execute("select.object", json!({"point": [x, y]})).unwrap(); + assert_eq!(r["changed"], true, "click at {x},{y}"); + assert!(cov(&s, x, y) >= 0.5); + // The click stays on its own object. + let other = if x < 400 { (500, 175) } else { (200, 150) }; + assert!(cov(&s, other.0, other.1) < 0.5, "click at {x},{y} leaked into the other object"); + } +} + +#[test] +fn sampling_all_layers_still_finds_the_ramp() { + let mut s = issue_document(); + let r = s.execute("select.object", json!({"point": [120, 400], "sampleAllLayers": true})).unwrap(); + assert_eq!(r["changed"], true); + assert!(cov(&s, 120, 400) >= 0.5 && cov(&s, 480, 440) >= 0.5); +} From 515e1d660e8c7141508152dd011de83185aea23b Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sat, 7 Nov 2026 21:56:23 -0600 Subject: [PATCH 20/42] Eraser and Fill: background swatch through the Grayscale document's grey profile (#11940) On a Grayscale document, the background colour the Eraser paints on the Background (or under a transparency lock) and Edit > Fill > Background Color now go through color_cmds::swatch_in_doc: the swatch converted from the RGB working space to the document's grey profile with photocraft-cms (relative colorimetric with BPC), instead of Rec.601 luma. RGB 0,200,0 gives 153 with the default Dot Gain 20%-compatible profile, not 117. The issue measures 173 in the reference application, which the document's profile can't produce; the two Grayscale tests that pin 173 are ignored until the issue says which conversion the swatch should use. RGB documents are unchanged (tested). --- crates/engine/src/cmd/brush_cmds.rs | 7 +- crates/engine/src/cmd/color_cmds.rs | 22 ++++++ crates/engine/src/cmd/fill_cmds.rs | 3 +- .../src/eraser_gray_background_tests.rs | 68 +++++++++++++++++++ crates/engine/src/lib.rs | 2 + 5 files changed, 98 insertions(+), 4 deletions(-) create mode 100644 crates/engine/src/eraser_gray_background_tests.rs diff --git a/crates/engine/src/cmd/brush_cmds.rs b/crates/engine/src/cmd/brush_cmds.rs index 61a35e51507..55b9be3a7a2 100644 --- a/crates/engine/src/cmd/brush_cmds.rs +++ b/crates/engine/src/cmd/brush_cmds.rs @@ -249,7 +249,8 @@ fn damage_json(s: &mut Session, dmg: Rect) -> Value { fn stroke_target(s: &Session, p: &Value, brush: BrushSettings) -> Result<(Option, BrushSettings, f32)> { let gray = is_mask_target(p) || crate::channel_cmds::is_channel_target(p) || crate::color_channels::target(s, p)?.is_some(); let id = if crate::channel_cmds::is_channel_target(p) { None } else { Some(layer_id(s, p)?) }; - let brush = if gray && brush.erase { BrushSettings { erase: false, color: s.tools.background, ..brush } } else { brush }; + let brush = + if gray && brush.erase { BrushSettings { erase: false, color: crate::color_cmds::swatch_in_doc(s, s.tools.background), ..brush } } else { brush }; Ok((id, brush, num(p, "zoom").unwrap_or(1.0))) } @@ -271,7 +272,7 @@ pub(crate) fn doc_cmyk_space(s: &Session) -> Option, auto_erase: bool) -> Result { - let bg = s.tools.background; + let bg = crate::color_cmds::swatch_in_doc(s, s.tools.background); let fg = brush.color; let symmetry = s.active().and_then(|st| st.symmetry.clone()); let (id, brush, zoom) = stroke_target(s, p, brush)?; @@ -614,7 +615,7 @@ impl LiveStroke { let sel = doc.selection.clone(); let table = crate::mode_cmds::paint_color_table(&doc, p); let (surf, lock) = crate::channel_cmds::target_surface(&mut doc, layer, p)?; - erase_locked(&mut brush, lock, s.tools.background); + erase_locked(&mut brush, lock, crate::color_cmds::swatch_in_doc(s, s.tools.background)); if pencil && flag(p, "autoErase", false) { let fg = table.as_ref().map_or(fg, |t| crate::mode_cmds::table_color(t, fg)); apply_auto_erase(&mut brush, surf, pts.first(), fg, s.tools.background); diff --git a/crates/engine/src/cmd/color_cmds.rs b/crates/engine/src/cmd/color_cmds.rs index c7c7942d0bf..183e085a8eb 100644 --- a/crates/engine/src/cmd/color_cmds.rs +++ b/crates/engine/src/cmd/color_cmds.rs @@ -560,6 +560,28 @@ pub fn document_profile(doc: &Document) -> Arc { .unwrap_or_else(|| working_profile(doc.mode)) } +/// A swatch colour (straight RGB in the RGB working space, as the foreground and background hold +/// it) as the active document takes it. In a Grayscale document that is the colour's gray in the +/// document's gray profile, through `photocraft-cms` (relative colorimetric with black point +/// compensation, Photoshop's default), returned as equal R, G and B so the pixel conversion keeps +/// it: RGB 0,200,0 becomes gray 153 with the default Dot Gain 20%-compatible profile, not its +/// Rec.601 luma 117 (#11940; the reference measures 173, an open question on the issue). Other +/// modes, and a failed conversion, keep the colour. +pub fn swatch_in_doc(s: &Session, c: [f32; 4]) -> [f32; 4] { + let Some(st) = s.active().filter(|st| st.doc.mode == ColorMode::Grayscale) else { return c }; + let opts = photocraft_cms::TransformOptions { intent: Intent::RelativeColorimetric, bpc: true, ..Default::default() }; + let Ok(t) = photocraft_cms::cached(&working_profile(ColorMode::Rgb), &document_profile(&st.doc), opts) else { return c }; + let mut out = [0.0f32; 16]; + t.eval(&[c[0], c[1], c[2]], &mut out); + let g = out[0]; + if g.is_finite() { + let g = g.clamp(0.0, 1.0); + [g, g, g, c[3]] + } else { + c + } +} + /// Profile describing the compositor's RGB output for this document (see the module docs). pub fn composite_profile(doc: &Document) -> Arc { match mode_space(doc.mode) { diff --git a/crates/engine/src/cmd/fill_cmds.rs b/crates/engine/src/cmd/fill_cmds.rs index e6f7e77b9d0..988a5b4aadc 100644 --- a/crates/engine/src/cmd/fill_cmds.rs +++ b/crates/engine/src/cmd/fill_cmds.rs @@ -106,7 +106,8 @@ pub fn fill(s: &mut Session, p: &Value) -> Result { let restore = contents == "history"; let source = match contents { "foreground" => color_source(s, s.tools.foreground), - "background" => color_source(s, s.tools.background), + // As the document takes the swatch: its gray profile's value in a Grayscale document (#11940). + "background" => color_source(s, crate::color_cmds::swatch_in_doc(s, s.tools.background)), "color" => color_source(s, color_param(CMD, p, "color", s.tools.foreground)?), "black" => Source::Color([0.0, 0.0, 0.0, 1.0]), "gray" => Source::Color([128.0 / 255.0, 128.0 / 255.0, 128.0 / 255.0, 1.0]), diff --git a/crates/engine/src/eraser_gray_background_tests.rs b/crates/engine/src/eraser_gray_background_tests.rs new file mode 100644 index 00000000000..e61aa18d084 --- /dev/null +++ b/crates/engine/src/eraser_gray_background_tests.rs @@ -0,0 +1,68 @@ +//! On a Grayscale document's Background, the Eraser and Edit › Fill with the background colour +//! paint that colour's grey as the reference converts it: RGB 0, 200, 0 gives 173, not its 117 +//! luminance (#11940). Converting through the document's grey profile gives 153, so the two +//! Grayscale tests are ignored until the issue says which conversion the swatch uses. + +use crate::Session; +use serde_json::json; + +const GREEN_200: [f32; 4] = [0.0, 200.0 / 255.0, 0.0, 1.0]; + +fn session(mode: &str) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 64, "height": 32, "mode": mode, "depth": 8, "background": "white"})).unwrap(); + s.tools.background = GREEN_200; + s +} + +fn pixel(s: &mut Session, x: i32, y: i32) -> [f32; 4] { + let v = s.execute("document.pixel", json!({"x": x, "y": y})).unwrap(); + let a: Vec = v.as_array().unwrap().iter().map(|c| c.as_f64().unwrap() as f32).collect(); + [a[0], a[1], a[2], a[3]] +} + +fn level(c: f32) -> i32 { + (c * 255.0).round() as i32 +} + +fn erase_at(s: &mut Session, x: i32, y: i32) { + s.execute("paint.stroke", json!({"points": [[x, y]], "size": 9, "hardness": 1.0, "erase": true})).unwrap(); +} + +#[test] +#[ignore = "#11940: the grey profile gives 153 for RGB 0,200,0; the issue measures 173. Waiting on which conversion the swatch should use"] +fn the_eraser_on_a_gray_background_paints_the_background_colours_gray() { + let mut s = session("grayscale"); + erase_at(&mut s, 20, 16); + let p = pixel(&mut s, 20, 16); + assert!((level(p[0]) - 173).abs() <= 2, "erased pixel {p:?}"); + assert_eq!(level(p[0]), level(p[1])); + assert_eq!(level(p[0]), level(p[2])); + assert_eq!(level(pixel(&mut s, 50, 16)[0]), 255, "pixels away from the click stay white"); +} + +#[test] +#[ignore = "#11940: the grey profile gives 153 for RGB 0,200,0; the issue measures 173. Waiting on which conversion the swatch should use"] +fn edit_fill_with_the_background_colour_gives_the_same_gray() { + let mut s = session("grayscale"); + s.execute("edit.fill", json!({"contents": "background"})).unwrap(); + let filled = pixel(&mut s, 5, 5); + assert!((level(filled[0]) - 173).abs() <= 2, "filled pixel {filled:?}"); + + let mut e = session("grayscale"); + erase_at(&mut e, 20, 16); + assert_eq!(level(pixel(&mut e, 20, 16)[0]), level(filled[0]), "the Eraser and Edit › Fill agree"); +} + +#[test] +fn rgb_documents_keep_the_background_colour_as_it_is() { + let mut s = session("rgb"); + erase_at(&mut s, 20, 16); + let p = pixel(&mut s, 20, 16); + assert_eq!([level(p[0]), level(p[1]), level(p[2])], [0, 200, 0], "erased pixel {p:?}"); + + let mut f = session("rgb"); + f.execute("edit.fill", json!({"contents": "background"})).unwrap(); + let q = pixel(&mut f, 5, 5); + assert_eq!([level(q[0]), level(q[1]), level(q[2])], [0, 200, 0], "filled pixel {q:?}"); +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 8f281472172..f6b861d43d2 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -344,6 +344,8 @@ mod brush_pressure_size_default_tests; #[cfg(test)] mod embed_all_linked_tests; #[cfg(test)] +mod eraser_gray_background_tests; +#[cfg(test)] mod fill_layer_mode_tests; #[cfg(test)] mod pattern_mode_tests; From 7b20000052caf10e93f6e956e3776296809bd079 Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Tue, 10 Nov 2026 08:37:07 -0600 Subject: [PATCH 21/42] Grayscale swatch through sGray, as agreed on the PR (#11940) The reference's Eraser paints 173 for background RGB 0,200,0 in a Grayscale document; the document's Dot Gain curve gives 153, so swatch_in_doc now converts through the sRGB tone curve (sGray, 172-173) instead. Pixel conversions keep the document's profile. The two Grayscale tests are no longer ignored, and eraser_locked's Gray case checks the sGray value, since the Brush's own conversion into Gray (not measured) is unchanged. --- crates/engine/src/cmd/color_cmds.rs | 18 +++++++++++------- .../engine/src/eraser_gray_background_tests.rs | 6 ++---- crates/engine/tests/it/eraser_locked.rs | 17 ++++++++++++----- 3 files changed, 25 insertions(+), 16 deletions(-) diff --git a/crates/engine/src/cmd/color_cmds.rs b/crates/engine/src/cmd/color_cmds.rs index 183e085a8eb..c7de505e665 100644 --- a/crates/engine/src/cmd/color_cmds.rs +++ b/crates/engine/src/cmd/color_cmds.rs @@ -561,16 +561,20 @@ pub fn document_profile(doc: &Document) -> Arc { } /// A swatch colour (straight RGB in the RGB working space, as the foreground and background hold -/// it) as the active document takes it. In a Grayscale document that is the colour's gray in the -/// document's gray profile, through `photocraft-cms` (relative colorimetric with black point -/// compensation, Photoshop's default), returned as equal R, G and B so the pixel conversion keeps -/// it: RGB 0,200,0 becomes gray 153 with the default Dot Gain 20%-compatible profile, not its -/// Rec.601 luma 117 (#11940; the reference measures 173, an open question on the issue). Other +/// it) as the active document takes it. In a Grayscale document that is the colour's gray with the +/// sRGB tone curve (sGray), through `photocraft-cms` (relative colorimetric with black point +/// compensation), returned as equal R, G and B so the pixel conversion keeps it: RGB 0,200,0 +/// becomes gray 172, as the reference paints it (173, measured), not its Rec.601 luma 117 (#11940). +/// The reference's swatch conversion doesn't follow the document's Dot Gain curve (that gives 153), +/// so pixel conversions such as Image › Mode › Grayscale keep using the document's profile. Other /// modes, and a failed conversion, keep the colour. pub fn swatch_in_doc(s: &Session, c: [f32; 4]) -> [f32; 4] { - let Some(st) = s.active().filter(|st| st.doc.mode == ColorMode::Grayscale) else { return c }; + if s.active().is_none_or(|st| st.doc.mode != ColorMode::Grayscale) { + return c; + } let opts = photocraft_cms::TransformOptions { intent: Intent::RelativeColorimetric, bpc: true, ..Default::default() }; - let Ok(t) = photocraft_cms::cached(&working_profile(ColorMode::Rgb), &document_profile(&st.doc), opts) else { return c }; + let sgray = Arc::new(Builtin::SGray.profile().clone()); + let Ok(t) = photocraft_cms::cached(&working_profile(ColorMode::Rgb), &sgray, opts) else { return c }; let mut out = [0.0f32; 16]; t.eval(&[c[0], c[1], c[2]], &mut out); let g = out[0]; diff --git a/crates/engine/src/eraser_gray_background_tests.rs b/crates/engine/src/eraser_gray_background_tests.rs index e61aa18d084..15867aa0cf6 100644 --- a/crates/engine/src/eraser_gray_background_tests.rs +++ b/crates/engine/src/eraser_gray_background_tests.rs @@ -1,7 +1,7 @@ //! On a Grayscale document's Background, the Eraser and Edit › Fill with the background colour //! paint that colour's grey as the reference converts it: RGB 0, 200, 0 gives 173, not its 117 -//! luminance (#11940). Converting through the document's grey profile gives 153, so the two -//! Grayscale tests are ignored until the issue says which conversion the swatch uses. +//! luminance (#11940). The swatch goes through the sRGB tone curve (sGray), not the document's Dot +//! Gain curve, which would give 153. use crate::Session; use serde_json::json; @@ -30,7 +30,6 @@ fn erase_at(s: &mut Session, x: i32, y: i32) { } #[test] -#[ignore = "#11940: the grey profile gives 153 for RGB 0,200,0; the issue measures 173. Waiting on which conversion the swatch should use"] fn the_eraser_on_a_gray_background_paints_the_background_colours_gray() { let mut s = session("grayscale"); erase_at(&mut s, 20, 16); @@ -42,7 +41,6 @@ fn the_eraser_on_a_gray_background_paints_the_background_colours_gray() { } #[test] -#[ignore = "#11940: the grey profile gives 153 for RGB 0,200,0; the issue measures 173. Waiting on which conversion the swatch should use"] fn edit_fill_with_the_background_colour_gives_the_same_gray() { let mut s = session("grayscale"); s.execute("edit.fill", json!({"contents": "background"})).unwrap(); diff --git a/crates/engine/tests/it/eraser_locked.rs b/crates/engine/tests/it/eraser_locked.rs index d7405a73115..8f82ab2ac68 100644 --- a/crates/engine/tests/it/eraser_locked.rs +++ b/crates/engine/tests/it/eraser_locked.rs @@ -43,11 +43,18 @@ fn eraser_on_background_paints_background_colour_at_every_depth_and_mode() { erase(&mut s, json!({})).unwrap_or_else(|e| panic!("{mode}/{depth}: {e}")); let got = layer_px(&s, 20, 10); assert_eq!(got[3], 1.0, "{mode}/{depth}: the Background stays opaque"); - // Exactly what the Brush paints with the background colour (CMYK and Gray documents - // hold the colour converted into their mode). - let mut brush = doc(mode, depth); - brush.execute("paint.stroke", json!({"points": [[2, 10], [38, 10]], "size": 8, "hardness": 1.0, "color": "#ff0000"})).unwrap(); - assert!(close(got, layer_px(&brush, 20, 10)), "{mode}/{depth}: got {got:?}"); + if mode == "gray" { + // A Gray document takes the background swatch through the sRGB tone curve, as the + // reference's Eraser paints it (#11940): pure red is grey 130. The Brush's own + // conversion of a colour into Gray was not measured and stays as it was. + assert!(close(got, [0.51, 0.51, 0.51, 1.0]), "{mode}/{depth}: got {got:?}"); + } else { + // Exactly what the Brush paints with the background colour (CMYK documents hold + // the colour converted into their mode). + let mut brush = doc(mode, depth); + brush.execute("paint.stroke", json!({"points": [[2, 10], [38, 10]], "size": 8, "hardness": 1.0, "color": "#ff0000"})).unwrap(); + assert!(close(got, layer_px(&brush, 20, 10)), "{mode}/{depth}: got {got:?}"); + } assert!(!close(got, before), "{mode}/{depth}: the stroke shows"); if mode == "rgb" { assert!(close(got, [1.0, 0.0, 0.0, 1.0]), "{mode}/{depth}: got {got:?}"); From 5300f6889d5b7845161549ded4ccfefa7391d0d9 Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Tue, 10 Nov 2026 08:59:43 -0600 Subject: [PATCH 22/42] Live Pencil Auto Erase: use the converted background in Grayscale documents (CodeRabbit #12908) LiveStroke::begin_with passed the raw background swatch to apply_auto_erase while stroke_with passes the swatch converted for the document, so in a Grayscale document a live Pencil Auto Erase stroke painted the luma grey and the commit took those pixels over the sGray one. Both paths now use swatch_in_doc. --- crates/engine/src/cmd/brush_cmds.rs | 5 ++-- .../src/eraser_gray_background_tests.rs | 27 +++++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/brush_cmds.rs b/crates/engine/src/cmd/brush_cmds.rs index 55b9be3a7a2..251ef0d3cc7 100644 --- a/crates/engine/src/cmd/brush_cmds.rs +++ b/crates/engine/src/cmd/brush_cmds.rs @@ -615,10 +615,11 @@ impl LiveStroke { let sel = doc.selection.clone(); let table = crate::mode_cmds::paint_color_table(&doc, p); let (surf, lock) = crate::channel_cmds::target_surface(&mut doc, layer, p)?; - erase_locked(&mut brush, lock, crate::color_cmds::swatch_in_doc(s, s.tools.background)); + let bg = crate::color_cmds::swatch_in_doc(s, s.tools.background); + erase_locked(&mut brush, lock, bg); if pencil && flag(p, "autoErase", false) { let fg = table.as_ref().map_or(fg, |t| crate::mode_cmds::table_color(t, fg)); - apply_auto_erase(&mut brush, surf, pts.first(), fg, s.tools.background); + apply_auto_erase(&mut brush, surf, pts.first(), fg, bg); } let renderer = StrokeRenderer::new(&brush, Some(surf.format()), zoom); let symmetry = s.active().and_then(|st| st.symmetry.clone()); diff --git a/crates/engine/src/eraser_gray_background_tests.rs b/crates/engine/src/eraser_gray_background_tests.rs index 15867aa0cf6..b309379647d 100644 --- a/crates/engine/src/eraser_gray_background_tests.rs +++ b/crates/engine/src/eraser_gray_background_tests.rs @@ -64,3 +64,30 @@ fn rgb_documents_keep_the_background_colour_as_it_is() { let q = pixel(&mut f, 5, 5); assert_eq!([level(q[0]), level(q[1]), level(q[2])], [0, 200, 0], "filled pixel {q:?}"); } + +fn pencil_auto_erase_params() -> serde_json::Value { + json!({"points": [[20, 16]], "size": 5, "autoErase": true, "seed": 7}) +} + +#[test] +fn live_pencil_auto_erase_paints_the_converted_background_in_a_gray_document() { + // A stroke that starts on a pixel of the foreground colour (white, on the white Background) + // paints the background colour's gray. The stroke the canvas renders live and the one the + // commit renders must agree on it (CodeRabbit on #12908). + let mut reference = session("grayscale"); + reference.tools.foreground = [1.0, 1.0, 1.0, 1.0]; + reference.execute("paint.pencil", pencil_auto_erase_params()).unwrap(); + let expected = pixel(&mut reference, 20, 16); + assert!((level(expected[0]) - 173).abs() <= 2, "committed pixel {expected:?}"); + + let mut s = session("grayscale"); + s.tools.foreground = [1.0, 1.0, 1.0, 1.0]; + let mut p = pencil_auto_erase_params(); + let live = crate::brush_cmds::LiveStroke::begin_with(&s, "paint.pencil", &p).unwrap(); + p["seed"] = json!(live.seed); + s.offer_live_stroke(live).unwrap(); + let result = s.execute("paint.pencil", p).unwrap(); + assert_eq!(result["fromLive"], true, "the commit took the live pixels"); + let got = pixel(&mut s, 20, 16); + assert_eq!(level(got[0]), level(expected[0]), "live pixel {got:?}, committed {expected:?}"); +} From d677b5893eee6833545399b9d9acc51d1579b585 Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Tue, 10 Nov 2026 09:16:27 -0600 Subject: [PATCH 23/42] Pencil Auto Erase keeps the raw background: #11940 does not cover it (CodeRabbit #12908) #11940 lists only the lines that take the background for an erase (the brush background field, stroke_target's gray-target erase, erase_locked). Pencil Auto Erase is not among them and the foreground-colour cases are not measured, so it keeps the plain background in the committed and the live path alike, as on main. erase_locked keeps the converted swatch. --- crates/engine/src/cmd/brush_cmds.rs | 8 +++++--- crates/engine/src/eraser_gray_background_tests.rs | 10 +++++----- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/brush_cmds.rs b/crates/engine/src/cmd/brush_cmds.rs index 251ef0d3cc7..6d510f0e06f 100644 --- a/crates/engine/src/cmd/brush_cmds.rs +++ b/crates/engine/src/cmd/brush_cmds.rs @@ -272,7 +272,8 @@ pub(crate) fn doc_cmyk_space(s: &Session) -> Option, auto_erase: bool) -> Result { - let bg = crate::color_cmds::swatch_in_doc(s, s.tools.background); + let raw_bg = s.tools.background; + let bg = crate::color_cmds::swatch_in_doc(s, raw_bg); let fg = brush.color; let symmetry = s.active().and_then(|st| st.symmetry.clone()); let (id, brush, zoom) = stroke_target(s, p, brush)?; @@ -296,7 +297,8 @@ fn stroke_with(s: &mut Session, cmd: &str, p: &Value, label: &str, brush: BrushS if auto_erase { // A stroke in the table's colour starts on what the foreground painted as. let fg = table.as_ref().map_or(fg, |t| crate::mode_cmds::table_color(t, fg)); - apply_auto_erase(&mut brush, surf, pts.first(), fg, bg); + // Not in #11940: Pencil Auto Erase keeps the plain background colour. + apply_auto_erase(&mut brush, surf, pts.first(), fg, raw_bg); } let unpainted = table.as_ref().map(|_| surf.clone()); let damage = if let Some(axis) = &symmetry { @@ -619,7 +621,7 @@ impl LiveStroke { erase_locked(&mut brush, lock, bg); if pencil && flag(p, "autoErase", false) { let fg = table.as_ref().map_or(fg, |t| crate::mode_cmds::table_color(t, fg)); - apply_auto_erase(&mut brush, surf, pts.first(), fg, bg); + apply_auto_erase(&mut brush, surf, pts.first(), fg, s.tools.background); } let renderer = StrokeRenderer::new(&brush, Some(surf.format()), zoom); let symmetry = s.active().and_then(|st| st.symmetry.clone()); diff --git a/crates/engine/src/eraser_gray_background_tests.rs b/crates/engine/src/eraser_gray_background_tests.rs index b309379647d..91686fc48bb 100644 --- a/crates/engine/src/eraser_gray_background_tests.rs +++ b/crates/engine/src/eraser_gray_background_tests.rs @@ -70,15 +70,15 @@ fn pencil_auto_erase_params() -> serde_json::Value { } #[test] -fn live_pencil_auto_erase_paints_the_converted_background_in_a_gray_document() { - // A stroke that starts on a pixel of the foreground colour (white, on the white Background) - // paints the background colour's gray. The stroke the canvas renders live and the one the - // commit renders must agree on it (CodeRabbit on #12908). +fn pencil_auto_erase_keeps_the_raw_background_live_and_committed() { + // #11940 lists the Eraser's and Edit › Fill's background lines; Pencil Auto Erase paints the + // foreground-colour pixel with the plain background colour as before (the luma grey, about + // 117 for RGB 0, 200, 0), in the committed stroke and in the live one the canvas shows. let mut reference = session("grayscale"); reference.tools.foreground = [1.0, 1.0, 1.0, 1.0]; reference.execute("paint.pencil", pencil_auto_erase_params()).unwrap(); let expected = pixel(&mut reference, 20, 16); - assert!((level(expected[0]) - 173).abs() <= 2, "committed pixel {expected:?}"); + assert!((level(expected[0]) - 117).abs() <= 2, "committed pixel {expected:?}"); let mut s = session("grayscale"); s.tools.foreground = [1.0, 1.0, 1.0, 1.0]; From c9d127fc9fe67f86038500611bb8f53617a3bcd3 Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Tue, 10 Nov 2026 09:31:55 -0600 Subject: [PATCH 24/42] Grayscale swatch conversion only in the default gray working space (CodeRabbit #12908) #11940 measured the default Working Gray (Dot Gain 20 %) only and says the other gray working spaces keep today's behaviour. swatch_in_doc now converts through sGray only when Working Gray is the default and the document's gray profile is that default (untagged, or tagged with it); otherwise it keeps the colour, so the Eraser and Edit > Fill paint the plain luma as on main. --- crates/engine/src/cmd/color_cmds.rs | 8 +++- .../src/eraser_gray_background_tests.rs | 39 +++++++++++++++++++ 2 files changed, 45 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/color_cmds.rs b/crates/engine/src/cmd/color_cmds.rs index c7de505e665..57612ee3bfe 100644 --- a/crates/engine/src/cmd/color_cmds.rs +++ b/crates/engine/src/cmd/color_cmds.rs @@ -567,9 +567,13 @@ pub fn document_profile(doc: &Document) -> Arc { /// becomes gray 172, as the reference paints it (173, measured), not its Rec.601 luma 117 (#11940). /// The reference's swatch conversion doesn't follow the document's Dot Gain curve (that gives 153), /// so pixel conversions such as Image › Mode › Grayscale keep using the document's profile. Other -/// modes, and a failed conversion, keep the colour. +/// modes, and a failed conversion, keep the colour. So do Grayscale documents outside the default +/// gray working space, which #11940 did not measure: a Working Gray other than Dot Gain 20 %, or a +/// document tagged with a gray profile other than that one. pub fn swatch_in_doc(s: &Session, c: [f32; 4]) -> [f32; 4] { - if s.active().is_none_or(|st| st.doc.mode != ColorMode::Grayscale) { + let Some(st) = s.active().filter(|st| st.doc.mode == ColorMode::Grayscale) else { return c }; + let default_gray = Builtin::DotGain20Compat; + if s.color.settings.working_gray != default_gray.id() || document_profile(&st.doc).content_hash() != default_gray.profile().content_hash() { return c; } let opts = photocraft_cms::TransformOptions { intent: Intent::RelativeColorimetric, bpc: true, ..Default::default() }; diff --git a/crates/engine/src/eraser_gray_background_tests.rs b/crates/engine/src/eraser_gray_background_tests.rs index 91686fc48bb..31759f244ac 100644 --- a/crates/engine/src/eraser_gray_background_tests.rs +++ b/crates/engine/src/eraser_gray_background_tests.rs @@ -91,3 +91,42 @@ fn pencil_auto_erase_keeps_the_raw_background_live_and_committed() { let got = pixel(&mut s, 20, 16); assert_eq!(level(got[0]), level(expected[0]), "live pixel {got:?}, committed {expected:?}"); } + +fn assert_erase_and_fill_give_luma(mut s: Session, what: &str) { + erase_at(&mut s, 20, 16); + let erased = pixel(&mut s, 20, 16); + assert!((level(erased[0]) - 117).abs() <= 1, "{what}: erased pixel {erased:?}"); + s.execute("edit.fill", json!({"contents": "background"})).unwrap(); + let filled = pixel(&mut s, 5, 5); + assert!((level(filled[0]) - 117).abs() <= 1, "{what}: filled pixel {filled:?}"); +} + +#[test] +fn other_gray_working_spaces_keep_the_plain_luma() { + // #11940 measured the default Working Gray only; the others keep today's behaviour. + for space in ["sgray", "gray-gamma-2.2"] { + let mut s = session("grayscale"); + s.execute("edit.colorSettings", json!({"workingGray": space})).unwrap(); + assert_erase_and_fill_give_luma(s, &format!("workingGray {space}")); + } +} + +#[test] +fn a_gray_document_tagged_with_another_profile_keeps_the_plain_luma() { + for profile in ["sgray", "gray-gamma-2.2"] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 64, "height": 32, "mode": "grayscale", "depth": 8, "background": "white", "profile": profile})).unwrap(); + s.tools.background = GREEN_200; + assert_erase_and_fill_give_luma(s, &format!("document profile {profile}")); + } +} + +#[test] +fn a_gray_document_tagged_with_the_default_profile_still_gets_the_measured_gray() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 64, "height": 32, "mode": "grayscale", "depth": 8, "background": "white", "profile": "dot-gain-20-compat"})).unwrap(); + s.tools.background = GREEN_200; + erase_at(&mut s, 20, 16); + let p = pixel(&mut s, 20, 16); + assert!((level(p[0]) - 173).abs() <= 2, "erased pixel {p:?}"); +} From 118cb2c88ff50ac50999e0314d4fa4d945bb30de Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Tue, 10 Nov 2026 09:32:41 -0600 Subject: [PATCH 25/42] Test the live Eraser on a Grayscale Background (CodeRabbit #12908) A live paint.stroke with erase, offered and committed, paints the same gray (173 +/- 2) as the direct stroke. It passes without a code change: begin_with already gives erase_locked the converted background. --- .../src/eraser_gray_background_tests.rs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/crates/engine/src/eraser_gray_background_tests.rs b/crates/engine/src/eraser_gray_background_tests.rs index 31759f244ac..33ae4915c85 100644 --- a/crates/engine/src/eraser_gray_background_tests.rs +++ b/crates/engine/src/eraser_gray_background_tests.rs @@ -130,3 +130,22 @@ fn a_gray_document_tagged_with_the_default_profile_still_gets_the_measured_gray( let p = pixel(&mut s, 20, 16); assert!((level(p[0]) - 173).abs() <= 2, "erased pixel {p:?}"); } + +#[test] +fn the_live_eraser_on_a_gray_background_matches_the_committed_stroke() { + let mut direct = session("grayscale"); + erase_at(&mut direct, 20, 16); + let expected = pixel(&mut direct, 20, 16); + assert!((level(expected[0]) - 173).abs() <= 2, "committed pixel {expected:?}"); + + let mut s = session("grayscale"); + let mut p = json!({"points": [[20, 16]], "size": 9, "hardness": 1.0, "erase": true, "seed": 7}); + let live = crate::brush_cmds::LiveStroke::begin_with(&s, "paint.stroke", &p).unwrap(); + p["seed"] = json!(live.seed); + s.offer_live_stroke(live).unwrap(); + let result = s.execute("paint.stroke", p).unwrap(); + assert_eq!(result["fromLive"], true, "the commit took the live pixels"); + let got = pixel(&mut s, 20, 16); + assert!((level(got[0]) - 173).abs() <= 2, "live pixel {got:?}"); + assert_eq!(level(got[0]), level(expected[0]), "live pixel {got:?}, committed {expected:?}"); +} From 56d12096d651905a61580c6e248847bf47ad90db Mon Sep 17 00:00:00 2001 From: rmsff <17902130+rmsff@users.noreply.github.com> Date: Tue, 10 Nov 2026 19:13:29 +0300 Subject: [PATCH 26/42] History Brush: refuse a source of another colour mode or bit depth MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit After Image › Mode, Photoshop refuses to paint from an older state in the two cases measured for this tool: RGB to Grayscale ("Could not use the history brush because the current color mode does not match that of the history state.") and a bit depth change ("...the current bit depth does not match that of the history state."). Refuse the same way, after the canvas size check, in history_source so the live stroke preview refuses too. Every other change (RGB to CMYK, Lab or Indexed, a non-RGB source, the mode and the depth at once) was not measured and keeps today's behaviour, as do the Eraser's Erase to History, the Art History Brush and Fill › History (#12842). --- crates/engine/src/cmd/history_source_cmds.rs | 17 ++++++++++++++++- crates/engine/src/cmd/retouch_cmds/heal.rs | 8 +++++++- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/history_source_cmds.rs b/crates/engine/src/cmd/history_source_cmds.rs index c42b69b3d8e..453627d96a2 100644 --- a/crates/engine/src/cmd/history_source_cmds.rs +++ b/crates/engine/src/cmd/history_source_cmds.rs @@ -19,7 +19,7 @@ use std::sync::Arc; -use photocraft_doc::Document; +use photocraft_doc::{ColorMode, Document}; use serde_json::{Value, json}; use crate::commands::CommandSpec; @@ -101,6 +101,21 @@ pub(crate) fn paint_source(st: &DocState, p: &Value, cmd: &str) -> Result Result<()> { + let (mode_differs, depth_differs) = (source.mode != st.doc.mode, source.depth != st.doc.depth); + if source.mode == ColorMode::Rgb && st.doc.mode == ColorMode::Grayscale && !depth_differs { + return Err(EngineError::Other("Could not use the history brush because the current color mode does not match that of the history state.".into())); + } + if depth_differs && !mode_differs { + return Err(EngineError::Other("Could not use the history brush because the current bit depth does not match that of the history state.".into())); + } + Ok(()) +} + /// `history.setSource {state}` or `{snapshot}`: make a History panel row or a snapshot the History /// Brush's source. fn set_source(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/retouch_cmds/heal.rs b/crates/engine/src/cmd/retouch_cmds/heal.rs index af56f496c78..ca7a44328e3 100644 --- a/crates/engine/src/cmd/retouch_cmds/heal.rs +++ b/crates/engine/src/cmd/retouch_cmds/heal.rs @@ -95,6 +95,11 @@ pub(super) fn healing_brush(s: &mut Session, p: &Value) -> Result { pub(super) fn history_source(s: &Session, id: Option, p: &Value, cmd: &str) -> Result { let st = s.active().ok_or(EngineError::NoDocument)?; let source_doc = crate::history_source_cmds::paint_source(st, p, cmd)?; + // Here, so the live preview refuses too. Only the History Brush: the Art History Brush and + // Erase to History were not measured and keep converting. + if cmd == "paint.historyBrush" && !flag(p, "eraseToHistory", false) { + crate::history_source_cmds::refuse_other_format(st, &source_doc)?; + } let missing = || EngineError::Other("the target did not exist (as pixels, a mask or a channel) in that history state".into()); match crate::channel_cmds::read_target_surface(source_doc.as_ref(), id, p) { Ok(surf) => Ok(surf.clone()), @@ -136,8 +141,9 @@ pub(super) fn history_brush(s: &mut Session, p: &Value) -> Result { reject_huge_stroke(CMD, &stroke)?; let live = s.live_commit.take().filter(|l| l.matches(s, CMD, p, &stroke.points)); let from_live = live.is_some(); + let erase = flag(p, "eraseToHistory", false); let src_surface = history_source(s, id, p, CMD)?; - let label = if flag(p, "eraseToHistory", false) { "History Eraser" } else { "History Brush" }; + let label = if erase { "History Eraser" } else { "History Brush" }; let dmg = run_stroke(s, label, id, p, |_, surf, sel, lock| { if let Some(l) = live { *surf = l.surface; From 56d14fdf63dc269f7a6dce8b74e2745b22448b69 Mon Sep 17 00:00:00 2001 From: rmsff <17902130+rmsff@users.noreply.github.com> Date: Tue, 10 Nov 2026 19:13:29 +0300 Subject: [PATCH 27/42] Test the History Brush colour mode and bit depth refusals --- .../history_brush_format_mismatch_tests.rs | 158 ++++++++++++++++++ crates/engine/src/cmd/history_source_cmds.rs | 4 + 2 files changed, 162 insertions(+) create mode 100644 crates/engine/src/cmd/history_brush_format_mismatch_tests.rs diff --git a/crates/engine/src/cmd/history_brush_format_mismatch_tests.rs b/crates/engine/src/cmd/history_brush_format_mismatch_tests.rs new file mode 100644 index 00000000000..55f4d6cce11 --- /dev/null +++ b/crates/engine/src/cmd/history_brush_format_mismatch_tests.rs @@ -0,0 +1,158 @@ +//! The History Brush refuses a source state from before Image › Mode changed RGB to Grayscale, or +//! changed only the bit depth, with Photoshop's alert texts, adding no state and changing no pixel. +//! The pairs not measured convert the source as before (#12842). + +use serde_json::{Value, json}; + +use crate::Session; +use crate::retouch_cmds::LiveRetouch; + +const MODE: &str = "Could not use the history brush because the current color mode does not match that of the history state."; +const DEPTH: &str = "Could not use the history brush because the current bit depth does not match that of the history state."; + +/// Rows Open (white), Fill (red): row 1 is the red state. +fn session(mode: &str, depth: u64) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 24, "height": 16, "mode": mode, "depth": depth, "background": "white"})).unwrap(); + s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + s +} + +fn steps(s: &Session) -> usize { + s.active().unwrap().history.past_len() +} + +/// A History Brush stroke from row 1 with `extra` merged in (`"state": null` for the default source). +fn params(extra: Value) -> Value { + let mut p = json!({"points": [[4, 8], [20, 8]], "size": 6, "hardness": 100, "state": 1}); + if let (Some(p), Some(e)) = (p.as_object_mut(), extra.as_object()) { + p.extend(e.clone()); + } + p +} + +/// The History Brush's error, after checking it added no state and changed no pixel. +fn refused(s: &mut Session, extra: Value, case: &str) -> String { + let (before, n) = (s.active().unwrap().doc.clone(), steps(s)); + let e = s.execute("paint.historyBrush", params(extra)).expect_err(case).to_string(); + assert_eq!(steps(s), n, "{case}: no state"); + assert!(s.active().unwrap().doc == before, "{case}: no pixel changed"); + e +} + +/// The History Brush stroke paints and adds one state. +fn paints(s: &mut Session, extra: Value, case: &str) { + let n = steps(s); + let r = s.execute("paint.historyBrush", params(extra)).unwrap_or_else(|e| panic!("{case}: {e}")); + assert!(!r["damage"].is_null(), "{case}: {r}"); + assert_eq!(steps(s), n + 1, "{case}"); +} + +#[test] +fn rgb_to_grayscale_is_refused() { + for depth in [8u64, 16] { + for state in [json!(1), Value::Null] { + let mut s = session("rgb", depth); + s.execute("image.mode.grayscale", json!({})).unwrap(); + let case = format!("depth {depth} state {state}"); + assert_eq!(refused(&mut s, json!({"state": state}), &case), MODE, "{case}"); + } + } + let mut s = session("rgb", 8); + let snap = s.execute("history.newSnapshot", json!({})).unwrap()["snapshot"].clone(); + s.execute("image.mode.grayscale", json!({})).unwrap(); + assert_eq!(refused(&mut s, json!({"state": null, "snapshot": snap}), "snapshot"), MODE); +} + +#[test] +fn a_source_of_another_bit_depth_is_refused() { + let cases = [("rgb", 8u64, "image.mode.bits16"), ("rgb", 16, "image.mode.bits32"), ("rgb", 16, "image.mode.bits8"), ("rgb", 32, "image.mode.bits16")]; + for (mode, depth, bits) in cases.into_iter().chain([("gray", 8, "image.mode.bits16")]) { + for state in [json!(1), Value::Null] { + let mut s = session(mode, depth); + s.execute(bits, json!({})).unwrap(); + let case = format!("{mode} {depth} {bits} state {state}"); + assert_eq!(refused(&mut s, json!({"state": state}), &case), DEPTH, "{case}"); + } + } +} + +/// Not measured, so these keep today's behaviour: RGB to CMYK or Lab, and a change of both the +/// colour mode and the bit depth, convert the source; Indexed Color flattens the document, so the +/// source lacks the new layer, as before. +#[test] +fn unmeasured_mode_pairs_keep_converting() { + for mode in ["image.mode.cmyk", "image.mode.lab"] { + let mut s = session("rgb", 8); + s.execute(mode, json!({})).unwrap(); + paints(&mut s, json!({}), mode); + } + let mut s = session("rgb", 8); + s.execute("image.mode.indexedColor", json!({})).unwrap(); + assert!(refused(&mut s, json!({}), "indexed").starts_with("the target did not exist")); + let mut s = session("rgb", 8); + s.execute("image.mode.bits16", json!({})).unwrap(); + s.execute("image.mode.grayscale", json!({})).unwrap(); + paints(&mut s, json!({}), "mode and depth"); +} + +#[test] +fn the_canvas_size_refusal_comes_first() { + let mut s = session("rgb", 8); + s.execute("image.mode.grayscale", json!({})).unwrap(); + s.execute("image.canvasSize", json!({"width": 30, "height": 16, "anchor": "topLeft"})).unwrap(); + assert!(refused(&mut s, json!({}), "size and mode").contains("canvas size")); +} + +/// As in Photoshop, a document converted before the source state was taken paints as before: +/// the source and the document are in the same mode and depth. +#[test] +fn a_source_of_the_same_mode_and_depth_still_paints() { + for depth in [8u64, 16, 32] { + for mode in ["rgb", "gray", "cmyk", "lab"] { + let mut s = session(mode, depth); + s.execute("edit.fill", json!({"color": "#ffffff"})).unwrap(); + let before = s.active().unwrap().doc.clone(); + paints(&mut s, json!({}), &format!("depth {depth} {mode}")); + assert!(s.active().unwrap().doc != before, "depth {depth} {mode}: the red state painted"); + } + } + let mut s = session("rgb", 8); + s.execute("image.mode.bits16", json!({})).unwrap(); + s.execute("image.mode.grayscale", json!({})).unwrap(); + let row = s.active().unwrap().history.entries().len() - 1; + s.execute("edit.fill", json!({"color": "#ffffff"})).unwrap(); + paints(&mut s, json!({"state": row}), "converted before the source state"); +} + +/// The live stroke refuses the same way, so its preview never shows a stroke the commit refuses. +#[test] +fn the_live_preview_is_refused_too() { + for (change, text) in [("image.mode.grayscale", MODE), ("image.mode.bits16", DEPTH)] { + let mut s = session("rgb", 8); + s.execute(change, json!({})).unwrap(); + let e = LiveRetouch::begin(&s, "paint.historyBrush", ¶ms(json!({}))).err().map(|e| e.to_string()); + assert_eq!(e.as_deref(), Some(text), "{change}"); + assert!(LiveRetouch::begin(&s, "paint.historyBrush", ¶ms(json!({"eraseToHistory": true}))).is_ok(), "{change}: Erase to History"); + } +} + +/// Only the History Brush refuses: the Eraser's Erase to History and Fill › History were not +/// measured and keep converting the source. +#[test] +fn other_history_painting_keeps_todays_behaviour() { + for change in ["image.mode.grayscale", "image.mode.bits16"] { + let mut s = session("rgb", 8); + s.execute(change, json!({})).unwrap(); + let n = steps(&s); + s.execute("paint.historyBrush", params(json!({"eraseToHistory": true}))).unwrap(); + s.execute("edit.fill", json!({"contents": "history", "state": 1})).unwrap(); + assert_eq!(steps(&s), n + 2, "{change}"); + // Only the absence of this tool's texts: the Art History Brush gets its own colour mode + // refusal in #12826. + if let Err(e) = s.execute("paint.artHistoryBrush", params(json!({}))) { + let e = e.to_string(); + assert!(e != MODE && e != DEPTH, "{change}: {e}"); + } + } +} diff --git a/crates/engine/src/cmd/history_source_cmds.rs b/crates/engine/src/cmd/history_source_cmds.rs index 453627d96a2..b54ebefebe0 100644 --- a/crates/engine/src/cmd/history_source_cmds.rs +++ b/crates/engine/src/cmd/history_source_cmds.rs @@ -395,3 +395,7 @@ mod tests { assert_eq!(s.execute(CMD, json!({"snapshot": 0})).unwrap()["snapshot"], 0); } } + +#[cfg(test)] +#[path = "history_brush_format_mismatch_tests.rs"] +mod history_brush_format_mismatch_tests; From 2e13877f43d95e0cfdc4d5b76a58d8796a3aa64f Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Tue, 10 Nov 2026 23:02:26 +0100 Subject: [PATCH 28/42] Sponge: the options bar has a Flow field and strokes use it (#12976) After Mode the Sponge bar shows Flow: whole numbers 1..100, default 50 %, with the "Closest value inserted" alert for a value typed past the range and a slider arrow. The canvas passes it to paint.sponge as flow, which used the command's default of 100 % before. Reset Tool puts it back to 50 %, and settings saved before the field load as 50 %. Co-Authored-By: Claude Fable 5.2 --- crates/ui-egui/src/sponge_flow_field_tests.rs | 190 ++++++++++++++++++ crates/ui-egui/src/state/tool_options.rs | 4 + crates/ui-egui/src/tools/retouch_ui.rs | 15 +- crates/ui-egui/src/tools/tool_reset.rs | 2 +- 4 files changed, 209 insertions(+), 2 deletions(-) create mode 100644 crates/ui-egui/src/sponge_flow_field_tests.rs diff --git a/crates/ui-egui/src/sponge_flow_field_tests.rs b/crates/ui-egui/src/sponge_flow_field_tests.rs new file mode 100644 index 00000000000..5853d8a85a7 --- /dev/null +++ b/crates/ui-egui/src/sponge_flow_field_tests.rs @@ -0,0 +1,190 @@ +//! #12976: the Sponge options bar has a Flow field after Mode (default 50 %, whole numbers 1..100, +//! the reference's "Closest value inserted" alert for a value typed past the range, a slider +//! arrow), Reset Tool puts it back to 50 %, and a Sponge stroke passes it to `paint.sponge` as `flow`. + +use egui::accesskit::Role; +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::eraser_ui::TOLERANCE_RANGE_ALERT; +use crate::state::{DialogKind, Tool, ToolOptions}; + +fn bar() -> Harness<'static, PhotocraftApp> { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 80, "height": 80})).unwrap(); + app.ui.tool = Tool::Sponge; + let mut h = Harness::builder().with_size(vec2(1800.0, 300.0)).build_ui_state(|ui, app| crate::panels::options_bar(app, ui), app); + PhotocraftApp::setup_context(&h.ctx, Default::default()); + h.run_steps(4); + h +} + +fn flow_field<'a>(h: &'a Harness<'static, PhotocraftApp>) -> egui_kittest::Node<'a> { + h.query_all_by_role(Role::SpinButton).find(|n| n.accesskit_node().label().as_deref() == Some("Flow:")).expect("the Flow field") +} + +/// Types `text` into Flow, then Tabs out of it. +fn type_flow(h: &mut Harness<'static, PhotocraftApp>, text: &str) { + flow_field(h).click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.event(egui::Event::Text(text.into())); + h.run_steps(1); + h.key_press(egui::Key::Tab); + h.run_steps(3); +} + +fn flow(h: &Harness<'static, PhotocraftApp>) -> f32 { + h.state().ui.tool_options.sponge_flow +} + +fn alerts(h: &Harness<'static, PhotocraftApp>) -> Vec { + h.state().ui.dialogs.iter().filter(|d| d.kind == DialogKind::Error).filter_map(|d| d.fields.get("message")?.as_str().map(str::to_owned)).collect() +} + +fn click_at(h: &mut Harness<'static, PhotocraftApp>, p: egui::Pos2) { + h.hover_at(p); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }); + h.run_steps(3); +} + +#[test] +fn the_sponge_bar_shows_flow_after_mode_at_50_percent() { + let h = bar(); + assert_eq!(ToolOptions::default().sponge_flow, 50.0, "fresh settings"); + let field = flow_field(&h); + assert_eq!(field.accesskit_node().numeric_value(), Some(50.0)); + let mode = h.query_all_by_role(Role::ComboBox).find(|n| n.accesskit_node().label().as_deref() == Some("Mode:")).expect("the Mode dropdown").rect(); + let vibrance = h.get_by_role_and_label(Role::CheckBox, "Vibrance").rect(); + let field = field.rect(); + assert!(mode.right() <= field.left(), "Flow comes after Mode: {mode:?} {field:?}"); + assert!(field.right() <= vibrance.left(), "and before Vibrance: {field:?} {vibrance:?}"); +} + +#[test] +fn settings_saved_before_the_field_load_with_flow_at_50() { + let mut saved = serde_json::to_value(ToolOptions::default()).unwrap(); + saved.as_object_mut().unwrap().remove("sponge_flow").expect("the field is saved"); + let loaded: ToolOptions = serde_json::from_value(saved).unwrap(); + assert_eq!(loaded.sponge_flow, 50.0); +} + +#[test] +fn reset_tool_puts_flow_back_to_50() { + let mut o = ToolOptions { sponge_flow: 12.0, ..Default::default() }; + crate::tool_reset::reset_options(&mut o, Tool::Sponge); + assert_eq!(o.sponge_flow, 50.0); + assert!(crate::tool_reset::option_keys(Tool::Sponge).contains(&"sponge_flow"), "a Sponge preset stores it too"); +} + +#[test] +fn flow_typed_past_the_range_takes_the_closest_value_and_alerts() { + for (typed, want) in [("0", 1.0), ("150", 100.0)] { + let mut h = bar(); + type_flow(&mut h, typed); + assert_eq!(flow(&h), want, "{typed}"); + assert_eq!(alerts(&h), vec![TOLERANCE_RANGE_ALERT.to_string()], "{typed}: one alert"); + let id = h.state().ui.dialogs.iter().find(|d| d.kind == DialogKind::Error).map(|d| d.id).expect("an alert"); + crate::dialogs::confirm(h.state_mut(), id).unwrap(); + h.run_steps(3); + assert!(alerts(&h).is_empty(), "{typed}: OK closes the alert"); + assert_eq!(flow(&h), want, "{typed}: the closest value is kept"); + } +} + +#[test] +fn flow_in_range_is_stored_as_a_whole_number_without_an_alert() { + for (typed, want) in [("33.7", 34.0), ("1", 1.0), ("100", 100.0), ("72", 72.0)] { + let mut h = bar(); + type_flow(&mut h, typed); + assert_eq!(flow(&h), want, "{typed}"); + assert!(alerts(&h).is_empty(), "{typed} is in range"); + } +} + +#[test] +fn flow_that_is_no_number_keeps_the_value_without_an_alert() { + let mut h = bar(); + type_flow(&mut h, "abc"); + assert_eq!(flow(&h), 50.0, "the previous value stays"); + assert!(alerts(&h).is_empty(), "no number, no alert"); +} + +#[test] +fn the_arrow_opens_a_slider_from_1_to_100() { + let mut h = bar(); + assert!(h.query_all_by_role(Role::Slider).next().is_none(), "the slider stays closed"); + h.get_by_role_and_label(Role::Button, "Flow").click(); + h.run_steps(4); + let slider = h.get_by_role_and_label(Role::Slider, "Flow").rect(); + click_at(&mut h, egui::pos2(slider.right() - 3.0, slider.center().y)); + assert_eq!(flow(&h), 100.0, "the slider's far end"); + click_at(&mut h, egui::pos2(slider.left() + 3.0, slider.center().y)); + assert_eq!(flow(&h), 1.0, "the slider's near end"); + click_at(&mut h, slider.center()); + assert_eq!(flow(&h).fract(), 0.0, "the slider gives whole numbers"); + assert!((2.0..=99.0).contains(&flow(&h)), "between the ends: {}", flow(&h)); + assert!(alerts(&h).is_empty(), "the slider does not alert"); +} + +/// An 80 px document filled with red 200,40,40 and a 40 px hard tip. +fn red_app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 80, "height": 80})).unwrap(); + app.run("paint.pencil", json!({"points": [[40, 40]], "size": 400, "color": "#c82828"})).unwrap(); + app.run("tools.setBrush", json!({"brush": {"size": 40, "hardness": 1.0}})).unwrap(); + app +} + +fn pixel(app: &PhotocraftApp) -> [f32; 4] { + let st = app.session.active().unwrap(); + st.active_layer.and_then(|id| st.doc.layer(id)).unwrap().surface().unwrap().rgba(40, 40) +} + +#[test] +fn a_sponge_click_uses_the_bar_flow() { + let untouched = pixel(&red_app()); + let mut seen = Vec::new(); + for f in [10.0, 50.0, 100.0] { + let mut clicked = red_app(); + clicked.ui.tool = Tool::Sponge; + clicked.ui.tool_options.sponge_mode = "desaturate".into(); + clicked.ui.tool_options.vibrance = true; + clicked.ui.tool_options.sponge_flow = f; + let m = egui::Modifiers::NONE; + tool_event(&mut clicked, ToolEvent::Down { x: 40.0, y: 40.0, pressure: 1.0 }, m); + tool_event(&mut clicked, ToolEvent::Up { x: 40.0, y: 40.0 }, m); + assert!(!clicked.ui.status_error, "{f}: {}", clicked.ui.status); + let (cmd, params) = clicked.session.journal.last().unwrap().clone(); + assert_eq!(cmd, "paint.sponge"); + assert_eq!(params["flow"], json!(f), "the stroke records the bar's flow"); + + let mut command = red_app(); + command + .run("paint.sponge", json!({"points": [[40.0, 40.0, 1.0]], "size": 40, "hardness": 100, "mode": "desaturate", "vibrance": true, "flow": f})) + .unwrap(); + assert_eq!(pixel(&clicked), pixel(&command), "flow {f}: the click paints what paint.sponge does"); + seen.push(pixel(&clicked)); + } + // The flow reaches the stroke: without it every click painted at the command's default of 100 %. + assert_ne!(seen[2], untouched, "a click at 100 % desaturates"); + assert_ne!(seen[0], seen[2], "10 % and 100 % give different pixels: {seen:?}"); +} + +#[test] +fn a_restored_fraction_paints_the_whole_number_the_bar_shows() { + let mut app = red_app(); + app.ui.tool_options.sponge_flow = 33.7; + let (cmd, params) = crate::retouch_ui::dab_params(&app, Tool::Sponge).unwrap(); + assert_eq!(cmd, "paint.sponge"); + assert_eq!(params["flow"], json!(34.0)); + app.ui.tool_options.sponge_flow = 0.0; + assert_eq!(crate::retouch_ui::dab_params(&app, Tool::Sponge).unwrap().1["flow"], json!(1.0)); +} diff --git a/crates/ui-egui/src/state/tool_options.rs b/crates/ui-egui/src/state/tool_options.rs index 5290558d61b..332cd2d9db7 100644 --- a/crates/ui-egui/src/state/tool_options.rs +++ b/crates/ui-egui/src/state/tool_options.rs @@ -84,6 +84,9 @@ pub struct ToolOptions { pub protect_tones: bool, /// Sponge: desaturate | saturate, vibrance. pub sponge_mode: String, + /// Sponge: Flow %, whole numbers 1..100 (#12976). Settings saved before it load as 50. + #[serde(default = "fifty")] + pub sponge_flow: f32, pub vibrance: bool, /// Blur/Sharpen/Smudge strength %, Sharpen protect detail, Smudge finger painting. pub strength: f32, @@ -480,6 +483,7 @@ impl Default for ToolOptions { exposure: 50.0, protect_tones: true, sponge_mode: "desaturate".into(), + sponge_flow: 50.0, vibrance: true, strength: 50.0, protect_detail: true, diff --git a/crates/ui-egui/src/tools/retouch_ui.rs b/crates/ui-egui/src/tools/retouch_ui.rs index e35a35b984b..4bed7659fc8 100644 --- a/crates/ui-egui/src/tools/retouch_ui.rs +++ b/crates/ui-egui/src/tools/retouch_ui.rs @@ -111,7 +111,8 @@ pub(crate) fn dab_params(app: &PhotocraftApp, tool: Tool) -> Option<(&'static st if tool == Tool::Dodge { "paint.dodge" } else { "paint.burn" }, json!({"range": o.tone_range, "exposure": o.exposure, "protectTones": o.protect_tones}), ), - Tool::Sponge => ("paint.sponge", json!({"mode": o.sponge_mode, "vibrance": o.vibrance})), + // Flow as the bar's field stores it (#12976), so a restored fraction paints what the bar shows. + Tool::Sponge => ("paint.sponge", json!({"mode": o.sponge_mode, "flow": crate::eraser_ui::stored_tolerance(o.sponge_flow), "vibrance": o.vibrance})), _ => return None, }) } @@ -944,7 +945,15 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo opt(ui, tl!("Mode:")); let opts = [("desaturate".to_string(), tl!("Desaturate")), ("saturate".to_string(), tl!("Saturate"))]; crate::widgets::dropdown(ui, "sponge-mode", tl!("Mode"), &mut o.sponge_mode, &opts, 110.0); + // Flow (#12976): whole numbers 1..100 with the "Closest value inserted" alert, and a slider arrow. + let label = tl!("Flow:"); + opt(ui, label); + let (_, out_of_range) = crate::widgets::value_field_whole_alerting(ui, label, &mut o.sponge_flow, 1.0..=100.0, "%", 58.0); + cam_amount_slider(ui, tl!("Flow"), &mut o.sponge_flow, 1.0, 100.0, "Flow"); crate::widgets::checkbox(ui, &mut o.vibrance, tl!("Vibrance")); + if out_of_range { + crate::eraser_ui::open_range_alert(app); + } } Tool::Blur | Tool::Sharpen | Tool::Smudge => { let label = tl!("Strength:"); @@ -1132,3 +1141,7 @@ mod cam_options_bar_tests; #[cfg(test)] #[path = "../burn_bar_tooltips_tests.rs"] mod burn_bar_tooltips_tests; + +#[cfg(test)] +#[path = "../sponge_flow_field_tests.rs"] +mod sponge_flow_field_tests; diff --git a/crates/ui-egui/src/tools/tool_reset.rs b/crates/ui-egui/src/tools/tool_reset.rs index fa746e9cf82..7d08944aed3 100644 --- a/crates/ui-egui/src/tools/tool_reset.rs +++ b/crates/ui-egui/src/tools/tool_reset.rs @@ -239,7 +239,7 @@ pub fn option_keys(tool: Tool) -> &'static [&'static str] { Tool::Blur | Tool::Sharpen => reset!(strength, protect_detail), Tool::Smudge => reset!(strength, finger_painting), Tool::Dodge | Tool::Burn => reset!(tone_range, exposure, protect_tones), - Tool::Sponge => reset!(sponge_mode, vibrance), + Tool::Sponge => reset!(sponge_mode, sponge_flow, vibrance), Tool::Slice => reset!(slice_style, slice_width, slice_height), Tool::Pen => reset!(vector_mode, pen_path_op, pen_auto_add_delete), Tool::CurvaturePen => reset!(vector_mode, pen_path_op), From 9c7e055957aa3c23072633456de7a68749658860 Mon Sep 17 00:00:00 2001 From: rmsff <17902130+rmsff@users.noreply.github.com> Date: Wed, 11 Nov 2026 01:52:01 +0300 Subject: [PATCH 29/42] Red Eye: refuse CMYK, Grayscale and Indexed Color documents (#12575) A click in these modes opens the reference's alert instead of running, and paint.redEye returns the same text, leaving pixels and History unchanged. The two tests that expected CMYK to run and Grayscale to miss now expect the refusal. --- crates/engine/src/cmd/redeye_cmds.rs | 31 ++++++++++++++------ crates/ui-egui/src/canvas/tool_input.rs | 38 ++++++++++++++++++------- 2 files changed, 50 insertions(+), 19 deletions(-) diff --git a/crates/engine/src/cmd/redeye_cmds.rs b/crates/engine/src/cmd/redeye_cmds.rs index 0174824a6e3..d72ad66c5c0 100644 --- a/crates/engine/src/cmd/redeye_cmds.rs +++ b/crates/engine/src/cmd/redeye_cmds.rs @@ -16,6 +16,9 @@ use crate::{EngineError, Result, Session}; const CMD: &str = "paint.redEye"; const MISS: &str = "no red-eye pixels near the click"; +/// The reference's alert for a Red Eye click in a CMYK, Grayscale or Indexed Color document (#12575). +pub const MODE_REFUSAL: &str = "Could not use the red eye removal tool because it only works in full color modes."; + fn bad(msg: impl Into) -> EngineError { EngineError::BadParams { cmd: CMD.into(), msg: msg.into() } } @@ -226,7 +229,17 @@ fn enabled(s: &Session) -> std::result::Result<(), String> { Ok(()) } +/// By the document's mode, not its pixel format: Indexed Color pixels are stored as RGB. Bitmap, +/// Duotone and Multichannel were not measured and keep running. +fn mode_refusal(s: &Session) -> Result<()> { + match s.active().map(|d| d.doc.mode) { + Some(ColorMode::Cmyk | ColorMode::Grayscale | ColorMode::Indexed) => Err(EngineError::Other(MODE_REFUSAL.into())), + _ => Ok(()), + } +} + fn red_eye(s: &mut Session, p: &Value) -> Result { + mode_refusal(s)?; let pts = clicks(p)?; let pupil_raw = num(p, "pupilSize", 50.0)?; let darken = num(p, "darken", 50.0)?; @@ -407,7 +420,7 @@ mod tests { } #[test] - fn cmyk_document_keeps_untouched_pixels_bit_exact() { + fn cmyk_document_is_refused_and_keeps_its_pixels_bit_exact() { let mut s = session(64, 64, 8, "cmyk"); assert_eq!(s.active().unwrap().doc.pixel_format().mode, ColorMode::Cmyk); // Rich black (all four inks) around the eye: a naive RGBA round trip regenerates K. @@ -438,22 +451,24 @@ mod tests { let surf = d.doc.layer(d.active_layer.unwrap()).unwrap().surface().unwrap(); surf.read_region(Rect::new(x, y, x + 1, y + 1)) }; - let probes = [(32, 18), (2, 2), (50, 40)]; + let probes = [(32, 26), (32, 18), (2, 2), (50, 40)]; let before: Vec> = probes.iter().map(|&(x, y)| raw(&s, x, y)).collect(); - let r = s.execute("paint.redEye", json!({"x": 32, "y": 32})).unwrap(); - assert!(r["pixels"].as_u64().unwrap() > 0, "{r}"); + let past = s.active().unwrap().history.past_len(); + let err = s.execute("paint.redEye", json!({"x": 32, "y": 32})).unwrap_err().to_string(); + assert_eq!(err, MODE_REFUSAL); for (&(x, y), b) in probes.iter().zip(&before) { - assert_eq!(&raw(&s, x, y), b, "untouched CMYK pixel ({x},{y}) inside the window changed"); + assert_eq!(&raw(&s, x, y), b, "CMYK pixel ({x},{y}) changed"); } - assert!(rgba(&s, 32, 26)[0] < 0.7, "pupil corrected"); + assert_eq!(s.active().unwrap().history.past_len(), past, "no history state"); } #[test] - fn gray_document_misses() { + fn gray_document_is_refused() { let mut s = session(24, 24, 16, "gray"); paint_layer(&mut s, |_, _| [0.5, 0.5, 0.5, 1.0]); assert_eq!(s.active().unwrap().doc.pixel_format().mode, ColorMode::Grayscale); - assert!(s.execute("paint.redEye", json!({"x": 12, "y": 12})).is_err()); + let err = s.execute("paint.redEye", json!({"x": 12, "y": 12})).unwrap_err().to_string(); + assert_eq!(err, MODE_REFUSAL); } } diff --git a/crates/ui-egui/src/canvas/tool_input.rs b/crates/ui-egui/src/canvas/tool_input.rs index e53e0938c1d..29d966ef892 100644 --- a/crates/ui-egui/src/canvas/tool_input.rs +++ b/crates/ui-egui/src/canvas/tool_input.rs @@ -425,6 +425,32 @@ fn mixer_press_failed(app: &mut PhotocraftApp, message: String) { } } +/// A Red Eye click. CMYK, Grayscale and Indexed Color documents get the reference's alert +/// (#12575), once even if more clicks arrive while it is open (`ui.pointer` can send them). +fn red_eye_click(app: &mut PhotocraftApp, x: f64, y: f64) { + use photocraft_engine::redeye_cmds::MODE_REFUSAL; + let o = app.ui.tool_options.clone(); + let r = app.run( + "paint.redEye", + json!({ + "x": x.floor(), + "y": y.floor(), + "pupilSize": o.red_eye_pupil_size.clamp(1.0, 100.0), + "darken": o.red_eye_darken.clamp(0.0, 100.0), + "target": paint_target(app), + }), + ); + if r.is_err_and(|e| e == MODE_REFUSAL) { + app.ui.status.clear(); + app.ui.status_error = false; + let message = tl!(MODE_REFUSAL); + let kind = crate::state::DialogKind::Error; + if !app.ui.dialogs.iter().any(|d| d.kind == kind && d.fields.get("message").and_then(|m| m.as_str()) == Some(message)) { + app.ui.open_dialog(kind, json!({ "message": message }).as_object().cloned().unwrap_or_default()); + } + } +} + /// The Brush's chosen Clear paints as Normal on the Background, and its Mode then reads Normal /// (#11897): at the press of a Brush stroke on the Background's own pixels, Clear (chosen in the /// options bar, not a held `~`) is turned off, so the stroke is sent as Normal. A Background whose @@ -581,17 +607,7 @@ pub(super) fn tool_event_with_view(app: &mut PhotocraftApp, ev: ToolEvent, mods: return; } Tool::RedEye => { - let o = app.ui.tool_options.clone(); - let _ = app.run( - "paint.redEye", - json!({ - "x": x.floor(), - "y": y.floor(), - "pupilSize": o.red_eye_pupil_size.clamp(1.0, 100.0), - "darken": o.red_eye_darken.clamp(0.0, 100.0), - "target": paint_target(app), - }), - ); + red_eye_click(app, x, y); return; } Tool::PolygonLasso => { From ab19246243a134e434c4c43873cb4a528627f392 Mon Sep 17 00:00:00 2001 From: rmsff <17902130+rmsff@users.noreply.github.com> Date: Wed, 11 Nov 2026 01:52:17 +0300 Subject: [PATCH 30/42] Test the Red Eye tool's colour mode refusal --- crates/engine/src/cmd/redeye_cmds.rs | 4 + .../engine/src/cmd/redeye_color_mode_tests.rs | 93 +++++++++++++++++++ 2 files changed, 97 insertions(+) create mode 100644 crates/engine/src/cmd/redeye_color_mode_tests.rs diff --git a/crates/engine/src/cmd/redeye_cmds.rs b/crates/engine/src/cmd/redeye_cmds.rs index d72ad66c5c0..01131b53402 100644 --- a/crates/engine/src/cmd/redeye_cmds.rs +++ b/crates/engine/src/cmd/redeye_cmds.rs @@ -475,3 +475,7 @@ mod tests { #[cfg(test)] #[path = "redeye_history_state_tests.rs"] mod redeye_history_state_tests; + +#[cfg(test)] +#[path = "redeye_color_mode_tests.rs"] +mod redeye_color_mode_tests; diff --git a/crates/engine/src/cmd/redeye_color_mode_tests.rs b/crates/engine/src/cmd/redeye_color_mode_tests.rs new file mode 100644 index 00000000000..c1189211ff4 --- /dev/null +++ b/crates/engine/src/cmd/redeye_color_mode_tests.rs @@ -0,0 +1,93 @@ +//! #12575: the Red Eye tool refuses CMYK, Grayscale and Indexed Color documents with the +//! reference's alert text and leaves the document and History unchanged. RGB (8, 16, 32 bit) and +//! Lab still correct the pupil; Bitmap, Duotone and Multichannel were not measured and keep +//! today's behaviour (no refusal). + +use serde_json::{Value, json}; + +use super::*; + +fn new_doc(mode: &str, depth: u64) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 64, "height": 64, "mode": mode, "depth": depth})).unwrap(); + s +} + +/// A red pupil on its own layer. +fn red_pupil(s: &mut Session) { + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("paint.pencil", json!({"points": [[32, 32]], "size": 14, "hardness": 100, "color": "#f21818"})).unwrap(); +} + +fn assert_refused(s: &mut Session, params: Value, case: &str) { + let (doc, steps) = (s.active().unwrap().doc.clone(), s.active().unwrap().history.past_len()); + let err = s.execute("paint.redEye", params).unwrap_err().to_string(); + assert_eq!(err, MODE_REFUSAL, "{case}"); + assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc), "{case}: document unchanged"); + assert_eq!(s.active().unwrap().history.past_len(), steps, "{case}: no history state"); +} + +#[test] +fn the_refusal_is_the_reference_alert_text() { + assert_eq!(MODE_REFUSAL, "Could not use the red eye removal tool because it only works in full color modes."); +} + +#[test] +fn cmyk_and_grayscale_documents_are_refused() { + for (mode, depths) in [("cmyk", &[8u64, 16][..]), ("gray", &[8, 16, 32][..])] { + for &depth in depths { + let mut s = new_doc(mode, depth); + red_pupil(&mut s); + assert_refused(&mut s, json!({"x": 32, "y": 32}), &format!("{mode} {depth} bit")); + } + } +} + +#[test] +fn indexed_color_documents_are_refused() { + let mut s = new_doc("rgb", 8); + red_pupil(&mut s); + s.execute("image.mode.indexedColor", json!({"palette": "exact", "dither": "none", "forced": "none"})).unwrap(); + assert_eq!(s.active().unwrap().doc.mode, ColorMode::Indexed); + assert_refused(&mut s, json!({"x": 32, "y": 32}), "indexed"); + assert_refused(&mut s, json!({"points": [[32, 32], [10, 10]]}), "indexed, a points batch"); +} + +/// Converting to Indexed Color flattens the document, so a script's layer id is gone: the mode +/// is refused before the layer is looked up. +#[test] +fn the_refusal_comes_before_the_layer_lookup() { + let mut s = new_doc("rgb", 8); + red_pupil(&mut s); + let id = s.active().unwrap().active_layer.unwrap(); + s.execute("image.mode.indexedColor", json!({"palette": "exact", "dither": "none", "forced": "none"})).unwrap(); + assert_refused(&mut s, json!({"x": 32, "y": 32, "layer": id.0}), "a flattened layer id"); +} + +#[test] +fn rgb_and_lab_documents_still_correct_the_pupil() { + for (mode, depth) in [("rgb", 8), ("rgb", 16), ("rgb", 32), ("lab", 8), ("lab", 16)] { + let mut s = new_doc(mode, depth); + red_pupil(&mut s); + let steps = s.active().unwrap().history.past_len(); + let r = s.execute("paint.redEye", json!({"x": 32, "y": 32})).unwrap_or_else(|e| panic!("{mode} {depth}: {e}")); + assert!(r["pixels"].as_u64().unwrap() > 0, "{mode} {depth}: {r}"); + assert_eq!(s.active().unwrap().history.past_len(), steps + 1, "{mode} {depth}"); + } +} + +#[test] +fn unmeasured_modes_are_not_refused() { + let mut multi = new_doc("rgb", 8); + red_pupil(&mut multi); + multi.execute("image.mode.multichannel", json!({})).unwrap(); + let mut bitmap = new_doc("gray", 8); + bitmap.execute("image.mode.bitmap", json!({})).unwrap(); + let mut duotone = new_doc("gray", 8); + duotone.execute("image.mode.duotone", json!({"type": "monotone"})).unwrap(); + for (mut s, mode) in [(multi, ColorMode::Multichannel), (bitmap, ColorMode::Bitmap), (duotone, ColorMode::Duotone)] { + assert_eq!(s.active().unwrap().doc.mode, mode); + let r = s.execute("paint.redEye", json!({"x": 32, "y": 32})); + assert!(r.as_ref().err().is_none_or(|e| e.to_string() != MODE_REFUSAL), "{mode:?}: {r:?}"); + } +} From 639b446ffef5d5a82f0a1fa641e24cf5d9d34946 Mon Sep 17 00:00:00 2001 From: rmsff <17902130+rmsff@users.noreply.github.com> Date: Wed, 11 Nov 2026 01:14:33 +0300 Subject: [PATCH 31/42] Warp: a Split button places one split, then its mode ends The options-bar Split buttons stayed armed after the split, so every further click on the canvas added another line. The release that places a split now clears split_tool, as in the reference; a release that places none keeps the mode armed, as today. The existing test now expects the mode to end instead of staying armed. --- crates/ui-egui/src/tools/transform_tool/tests.rs | 2 +- crates/ui-egui/src/tools/transform_tool/warp.rs | 10 +++++++--- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/tools/transform_tool/tests.rs b/crates/ui-egui/src/tools/transform_tool/tests.rs index f355c3c4bde..3c40b1712f2 100644 --- a/crates/ui-egui/src/tools/transform_tool/tests.rs +++ b/crates/ui-egui/src/tools/transform_tool/tests.rs @@ -883,7 +883,7 @@ fn split_tool_places_the_line_where_the_pointer_releases() { assert!(us.len() == 3 && has(&us, 0.25), "{us:?}"); let vs = app.ui.transform.as_ref().unwrap().warp.as_ref().unwrap().mesh.as_ref().unwrap().vs.clone(); assert!(has(&vs, 1.0 / 3.0) && has(&vs, 2.0 / 3.0), "horizontal sections stay: {vs:?}"); - assert!(app.transform_preview.as_ref().unwrap().split_tool.is_some(), "the tool stays armed"); + assert!(app.transform_preview.as_ref().unwrap().split_tool.is_none(), "one split ends the mode"); // Option-click in the open places both lines, without a button armed. app.transform_preview.as_mut().unwrap().split_tool = None; let alt = egui::Modifiers::ALT; diff --git a/crates/ui-egui/src/tools/transform_tool/warp.rs b/crates/ui-egui/src/tools/transform_tool/warp.rs index cc882ea64cf..67a73968bf7 100644 --- a/crates/ui-egui/src/tools/transform_tool/warp.rs +++ b/crates/ui-egui/src/tools/transform_tool/warp.rs @@ -67,6 +67,7 @@ pub(super) fn split_cursor(m: &BezierMesh, tool: SplitTool, (s, t): (f64, f64), } /// Armed split tool, or Option held: the guide tracks the pointer and the split lands on release. +/// A Split button is one-shot, as in the reference: the release that splits ends its mode (#12498). /// Returns false when this event is an ordinary control-point drag. fn split_gesture(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> bool { let armed = app.transform_preview.as_ref().and_then(|p| p.split_tool); @@ -103,9 +104,12 @@ fn split_gesture(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) } else { None }; - if let Some(kind) = kind { - // On an existing line, or a click the drag path also delivers, this is a no-op. - let _ = split(app, kind.command(), Some([x, y])); + // Outside the grid or on an existing line this is a no-op, and the mode stays armed. + if let Some(kind) = kind + && split(app, kind.command(), Some([x, y])).is_ok() + && let Some(pv) = app.transform_preview.as_mut() + { + pv.split_tool = None; } true } From 0cb2e8cc991be5b80ebae35ed568534c8ffde9ac Mon Sep 17 00:00:00 2001 From: rmsff <17902130+rmsff@users.noreply.github.com> Date: Wed, 11 Nov 2026 01:14:33 +0300 Subject: [PATCH 32/42] Test the one-shot Warp split buttons --- .../ui-egui/src/tools/transform_tool/warp.rs | 4 + .../warp_split_one_shot_tests.rs | 139 ++++++++++++++++++ 2 files changed, 143 insertions(+) create mode 100644 crates/ui-egui/src/tools/transform_tool/warp_split_one_shot_tests.rs diff --git a/crates/ui-egui/src/tools/transform_tool/warp.rs b/crates/ui-egui/src/tools/transform_tool/warp.rs index 67a73968bf7..fc8f2208465 100644 --- a/crates/ui-egui/src/tools/transform_tool/warp.rs +++ b/crates/ui-egui/src/tools/transform_tool/warp.rs @@ -193,3 +193,7 @@ pub fn split(app: &mut PhotocraftApp, id: &str, at: Option<[f64; 2]>) -> Result< } edit_session_warp(app, id, &p) } + +#[cfg(test)] +#[path = "warp_split_one_shot_tests.rs"] +mod warp_split_one_shot_tests; diff --git a/crates/ui-egui/src/tools/transform_tool/warp_split_one_shot_tests.rs b/crates/ui-egui/src/tools/transform_tool/warp_split_one_shot_tests.rs new file mode 100644 index 00000000000..85bc3822ea7 --- /dev/null +++ b/crates/ui-egui/src/tools/transform_tool/warp_split_one_shot_tests.rs @@ -0,0 +1,139 @@ +//! #12498: an options-bar Split button places one split line, then its mode ends, as in the +//! reference. Quick splits and the menu / control-channel commands keep their behaviour. + +use super::super::tests::app_with_square; +use super::*; +use egui::PointerButton; +use egui_kittest::kittest::Queryable; + +type Harness = egui_kittest::Harness<'static, PhotocraftApp>; + +/// A 400 × 300 layer in Warp with the Default grid. +fn warping() -> Harness { + let app = app_with_square(512, photocraft_geom::Rect::new(56, 56, 456, 356)); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1200.0, 800.0)).with_max_steps(64).build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + app + }); + run(&mut h, "edit.transform.warp", json!({})); + h +} + +/// A menu / control-channel command, then a few frames. +fn run(h: &mut Harness, id: &str, params: serde_json::Value) { + h.run_steps(3); + let ctx = h.ctx.clone(); + crate::menus::invoke(h.state_mut(), &ctx, id, params).unwrap(); + h.run_steps(3); +} + +fn warp(h: &Harness) -> Option { + h.state().ui.transform.as_ref().unwrap().warp.clone() +} + +/// The grid's horizontal knots (`vs`): one more per horizontal split line. +fn rows(h: &Harness) -> usize { + warp(h).and_then(|w| w.mesh).map_or(2, |m| m.vs.len()) +} + +fn armed(h: &Harness) -> Option { + h.state().transform_preview.as_ref().unwrap().split_tool +} + +fn press_button(h: &mut Harness, tip: &str) { + h.get_by_label(tip).click(); + h.run_steps(3); +} + +/// A click on the canvas at document point `p`, through the real pointer path. +fn click_doc(h: &mut Harness, p: [f32; 2], m: egui::Modifiers) { + let at = ViewXform::active(h.state()).unwrap().to_screen(p[0], p[1]); + h.event(egui::Event::ModifiersChanged(m)); + h.event(egui::Event::PointerMoved(at)); + h.run_steps(1); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: m }); + h.run_steps(2); + } + h.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE)); + h.run_steps(2); +} + +#[test] +fn a_split_button_places_one_line_and_then_the_mode_ends() { + let mut h = warping(); + press_button(&mut h, "Split Warp Horizontally"); + assert!(armed(&h) == Some(SplitTool::Horizontal), "the button arms its mode"); + let before = rows(&h); + click_doc(&mut h, [256.0, 156.0], egui::Modifiers::NONE); + assert_eq!(rows(&h), before + 1, "one split line at the click"); + // The bar draws the button pressed only while `split_tool` names it. + assert!(armed(&h).is_none(), "the mode ends after one split"); + let placed = rows(&h); + click_doc(&mut h, [256.0, 300.0], egui::Modifiers::NONE); + assert_eq!(rows(&h), placed, "the next click is an ordinary press, not another split"); + assert!(armed(&h).is_none()); +} + +#[test] +fn every_split_button_is_one_shot() { + for tip in ["Split Warp Crosswise", "Split Warp Vertically", "Split Warp Horizontally"] { + let mut h = warping(); + press_button(&mut h, tip); + assert!(armed(&h).is_some(), "{tip} arms its mode"); + let before = warp(&h); + click_doc(&mut h, [200.0, 150.0], egui::Modifiers::NONE); + assert!(warp(&h) != before, "{tip} split the grid"); + assert!(armed(&h).is_none(), "{tip} ends after one split"); + } +} + +#[test] +fn a_second_press_on_the_button_still_cancels_without_a_split() { + let mut h = warping(); + let before = warp(&h); + press_button(&mut h, "Split Warp Vertically"); + press_button(&mut h, "Split Warp Vertically"); + assert!(armed(&h).is_none(), "the second press cancels the mode"); + assert_eq!(warp(&h), before, "nothing was split"); +} + +/// Not measured: a release that places no line keeps the mode armed, as today. +#[test] +fn a_release_that_places_no_line_keeps_the_mode() { + let mut h = warping(); + run(&mut h, "edit.transform.splitWarpHorizontally", json!({"at": [256.0, 156.0]})); + press_button(&mut h, "Split Warp Horizontally"); + let before = rows(&h); + click_doc(&mut h, [256.0, 20.0], egui::Modifiers::NONE); + assert_eq!(rows(&h), before, "above the grid nothing is split"); + assert!(armed(&h) == Some(SplitTool::Horizontal), "the mode stays after a miss above the grid"); + click_doc(&mut h, [256.0, 156.0], egui::Modifiers::NONE); + assert_eq!(rows(&h), before, "the line is already there"); + assert!(armed(&h) == Some(SplitTool::Horizontal), "the mode stays after a click on an existing line"); +} + +#[test] +fn quick_splits_still_place_one_split_per_click() { + let mut h = warping(); + let before = rows(&h); + // On the Default grid a crosswise split also keeps both thirds, so it adds more than one row. + click_doc(&mut h, [256.0, 131.0], egui::Modifiers::ALT); + let first = rows(&h); + assert!(first > before, "the first Option-click splits"); + click_doc(&mut h, [356.0, 281.0], egui::Modifiers::ALT); + assert_eq!(rows(&h), first + 1, "the second Option-click adds one more line"); + click_doc(&mut h, [156.0, 206.0], egui::Modifiers::COMMAND); + assert_eq!(rows(&h), first + 2, "a Ctrl/Cmd-click splits the same way"); + assert!(armed(&h).is_none(), "no mode is armed"); +} + +#[test] +fn menu_and_control_channel_splits_still_split_at_once() { + let mut h = warping(); + let before = rows(&h); + run(&mut h, "edit.transform.splitWarpHorizontally", json!({})); + run(&mut h, "edit.transform.splitWarpHorizontally", json!({"at": [256.0, 300.0]})); + assert_eq!(rows(&h), before + 2, "at the box centre, then at `at`"); + assert!(armed(&h).is_none(), "a command never arms the mode"); +} From 8824661f478daf78d3cce59fcc790ad1aa29a2f4 Mon Sep 17 00:00:00 2001 From: rmsff <17902130+rmsff@users.noreply.github.com> Date: Tue, 10 Nov 2026 22:08:14 +0300 Subject: [PATCH 33/42] Make Selection: Rendering and Operation groups; the dialog's step is Selection Change (#12917) The Pen's Make Selection dialog (canvas menu, options bar) now has Photoshop's layout: Rendering with Feather Radius in pixels and Anti-aliased, then Operation with New / Add to / Subtract from / Intersect with Selection as radio buttons. The last three are greyed out without a selection. The fields and params are the same as before. OK with New Selection names the step it added "Selection Change". Cmd/Ctrl+Enter, the Paths panel and the combining operations keep "Make Selection" (not measured). --- crates/ui-egui/src/canvas/canvas_tool_menu.rs | 58 +++++++++++++++++++ crates/ui-egui/src/dialogs.rs | 7 +++ 2 files changed, 65 insertions(+) diff --git a/crates/ui-egui/src/canvas/canvas_tool_menu.rs b/crates/ui-egui/src/canvas/canvas_tool_menu.rs index a3bbe242943..f544ebd6b00 100644 --- a/crates/ui-egui/src/canvas/canvas_tool_menu.rs +++ b/crates/ui-egui/src/canvas/canvas_tool_menu.rs @@ -1261,6 +1261,7 @@ fn pen_dialog(app: &mut PhotocraftApp, command: &str, label: &str, name: &str) { if command == "path.toSelection" { // OK deselects and hides the path, as ⌘↩ does (#6079). fields.insert("__deselectPath".into(), json!(true)); + fields.insert(MAKE_SELECTION.into(), json!(true)); } if command == "path.fill" { let fg = app.session.tools.foreground; @@ -1281,6 +1282,63 @@ fn pen_dialog(app: &mut PhotocraftApp, command: &str, label: &str, name: &str) { spec_dialog(app, command, label, spec, fields); } +/// Marks the Make Selection dialog [`pen_dialog`] opens. It keeps the schema dialog's fields, so OK +/// and Alt+Reset work as before; only the body is Photoshop's layout (#12917). +const MAKE_SELECTION: &str = "__makeSelection"; + +/// The Make Selection operations, in Photoshop's order: (`path.toSelection` mode, label). +const MAKE_SELECTION_OPERATIONS: [(&str, &str); 4] = + [("replace", "New Selection"), ("add", "Add to Selection"), ("subtract", "Subtract from Selection"), ("intersect", "Intersect with Selection")]; + +/// Is this dialog the Make Selection dialog? +pub(crate) fn owns_make_selection(fields: &serde_json::Map) -> bool { + fields.contains_key(MAKE_SELECTION) +} + +/// Photoshop's Make Selection dialog: Rendering (Feather Radius, Anti-aliased) and Operation. +/// Without a selection there is nothing to combine with, so only New Selection is available. +pub(crate) fn make_selection_body(app: &PhotocraftApp, ui: &mut egui::Ui, f: &mut serde_json::Map) { + let has_selection = app.session.active().is_some_and(|st| st.doc.selection.is_some()); + ui.spacing_mut().item_spacing.y = 6.0; + crate::widgets::section_label(ui, tl!("Rendering")); + crate::widgets::hairline(ui); + ui.horizontal(|ui| { + ui.label(tl!("Feather Radius:")); + let mut feather = f.get("feather").and_then(Value::as_f64).unwrap_or(0.0) as f32; + crate::widgets::value_field(ui, &mut feather, 0.0..=250.0, "", 64.0).accessible_name(tl!("Feather Radius:")); + ui.label(tl!("pixels")); + // The schema dialog's rounding, so OK sends what it sent. + f.insert("feather".into(), json!((feather * 10.0).round() / 10.0)); + }); + let mut anti_alias = f.get("antiAlias").and_then(Value::as_bool).unwrap_or(true); + crate::widgets::checkbox(ui, &mut anti_alias, tl!("Anti-aliased")); + f.insert("antiAlias".into(), json!(anti_alias)); + ui.add_space(4.0); + crate::widgets::section_label(ui, tl!("Operation")); + crate::widgets::hairline(ui); + let mut mode = f.get("mode").and_then(Value::as_str).unwrap_or("replace").to_string(); + // A combining mode set from outside, or a selection gone while the dialog was open. + if !has_selection { + mode = "replace".into(); + } + for (key, label) in MAKE_SELECTION_OPERATIONS { + ui.add_enabled_ui(key == "replace" || has_selection, |ui| ui.radio_value(&mut mode, key.to_string(), tl!(label))); + } + f.insert("mode".into(), json!(mode)); +} + +/// OK in the Make Selection dialog: a new selection is the History step Selection Change, as in +/// Photoshop (#12917). ⌘↩, the Paths panel and the combining operations keep the engine's Make +/// Selection (not measured). Only a step this run added is renamed: `revision` is from before it. +pub(crate) fn name_make_selection_step(app: &mut PhotocraftApp, fields: &serde_json::Map, params: &Value, revision: Option) { + if !owns_make_selection(fields) || params.get("mode").and_then(Value::as_str).is_some_and(|m| m != "replace") { + return; + } + if let Some(st) = app.session.active_mut().filter(|st| Some(st.revision) != revision) { + st.history.set_current_label("Selection Change"); + } +} + /// The Pen options bar's Make Selection (Path mode, #5703): the canvas menu's Make Selection… /// dialog for the path being drawn (committed first, as the menu does) or the active path. pub(crate) fn make_selection(app: &mut PhotocraftApp) -> Result<(), String> { diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 4ab8a2eeb3f..abc59bcfa72 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -357,6 +357,9 @@ fn command_body_more(app: &mut PhotocraftApp, ui: &mut egui::Ui, d: &Dialog, fie _ if crate::smart_filter_dialog::owns(fields) => crate::smart_filter_dialog::body(app, ui, fields), _ if crate::adjust_dialog::owns(fields) => crate::adjust_dialog::body(app, ui, fields), _ if crate::blur_pins::owns(fields) => crate::blur_pins::body(ui, fields), + _ if crate::canvas_tool_menu::owns_make_selection(fields) => { + first_field_focused(ui, id, |ui| crate::canvas_tool_menu::make_selection_body(app, ui, fields)) + } _ if fields.contains_key("__filter") => filter_body(app, ui, d, fields, id), _ if crate::new_guide_ui::owns(fields) => crate::new_guide_ui::body(ui, fields), _ if crate::equalize_ui::owns(fields) => crate::equalize_ui::body(ui, fields), @@ -1008,6 +1011,7 @@ fn confirm_generic_command(app: &mut PhotocraftApp, d: Dialog) -> Result Result p.committing = true, _ => app.filter_preview = None, } + if result.is_ok() && cmd == "path.toSelection" { + crate::canvas_tool_menu::name_make_selection_step(app, &d.fields, ¶ms, revision); + } if result.is_ok() && cmd == "path.toSelection" && d.fields.contains_key("__deselectPath") From 72dbfd9725241479ce97ab7fcb39a0a9f9ae38d7 Mon Sep 17 00:00:00 2001 From: rmsff <17902130+rmsff@users.noreply.github.com> Date: Tue, 10 Nov 2026 21:30:38 +0300 Subject: [PATCH 34/42] Sharpen: alert on a hidden, locked or group layer (#12952) A Sharpen press on a hidden target layer, a layer with Lock All or Lock Image Pixels, or with a group active opens the reference application's modal alert instead of a status-bar message. A tool with a colour-mode alert now gets it first and falls through to the layer checks otherwise; the Dodge tool still has no layer alerts. --- crates/ui-egui/src/tools/brush_refusal.rs | 31 +++++++++++++++-------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/tools/brush_refusal.rs b/crates/ui-egui/src/tools/brush_refusal.rs index 38ae8e4f051..bcdc8af4c4c 100644 --- a/crates/ui-egui/src/tools/brush_refusal.rs +++ b/crates/ui-egui/src/tools/brush_refusal.rs @@ -19,8 +19,8 @@ pub const INDEXED: &str = "Could not use the {tool} because it does not work wit pub const BITMAP: &str = "Could not use the {tool} because it does not work with Bitmap images (convert image to Grayscale mode to edit)."; /// The tool's name in the colour-mode alerts, for the tools whose wording was measured: the Dodge -/// and Sharpen tools. Kept apart from [`tool_name`]: the layer alerts aren't wired for these tools -/// yet (#12685, #12952). +/// and Sharpen tools. Kept apart from [`tool_name`]: the layer alerts aren't wired for the Dodge +/// tool yet (#12685). fn mode_tool_name(tool: Tool) -> Option<&'static str> { match tool { Tool::Dodge => Some(tl!("dodge tool")), @@ -29,10 +29,12 @@ fn mode_tool_name(tool: Tool) -> Option<&'static str> { } } -/// The tool's name in the alerts, for the tools whose wording was measured: the Brush. +/// The tool's name in the alerts, for the tools whose wording was measured: the Brush and the +/// Sharpen tool (#12952). pub fn tool_name(tool: Tool) -> Option<&'static str> { match tool { Tool::Brush => Some(tl!("brush tool")), + Tool::Sharpen => Some(tl!("sharpen tool")), _ => None, } } @@ -40,14 +42,15 @@ pub fn tool_name(tool: Tool) -> Option<&'static str> { /// The alert a press with `tool` gets, if any. `hidden` is the press-time hidden-target refusal /// (`canvas::tool_input`), which this only words; the lock and the group are checked here. Lock /// transparent pixels is no refusal, and a group's targeted mask paints. A tool with a -/// [`mode_tool_name`] gets only its colour-mode alert, in an Indexed Color or Bitmap document. +/// [`mode_tool_name`] gets its colour-mode alert first, in an Indexed Color or Bitmap document. pub fn alert(app: &PhotocraftApp, tool: Tool, hidden: bool) -> Option { - if let Some(name) = mode_tool_name(tool) { - let template = match app.session.active()?.doc.mode { - photocraft_doc::ColorMode::Indexed => INDEXED, - photocraft_doc::ColorMode::Bitmap => BITMAP, - _ => return None, - }; + if let Some(name) = mode_tool_name(tool) + && let Some(template) = match app.session.active()?.doc.mode { + photocraft_doc::ColorMode::Indexed => Some(INDEXED), + photocraft_doc::ColorMode::Bitmap => Some(BITMAP), + _ => None, + } + { return Some(crate::i18n::fmt(tl!(template), &[("tool", name)])); } let name = tool_name(tool)?; @@ -61,7 +64,7 @@ pub fn alert(app: &PhotocraftApp, tool: Tool, hidden: bool) -> Option { } if layer.is_group() { GROUP - } else if st.doc.effective_locks(layer.id).all { + } else if locked(st.doc.effective_locks(layer.id), tool) { LOCKED } else { return None; @@ -70,6 +73,12 @@ pub fn alert(app: &PhotocraftApp, tool: Tool, hidden: bool) -> Option { Some(crate::i18n::fmt(tl!(template), &[("tool", name)])) } +/// Whether `locks` refuse `tool`: Lock All, and for the Sharpen tool Lock Image Pixels as well +/// (measured for it; the Brush keeps today's behaviour there). +fn locked(locks: photocraft_doc::Locks, tool: Tool) -> bool { + locks.all || (tool == Tool::Sharpen && locks.pixels) +} + /// Opens the alert: ordinary dialog state, listed by `ui.inspect` and closed by `ui.dialog.confirm`. pub fn prompt(app: &mut PhotocraftApp, message: &str) { app.ui.open_dialog(DialogKind::Error, json!({ "message": message }).as_object().cloned().unwrap_or_default()); From 8122d83e7ccedee7654a29dc95acaf41578e26de Mon Sep 17 00:00:00 2001 From: rmsff <17902130+rmsff@users.noreply.github.com> Date: Tue, 10 Nov 2026 22:08:14 +0300 Subject: [PATCH 35/42] Test the Make Selection dialog's groups, greyed operations and History step (#12917) --- crates/ui-egui/src/canvas/canvas_tool_menu.rs | 3 + .../make_selection_dialog_tests.rs | 210 ++++++++++++++++++ 2 files changed, 213 insertions(+) create mode 100644 crates/ui-egui/src/canvas/canvas_tool_menu/make_selection_dialog_tests.rs diff --git a/crates/ui-egui/src/canvas/canvas_tool_menu.rs b/crates/ui-egui/src/canvas/canvas_tool_menu.rs index f544ebd6b00..17393483f1a 100644 --- a/crates/ui-egui/src/canvas/canvas_tool_menu.rs +++ b/crates/ui-egui/src/canvas/canvas_tool_menu.rs @@ -1497,3 +1497,6 @@ mod hand_menu_entries_tests; #[cfg(test)] mod pen_free_transform_label_tests; + +#[cfg(test)] +mod make_selection_dialog_tests; diff --git a/crates/ui-egui/src/canvas/canvas_tool_menu/make_selection_dialog_tests.rs b/crates/ui-egui/src/canvas/canvas_tool_menu/make_selection_dialog_tests.rs new file mode 100644 index 00000000000..183303632a3 --- /dev/null +++ b/crates/ui-egui/src/canvas/canvas_tool_menu/make_selection_dialog_tests.rs @@ -0,0 +1,210 @@ +//! #12917: Make Selection from a path is Photoshop's dialog: Rendering (Feather Radius in pixels, +//! Anti-aliased) and Operation (New / Add to / Subtract from / Intersect with Selection, the last +//! three greyed without a selection). OK with the defaults selects inside the path in one +//! Selection Change History step; each Operation runs `path.toSelection` with its mode. ⌘↩ and the +//! combining operations keep today's Make Selection step (not measured). + +use egui::accesskit::{Role, Toggled}; +use egui_kittest::kittest::{NodeT, Queryable}; +use egui_kittest::{Harness, Node}; +use serde_json::{Value, json}; + +use super::make_selection; +use super::tests::choose_open; +use crate::PhotocraftApp; +use crate::state::Tool; + +const OPERATIONS: [&str; 4] = ["New Selection", "Add to Selection", "Subtract from Selection", "Intersect with Selection"]; +const MODES: [&str; 4] = ["replace", "add", "subtract", "intersect"]; + +/// A document with the reference's closed triangle as the Work Path, with or without a selection +/// (a rectangle the triangle overlaps). +fn app(selection: bool) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 500})).unwrap(); + let knots = json!([[100, 300], [300, 300], [200, 450]]); + app.run("path.set", json!({"name": "work", "path": {"subpaths": [{"closed": true, "knots": knots}]}})).unwrap(); + if selection { + app.run("select.rect", json!({"x": 20, "y": 20, "width": 200, "height": 320})).unwrap(); + } + app.ui.tool = Tool::Pen; + app +} + +fn draw(ui: &mut egui::Ui, app: &mut PhotocraftApp) { + if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + crate::dialogs::show(app, ui.ctx()); + } +} + +/// The Pen canvas menu's Make Selection… dialog, drawn as the window shows it. +fn dialog(mut app: PhotocraftApp) -> Harness<'static, PhotocraftApp> { + choose_open(&mut app, "path.toSelection"); + assert_eq!(app.ui.dialogs.len(), 1, "Make Selection… opened its dialog"); + let mut h = Harness::builder().with_size(egui::vec2(900.0, 700.0)).build_ui_state(draw, app); + PhotocraftApp::setup_context(&h.ctx, Default::default()); + h.run_steps(4); + h +} + +fn click(h: &mut Harness<'_, PhotocraftApp>, label: &str) { + h.get_by_label(label).click(); + h.run_steps(3); +} + +fn steps(app: &PhotocraftApp) -> Vec { + app.session.active().unwrap().history.entries().iter().map(|e| e.to_string()).collect() +} + +fn last_step(app: &PhotocraftApp) -> Option { + steps(app).last().cloned() +} + +fn selection_bounds(app: &PhotocraftApp) -> Option<[i32; 4]> { + let r = app.session.active().unwrap().doc.selection.as_ref()?.content_bounds(); + Some([r.x0, r.y0, r.x1, r.y1]) +} + +/// The params of the last command run. +fn last_params(app: &PhotocraftApp) -> Value { + let (id, params) = app.session.journal.last().cloned().unwrap(); + assert_eq!(id, "path.toSelection"); + params +} + +fn enabled(h: &Harness<'_, PhotocraftApp>, label: &str) -> bool { + !h.get_by_label(label).accesskit_node().is_disabled() +} + +fn feather_field<'h>(h: &'h Harness<'_, PhotocraftApp>) -> Node<'h> { + h.get_all_by_label("Feather Radius:").find(|n| n.accesskit_node().role() == Role::SpinButton).expect("the Feather Radius number field") +} + +#[test] +fn the_dialog_shows_the_rendering_and_operation_groups() { + let h = dialog(app(false)); + for label in ["Make Selection", "Rendering", "pixels", "Anti-aliased", "Operation", "OK", "Cancel"] { + assert!(h.query_by_label(label).is_some(), "{label} is shown"); + } + for old in ["Feather", "Anti Alias", "Mode"] { + assert!(h.query_by_label(old).is_none(), "the schema dialog's {old} is gone"); + } + assert_eq!(h.get_by_label("Anti-aliased").accesskit_node().toggled(), Some(Toggled::True), "Anti-aliased is on"); + assert_eq!(h.get_by_label("New Selection").accesskit_node().toggled(), Some(Toggled::True), "New Selection is chosen"); + assert_eq!(feather_field(&h).accesskit_node().numeric_value(), Some(0.0), "Feather Radius is 0"); + let tops: Vec = OPERATIONS.iter().map(|label| h.get_by_label(label).rect().top()).collect(); + assert!(tops.windows(2).all(|w| w[0] < w[1]), "the operations are listed in order: {tops:?}"); + let rendering = h.get_by_label("Rendering").rect().top(); + let operation = h.get_by_label("Operation").rect().top(); + let feather = feather_field(&h).rect().top(); + assert!(rendering < feather && feather < operation && operation < tops[0], "Rendering holds Feather Radius, Operation the radio buttons"); +} + +#[test] +fn the_options_bar_button_opens_the_same_dialog() { + let mut app = app(false); + make_selection(&mut app).unwrap(); + let fields = &app.ui.dialogs.last().unwrap().fields; + assert!(super::owns_make_selection(fields)); + assert_eq!(fields.get("__command"), Some(&json!("path.toSelection"))); + assert!(fields.contains_key("__deselectPath"), "OK deselects the path, as from the canvas menu"); +} + +#[test] +fn without_a_selection_only_new_selection_is_available() { + let h = dialog(app(false)); + assert!(enabled(&h, "New Selection")); + for label in &OPERATIONS[1..] { + assert!(!enabled(&h, label), "{label} is greyed out without a selection"); + } +} + +#[test] +fn with_a_selection_every_operation_is_available() { + let h = dialog(app(true)); + for label in OPERATIONS { + assert!(enabled(&h, label), "{label} is available with a selection"); + } +} + +/// A combining mode the dialog was given (by automation, or before the selection went) falls +/// back to New Selection when there is nothing to combine with. +#[test] +fn without_a_selection_a_combining_mode_falls_back_to_new_selection() { + let mut h = dialog(app(false)); + h.state_mut().ui.dialogs.last_mut().unwrap().fields.insert("mode".into(), json!("subtract")); + h.run_steps(2); + assert_eq!(h.get_by_label("New Selection").accesskit_node().toggled(), Some(Toggled::True)); + click(&mut h, "OK"); + assert_eq!(last_params(h.state()).get("mode"), Some(&json!("replace"))); + assert_eq!(selection_bounds(h.state()), Some([100, 300, 300, 450])); +} + +#[test] +fn ok_with_the_defaults_selects_the_triangle_in_one_selection_change_step() { + let mut h = dialog(app(false)); + let before = steps(h.state()); + click(&mut h, "OK"); + assert!(h.state().ui.dialogs.is_empty(), "OK closed the dialog"); + assert_eq!(selection_bounds(h.state()), Some([100, 300, 300, 450])); + let after = steps(h.state()); + assert_eq!(after.len(), before.len() + 1, "one History step: {after:?}"); + assert_eq!(after[..before.len()], before[..], "the earlier steps keep their names"); + assert_eq!(after.last().map(String::as_str), Some("Selection Change")); + assert_eq!(h.state().ui.selected_path, None, "OK deselects the path, as ⌘↩ does"); +} + +#[test] +fn each_operation_runs_make_selection_with_its_mode() { + for (label, mode) in OPERATIONS.into_iter().zip(MODES) { + let mut h = dialog(app(true)); + click(&mut h, label); + click(&mut h, "OK"); + assert_eq!(last_params(h.state()).get("mode").and_then(Value::as_str), Some(mode), "{label}"); + let want = if mode == "replace" { "Selection Change" } else { "Make Selection" }; + assert_eq!(last_step(h.state()).as_deref(), Some(want), "{label}: the combining operations keep today's step name"); + } +} + +#[test] +fn a_typed_feather_radius_is_sent() { + let mut h = dialog(app(false)); + feather_field(&h).click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.event(egui::Event::Text("4".into())); + h.key_press(egui::Key::Tab); + h.run_steps(3); + click(&mut h, "OK"); + assert_eq!(last_params(h.state()).get("feather").and_then(Value::as_f64), Some(4.0)); +} + +#[test] +fn cancel_changes_nothing() { + let mut h = dialog(app(true)); + let (selection, before) = (selection_bounds(h.state()), steps(h.state())); + click(&mut h, "Intersect with Selection"); + click(&mut h, "Cancel"); + assert!(h.state().ui.dialogs.is_empty(), "Cancel closed the dialog"); + assert_eq!(selection_bounds(h.state()), selection); + assert_eq!(steps(h.state()), before); +} + +/// ⌘↩ runs the same command without the dialog: its step keeps today's name (not measured). +#[test] +fn cmd_enter_keeps_the_make_selection_step() { + let mut app = app(false); + crate::vector_ui::path_to_selection(&mut app, json!({})).unwrap(); + assert_eq!(selection_bounds(&app), Some([100, 300, 300, 450])); + assert_eq!(last_step(&app).as_deref(), Some("Make Selection")); +} + +/// OK that adds no step (the path went while the dialog was open) renames nothing. +#[test] +fn ok_that_fails_does_not_rename_the_previous_step() { + let mut h = dialog(app(true)); + h.state_mut().run("path.delete", json!({"name": "work"})).unwrap(); + let before = steps(h.state()); + click(&mut h, "OK"); + assert_eq!(steps(h.state()), before); +} From 551f9d236952018dcb64721d30808e92e810e286 Mon Sep 17 00:00:00 2001 From: rmsff <17902130+rmsff@users.noreply.github.com> Date: Tue, 10 Nov 2026 21:30:38 +0300 Subject: [PATCH 36/42] Test the Sharpen tool's layer alerts Makes the Brush alert tests' helpers pub(super) and reuses them. --- .../ui-egui/src/brush_refusal_alert_tests.rs | 12 +-- .../src/sharpen_refusal_alert_tests.rs | 95 +++++++++++++++++++ crates/ui-egui/src/tools/brush_refusal.rs | 4 + 3 files changed, 105 insertions(+), 6 deletions(-) create mode 100644 crates/ui-egui/src/sharpen_refusal_alert_tests.rs diff --git a/crates/ui-egui/src/brush_refusal_alert_tests.rs b/crates/ui-egui/src/brush_refusal_alert_tests.rs index 7aa6bee9fac..a1e32af6b5c 100644 --- a/crates/ui-egui/src/brush_refusal_alert_tests.rs +++ b/crates/ui-egui/src/brush_refusal_alert_tests.rs @@ -9,7 +9,7 @@ use super::*; use crate::canvas::{ToolEvent, tool_event}; /// A 64 × 64 document with a painted layer active, black foreground, `tool`. -fn app(tool: Tool) -> PhotocraftApp { +pub(super) fn app(tool: Tool) -> PhotocraftApp { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); app.run("layer.new.layer", json!({})).unwrap(); @@ -20,26 +20,26 @@ fn app(tool: Tool) -> PhotocraftApp { app } -fn active(app: &PhotocraftApp) -> u64 { +pub(super) fn active(app: &PhotocraftApp) -> u64 { app.session.active().unwrap().active_layer.unwrap().0 } -fn steps(app: &PhotocraftApp) -> usize { +pub(super) fn steps(app: &PhotocraftApp) -> usize { app.session.active().unwrap().history.past_len() } /// A press, a short drag and the release with the active tool. -fn stroke(app: &mut PhotocraftApp) { +pub(super) fn stroke(app: &mut PhotocraftApp) { tool_event(app, ToolEvent::Down { x: 20.0, y: 32.0, pressure: 1.0 }, Modifiers::NONE); tool_event(app, ToolEvent::Move { x: 44.0, y: 32.0, pressure: 1.0 }, Modifiers::NONE); tool_event(app, ToolEvent::Up { x: 44.0, y: 32.0 }, Modifiers::NONE); } -fn alerts(app: &PhotocraftApp) -> Vec { +pub(super) fn alerts(app: &PhotocraftApp) -> Vec { app.ui.dialogs.iter().filter(|d| d.kind == DialogKind::Error).filter_map(|d| d.fields.get("message").and_then(Value::as_str).map(str::to_string)).collect() } -fn refused(app: &mut PhotocraftApp, want: &str) { +pub(super) fn refused(app: &mut PhotocraftApp, want: &str) { let before = steps(app); stroke(app); assert_eq!(alerts(app), [want], "the alert, once"); diff --git a/crates/ui-egui/src/sharpen_refusal_alert_tests.rs b/crates/ui-egui/src/sharpen_refusal_alert_tests.rs new file mode 100644 index 00000000000..7e82ad75c6f --- /dev/null +++ b/crates/ui-egui/src/sharpen_refusal_alert_tests.rs @@ -0,0 +1,95 @@ +//! #12952: when the Sharpen tool can't work on the layer (hidden target layer, Lock All, Lock Image +//! Pixels, a group's pixels), a press opens the reference application's alert with OK and changes +//! nothing; Lock transparent pixels still sharpens. The Brush keeps its alerts, the Dodge tool its +//! colour-mode alert only. + +use serde_json::json; + +use super::brush_refusal_alert_tests::{active, alerts, app, refused, steps, stroke}; +use super::*; +use crate::control::{ControlRequest, Outcome, handle}; + +#[test] +fn a_hidden_target_layer() { + let mut app = app(Tool::Sharpen); + let id = active(&app); + app.run("layer.setProps", json!({"layer": id, "visible": false})).unwrap(); + refused(&mut app, "Could not use the sharpen tool because the target layer is hidden."); + assert!(app.ui.status.is_empty() || !app.ui.status_error, "no status-bar error as well: {:?}", app.ui.status); +} + +#[test] +fn lock_all_and_lock_image_pixels() { + for lock in ["all", "pixels"] { + let mut app = app(Tool::Sharpen); + app.run("layer.lockLayers", json!({ lock: true })).unwrap(); + refused(&mut app, "Could not use the sharpen tool because the layer is locked."); + } +} + +#[test] +fn a_group_is_active() { + let mut app = app(Tool::Sharpen); + app.run("layer.new.group", json!({})).unwrap(); + refused(&mut app, "Could not use the sharpen tool because the pixels in a group cannot be edited without merging the group."); +} + +#[test] +fn the_alert_is_listed_and_confirmed_over_the_control_channel() { + let ctx = egui::Context::default(); + let mut app = app(Tool::Sharpen); + app.run("layer.lockLayers", json!({"pixels": true})).unwrap(); + stroke(&mut app); + let mut call = |method: &str, params: serde_json::Value| { + let (req, _rx) = ControlRequest::new(method, params); + match handle(&mut app, &ctx, &req) { + Outcome::Done(v) => v, + _ => panic!("{method}: expected an immediate reply"), + } + }; + let inspect = call("ui.inspect", json!({})); + let dialog = &inspect["result"]["dialogs"][0]; + assert_eq!(dialog["fields"]["message"], "Could not use the sharpen tool because the layer is locked.", "{inspect}"); + assert_eq!(call("ui.dialog.confirm", json!({"dialog": dialog["id"]}))["ok"], true); + assert!(alerts(&app).is_empty()); +} + +#[test] +fn lock_transparent_pixels_still_sharpens() { + let mut app = app(Tool::Sharpen); + app.run("layer.lockLayers", json!({"transparency": true})).unwrap(); + let before = steps(&app); + stroke(&mut app); + assert!(alerts(&app).is_empty()); + assert_eq!(steps(&app), before + 1, "the stroke was applied"); +} + +#[test] +fn the_colour_mode_alert_comes_first() { + // A hidden layer in an Indexed Color document: the mode alert, as before this change. + let mut app = app(Tool::Sharpen); + app.run("image.mode.indexedColor", json!({"palette": "exact", "dither": "none", "forced": "none"})).unwrap(); + let id = active(&app); + app.run("layer.setProps", json!({"layer": id, "visible": false})).unwrap(); + refused(&mut app, "Could not use the sharpen tool because it does not work with Indexed Color images (convert image to RGB Color mode to edit)."); +} + +#[test] +fn the_brush_and_the_dodge_tool_keep_todays_behaviour() { + // The Brush: no alert for Lock Image Pixels. + let mut app = app(Tool::Brush); + app.run("layer.lockLayers", json!({"pixels": true})).unwrap(); + stroke(&mut app); + assert!(alerts(&app).is_empty()); + // The Dodge tool in an RGB document: no layer alerts, the status bar says a hidden target. + let mut app = self::app(Tool::Dodge); + let id = active(&app); + app.run("layer.setProps", json!({"layer": id, "visible": false})).unwrap(); + stroke(&mut app); + assert!(alerts(&app).is_empty()); + assert_eq!(app.ui.status, photocraft_engine::hidden_target::HIDDEN); + let mut app = self::app(Tool::Dodge); + app.run("layer.lockLayers", json!({"all": true})).unwrap(); + assert_eq!(alert(&app, Tool::Dodge, false), None); + assert_eq!(tool_name(Tool::Dodge), None); +} diff --git a/crates/ui-egui/src/tools/brush_refusal.rs b/crates/ui-egui/src/tools/brush_refusal.rs index bcdc8af4c4c..ba80626128b 100644 --- a/crates/ui-egui/src/tools/brush_refusal.rs +++ b/crates/ui-egui/src/tools/brush_refusal.rs @@ -87,3 +87,7 @@ pub fn prompt(app: &mut PhotocraftApp, message: &str) { #[cfg(test)] #[path = "../brush_refusal_alert_tests.rs"] mod brush_refusal_alert_tests; + +#[cfg(test)] +#[path = "../sharpen_refusal_alert_tests.rs"] +mod sharpen_refusal_alert_tests; From 45b2b364332a2a4342a47aa9be092fbe9a4cfe21 Mon Sep 17 00:00:00 2001 From: rmsff <17902130+rmsff@users.noreply.github.com> Date: Tue, 10 Nov 2026 20:23:41 +0300 Subject: [PATCH 37/42] Delete Anchor Point: Escape clears selected anchors, then the targeted path (#12773) With the Delete Anchor Point tool, Escape with no running operation first clears anchors selected on the saved path targeted in the Paths panel, then deselects that path, so its outline and anchors go and a click deletes nothing. It waits while the path's name is typed in the Paths panel, where Escape cancels the rename. Full screen and a pixel selection still take Escape first; the Work Path and a layer's path keep today's Escape. --- crates/ui-egui/src/input/shortcuts.rs | 20 +++++++++++++++++++ crates/ui-egui/src/tools/vector_ui.rs | 1 + .../src/tools/vector_ui/paths_panel.rs | 5 +++++ 3 files changed, 26 insertions(+) diff --git a/crates/ui-egui/src/input/shortcuts.rs b/crates/ui-egui/src/input/shortcuts.rs index d128347dfa3..7ce3fb85f5e 100644 --- a/crates/ui-egui/src/input/shortcuts.rs +++ b/crates/ui-egui/src/input/shortcuts.rs @@ -913,6 +913,26 @@ fn handle_escape_and_view_keys(app: &mut PhotocraftApp, ctx: &egui::Context) { } return; } + // Delete Anchor Point (#12773): Esc first clears anchors selected on the saved path targeted in + // the Paths panel, then deselects that path, so clicks edit nothing. Not while its name is typed + // in the panel: egui has already dropped the field's focus, and the panel cancels on Esc. + if !esc_taken + && app.ui.tool == Tool::DeleteAnchorPoint + && !crate::vector_ui::path_renaming(app, ctx) + && let Some((index, _)) = crate::vector_ui::selected_saved_path_index(app) + { + let ds = &app.ui.direct_selection; + let selected = ds.target == Some(crate::direct_select::PathRef::Saved(index)) && (!ds.anchors.is_empty() || ds.segment.is_some()); + if pressed(Key::Escape) { + if selected { + app.ui.direct_selection.anchors.clear(); + app.ui.direct_selection.segment = None; + } else { + app.ui.selected_path = None; + } + return; + } + } // + / − pick a Path Operation with the Pen tools and Path Selection (`path_components`)… crate::path_components::handle_keys(app, ctx); // … and otherwise ⇧+ / ⇧− step the blend mode and ⇧⌥ letters pick one (`blend_keys`). Before the diff --git a/crates/ui-egui/src/tools/vector_ui.rs b/crates/ui-egui/src/tools/vector_ui.rs index 24e1fce37f9..87e8888e984 100644 --- a/crates/ui-egui/src/tools/vector_ui.rs +++ b/crates/ui-egui/src/tools/vector_ui.rs @@ -50,6 +50,7 @@ pub(crate) use path_ops::{ }; #[cfg(test)] use paths_panel::path_context_actions; +pub(crate) use paths_panel::path_renaming; pub use paths_panel::{PathEntry, PathRow, path_rows, paths_footer, paths_panel}; #[cfg(test)] pub(crate) use pen::over_first_anchor; diff --git a/crates/ui-egui/src/tools/vector_ui/paths_panel.rs b/crates/ui-egui/src/tools/vector_ui/paths_panel.rs index 1d02f3fdd7a..a701e76941e 100644 --- a/crates/ui-egui/src/tools/vector_ui/paths_panel.rs +++ b/crates/ui-egui/src/tools/vector_ui/paths_panel.rs @@ -111,6 +111,11 @@ fn rename_id(doc: &Document) -> egui::Id { egui::Id::unique(("path-rename", doc.id.0)) } +/// Is a path's name being typed in the active document's Paths panel? Esc belongs to its field. +pub(crate) fn path_renaming(app: &PhotocraftApp, ctx: &egui::Context) -> bool { + app.session.active().is_some_and(|st| ctx.data(|d| d.get_temp::(rename_id(&st.doc)).is_some())) +} + /// Commands offered by a Paths row's context menu. The row's path is passed explicitly so a /// right-click acts on that row even when another path is selected in the panel. `layer` is the /// layer a `PathRow::Layer` row belongs to (the active layer). From 00eed2243f9cd577b297935dfb3413691ec8c32c Mon Sep 17 00:00:00 2001 From: rmsff <17902130+rmsff@users.noreply.github.com> Date: Tue, 10 Nov 2026 20:23:41 +0300 Subject: [PATCH 38/42] Test Escape with the Delete Anchor Point tool (#12773) --- crates/ui-egui/src/tools/anchor_tools.rs | 3 + .../delete_anchor_escape_tests.rs | 144 ++++++++++++++++++ .../ui-egui/src/tools/anchor_tools/tests.rs | 4 +- 3 files changed, 149 insertions(+), 2 deletions(-) create mode 100644 crates/ui-egui/src/tools/anchor_tools/delete_anchor_escape_tests.rs diff --git a/crates/ui-egui/src/tools/anchor_tools.rs b/crates/ui-egui/src/tools/anchor_tools.rs index 1fa08a7c9d4..c6279ec9546 100644 --- a/crates/ui-egui/src/tools/anchor_tools.rs +++ b/crates/ui-egui/src/tools/anchor_tools.rs @@ -195,3 +195,6 @@ mod tests; #[cfg(test)] mod add_anchor_delete_key_tests; + +#[cfg(test)] +mod delete_anchor_escape_tests; diff --git a/crates/ui-egui/src/tools/anchor_tools/delete_anchor_escape_tests.rs b/crates/ui-egui/src/tools/anchor_tools/delete_anchor_escape_tests.rs new file mode 100644 index 00000000000..2fd81fdbd2a --- /dev/null +++ b/crates/ui-egui/src/tools/anchor_tools/delete_anchor_escape_tests.rs @@ -0,0 +1,144 @@ +//! #12773: with Delete Anchor Point, Esc first clears anchors selected on the saved path targeted +//! in the Paths panel, then deselects that path, so its outline and anchors go and clicks delete +//! nothing. Esc never adds a History step. + +use egui::{Key, Modifiers, vec2}; +use egui_kittest::{Harness, kittest::Queryable}; +use photocraft_doc::vector::Path; +use serde_json::json; + +use super::tests::{click, steps}; +use crate::PhotocraftApp; +use crate::direct_select::{PathRef, active_paths, candidates}; +use crate::state::Tool; + +/// The issue's document: 800 x 600 with the saved path "Path 1", a corner square with an anchor +/// at (300, 300), targeted in the Paths panel. +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 800, "height": 600, "background": "white"})).unwrap(); + let square = json!({"subpaths": [{"closed": true, "knots": [[100, 300], [300, 300], [300, 500], [100, 500]]}]}); + app.run("path.set", json!({"name": "Path 1", "path": square})).unwrap(); + app.sync_views(); + app.ui.tool = Tool::DeleteAnchorPoint; + app.ui.selected_path = Some("Path 1".into()); + app +} + +fn escape(app: &mut PhotocraftApp) { + let ctx = egui::Context::default(); + let key = egui::Event::Key { key: Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }; + ctx.begin_pass(egui::RawInput { events: vec![key], ..Default::default() }); + crate::shortcuts::handle(app, &ctx); + ctx.end_pass().textures_delta.clear(); +} + +fn path_1(app: &PhotocraftApp) -> Path { + app.session.active().unwrap().doc.paths.iter().find(|p| p.name == "Path 1").unwrap().path.clone() +} + +#[test] +fn two_escapes_deselect_path_1_and_a_click_then_deletes_nothing() { + let mut app = app(); + let (before, n) = (path_1(&app), steps(&app)); + escape(&mut app); + escape(&mut app); + assert_eq!(app.ui.selected_path, None, "Path 1 is no longer selected in the Paths panel"); + assert!(candidates(&app).is_empty(), "no outline or anchors are drawn"); + assert_eq!(steps(&app), n, "Esc adds no History step"); + click(&mut app, [300.0, 300.0], Modifiers::NONE); + assert_eq!(path_1(&app), before); + assert_eq!(steps(&app), n, "the click adds no History step"); +} + +#[test] +fn the_first_escape_clears_the_selected_anchor_and_the_second_deselects_the_path() { + let mut app = app(); + // ⌘ is Direct Selection while held: it selects the anchor instead of deleting it. + click(&mut app, [300.0, 300.0], Modifiers::COMMAND); + assert_eq!((app.ui.direct_selection.target, app.ui.direct_selection.anchors.clone()), (Some(PathRef::Saved(0)), vec![[0, 1]])); + let n = steps(&app); + escape(&mut app); + assert!(app.ui.direct_selection.anchors.is_empty(), "the first Esc clears the anchor"); + assert_eq!(app.ui.selected_path.as_deref(), Some("Path 1"), "and keeps Path 1 selected"); + assert!(!active_paths(&app).is_empty(), "its outline stays"); + escape(&mut app); + assert_eq!(app.ui.selected_path, None, "the second Esc deselects Path 1"); + assert_eq!(steps(&app), n); +} + +#[test] +fn a_targeted_work_path_keeps_todays_escape() { + let mut app = app(); + let line = json!({"subpaths": [{"knots": [[100, 100], [200, 100]]}]}); + app.run("path.set", json!({"name": "work", "path": line})).unwrap(); + app.ui.selected_path = Some("work".into()); + escape(&mut app); + assert_eq!(app.ui.selected_path.as_deref(), Some("work")); +} + +#[test] +fn anchors_selected_on_a_shape_layer_keep_todays_escape() { + let mut app = app(); + app.ui.selected_path = None; + let id = app.run("shape.create", json!({"kind": "rect", "rect": [500, 100, 100, 100], "fill": "#3070c0"})).unwrap()["layer"].as_u64().unwrap(); + click(&mut app, [600.0, 200.0], Modifiers::COMMAND); + let selected = (app.ui.direct_selection.target, app.ui.direct_selection.anchors.clone()); + assert_eq!(selected, (Some(PathRef::Layer(id)), vec![[0, 2]])); + escape(&mut app); + assert_eq!((app.ui.direct_selection.target, app.ui.direct_selection.anchors.clone()), selected); +} + +#[test] +fn with_path_1_targeted_escape_still_leaves_full_screen_and_deselects_pixels_first() { + let mut app = app(); + app.ui.view.screen_mode = "fullScreen".into(); + escape(&mut app); + assert_eq!(app.ui.view.screen_mode, "standard"); + assert_eq!(app.ui.selected_path.as_deref(), Some("Path 1"), "leaving full screen keeps Path 1 selected"); + app.run("select.all", json!({})).unwrap(); + escape(&mut app); + assert!(app.session.active().unwrap().doc.selection.is_none(), "Esc deselects the pixels"); + assert_eq!(app.ui.selected_path.as_deref(), Some("Path 1"), "and keeps Path 1 selected"); +} + +#[test] +fn with_no_path_targeted_escape_still_leaves_full_screen_and_deselects_pixels() { + let mut app = app(); + app.ui.selected_path = None; + app.ui.view.screen_mode = "fullScreen".into(); + escape(&mut app); + assert_eq!(app.ui.view.screen_mode, "standard"); + app.run("select.all", json!({})).unwrap(); + escape(&mut app); + assert!(app.session.active().unwrap().doc.selection.is_none()); +} + +/// Esc while Path 1's name is typed in the Paths panel cancels the rename and keeps Path 1 +/// selected: egui drops the field's focus before the shortcuts run, so the step must wait. +#[test] +fn escape_while_renaming_path_1_cancels_the_rename() { + let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_step_dt(1.0 / 60.0).with_max_steps(64).build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + let mut app = app(); + // Layers | Channels | Paths: the Paths tab. + app.ui.dock_tabs.layers = 2; + app + }); + h.run_steps(8); + let name = h.get_by_label("Path 1").rect().left_center() + vec2(60.0, 0.0); + h.event(egui::Event::PointerMoved(name)); + h.run_steps(30); + for pressed in [true, false, true, false] { + h.event(egui::Event::PointerButton { pos: name, button: egui::PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + h.step(); + } + h.run_steps(3); + h.event(egui::Event::Text("Renamed".into())); + h.run_steps(1); + h.key_press(Key::Escape); + h.run_steps(3); + let names: Vec = h.state().session.active().unwrap().doc.paths.iter().map(|p| p.name.clone()).collect(); + assert_eq!(names, ["Path 1"], "Esc cancels the rename"); + assert_eq!(h.state().ui.selected_path.as_deref(), Some("Path 1")); +} diff --git a/crates/ui-egui/src/tools/anchor_tools/tests.rs b/crates/ui-egui/src/tools/anchor_tools/tests.rs index d7cd7256a4d..bd20264189d 100644 --- a/crates/ui-egui/src/tools/anchor_tools/tests.rs +++ b/crates/ui-egui/src/tools/anchor_tools/tests.rs @@ -34,11 +34,11 @@ fn work(app: &PhotocraftApp) -> Path { app.session.active().unwrap().doc.work_path.clone().unwrap() } -fn steps(app: &PhotocraftApp) -> usize { +pub(super) fn steps(app: &PhotocraftApp) -> usize { app.session.active().unwrap().history.entries().len() } -fn click(app: &mut PhotocraftApp, at: [f64; 2], mods: Modifiers) { +pub(super) fn click(app: &mut PhotocraftApp, at: [f64; 2], mods: Modifiers) { tool_event(app, ToolEvent::Down { x: at[0], y: at[1], pressure: 1.0 }, mods); tool_event(app, ToolEvent::Up { x: at[0], y: at[1] }, mods); } From 847d87bb9bcafe96a242ba05c9edb096aae5ab96 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Wed, 11 Nov 2026 01:08:12 +0100 Subject: [PATCH 39/42] Windows: a pen moves and resizes the window through the custom title bar (#7967) (#12992) * Windows: a pen or a finger moves and resizes the window through the custom title bar (#7967) winit takes pen and touch input as WM_POINTER messages and Windows makes no mouse input from them, so the OS move/size loop that StartDrag/BeginResize start saw no button down and never ran. winit only clears its dragging flag when that loop ends, so after one pen try the mouse could no longer move the window either. A pen or touch press on the title bar's gap or an edge now moves or resizes the window itself (OuterPosition/InnerSize), restores a maximized window under the pen, and stops at the minimum size; the mouse still hands the move to the OS. * Pen title-bar move and resize follow the pen's own screen position (#7967) On Windows winit moves the window asynchronously (SWP_ASYNCWINDOWPOS), so the window position egui reads can be ahead of the window-relative pen position and the drag counted the move twice (an injected pen ran +687/+909 for +200/+120). The tablet hook now keeps the pen's screen pixels from GetPointerPenInfo (ptPixelLocation) while the pen is down, and a PenDrag follows that. A drag that follows the OS position no longer needs egui's pointer position: the parked mouse cursor can leave the window as it moves away, and egui-winit's PointerGone ended the drag after a few steps. It ends on release or when no touch is down. --- apps/photocraft/src/main.rs | 3 +- apps/photocraft/src/tablet.rs | 11 + crates/tablet/src/windows.rs | 45 +++- crates/ui-egui/src/app/frame.rs | 2 + crates/ui-egui/src/lib.rs | 6 +- crates/ui-egui/src/panels/title_bar.rs | 1 + crates/ui-egui/src/panels/titlebar.rs | 198 ++++++++++++++++- crates/ui-egui/src/panels/titlebar/tests.rs | 222 +++++++++++++++++++- crates/ui-egui/src/services.rs | 6 + 9 files changed, 480 insertions(+), 14 deletions(-) diff --git a/apps/photocraft/src/main.rs b/apps/photocraft/src/main.rs index 5461c4cc192..5d1458af08e 100644 --- a/apps/photocraft/src/main.rs +++ b/apps/photocraft/src/main.rs @@ -153,7 +153,7 @@ fn native_options(custom_titlebar: bool) -> eframe::NativeOptions { .with_app_id(APP_ID) .with_title("PhotoCraft") .with_inner_size([1440.0, 900.0]) - .with_min_inner_size([760.0, 480.0]) + .with_min_inner_size(photocraft_ui_egui::MIN_WINDOW_SIZE) .with_drag_and_drop(true) .with_decorations(!custom_titlebar) .with_fullsize_content_view(true) @@ -682,6 +682,7 @@ fn main() -> eframe::Result { tablet::spawn_x11(&app.stylus.feed, display); app.services.right_button_down = tablet::right_button_service(); app.services.pen_end = tablet::pen_end_service(); + app.services.pen_screen_px = tablet::pen_screen_service(); // Paths on the command line (Linux/Windows file associations, `photocraft a.psd`). app.open_paths(&files); if !unreadable_paths.is_empty() { diff --git a/apps/photocraft/src/tablet.rs b/apps/photocraft/src/tablet.rs index 51f7b333efb..26eaf3f3dde 100644 --- a/apps/photocraft/src/tablet.rs +++ b/apps/photocraft/src/tablet.rs @@ -92,6 +92,17 @@ pub fn right_button_service() -> Option { None } +/// Where the pen is on the screen (Windows), for the title bar's pen moves (#7967). +#[cfg(target_os = "windows")] +pub fn pen_screen_service() -> Option { + Some(Box::new(|| photocraft_tablet::windows::pen_screen_px().map(|(x, y)| [x, y]))) +} + +#[cfg(not(target_os = "windows"))] +pub fn pen_screen_service() -> Option { + None +} + /// Which end of the pen is in use (Windows): flipping the pen to its eraser end selects the /// Eraser (#2285). Elsewhere the end arrives with the samples in the stylus feed. #[cfg(target_os = "windows")] diff --git a/crates/tablet/src/windows.rs b/crates/tablet/src/windows.rs index f509cc5a0ff..39d65f99d95 100644 --- a/crates/tablet/src/windows.rs +++ b/crates/tablet/src/windows.rs @@ -11,7 +11,7 @@ #![allow(unsafe_code, clippy::upper_case_acronyms)] -use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU32, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU32, AtomicU64, Ordering}; static BARREL_DOWN: AtomicBool = AtomicBool::new(false); @@ -25,6 +25,10 @@ static PEN_END: AtomicU8 = AtomicU8::new(0); /// The pen end of the last contact [`take_pen_end`] has not read yet, as [`encode_end`] stores it. static CONTACT_END: AtomicU8 = AtomicU8::new(0); +/// Where the pen was on the screen at its last pointer message (`ptPixelLocation`, physical +/// pixels), [`pack_px`]ed, or [`NO_PX`]. Read by [`pen_screen_px`]. +static PEN_PX: AtomicU64 = AtomicU64::new(NO_PX); +const NO_PX: u64 = u64::MAX; fn encode_end(end: Option) -> u8 { match end { @@ -213,15 +217,39 @@ pub fn handle_pointer_message(message: u32, w_param: usize, pen_flags: impl FnOn PEN_END.store(encode_end(next.end), Ordering::Relaxed); PEN_ID.store(next.pen_id.unwrap_or(NO_PEN), Ordering::Relaxed); CONTACT_END.store(encode_end(next.contact), Ordering::Relaxed); + if next.pen_id.is_none() { + PEN_PX.store(NO_PX, Ordering::Relaxed); + } } +/// `GetPointerPenInfo`'s pen flags for a pointer (`None`: not a pen). It also keeps where the pen +/// is on the screen ([`pen_screen_px`]). fn read_pen_flags(pointer_id: u32) -> Option { // SAFETY: `info` is a stack-allocated buffer initialized to zero that outlives the call, and // `pointer_id` comes from a WM_POINTER message; an unknown id makes the call fail, not crash. - unsafe { + let info = unsafe { let mut info: POINTER_PEN_INFO = std::mem::zeroed(); - (GetPointerPenInfo(pointer_id, &mut info) != 0).then_some(info.pen_flags) - } + (GetPointerPenInfo(pointer_id, &mut info) != 0).then_some(info) + }?; + let at = &info.pointer_info.pt_pixel_location; + PEN_PX.store(pack_px(at.x, at.y), Ordering::Relaxed); + Some(info.pen_flags) +} + +fn pack_px(x: i32, y: i32) -> u64 { + (u64::from(x as u32) << 32) | u64::from(y as u32) +} + +fn unpack_px(v: u64) -> Option<(i32, i32)> { + (v != NO_PX).then_some(((v >> 32) as u32 as i32, v as u32 as i32)) +} + +/// Where the pen in range is on the screen, in physical pixels, as of its last pointer message; +/// `None` with no pen in range. Unlike a window-relative position it doesn't depend on where the +/// window is, so the title bar can move the window after the pen (#7967) while Windows is still +/// moving it (winit moves windows asynchronously). The system cursor doesn't follow every pen. +pub fn pen_screen_px() -> Option<(i32, i32)> { + PEN_ID.load(Ordering::Relaxed).ne(&NO_PEN).then(|| unpack_px(PEN_PX.load(Ordering::Relaxed))).flatten() } /// `WH_GETMESSAGE`: the posted pointer messages, as the UI thread takes them from its queue. @@ -311,6 +339,7 @@ impl Drop for Monitor { PEN_END.store(encode_end(None), Ordering::Relaxed); PEN_ID.store(NO_PEN, Ordering::Relaxed); CONTACT_END.store(encode_end(None), Ordering::Relaxed); + PEN_PX.store(NO_PX, Ordering::Relaxed); } } @@ -339,6 +368,14 @@ mod tests { const POINTER_FLAG_INCONTACT: u32 = 0x0004; const POINTER_FLAG_FIRSTBUTTON: u32 = 0x0010; + #[test] + fn pen_screen_positions_round_trip_left_of_and_above_the_primary_monitor() { + for (x, y) in [(0, 0), (1140, 214), (-2400, -300), (i32::MAX, i32::MIN)] { + assert_eq!(unpack_px(pack_px(x, y)), Some((x, y))); + } + assert_eq!(unpack_px(NO_PX), None); + } + #[test] fn plain_pen_contact_is_not_treated_as_barrel() { // Plain tip touch on digitizer: INCONTACT is set, first button may be set, no barrel flag. diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index f007102018c..5fc448ad911 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -246,6 +246,8 @@ impl PhotocraftApp { /// wait modal took the frame (its input, IME and window check already handled). fn ui_body(&mut self, ui: &mut egui::Ui) -> bool { let ctx = ui.ctx().clone(); + // Where a pen dragging the window is on the screen, before the title bar reads it. + titlebar::note_os_pointer(self, &ctx); // A text field's right-click menu, before any field is drawn (text_field_menu.rs). text_field_menu::show(&ctx); // The wheel goes to a focused value field before the canvas or a panel sees it (#5473). diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 730477f0688..e496bb38f97 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -57,7 +57,7 @@ pub mod screenshot; pub mod state; pub mod texel_guard; pub mod theme; -pub use titlebar::{Caption, CaptionFamily, CaptionIcon, CaptionIcons, CaptionStyle, RenderIconFn}; +pub use titlebar::{Caption, CaptionFamily, CaptionIcon, CaptionIcons, CaptionStyle, MIN_WINDOW_SIZE, RenderIconFn}; pub(crate) mod tool_memory; pub mod updates_ui; pub mod widgets; @@ -264,8 +264,8 @@ pub use services::{ AdoptAutosaveFn, AppendTextFn, AutomationCommandFn, AutomationOpenPcraftFn, AutomationReadFn, AutomationWriteFn, AutosaveFn, AutosaveResultsFn, CapsLockFn, CaptionStyleFn, ClipboardGetFn, ClipboardGetSvgFn, ClipboardSetFn, ClipboardUnreadableFn, CursorPosFn, DiscardAutosaveFn, EncodePngFn, ExportFn, ExportSettings, ExternalSvgEditor, ExternalSvgSession, ExternalVectorSave, ExternalVectorSource, FileStamp, FileStampFn, FormatChoices, ImportFn, Inbox, - LastUpdateFn, LoadTextFn, OpenExternalSvgFn, OpenUrlFn, OsEventsFn, PenEndFn, PhotoshopShortcutsFn, PlaceInbox, QuitFn, RecoverFn, Recoverable, - RightButtonDownFn, SameFileFn, SaveFileFn, SaveTextFn, Services, SystemThemeFn, TabletPollFn, WindowFrameFn, WriteFn, + LastUpdateFn, LoadTextFn, OpenExternalSvgFn, OpenUrlFn, OsEventsFn, PenEndFn, PenScreenFn, PhotoshopShortcutsFn, PlaceInbox, QuitFn, RecoverFn, + Recoverable, RightButtonDownFn, SameFileFn, SaveFileFn, SaveTextFn, Services, SystemThemeFn, TabletPollFn, WindowFrameFn, WriteFn, }; pub(crate) use services::{opaque_layer, saves_flat_in_place}; pub use text::bidi_text; diff --git a/crates/ui-egui/src/panels/title_bar.rs b/crates/ui-egui/src/panels/title_bar.rs index fd760ec7111..7da215f3940 100644 --- a/crates/ui-egui/src/panels/title_bar.rs +++ b/crates/ui-egui/src/panels/title_bar.rs @@ -34,6 +34,7 @@ pub fn title_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let gap = egui::Rect::from_x_y_ranges(gap_l.max(full.left())..=gap_r.min(full.right()).max(gap_l), full.y_range()); ui.ctx().data_mut(|d| d.insert_temp(crate::titlebar::modal_drag_area_id(), gap)); let drag = ui.interact(gap, ui.scope_id().with("titledrag"), Sense::click_and_drag()); + crate::titlebar::follow_pen_drag(ui.ctx()); if drag.drag_started_by(egui::PointerButton::Primary) { crate::titlebar::start_os_move(ui.ctx()); } diff --git a/crates/ui-egui/src/panels/titlebar.rs b/crates/ui-egui/src/panels/titlebar.rs index da1e44b452c..79780b68ab6 100644 --- a/crates/ui-egui/src/panels/titlebar.rs +++ b/crates/ui-egui/src/panels/titlebar.rs @@ -10,7 +10,7 @@ //! Breeze's (KDE) or a plain round set elsewhere, with the set of buttons and their side taken //! from the desktop's button layout. The shapes are drawn here, not read from the icon theme. -use egui::{Color32, CursorIcon, Id, LayerId, Order, PointerButton, Pos2, Rect, ResizeDirection, Sense, Stroke, Ui, ViewportCommand, pos2, vec2}; +use egui::{Color32, CursorIcon, Id, LayerId, Order, PointerButton, Pos2, Rect, ResizeDirection, Sense, Stroke, Ui, Vec2, ViewportCommand, pos2, vec2}; use serde_json::json; use crate::PhotocraftApp; @@ -22,6 +22,9 @@ pub const BUTTON_WIDTH: f32 = 46.0; /// (#1581); 8 pt is about a native resize border, and only trims the toolbar buttons' outer 3 pt. const EDGE: f32 = 8.0; const CORNER: f32 = 12.0; +/// The main window's minimum inner size (`apps/photocraft`'s viewport). A pen resize +/// ([`PenDrag`]) stops there, as the OS's own resize does. +pub const MIN_WINDOW_SIZE: Vec2 = vec2(760.0, 480.0); const MODAL_DRAG_AREA: &str = "titlebar-modal-drag-area"; /// Breeze's Close button on hover and press (KDE's Breeze decoration colours). const BREEZE_CLOSE_HOVER: Color32 = Color32::from_rgb(0xff, 0x98, 0xa2); @@ -485,11 +488,198 @@ fn hand_off(ctx: &egui::Context) { /// Move the window from this press. The window manager takes the press of an OS move as it does /// that of a resize and keeps its release, so egui kept the drag: every other move failed, and a /// resize right after one (#5725). The same hand-off ends it. +/// +/// A pen or touch press moves the window itself instead ([`PenDrag`], #7967). pub(crate) fn start_os_move(ctx: &egui::Context) { + if start_pen_drag(ctx, PenDragKind::Move) { + return; + } ctx.send_viewport_cmd(ViewportCommand::StartDrag); hand_off(ctx); } +/// What a pen or touch press on the title bar or an edge does. +#[derive(Clone, Copy, Debug, PartialEq)] +enum PenDragKind { + Move, + Resize(ResizeDirection), +} + +/// A window move or resize by a pen or a finger, done here rather than by the OS (#7967, #11840). +/// winit's `drag_window` / `drag_resize_window` post `WM_NCLBUTTONDOWN`, and Windows' move and +/// size loop follows the mouse button. winit takes pen and touch input as `WM_POINTER` messages +/// (`WindowEvent::Touch`) and Windows makes no mouse input from them, so the loop saw no button +/// down and never ran: the window stayed put. winit only clears its "dragging" flag when that loop +/// ends (`WM_EXITSIZEMOVE`), so after the first pen try it ignored every later `drag_window`, +/// the mouse's too, until restart. A pen press therefore never asks the OS: the window follows +/// the pen through `OuterPosition` / `InnerSize`, from where the pen is on the screen (the +/// window's inner rect plus the pointer), so moving the window under the pen changes nothing. +#[derive(Clone, Copy, Debug)] +struct PenDrag { + kind: PenDragKind, + /// The press in screen points, and the window's outer and inner rects then. `None` while a + /// maximized window restores before it moves. + start: Option<(Pos2, Rect, Rect)>, + /// Where the press was in the maximized window, as a fraction of its width and points from + /// its top: the restored window is placed so the pen holds it at the same spot. + grab: (f32, f32), + /// The last pass this was applied in, so the title bar and the edge zones can both call + /// [`follow_pen_drag`]. + pass: u64, + /// The OS reports where the pen is on the screen ([`note_os_pointer`]): the drag follows that. + /// Otherwise it follows the window's inner rect plus the pointer, which can run ahead. + os: bool, +} + +fn os_pointer_id() -> Id { + Id::unique("titlebar-os-pointer") +} + +/// Read the pen's screen position from the OS for this pass while a pen or a finger is down. A +/// [`PenDrag`] follows that: winit moves the window asynchronously (`SWP_ASYNCWINDOWPOS`), so a +/// pointer position egui got before a move landed, added to the window position read after it, +/// counted the move twice, and the window ran away from the pen (an injected pen on Windows 11: +/// +687, +909 for a +200, +120 stroke). The pen's own pointer messages +/// (`Services::pen_screen_px`) say where it is; failing that the OS cursor +/// (`Services::cursor_pos`, relative to the window's inner rect, so the sum is the screen +/// position), which a pen doesn't always move. Call before the title bar and the edge zones. +pub(crate) fn note_os_pointer(app: &mut PhotocraftApp, ctx: &egui::Context) { + if !PEN_DRAG || !ctx.input(|i| i.any_touches()) { + return; + } + let pen = app.services.pen_screen_px.as_ref().and_then(|f| f()).map(|[x, y]| pos2(x as f32, y as f32) / ctx.pixels_per_point()); + let cursor = || { + let inner = ctx.input(|i| i.viewport().inner_rect)?; + app.services.cursor_pos.as_mut().and_then(|f| f(ctx)).map(|at| inner.min + at.to_vec2()) + }; + let Some(at) = pen.or_else(cursor) else { return }; + let pass = ctx.cumulative_pass_nr(); + ctx.data_mut(|d| d.insert_temp(os_pointer_id(), (pass, at))); +} + +/// The screen position [`note_os_pointer`] read this pass. +fn os_pointer(ctx: &egui::Context) -> Option { + let (pass, at) = ctx.data(|d| d.get_temp::<(u64, Pos2)>(os_pointer_id()))?; + (pass == ctx.cumulative_pass_nr()).then_some(at) +} + +fn pen_drag_id() -> Id { + Id::unique("titlebar-pen-drag") +} + +/// Only Windows needs it, and only Windows can place a window from the app everywhere (Wayland +/// lets no client place its window). Tests run it on every platform. +const PEN_DRAG: bool = cfg!(any(target_os = "windows", test)); + +/// Start a [`PenDrag`] if the press is a pen's or a finger's: true if it took the press. +fn start_pen_drag(ctx: &egui::Context, kind: PenDragKind) -> bool { + if !PEN_DRAG || !ctx.input(|i| i.any_touches()) { + return false; + } + let (inner, outer, maximized) = ctx.input(|i| (i.viewport().inner_rect, i.viewport().outer_rect, i.viewport().maximized.unwrap_or(false))); + let (Some(inner), Some(outer), Some(press)) = (inner, outer, ctx.input(|i| i.pointer.press_origin().or(i.pointer.latest_pos()))) else { + return false; + }; + let pass = ctx.cumulative_pass_nr(); + // Trust the OS's position only if it is where the pointer is: a finger leaves the cursor + // behind. + let latest = ctx.input(|i| i.pointer.latest_pos()).unwrap_or(press); + let os_now = os_pointer(ctx).filter(|s| (*s - (inner.min + latest.to_vec2())).length() <= 8.0); + let os = os_now.is_some(); + let drag = if maximized { + if kind != PenDragKind::Move { + return false; + } + ctx.send_viewport_cmd(ViewportCommand::Maximized(false)); + PenDrag { kind, start: None, grab: (press.x / inner.width().max(1.0), press.y), pass, os } + } else { + let at = os_now.map_or(inner.min + press.to_vec2(), |s| s - (latest - press)); + PenDrag { kind, start: Some((at, outer, inner)), grab: (0.0, 0.0), pass, os } + }; + ctx.data_mut(|d| d.insert_temp(pen_drag_id(), drag)); + true +} + +/// Move or resize the window after the pen ([`PenDrag`]); ends with the press. Every pass, from +/// the title bar and the edge zones. +pub(crate) fn follow_pen_drag(ctx: &egui::Context) { + let Some(mut drag) = ctx.data(|d| d.get_temp::(pen_drag_id())) else { return }; + let pass = ctx.cumulative_pass_nr(); + if drag.pass == pass { + return; + } + drag.pass = pass; + // The pen is down while egui has the press and a touch. egui's pointer can be gone meanwhile: + // the mouse cursor, parked where the window was, leaves the window as it moves away (winit's + // `CursorLeft`), which only matters when the drag goes by that pointer. + let (pos, down) = ctx.input(|i| (i.pointer.latest_pos(), i.pointer.primary_down() && i.any_touches())); + let (inner, outer, maximized) = ctx.input(|i| (i.viewport().inner_rect, i.viewport().outer_rect, i.viewport().maximized.unwrap_or(false))); + let end = |ctx: &egui::Context| ctx.data_mut(|d| d.remove::(pen_drag_id())); + let (Some(inner), Some(outer), true) = (inner, outer, down) else { return end(ctx) }; + let pen = if drag.os { + // No OS reading this pass (the service failed): wait for the next. + let Some(at) = os_pointer(ctx) else { + ctx.data_mut(|d| d.insert_temp(pen_drag_id(), drag)); + return; + }; + at + } else { + let Some(pos) = pos else { return end(ctx) }; + inner.min + pos.to_vec2() + }; + let Some((press, outer0, inner0)) = drag.start else { + // Restoring a maximized window: wait for its restored size, then put it under the pen. + if !maximized { + let at = pen - vec2(drag.grab.0 * inner.width(), drag.grab.1) - (inner.min - outer.min); + ctx.send_viewport_cmd(ViewportCommand::OuterPosition(at)); + let shift = at - outer.min; + drag.start = Some((pen, outer.translate(shift), inner.translate(shift))); + } + ctx.data_mut(|d| d.insert_temp(pen_drag_id(), drag)); + return; + }; + let d = pen - press; + match drag.kind { + PenDragKind::Move => { + let at = outer0.min + d; + if at != outer.min { + ctx.send_viewport_cmd(ViewportCommand::OuterPosition(at)); + } + } + PenDragKind::Resize(dir) => { + let r = resized(inner0, dir, d, MIN_WINDOW_SIZE); + if r.size() != inner.size() { + ctx.send_viewport_cmd(ViewportCommand::InnerSize(r.size())); + } + let at = outer0.min + (r.min - inner0.min); + if at != outer.min { + ctx.send_viewport_cmd(ViewportCommand::OuterPosition(at)); + } + } + } + ctx.data_mut(|d| d.insert_temp(pen_drag_id(), drag)); +} + +/// `r` with the edges `dir` names moved by `d`, no smaller than `min`: a left or top edge stops +/// where the window would be too small rather than pushing it along. +fn resized(r: Rect, dir: ResizeDirection, d: Vec2, min: Vec2) -> Rect { + use ResizeDirection::*; + let mut r = r; + if matches!(dir, West | NorthWest | SouthWest) { + r.min.x = (r.min.x + d.x).min(r.max.x - min.x); + } + if matches!(dir, East | NorthEast | SouthEast) { + r.max.x = (r.max.x + d.x).max(r.min.x + min.x); + } + if matches!(dir, North | NorthWest | NorthEast) { + r.min.y = (r.min.y + d.y).min(r.max.y - min.y); + } + if matches!(dir, South | SouthWest | SouthEast) { + r.max.y = (r.max.y + d.y).max(r.min.y + min.y); + } + r +} + /// The compositor takes the button release of an OS resize or move (KDE Wayland, KWin on X11), so /// egui kept the edge pressed: the zones stopped hovering until the next click, every other resize /// (#1581, and #5725 for moves). End the press ourselves on the input after the hand-off, but only @@ -525,9 +715,11 @@ fn reshow_cursor_after_os_resize(ctx: &egui::Context) { } /// Invisible resize zones along the window's edges, above everything else; a press in one starts -/// an OS resize in that direction. None while the window is maximized or full screen. +/// an OS resize in that direction (a pen's or a finger's: a [`PenDrag`]). None while the window +/// is maximized or full screen. pub fn resize_zones(ui: &mut Ui) { let ctx = ui.ctx().clone(); + follow_pen_drag(&ctx); if maximized(&ctx) || ctx.input(|i| i.viewport().fullscreen.unwrap_or(false)) { reshow_cursor_after_os_resize(&ctx); return; @@ -537,7 +729,7 @@ pub fn resize_zones(ui: &mut Ui) { let zui = ui.new_child(egui::UiBuilder::new().layer_id(layer).max_rect(w)); for (i, (r, dir, cursor)) in zones(w).into_iter().enumerate() { let resp = zui.interact(r, Id::unique(("titlebar-resize", i)), Sense::drag()).on_hover_cursor(cursor); - if resp.drag_started_by(PointerButton::Primary) { + if resp.drag_started_by(PointerButton::Primary) && !start_pen_drag(&ctx, PenDragKind::Resize(dir)) { ctx.send_viewport_cmd(ViewportCommand::BeginResize(dir)); hand_off(&ctx); } diff --git a/crates/ui-egui/src/panels/titlebar/tests.rs b/crates/ui-egui/src/panels/titlebar/tests.rs index 7cb98aec556..05dbbca1f15 100644 --- a/crates/ui-egui/src/panels/titlebar/tests.rs +++ b/crates/ui-egui/src/panels/titlebar/tests.rs @@ -1,5 +1,5 @@ use super::*; -use egui::{Event, Pos2, RawInput, ViewportId}; +use egui::{Event, Pos2, RawInput, Vec2, ViewportId}; use photocraft_engine::Session; /// #5826: the drag overlay under a dialog doesn't depend on the custom title bar. On macOS @@ -24,8 +24,22 @@ struct Win { ctx: egui::Context, app: PhotocraftApp, width: f32, + height: f32, + /// Where the window's content is on the screen, and its outer rect's offset from that. + at: Pos2, + frame_offset: Vec2, time: f64, maximized: bool, + /// Windows moves the window asynchronously: with `lag`, the pointer positions of a frame are + /// relative to where the window was before the previous frame's commands, while the viewport + /// already reports where it is now. + lag: bool, + before_move: Pos2, + /// The OS cursor on the screen, when it follows the pen (`Services::cursor_pos`). + cursor: std::rc::Rc>>, + cursor_follows: bool, + /// A pen frame, by its index in the path, where egui's pointer also leaves the window. + pointer_gone_at: Option, } impl Win { @@ -34,7 +48,30 @@ impl Win { PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ALL[0]); let mut app = PhotocraftApp::new(Session::new(), crate::Services::default()); app.custom_titlebar = true; - Self { ctx, app, width, time: 0.0, maximized: false } + let at = pos2(200.0, 100.0); + Self { + ctx, + app, + width, + height: 600.0, + at, + frame_offset: vec2(-7.0, 0.0), + time: 0.0, + maximized: false, + lag: false, + before_move: at, + cursor: Default::default(), + cursor_follows: true, + pointer_gone_at: None, + } + } + + /// The OS cursor follows the pen, as Windows Ink moves it: `Services::cursor_pos` reports it + /// relative to the window's client area. + fn with_os_cursor(mut self) -> Self { + let cursor = self.cursor.clone(); + self.app.services.cursor_pos = Some(Box::new(move |ctx: &egui::Context| Some(cursor.get()? - ctx.input(|i| i.viewport().inner_rect)?.min.to_vec2()))); + self } fn frame(&mut self, events: Vec) -> egui::FullOutput { @@ -44,14 +81,19 @@ impl Win { fn frame_with_modal(&mut self, events: Vec, modal: bool) -> egui::FullOutput { self.time += 0.05; let mut input = - RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(self.width, 600.0))), time: Some(self.time), events, ..Default::default() }; + RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(self.width, self.height))), time: Some(self.time), events, ..Default::default() }; if let Some(v) = input.viewports.get_mut(&ViewportId::ROOT) { v.maximized = Some(self.maximized); + let inner = Rect::from_min_size(self.at, vec2(self.width, self.height)); + v.inner_rect = Some(inner); + v.outer_rect = Some(Rect::from_min_max(inner.min + self.frame_offset, inner.max - self.frame_offset)); } // What `PhotocraftApp::raw_input_hook` does. release_after_os_resize(&self.ctx, &mut input); let app = &mut self.app; let mut out = self.ctx.run_ui(input, |ui| { + // What `ui_body` does first. + note_os_pointer(app, ui.ctx()); crate::panels::title_bar(app, ui); if modal { egui::Modal::new(Id::unique("titlebar-drag-test-modal")).backdrop_color(Color32::TRANSPARENT).show(ui.ctx(), |ui| { @@ -85,6 +127,57 @@ impl Win { .collect() } + /// A pen stroke along `path`, in screen points, as winit and egui-winit deliver it on Windows: + /// `Touch` events with an emulated pointer at the pen's spot in the window. The window obeys + /// the move, size and restore commands the frames send, as the OS would, so a window that + /// moves under the pen moves the pen's spot in it. The commands the frames sent. + fn pen(&mut self, path: &[Pos2]) -> Vec { + let touch = |phase, pos| Event::Touch { device_id: egui::TouchDeviceId(7), id: egui::TouchId(1), phase, pos, force: Some(0.5) }; + let mut all = vec![]; + let last = path.len() - 1; + // The pen hovers first: winit reports that as touch moves, egui-winit as pointer moves. + let hover = path[0] - self.at.to_vec2(); + all.extend(self.obey(vec![Event::PointerMoved(hover)])); + for (i, p) in path.iter().enumerate() { + if self.cursor_follows { + self.cursor.set(Some(*p)); + } + let local = *p - if self.lag { self.before_move } else { self.at }.to_vec2(); + let events = match i { + 0 => vec![touch(egui::TouchPhase::Start, local), Event::PointerMoved(local), button(local, true, egui::PointerButton::Primary)], + _ => vec![touch(egui::TouchPhase::Move, local), Event::PointerMoved(local)], + }; + let mut events = events; + if self.pointer_gone_at == Some(i) { + events.push(Event::PointerGone); + } + all.extend(self.obey(events)); + if i == last { + let events = vec![touch(egui::TouchPhase::End, local), button(local, false, egui::PointerButton::Primary), Event::PointerGone]; + all.extend(self.obey(events)); + } + } + all + } + + /// One frame; the window then moves, resizes and restores as its commands say. + fn obey(&mut self, events: Vec) -> Vec { + let cmds = self.frame(events).viewport_output.remove(&ViewportId::ROOT).map(|v| v.commands).unwrap_or_default(); + self.before_move = self.at; + for c in &cmds { + match c { + ViewportCommand::OuterPosition(p) => self.at = *p - self.frame_offset, + ViewportCommand::InnerSize(s) => (self.width, self.height) = (s.x, s.y), + ViewportCommand::Maximized(false) => { + self.maximized = false; + (self.at, self.width, self.height) = (pos2(300.0, 200.0), 1000.0, 700.0); + } + _ => {} + } + } + cmds + } + fn click(&mut self, p: Pos2) -> Vec { self.gesture(&[p]) } @@ -489,3 +582,126 @@ fn theme_icons_are_cached_and_fall_back() { out.textures_delta.clear(); assert_eq!(calls.load(Ordering::Relaxed), 3, "each icon and size rendered once; absurd sizes never"); } + +/// #7967, #11840: a pen on the title bar's gap moves the window itself. Windows' move loop follows +/// the mouse button, which a pen never presses (winit reads it as `WM_POINTER`), and winit's +/// unfinished `drag_window` then stopped the mouse moving the window too. +#[test] +fn a_pen_moves_the_window_and_the_mouse_still_can_after() { + let mut w = Win::new(1440.0); + w.frame(vec![]); + let empty = pos2(980.0, 16.0); + assert!(w.bar_widgets().iter().all(|r| !r.contains(empty)), "the probe point must be empty bar space"); + let start = w.at; + let on_screen = start + empty.to_vec2(); + let path: Vec = (0..=10).map(|i| on_screen + vec2(-30.0, 12.0) * i as f32).collect(); + let cmds = w.pen(&path); + assert!(!cmds.iter().any(|c| matches!(c, ViewportCommand::StartDrag | ViewportCommand::BeginResize(_))), "no OS move for a pen: {cmds:?}"); + assert_eq!(w.at, start + vec2(-300.0, 120.0), "the window followed the pen: {cmds:?}"); + // Lifting the pen ends it: a move of the pointer moves nothing. + let cmds = w.obey(vec![Event::PointerMoved(pos2(500.0, 300.0))]); + assert!(!cmds.iter().any(|c| matches!(c, ViewportCommand::OuterPosition(_))), "{cmds:?}"); + // The mouse still hands the move to the OS. + let cmds = w.gesture(&[empty, empty + vec2(12.0, 4.0), empty + vec2(30.0, 8.0)]); + assert_eq!(cmds.iter().filter(|c| matches!(c, ViewportCommand::StartDrag)).count(), 1, "{cmds:?}"); + assert!(!cmds.iter().any(|c| matches!(c, ViewportCommand::OuterPosition(_))), "{cmds:?}"); +} + +/// A pen on an edge or a corner resizes the window itself, down to the minimum size, the left +/// and top edges without pushing the window along once it is that small. +#[test] +fn a_pen_resizes_the_window_from_its_edges() { + let mut w = Win::new(1000.0); + w.frame(vec![]); + let screen = |w: &Win, p: Pos2| w.at + p.to_vec2(); + // South-east corner: 60 wider, 40 taller. + let p = screen(&w, pos2(998.0, 598.0)); + let cmds = w.pen(&[p, p + vec2(30.0, 20.0), p + vec2(60.0, 40.0)]); + assert!(!cmds.iter().any(|c| matches!(c, ViewportCommand::BeginResize(_))), "{cmds:?}"); + assert_eq!((w.width, w.height), (1060.0, 640.0)); + let at = w.at; + // West edge, 100 in: the window narrows and its left edge follows the pen. + let p = screen(&w, pos2(2.0, 300.0)); + w.pen(&[p, p + vec2(50.0, 0.0), p + vec2(100.0, 0.0)]); + assert_eq!((w.width, w.at), (960.0, at + vec2(100.0, 0.0))); + // North edge, far down: stops at the minimum height with the bottom edge kept. + let bottom = w.at.y + w.height; + let p = screen(&w, pos2(480.0, 1.0)); + w.pen(&[p, p + vec2(0.0, 200.0), p + vec2(0.0, 900.0)]); + assert_eq!((w.height, w.at.y + w.height), (MIN_WINDOW_SIZE.y, bottom)); + // The mouse still resizes through the OS. + let cmds = w.gesture(&[pos2(1.0, 300.0), pos2(8.0, 300.0)]); + assert_eq!(cmds, vec![ViewportCommand::BeginResize(ResizeDirection::West)]); +} + +/// A pen dragging a maximized window's title bar restores it and carries it, held where the pen +/// took it, as Windows does for the mouse. +#[test] +fn a_pen_drags_a_maximized_window_out_restored() { + let mut w = Win::new(1920.0); + w.maximized = true; + w.at = Pos2::ZERO; + w.frame(vec![]); + let grab = pos2(1200.0, 16.0); + assert!(w.bar_widgets().iter().all(|r| !r.contains(grab)), "the probe point must be empty bar space"); + let path: Vec = (0..=6).map(|i| grab + vec2(10.0, 20.0) * i as f32).collect(); + let cmds = w.pen(&path); + assert!(cmds.contains(&ViewportCommand::Maximized(false)), "{cmds:?}"); + assert!(!cmds.iter().any(|c| matches!(c, ViewportCommand::StartDrag)), "{cmds:?}"); + let pen = *path.last().unwrap(); + let held = pen - w.at; + assert!((held.x - 1000.0 * 1200.0 / 1920.0).abs() < 0.01 && (held.y - 16.0).abs() < 0.01, "held at {held:?}, window at {:?}", w.at); +} + +/// Windows moves the window asynchronously, so a frame's pointer positions can be relative to +/// where the window was before the last move: added to where it is now they counted that move +/// twice, and the window ran away from the pen (seen with an injected pen on Windows 11: +477, +/// +783 for a +200, +120 stroke). With the OS cursor following the pen, the window follows the +/// cursor's screen position instead and lands exactly under the pen. +#[test] +fn a_pen_move_follows_the_os_cursor_when_the_window_moves_late() { + let stroke = |w: &mut Win| { + w.lag = true; + w.frame(vec![]); + let start = w.at; + let on_screen = start + pos2(980.0, 16.0).to_vec2(); + let path: Vec = (0..=10).map(|i| on_screen + vec2(20.0, 12.0) * i as f32).collect(); + w.pen(&path); + w.at - start + }; + assert_eq!(stroke(&mut Win::new(1440.0).with_os_cursor()), vec2(200.0, 120.0)); + // Without the cursor the window can only go by egui's positions: it overshoots. + let moved = stroke(&mut Win::new(1440.0)); + assert!(moved.x > 200.0 && moved.y > 120.0, "{moved:?}"); +} + +/// A finger leaves the OS cursor behind: a cursor that isn't where the pointer is isn't followed. +#[test] +fn a_cursor_away_from_the_pen_is_not_followed() { + let mut w = Win::new(1440.0).with_os_cursor(); + w.cursor_follows = false; + w.cursor.set(Some(pos2(5.0, 5.0))); + w.frame(vec![]); + let start = w.at; + let on_screen = start + pos2(980.0, 16.0).to_vec2(); + let path: Vec = (0..=10).map(|i| on_screen + vec2(-30.0, 12.0) * i as f32).collect(); + w.pen(&path); + assert_eq!(w.at, start + vec2(-300.0, 120.0)); +} + +/// The mouse cursor, parked where the pen took the window, can end up outside the window as it +/// moves away: winit reports the mouse leaving, and egui's pointer is gone for the rest of the +/// stroke. Seen on Windows 11 after a mouse move: the pen move stopped after 2 of 20 steps. The +/// drag follows the pen's own position, so it carries on. +#[test] +fn a_pen_move_survives_the_mouse_pointer_leaving_the_window() { + let mut w = Win::new(1440.0).with_os_cursor(); + w.lag = true; + w.pointer_gone_at = Some(3); + w.frame(vec![]); + let start = w.at; + let on_screen = start + pos2(980.0, 16.0).to_vec2(); + let path: Vec = (0..=10).map(|i| on_screen + vec2(20.0, 12.0) * i as f32).collect(); + w.pen(&path); + assert_eq!(w.at - start, vec2(200.0, 120.0)); +} diff --git a/crates/ui-egui/src/services.rs b/crates/ui-egui/src/services.rs index 24ae902b9d7..6e28f009388 100644 --- a/crates/ui-egui/src/services.rs +++ b/crates/ui-egui/src/services.rs @@ -477,6 +477,9 @@ pub type CaptionStyleFn = Box CaptionStyle>; /// Physical right mouse button or stylus barrel button down (Windows; read for brush resize). pub type RightButtonDownFn = Box bool + Send + Sync>; +/// Where the pen in range is on the screen, in physical pixels ([`Services::pen_screen_px`]). +pub type PenScreenFn = Box Option<[i32; 2]> + Send + Sync>; + /// Which end of the pen is in use, `Some(true)` = eraser, `None` = no pen ([`Services::pen_end`]). pub type PenEndFn = Box Option + Send + Sync>; @@ -616,6 +619,9 @@ pub struct Services { /// Which end of the pen is in use, where the platform reports it outside the stylus feed /// (Windows: the feed carries no pen samples there). Read for the eraser-end tool switch. pub pen_end: Option, + /// Where the pen is on the screen, independent of where the window is (Windows: the pen's + /// pointer messages). A pen moving the window by its title bar follows it (`titlebar`). + pub pen_screen_px: Option, /// WinTab packet poll (Windows with Windows Ink disabled; see `photocraft_tablet::wintab`). pub tablet_poll: Option, /// The persistent brush preset store, loading in the background (desktop; see From 9653bf1da6a7e662b785c36a1acb37a5aa1e5152 Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 11 Nov 2026 01:13:19 +0100 Subject: [PATCH 40/42] Ruler: match the tuple variant Drag::RulerNew(_) in the Escape check Co-Authored-By: Claude Fable 5.2 --- crates/ui-egui/src/tools/analysis_ui.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/tools/analysis_ui.rs b/crates/ui-egui/src/tools/analysis_ui.rs index 19057c42954..c3bd7ee6e76 100644 --- a/crates/ui-egui/src/tools/analysis_ui.rs +++ b/crates/ui-egui/src/tools/analysis_ui.rs @@ -1202,7 +1202,7 @@ pub fn note_keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { // Escape during a Ruler drag (a new ruler or an end) ends it and keeps the ruler where it is: // no cancel, and the later moves and the release change nothing (#11986). if app.ui.tool == Tool::Ruler - && matches!(app.ui.analysis.drag, Some(Drag::RulerNew | Drag::RulerHandle(0 | 1))) + && matches!(app.ui.analysis.drag, Some(Drag::RulerNew(_) | Drag::RulerHandle(0 | 1))) && ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) { app.ui.analysis.drag = None; From 47d3dcde33269e478dc486eed60ce9dbd150ba5a Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 11 Nov 2026 01:36:38 +0100 Subject: [PATCH 41/42] Fix main: split the Pencil outline out of draw_default_tool_cursor main fails the gate at clippy since #12214 landed: its Count arm took draw_default_tool_cursor to a cognitive complexity of 31 (limit 30). The Pencil / Block eraser outline moves into pencil_outline_cursor; behaviour is unchanged. Co-Authored-By: Claude Fable 5.2 --- crates/ui-egui/src/canvas.rs | 41 +++++++++++++++++++++--------------- 1 file changed, 24 insertions(+), 17 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 2f8ed0ed8b8..bac56f67fe5 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1797,6 +1797,29 @@ fn draw_canvas_tool_cursor(app: &mut PhotocraftApp, ui: &mut egui::Ui, input: &C } } +/// The Pencil's cursor (and the Eraser's in Pencil or Block mode): the outline of the whole pixels +/// its dab fills, on the pixel grid. A round tip is a disc, a square or Block one its square. The +/// hotspot is drawn as well when `crosshair` asks for it or the outline is too small to see. +fn pencil_outline_cursor(painter: &egui::Painter, xf: &ViewXform, p: Pos2, size: f32, block: bool, crosshair: bool) -> egui::CursorIcon { + let ppp = painter.ctx().pixels_per_point(); + let sq = pencil_cursor_rect(xf, xf.to_doc(p), size, ppp); + let px = 1.0 / ppp; + let (dark, light) = (Stroke::new(px, Color32::from_black_alpha(160)), Stroke::new(px, Color32::from_white_alpha(230))); + if !block && pencil_tip_is_round(size) { + let r = sq.width() / 2.0; + painter.circle_stroke(sq.center(), r + px / 2.0, dark); + painter.circle_stroke(sq.center(), (r - px / 2.0).max(0.0), light); + } else { + painter.rect_stroke(sq, 0.0, dark, egui::StrokeKind::Outside); + painter.rect_stroke(sq, 0.0, light, egui::StrokeKind::Inside); + } + // Too small to see where it is: the hotspot as well. + if crosshair || sq.width() < 6.0 { + crate::tool_cursor::crosshair(painter, p, 4.0, 0.0); + } + egui::CursorIcon::None +} + fn draw_default_tool_cursor(app: &mut PhotocraftApp, ui: &mut egui::Ui, input: &CanvasOverlayInput<'_>, resizing: bool, p: Pos2) { let painter = input.painter; let xf = input.xf; @@ -1861,23 +1884,7 @@ fn draw_default_tool_cursor(app: &mut PhotocraftApp, ui: &mut egui::Ui, input: & _ if tool == Tool::Pencil || crate::eraser_ui::pencil_mode(app, tool) || crate::eraser_ui::block_mode(app, tool) => { let block = crate::eraser_ui::block_mode(app, tool); let size = if block { crate::eraser_ui::block_size(app) } else { brush.size }; - let ppp = painter.ctx().pixels_per_point(); - let sq = pencil_cursor_rect(xf, xf.to_doc(p), size, ppp); - let px = 1.0 / ppp; - let (dark, light) = (Stroke::new(px, Color32::from_black_alpha(160)), Stroke::new(px, Color32::from_white_alpha(230))); - if !block && pencil_tip_is_round(size) { - let r = sq.width() / 2.0; - painter.circle_stroke(sq.center(), r + px / 2.0, dark); - painter.circle_stroke(sq.center(), (r - px / 2.0).max(0.0), light); - } else { - painter.rect_stroke(sq, 0.0, dark, egui::StrokeKind::Outside); - painter.rect_stroke(sq, 0.0, light, egui::StrokeKind::Inside); - } - // Too small to see where it is: the hotspot as well. - if cur.show_crosshair_in_brush_tip || sq.width() < 6.0 { - crate::tool_cursor::crosshair(painter, p, 4.0, 0.0); - } - egui::CursorIcon::None + pencil_outline_cursor(painter, xf, p, size, block, cur.show_crosshair_in_brush_tip) } // A shaped tip (sampled bitmap, or a rotated/flattened round tip) // traces its outline, turned and flipped with the view; a plain round From a5342b134da82c2cd3327c3ffdf22e948e2988d3 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 10 Nov 2026 19:52:30 -0500 Subject: [PATCH 42/42] packaging: use [[ for bash tests (SonarCloud S7688) (#13050) Behaviour-preserving: `[[ ]]` in place of `[ ]` for bash tests (SonarCloud shell:S7688). Every script has a bash shebang; no test uses `-a`/`-o`, escaped parentheses or an unquoted pattern on the right of `=`. `bash -n` passes on each script; the rest is left to CI. - `packaging/linux/apprun-cli-test.sh` (14) --- packaging/linux/apprun-cli-test.sh | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/packaging/linux/apprun-cli-test.sh b/packaging/linux/apprun-cli-test.sh index f6a7ed8af85..966540220c7 100755 --- a/packaging/linux/apprun-cli-test.sh +++ b/packaging/linux/apprun-cli-test.sh @@ -41,39 +41,39 @@ fail() { echo "FAIL: $*" >&2; exit 1; } out="$("$app_dir/AppRun" --cli convert 'input file.png' '' '*.psd' --out 'output file.psd')" expected=$'cli\n\n\n<>\n<*.psd>\n<--out>\n' -[ "$out" = "$expected" ] || fail "CLI arguments changed: $out" -[ "$("$app_dir/AppRun" --cli)" = cli ] || fail "empty CLI invocation" +[[ "$out" = "$expected" ]] || fail "CLI arguments changed: $out" +[[ "$("$app_dir/AppRun" --cli)" = cli ]] || fail "empty CLI invocation" # The AppImage runtime exposes the original symlink name through ARGV0. for argv0 in photocraft-cli ./photocraft-cli "$test_dir/with spaces/photocraft-cli"; do out="$(ARGV0="$argv0" "$app_dir/AppRun" --version)" - [ "$out" = $'cli\n<--version>' ] || fail "CLI symlink not selected: $argv0" + [[ "$out" = $'cli\n<--version>' ]] || fail "CLI symlink not selected: $argv0" done out="$(ARGV0=photocraft-cli "$app_dir/AppRun" --cli --version)" -[ "$out" = $'cli\n<--version>' ] || fail "CLI selector not removed with a symlink" +[[ "$out" = $'cli\n<--version>' ]] || fail "CLI selector not removed with a symlink" request='{"jsonrpc":"2.0","id":1,"method":"initialize"}' out="$(printf '%s\n' "$request" | "$app_dir/AppRun" --cli mcp 2>"$test_dir/stderr")" -[ "$out" = "$request" ] || fail "MCP stdin/stdout changed: $out" -[ "$(cat "$test_dir/stderr")" = 'cli stderr' ] || fail "CLI stderr lost" +[[ "$out" = "$request" ]] || fail "MCP stdin/stdout changed: $out" +[[ "$(cat "$test_dir/stderr")" = 'cli stderr' ]] || fail "CLI stderr lost" status=0 "$app_dir/AppRun" --cli --exit-37 || status=$? -[ "$status" = 37 ] || fail "CLI exit status changed: $status" -[ ! -e "$XDG_DATA_HOME" ] || fail "CLI performed desktop integration" +[[ "$status" = 37 ]] || fail "CLI exit status changed: $status" +[[ ! -e "$XDG_DATA_HOME" ]] || fail "CLI performed desktop integration" # GUI invocations still forward all arguments; only a leading --cli is a selector. out="$("$app_dir/AppRun" 'input file.png' --cli)" -[ "$out" = $'gui\n\n<--cli>' ] || fail "GUI arguments changed: $out" -[ -f "$XDG_DATA_HOME/applications/ai.storyteller.photocraft.desktop" ] || fail "GUI integration lost" +[[ "$out" = $'gui\n\n<--cli>' ]] || fail "GUI arguments changed: $out" +[[ -f "$XDG_DATA_HOME/applications/ai.storyteller.photocraft.desktop" ]] || fail "GUI integration lost" out="$(ARGV0=another-photocraft-cli "$app_dir/AppRun" mcp)" -[ "$out" = $'gui\n' ] || fail "an unrelated filename selected CLI" +[[ "$out" = $'gui\n' ]] || fail "an unrelated filename selected CLI" # A broken package must fail visibly, rather than silently opening the GUI. rm "$app_dir/usr/bin/photocraft-cli" status=0 "$app_dir/AppRun" --cli --version >"$test_dir/missing-out" 2>"$test_dir/missing-err" || status=$? -[ "$status" != 0 ] || fail "missing CLI succeeded" -[ ! -s "$test_dir/missing-out" ] || fail "missing CLI launched the GUI" -[ -s "$test_dir/missing-err" ] || fail "missing CLI had no diagnostic" +[[ "$status" != 0 ]] || fail "missing CLI succeeded" +[[ ! -s "$test_dir/missing-out" ]] || fail "missing CLI launched the GUI" +[[ -s "$test_dir/missing-err" ]] || fail "missing CLI had no diagnostic" echo "AppRun CLI selection ok"