PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Crop tool: show the pixels past the canvas while a frame is edited, as Photoshop does (#1508)
Unemars6054a8a01918
diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rsindex c929246fb..31817c83d 100644--- a/crates/compose/src/lib.rs+++ b/crates/compose/src/lib.rs@@ -309,7 +309,14 @@ pub fn thumbnail_buffer(doc: &Document, max_side: u32) -> Buffer {/// The document's composite area-averaged (premultiplied) down to `w`×`h` (clamped to the/// document size), rendered in bands so no full-size composite is held.pub fn render_reduced(doc: &Document, w: u32, h: u32) -> Buffer {- render_reduced_in_bands(doc, w, h, None, 0)+ render_reduced_in_bands(doc, doc.bounds(), w, h, None, 0)+}++/// [`render_reduced`] of any area of the document plane, `rect`, which may lie past the canvas+/// (layer pixels there are kept until a crop deletes them). The buffer's rect is in output pixels+/// from (0, 0).+pub fn render_reduced_rect(doc: &Document, rect: Rect, w: u32, h: u32) -> Buffer {+ render_reduced_in_bands(doc, rect, w, h, None, 0)}/// The part of [`render_reduced`]`(doc, w, h)` that a change to `damage` (document pixels) can@@ -317,13 +324,12 @@ pub fn render_reduced(doc: &Document, w: u32, h: u32) -> Buffer {/// same values the whole reduction gives them. The buffer's rect is in output pixels (empty when/// `damage` misses the document), so a reduced canvas texture can update only what a stroke touched.pub fn render_reduced_damage(doc: &Document, w: u32, h: u32, damage: Rect) -> Buffer {- render_reduced_in_bands(doc, w, h, Some(damage), 0)+ render_reduced_in_bands(doc, doc.bounds(), w, h, Some(damage), 0)}-/// [`render_reduced`] (or, with `damage`, [`render_reduced_damage`]) with an explicit band height-/// (see [`render_bands`]).-fn render_reduced_in_bands(doc: &Document, w: u32, h: u32, damage: Option<Rect>, band_rows: i32) -> Buffer {- let b = doc.bounds();+/// [`render_reduced_rect`] (or, with `damage`, [`render_reduced_damage`]) of area `b` with an+/// explicit band height (see [`render_bands`]).+fn render_reduced_in_bands(doc: &Document, b: Rect, w: u32, h: u32, damage: Option<Rect>, band_rows: i32) -> Buffer {let (fw, fh) = (b.width() as usize, b.height() as usize);let (w, h) = (w.clamp(1, b.width().max(1)) as usize, h.clamp(1, b.height().max(1)) as usize);let full = Rect::from_xywh(0, 0, w as u32, h as u32);diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rsindex c48bae2f8..faff16595 100644--- a/crates/compose/src/tests.rs+++ b/crates/compose/src/tests.rs@@ -1405,7 +1405,7 @@ fn reference_reduce(doc: &Document, w: usize, h: usize) -> Vec<[f32; 4]> {fn reduced_render_matches_the_full_composite_averaged() {let d = tall_doc(53, 1000);for (w, h, band) in [(10, 190, 0), (7, 33, 256), (53, 999, 512), (1, 1, 256)] {- let got = render_reduced_in_bands(&d, w, h, None, band);+ let got = render_reduced_in_bands(&d, d.bounds(), w, h, None, band);assert_eq!((got.rect.width(), got.rect.height()), (w, h));assert_eq!(got.px, reference_reduce(&d, w as usize, h as usize), "{w}x{h} band {band}");}@@ -1421,9 +1421,9 @@ fn reduced_damage_matches_the_whole_reduction() {// whole reduction's, for uneven factors, damage on span edges and bands smaller than the area.let d = tall_doc(53, 1000);for (w, h, band) in [(10, 190, 0), (7, 33, 256), (53, 999, 64), (53, 1000, 0), (1, 1, 256)] {- let all = render_reduced_in_bands(&d, w, h, None, band);+ let all = render_reduced_in_bands(&d, d.bounds(), w, h, None, band);for dmg in [Rect::new(0, 0, 1, 1), Rect::new(5, 17, 6, 18), Rect::new(12, 300, 40, 701), Rect::new(-9, 990, 80, 2000), Rect::new(0, 0, 53, 1000)] {- let part = render_reduced_in_bands(&d, w, h, Some(dmg), band);+ let part = render_reduced_in_bands(&d, d.bounds(), w, h, Some(dmg), band);let r = part.rect;assert!(!r.is_empty() && r.x0 >= 0 && r.y0 >= 0 && r.x1 as u32 <= w && r.y1 as u32 <= h, "{w}x{h} {dmg:?} -> {r:?}");for y in r.y0..r.y1 {@@ -1442,10 +1442,40 @@ fn reduced_damage_matches_the_whole_reduction() {}}}- assert!(render_reduced_in_bands(&d, w, h, Some(Rect::new(60, 0, 70, 10)), band).rect.is_empty());+ assert!(render_reduced_in_bands(&d, d.bounds(), w, h, Some(Rect::new(60, 0, 70, 10)), band).rect.is_empty());}}+#[test]+fn reduced_render_of_an_area_past_the_canvas() {+ // The Crop tool shows layer pixels beyond the canvas: rendered in place, they must equal the+ // same pixels on a canvas that holds them (adjustment layers apply out there too).+ let paint = |d: &mut Document, dx: i32, dy: i32| {+ let mut l = Layer::raster("big", PixelFormat::RGBA8);+ let s = l.surface_mut().unwrap();+ for y in -10..40 {+ for x in -20..60 {+ let a = if x < 0 || y >= 30 { 0.6 } else { 1.0 };+ s.fill_rect(Rect::new(x + dx, y + dy, x + dx + 1, y + dy + 1), &[(x + 20) as f32 / 80.0, (y + 10) as f32 / 50.0, 0.5, a]);+ }+ }+ d.layers.push(l);+ d.layers.push(Layer::new("inv", LayerContent::Adjustment(Adjustment::Invert)));+ };+ let mut d = Document::new("d", Size::new(40, 30), ColorMode::Rgb, SampleType::U8);+ paint(&mut d, 0, 0);+ let mut whole = Document::new("w", Size::new(80, 50), ColorMode::Rgb, SampleType::U8);+ paint(&mut whole, 20, 10);+ let area = Rect::new(-20, -10, 60, 40);+ for (w, h) in [(80, 50), (8, 5), (27, 13), (1, 1)] {+ let got = render_reduced_rect(&d, area, w, h);+ assert_eq!(got.rect, Rect::new(0, 0, w as i32, h as i32));+ assert_eq!(got.px, render_reduced(&whole, w, h).px, "{w}x{h}");+ }+ // Past every layer there is nothing to show.+ assert!(render_reduced_rect(&d, Rect::new(100, 100, 120, 110), 20, 10).px.iter().all(|p| p[3] == 0.0));+}+#[test]fn large_documents_thumbnail_from_a_proxy() {// 4200 × 4200 (17.6 MP) is above PROXY_THUMBNAIL_PIXELS: the proxy path must still give adiff --git a/crates/engine/src/extra_cmds.rs b/crates/engine/src/extra_cmds.rsindex 9b70a04e0..9972bf462 100644--- a/crates/engine/src/extra_cmds.rs+++ b/crates/engine/src/extra_cmds.rs@@ -338,6 +338,12 @@ fn paste_into(s: &mut Session, p: &Value, outside: bool) -> Result<Value> {Ok(r)}+/// The canvas grown to every layer's pixels: Image › Reveal All's new canvas, and what the Crop+/// tool shows while a frame is edited.+pub fn reveal_all_bounds(doc: &Document) -> Rect {+ doc.walk().into_iter().filter_map(|(_, _, l)| l.surface().map(|s| s.content_bounds())).fold(doc.bounds(), |a, b| a.union(&b))+}+// ---------- layers ----------fn layer_from_background(s: &mut Session) -> Result<Value> {@@ -652,9 +658,8 @@ pub fn specs() -> Vec<CommandSpec> {spec!("image.adjustments.equalize", "Equalize", &["Image", "Adjustments"], None, "{}", has_pixels, |s, _| equalize(s)),spec!("image.revealAll", "Reveal All", &["Image"], None, "{}", has_doc, |s, _| {let d = s.active().ok_or(EngineError::NoDocument)?;- let canvas = d.doc.bounds();- let all = d.doc.walk().into_iter().filter_map(|(_, _, l)| l.surface().map(|s| s.content_bounds())).fold(canvas, |a, b| a.union(&b));- if all == canvas {+ let all = reveal_all_bounds(&d.doc);+ if all == d.doc.bounds() {return Ok(json!({"changed": false}));}s.execute("image.crop", json!({"x": all.x0, "y": all.y0, "width": all.width(), "height": all.height(), "deleteCroppedPixels": false}))?;@@ -1037,6 +1042,7 @@ mod tests {let mut s = session(8);s.execute("layer.translate", json!({"dx": 0, "dy": 0})).ok();paint_square(&mut s, Rect::new(-5, 0, 10, 10), [1.0, 0.0, 0.0, 1.0]);+ assert_eq!(reveal_all_bounds(doc(&s)), Rect::new(-5, 0, 40, 30));s.execute("image.revealAll", json!({})).unwrap();assert_eq!((doc(&s).size.width, doc(&s).size.height), (45, 30));assert_eq!(s.execute("image.revealAll", json!({})).unwrap()["changed"], false);diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rsindex 537358ed6..10567dcae 100644--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@ -1896,6 +1896,10 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:let drop_shadow = border == photocraft_engine::prefs::CanvasBorder::DropShadow;// Drop shadow, checkerboard, document image.let img_rect = xf.doc_rect(doc.bounds());+ // Crop tool: the layers' pixels past the canvas while a frame is edited, under the canvas+ // (whose edge blends into them) and without its shadow.+ let beyond = draw_beyond_canvas(app, &painter, &xf, idx, output);+ let drop_shadow = drop_shadow && !beyond;// Live adjustment previews on big documents use a downsampled proxy (see proxy.rs), unless// Preferences › Performance › Low Resolution Previews is off.let mut on_gpu = false;@@ -2173,6 +2177,11 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:// (Preferences › Tools, `paint_mouse`).crate::paint_mouse::sync_tool_smoothing(app);let mut buttons = crate::paint_mouse::canvas_buttons(app, &response, tool);+ // The Crop tool's frame is edited from the press (before egui's drag threshold), so the+ // pixels past the canvas show at once, as in Photoshop.+ if tool == Tool::Crop && response.is_pointer_button_down_on() && ui.input(|i| i.pointer.primary_down()) && crate::crop_ui::press(app) {+ ctx.request_repaint();+ }// Capture temporary Type transforms at the actual press, before egui's drag threshold.// Releasing Command before the first recognised move must not turn it into text selection.let type_press = egui::Id::new("type-pointer-press-modifiers");@@ -2395,7 +2404,8 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:crate::layer_pick_ui::show(app, &ctx);crate::canvas_tool_menu::show(app, &ctx);crate::snap_ui::draw(app, &painter, &xf);- if border == photocraft_engine::prefs::CanvasBorder::Line {+ // The canvas edge isn't outlined while the pixels past it show (Photoshop's crop preview).+ if border == photocraft_engine::prefs::CanvasBorder::Line && !beyond {painter.rect_stroke(img_rect, 0.0, Stroke::new(1.0, Color32::from_gray(20)), egui::StrokeKind::Outside);}crate::type_tool::draw_overlay(app, &painter, &xf);@@ -2682,6 +2692,139 @@ fn crop_overlay(painter: &egui::Painter, r: Rect) {}}+/// What the Crop tool shows past the canvas, cached per document state ([`draw_beyond_canvas`]).+#[derive(Clone)]+struct BeyondCanvas {+ snapshot: std::sync::Weak<Document>,+ key: u64,+ /// Every layer's pixels and the canvas (`extra_cmds::reveal_all_bounds`).+ extent: DRect,+ /// The composite around the canvas: each band, the area its texture covers, the texture.+ bands: Vec<(DRect, DRect, egui::TextureHandle)>,+}++/// Band `r` around the canvas `c` (on screen) pushed a point under the canvas's edge, so that the+/// edge's anti-aliased pixels blend with the band rather than with the pasteboard.+fn under_canvas(mut r: Rect, c: Rect) -> Rect {+ let near = |a: f32, b: f32| (a - b).abs() < 0.01;+ if near(r.max.y, c.min.y) {+ r.max.y += 1.0;+ }+ if near(r.min.y, c.max.y) {+ r.min.y -= 1.0;+ }+ if near(r.max.x, c.min.x) {+ r.max.x += 1.0;+ }+ if near(r.min.x, c.max.x) {+ r.min.x -= 1.0;+ }+ r+}++/// `outer` minus `inner`: the bands above, below, left and right of it (empty ones dropped).+fn ring(outer: DRect, inner: DRect) -> Vec<DRect> {+ let i = inner.intersect(&outer);+ if i.is_empty() {+ return if outer.is_empty() { Vec::new() } else { vec![outer] };+ }+ [+ DRect::new(outer.x0, outer.y0, outer.x1, i.y0),+ DRect::new(outer.x0, i.y1, outer.x1, outer.y1),+ DRect::new(outer.x0, i.y0, i.x0, i.y1),+ DRect::new(i.x1, i.y0, outer.x1, i.y1),+ ]+ .into_iter()+ .filter(|r| !r.is_empty())+ .collect()+}++/// Crop tool, while a frame is edited (`crop_ui::shows_beyond_canvas`): like Photoshop's crop+/// preview, the canvas grows to every layer's pixels (a crop with Delete Cropped Pixels off keeps+/// them; a moved layer reaches past the edges) and to the frame, transparency drawn as the+/// checkerboard, all under the shield `crop_overlay` adds. Only the ring around the canvas is+/// composited, on the CPU, once per document state: at most `MAX_TEXTURE` texels per side, from a+/// downsampled proxy past that (so a far-off layer costs no more than a 16 MP composite).+/// Drawn before the canvas, each band reaching a point under its edge. Returns whether anything+/// past the canvas was drawn.+fn draw_beyond_canvas(app: &mut PhotocraftApp, painter: &egui::Painter, xf: &ViewXform, idx: usize, output: Option<u32>) -> bool {+ let ctx = painter.ctx().clone();+ let Some((snapshot, id)) = app.session.documents().get(idx).map(|st| (std::sync::Arc::downgrade(&st.doc), st.doc.id)) else { return false };+ let key = egui::Id::new(("crop-beyond-canvas", id.0, output));+ let frame =+ app.ui.crop_rect.filter(|f| f.iter().all(|v| v.is_finite()) && app.session.active_index() == Some(idx) && crate::crop_ui::shows_beyond_canvas(app));+ let Some(f) = frame else {+ ctx.data_mut(|d| d.remove::<BeyondCanvas>(key));+ return false;+ };+ let (doc, preview_key) = display_doc(app, idx);+ if doc.has_artboards() {+ return false;+ }+ let (display, display_key) = canvas_display(app, &doc, output);+ let doc_key = preview_key ^ display_key;+ let cached: Option<BeyondCanvas> = ctx.data(|d| d.get_temp(key));+ let c = match cached.filter(|c| c.snapshot.ptr_eq(&snapshot) && c.key == doc_key) {+ Some(c) => c,+ None => {+ let t0 = crate::gpu_canvas::now_ms();+ let extent = photocraft_engine::extra_cmds::reveal_all_bounds(&doc);+ // One texel per `k` document pixels keeps every texture within MAX_TEXTURE.+ let k = extent.width().max(extent.height()).div_ceil(MAX_TEXTURE).max(1);+ let proxy = (k > 1).then(|| photocraft_compose::proxy::proxy_document(&doc, k));+ let src = proxy.as_ref().unwrap_or(&*doc);+ let k = k as i32;+ let opts = TextureOptions { magnification: egui::TextureFilter::Nearest, ..TextureOptions::LINEAR };+ let bands = ring(extent, doc.bounds())+ .into_iter()+ .map(|b| {+ // The proxy pixels over `b`: document pixels / k, rounded outwards.+ let up = |v: i32| v.div_euclid(k) + i32::from(v.rem_euclid(k) != 0);+ let p = DRect::new(b.x0.div_euclid(k), b.y0.div_euclid(k), up(b.x1), up(b.y1));+ let buf = photocraft_compose::render_reduced_rect(src, p, p.width(), p.height());+ let tex = ctx.load_texture("crop-beyond-canvas", display_image(display.as_deref(), &buf), opts);+ (b, DRect::new(p.x0.saturating_mul(k), p.y0.saturating_mul(k), p.x1.saturating_mul(k), p.y1.saturating_mul(k)), tex)+ })+ .collect();+ app.perf.span("crop-beyond-canvas", crate::gpu_canvas::now_ms() - t0);+ let c = BeyondCanvas { snapshot, key: doc_key, extent, bands };+ ctx.data_mut(|d| d.insert_temp(key, c.clone()));+ c+ }+ };+ // Transparency out to the frame, in phase with the canvas's own checkerboard.+ let canvas = xf.doc_rect(doc.bounds());+ let fr = DRect::new(f[0].floor() as i32, f[1].floor() as i32, f[2].ceil() as i32, f[3].ceil() as i32);+ let square = app.session.prefs().transparency_and_gamut.square();+ let checker_id = square.map(|_| checker(app, &ctx));+ let around = ring(c.extent.union(&fr), doc.bounds());+ for &b in &around {+ let r = under_canvas(xf.doc_rect(b), canvas);+ match square.zip(checker_id) {+ Some((sq, id)) => {+ let uv = Rect::from_min_max(((r.min - canvas.min) / (2.0 * sq)).to_pos2(), ((r.max - canvas.min) / (2.0 * sq)).to_pos2());+ painter.image(id, r, uv, Color32::WHITE);+ }+ None => {+ painter.rect_filled(r, 0.0, Color32::WHITE);+ }+ }+ }+ for (b, t, tex) in &c.bands {+ let part = |a: i32, o: i32, len: u32| (i64::from(a) - i64::from(o)) as f32 / len.max(1) as f32;+ let (mut u0, mut u1) = (part(b.x0, t.x0, t.width()), part(b.x1, t.x0, t.width()));+ if xf.flip {+ (u0, u1) = (u1, u0);+ }+ let uv = Rect::from_min_max(pos2(u0, part(b.y0, t.y0, t.height())), pos2(u1, part(b.y1, t.y0, t.height())));+ // The texture's edge texels stretch over the point under the canvas.+ let (r, e) = (xf.doc_rect(*b), under_canvas(xf.doc_rect(*b), canvas));+ let at = |p: Pos2| uv.min + (p - r.min) / r.size() * uv.size();+ painter.image(tex.id(), e, Rect::from_min_max(at(e.min), at(e.max)), Color32::WHITE);+ }+ !around.is_empty()+}+/// Overlays that persist between gestures: polygonal or magnetic lasso in progress, pending crop box.fn draw_tool_state(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform, hover: Option<Pos2>) {crate::magnetic_lasso_ui::draw(app, painter, xf, hover);diff --git a/crates/ui-egui/src/crop_ui.rs b/crates/ui-egui/src/crop_ui.rsindex a7b0ff220..d6971fe6f 100644--- a/crates/ui-egui/src/crop_ui.rs+++ b/crates/ui-egui/src/crop_ui.rs@@ -9,6 +9,10 @@//! ↵ commits (`image.crop`, see `canvas::commit_crop`) and Esc cancels. The pending frame lives in//! `UiState::crop_rect`, so the control channel reads it. `image.crop` has no angle, so dragging//! outside the frame draws a new one rather than rotating it.+//!+//! As in Photoshop, from the first press until the crop is committed or cancelled the canvas also+//! shows the layers' pixels past its edges (kept by a crop with Delete Cropped Pixels off, or moved+//! out), with transparency out to the frame, under the shield ([`shows_beyond_canvas`]).use egui::{CursorIcon, Modifiers};@@ -32,6 +36,8 @@ pub struct CropState {pub default_frame: bool,/// The document (index and size) the default frame was made for.frame_for: Option<(usize, u32, u32)>,+ /// The frame is being edited (pressed since it was made): the canvas shows what lies past it.+ pub editing: bool,}/// A crop gesture in progress. Rects are `[x0, y0, x1, y1]` in document coordinates.@@ -158,6 +164,7 @@ pub fn set_space(app: &mut PhotocraftApp, down: bool) {/// cancelled or committed, it frames the selection's bounds, or the whole canvas.pub fn ensure_frame(app: &mut PhotocraftApp) {if app.ui.tool != Tool::Crop {+ app.crop.editing = false;// Leaving the tool drops an untouched default frame (a drawn one stays pending).if app.crop.default_frame {app.ui.crop_rect = None;@@ -183,6 +190,7 @@ pub fn ensure_frame(app: &mut PhotocraftApp) {app.ui.crop_rect = Some([f64::from(r.x0), f64::from(r.y0), f64::from(r.x1), f64::from(r.y1)]);app.crop.default_frame = true;app.crop.frame_for = key;+ app.crop.editing = false;}/// A crop gesture is in progress: Space repositions the frame rather than panning.@@ -190,6 +198,22 @@ pub fn active(app: &PhotocraftApp) -> bool {app.ui.tool == Tool::Crop && app.crop.drag.is_some()}+/// The frame is being edited, so the canvas shows the pixels past its edges (Photoshop's crop+/// preview): from the first press with the tool until the crop is committed or cancelled.+pub fn shows_beyond_canvas(app: &PhotocraftApp) -> bool {+ app.ui.tool == Tool::Crop && app.ui.crop_rect.is_some() && (app.crop.editing || app.crop.drag.is_some())+}++/// The button went down on the canvas with the Crop tool: the frame is being edited from now on.+/// Returns true when that is new.+pub fn press(app: &mut PhotocraftApp) -> bool {+ let new = app.ui.tool == Tool::Crop && app.ui.crop_rect.is_some() && !app.crop.editing;+ if new {+ app.crop.editing = true;+ }+ new+}+fn tolerance(app: &PhotocraftApp) -> f64 {HANDLE_PX / (app.current_zoom() as f64).max(0.01)}@@ -208,6 +232,7 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: Modifiers) -> bool}match ev {ToolEvent::Down { .. } => {+ app.crop.editing = true;let frame = app.ui.crop_rect.filter(|r| r.iter().all(|v| v.is_finite()));app.crop.drag = Some(match frame.map(|r| (r, hit(r, p, tolerance(app)))) {Some((rect, Hit::Handle(hx, hy))) => CropDrag::Resize { hx, hy, start: p, rect },@@ -350,6 +375,36 @@ mod tests {assert_eq!(app.ui.crop_rect, None);}+ #[test]+ fn the_frame_is_edited_from_a_press_until_commit_cancel_or_another_tool() {+ let mut app = app(SampleType::U8);+ ensure_frame(&mut app);+ assert!(!shows_beyond_canvas(&app), "a new frame is not being edited");+ assert!(press(&mut app));+ assert!(shows_beyond_canvas(&app));+ assert!(!press(&mut app), "only the first press is news");+ // A click on the frame keeps it edited.+ drag(&mut app, &[[50.0, 50.0]], NONE);+ assert!(shows_beyond_canvas(&app));+ // Esc drops the frame: the new default one isn't edited.+ app.ui.crop_rect = None;+ ensure_frame(&mut app);+ assert!(!shows_beyond_canvas(&app));+ // A drawn frame is edited until it is committed.+ drag(&mut app, &[[10.0, 10.0], [60.0, 40.0]], NONE);+ assert!(shows_beyond_canvas(&app));+ crate::canvas::commit_crop(&mut app);+ ensure_frame(&mut app);+ assert_eq!(app.ui.crop_rect, Some([0.0, 0.0, 50.0, 30.0]));+ assert!(!shows_beyond_canvas(&app));+ // Or until another tool is picked.+ drag(&mut app, &[[5.0, 5.0], [20.0, 20.0]], NONE);+ app.ui.tool = Tool::Brush;+ ensure_frame(&mut app);+ assert!(!app.crop.editing && !shows_beyond_canvas(&app));+ assert!(!press(&mut app), "no frame without the Crop tool");+ }+#[test]fn hit_test_finds_handles_inside_and_outside() {let r = [10.0, 10.0, 110.0, 60.0];diff --git a/crates/ui-egui/tests/crop_beyond_canvas.rs b/crates/ui-egui/tests/crop_beyond_canvas.rsnew file mode 100644index 000000000..bb579daa5--- /dev/null+++ b/crates/ui-egui/tests/crop_beyond_canvas.rs@@ -0,0 +1,178 @@+//! Crop tool: while a frame is edited, the canvas shows the layers' pixels past its edges, as+//! Photoshop's crop preview does.+//!+//! A crop with Delete Cropped Pixels off keeps what it cut away, but PhotoCraft drew only the+//! canvas, so a frame couldn't be pulled back out over those pixels by eye. Photoshop (measured on+//! 25.4) grows the view to every layer's bounds and the frame once the frame is pressed: the+//! hidden pixels under the shield, transparency as the checkerboard, until ↵ or Esc.+//!+//! The real app runs offscreen on wgpu with real egui pointer events; the test reads the rendered+//! pixels. Skips when no GPU adapter exists (like `drag_preview_canvas.rs`).++use egui::{Key, Modifiers, PointerButton, Pos2};+use photocraft_ui_egui::PhotocraftApp;+use photocraft_ui_egui::canvas::ViewXform;+use photocraft_ui_egui::control::{ControlRequest, handle};+use serde_json::{Value, json};++type Harness = egui_kittest::Harness<'static, PhotocraftApp>;++/// A rendered frame: RGBA8, physical pixels.+struct Image {+ w: u32,+ h: u32,+ px: Vec<u8>,+}++impl Image {+ fn rgb(&self, p: Pos2) -> [u8; 3] {+ let (x, y) = (p.x.round() as i64, p.y.round() as i64);+ assert!(x >= 0 && y >= 0 && x < i64::from(self.w) && y < i64::from(self.h), "{p:?} is off the frame");+ let i = (y as usize * self.w as usize + x as usize) * 4;+ [self.px[i], self.px[i + 1], self.px[i + 2]]+ }+}++fn harness() -> Option<Harness> {+ let built = std::panic::catch_unwind(|| {+ egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 640.0)).with_max_steps(64).wgpu().build_eframe(|cc| {+ PhotocraftApp::setup_context(&cc.egui_ctx, Default::default());+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());+ if let Some(rs) = cc.wgpu_render_state.as_ref() {+ app.set_wgpu(rs.clone());+ }+ app+ })+ });+ match built {+ Ok(h) => Some(h),+ Err(_) => {+ eprintln!("skipping: no GPU adapter");+ None+ }+ }+}++fn control(h: &mut Harness, method: &str, params: Value) {+ let ctx = h.ctx.clone();+ let (req, _rx) = ControlRequest::new(method, params);+ handle(h.state_mut(), &ctx, &req);+ h.run_steps(3);+}++fn screen(h: &Harness, x: f32, y: f32) -> Pos2 {+ let app = h.state();+ let v = &app.ui.views[0];+ let xf = ViewXform {+ rect: photocraft_ui_egui::rulers::content_rect(app, app.last_canvas_rect),+ zoom: v.zoom,+ center: v.center,+ flip: app.ui.view.flip_horizontal,+ };+ xf.to_screen(x, y)+}++fn button(h: &mut Harness, x: f32, y: f32, pressed: bool) {+ let p = screen(h, x, y);+ h.event(egui::Event::PointerMoved(p));+ h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE });+ h.step();+}++fn drag(h: &mut Harness, from: [f32; 2], to: [f32; 2]) {+ button(h, from[0], from[1], true);+ for i in 1..=6 {+ let t = i as f32 / 6.0;+ h.event(egui::Event::PointerMoved(screen(h, from[0] + (to[0] - from[0]) * t, from[1] + (to[1] - from[1]) * t)));+ h.step();+ }+ button(h, to[0], to[1], false);+}++fn render(h: &mut Harness) -> Image {+ let img = h.render().expect("render");+ Image { w: img.width(), h: img.height(), px: img.into_raw() }+}++/// Mostly `c` (one channel well above the other two), dimmed or not.+fn tinted(p: [u8; 3], c: usize) -> bool {+ (0..3).filter(|&i| i != c).all(|i| p[c] > 60 && p[i] < p[c] / 2)+}++#[test]+fn editing_a_crop_frame_shows_the_pixels_past_the_canvas() {+ let Some(mut h) = harness() else { return };+ h.run_steps(4);+ {+ let app = h.state_mut();+ // 300 × 120: red down the left 60 px and blue down the right 60 px of a new layer, then+ // cropped to (50, 0) 200 × 100 keeping the pixels: 50 px of red past the left edge, 50 of+ // blue past the right, and 20 rows of the white Background below.+ app.run("file.new", json!({"width": 300, "height": 120, "background": "white"})).expect("new");+ app.run("layer.new.layer", json!({})).expect("layer");+ for (x, color) in [(0, "#ff0000"), (240, "#0000ff")] {+ app.run("select.rect", json!({"x": x, "y": 0, "width": 60, "height": 120})).expect("select");+ app.run("edit.fill", json!({"color": color})).expect("fill");+ }+ app.run("select.deselect", json!({})).expect("deselect");+ app.run("image.crop", json!({"x": 50, "y": 0, "width": 200, "height": 100, "deleteCroppedPixels": false})).expect("crop");+ app.sync_views();+ app.ui.extras.rulers = false;+ app.ui.extras.snap = false;+ }+ control(&mut h, "ui.set", json!({"tool": "crop", "zoom": 1.0, "center": [100, 50]}));+ h.run_steps(3);+ assert_eq!(h.state().ui.crop_rect, Some([0.0, 0.0, 200.0, 100.0]), "the default frame");+ let (red, blue, white, beyond) = ([-25.0, 50.0], [225.0, 50.0], [100.0, 110.0], [-80.0, 50.0]);+ let at = |h: &Harness, img: &Image, p: [f32; 2]| img.rgb(screen(h, p[0], p[1]));++ // Picking the tool shows only the canvas (and the pasteboard around it, dimmed by the shield).+ let before = render(&mut h);+ let shown = |h: &Harness, img: &Image| [red, blue, white, beyond].map(|p| at(h, img, p));+ let was = shown(&h, &before);+ assert!(!tinted(was[0], 0) && !tinted(was[1], 2), "nothing past the canvas yet: {was:?}");++ // A press on the frame starts editing, before any move: the pixels past the canvas show,+ // under the shield (the press asks for the frame that draws them).+ button(&mut h, 100.0, 50.0, true);+ h.step();+ let img = render(&mut h);+ let [r, b, w, past] = shown(&h, &img);+ assert!(tinted(r, 0), "hidden red: {r:?}");+ assert!(tinted(b, 2), "hidden blue: {b:?}");+ assert!(w.iter().all(|&c| c > 90 && c < 200) && w[0] == w[1] && w[1] == w[2] && w != was[2], "hidden white, dimmed: {w:?}");+ assert_eq!(past, was[3], "past every layer and the frame: the pasteboard");+ // Inside the frame nothing changed.+ assert_eq!(at(&h, &img, [150.0, 30.0]), at(&h, &before, [150.0, 30.0]));+ // Releasing (a click on the untouched frame) keeps the crop being edited.+ button(&mut h, 100.0, 50.0, false);+ let img = render(&mut h);+ assert!(tinted(at(&h, &img, red), 0), "still shown after the click");++ // The left edge pulled out past the red: the red inside the frame is undimmed, and where+ // there are no pixels the frame shows transparency.+ drag(&mut h, [0.0, 50.0], [-80.0, 50.0]);+ assert_eq!(h.state().ui.crop_rect, Some([-80.0, 0.0, 200.0, 100.0]));+ let img = render(&mut h);+ let r = at(&h, &img, red);+ assert!(r[0] > 230 && r[1] < 40 && r[2] < 40, "red inside the frame at full strength: {r:?}");+ // (egui_kittest samples textures through its own clamped bilinear filter, so the checkerboard+ // shows as a light, neutral grey here rather than as squares.)+ for p in [[-70.0, 50.0], [-62.0, 80.0]] {+ let c = at(&h, &img, p);+ assert!(c.iter().all(|&v| v >= 190) && c[0] == c[1] && c[1] == c[2], "transparency past the layers at {p:?}: {c:?}");+ }+ // The red runs on across the canvas edge: no canvas border line between.+ for x in [-2.0, -1.0, 0.0, 1.0] {+ let c = at(&h, &img, [x, 50.0]);+ assert!(c[0] > 230 && c[1] < 40, "at x = {x}: {c:?}");+ }++ // Esc cancels: back to the canvas alone.+ h.event(egui::Event::PointerGone);+ h.event(egui::Event::Key { key: Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE });+ h.run_steps(3);+ let img = render(&mut h);+ assert_eq!(h.state().ui.crop_rect, Some([0.0, 0.0, 200.0, 100.0]));+ assert_eq!(shown(&h, &img), was, "hidden again after Esc");+}