PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Polygonal Lasso: double-click closes the polygon; a new polygon replaces the selection in one step (#361)
reese68831a43362d
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rsindex e9376aa58..62712de6f 100644--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@ -1444,7 +1444,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:}// 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)) {+ if let Some(sel) = doc.selection.as_ref().filter(|_| app.ui.view.shows(app.ui.view.show.selection_edges) && !polygon_replaces_selection(app)) {// Trace at display resolution over the visible part only; key by the mask's tile identity// (not the document revision) so unrelated edits don't re-trace it.let step = (1.0 / view.zoom.max(1e-3)).log2().floor().exp2().clamp(1.0, 64.0) as u32;@@ -1655,6 +1655,10 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:}// A click with the (temporary) Hand does nothing, never the tool underneath.Tool::Hand => {}+ // Double-clicking closes the polygonal lasso: the first click placed the last+ // vertex (or already closed it), so the second never starts a new polygon. egui+ // reports it as a triple click when a vertex went down shortly before.+ Tool::PolygonLasso if response.double_clicked() || response.triple_clicked() => commit_polygon(app),_ => {if tool == Tool::Move && app.ui.transform.is_none() {begin_transform_controls_at(app, &ctx, &xf, p);@@ -2239,15 +2243,7 @@ pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers)return;}Tool::PolygonLasso => {- // Click adds a vertex; clicking near the first vertex closes the polygon.- let close = app.ui.polygon.first().is_some_and(|p0| {- app.ui.polygon.len() >= 3 && ((p0[0] - x).powi(2) + (p0[1] - y).powi(2)).sqrt() < 8.0 / app.current_zoom().max(0.01) as f64- });- if close {- commit_polygon(app, mods);- } else {- app.ui.polygon.push([x, y]);- }+ polygon_click(app, x, y, mods);return;}Tool::Type if crate::type_tool::pointer_down(app, x, y, mods.shift) => return,@@ -2424,11 +2420,36 @@ fn selection_mode(app: &PhotocraftApp, m: egui::Modifiers) -> &'static str {crate::tool_feedback::selection_mode(Tool::Lasso, app.ui.selection_mode, m)}-/// Close the polygonal lasso and make the selection.-pub fn commit_polygon(app: &mut PhotocraftApp, mods: egui::Modifiers) {+/// A polygonal lasso click adds a vertex; clicking near the first vertex closes the polygon. The+/// first click fixes the selection mode; a new-selection polygon hides the old outline while it is+/// drawn, and replaces it in one history step when it closes.+fn polygon_click(app: &mut PhotocraftApp, x: f64, y: f64, mods: egui::Modifiers) {+ let close = app+ .ui+ .polygon+ .first()+ .is_some_and(|p0| app.ui.polygon.len() >= 3 && ((p0[0] - x).powi(2) + (p0[1] - y).powi(2)).sqrt() < 8.0 / app.current_zoom().max(0.01) as f64);+ if close {+ commit_polygon(app);+ return;+ }+ if app.ui.polygon.is_empty() {+ app.ui.polygon_mode = selection_mode(app, mods).into();+ }+ app.ui.polygon.push([x, y]);+}++/// A new-selection polygonal lasso is being drawn, so the selection it will replace is hidden.+pub fn polygon_replaces_selection(app: &PhotocraftApp) -> bool {+ !app.ui.polygon.is_empty() && app.ui.polygon_mode == "replace"+}++/// Close the polygonal lasso and make the selection in the mode it started in.+pub fn commit_polygon(app: &mut PhotocraftApp) {let pts = std::mem::take(&mut app.ui.polygon);+ let mode = std::mem::take(&mut app.ui.polygon_mode);if pts.len() >= 3 {- let mode = selection_mode(app, mods);+ let mode = if mode.is_empty() { selection_mode(app, egui::Modifiers::NONE).to_owned() } else { mode };let _ = app.run("select.lasso", json!({"points": pts, "mode": mode, "antiAlias": app.ui.tool_options.anti_alias}));}}diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex 88600f893..d8bb503d0 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -1276,6 +1276,9 @@ mod marquee_tests;#[cfg(test)]mod stamp_tests;+#[cfg(test)]+mod polygon_lasso_tests;+#[cfg(test)]mod clipboard_tests {use super::*;diff --git a/crates/ui-egui/src/polygon_lasso_tests.rs b/crates/ui-egui/src/polygon_lasso_tests.rsnew file mode 100644index 000000000..7a44ec73d--- /dev/null+++ b/crates/ui-egui/src/polygon_lasso_tests.rs@@ -0,0 +1,208 @@+//! Polygonal Lasso through the real canvas: a double-click closes the polygon, and a+//! new-selection polygon hides the selection it replaces while it is drawn (⇧ or ⌥ at the first+//! click keep it, to add to or subtract from), replacing it in one history step.++use egui::{Modifiers, PointerButton, Pos2, vec2};+use egui_kittest::Harness;+use photocraft_geom::Rect;+use serde_json::json;++use crate::PhotocraftApp;+use crate::canvas::ViewXform;+use crate::state::Tool;++fn harness() -> Harness<'static, PhotocraftApp> {+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({"width": 400, "height": 300})).unwrap();+ app.sync_views();+ app.ui.extras.rulers = false;+ app.ui.tool = Tool::PolygonLasso;+ // 60 fps, so a double-click's two clicks fall inside egui's 0.3 s window.+ let mut h = Harness::builder().with_size(vec2(1000.0, 700.0)).with_step_dt(1.0 / 60.0).build_ui_state(+ |ui, app: &mut PhotocraftApp| {+ let ctx = ui.ctx().clone();+ if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) {+ return;+ }+ crate::shortcuts::handle(app, &ctx);+ 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);+ // 100 %: one document pixel per point.+ let v = &mut h.state_mut().ui.views[0];+ v.zoom = 1.0;+ v.center = [200.0, 150.0];+ v.fit_pending = false;+ h.run_steps(2);+ h+}++fn screen(h: &Harness<'static, PhotocraftApp>, x: f32, y: f32) -> Pos2 {+ let app = h.state();+ let v = &app.ui.views[0];+ let xf = ViewXform { rect: crate::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<'static, PhotocraftApp>, p: Pos2, down: bool, m: Modifiers) {+ h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: down, modifiers: m });+ h.run_steps(1);+}++/// A click at document point `(x, y)`, the pointer still between press and release.+fn click(h: &mut Harness<'static, PhotocraftApp>, x: f32, y: f32, m: Modifiers) {+ let p = screen(h, x, y);+ h.event(egui::Event::PointerMoved(p));+ h.run_steps(1);+ button(h, p, true, m);+ button(h, p, false, m);+}++fn double_click(h: &mut Harness<'static, PhotocraftApp>, x: f32, y: f32) {+ click(h, x, y, Modifiers::NONE);+ click(h, x, y, Modifiers::NONE);+ h.run_steps(1);+}++fn selection(h: &Harness<'static, PhotocraftApp>) -> Option<Rect> {+ h.state().session.active().unwrap().doc.selection.as_ref().map(|s| s.content_bounds())+}++fn near(r: Rect, x0: i32, y0: i32, x1: i32, y1: i32) -> bool {+ r.x0.abs_diff(x0) <= 1 && r.y0.abs_diff(y0) <= 1 && r.x1.abs_diff(x1) <= 1 && r.y1.abs_diff(y1) <= 1+}++#[test]+fn double_click_closes_the_polygon_at_the_last_point() {+ let mut h = harness();+ click(&mut h, 50.0, 50.0, Modifiers::NONE);+ h.run_steps(30); // Well past egui's double-click delay: separate clicks.+ click(&mut h, 150.0, 50.0, Modifiers::NONE);+ h.run_steps(30);+ double_click(&mut h, 150.0, 150.0);+ assert!(h.state().ui.polygon.is_empty(), "the polygon closed: {:?}", h.state().ui.polygon);+ let r = selection(&h).expect("a selection");+ assert!(near(r, 50, 50, 150, 150), "the triangle's bounds: {r:?}");+ // Only one vertex was added at the double-click, not a duplicate starting a new polygon.+ h.run_steps(30);+ assert!(h.state().ui.polygon.is_empty());+}++/// Vertices placed quickly: egui counts the double-click's second click as a triple click (the+/// vertex before it was under 0.6 s earlier). It still closes the polygon.+#[test]+fn double_click_closes_the_polygon_after_quickly_placed_vertices() {+ let mut h = harness();+ click(&mut h, 50.0, 50.0, Modifiers::NONE);+ h.run_steps(12);+ click(&mut h, 150.0, 50.0, Modifiers::NONE);+ h.run_steps(12);+ double_click(&mut h, 150.0, 150.0);+ assert!(h.state().ui.polygon.is_empty(), "{:?}", h.state().ui.polygon);+ assert!(selection(&h).is_some_and(|r| near(r, 50, 50, 150, 150)), "{:?}", selection(&h));+}++/// Double-clicking on the first vertex: the first click closes the polygon, and the second must+/// not start a new one (which would deselect what was just made).+#[test]+fn double_click_on_the_first_vertex_keeps_the_new_selection() {+ let mut h = harness();+ for (x, y) in [(50.0, 50.0), (150.0, 50.0), (150.0, 150.0)] {+ click(&mut h, x, y, Modifiers::NONE);+ h.run_steps(30);+ }+ double_click(&mut h, 50.0, 50.0);+ assert!(h.state().ui.polygon.is_empty());+ assert!(selection(&h).is_some_and(|r| near(r, 50, 50, 150, 150)), "{:?}", selection(&h));+}++/// Three clicks and Enter: a triangle with corners at the first three points.+fn triangle(h: &mut Harness<'static, PhotocraftApp>, x: f32, y: f32, m: Modifiers) {+ h.event(egui::Event::ModifiersChanged(m));+ h.run_steps(1);+ for (dx, dy) in [(0.0, 0.0), (100.0, 0.0), (100.0, 100.0)] {+ click(h, x + dx, y + dy, m);+ h.run_steps(30); // Not a double-click with the click before.+ }+ h.event(egui::Event::ModifiersChanged(Modifiers::NONE));+ h.run_steps(1);+ h.key_press(egui::Key::Enter);+ h.run_steps(2);+}++fn steps(h: &Harness<'static, PhotocraftApp>) -> usize {+ h.state().session.active().unwrap().history.entries().len()+}++/// A new polygon hides the selection it will replace; Esc brings it back untouched.+#[test]+fn a_new_polygon_hides_the_selection_and_esc_restores_it() {+ let mut h = harness();+ h.state_mut().run("select.rect", json!({"x": 200, "y": 150, "width": 100, "height": 100})).unwrap();+ h.run_steps(1);+ let before = steps(&h);+ click(&mut h, 20.0, 20.0, Modifiers::NONE);+ assert_eq!(h.state().ui.polygon.len(), 1);+ assert!(crate::canvas::polygon_replaces_selection(h.state()), "the old outline is hidden");+ assert_eq!(steps(&h), before, "starting a polygon records nothing");+ h.key_press(egui::Key::Escape);+ h.run_steps(2);+ assert!(h.state().ui.polygon.is_empty());+ assert!(!crate::canvas::polygon_replaces_selection(h.state()));+ assert!(selection(&h).is_some_and(|r| near(r, 200, 150, 300, 250)), "{:?}", selection(&h));+ assert_eq!(steps(&h), before);+}++/// Replacing a selection is one history step, and one Undo brings the old selection back.+#[test]+fn replacing_a_selection_is_one_history_step() {+ let mut h = harness();+ h.state_mut().run("select.rect", json!({"x": 200, "y": 150, "width": 100, "height": 100})).unwrap();+ h.run_steps(1);+ let before = steps(&h);+ triangle(&mut h, 20.0, 20.0, Modifiers::NONE);+ assert!(selection(&h).is_some_and(|r| near(r, 20, 20, 120, 120)), "{:?}", selection(&h));+ assert_eq!(steps(&h), before + 1);+ h.state_mut().run("edit.undo", json!({})).unwrap();+ assert!(selection(&h).is_some_and(|r| near(r, 200, 150, 300, 250)), "{:?}", selection(&h));+}++/// ⇧ (add) and ⌥ (subtract) at the first click keep the selection in view, and the polygon+/// combines in that mode even when it is closed with a bare Enter.+#[test]+fn modifiers_at_the_first_click_keep_and_combine_the_selection() {+ let mut h = harness();+ h.state_mut().run("select.rect", json!({"x": 200, "y": 150, "width": 100, "height": 100})).unwrap();+ h.run_steps(1);+ for m in [Modifiers::SHIFT, Modifiers::ALT] {+ h.event(egui::Event::ModifiersChanged(m));+ h.run_steps(1);+ click(&mut h, 20.0, 20.0, m);+ h.event(egui::Event::ModifiersChanged(Modifiers::NONE));+ h.run_steps(1);+ assert_eq!(h.state().ui.polygon.len(), 1, "{m:?}");+ assert!(!crate::canvas::polygon_replaces_selection(h.state()), "{m:?}: the selection stays in view");+ h.key_press(egui::Key::Escape);+ h.run_steps(30);+ }+ triangle(&mut h, 20.0, 20.0, Modifiers::SHIFT);+ assert!(selection(&h).is_some_and(|r| near(r, 20, 20, 300, 250)), "added: {:?}", selection(&h));+}++/// A new polygon over no selection records one step: the selection it makes.+#[test]+fn a_new_polygon_without_a_selection_adds_one_step() {+ let mut h = harness();+ let before = steps(&h);+ click(&mut h, 20.0, 20.0, Modifiers::NONE);+ assert_eq!(h.state().ui.polygon.len(), 1);+ assert_eq!(steps(&h), before);+ h.run_steps(30);+ h.key_press(egui::Key::Escape);+ h.run_steps(30);+ triangle(&mut h, 20.0, 20.0, Modifiers::NONE);+ assert_eq!(steps(&h), before + 1);+}diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rsindex bfc7579a7..3f92eca10 100644--- a/crates/ui-egui/src/shortcuts.rs+++ b/crates/ui-egui/src/shortcuts.rs@@ -301,7 +301,7 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context) {if !app.ui.polygon.is_empty() || app.ui.crop_rect.is_some() {if pressed(Key::Enter) {if !app.ui.polygon.is_empty() {- crate::canvas::commit_polygon(app, Modifiers::NONE);+ crate::canvas::commit_polygon(app);} else {crate::canvas::commit_crop(app);}@@ -309,6 +309,7 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context) {}if pressed(Key::Escape) {app.ui.polygon.clear();+ app.ui.polygon_mode.clear();app.ui.crop_rect = None;app.crop.drag = None;return;diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rsindex 4433eb55c..31989e0d1 100644--- a/crates/ui-egui/src/state.rs+++ b/crates/ui-egui/src/state.rs@@ -648,6 +648,10 @@ pub struct UiState {/// In-progress polygonal lasso vertices (document coordinates).#[serde(default)]pub polygon: Vec<[f64; 2]>,+ /// The selection mode the polygonal lasso started in ("replace", "add", ...), set by the+ /// modifiers held at its first click.+ #[serde(default)]+ pub polygon_mode: String,/// Crop tool rectangle being edited [x0, y0, x1, y1] (document coordinates).#[serde(default)]pub crop_rect: Option<[f64; 4]>,@@ -711,6 +715,7 @@ impl Default for UiState {selection_mode: 0,tool_options: ToolOptions::default(),polygon: Vec::new(),+ polygon_mode: String::new(),crop_rect: None,next_id: 1,status: String::new(),