PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Move tool: outline follows the moved layer (#2413) (#2565)
Valentin Klein87068253c6be
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rsindex 3889385ae..856d9e22b 100644--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@ -591,6 +591,9 @@ pub enum ToolEvent {Up { x: f64, y: f64 },}+/// View › Show › Layer Edges: the colour of the active layer's outline.+pub(crate) const LAYER_EDGES: Color32 = Color32::from_rgb(0x2d, 0x8c, 0xeb);+/// Document ↔ screen mapping for a canvas rect and a view.#[derive(Clone, Copy, Debug)]pub struct ViewXform {@@ -2371,14 +2374,9 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:crate::pixel_grid::paint(app, &painter, &xf, idx, output, visible_doc_rect(&xf));}- // View › Show › Layer Edges: the active layer's content bounds.- if app.ui.view.shows(app.ui.view.show.layer_edges)- && let Some(st) = app.session.documents().get(idx)- && let Some(b) = st.active_layer.and_then(|id| st.doc.layer(id)).and_then(|l| l.surface()).map(photocraft_compose::bounds::content_bounds)- && !b.is_empty()- {- painter.rect_stroke(xf.doc_rect(b), 0, Stroke::new(1.0, Color32::from_rgb(0x2d, 0x8c, 0xeb)), egui::StrokeKind::Outside);- }+ // View › Show › Layer Edges: drawn at this depth, but only once this frame's tool events are+ // in (`layer_edges_rect`), so a press that Auto-Selects a layer outlines that layer.+ let layer_edges = painter.add(egui::Shape::Noop);// Selection outline: true boundary, animated marching ants (cached per revision).if let Some(sel) = doc.selection.as_ref().filter(|_| app.ui.view.shows(app.ui.view.show.selection_edges) && !polygon_replaces_selection(app)) {@@ -3019,6 +3017,9 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:}}app.tool_override = None;+ if let Some(b) = layer_edges_rect(app, idx) {+ painter.set(layer_edges, egui::Shape::rect_stroke(xf.doc_rect(b), 0, Stroke::new(1.0, LAYER_EDGES), egui::StrokeKind::Outside));+ }// Scrollbars (scrollbars.rs): drawn over the canvas edges, they take the pointer there.let t0 = crate::gpu_canvas::now_ms();let before = view.center;@@ -3393,6 +3394,23 @@ fn draw_tool_state(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform,}}+/// View › Show › Layer Edges: the active layer's content bounds (cached per tile) where the canvas+/// shows them. During a Move drag that is at the offset the image was drawn with this frame, so+/// the outline moves in lockstep with the layer's pixels (#2413).+pub(crate) fn layer_edges_rect(app: &PhotocraftApp, idx: usize) -> Option<photocraft_geom::Rect> {+ if !app.ui.view.shows(app.ui.view.show.layer_edges) {+ return None;+ }+ let st = app.session.documents().get(idx)?;+ let id = st.active_layer?;+ let b = st.doc.layer(id)?.surface().map(photocraft_compose::bounds::content_bounds)?;+ if b.is_empty() {+ return None;+ }+ let (dx, dy) = crate::move_ui::shown_offset(app, st.doc.id, st.revision, id).unwrap_or((0, 0));+ Some(b.translate(dx, dy))+}+/// Move tool › Show Transform Controls: the active layer's transform bounds.fn transform_controls_rect(app: &PhotocraftApp, xf: &ViewXform) -> Option<Rect> {if app.ui.tool != Tool::Move || !app.ui.tool_options.move_show_transform || app.ui.transform.is_some() || app.drag.is_some() {diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex c3257b14a..d0046a313 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -1887,6 +1887,9 @@ mod save_identity_tests;#[cfg(test)]mod move_auto_select_tests;+#[cfg(test)]+mod move_outline_tests;+#[cfg(test)]mod mask_thumb_refresh_tests;diff --git a/crates/ui-egui/src/move_outline_tests.rs b/crates/ui-egui/src/move_outline_tests.rsnew file mode 100644index 000000000..1e4c112f9--- /dev/null+++ b/crates/ui-egui/src/move_outline_tests.rs@@ -0,0 +1,151 @@+//! #2413: View › Show › Layer Edges while the Move tool drags. As in Photoshop, the outline belongs+//! to the layer being moved (the one Auto-Select picks on the press, not the one selected before)+//! and moves in lockstep with its pixels, however fast the pointer goes.++use egui::{Event, PointerButton, Pos2};+use egui_kittest::Harness;+use photocraft_doc::LayerId;+use photocraft_geom::Rect;+use serde_json::json;++use crate::PhotocraftApp;+use crate::canvas::{LAYER_EDGES, ViewXform};+use crate::state::{Tool, View};++/// A 64×64 document with two painted layers: A covers (8..24)², B covers (40..56)². B is active,+/// the Move tool (Auto-Select on) is current and View › Show › Layer Edges is on.+fn app() -> (PhotocraftApp, LayerId, LayerId) {+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());+ app.session.execute("file.new", json!({"width": 64, "height": 64})).unwrap();+ app.sync_views();+ let mut ids = Vec::new();+ for at in [8, 40] {+ app.session.execute("layer.new.layer", json!({})).unwrap();+ app.session+ .edit("paint", |doc, a| {+ doc.layer_mut(a.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(at, at, at + 16, at + 16), &[1.0, 0.0, 0.0, 1.0]);+ Ok(())+ })+ .unwrap();+ ids.push(app.session.active().unwrap().active_layer.unwrap());+ }+ app.ui.tool = Tool::Move;+ assert!(app.ui.tool_options.move_auto_select);+ // Snapping would shift the expected offsets.+ app.ui.extras.snap = false;+ app.ui.view.show.smart_guides = false;+ app.ui.extras.rulers = false;+ app.ui.view.extras = true;+ app.ui.view.show.layer_edges = true;+ // 4 screen px per document px, the document centred.+ app.ui.views = vec![View { zoom: 4.0, center: [32.0, 32.0], fit_pending: false, fill_pending: false, doc_size: [64, 64], rotation: 0.0 }];+ (app, ids[0], ids[1])+}++fn harness(app: PhotocraftApp) -> Harness<'static, PhotocraftApp> {+ let mut h = Harness::builder().with_size(egui::vec2(400.0, 340.0)).build_ui_state(+ |ui, app: &mut PhotocraftApp| {+ app.last_canvas_rect = ui.max_rect();+ let v = app.ui.views[0].clone();+ crate::canvas::canvas_view(app, ui, 0, ui.max_rect(), v, true);+ },+ app,+ );+ h.run_steps(2);+ h+}++fn xf(app: &PhotocraftApp) -> ViewXform {+ let v = &app.ui.views[0];+ ViewXform { rect: app.last_canvas_rect, zoom: v.zoom / app.ppp, center: v.center, flip: false, rotation: 0.0 }+}++/// The screen point of document point `p`.+fn at(h: &Harness<'_, PhotocraftApp>, p: [f32; 2]) -> Pos2 {+ xf(h.state()).to_screen(p[0], p[1])+}++/// The Layer Edges outlines the last frame drew.+fn edges(h: &Harness<'_, PhotocraftApp>) -> Vec<egui::Rect> {+ h.output()+ .shapes+ .iter()+ .filter_map(|c| match &c.shape {+ egui::Shape::Rect(r) if r.stroke.color == LAYER_EDGES && r.fill == egui::Color32::TRANSPARENT => Some(r.rect),+ _ => None,+ })+ .collect()+}++/// The outline Layer Edges draws around document rect `r`.+fn outline(h: &Harness<'_, PhotocraftApp>, r: Rect) -> Vec<egui::Rect> {+ vec![xf(h.state()).doc_rect(r)]+}++fn button(h: &mut Harness<'_, PhotocraftApp>, pos: Pos2, pressed: bool) {+ h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE });+}++fn active(h: &Harness<'_, PhotocraftApp>) -> Option<LayerId> {+ h.state().session.active().unwrap().active_layer+}++const A: Rect = Rect::new(8, 8, 24, 24);+const B: Rect = Rect::new(40, 40, 56, 56);++#[test]+fn the_outline_belongs_to_the_layer_auto_select_picked() {+ let (app, a, b) = app();+ let mut h = harness(app);+ assert_eq!(active(&h), Some(b));+ assert_eq!(edges(&h), outline(&h, B), "B is selected: its edges show");+ // Press on A and drag it 5 px to the right (20 screen px, past egui's click distance).+ let p0 = at(&h, [16.0, 16.0]);+ h.event(Event::PointerMoved(p0));+ button(&mut h, p0, true);+ h.step();+ h.event(Event::PointerMoved(p0 + egui::vec2(20.0, 0.0)));+ h.step();+ // The frame the drag starts in picks A: it outlines A, never B, which isn't moving.+ assert_eq!(active(&h), Some(a), "Auto-Select picked A");+ assert_eq!(edges(&h), outline(&h, A), "the frame that picks A outlines A, not the previously selected B");+ h.step();+ assert_eq!(edges(&h), outline(&h, A.translate(5, 0)), "A's outline follows it");+ button(&mut h, p0 + egui::vec2(20.0, 0.0), false);+ h.step();+ h.step();+ assert_eq!(edges(&h), outline(&h, A.translate(5, 0)), "after the release the outline stays on A where it landed");+ let st = h.state().session.active().unwrap();+ assert_eq!(st.doc.layer(a).unwrap().surface().unwrap().content_bounds(), A.translate(5, 0));+}++#[test]+fn the_outline_moves_in_lockstep_with_a_fast_drag() {+ let (app, _, b) = app();+ let mut h = harness(app);+ let p0 = at(&h, [48.0, 48.0]);+ h.event(Event::PointerMoved(p0));+ button(&mut h, p0, true);+ h.step();+ h.event(Event::PointerMoved(p0 + egui::vec2(-20.0, 0.0)));+ h.step();+ h.step();+ assert_eq!(active(&h), Some(b));+ assert_eq!(edges(&h), outline(&h, B.translate(-5, 0)));+ // Big jumps, one per frame. A frame draws the layer where the previous frame's events left it+ // (the image is painted before this frame's events are read), and the outline goes with it.+ let mut shown = (-5, 0);+ for (dx, dy) in [(-30, -10), (-36, -30), (-12, -36), (-40, 0)] {+ h.event(Event::PointerMoved(p0 + egui::vec2(dx as f32 * 4.0, dy as f32 * 4.0)));+ h.step();+ assert_eq!(edges(&h), outline(&h, B.translate(shown.0, shown.1)), "drawn with the layer at {shown:?} while the pointer moved to {dx},{dy}");+ // The next frame shows both at the pointer.+ h.step();+ assert_eq!(edges(&h), outline(&h, B.translate(dx, dy)), "the outline is where the layer is shown, at {dx},{dy}");+ shown = (dx, dy);+ }+ button(&mut h, p0 + egui::vec2(-160.0, 0.0), false);+ h.step();+ h.step();+ assert_eq!(edges(&h), outline(&h, B.translate(-40, 0)), "dropped where it was shown");+}diff --git a/crates/ui-egui/src/move_ui.rs b/crates/ui-egui/src/move_ui.rsindex 883ebc271..630d66068 100644--- a/crates/ui-egui/src/move_ui.rs+++ b/crates/ui-egui/src/move_ui.rs@@ -60,6 +60,8 @@ pub(crate) struct MovePreview {revision: u64,/// Layers that move ([`photocraft_engine::layer_multi_cmds::move_targets`]).ids: Vec<LayerId>,+ /// `ids` and every layer inside them: the layers shown at the drag's offset.+ moving: Vec<LayerId>,/// What moving them can change at offset (0, 0), not clipped to the canvas: a layer larger/// than the canvas brings its pixels from beyond the edge into view (`None` = anything).bounds: Option<Rect>,@@ -127,7 +129,8 @@ pub(crate) fn display_doc(app: &mut PhotocraftApp, idx: usize) -> Option<(Arc<Dolet all = Rect::new(i32::MIN / 2, i32::MIN / 2, i32::MAX / 2, i32::MAX / 2);let bounds = ids.iter().try_fold(Rect::EMPTY, |acc, id| Some(acc.union(&photocraft_compose::change_bounds(doc.layer(*id)?, all)?)));let canvas = doc.bounds();- app.move_preview = Some(MovePreview { doc: doc_id, revision, ids, bounds, canvas, offsets: Vec::new(), shown: None, floating: false });+ let moving = with_descendants(&doc, &ids);+ app.move_preview = Some(MovePreview { doc: doc_id, revision, ids, moving, bounds, canvas, offsets: Vec::new(), shown: None, floating: false });}let p = app.move_preview.as_mut()?;if offset == (0, 0) && p.offsets.is_empty() {@@ -153,6 +156,25 @@ pub(crate) fn display_doc(app: &mut PhotocraftApp, idx: usize) -> Option<(Arc<DoSome((p.shown.clone()?, p.key()))}+/// `ids` and every layer inside them (groups move their contents).+fn with_descendants(doc: &Document, ids: &[LayerId]) -> Vec<LayerId> {+ let walk = doc.walk();+ let roots: Vec<_> = walk.iter().filter(|(_, _, l)| ids.contains(&l.id)).map(|(p, _, _)| p.as_slice()).collect();+ walk.iter().filter(|(p, _, _)| roots.iter().any(|r| p.starts_with(r))).map(|(_, _, l)| l.id).collect()+}++/// Where the canvas shows layer `id` of document `doc` at `revision` relative to where it is: the+/// offset of the latest Move drag frame drawn ([`display_doc`]) when the layer moves with the drag,+/// so its Layer Edges outline moves in lockstep with its pixels (#2413). `None` when it shows+/// where it is.+pub(crate) fn shown_offset(app: &PhotocraftApp, doc: DocId, revision: u64, id: LayerId) -> Option<(i32, i32)> {+ let p = app.move_preview.as_ref().filter(|p| p.doc == doc && p.revision == revision && !p.floating && p.shown.is_some())?;+ if !p.moving.contains(&id) {+ return None;+ }+ p.offsets.last().copied()+}+/// A floating selection's offset plus a drag of it in progress (`canvas::selection_drag_delta`).pub(crate) fn floating_offset(app: &PhotocraftApp) -> Option<(i32, i32)> {let f = photocraft_engine::float_cmds::floating(app.session.active()?)?;@@ -172,7 +194,17 @@ fn floating_doc(app: &mut PhotocraftApp, idx: usize) -> Option<(Arc<Document>, uif !fresh {let bounds = st.doc.selection.as_ref().map(|s| s.content_bounds());let canvas = st.doc.bounds();- app.move_preview = Some(MovePreview { doc: doc_id, revision, ids: vec![f.layer], bounds, canvas, offsets: Vec::new(), shown: None, floating: true });+ app.move_preview = Some(MovePreview {+ doc: doc_id,+ revision,+ ids: vec![f.layer],+ moving: Vec::new(),+ bounds,+ canvas,+ offsets: Vec::new(),+ shown: None,+ floating: true,+ });}let st = app.session.documents().get(idx)?;let shown = app.move_preview.as_ref()?.offsets.last() != Some(&offset);