diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1282fc662c..cf927388b6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -174,8 +174,8 @@ jobs: # Windows tests run as two legs in parallel: the unit tests and the integration tests. As one job # they took ~28 min on the Windows runner; the legs take ~13 and ~15. Splitting the integration # tests over a third runner (nextest --partition) saved ~2 min of wall time but cost ~7 - # runner-minutes and one more Windows slot per PR. They stay outside the shared gate for sccache, - # which needs its own action step. + # runner-minutes and one more Windows slot per PR. Moving these legs into the shared gate is + # tracked by storytold/craft-common-actions#212. windows: needs: platforms if: needs.platforms.outputs.windows == 'true' @@ -187,6 +187,10 @@ jobs: matrix: part: [unit, integration] env: + # Released sccache expands Cargo's response files and exceeds Windows' rustc spawn limit + # (#13543). Let Cargo handle long commands until a release includes mozilla/sccache#3026. + # The dependency rust-cache below stays enabled; only compiler caching is disabled. + RUSTC_WRAPPER: "" # No debuginfo on Windows: writing PDBs for ~200 test binaries cost 2.2 of ~21 build minutes. # A panic still names its file and line; only backtrace frames lose theirs (Linux keeps # line-tables-only, so a backtrace with lines is one OS away). @@ -236,24 +240,6 @@ jobs: save-if: ${{ github.ref == 'refs/heads/main' && matrix.part == 'integration' }} cache-on-failure: true - # sccache caches the workspace crates' compiled libraries, which rust-cache leaves out: - # warm, each Windows leg built 4.5 min faster. Like rust-cache, only main writes (PRs read - # main's entries); a full set is ~90 MB, so it barely touches the 10 GB budget (#2688). - # Test executables can't be cached, so a PR still links its tests. - - name: Install sccache - uses: step-security/sccache-action@ae2d64c53dbae979f387673f0aae7ebb52087f6b # v0.0.11 - with: - version: v0.18.0 - - - name: Use sccache - env: - MAIN: ${{ github.ref == 'refs/heads/main' }} - run: | - echo "SCCACHE_GHA_ENABLED=true" >> "$GITHUB_ENV" - echo "RUSTC_WRAPPER=sccache" >> "$GITHUB_ENV" - if [ "$MAIN" != true ]; then echo "SCCACHE_GHA_RW_MODE=READ_ONLY" >> "$GITHUB_ENV"; fi - shell: bash - - name: Clippy if: matrix.part == 'integration' run: cargo clippy --workspace --all-targets --locked --features heif -- -D warnings diff --git a/apps/photocraft/src/external_svg.rs b/apps/photocraft/src/external_svg.rs index 1d4f552573..c34dd88bd0 100644 --- a/apps/photocraft/src/external_svg.rs +++ b/apps/photocraft/src/external_svg.rs @@ -627,17 +627,14 @@ mod native { /// True for a symlink, or on Windows any reparse point, whose target could be swapped. /// Expects `symlink_metadata`, which describes the link itself rather than its target. fn is_redirect(metadata: &Metadata) -> bool { - if metadata.file_type().is_symlink() { - return true; - } #[cfg(windows)] { use std::os::windows::fs::MetadataExt; - metadata.file_attributes() & 0x0000_0400 != 0 // FILE_ATTRIBUTE_REPARSE_POINT + metadata.file_type().is_symlink() || metadata.file_attributes() & 0x0000_0400 != 0 // FILE_ATTRIBUTE_REPARSE_POINT } #[cfg(not(windows))] { - false + metadata.file_type().is_symlink() } } diff --git a/crates/algo/src/photo_util.rs b/crates/algo/src/photo_util.rs index 96c6f7b434..8f1e436d53 100644 --- a/crates/algo/src/photo_util.rs +++ b/crates/algo/src/photo_util.rs @@ -167,8 +167,8 @@ impl BandChol { let n = a.diag.len(); let mut p = 0; for i in 0..n { - for k in a.rows[i]..a.rows[i + 1] { - p = p.max(i.abs_diff(a.cols[k])); + for &j in &a.cols[a.rows[i]..a.rows[i + 1]] { + p = p.max(i.abs_diff(j)); } } if n.saturating_mul(p + 1) > 40_000_000 { diff --git a/crates/algo/src/transform.rs b/crates/algo/src/transform.rs index 5a46b472e9..5dabbd2a0c 100644 --- a/crates/algo/src/transform.rs +++ b/crates/algo/src/transform.rs @@ -210,6 +210,15 @@ pub fn convex_quad(q: &[[f64; 2]; 4]) -> bool { area2.is_finite() && area2 >= 2.0 } +/// Is `q` (TL, TR, BR, BL) a usable Perspective Crop quad in either winding: a [`convex_quad`], +/// or one wound counter-clockwise on screen (a box flipped on one axis, which crops mirrored, +/// #12489) with the same corner angle and area limits? Self-crossing, degenerate and non-finite +/// quads are not. The Perspective Warp steps keep the clockwise-only [`convex_quad`]. +pub fn convex_quad_any_winding(q: &[[f64; 2]; 4]) -> bool { + let [tl, tr, br, bl] = *q; + convex_quad(q) || convex_quad(&[tl, bl, br, tr]) +} + /// The output size a Perspective Crop of `q` (TL, TR, BR, BL) takes when none is given: the mean /// length of the top and bottom edges by the mean length of the left and right edges. pub fn quad_size(q: &[[f64; 2]; 4]) -> (f64, f64) { @@ -287,9 +296,10 @@ fn perspective_estimate(q: &[[f64; 2]; 4], [cx, cy]: [f64; 2]) -> Option<(f64, f /// The homography taking the quad `q` (TL, TR, BR, BL) onto the rectangle (0, 0)–(`w`, `h`), corner /// to corner: the inverse of the unit-square-to-quad map (Heckbert, "Fundamentals of Texture /// Mapping and Image Warping", 1989, §2.2.3) scaled to the rectangle. `None` when `q` isn't a -/// [`convex_quad`] or the size isn't positive. +/// [`convex_quad_any_winding`] or the size isn't positive. A quad wound counter-clockwise maps +/// mirrored, each corner onto its own rectangle corner. pub fn quad_to_rect(q: &[[f64; 2]; 4], w: f64, h: f64) -> Option { - if !(convex_quad(q) && w.is_finite() && h.is_finite() && w > 0.0 && h > 0.0) { + if !(convex_quad_any_winding(q) && w.is_finite() && h.is_finite() && w > 0.0 && h > 0.0) { return None; } Homography::rect_to_quad([0.0, 0.0, w, h], *q)?.inverse() diff --git a/crates/algo/src/transform/tests.rs b/crates/algo/src/transform/tests.rs index b70bc74c3d..af6e81b615 100644 --- a/crates/algo/src/transform/tests.rs +++ b/crates/algo/src/transform/tests.rs @@ -61,7 +61,7 @@ fn the_interruptible_warp_reports_progress_and_stops_when_cancelled() { } /// Perspective Crop's map lands each quad corner exactly on its rectangle corner; degenerate, -/// self-crossing, counter-clockwise and non-finite quads have none. +/// self-crossing and non-finite quads have none. #[test] fn quad_to_rect_maps_corners_and_refuses_bad_quads() { let q = [[30.0, 12.0], [140.0, 25.0], [128.0, 110.0], [14.0, 95.0]]; @@ -75,7 +75,7 @@ fn quad_to_rect_maps_corners_and_refuses_bad_quads() { for bad in [ [[0.0, 0.0], [50.0, 0.0], [100.0, 0.0], [0.0, 50.0]], [[0.0, 0.0], [50.0, 50.0], [50.0, 0.0], [0.0, 50.0]], - [[0.0, 0.0], [0.0, 50.0], [50.0, 50.0], [50.0, 0.0]], + [[0.0, 0.0], [50.0, 50.0], [0.0, 50.0], [50.0, 0.0]], [[0.0, 0.0], [f64::NAN, 0.0], [50.0, 50.0], [0.0, 50.0]], [[0.0, 0.0]; 4], ] { @@ -84,6 +84,30 @@ fn quad_to_rect_maps_corners_and_refuses_bad_quads() { assert!(quad_to_rect(&q, 0.0, 10.0).is_none()); } +/// #12489: a quad wound counter-clockwise (a box flipped on one axis) maps mirrored, each corner +/// onto its own rectangle corner. Perspective Warp's clockwise-only check still refuses it. +#[test] +fn quad_to_rect_maps_a_counter_clockwise_quad_mirrored() { + let q = [[140.0, 25.0], [30.0, 12.0], [14.0, 95.0], [128.0, 110.0]]; + assert!(!convex_quad(&q) && convex_quad_any_winding(&q)); + let h = quad_to_rect(&q, 100.0, 80.0).unwrap(); + for (c, want) in q.iter().zip([[0.0, 0.0], [100.0, 0.0], [100.0, 80.0], [0.0, 80.0]]) { + let (x, y) = h.apply(c[0], c[1]); + assert!((x - want[0]).abs() < 1e-9 && (y - want[1]).abs() < 1e-9, "{c:?} -> ({x}, {y})"); + } + // Self-crossing in either winding, three corners on a line, and a sliver stay refused. + for bad in [ + [[0.0, 0.0], [50.0, 0.0], [0.0, 50.0], [50.0, 50.0]], + [[50.0, 0.0], [0.0, 0.0], [50.0, 50.0], [0.0, 50.0]], + [[50.0, 0.0], [25.0, 0.0], [0.0, 0.0], [50.0, 50.0]], + [[50.0, 0.0], [0.0, 0.0], [0.0, 0.01], [50.0, 0.01]], + [[50.0, 0.0], [0.0, f64::INFINITY], [0.0, 50.0], [50.0, 50.0]], + ] { + assert!(!convex_quad_any_winding(&bad), "{bad:?}"); + assert!(quad_to_rect(&bad, 10.0, 10.0).is_none(), "{bad:?}"); + } +} + fn rgba() -> Surface { Surface::new(PixelFormat::RGBA8) } diff --git a/crates/cms/src/synth.rs b/crates/cms/src/synth.rs index 390e509dce..c86bedc9bd 100644 --- a/crates/cms/src/synth.rs +++ b/crates/cms/src/synth.rs @@ -119,7 +119,7 @@ impl CmykModel { (v + 4.0 * self.tvi[i] * v * (1.0 - v)).clamp(0.0, 1.0) }); let mut s = [0.0; 3]; - for m in 0..16 { + for (m, prim) in self.prim_n.iter().enumerate() { let mut w = 1.0; for (i, ai) in a.iter().enumerate() { w *= if m & (1 << i) != 0 { *ai } else { 1.0 - ai }; @@ -127,7 +127,7 @@ impl CmykModel { if w == 0.0 { continue; } - for (acc, p) in s.iter_mut().zip(&self.prim_n[m]) { + for (acc, p) in s.iter_mut().zip(prim) { *acc += w * p; } } diff --git a/crates/engine/src/cmd/brush_cmds.rs b/crates/engine/src/cmd/brush_cmds.rs index 0a41092679..6a3164c07a 100644 --- a/crates/engine/src/cmd/brush_cmds.rs +++ b/crates/engine/src/cmd/brush_cmds.rs @@ -341,12 +341,23 @@ 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). 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. +/// off paints the foreground. In a CMYK layer a foreground picked as CMYK is probed as the inks +/// the stroke paints (#13060), not as its RGB stand-in converted back. 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); - 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 format = surf.format(); + let mut px = photocraft_raster::from_rgba(&format, [fg[0], fg[1], fg[2], 1.0]); + // The renderer's condition for painting the picked inks (`StrokeRenderer::composite`), keyed + // on the foreground being probed. + if let (photocraft_color::ColorMode::Cmyk, Some((rgb, inks))) = (format.mode, brush.color_cmyk) + && rgb == [fg[0], fg[1], fg[2]] + && let Some(channels) = px.get_mut(..4) + { + channels.copy_from_slice(&inks); + } + let mut probe = Surface::new(format); + probe.write_pixel(0, 0, &px); 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) { diff --git a/crates/engine/src/cmd/brush_cmds/tests.rs b/crates/engine/src/cmd/brush_cmds/tests.rs index 7a424e2f03..5d67b14b46 100644 --- a/crates/engine/src/cmd/brush_cmds/tests.rs +++ b/crates/engine/src/cmd/brush_cmds/tests.rs @@ -212,6 +212,35 @@ fn pencil_is_aliased_and_auto_erases() { assert_eq!(rgba(&s, 40, 26), [0.0, 0.0, 0.0, 1.0]); } +/// #13060: in a CMYK document a foreground picked as CMYK inks (a rich black, which its sRGB +/// stand-in does not convert back to) is painted as those inks, and Pencil Auto Erase recognises +/// them: a stroke that starts on it paints the background colour, live and committed. +#[test] +fn pencil_auto_erase_probes_a_cmyk_pick_with_the_picked_inks() { + let rich_black = [0.6f32, 0.4, 0.4, 1.0]; + let rgb = photocraft_color::convert::cmyk_to_rgb(rich_black).map(|c| c.clamp(0.0, 1.0)); + let mut s = session(40, 20); + s.execute("image.mode.cmyk", json!({})).unwrap(); + s.execute("tools.setColors", json!({"foreground": rgb, "foregroundCmyk": rich_black, "background": "#ffffff"})).unwrap(); + s.execute("paint.pencil", json!({"points": [[5, 10], [35, 10]], "size": 5})).unwrap(); + let pixel = |s: &Session, x: i32, y: i32| -> Vec { surface(s).read_region(Rect::new(x, y, x + 1, y + 1)).into_iter().take(4).collect() }; + let painted = pixel(&s, 20, 10); + assert!(painted.iter().zip(rich_black).all(|(a, b)| (a - b).abs() < 0.01), "the stroke paints the picked inks: {painted:?}"); + let white = [1.0f32, 1.0, 1.0, 1.0]; + + // Live: the stroke that starts on the rich black paints the background. + let p = json!({"points": [[12, 10]], "autoErase": true, "smoothing": 0.0}); + let mut live = LiveStroke::begin_with(&s, "paint.pencil", &p).unwrap(); + live.push(&[StrokePoint::new(12.0, 18.0, 1.0)]).unwrap(); + let shown = live.doc.layer(s.active().unwrap().active_layer.unwrap()).unwrap().surface().unwrap().rgba(12, 17); + assert!(shown.iter().zip(white).all(|(a, b)| (a - b).abs() < 1e-3), "live: {shown:?}"); + + // Committed: the same. + s.execute("paint.pencil", json!({"points": [[20, 10], [20, 18]], "size": 3, "autoErase": true})).unwrap(); + let erased = rgba(&s, 20, 17); + assert!(erased.iter().zip(white).all(|(a, b)| (a - b).abs() < 1e-3), "committed: {erased:?}"); +} + #[test] fn mixer_brush_reservoir_and_cleaning() { let mut s = session(200, 30); diff --git a/crates/engine/src/cmd/multichannel_cmds/tests.rs b/crates/engine/src/cmd/multichannel_cmds/tests.rs index fc3cfd1cd6..99ad72d673 100644 --- a/crates/engine/src/cmd/multichannel_cmds/tests.rs +++ b/crates/engine/src/cmd/multichannel_cmds/tests.rs @@ -110,8 +110,8 @@ fn flattens_layers_and_keeps_alpha_channels() { assert_eq!(d.channels.len(), 4); assert!(d.channels[3].spot.is_none(), "the saved selection stays an alpha channel"); // The black fill on the upper layer is solid ink in all three plates. - for k in 0..3 { - assert!(d.channels[k].surface.pixel(1, 1)[0] > 0.99); + for c in &d.channels[..3] { + assert!(c.surface.pixel(1, 1)[0] > 0.99); } // Back to RGB: the alpha channel survives, the inks become colour channels. s.execute("image.mode.rgb", json!({})).unwrap(); diff --git a/crates/engine/src/cmd/perspective_crop_cmds.rs b/crates/engine/src/cmd/perspective_crop_cmds.rs index d5d4db24f5..161fa35e70 100644 --- a/crates/engine/src/cmd/perspective_crop_cmds.rs +++ b/crates/engine/src/cmd/perspective_crop_cmds.rs @@ -12,7 +12,7 @@ //! editable equivalent for them. Vector masks, paths, notes, slices and guides follow the affine //! map closest to the homography (exact when the quad is a parallelogram). -use photocraft_algo::transform::{Homography, Interp, convex_quad, quad_free_size, quad_size, quad_to_rect, warp_surface_clipped}; +use photocraft_algo::transform::{Homography, Interp, convex_quad_any_winding, quad_free_size, quad_size, quad_to_rect, warp_surface_clipped}; use photocraft_color::PixelFormat; use photocraft_doc::{Document, Layer, LayerContent, LayerId, Size}; use photocraft_geom::{Affine, Rect}; @@ -39,7 +39,8 @@ fn has_doc(s: &Session) -> std::result::Result<(), String> { s.active().map(|_| ()).ok_or_else(|| "no document open".into()) } -/// `corners`: four `[x, y]` points, TL, TR, BR, BL, forming a convex quad clockwise on screen. +/// `corners`: four `[x, y]` points, TL, TR, BR, BL, forming a convex quad. Wound counter-clockwise +/// on screen (a box flipped on one axis) it crops mirrored, each corner as it lies (#12489). fn corners(p: &Value) -> Result<[[f64; 2]; 4]> { let shape = || bad("`corners` must be four [x, y] points: top-left, top-right, bottom-right, bottom-left"); let list = p.get("corners").and_then(Value::as_array).filter(|a| a.len() == 4).ok_or_else(shape)?; @@ -52,9 +53,9 @@ fn corners(p: &Value) -> Result<[[f64; 2]; 4]> { } *slot = [x, y]; } - if !convex_quad(&q) { + if !convex_quad_any_winding(&q) { return Err(bad( - "the corners must form a convex quadrilateral at least 1 px in area, in order top-left, top-right, bottom-right, bottom-left (clockwise on screen)", + "the corners must form a convex quadrilateral at least 1 px in area, in order top-left, top-right, bottom-right, bottom-left (counter-clockwise on screen crops mirrored)", )); } Ok(q) @@ -387,7 +388,7 @@ mod tests { json!({"corners": [[0, 0], [10, 0], [10, 10]]}), json!({"corners": [[0, 0], [50, 0], [100, 0], [0, 50]]}), json!({"corners": [[0, 0], [50, 50], [50, 0], [0, 50]]}), - json!({"corners": [[0, 0], [0, 50], [50, 50], [50, 0]]}), + json!({"corners": [[50, 0], [0, 0], [50, 50], [0, 50]]}), json!({"corners": [[0, 0], [0.5, 0], [0.5, 0.5], [0, 0.5]]}), json!({"corners": [[0, 0], [1e300, 0], [50, 50], [0, 50]]}), json!({"corners": [[0, 0], ["a", 0], [50, 50], [0, 50]]}), diff --git a/crates/engine/src/cmd/retouch_cmds/blur_refuses_indexed_tests.rs b/crates/engine/src/cmd/retouch_cmds/blur_refuses_indexed_tests.rs new file mode 100644 index 0000000000..16e430f650 --- /dev/null +++ b/crates/engine/src/cmd/retouch_cmds/blur_refuses_indexed_tests.rs @@ -0,0 +1,57 @@ +//! #12656: the Blur tool refuses Indexed Color and Bitmap documents with the reference +//! application's messages, changing nothing and adding no history; the live stroke is refused the +//! same way. RGB, Grayscale, CMYK and Lab at every depth, Multichannel and Duotone keep working. + +use photocraft_color::{ColorMode, SampleType}; +use serde_json::json; + +use super::dodge_refuses_indexed_tests::{pixels, session, steps}; +use super::*; + +const INDEXED: &str = "Could not use the blur tool because it does not work with Indexed Color images (convert image to RGB Color mode to edit)."; +const BITMAP: &str = "Could not use the blur tool because it does not work with Bitmap images (convert image to Grayscale mode to edit)."; + +/// The grey document with its left half black: an edge for the stroke to work on. +fn edged(mode: ColorMode, depth: SampleType) -> Session { + let mut s = session(mode, depth); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 32, "height": 64})).unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": "#000000"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + s +} + +fn stroke() -> Value { + json!({"points": [[20, 32], [44, 32]], "size": 20, "hardness": 100, "strength": 100}) +} + +#[test] +fn indexed_and_bitmap_documents_refuse_with_the_reference_words() { + // Per mode: the command's error, the live stroke's error, pixels kept, history kept. + let got = [ColorMode::Indexed, ColorMode::Bitmap].map(|mode| { + let mut s = edged(mode, SampleType::U8); + let (before, n) = (pixels(&s), steps(&s)); + let err = s.execute("paint.blur", stroke()).err().map(|e| e.to_string()); + let live = LiveDab::begin(&s, "paint.blur", &stroke()).err().map(|e| e.to_string()); + (err, live, pixels(&s) == before, steps(&s) == n) + }); + let want = [INDEXED, BITMAP].map(|m| (Some(m.to_string()), Some(m.to_string()), true, true)); + assert_eq!(got, want); +} + +/// Every other mode and depth keeps working: one History step and a live stroke. +#[test] +fn other_modes_keep_working_at_every_depth() { + let depths = [SampleType::U8, SampleType::U16, SampleType::F32]; + let measured = [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab].into_iter().flat_map(|m| depths.map(|d| (m, d))); + // Not measured in the reference: they keep today's behaviour. + let unmeasured = [(ColorMode::Multichannel, SampleType::U8), (ColorMode::Duotone, SampleType::U8)]; + for (mode, depth) in measured.chain(unmeasured) { + let mut s = edged(mode, depth); + let n = steps(&s); + assert!(LiveDab::begin(&s, "paint.blur", &stroke()).is_ok(), "{mode:?}/{depth:?}: live"); + let before = pixels(&s); + s.execute("paint.blur", stroke()).unwrap_or_else(|e| panic!("{mode:?}/{depth:?}: {e}")); + assert_ne!(pixels(&s), before, "{mode:?}/{depth:?}: the stroke changed pixels"); + assert_eq!(steps(&s), n + 1, "{mode:?}/{depth:?}: one history step"); + } +} diff --git a/crates/engine/src/cmd/retouch_cmds/burn_refuses_indexed_tests.rs b/crates/engine/src/cmd/retouch_cmds/burn_refuses_indexed_tests.rs new file mode 100644 index 0000000000..d278633555 --- /dev/null +++ b/crates/engine/src/cmd/retouch_cmds/burn_refuses_indexed_tests.rs @@ -0,0 +1,48 @@ +//! #12673: the Burn tool refuses Indexed Color and Bitmap documents with the reference +//! application's messages, changing nothing and adding no history; the live stroke is refused the +//! same way. RGB, Grayscale, CMYK and Lab at every depth, Multichannel and Duotone keep working. + +use photocraft_color::{ColorMode, SampleType}; +use serde_json::json; + +use super::dodge_refuses_indexed_tests::{pixels, session, steps}; +use super::*; + +const INDEXED: &str = "Could not use the burn tool because it does not work with Indexed Color images (convert image to RGB Color mode to edit)."; +const BITMAP: &str = "Could not use the burn tool because it does not work with Bitmap images (convert image to Grayscale mode to edit)."; + +fn stroke() -> Value { + json!({"points": [[20, 32], [44, 32]], "size": 20, "hardness": 100, "range": "midtones", "exposure": 100}) +} + +#[test] +fn indexed_and_bitmap_documents_refuse_with_the_reference_words() { + // Per mode: the command's error, the live stroke's error, pixels kept, history kept. + let got = [ColorMode::Indexed, ColorMode::Bitmap].map(|mode| { + let mut s = session(mode, SampleType::U8); + let (before, n) = (pixels(&s), steps(&s)); + let err = s.execute("paint.burn", stroke()).err().map(|e| e.to_string()); + let live = LiveDab::begin(&s, "paint.burn", &stroke()).err().map(|e| e.to_string()); + (err, live, pixels(&s) == before, steps(&s) == n) + }); + let want = [INDEXED, BITMAP].map(|m| (Some(m.to_string()), Some(m.to_string()), true, true)); + assert_eq!(got, want); +} + +/// Every other mode and depth keeps working: one History step and a live stroke. +#[test] +fn other_modes_keep_working_at_every_depth() { + let depths = [SampleType::U8, SampleType::U16, SampleType::F32]; + let measured = [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab].into_iter().flat_map(|m| depths.map(|d| (m, d))); + // Not measured in the reference: they keep today's behaviour. + let unmeasured = [(ColorMode::Multichannel, SampleType::U8), (ColorMode::Duotone, SampleType::U8)]; + for (mode, depth) in measured.chain(unmeasured) { + let mut s = session(mode, depth); + let n = steps(&s); + assert!(LiveDab::begin(&s, "paint.burn", &stroke()).is_ok(), "{mode:?}/{depth:?}: live"); + let before = pixels(&s); + s.execute("paint.burn", stroke()).unwrap_or_else(|e| panic!("{mode:?}/{depth:?}: {e}")); + assert_ne!(pixels(&s), before, "{mode:?}/{depth:?}: the stroke changed pixels"); + assert_eq!(steps(&s), n + 1, "{mode:?}/{depth:?}: one history step"); + } +} diff --git a/crates/engine/src/cmd/retouch_cmds/dab.rs b/crates/engine/src/cmd/retouch_cmds/dab.rs index 1550cbb825..564df7512d 100644 --- a/crates/engine/src/cmd/retouch_cmds/dab.rs +++ b/crates/engine/src/cmd/retouch_cmds/dab.rs @@ -359,13 +359,18 @@ impl DabTool { } } -/// The reference application refuses a Dodge or Sharpen stroke in Indexed Color and Bitmap -/// documents, with its alert's words (#12686, #12953); other modes (Multichannel and Duotone were -/// not measured) paint as before. The live stroke checks this too, so it previews nothing there. +/// The reference application refuses a Dodge, Burn, Sponge, Blur, Sharpen or Smudge stroke in +/// Indexed Color and Bitmap documents, with its alert's words (#12686, #12673, #13033, #12656, +/// #12953, #12967); other modes (Multichannel and Duotone were not measured) paint as before. The +/// live stroke checks this too, so it previews nothing there. fn mode_refusal(s: &Session, cmd: &str) -> Result<()> { let tool = match cmd { "paint.dodge" => "dodge tool", + "paint.burn" => "burn tool", + "paint.sponge" => "sponge tool", + "paint.blur" => "blur tool", "paint.sharpen" => "sharpen tool", + "paint.smudge" => "smudge tool", _ => return Ok(()), }; let why = match s.active().map(|st| st.doc.mode) { @@ -796,6 +801,22 @@ mod dodge_refuses_indexed_tests; #[path = "sharpen_refuses_indexed_tests.rs"] mod sharpen_refuses_indexed_tests; +#[cfg(test)] +#[path = "burn_refuses_indexed_tests.rs"] +mod burn_refuses_indexed_tests; + +#[cfg(test)] +#[path = "sponge_refuses_indexed_tests.rs"] +mod sponge_refuses_indexed_tests; + +#[cfg(test)] +#[path = "blur_refuses_indexed_tests.rs"] +mod blur_refuses_indexed_tests; + +#[cfg(test)] +#[path = "smudge_refuses_indexed_tests.rs"] +mod smudge_refuses_indexed_tests; + #[cfg(test)] #[path = "smudge_mode_tests.rs"] mod smudge_mode_tests; diff --git a/crates/engine/src/cmd/retouch_cmds/smudge_refuses_indexed_tests.rs b/crates/engine/src/cmd/retouch_cmds/smudge_refuses_indexed_tests.rs new file mode 100644 index 0000000000..4a621b27c3 --- /dev/null +++ b/crates/engine/src/cmd/retouch_cmds/smudge_refuses_indexed_tests.rs @@ -0,0 +1,57 @@ +//! #12967: the Smudge tool refuses Indexed Color and Bitmap documents with the reference +//! application's messages, changing nothing and adding no history; the live stroke is refused the +//! same way. RGB, Grayscale, CMYK and Lab at every depth, Multichannel and Duotone keep working. + +use photocraft_color::{ColorMode, SampleType}; +use serde_json::json; + +use super::dodge_refuses_indexed_tests::{pixels, session, steps}; +use super::*; + +const INDEXED: &str = "Could not use the smudge tool because it does not work with Indexed Color images (convert image to RGB Color mode to edit)."; +const BITMAP: &str = "Could not use the smudge tool because it does not work with Bitmap images (convert image to Grayscale mode to edit)."; + +/// The grey document with its left half black: an edge for the stroke to work on. +fn edged(mode: ColorMode, depth: SampleType) -> Session { + let mut s = session(mode, depth); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 32, "height": 64})).unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": "#000000"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + s +} + +fn stroke() -> Value { + json!({"points": [[20, 32], [44, 32]], "size": 20, "hardness": 100, "strength": 100}) +} + +#[test] +fn indexed_and_bitmap_documents_refuse_with_the_reference_words() { + // Per mode: the command's error, the live stroke's error, pixels kept, history kept. + let got = [ColorMode::Indexed, ColorMode::Bitmap].map(|mode| { + let mut s = edged(mode, SampleType::U8); + let (before, n) = (pixels(&s), steps(&s)); + let err = s.execute("paint.smudge", stroke()).err().map(|e| e.to_string()); + let live = LiveDab::begin(&s, "paint.smudge", &stroke()).err().map(|e| e.to_string()); + (err, live, pixels(&s) == before, steps(&s) == n) + }); + let want = [INDEXED, BITMAP].map(|m| (Some(m.to_string()), Some(m.to_string()), true, true)); + assert_eq!(got, want); +} + +/// Every other mode and depth keeps working: one History step and a live stroke. +#[test] +fn other_modes_keep_working_at_every_depth() { + let depths = [SampleType::U8, SampleType::U16, SampleType::F32]; + let measured = [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab].into_iter().flat_map(|m| depths.map(|d| (m, d))); + // Not measured in the reference: they keep today's behaviour. + let unmeasured = [(ColorMode::Multichannel, SampleType::U8), (ColorMode::Duotone, SampleType::U8)]; + for (mode, depth) in measured.chain(unmeasured) { + let mut s = edged(mode, depth); + let n = steps(&s); + assert!(LiveDab::begin(&s, "paint.smudge", &stroke()).is_ok(), "{mode:?}/{depth:?}: live"); + let before = pixels(&s); + s.execute("paint.smudge", stroke()).unwrap_or_else(|e| panic!("{mode:?}/{depth:?}: {e}")); + assert_ne!(pixels(&s), before, "{mode:?}/{depth:?}: the stroke changed pixels"); + assert_eq!(steps(&s), n + 1, "{mode:?}/{depth:?}: one history step"); + } +} diff --git a/crates/engine/src/cmd/retouch_cmds/sponge_refuses_indexed_tests.rs b/crates/engine/src/cmd/retouch_cmds/sponge_refuses_indexed_tests.rs new file mode 100644 index 0000000000..61dd03901c --- /dev/null +++ b/crates/engine/src/cmd/retouch_cmds/sponge_refuses_indexed_tests.rs @@ -0,0 +1,49 @@ +//! #13033: the Sponge tool refuses Indexed Color and Bitmap documents with the reference +//! application's messages, changing nothing and adding no history; the live stroke is refused the +//! same way. RGB, Grayscale, CMYK and Lab at every depth, Multichannel and Duotone keep working. + +use photocraft_color::{ColorMode, SampleType}; +use serde_json::json; + +use super::dodge_refuses_indexed_tests::{pixels, session, steps}; +use super::*; + +const INDEXED: &str = "Could not use the sponge tool because it does not work with Indexed Color images (convert image to RGB Color mode to edit)."; +const BITMAP: &str = "Could not use the sponge tool because it does not work with Bitmap images (convert image to Grayscale mode to edit)."; + +fn stroke() -> Value { + json!({"points": [[20, 32], [44, 32]], "size": 20, "hardness": 100, "mode": "desaturate"}) +} + +#[test] +fn indexed_and_bitmap_documents_refuse_with_the_reference_words() { + // Per mode: the command's error, the live stroke's error, pixels kept, history kept. + let got = [ColorMode::Indexed, ColorMode::Bitmap].map(|mode| { + let mut s = session(mode, SampleType::U8); + let (before, n) = (pixels(&s), steps(&s)); + let err = s.execute("paint.sponge", stroke()).err().map(|e| e.to_string()); + let live = LiveDab::begin(&s, "paint.sponge", &stroke()).err().map(|e| e.to_string()); + (err, live, pixels(&s) == before, steps(&s) == n) + }); + let want = [INDEXED, BITMAP].map(|m| (Some(m.to_string()), Some(m.to_string()), true, true)); + assert_eq!(got, want); +} + +/// Every other mode and depth keeps working: one History step and a live stroke. +/// +/// The grey document has no saturation to take away, so this checks that the stroke runs and +/// records its History step, not that pixels change. +#[test] +fn other_modes_keep_working_at_every_depth() { + let depths = [SampleType::U8, SampleType::U16, SampleType::F32]; + let measured = [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab].into_iter().flat_map(|m| depths.map(|d| (m, d))); + // Not measured in the reference: they keep today's behaviour. + let unmeasured = [(ColorMode::Multichannel, SampleType::U8), (ColorMode::Duotone, SampleType::U8)]; + for (mode, depth) in measured.chain(unmeasured) { + let mut s = session(mode, depth); + let n = steps(&s); + assert!(LiveDab::begin(&s, "paint.sponge", &stroke()).is_ok(), "{mode:?}/{depth:?}: live"); + s.execute("paint.sponge", stroke()).unwrap_or_else(|e| panic!("{mode:?}/{depth:?}: {e}")); + assert_eq!(steps(&s), n + 1, "{mode:?}/{depth:?}: one history step"); + } +} diff --git a/crates/format/src/noreplace.rs b/crates/format/src/noreplace.rs index 75a54350c5..60d74d29c8 100644 --- a/crates/format/src/noreplace.rs +++ b/crates/format/src/noreplace.rs @@ -107,14 +107,11 @@ pub fn rename_noreplace(from: &Path, to: &Path) -> io::Result<()> { /// Use fallback only when the exclusive rename primitive itself is unsupported. fn unsupported_rename(error: &io::Error) -> bool { - if error.kind() == io::ErrorKind::Unsupported { - return true; - } #[cfg(unix)] if matches!(error.raw_os_error(), Some(code) if code == rustix::io::Errno::INVAL.raw_os_error() || code == rustix::io::Errno::NOSYS.raw_os_error()) { return true; } - false + error.kind() == io::ErrorKind::Unsupported } /// Linking claims an absent destination atomically; a later unlink failure is already published. diff --git a/crates/raster/src/memory/system.rs b/crates/raster/src/memory/system.rs index 998720b8b5..5ad4ebf5e5 100644 --- a/crates/raster/src/memory/system.rs +++ b/crates/raster/src/memory/system.rs @@ -127,12 +127,12 @@ pub(super) mod linux { } #[derive(Clone, Debug, PartialEq, Eq)] - struct Mount { - root: String, - mount_point: String, - fstype: String, - options: String, - super_options: String, + pub(super) struct Mount { + pub(super) root: String, + pub(super) mount_point: String, + pub(super) fstype: String, + pub(super) options: String, + pub(super) super_options: String, } /// Measures available RAM and free swap from `/proc/meminfo`, capped by the process's memory @@ -206,14 +206,14 @@ pub(super) mod linux { MembershipParse::Malformed => return CgroupLimits::Unreadable, }; let mountinfo = std::fs::read_to_string(proc_root.join("self/mountinfo")).ok(); - // A sandbox with no cgroup filesystem mounted and no `/sys/fs/cgroup` at all (Flatpak) - // shows the process its membership path but no interface files, so no limit is - // observable. Failing closed there reported 0 bytes free and refused every PSD on a - // machine with tens of GB. A present directory still takes the guarded path below. - // Only a confirmed NotFound counts as absent: a stat that fails for another reason - // (permissions) leaves the directory possibly present, so that case stays fail-closed. - let sys_root_absent = matches!(std::fs::metadata(sys_root), Err(e) if e.kind() == std::io::ErrorKind::NotFound); - if sys_root_absent && mountinfo.as_deref().is_some_and(lists_mounts_without_cgroup) { + // A sandbox with no cgroup filesystem mounted and no `/sys/fs/cgroup` at all (Flatpak) or + // only an empty mount-point directory left by `sysfs` shows the process its membership path + // but no interface files, so no limit is observable. Failing closed there reported 0 bytes + // free and refused every PSD on a machine with tens of GB. Only a present non-empty or + // unreadable directory takes the guarded path below: a stat or read_dir that fails for + // another reason (permissions, non-directory) leaves a mounted hierarchy possibly present, + // so that case stays fail-closed. + if sys_root_absent_or_empty(sys_root) && mountinfo.as_deref().is_some_and(lists_mounts_without_cgroup) { return CgroupLimits::NotConstrained; } @@ -273,16 +273,34 @@ pub(super) mod linux { MembershipParse::Parsed(membership) } + /// Whether `/sys/fs/cgroup` is absent (`ErrorKind::NotFound`) or a readable empty directory. + /// + /// Permission errors, non-directory paths, and unreadable directories return `false` and stay + /// fail-closed. + pub(super) fn sys_root_absent_or_empty(sys_root: &Path) -> bool { + match std::fs::metadata(sys_root) { + Err(e) => e.kind() == std::io::ErrorKind::NotFound, + Ok(meta) => meta.is_dir() && std::fs::read_dir(sys_root).is_ok_and(|mut entries| entries.next().is_none()), + } + } + /// Parses `/proc/self/mountinfo` into the mount fields used to locate a cgroup hierarchy. /// /// Malformed lines are skipped; callers fail closed when no matching mount is found. - fn parse_mountinfo(text: &str) -> Vec { + pub(super) fn parse_mountinfo(text: &str) -> Vec { let mut mounts = Vec::new(); for line in text.lines() { let fields: Vec<&str> = line.split_whitespace().collect(); let Some(separator) = fields.iter().position(|f| *f == "-") else { continue }; + let super_options = fields.get(separator + 3).copied().or_else(|| { + // `show_mountinfo` writes ` `; an empty source + // (e.g. a bubblewrap tmpfs mount) leaves two spaces between `fstype` and options. + let after = line.split_once(" - ")?.1.trim_start(); + let fstype = fields.get(separator + 1).copied()?; + after.strip_prefix(fstype)?.starts_with(" ").then(|| fields.get(separator + 2).copied()).flatten() + }); let (Some(root), Some(point), Some(fstype), Some(super_options)) = - (fields.get(3).copied(), fields.get(4).copied(), fields.get(separator + 1).copied(), fields.get(separator + 3).copied()) + (fields.get(3).copied(), fields.get(4).copied(), fields.get(separator + 1).copied(), super_options) else { continue; }; @@ -966,6 +984,23 @@ mod tests { assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::NotConstrained); std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + // Isolated case 1: a readable empty `/sys/fs/cgroup` mount-point directory with normal + // non-cgroup `mountinfo` also reports `NotConstrained`. + let (proc, sys) = fixture("empty-cgroup-mountpoint"); + write(&proc.join("self/cgroup"), "0::/app.slice/app-flatpak.scope\n"); + write(&proc.join("self/mountinfo"), "25 20 0:23 / /proc rw - proc proc rw\n"); + assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::NotConstrained); + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + + // Isolated case 2: absent `/sys/fs/cgroup` with a bubblewrap empty-source non-cgroup mount + // (`- tmpfs rw,...`) parses cleanly and reports `NotConstrained`. + let (proc, _) = fixture("absent-cgroup-empty-source"); + let sys = proc.parent().unwrap().join("absent-sys"); + write(&proc.join("self/cgroup"), "0::/app.slice/app-flatpak.scope\n"); + write(&proc.join("self/mountinfo"), "25 20 0:23 / /proc rw - proc proc rw\n26 20 0:24 / /tmp rw,nosuid,nodev - tmpfs rw,nosuid,nodev\n"); + assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::NotConstrained); + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + // A truncated mount line may be the cgroup mount: with /sys/fs/cgroup absent, fail closed. let (proc, _) = fixture("truncated-mountinfo-line"); let sys = proc.parent().unwrap().join("absent-sys"); @@ -1269,4 +1304,91 @@ mod tests { assert_eq!(linux::available_at(&proc, &sys), Some((4 << 30) + (512 << 20)), "legacy helper keeps RAM + swap"); std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); } + + #[cfg(target_os = "linux")] + #[test] + fn linux_parse_mountinfo_handles_empty_mount_source() { + let tmpfs = "26 20 0:24 / /tmp rw,nosuid,nodev - tmpfs rw,nosuid,nodev,size=65536k\n"; + let cg2 = "30 20 0:26 /user.slice /sys/fs/cg\\0402 rw,relatime - cgroup2 rw,nsdelegate\n"; + let truncated = "31 20 0:27 / /sys/fs/cgroup rw - cgroup2 rw\n"; + let mounts = linux::parse_mountinfo(&format!("{tmpfs}{cg2}{truncated}")); + assert_eq!(mounts.len(), 2, "single-space line missing super_options is skipped"); + let m0 = &mounts[0]; + assert_eq!((&m0.root[..], &m0.mount_point[..], &m0.fstype[..]), ("/", "/tmp", "tmpfs")); + assert_eq!((&m0.options[..], &m0.super_options[..]), ("rw,nosuid,nodev", "rw,nosuid,nodev,size=65536k")); + let m1 = &mounts[1]; + assert_eq!((&m1.root[..], &m1.mount_point[..], &m1.fstype[..]), ("/user.slice", "/sys/fs/cg 2", "cgroup2")); + assert_eq!((&m1.options[..], &m1.super_options[..]), ("rw,relatime", "rw,nsdelegate")); + } + + /// An empty `/sys/fs/cgroup` directory only reports `NotConstrained` when `mountinfo` parses + /// cleanly with no cgroup mount; cgroup mounts (including empty-source lines), missing/empty/ + /// truncated `mountinfo`, non-empty directories, files, and unreadable directories fail closed. + #[cfg(target_os = "linux")] + #[test] + fn linux_empty_or_invalid_sys_root_fails_closed_unless_proven_unmounted() { + use std::os::unix::fs::PermissionsExt; + + let bad_mountinfo: [(&str, Option<&str>); 6] = [ + ("empty-sys-missing-mountinfo", None), + ("empty-sys-empty-mountinfo", Some("")), + ("empty-sys-garbage-mountinfo", Some("not a mountinfo line\n")), + ("empty-sys-truncated-mountinfo", Some("25 20 0:23 / /proc rw - proc proc rw\n30 20 0:26 / /sys/fs/cgroup rw - cgroup2\n")), + ("empty-sys-cgroup2-mount", Some("30 20 0:26 / /sys/fs/cgroup rw - cgroup2 cgroup2 rw\n")), + ("empty-sys-empty-source-cgroup2", Some("30 20 0:26 / /sys/fs/cgroup rw - cgroup2 rw\n")), + ]; + for (name, mountinfo) in bad_mountinfo { + let (proc, sys) = fixture(name); + write(&proc.join("self/cgroup"), "0::/app\n"); + if let Some(text) = mountinfo { + write(&proc.join("self/mountinfo"), text); + } + assert!(linux::sys_root_absent_or_empty(&sys), "{name}"); + assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::Unreadable, "{name}"); + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + } + + // Empty `/sys/fs/cgroup` with a v1 memory mount in `mountinfo` also fails closed. + let (proc, sys) = fixture("empty-sys-cgroup-v1-mount"); + write(&proc.join("self/cgroup"), "4:memory:/app\n"); + write(&proc.join("self/mountinfo"), "31 24 0:26 / /sys/fs/cgroup/memory rw - cgroup cgroup rw,memory\n"); + assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::Unreadable); + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + + // A non-empty `/sys/fs/cgroup` directory is not treated as unmounted even with non-cgroup mountinfo. + let (proc, sys) = fixture("non-empty-sys-root"); + write(&proc.join("self/cgroup"), "0::/app\n"); + write(&proc.join("self/mountinfo"), "25 20 0:23 / /proc rw - proc proc rw\n"); + write(&sys.join("memory.max"), "1073741824\n"); + assert!(!linux::sys_root_absent_or_empty(&sys)); + assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::Unreadable); + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + + // `sys_root` as a regular file and a `NotADirectory` path component return false and fail closed. + let (proc, _) = fixture("file-sys-root"); + let file_sys = proc.parent().unwrap().join("sys-as-file"); + write(&file_sys, ""); + write(&proc.join("self/cgroup"), "0::/app\n"); + write(&proc.join("self/mountinfo"), "25 20 0:23 / /proc rw - proc proc rw\n"); + for path in [&file_sys, &file_sys.join("cgroup")] { + assert!(!linux::sys_root_absent_or_empty(path)); + assert_eq!(linux::cgroup_limits(&proc, path), linux::CgroupLimits::Unreadable); + } + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + + // An unreadable `/sys/fs/cgroup` directory (`read_dir` error) returns false and fails closed. + let (proc, sys) = fixture("unreadable-sys-root"); + write(&proc.join("self/cgroup"), "0::/app\n"); + write(&proc.join("self/mountinfo"), "25 20 0:23 / /proc rw - proc proc rw\n"); + std::fs::set_permissions(&sys, std::fs::Permissions::from_mode(0o000)).unwrap(); + let read_blocked = std::fs::read_dir(&sys).is_err(); + let absent = linux::sys_root_absent_or_empty(&sys); + let limits = linux::cgroup_limits(&proc, &sys); + std::fs::set_permissions(&sys, std::fs::Permissions::from_mode(0o700)).unwrap(); + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + if read_blocked { + assert!(!absent); + assert_eq!(limits, linux::CgroupLimits::Unreadable); + } + } } diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 7b4e54e92d..988b08d3d5 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1871,6 +1871,22 @@ fn pencil_outline_cursor(painter: &egui::Painter, xf: &ViewXform, p: Pos2, size: egui::CursorIcon::None } +/// A pen tool's cursor at screen point `p` (document point `doc`): the crosshair for precise Other +/// Cursors (#4639), the black arrow for Add Anchor Point unless a click would split a segment +/// (#12729; ⌘ is Direct Selection's arrow, ⌥ keeps the pen), else the tool's own pen icon. +fn pen_tool_cursor(app: &PhotocraftApp, ui: &egui::Ui, tool: Tool, doc: [f64; 2], p: Pos2) -> egui::CursorIcon { + if precise_other_cursor(app) { + return egui::CursorIcon::Crosshair; + } + if tool == Tool::AddAnchorPoint { + let mods = crate::workspace_ui::sticky_mods(app, ui.input(|i| i.modifiers)); + if !mods.alt && (mods.command || !crate::anchor_tools::adds_anchor_at(app, tool, doc)) { + return crate::tool_cursor::arrow(ui.ctx(), p); + } + } + pen_cursor(ui.ctx(), tool, p) +} + 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; @@ -2004,10 +2020,12 @@ fn draw_default_tool_cursor(app: &mut PhotocraftApp, ui: &mut egui::Ui, input: & { crate::tool_cursor::continue_path(painter, p) } + // Add Anchor Point: the pen with "+" only over a segment a click would split, else the + // black arrow (#12729); ⌘ is Direct Selection's arrow. ⌥ and Precise stay as they were. // The pen tools: their own icon with its nib on the point, or the crosshair for - // precise Other Cursors (#4639). + // precise Other Cursors (#4639); Add Anchor Point the black arrow off a segment (#12729). Tool::Pen | Tool::FreeformPen | Tool::CurvaturePen | Tool::AddAnchorPoint | Tool::DeleteAnchorPoint | Tool::ConvertPoint => { - if precise_other_cursor(app) { egui::CursorIcon::Crosshair } else { pen_cursor(ui.ctx(), tool, p) } + pen_tool_cursor(app, ui, tool, xf.to_doc(p), p) } // Preferences › Cursors › Other Cursors: Precise shows a crosshair for every tool. Tool::Move if crate::move_mods::copying(app, alt) => egui::CursorIcon::Copy, diff --git a/crates/ui-egui/src/canvas/gesture.rs b/crates/ui-egui/src/canvas/gesture.rs index 1b82804e3d..c30bcf1694 100644 --- a/crates/ui-egui/src/canvas/gesture.rs +++ b/crates/ui-egui/src/canvas/gesture.rs @@ -6,6 +6,10 @@ use super::strokes::{ use super::textures::shown_as_document; use super::{PhotocraftApp, Tool, json}; +#[cfg(test)] +#[path = "rectangle_click_in_shape_tests.rs"] +mod rectangle_click_in_shape_tests; + pub(crate) fn finish_gesture(app: &mut PhotocraftApp, d: Drag) { finish(app, d, None); } @@ -110,8 +114,10 @@ fn finish(app: &mut PhotocraftApp, mut d: Drag, click: Option) { // mode a click adds nothing: the dialog makes a shape layer, which Path mode never draws, // and the click's few pixels of travel would add a speck of a subpath to the work path. t if crate::vector_ui::is_shape_tool(t) - && crate::shape_dialog::is_click(d.start, &d.points, app.point_zoom()) - && (crate::vector_ui::draws_path(&app.ui.tool_options) || crate::shape_dialog::open(app, t, d.start).is_some()) => {} + && crate::shape_dialog::is_tool_click(t, &app.ui.tool_options, d.start, &d.points, app.point_zoom()) + && (crate::vector_ui::draws_path(&app.ui.tool_options) + || crate::shape_dialog::click_inside_active_rectangle(app, t, d.start) + || crate::shape_dialog::open(app, t, d.start).is_some()) => {} t if crate::vector_ui::is_shape_tool(t) => crate::vector_ui::finish_shape(app, t, d.start, [end[0], end[1]], d.live), Tool::PathSelection => crate::vector_ui::path_selection_finish(app, d.start, [end[0], end[1]]), Tool::Type | Tool::VerticalType | Tool::HorizontalTypeMask | Tool::VerticalTypeMask => crate::type_tool::pointer_up(app, d.start, [end[0], end[1]]), diff --git a/crates/ui-egui/src/canvas/rectangle_click_in_shape_tests.rs b/crates/ui-egui/src/canvas/rectangle_click_in_shape_tests.rs new file mode 100644 index 0000000000..ec3c180e7f --- /dev/null +++ b/crates/ui-egui/src/canvas/rectangle_click_in_shape_tests.rs @@ -0,0 +1,121 @@ +use crate::canvas::{ToolEvent, tool_event}; +use crate::state::Tool; +use crate::{PhotocraftApp, Services}; +use serde_json::json; + +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Services::default()); + app.run("file.new", json!({"width": 800, "height": 600, "background": "white"})).unwrap(); + app.ui.tool = Tool::Rectangle; + app.ui.extras.snap = false; + app.sync_views(); + app +} + +fn shape(app: &mut PhotocraftApp, kind: &str, radius: f64) { + let radii = [radius; 4]; + app.run("shape.create", json!({"kind": kind, "rect": [400, 300, 200, 100], "radii": radii, "fill": "#ff0000"})).unwrap(); +} + +fn gesture(app: &mut PhotocraftApp, [x, y]: [f64; 2], [end_x, end_y]: [f64; 2]) { + let mods = egui::Modifiers::NONE; + tool_event(app, ToolEvent::Down { x, y, pressure: 1.0 }, mods); + tool_event(app, ToolEvent::Move { x: end_x, y: end_y, pressure: 1.0 }, mods); + tool_event(app, ToolEvent::Up { x: end_x, y: end_y }, mods); +} + +fn state(app: &PhotocraftApp) -> (usize, usize) { + let active = app.session.active().unwrap(); + (active.doc.layer_count(), active.history.past_len()) +} + +fn assert_create_rectangle(app: &PhotocraftApp) { + let [dialog] = app.ui.dialogs.as_slice() else { panic!("expected one Create Rectangle dialog") }; + assert_eq!(dialog.fields["__label"], "Create Rectangle"); + assert_eq!(dialog.fields["width"], 100.0); + assert_eq!(dialog.fields["height"], 100.0); + assert_eq!(dialog.fields["fromCenter"], false); +} + +#[test] +fn inside_the_active_live_rectangle_is_a_no_op() { + let mut app = app(); + shape(&mut app, "rect", 0.0); + let before = state(&app); + let center = [500.0, 350.0]; + for end in [center, [501.0, 350.0]] { + gesture(&mut app, center, end); + assert!(app.ui.dialogs.is_empty()); + assert_eq!(state(&app), before); + } +} + +#[test] +fn outside_the_rectangle_and_on_the_pasteboard_open_create_rectangle() { + for point in [[100.0, 500.0], [-20.0, 500.0]] { + let mut app = app(); + shape(&mut app, "rect", 0.0); + let before = state(&app); + gesture(&mut app, point, point); + assert_create_rectangle(&app); + assert_eq!(state(&app), before); + } +} + +#[test] +fn a_pixel_layer_or_non_rectangle_shape_leaves_the_dialog_available() { + let point = [500.0, 350.0]; + for other_shape in [false, true] { + let mut app = app(); + shape(&mut app, "rect", 0.0); + if other_shape { + shape(&mut app, "ellipse", 0.0); + } else { + app.run("layer.new.layer", json!({"name": "Pixels"})).unwrap(); + } + let before = state(&app); + gesture(&mut app, point, point); + assert_create_rectangle(&app); + assert_eq!(state(&app), before); + } +} + +#[test] +fn rounded_corners_use_the_outline() { + let mut app = app(); + shape(&mut app, "roundedRect", 30.0); + let before = state(&app); + let center = [500.0, 350.0]; + gesture(&mut app, center, center); + assert!(app.ui.dialogs.is_empty()); + assert_eq!(state(&app), before); + let corner = [401.0, 301.0]; + super::finish_gesture(&mut app, super::Drag::new(Tool::Rectangle, corner, vec![[corner[0], corner[1], 1.0]], egui::Modifiers::NONE, false)); + assert_create_rectangle(&app); +} + +#[test] +fn other_modes_keep_their_click_behavior() { + let mut app = app(); + shape(&mut app, "rect", 0.0); + let before = state(&app); + let center = [500.0, 350.0]; + app.ui.tool_options.shape_mode = "path".into(); + gesture(&mut app, center, center); + assert!(app.ui.dialogs.is_empty()); + assert!(app.session.active().unwrap().doc.work_path.is_none()); + app.ui.tool_options.shape_mode = "pixels".into(); + super::finish_gesture(&mut app, super::Drag::new(Tool::Rectangle, center, vec![[center[0], center[1], 1.0]], egui::Modifiers::NONE, false)); + assert_create_rectangle(&app); + assert_eq!(state(&app), before); +} + +#[test] +fn more_than_one_pixel_of_travel_still_draws_a_shape() { + let mut app = app(); + shape(&mut app, "rect", 0.0); + let (layers, history) = state(&app); + gesture(&mut app, [500.0, 350.0], [502.0, 351.0]); + assert!(app.ui.dialogs.is_empty()); + assert_eq!(state(&app), (layers + 1, history + 1)); +} diff --git a/crates/ui-egui/src/canvas/tool_cursor.rs b/crates/ui-egui/src/canvas/tool_cursor.rs index c7244b0c18..7810827393 100644 --- a/crates/ui-egui/src/canvas/tool_cursor.rs +++ b/crates/ui-egui/src/canvas/tool_cursor.rs @@ -12,6 +12,7 @@ use egui::{CursorIcon, CustomCursorImage, Painter, Pos2, Stroke, Vec2, vec2}; use crate::canvas::ViewXform; use crate::state::Tool; +mod arrow; mod bucket; mod hand; mod pen; @@ -30,9 +31,11 @@ const MAX_SIDE: u16 = if cfg!(any(target_os = "windows", target_os = "macos")) { /// What a bitmap cursor shows. `Hand` is the Hand tool's open hand, or its fist while it drags; /// `Zoom` is the Zoom tool's magnifier, with a minus when it zooms out. `Outline` is a brush tip -/// outline: closed rings of logical-point offsets from the hotspot. +/// outline: closed rings of logical-point offsets from the hotspot. `Arrow` is the black arrow +/// pointer, its tip on the hotspot. #[derive(Clone, Debug, PartialEq)] enum Shape { + Arrow, Circle { radius: f32, centre: bool }, Crosshair { length: f32, gap: f32 }, Hand { closed: bool }, @@ -405,6 +408,20 @@ fn hand_with(ctx: &egui::Context, closed: bool, bitmap: bool) -> CursorIcon { if closed { CursorIcon::Grabbing } else { CursorIcon::Grab } } +/// The black arrow pointer, its tip on the pointer (`_at`): an OS cursor bitmap on every platform +/// that takes one, the system arrow where none can be set. +pub(crate) fn arrow(ctx: &egui::Context, _at: Pos2) -> CursorIcon { + arrow_with(ctx, native(ctx)) +} + +fn arrow_with(ctx: &egui::Context, bitmap: bool) -> CursorIcon { + if bitmap && let Some(image) = cached_image(ctx, &Shape::Arrow, native_scale(ctx)) { + ctx.set_cursor_image(Some(image)); + return CursorIcon::None; + } + CursorIcon::Default +} + /// The bitmap [`hand`] hands Windows, for tests that check the Hand's pointer on every platform. #[cfg(test)] pub(crate) fn hand_bitmap(ctx: &egui::Context, closed: bool) -> Option { @@ -589,7 +606,7 @@ fn paint(painter: &Painter, at: Pos2, shape: &Shape) -> bool { } } // Only ever a bitmap: without one the OS draws its own grab cursors. - Shape::Hand { .. } | Shape::Zoom { .. } | Shape::Pipette => {} + Shape::Arrow | Shape::Hand { .. } | Shape::Zoom { .. } | Shape::Pipette => {} } } true @@ -638,6 +655,7 @@ fn extent(shape: &Shape) -> Option { } if *centre { e.max(3.0) } else { e } } + Shape::Arrow => arrow::REACH, Shape::Hand { .. } => hand::HALF, Shape::Zoom { .. } => zoom::HALF, // The 24-unit SVG extends at most 22 units from (2, 22). This extra unit plus @@ -691,6 +709,10 @@ fn coverage(shape: &Shape, dx: f32, dy: f32, scale: f32) -> (f32, f32) { let (lx, ly) = (dx / scale, dy / scale); silhouette(zoom::shape(lx, ly), zoom::glyph(*out, lx, ly), 0.75, scale) } + Shape::Arrow => { + let (lx, ly) = (dx / scale, dy / scale); + silhouette(arrow::shape(lx, ly), f32::MAX, 0.0, scale) + } Shape::Pipette => (0.0, 0.0), // SVG rasterization supplies these pixels. } } @@ -804,7 +826,7 @@ fn rasterize(shape: &Shape, scale: f32) -> Option { let hotf = f32::from(hot); let mut put = |col: usize, row: usize, cov: (f32, f32)| { if let Some(px) = row.checked_mul(n).and_then(|i| i.checked_add(col)).and_then(|i| rgba.get_mut(i * 4..i * 4 + 4)) { - px.copy_from_slice(&stroke_pixel(cov, dark, light)); + px.copy_from_slice(&if matches!(shape, Shape::Arrow) { arrow::pixel(cov) } else { stroke_pixel(cov, dark, light) }); } }; if let Shape::Outline { rings, centre } = shape { @@ -856,7 +878,8 @@ fn rasterize(shape: &Shape, scale: f32) -> Option { } } } - Some(CustomCursorImage { rgba: Arc::from(rgba), size: [side, side], hotspot: [hot, hot] }) + let image = CustomCursorImage { rgba: Arc::from(rgba), size: [side, side], hotspot: [hot, hot] }; + if matches!(shape, Shape::Arrow) { arrow::crop(image) } else { Some(image) } } /// Use the toolbar's actual SVG, with its lower-left tip (2, 22) at the hotspot. @@ -898,3 +921,6 @@ mod tests; #[cfg(test)] mod count_tests; + +#[cfg(test)] +mod add_anchor_cursor_tests; diff --git a/crates/ui-egui/src/canvas/tool_cursor/add_anchor_cursor_tests.rs b/crates/ui-egui/src/canvas/tool_cursor/add_anchor_cursor_tests.rs new file mode 100644 index 0000000000..27b746d7c8 --- /dev/null +++ b/crates/ui-egui/src/canvas/tool_cursor/add_anchor_cursor_tests.rs @@ -0,0 +1,158 @@ +//! #12729: Add Anchor Point's cursor says what a click would do. Over a segment of the targeted path +//! it is the pen with "+"; over an anchor, a handle end, empty canvas, with no path targeted and +//! over a locked shape layer's segments it is the black arrow. ⌘ keeps Direct Selection's arrow, +//! ⌥ and the Precise "Other Cursors" crosshair stay as they were. The tests drive the real canvas +//! (`document_area`) and compare the OS cursor bitmap it hands the platform with the arrow's and +//! the pen's. + +use egui::{CursorIcon, Modifiers, Pos2, vec2}; +use egui_kittest::Harness; +use serde_json::json; + +use super::{PenVariant, Shape, rasterize}; +use crate::PhotocraftApp; +use crate::anchor_tools::delete_anchor_targeted_path_tests::{select_layer, select_saved_path, setup}; +use crate::state::Tool; + +/// Path 1 is the square (50,450)-(150,550); the shape layer is the rectangle (450,100)-(650,250). +const SQUARE_TOP: [f32; 2] = [100.0, 450.0]; +const SQUARE_CORNER: [f32; 2] = [50.0, 450.0]; +const SQUARE_MIDDLE: [f32; 2] = [100.0, 500.0]; +const SHAPE_TOP: [f32; 2] = [550.0, 100.0]; + +/// The canvas at 100 % over `app`, the view centred on `view` (a document point). +fn harness(app: PhotocraftApp, view: [f32; 2]) -> Harness<'static, PhotocraftApp> { + let mut app = app; + app.sync_views(); + app.ui.extras.rulers = false; + let mut h = Harness::builder().with_size(vec2(900.0, 600.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + } + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run_steps(4); + let v = &mut h.state_mut().ui.views[0]; + v.zoom = 1.0; + v.center = view; + v.fit_pending = false; + h.run_steps(2); + h +} + +/// Hover the document point `at` with `mods` held. +fn hover(h: &mut Harness<'static, PhotocraftApp>, at: [f32; 2], view: [f32; 2], mods: Modifiers) { + h.event(egui::Event::ModifiersChanged(mods)); + let p: Pos2 = h.state().last_canvas_rect.center() + vec2(at[0] - view[0], at[1] - view[1]); + h.hover_at(p); + h.run_steps(3); +} + +#[derive(Debug, PartialEq)] +enum Shown { + Arrow, + Pen, + Crosshair, + Other, +} + +/// Which cursor the last frame asked the platform for. +fn shown(h: &Harness<'static, PhotocraftApp>) -> Shown { + let out = &h.output().platform_output; + let scale = super::native_scale(&h.ctx); + let same = + |a: &egui::CustomCursorImage, b: Option| b.is_some_and(|b| a.size == b.size && a.hotspot == b.hotspot && a.rgba == b.rgba); + match &out.cursor_image { + Some(i) if same(i, rasterize(&Shape::Arrow, scale)) => Shown::Arrow, + Some(i) if same(i, PenVariant::from_tool(Tool::AddAnchorPoint).and_then(|v| super::pen::rasterize(v, scale))) => Shown::Pen, + Some(i) if same(i, rasterize(&super::STANDARD_CROSSHAIR, scale)) => Shown::Crosshair, + _ => Shown::Other, + } +} + +/// The square's Path 1 targeted, the pointer at `at` on it. +fn on_path_one(at: [f32; 2], mods: Modifiers) -> Shown { + let (mut app, _) = setup(Tool::AddAnchorPoint); + select_saved_path(&mut app); + let mut h = harness(app, SQUARE_MIDDLE); + hover(&mut h, at, SQUARE_MIDDLE, mods); + shown(&h) +} + +#[test] +fn over_a_segment_of_the_targeted_path_it_is_the_pen_with_plus() { + assert_eq!(on_path_one(SQUARE_TOP, Modifiers::NONE), Shown::Pen); +} + +#[test] +fn over_an_anchor_a_handle_end_or_empty_canvas_it_is_the_black_arrow() { + assert_eq!(on_path_one(SQUARE_CORNER, Modifiers::NONE), Shown::Arrow); + assert_eq!(on_path_one(SQUARE_MIDDLE, Modifiers::NONE), Shown::Arrow); + // A handle end: a curved top edge's out-handle ends in empty canvas, off every segment. + let (mut app, _) = setup(Tool::AddAnchorPoint); + let path = json!({"subpaths": [{"closed": true, "knots": [{"anchor": [50, 450], "in": [50, 450], "out": [50, 400]}, [150, 450], [150, 550], [50, 550]]}]}); + app.run("path.set", json!({"name": "Path 1", "path": path})).unwrap(); + app.ui.selected_path = Some("Path 1".into()); + let mut h = harness(app, SQUARE_MIDDLE); + hover(&mut h, [50.0, 400.0], SQUARE_MIDDLE, Modifiers::NONE); + assert_eq!(shown(&h), Shown::Arrow); +} + +#[test] +fn with_no_path_targeted_it_is_the_black_arrow_everywhere() { + // The active layer is the pixel layer "Red": no path is targeted, whatever lies under the pointer. + for at in [SHAPE_TOP, [450.0, 100.0], [550.0, 175.0], [300.0, 150.0]] { + let (app, _) = setup(Tool::AddAnchorPoint); + let mut h = harness(app, SHAPE_TOP); + hover(&mut h, at, SHAPE_TOP, Modifiers::NONE); + assert_eq!(shown(&h), Shown::Arrow, "{at:?}"); + } +} + +#[test] +fn over_a_segment_of_a_locked_shape_layers_mask_it_is_the_black_arrow() { + let (mut app, shape) = setup(Tool::AddAnchorPoint); + select_layer(&mut app, shape); + let mut h = harness(app, SHAPE_TOP); + hover(&mut h, SHAPE_TOP, SHAPE_TOP, Modifiers::NONE); + assert_eq!(shown(&h), Shown::Pen, "unlocked, the same point is a segment"); + h.state_mut().run("layer.lockLayers", json!({"position": true})).unwrap(); + hover(&mut h, SHAPE_TOP, SHAPE_TOP, Modifiers::NONE); + assert_eq!(shown(&h), Shown::Arrow); +} + +#[test] +fn with_ctrl_held_it_is_the_black_arrow_even_over_a_segment() { + assert_eq!(on_path_one(SQUARE_TOP, Modifiers::COMMAND), Shown::Arrow); +} + +#[test] +fn with_alt_held_it_stays_the_pen_over_empty_canvas() { + assert_eq!(on_path_one(SQUARE_MIDDLE, Modifiers::ALT), Shown::Pen); +} + +#[test] +fn the_precise_other_cursors_crosshair_keeps_working() { + for at in [SQUARE_TOP, SQUARE_MIDDLE] { + let (mut app, _) = setup(Tool::AddAnchorPoint); + select_saved_path(&mut app); + app.run("prefs.set", json!({"path": "cursors.other", "value": "precise"})).unwrap(); + let mut h = harness(app, SQUARE_MIDDLE); + hover(&mut h, at, SQUARE_MIDDLE, Modifiers::NONE); + assert_eq!(shown(&h), Shown::Crosshair, "{at:?}"); + } +} + +#[test] +fn the_arrow_bitmap_is_not_empty_and_its_hotspot_is_the_tip_at_1_1() { + let image = rasterize(&Shape::Arrow, 1.0).unwrap(); + assert_eq!(image.hotspot, [1, 1]); + let alpha = |x: usize, y: usize| image.rgba[(y * usize::from(image.size[0]) + x) * 4 + 3]; + assert!(image.rgba.chunks(4).any(|p| p[3] == 255 && p[0] == 0), "a solid black body"); + assert!(image.rgba.chunks(4).any(|p| p[3] > 0 && p[0] == 255), "a white edge"); + assert!(alpha(1, 1) > 0, "the tip pixel is covered"); + assert_eq!(super::arrow_with(&egui::Context::default(), false), CursorIcon::Default); +} diff --git a/crates/ui-egui/src/canvas/tool_cursor/arrow.rs b/crates/ui-egui/src/canvas/tool_cursor/arrow.rs new file mode 100644 index 0000000000..b99cd20886 --- /dev/null +++ b/crates/ui-egui/src/canvas/tool_cursor/arrow.rs @@ -0,0 +1,60 @@ +//! The black arrow pointer: a filled black arrow with a white edge, PhotoCraft's own drawing from +//! one polygon (tip at the top left, body down to the right, a short tail), as a signed distance +//! field (negative inside) in logical pixels from the tip with y pointing down. The hotspot is the +//! tip; the bitmap is cropped to the arrow so the tip sits one pixel in from its top left corner, +//! at (1, 1) at 100 %. Windows' stock arrow is white, so every platform gets this bitmap. + +use std::sync::Arc; + +use egui::CustomCursorImage; + +use super::hand::capsule; + +/// How far the polygon reaches from the tip, outline excluded. +pub(super) const REACH: f32 = 20.0; + +/// The arrow's corners, clockwise from the tip. +const OUTLINE: [[f32; 2]; 7] = [[0.0, 0.0], [11.5, 11.8], [6.7, 11.8], [9.2, 17.4], [6.6, 18.6], [4.0, 12.8], [0.0, 16.5]]; + +/// The arrow's silhouette: negative inside it. +pub(super) fn shape(x: f32, y: f32) -> f32 { + let mut distance = f32::MAX; + let mut inside = false; + for (&a, &b) in OUTLINE.iter().zip(OUTLINE.iter().cycle().skip(1)) { + distance = distance.min(capsule(x, y, a, b, 0.0)); + // Even-odd rule: a ray towards +x crossing this edge flips the answer. + if (a[1] > y) != (b[1] > y) && x < a[0] + (y - a[1]) * (b[0] - a[0]) / (b[1] - a[1]) { + inside = !inside; + } + } + if inside { -distance } else { distance } +} + +/// One bitmap pixel in straight RGBA: black `fill` over a white edge, `outline` being the coverage +/// of the whole arrow (edge included), each 0 to 1. No coverage is `[0; 4]`. +pub(super) fn pixel((fill, outline): (f32, f32)) -> [u8; 4] { + let edge = outline * (1.0 - fill); + let alpha = fill + edge; + let white = if alpha > 0.0 { (255.0 * edge / alpha).round() as u8 } else { 0 }; + [white, white, white, (255.0 * alpha).round() as u8] +} + +/// Crop `image` (the arrow centred on its hotspot) to the pixels it covers, the hotspot moving +/// with them. `None` when nothing is covered. +pub(super) fn crop(image: CustomCursorImage) -> Option { + let [w, h] = image.size.map(usize::from); + let covered = |col: usize, row: usize| image.rgba.get((row * w + col) * 4 + 3).is_some_and(|&a| a > 0); + let cols: Vec = (0..w).filter(|&c| (0..h).any(|r| covered(c, r))).collect(); + let rows: Vec = (0..h).filter(|&r| (0..w).any(|c| covered(c, r))).collect(); + let (&c0, &c1) = (cols.first()?, cols.last()?); + let (&r0, &r1) = (rows.first()?, rows.last()?); + let mut rgba = Vec::with_capacity((c1 - c0 + 1) * (r1 - r0 + 1) * 4); + for row in r0..=r1 { + rgba.extend_from_slice(image.rgba.get((row * w + c0) * 4..(row * w + c1 + 1) * 4)?); + } + Some(CustomCursorImage { + rgba: Arc::from(rgba), + size: [u16::try_from(c1 - c0 + 1).ok()?, u16::try_from(r1 - r0 + 1).ok()?], + hotspot: [image.hotspot[0].checked_sub(u16::try_from(c0).ok()?)?, image.hotspot[1].checked_sub(u16::try_from(r0).ok()?)?], + }) +} diff --git a/crates/ui-egui/src/canvas/tool_feedback.rs b/crates/ui-egui/src/canvas/tool_feedback.rs index ba7bf35cf6..d25f587c0d 100644 --- a/crates/ui-egui/src/canvas/tool_feedback.rs +++ b/crates/ui-egui/src/canvas/tool_feedback.rs @@ -101,7 +101,14 @@ pub fn badge(app: &PhotocraftApp, tool: Tool, m: egui::Modifiers) -> Option bool { /// True for a press and release that never left `start` by more than a few screen pixels. pub fn is_click(start: [f64; 2], points: &[[f64; 3]], zoom: f32) -> bool { - let slop = 3.0 / f64::from(zoom.max(0.01)); + within_click_slop(start, points, zoom, 3.0) +} + +pub(crate) fn is_tool_click(tool: Tool, options: &crate::state::ToolOptions, start: [f64; 2], points: &[[f64; 3]], zoom: f32) -> bool { + if tool == Tool::Rectangle && options.shape_mode == "shape" { within_click_slop(start, points, zoom, 1.0) } else { is_click(start, points, zoom) } +} + +fn within_click_slop(start: [f64; 2], points: &[[f64; 3]], zoom: f32, pixels: f64) -> bool { + let slop = pixels / f64::from(zoom.max(0.01)); points.iter().all(|p| (p[0] - start[0]).hypot(p[1] - start[1]) <= slop) } +/// A Shape-mode Rectangle click inside the active live rectangle leaves the shape alone (#13340). +pub(crate) fn click_inside_active_rectangle(app: &PhotocraftApp, tool: Tool, at: [f64; 2]) -> bool { + use photocraft_doc::{LayerContent, LiveShape}; + + if tool != Tool::Rectangle || app.ui.tool_options.shape_mode != "shape" { + return false; + } + let Some(layer) = app.session.active().and_then(|st| st.active_layer.and_then(|id| st.doc.layer(id))) else { return false }; + let LayerContent::Shape(shape) = &layer.content else { return false }; + let Some(LiveShape::Rect { rect: [x, y, w, h], radii }) = shape.live else { return false }; + let (left, top) = (x.min(x + w), y.min(y + h)); + let (right, bottom) = (x.max(x + w), y.max(y + h)); + let [px, py] = at; + if !((left..=right).contains(&px) && (top..=bottom).contains(&py)) { + return false; + } + let (l, r, t, b) = (px - left, right - px, py - top, bottom - py); + [(l, t), (r, t), (r, b), (l, b)] + .into_iter() + .zip(photocraft_vector::shapes::clamp_radii(w.abs(), h.abs(), radii)) + .all(|((dx, dy), radius)| dx >= radius || dy >= radius || (radius - dx).hypot(radius - dy) <= radius) +} + /// Open the creation dialog of `tool` for a click at `at` (document px). `None` for a tool without /// one (Line, Custom Shape). pub fn open(app: &mut PhotocraftApp, tool: Tool, at: [f64; 2]) -> Option { diff --git a/crates/ui-egui/src/dialogs/shape_dialog/tests.rs b/crates/ui-egui/src/dialogs/shape_dialog/tests.rs index 1ca5de28f7..03f65d743d 100644 --- a/crates/ui-egui/src/dialogs/shape_dialog/tests.rs +++ b/crates/ui-egui/src/dialogs/shape_dialog/tests.rs @@ -174,7 +174,7 @@ fn a_click_with_jitter_opens_the_dialog_on_hidpi() { let i = app.session.active_index().unwrap(); app.ui.views[i].zoom = 1.0; let before = layers(&app); - press(&mut app, Tool::Rectangle, [20.0, 30.0], [24.0, 30.0]); + press(&mut app, Tool::Rectangle, [20.0, 30.0], [22.0, 30.0]); only_dialog(&app); assert_eq!(layers(&app), before, "a jittery click draws nothing"); } @@ -347,7 +347,7 @@ fn right_click_picks_the_unit_of_that_field_only_and_it_is_not_remembered() { set(&mut app, id, json!({"widthUnit": "mm", "width": 50})); crate::dialogs::confirm(&mut app, id).unwrap(); app.run("prefs.set", json!({"path": "unitsAndRulers.rulers", "value": "cm"})).unwrap(); - press(&mut app, Tool::Rectangle, [40.0, 40.0], [40.0, 40.0]); + press(&mut app, Tool::Rectangle, [140.0, 140.0], [140.0, 140.0]); let id = only_dialog(&app); let mut f = app.ui.dialog_mut(id).unwrap().fields.clone(); assert_eq!((f.get("widthUnit"), f["width"].as_f64()), (None, Some(50.0)), "the size is remembered, the unit isn't"); diff --git a/crates/ui-egui/src/home_recent_ui.rs b/crates/ui-egui/src/home_recent_ui.rs index 2cd4d5d2b4..e8f25a1e72 100644 --- a/crates/ui-egui/src/home_recent_ui.rs +++ b/crates/ui-egui/src/home_recent_ui.rs @@ -82,18 +82,13 @@ impl ThumbnailCache { /// Check if two path strings match, tolerating slash direction and Windows case differences. fn paths_match(a: &str, b: &str) -> bool { - if a == b { - return true; - } #[cfg(windows)] { - let a_norm = a.replace('\\', "/"); - let b_norm = b.replace('\\', "/"); - a_norm.eq_ignore_ascii_case(&b_norm) + a == b || a.replace('\\', "/").eq_ignore_ascii_case(&b.replace('\\', "/")) } #[cfg(not(windows))] { - false + a == b } } diff --git a/crates/ui-egui/src/retouch_mode_refusal_alert_tests.rs b/crates/ui-egui/src/retouch_mode_refusal_alert_tests.rs new file mode 100644 index 0000000000..eba8c7bce4 --- /dev/null +++ b/crates/ui-egui/src/retouch_mode_refusal_alert_tests.rs @@ -0,0 +1,41 @@ +//! #12673, #13033, #12656, #12967: a press with the Burn, Sponge, Blur or Smudge tool in an Indexed +//! Color or Bitmap document opens the reference application's colour-mode alert with OK, once, and +//! paints nothing; in RGB the same press still paints. + +use serde_json::json; + +use super::brush_refusal_alert_tests::{alerts, app, refused, steps, stroke}; +use super::*; + +const TOOLS: [(Tool, &str); 4] = [(Tool::Burn, "burn tool"), (Tool::Sponge, "sponge tool"), (Tool::Blur, "blur tool"), (Tool::Smudge, "smudge tool")]; + +#[test] +fn indexed_color_documents_get_the_mode_alert() { + for (tool, name) in TOOLS { + let mut app = app(tool); + app.run("image.mode.indexedColor", json!({"palette": "exact", "dither": "none", "forced": "none"})).unwrap(); + refused(&mut app, &format!("Could not use the {name} because it does not work with Indexed Color images (convert image to RGB Color mode to edit).")); + } +} + +#[test] +fn bitmap_documents_get_the_mode_alert() { + for (tool, name) in TOOLS { + let mut app = app(tool); + app.run("image.mode.grayscale", json!({})).unwrap(); + app.run("image.mode.bitmap", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().doc.mode, photocraft_doc::ColorMode::Bitmap); + refused(&mut app, &format!("Could not use the {name} because it does not work with Bitmap images (convert image to Grayscale mode to edit).")); + } +} + +#[test] +fn rgb_documents_keep_painting() { + for (tool, _) in TOOLS { + let mut app = app(tool); + let before = steps(&app); + stroke(&mut app); + assert!(alerts(&app).is_empty(), "{tool:?}: no alert"); + assert_eq!(steps(&app), before + 1, "{tool:?}: the stroke was applied"); + } +} diff --git a/crates/ui-egui/src/tools.rs b/crates/ui-egui/src/tools.rs index 41ef241233..721057faac 100644 --- a/crates/ui-egui/src/tools.rs +++ b/crates/ui-egui/src/tools.rs @@ -76,6 +76,8 @@ mod gradient_options_bar_mode_tests; mod gradient_refusal_messages_tests; #[cfg(test)] mod line_tool_defaults_tests; +#[cfg(test)] +mod path_selection_shape_over_saved_path_tests; #[cfg(test)] mod remove_default_size_tests; diff --git a/crates/ui-egui/src/tools/anchor_tools.rs b/crates/ui-egui/src/tools/anchor_tools.rs index 4c5aa8d6f1..f36814934c 100644 --- a/crates/ui-egui/src/tools/anchor_tools.rs +++ b/crates/ui-egui/src/tools/anchor_tools.rs @@ -69,6 +69,13 @@ fn target(app: &PhotocraftApp, tool: Tool, p: [f64; 2]) -> Option<(PathRef, Path } } +/// Whether a click at `p` with Add Anchor Point (`tool`) would add an anchor: the pointer is over +/// a segment of the targeted path that the tool may edit. Read-only; the cursor and its badge +/// (#12729) ask it, so they show the pen with "+" only where a click does something. +pub(crate) fn adds_anchor_at(app: &PhotocraftApp, tool: Tool, p: [f64; 2]) -> bool { + tool == Tool::AddAnchorPoint && target(app, tool, p).is_some() +} + /// The Pen's Auto Add/Delete (#4144): what a Pen click at `p` does to the active path instead of /// starting a new one, as the anchor tool that does it (Add Anchor Point on a segment, Delete /// Anchor Point on an anchor), the path and the hit. While a path is being drawn it edits that diff --git a/crates/ui-egui/src/tools/anchor_tools/tests.rs b/crates/ui-egui/src/tools/anchor_tools/tests.rs index ef815c66cf..ae58b9b611 100644 --- a/crates/ui-egui/src/tools/anchor_tools/tests.rs +++ b/crates/ui-egui/src/tools/anchor_tools/tests.rs @@ -148,7 +148,13 @@ fn shape_layer_paths_are_edited_and_the_added_anchor_replaces_the_selection() { #[test] fn the_cursor_shows_plus_or_minus() { use crate::tool_feedback::{Badge, badge}; - let app = app(Tool::AddAnchorPoint); + let mut app = app(Tool::AddAnchorPoint); + assert_eq!(badge(&app, Tool::AddAnchorPoint, Modifiers::NONE), None, "no path targeted, no segment under the pointer (#12729)"); + with_path(&mut app); + app.ui.selected_path = Some("work".into()); + app.hover_doc = Some([80.0, 80.0]); + assert_eq!(badge(&app, Tool::AddAnchorPoint, Modifiers::NONE), None, "off the path's segments"); + app.hover_doc = Some([80.0, 120.0]); assert_eq!(badge(&app, Tool::AddAnchorPoint, Modifiers::NONE), Some(Badge::Add)); assert_eq!(badge(&app, Tool::AddAnchorPoint, Modifiers::ALT), Some(Badge::Subtract)); assert_eq!(badge(&app, Tool::DeleteAnchorPoint, Modifiers::NONE), Some(Badge::Subtract)); diff --git a/crates/ui-egui/src/tools/brush_refusal.rs b/crates/ui-egui/src/tools/brush_refusal.rs index bfa63bb3ab..0fa245f0b5 100644 --- a/crates/ui-egui/src/tools/brush_refusal.rs +++ b/crates/ui-egui/src/tools/brush_refusal.rs @@ -22,13 +22,17 @@ pub const REMOVE_LOCKED: &str = "Can't use the tool because the layer is locked. pub const INDEXED: &str = "Could not use the {tool} because it does not work with Indexed Color images (convert image to RGB Color mode to edit)."; 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 the Dodge -/// tool yet (#12685). +/// The tool's name in the colour-mode alerts, for the tools whose wording was measured: the Dodge, +/// Burn, Sponge, Blur, Sharpen and Smudge tools. Kept apart from [`tool_name`]: the layer alerts +/// aren't wired for all of them yet (#12685). fn mode_tool_name(tool: Tool) -> Option<&'static str> { match tool { Tool::Dodge => Some(tl!("dodge tool")), + Tool::Burn => Some(tl!("burn tool")), + Tool::Sponge => Some(tl!("sponge tool")), + Tool::Blur => Some(tl!("blur tool")), Tool::Sharpen => Some(tl!("sharpen tool")), + Tool::Smudge => Some(tl!("smudge tool")), _ => None, } } @@ -110,6 +114,10 @@ mod sharpen_refusal_alert_tests; #[path = "../sponge_refusal_alert_tests.rs"] mod sponge_refusal_alert_tests; +#[cfg(test)] +#[path = "../retouch_mode_refusal_alert_tests.rs"] +mod retouch_mode_refusal_alert_tests; + #[cfg(test)] #[path = "../bucket_bitmap_alert_tests.rs"] mod bucket_bitmap_alert_tests; diff --git a/crates/ui-egui/src/tools/path_components.rs b/crates/ui-egui/src/tools/path_components.rs index 041279b748..f55b6109d8 100644 --- a/crates/ui-egui/src/tools/path_components.rs +++ b/crates/ui-egui/src/tools/path_components.rs @@ -32,6 +32,17 @@ fn target(app: &PhotocraftApp) -> Option<(PathRef, Path)> { active_paths(app).into_iter().next() } +/// A Path Selection press on a shape layer, off every component of the targeted saved path: +/// the saved path is no longer the target, so the press and drag act on the shape (#13270). +/// A press on one of the saved path's components keeps it targeted. +pub(crate) fn untarget_saved_path_off(app: &mut PhotocraftApp, at: [f64; 2], tol: f64) { + if let Some((PathRef::Saved(_), path)) = target(app) + && component_at(&path, at, tol).is_none() + { + app.ui.selected_path = None; + } +} + /// The selected components: their path and the first subpath of each, in order. `None` with /// nothing selected, a selection on a path that is not an active one any more, or a tool other /// than Path Selection (the only one that shows it, so the only one that acts on it). diff --git a/crates/ui-egui/src/tools/path_selection_shape_over_saved_path_tests.rs b/crates/ui-egui/src/tools/path_selection_shape_over_saved_path_tests.rs new file mode 100644 index 0000000000..4590657480 --- /dev/null +++ b/crates/ui-egui/src/tools/path_selection_shape_over_saved_path_tests.rs @@ -0,0 +1,70 @@ +//! #13270: with a saved path targeted in the Paths panel, a Path Selection drag on a shape layer +//! targets and moves the shape, as in the reference application; the saved path keeps its points. +//! A drag on a component of the saved path still moves that component. + +use egui::Modifiers; +use photocraft_doc::{LayerContent, LayerId, Path}; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::state::Tool; + +const SAVED: &str = "Path 1"; + +/// A rectangle shape at 500,100–700,200, a pixel layer "Red" above it, active, and the saved +/// path "Path 1" (a square 100,300–200,400) selected in the Paths panel, with Path Selection. +fn setup() -> (PhotocraftApp, LayerId) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 800, "height": 600, "background": "white"})).unwrap(); + app.run("shape.create", json!({"kind": "rect", "rect": [500, 100, 200, 100], "fill": "#2050c0"})).unwrap(); + let shape = app.session.active().unwrap().active_layer.unwrap(); + app.run("layer.new.layer", json!({"name": "Red"})).unwrap(); + let square = json!({"subpaths": [{"closed": true, "knots": [[100, 300], [200, 300], [200, 400], [100, 400]]}]}); + app.run("path.set", json!({"name": SAVED, "path": square})).unwrap(); + app.ui.selected_path = Some(SAVED.into()); + app.ui.tool = Tool::PathSelection; + (app, shape) +} + +fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2]) { + tool_event(app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, Modifiers::NONE); + let mid = [(from[0] + to[0]) / 2.0, (from[1] + to[1]) / 2.0]; + tool_event(app, ToolEvent::Move { x: mid[0], y: mid[1], pressure: 1.0 }, Modifiers::NONE); + tool_event(app, ToolEvent::Move { x: to[0], y: to[1], pressure: 1.0 }, Modifiers::NONE); + tool_event(app, ToolEvent::Up { x: to[0], y: to[1] }, Modifiers::NONE); +} + +fn saved(app: &PhotocraftApp) -> Path { + app.session.active().unwrap().doc.paths.iter().find(|p| p.name == SAVED).unwrap().path.clone() +} + +fn shape_bounds(app: &PhotocraftApp, id: LayerId) -> Option<(f64, f64, f64, f64)> { + let doc = &app.session.active().unwrap().doc; + doc.walk().iter().find(|(_, _, l)| l.id == id).and_then(|(_, _, l)| match &l.content { + LayerContent::Shape(sh) => sh.path.control_bounds(), + _ => None, + }) +} + +#[test] +fn a_drag_on_a_shape_moves_the_shape_not_the_targeted_saved_path() { + let (mut app, shape) = setup(); + let (path_before, shape_before) = (saved(&app), shape_bounds(&app, shape).unwrap()); + drag(&mut app, [600.0, 150.0], [650.0, 200.0]); + assert_eq!(app.session.active().unwrap().active_layer, Some(shape), "the shape is the active layer"); + assert_eq!(saved(&app), path_before, "the saved path keeps its points"); + let (x0, y0, x1, y1) = shape_before; + assert_eq!(shape_bounds(&app, shape), Some((x0 + 50.0, y0 + 50.0, x1 + 50.0, y1 + 50.0)), "the shape moved by the drag"); + assert_eq!(app.ui.selected_path, None, "the saved path is no longer the target"); +} + +#[test] +fn a_drag_on_a_component_of_the_saved_path_still_moves_it() { + let (mut app, shape) = setup(); + let shape_before = shape_bounds(&app, shape); + drag(&mut app, [150.0, 350.0], [180.0, 370.0]); + assert_eq!(saved(&app).control_bounds(), Some((130.0, 320.0, 230.0, 420.0)), "the saved path moved"); + assert_eq!(shape_bounds(&app, shape), shape_before, "the shape stays"); + assert_eq!(app.ui.selected_path.as_deref(), Some(SAVED)); +} diff --git a/crates/ui-egui/src/tools/perspective_crop_mirrored_tests.rs b/crates/ui-egui/src/tools/perspective_crop_mirrored_tests.rs new file mode 100644 index 0000000000..e01e64387c --- /dev/null +++ b/crates/ui-egui/src/tools/perspective_crop_mirrored_tests.rs @@ -0,0 +1,138 @@ +//! #12489: a Perspective Crop box flipped on one axis (⌥ dragging a corner past the opposite one +//! along x only) is wound counter-clockwise. It is drawn valid and commits mirrored, each corner +//! mapped as it lies, as in the reference application; `image.perspectiveCrop` takes the same +//! corners. Clicked corners still commit upright, a box turned 180° still commits upside down, and +//! self-crossing and degenerate quads stay invalid. + +use std::sync::Arc; + +use egui::{Modifiers, Pos2, Rect, vec2}; +use serde_json::json; + +use super::*; + +const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0]; +const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0]; +const BLUE: [f32; 4] = [0.0, 0.0, 1.0, 1.0]; +const YELLOW: [f32; 4] = [1.0, 1.0, 0.0, 1.0]; + +/// The measured test document: 800 x 500, red (top left), green (top right), blue (bottom left) +/// and yellow (bottom right) quadrants with a black square in the middle; the Perspective Crop tool. +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 800, "height": 500})).unwrap(); + app.sync_views(); + app.ui.tool = Tool::PerspectiveCrop; + let surf = Arc::make_mut(&mut app.session.active_mut().unwrap().doc).layers[0].surface_mut().unwrap(); + for (x, y, c) in [(0, 0, RED), (400, 0, GREEN), (0, 250, BLUE), (400, 250, YELLOW)] { + surf.fill_rect(photocraft_geom::Rect::from_xywh(x, y, 400, 250), &c); + } + surf.fill_rect(photocraft_geom::Rect::from_xywh(395, 245, 10, 10), &[0.0, 0.0, 0.0, 1.0]); + app +} + +fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2], mods: Modifiers) { + assert!(pointer(app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, mods)); + let mid = [(from[0] + to[0]) / 2.0, (from[1] + to[1]) / 2.0]; + assert!(pointer(app, ToolEvent::Move { x: mid[0], y: mid[1], pressure: 1.0 }, mods)); + assert!(pointer(app, ToolEvent::Move { x: to[0], y: to[1], pressure: 1.0 }, mods)); + assert!(pointer(app, ToolEvent::Up { x: to[0], y: to[1] }, mods)); +} + +fn click(app: &mut PhotocraftApp, p: [f64; 2]) { + drag(app, p, p, Modifiers::NONE); +} + +/// The overlay `draw_overlay` paints: (shield polygons, whether the frame is red). +fn overlay(app: &PhotocraftApp) -> (usize, bool) { + let ctx = egui::Context::default(); + let xf = + ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(800.0, 500.0)), zoom: 1.0, center: [400.0, 250.0], flip: false, rotation: 0.0, aspect: 1.0 }; + let mut o = ctx.run_ui(Default::default(), |ui| draw_overlay(app, ui.painter(), &xf)); + o.textures_delta.clear(); + let shield = o.shapes.iter().filter(|c| matches!(&c.shape, egui::Shape::Path(p) if p.fill == SHIELD)).count(); + let red = Color32::from_rgb(0xe5, 0x3e, 0x3e); + let frame_red = o.shapes.iter().any(|c| matches!(&c.shape, egui::Shape::Path(p) if p.closed && p.stroke.color == egui::epaint::ColorMode::Solid(red))); + (shield, frame_red) +} + +/// The committed canvas's size and the colours at its four corners (TL, TR, BL, BR). +fn corners(app: &PhotocraftApp) -> ((u32, u32), [[f32; 4]; 4]) { + let doc = &app.session.active().unwrap().doc; + let (w, h) = (doc.size.width as i32, doc.size.height as i32); + let surf = doc.layers[0].surface().unwrap(); + ((doc.size.width, doc.size.height), [surf.rgba(3, 3), surf.rgba(w - 4, 3), surf.rgba(3, h - 4), surf.rgba(w - 4, h - 4)]) +} + +#[test] +fn alt_corner_drag_past_the_opposite_corner_on_one_axis_commits_mirrored() { + let mut app = app(); + // A fresh 100 x 100 box, its bottom right corner ⌥ dragged past the fixed top left one on x only. + drag(&mut app, [450.0, 220.0], [550.0, 320.0], Modifiers::NONE); + drag(&mut app, [550.0, 320.0], [350.0, 300.0], Modifiers::ALT); + assert_eq!(app.ui.perspective_crop, Some([[450.0, 220.0], [350.0, 220.0], [350.0, 300.0], [450.0, 300.0]]), "flipped left to right"); + let (shield, red) = overlay(&app); + assert!(shield > 0 && !red, "drawn as a valid quad: accent frame and shield, not red"); + commit(&mut app); + assert!(app.ui.perspective_crop.is_none(), "committed"); + let (size, [tl, tr, bl, br]) = corners(&app); + assert_eq!(size, (100, 80)); + assert_eq!([tl, tr, bl, br], [GREEN, RED, YELLOW, BLUE], "mirrored left to right, top stays on top"); +} + +#[test] +fn the_command_takes_counter_clockwise_corners_and_mirrors() { + let mut app = app(); + let r = app.run("image.perspectiveCrop", json!({"corners": [[450, 220], [350, 220], [350, 300], [450, 300]]})).unwrap(); + assert_eq!((r["width"].as_u64(), r["height"].as_u64()), (Some(100), Some(80))); + assert_eq!(corners(&app).1, [GREEN, RED, YELLOW, BLUE]); + // Mirrored top to bottom the other way round. + let mut app = self::app(); + app.run("image.perspectiveCrop", json!({"corners": [[350, 300], [450, 300], [450, 220], [350, 220]]})).unwrap(); + assert_eq!(corners(&app).1, [BLUE, YELLOW, RED, GREEN]); +} + +#[test] +fn clicked_corners_commit_upright_in_any_order() { + let mut app = app(); + // Counter-clockwise clicks from the top left. + for p in [[350.0, 220.0], [350.0, 300.0], [450.0, 300.0], [450.0, 220.0]] { + click(&mut app, p); + } + assert_eq!(app.ui.perspective_crop, Some([[350.0, 220.0], [450.0, 220.0], [450.0, 300.0], [350.0, 300.0]]), "sorted clockwise"); + commit(&mut app); + assert_eq!(corners(&app), ((100, 80), [RED, GREEN, BLUE, YELLOW])); +} + +#[test] +fn a_box_turned_180_degrees_commits_upside_down() { + let mut app = app(); + drag(&mut app, [450.0, 300.0], [550.0, 400.0], Modifiers::NONE); + drag(&mut app, [550.0, 400.0], [350.0, 200.0], Modifiers::ALT); + assert_eq!(app.ui.perspective_crop, Some([[450.0, 300.0], [350.0, 300.0], [350.0, 200.0], [450.0, 200.0]])); + commit(&mut app); + assert_eq!(corners(&app), ((100, 100), [YELLOW, BLUE, GREEN, RED])); +} + +#[test] +fn self_crossing_and_degenerate_quads_stay_invalid() { + for q in [ + // Self-crossing (a bow tie), each way round. + [[350.0, 220.0], [450.0, 220.0], [350.0, 300.0], [450.0, 300.0]], + [[450.0, 220.0], [350.0, 220.0], [450.0, 300.0], [350.0, 300.0]], + // Three corners on a line, and no area. + [[350.0, 220.0], [400.0, 220.0], [450.0, 220.0], [350.0, 300.0]], + [[400.0, 250.0]; 4], + ] { + let mut app = app(); + app.ui.perspective_crop = Some(q); + let (shield, red) = overlay(&app); + assert!(shield == 0 && red, "{q:?} is drawn red without the shield"); + assert!(app.run("image.perspectiveCrop", json!({ "corners": q })).is_err(), "{q:?}"); + commit(&mut app); + assert_eq!(app.ui.perspective_crop, Some(q), "{q:?} stays for fixing"); + assert_eq!(app.session.active().unwrap().doc.size.width, 800); + } + let mut app = app(); + assert!(app.run("image.perspectiveCrop", json!({"corners": [[350, 220], [f64::NAN, 220], [450, 300], [350, 300]]})).is_err()); +} diff --git a/crates/ui-egui/src/tools/perspective_crop_ui.rs b/crates/ui-egui/src/tools/perspective_crop_ui.rs index 0fb7765294..aad099ee2c 100644 --- a/crates/ui-egui/src/tools/perspective_crop_ui.rs +++ b/crates/ui-egui/src/tools/perspective_crop_ui.rs @@ -4,8 +4,8 @@ //! BL in document px; clicked corners are put in that order); //! - drag a corner to move it alone, onto an edge of a skewed object (a photographed page, a //! facade); drag inside the quad to move it; -//! - the quad shows its perspective grid (Show Grid) and turns red while it isn't a convex quad -//! wound like its box, which can't be committed; +//! - the quad shows its perspective grid (Show Grid) and turns red while it isn't a convex quad, +//! which can't be committed; one flipped on one axis (wound the other way) commits mirrored; //! - ↵ (or ✓) commits: `image.perspectiveCrop` maps the quad onto an upright rectangle, the whole //! document in one undo step. Its size comes from the options bar's W x H (and the resolution), //! which are the Crop tool's fields (`crop_size`), or with them empty from the rectangle the @@ -14,7 +14,7 @@ //! A pending quad belongs to the document it was drawn on, like the Crop tool's frame. use egui::{Color32, Pos2, Stroke}; -use photocraft_algo::transform::{Homography, convex_quad}; +use photocraft_algo::transform::{Homography, convex_quad, convex_quad_any_winding}; use photocraft_engine::prefs::Unit; use serde_json::{Value, json}; @@ -426,7 +426,8 @@ pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform _ => app.ui.perspective_crop, }; if let Some(q) = quad.filter(|q| q.iter().flatten().all(|v| v.is_finite())) { - let ok = convex_quad(&q); + // A quad flipped on one axis is wound counter-clockwise and commits mirrored (#12489). + let ok = convex_quad_any_winding(&q); let color = if ok { accent } else { Color32::from_rgb(0xe5, 0x3e, 0x3e) }; // The image outside the quad is dimmed (#11972), following the quad while it is dragged. if ok && let Some(size) = app.session.active().map(|d| d.doc.size) { @@ -554,6 +555,10 @@ mod perspective_crop_shield_tests; #[path = "perspective_crop_deselect_tests.rs"] mod perspective_crop_deselect_tests; +#[cfg(test)] +#[path = "perspective_crop_mirrored_tests.rs"] +mod perspective_crop_mirrored_tests; + #[cfg(test)] mod tests { use super::*; diff --git a/crates/ui-egui/src/tools/rectangle_radius_target_tests.rs b/crates/ui-egui/src/tools/rectangle_radius_target_tests.rs new file mode 100644 index 0000000000..9c9a5bf46d --- /dev/null +++ b/crates/ui-egui/src/tools/rectangle_radius_target_tests.rs @@ -0,0 +1,111 @@ +//! #13338: the Rectangle tool's options-bar Radius sets the next rectangle, not the active shape. +//! It shows the tool's own radius. The Path Selection / Direct Selection Radius still edits the +//! active shape. + +use egui::accesskit::Role; +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use photocraft_doc::{LayerContent, LiveShape}; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::state::Tool; + +/// A document with Rectangle 1 (radius 20) as the active layer, and `tool` current. +fn bar_with(tool: Tool) -> Harness<'static, PhotocraftApp> { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("shape.create", json!({"kind": "roundedRect", "rect": [10, 10, 80, 60], "radii": [20, 20, 20, 20], "fill": "#ff0000"})).unwrap(); + app.sync_views(); + app.ui.tool = tool; + 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 type_radius(h: &mut Harness<'static, PhotocraftApp>, text: &str) { + h.query_all_by_role(Role::SpinButton).find(|n| n.accesskit_node().label().as_deref() == Some("Radius:")).expect("the Radius field").click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.event(egui::Event::Text(text.into())); + h.run_steps(1); + h.key_press(egui::Key::Tab); + h.run_steps(3); +} + +fn history_len(h: &Harness<'static, PhotocraftApp>) -> usize { + h.state().session.active().unwrap().history.past_len() +} + +/// The first radius of every rectangle shape layer, bottom to top. +fn radii(h: &Harness<'static, PhotocraftApp>) -> Vec { + let st = h.state().session.active().unwrap(); + st.doc + .walk() + .into_iter() + .filter_map(|(_, _, l)| match &l.content { + LayerContent::Shape(sh) => match &sh.live { + Some(LiveShape::Rect { radii, .. }) => Some(radii[0]), + _ => None, + }, + _ => None, + }) + .collect() +} + +fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2]) { + let mods = egui::Modifiers::NONE; + 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); +} + +#[test] +fn the_rectangle_tools_radius_field_leaves_the_active_shape_alone() { + let mut h = bar_with(Tool::Rectangle); + let before = history_len(&h); + type_radius(&mut h, "5000"); + assert_eq!(radii(&h), vec![20.0], "Rectangle 1 keeps its radius"); + assert_eq!(history_len(&h), before, "no History state"); + assert_eq!(h.state().ui.tool_options.corner_radius, 5000.0); +} + +#[test] +fn the_next_rectangle_takes_the_typed_radius() { + let mut h = bar_with(Tool::Rectangle); + type_radius(&mut h, "5000"); + drag(h.state_mut(), [100.0, 100.0], [180.0, 170.0]); + let all = radii(&h); + assert_eq!(all.len(), 2, "a second rectangle was drawn: {all:?}"); + assert_eq!(all[0], 20.0); + assert_eq!(all[1], 5000.0); +} + +#[test] +fn the_rectangle_tools_radius_field_shows_the_tools_radius() { + let mut h = bar_with(Tool::Rectangle); + h.state_mut().ui.tool_options.corner_radius = 0.0; + h.run_steps(3); + let field = h.query_all_by_role(Role::SpinButton).find(|n| n.accesskit_node().label().as_deref() == Some("Radius:")).expect("the Radius field"); + let shown = field + .accesskit_node() + .numeric_value() + .map(|v| v as f32) + .or_else(|| field.accesskit_node().value().and_then(|v| v.trim_end_matches(" px").trim().parse().ok())); + assert_eq!(shown, Some(0.0), "the tool's radius, not the shape's 20"); +} + +#[test] +fn the_path_selection_radius_field_still_edits_the_active_shape() { + for tool in [Tool::PathSelection, Tool::DirectSelection] { + let mut h = bar_with(tool); + let before = history_len(&h); + type_radius(&mut h, "30"); + assert_eq!(radii(&h), vec![30.0], "{tool:?}: the active shape takes it"); + assert_eq!(history_len(&h), before + 1, "{tool:?}: one History state"); + } +} diff --git a/crates/ui-egui/src/tools/shape_options.rs b/crates/ui-egui/src/tools/shape_options.rs index d0f7e3c5a8..966fdff212 100644 --- a/crates/ui-egui/src/tools/shape_options.rs +++ b/crates/ui-egui/src/tools/shape_options.rs @@ -107,16 +107,12 @@ pub(crate) fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool crate::widgets::vline(ui, 22.0); let label = tl!("Radius:"); lbl(ui, label); - let mut r = match target.as_ref().and_then(|s| s.live.as_ref()) { - Some(photocraft_doc::LiveShape::Rect { radii, .. }) => radii[0] as f32, - _ => o.corner_radius, - }; + // The tool's own radius for the next rectangle (#13338); the active shape is not touched. + let mut r = o.corner_radius; let (resp, out_of_range) = crate::widgets::value_field_alerting(ui, label, &mut r, RADIUS_RANGE, "px", 62.0); radius_alert = out_of_range; if resp.changed() { o.corner_radius = r; - let rf = r as f64; - edit = Some(json!({"radii": [rf, rf, rf, rf], "coalesce": key("radius")})); } } Tool::Polygon => { @@ -225,6 +221,10 @@ fn radius_range_alert(app: &mut PhotocraftApp, owed: bool) { #[path = "rectangle_radius_range_tests.rs"] mod rectangle_radius_range_tests; +#[cfg(test)] +#[path = "rectangle_radius_target_tests.rs"] +mod rectangle_radius_target_tests; + /// Tool-bar paint changes affect the next shape; Properties edits the selected shape instead. pub(crate) fn set_tool_paint(app: &mut PhotocraftApp, stroke: bool, change: PaintChange) -> Result<(), String> { // A colour takes the place of a gradient; No Color keeps it for when the paint comes back.