PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Support Alt-held polygon segments in the freehand lasso (#711)
jerrykimo9e88c65d3348
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rsindex cbf71831c..cb02c076c 100644--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@ -52,11 +52,12 @@ pub struct Drag {/// A marquee or lasso drag that started inside the selection moves it instead of drawing:/// `Some(false)` moves the outline, `Some(true)` moves the floating piece (`select.float`).pub sel_move: Option<bool>,+ pub lasso: Option<crate::lasso_ui::Lasso>,}impl Drag {pub fn new(tool: Tool, start: [f64; 2], points: Vec<[f64; 3]>, modifiers: egui::Modifiers, erase: bool) -> Self {- Self { tool, start, points, modifiers, erase, constrain: None, live: modifiers, released: egui::Modifiers::NONE, reposition: false, sel_move: None }+ Self { tool, start, points, modifiers, erase, constrain: None, live: modifiers, released: egui::Modifiers::NONE, reposition: false, sel_move: None, lasso: None }}/// Reposition: move the start and every point so the last one lands on `to` (same size).@@ -77,7 +78,7 @@ impl Drag {}/// Record the modifiers of a pointer event.- fn track(&mut self, mods: egui::Modifiers) {+ pub(crate) fn track(&mut self, mods: egui::Modifiers) {self.live = mods;self.released.shift |= !mods.shift;self.released.alt |= !mods.alt;@@ -1693,6 +1694,10 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:{crate::canvas_tool_menu::open_transform(app, [p.x, p.y]);}+ if tool == Tool::Lasso {+ crate::lasso_ui::canvas_input(app, &ctx, &xf, &response);+ (buttons.started, buttons.dragged, buttons.stopped, buttons.clicked) = (false, false, false, false);+ }// Right-click with the Move tool, or ⌘/Ctrl+right-click: the layers under the pointer.if response.secondary_clicked()&& !transforming@@ -2187,7 +2192,10 @@ fn draw_drag_preview(app: &mut PhotocraftApp, painter: &egui::Painter, xf: &View}}Tool::Lasso | Tool::Patch => {- let pts: Vec<Pos2> = d.points.iter().map(|p| xf.to_screen(p[0] as f32, p[1] as f32)).collect();+ let mut pts: Vec<Pos2> = d.points.iter().map(|p| xf.to_screen(p[0] as f32, p[1] as f32)).collect();+ if let Some(lasso) = &d.lasso {+ pts.push(xf.to_screen(lasso.cursor[0] as f32, lasso.cursor[1] as f32));+ }crate::tool_feedback::draw_ants(painter, &pts, false);}Tool::Gradient => {@@ -2338,6 +2346,9 @@ pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers)if crate::gradient_ui::pointer(app, ev, mods) {return;}+ if crate::lasso_ui::pointer(app, ev, mods) {+ return;+ }let tool = app.ui.tool;if tool == Tool::Eyedropper {match ev {@@ -2549,7 +2560,7 @@ fn finish_selection_drag(app: &mut PhotocraftApp, floating: bool, start: [f64; 2}}-fn finish_gesture(app: &mut PhotocraftApp, d: Drag) {+pub(crate) fn finish_gesture(app: &mut PhotocraftApp, d: Drag) {let end = d.points.last().copied().unwrap_or([d.start[0], d.start[1], 1.0]);if let Some(floating) = d.sel_move {finish_selection_drag(app, floating, d.start, [end[0], end[1]]);diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsvindex ea8b41224..c1542a96f 100644--- a/crates/ui-egui/src/i18n/cs.tsv+++ b/crates/ui-egui/src/i18n/cs.tsv@@ -2070,3 +2070,5 @@ cameraRaw Color BarvyEdit Type Upravit textNo patterns Žádné vzorkyEnable {name} Povolit {name}+ Hold Alt while drawing for straight segments Podržením Alt při kreslení vytvoříte rovné úseky+ Drag or click polygon points · hold Alt during lasso for straight segments · {add} add · {sub} before drawing subtracts Táhněte nebo klikejte body mnohoúhelníku · podržením Alt během lasa kreslíte rovné úseky · {add} přidat · {sub} před kreslením odečtediff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsvindex bd3f61e1c..7bb676dc1 100644--- a/crates/ui-egui/src/i18n/de.tsv+++ b/crates/ui-egui/src/i18n/de.tsv@@ -2111,3 +2111,5 @@300% 300 %No patterns Keine MusterEnable {name} {name} aktivieren+ Hold Alt while drawing for straight segments Beim Zeichnen Alt gedrückt halten für gerade Segmente+ Drag or click polygon points · hold Alt during lasso for straight segments · {add} add · {sub} before drawing subtracts Ziehen oder Polygonpunkte klicken · Alt während des Lassos halten für gerade Segmente · {add} hinzufügen · {sub} vor dem Zeichnen zieht abdiff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsvindex 6f72b9cd7..46717ec46 100644--- a/crates/ui-egui/src/i18n/es.tsv+++ b/crates/ui-egui/src/i18n/es.tsv@@ -2147,3 +2147,5 @@ cameraRaw Amount CantidadEdit Type Editar textoNo patterns Sin motivosEnable {name} Activar {name}+ Hold Alt while drawing for straight segments Mantenga Alt al dibujar para segmentos rectos+ Drag or click polygon points · hold Alt during lasso for straight segments · {add} add · {sub} before drawing subtracts Arrastre o haga clic en los puntos del polígono · mantenga Alt durante el lazo para segmentos rectos · {add} añadir · {sub} antes de dibujar restadiff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsvindex c6e8610cc..bb18f73b2 100644--- a/crates/ui-egui/src/i18n/fr.tsv+++ b/crates/ui-egui/src/i18n/fr.tsv@@ -2500,3 +2500,5 @@ cameraRaw Blending FusionEdit Type Modifier le texteNo patterns Aucun motifEnable {name} Activer {name}+ Hold Alt while drawing for straight segments Maintenez Alt en dessinant pour des segments droits+ Drag or click polygon points · hold Alt during lasso for straight segments · {add} add · {sub} before drawing subtracts Faites glisser ou cliquez des points de polygone · maintenez Alt pendant le lasso pour des segments droits · {add} ajouter · {sub} avant de dessiner soustraitdiff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsvindex 154b72231..d9727d1b7 100644--- a/crates/ui-egui/src/i18n/id.tsv+++ b/crates/ui-egui/src/i18n/id.tsv@@ -2487,3 +2487,5 @@ cameraRaw Blending PembauranEdit Type Edit TeksNo patterns Tidak ada polaEnable {name} Aktifkan {name}+ Hold Alt while drawing for straight segments Tahan Alt saat menggambar untuk segmen lurus+ Drag or click polygon points · hold Alt during lasso for straight segments · {add} add · {sub} before drawing subtracts Seret atau klik titik poligon · tahan Alt saat lasso untuk segmen lurus · {add} tambah · {sub} sebelum menggambar mengurangidiff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsvindex 9bbfddce7..680d991f1 100644--- a/crates/ui-egui/src/i18n/ja.tsv+++ b/crates/ui-egui/src/i18n/ja.tsv@@ -2053,3 +2053,5 @@ cameraRaw Color カラーEdit Type 文字を編集No patterns パターンなしEnable {name} {name}を有効にする+ Hold Alt while drawing for straight segments 描画中に Alt を押すと直線セグメントになります+ Drag or click polygon points · hold Alt during lasso for straight segments · {add} add · {sub} before drawing subtracts ドラッグまたは多角形の点をクリック · なげなわ中に Alt で直線セグメント · {add} 追加 · 描画前の {sub} で削除diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsvindex 55d07e550..37bf06aca 100644--- a/crates/ui-egui/src/i18n/ko.tsv+++ b/crates/ui-egui/src/i18n/ko.tsv@@ -2650,3 +2650,5 @@ cameraRaw Color 색상Wrap 감싸기Zigzag 지그재그@id filter.sharpen.sharpen 선명하게+ Hold Alt while drawing for straight segments 그리는 중 Alt를 누르면 직선 구간+ Drag or click polygon points · hold Alt during lasso for straight segments · {add} add · {sub} before drawing subtracts 드래그하거나 다각형 점 클릭 · 올가미 중 Alt를 누르면 직선 구간 · {add} 추가 · 그리기 전 {sub} 빼기diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsvindex 249dc6963..a23b7e498 100644--- a/crates/ui-egui/src/i18n/pt-br.tsv+++ b/crates/ui-egui/src/i18n/pt-br.tsv@@ -2510,3 +2510,5 @@ cameraRaw Roughness AsperezacameraRaw Whites BrancosNo patterns Nenhum padrãoEnable {name} Ativar {name}+ Hold Alt while drawing for straight segments Segure Alt ao desenhar para segmentos retos+ Drag or click polygon points · hold Alt during lasso for straight segments · {add} add · {sub} before drawing subtracts Arraste ou clique nos pontos do polígono · segure Alt durante o laço para segmentos retos · {add} adicionar · {sub} antes de desenhar subtraidiff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsvindex 738dfc125..d88b7f8e5 100644--- a/crates/ui-egui/src/i18n/ru.tsv+++ b/crates/ui-egui/src/i18n/ru.tsv@@ -2348,3 +2348,5 @@ cameraRaw Roughness НеровностьEdit Type Редактировать текстNo patterns Нет узоровEnable {name} Включить {name}+ Hold Alt while drawing for straight segments Удерживайте Alt при рисовании для прямых отрезков+ Drag or click polygon points · hold Alt during lasso for straight segments · {add} add · {sub} before drawing subtracts Перетащите или щёлкайте точки многоугольника · удерживайте Alt во время лассо для прямых отрезков · {add} добавить · {sub} перед рисованием вычитаетdiff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsvindex 35e1766f1..2010a5e0a 100644--- a/crates/ui-egui/src/i18n/zh-hans.tsv+++ b/crates/ui-egui/src/i18n/zh-hans.tsv@@ -2079,3 +2079,5 @@ cameraRaw Blending 混合Edit Type 编辑文字No patterns 无图案Enable {name} 启用{name}+ Hold Alt while drawing for straight segments 绘制中按住 Alt 可逐点连接直线+ Drag or click polygon points · hold Alt during lasso for straight segments · {add} add · {sub} before drawing subtracts 拖动圈选或逐点绘制 · 圈选中按住 Alt 画直线 · {add} 添加 · 起笔前按 {sub} 减去diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsvindex 86e44fffd..385d653c2 100644--- a/crates/ui-egui/src/i18n/zh-hant.tsv+++ b/crates/ui-egui/src/i18n/zh-hant.tsv@@ -2048,3 +2048,5 @@ cameraRaw Blending 混合Edit Type 編輯文字No patterns 無圖樣Enable {name} 啟用{name}+ Hold Alt while drawing for straight segments 繪製中按住 Alt 可逐點連接直線+ Drag or click polygon points · hold Alt during lasso for straight segments · {add} add · {sub} before drawing subtracts 拖曳圈選或逐點繪製 · 圈選中按住 Alt 畫直線 · {add} 增加 · 起筆前按 {sub} 減去diff --git a/crates/ui-egui/src/lasso_ui.rs b/crates/ui-egui/src/lasso_ui.rsnew file mode 100644index 000000000..889714818--- /dev/null+++ b/crates/ui-egui/src/lasso_ui.rs@@ -0,0 +1,186 @@+//! One lasso outline can alternate between freehand strokes and Alt-held straight segments.+//! Selection intent is latched at the first press; Alt pressed later changes drawing mode.++use crate::{+ PhotocraftApp,+ canvas::{Drag, ToolEvent, ViewXform},+ state::Tool,+};+use egui::{Event, Modifiers, PointerButton};++#[derive(Clone, Debug)]+pub struct Lasso {+ pub cursor: [f64; 2],+ down: bool,+ polygonal: bool,+ document: Option<photocraft_doc::DocId>,+}++pub fn active(app: &PhotocraftApp) -> bool {+ app.drag.as_ref().is_some_and(|d| d.tool == Tool::Lasso && d.lasso.is_some())+}++/// A lasso drag that moves the selection (started inside it, `canvas::selection_drag_kind`):+/// the canvas's own selection-move path handles it, this module only feeds it the events.+fn moving_selection(app: &PhotocraftApp) -> bool {+ app.drag.as_ref().is_some_and(|d| d.tool == Tool::Lasso && d.sel_move.is_some())+}++pub fn cancel_stale(app: &mut PhotocraftApp) {+ if app+ .drag+ .as_ref()+ .and_then(|d| d.lasso.as_ref())+ .is_some_and(|lasso| app.ui.tool != Tool::Lasso || lasso.document != app.session.active().map(|st| st.doc.id))+ {+ app.drag = None;+ }+}++fn append(d: &mut Drag, p: [f64; 2]) {+ if d.points.last().is_none_or(|last| last[0] != p[0] || last[1] != p[1]) {+ d.points.push([p[0], p[1], 1.0]);+ }+}++fn modifiers(app: &mut PhotocraftApp, mods: Modifiers) {+ let Some(d) = app.drag.as_mut().filter(|d| d.tool == Tool::Lasso) else { return };+ d.track(mods);+ // Alt held before the initial press still means subtract, until released and pressed again.+ let polygonal = mods.alt && (!d.modifiers.alt || d.released.alt);+ if let Some(lasso) = &d.lasso {+ let anchor = (lasso.polygonal && !polygonal && lasso.down).then_some(lasso.cursor);+ if let Some(p) = anchor {+ append(d, p);+ }+ }+ if let Some(lasso) = &mut d.lasso {+ lasso.polygonal = polygonal;+ }+}++pub fn commit(app: &mut PhotocraftApp) {+ cancel_stale(app);+ if active(app)+ && let Some(d) = app.drag.take()+ {+ crate::canvas::finish_gesture(app, d);+ }+}++pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: Modifiers) -> bool {+ cancel_stale(app);+ if app.ui.tool != Tool::Lasso || moving_selection(app) {+ return false;+ }+ let p = match ev {+ ToolEvent::Down { x, y, .. } | ToolEvent::Move { x, y, .. } | ToolEvent::Up { x, y } => [x, y],+ };+ // A press inside the selection (no outline in progress) drags the selection instead.+ if matches!(ev, ToolEvent::Down { .. })+ && !active(app)+ && p.iter().all(|n| n.is_finite())+ && crate::canvas::selection_drag_kind(app, Tool::Lasso, p, mods).is_some()+ {+ return false;+ }+ if !p.iter().all(|n| n.is_finite()) {+ return true;+ }+ modifiers(app, mods);+ match ev {+ ToolEvent::Down { .. } => {+ if active(app) {+ let close = app+ .drag+ .as_ref()+ .is_some_and(|d| d.points.len() >= 3 && (d.start[0] - p[0]).hypot(d.start[1] - p[1]) < 8.0 / app.current_zoom().max(0.01) as f64);+ if close {+ commit(app);+ return true;+ }+ if let Some(d) = &mut app.drag {+ append(d, p);+ if let Some(lasso) = &mut d.lasso {+ lasso.cursor = p;+ lasso.down = true;+ }+ }+ } else {+ let mut d = Drag::new(Tool::Lasso, p, vec![[p[0], p[1], 1.0]], mods, false);+ d.lasso = Some(Lasso { cursor: p, down: true, polygonal: false, document: app.session.active().map(|st| st.doc.id) });+ app.drag = Some(d);+ }+ }+ ToolEvent::Move { .. } | ToolEvent::Up { .. } => {+ let up = matches!(ev, ToolEvent::Up { .. });+ let Some(d) = app.drag.as_mut().filter(|d| d.tool == Tool::Lasso) else { return true };+ let Some(lasso) = &d.lasso else { return true };+ let (down, polygonal, previous) = (lasso.down, lasso.polygonal, lasso.cursor);+ if d.reposition {+ // Move relative to the rubber-band endpoint, not the last fixed vertex.+ let last = d.points.last().map_or(d.start, |p| [p[0], p[1]]);+ d.shift_to([last[0] + p[0] - previous[0], last[1] + p[1] - previous[1]]);+ } else if down && (!polygonal || up) {+ append(d, p);+ }+ if let Some(lasso) = &mut d.lasso {+ lasso.cursor = p;+ if up {+ lasso.down = false;+ }+ }+ if up && down && !polygonal {+ commit(app);+ }+ }+ }+ true+}++/// Read actual presses/releases, including clicks below egui's drag threshold. Hover moves+/// update only the rubber band; they must never become freehand vertices between Alt clicks.+pub fn canvas_input(app: &mut PhotocraftApp, ctx: &egui::Context, xf: &ViewXform, response: &egui::Response) {+ let events = ctx.input(|i| i.events.clone());+ let mut mods = app.drag.as_ref().map_or(ctx.input(|i| i.modifiers), |d| d.live);+ for ev in events {+ let tool_ev = match ev {+ Event::ModifiersChanged(m) => {+ mods = m;+ modifiers(app, crate::workspace_ui::sticky_mods(app, m));+ None+ }+ Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: m } => {+ mods = m;+ let p = xf.to_doc(pos);+ if pressed && response.contains_pointer() && response.rect.contains(pos) {+ Some(ToolEvent::Down { x: p[0], y: p[1], pressure: 1.0 })+ } else if !pressed && (active(app) || moving_selection(app)) {+ Some(ToolEvent::Up { x: p[0], y: p[1] })+ } else {+ None+ }+ }+ Event::PointerMoved(pos) if active(app) || moving_selection(app) => {+ let p = xf.to_doc(pos);+ Some(ToolEvent::Move { x: p[0], y: p[1], pressure: 1.0 })+ }+ Event::WindowFocused(false) => {+ if active(app) || moving_selection(app) {+ app.drag = None;+ }+ None+ }+ _ => None,+ };+ if let Some(ev) = tool_ev {+ crate::canvas::tool_event(app, ev, mods);+ }+ }+ if response.double_clicked() {+ commit(app);+ }+}++#[cfg(test)]+mod tests;diff --git a/crates/ui-egui/src/lasso_ui/tests.rs b/crates/ui-egui/src/lasso_ui/tests.rsnew file mode 100644index 000000000..7639170ed--- /dev/null+++ b/crates/ui-egui/src/lasso_ui/tests.rs@@ -0,0 +1,201 @@+use super::*;+use crate::canvas::tool_event;+use serde_json::json;++fn app() -> PhotocraftApp {+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());+ app.run("file.new", json!({"width": 400, "height": 300})).unwrap();+ app.sync_views();+ app.ui.tool = Tool::Lasso;+ app+}++fn event(app: &mut PhotocraftApp, kind: &str, x: f64, y: f64, mods: Modifiers) {+ let ev = match kind {+ "down" => ToolEvent::Down { x, y, pressure: 1.0 },+ "up" => ToolEvent::Up { x, y },+ _ => ToolEvent::Move { x, y, pressure: 1.0 },+ };+ tool_event(app, ev, mods);+}++fn begin(app: &mut PhotocraftApp, mods: Modifiers) {+ event(app, "down", 50.0, 50.0, mods);+ event(app, "move", 90.0, 40.0, mods);+ event(app, "move", 120.0, 50.0, mods);+}++#[test]+fn alt_clicks_preserve_outline_and_hover_does_not_draw() {+ let mut app = app();+ begin(&mut app, Modifiers::NONE);+ event(&mut app, "up", 120.0, 50.0, Modifiers::ALT);+ assert!(app.session.active().unwrap().doc.selection.is_none());+ event(&mut app, "move", 170.0, 10.0, Modifiers::ALT);+ event(&mut app, "move", 180.0, 100.0, Modifiers::ALT);+ assert_eq!(app.drag.as_ref().unwrap().points.len(), 3);+ event(&mut app, "down", 180.0, 100.0, Modifiers::ALT);+ event(&mut app, "up", 180.0, 100.0, Modifiers::ALT);+ assert_eq!(app.drag.as_ref().unwrap().points.len(), 4);+ assert_eq!(crate::tool_feedback::badge(&app, Tool::Lasso, Modifiers::ALT), None);+ // Release Alt between clicks, then continue a freehand stroke in the same outline.+ event(&mut app, "move", 140.0, 150.0, Modifiers::NONE);+ assert_eq!(app.drag.as_ref().unwrap().points.len(), 4);+ event(&mut app, "down", 130.0, 140.0, Modifiers::NONE);+ event(&mut app, "move", 90.0, 130.0, Modifiers::NONE);+ event(&mut app, "up", 50.0, 120.0, Modifiers::NONE);+ assert!(!active(&app));+ let sel = app.session.active().unwrap().doc.selection.as_ref().unwrap();+ assert!(sel.sample_channel(100, 80, 0) > 0.9);+ assert!(sel.sample_channel(160, 20, 0) < 0.1, "hover detour must stay outside");+ app.run("edit.undo", json!({})).unwrap();+ assert!(app.session.active().unwrap().doc.selection.is_none(), "one selection undo");+}++#[test]+fn switching_back_while_pressed_fixes_the_straight_endpoint() {+ let mut app = app();+ begin(&mut app, Modifiers::NONE);+ event(&mut app, "move", 180.0, 100.0, Modifiers::ALT);+ assert_eq!(app.drag.as_ref().unwrap().points.len(), 3);+ event(&mut app, "move", 170.0, 130.0, Modifiers::NONE);+ let pts = &app.drag.as_ref().unwrap().points;+ assert_eq!(&pts[3..], &[[180.0, 100.0, 1.0], [170.0, 130.0, 1.0]]);+ event(&mut app, "up", 50.0, 120.0, Modifiers::NONE);+ assert!(app.session.active().unwrap().doc.selection.is_some());+}++#[test]+fn initial_alt_still_subtracts_and_initial_shift_still_adds() {+ for initial in [Modifiers::ALT, Modifiers::SHIFT, Modifiers::SHIFT | Modifiers::ALT] {+ let mut app = app();+ app.run("select.rect", json!({"x": 0, "y": 0, "width": 150, "height": 200})).unwrap();+ begin(&mut app, initial);+ if initial.alt {+ event(&mut app, "move", 120.0, 50.0, Modifiers::NONE);+ }+ event(&mut app, "up", 120.0, 50.0, Modifiers::ALT);+ event(&mut app, "down", 180.0, 150.0, Modifiers::ALT);+ event(&mut app, "up", 180.0, 150.0, Modifiers::ALT);+ commit(&mut app);+ let sel = app.session.active().unwrap().doc.selection.as_ref().unwrap();+ assert_eq!(sel.sample_channel(120, 90, 0) > 0.5, initial.shift);+ assert_eq!(sel.sample_channel(10, 10, 0) > 0.5, !(initial.shift && initial.alt));+ }+}++#[test]+fn tool_or_document_switch_discards_pending_outline() {+ let mut app = app();+ begin(&mut app, Modifiers::NONE);+ event(&mut app, "up", 120.0, 50.0, Modifiers::ALT);+ app.ui.tool = Tool::Brush;+ app.sync_views();+ assert!(!active(&app));+ app.ui.tool = Tool::Lasso;+ begin(&mut app, Modifiers::NONE);+ event(&mut app, "up", 120.0, 50.0, Modifiers::ALT);+ app.run("file.new", json!({"width": 200, "height": 200})).unwrap();+ commit(&mut app);+ assert!(!active(&app));+ assert!(app.session.active().unwrap().doc.selection.is_none());+}++fn harness() -> egui_kittest::Harness<'static, PhotocraftApp> {+ let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1000.0, 700.0)).build_ui_state(+ |ui, app: &mut PhotocraftApp| {+ let ctx = ui.ctx().clone();+ if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) {+ return;+ }+ crate::shortcuts::handle(app, &ctx);+ egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui));+ },+ app(),+ );+ PhotocraftApp::setup_context(&h.ctx, Default::default());+ h.run_steps(4);+ 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 mouse(h: &mut egui_kittest::Harness<'static, PhotocraftApp>, kind: &str, x: f32, y: f32, mods: Modifiers) {+ 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: false };+ let pos = xf.to_screen(x, y);+ h.event(Event::ModifiersChanged(mods));+ h.event(Event::PointerMoved(pos));+ if kind != "move" {+ h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed: kind == "down", modifiers: mods });+ }+ h.run_steps(2);+}++#[test]+fn real_canvas_alt_clicks_enter_escape_and_resume() {+ for finish in ["enter", "escape", "resume", "close"] {+ let mut h = harness();+ mouse(&mut h, "down", 50.0, 50.0, Modifiers::NONE);+ mouse(&mut h, "move", 120.0, 50.0, Modifiers::NONE);+ mouse(&mut h, "up", 120.0, 50.0, Modifiers::ALT);+ assert!(active(h.state()), "Alt release must keep gesture");+ mouse(&mut h, "move", 180.0, 100.0, Modifiers::ALT);+ mouse(&mut h, "down", 180.0, 100.0, Modifiers::ALT);+ mouse(&mut h, "up", 180.0, 100.0, Modifiers::ALT);+ assert_eq!(h.state().drag.as_ref().unwrap().points.len(), 3);+ match finish {+ "resume" => {+ mouse(&mut h, "down", 150.0, 150.0, Modifiers::NONE);+ mouse(&mut h, "move", 90.0, 130.0, Modifiers::NONE);+ mouse(&mut h, "up", 50.0, 120.0, Modifiers::NONE);+ }+ "close" => {+ mouse(&mut h, "down", 50.0, 50.0, Modifiers::ALT);+ mouse(&mut h, "up", 50.0, 50.0, Modifiers::ALT);+ }+ _ => {+ h.event(Event::Key {+ key: if finish == "escape" { egui::Key::Escape } else { egui::Key::Enter },+ physical_key: None,+ pressed: true,+ repeat: false,+ modifiers: Modifiers::ALT,+ });+ h.run_steps(2);+ }+ }+ assert!(!active(h.state()), "{finish}");+ assert_eq!(h.state().session.active().unwrap().doc.selection.is_some(), finish != "escape", "{finish}");+ }+}++/// A lasso press inside the selection still drags the selection (`canvas::selection_drag_kind`),+/// both through tool events and through the real canvas.+#[test]+fn a_drag_inside_the_selection_moves_it() {+ let mut app = app();+ app.ui.extras.snap = false;+ app.run("select.rect", json!({"x": 100, "y": 100, "width": 50, "height": 40})).unwrap();+ let bounds = |app: &PhotocraftApp| app.session.active().unwrap().doc.selection.as_ref().map(|s| s.content_bounds());+ event(&mut app, "down", 120.0, 120.0, Modifiers::NONE);+ event(&mut app, "move", 130.0, 125.0, Modifiers::NONE);+ event(&mut app, "up", 130.0, 125.0, Modifiers::NONE);+ assert!(!active(&app));+ assert_eq!(bounds(&app), Some(photocraft_geom::Rect::new(110, 105, 160, 145)));++ let mut h = harness();+ h.state_mut().ui.extras.snap = false;+ h.state_mut().run("select.rect", json!({"x": 100, "y": 100, "width": 50, "height": 40})).unwrap();+ h.run_steps(1);+ mouse(&mut h, "down", 120.0, 120.0, Modifiers::NONE);+ mouse(&mut h, "move", 125.0, 122.0, Modifiers::NONE);+ mouse(&mut h, "move", 130.0, 125.0, Modifiers::NONE);+ mouse(&mut h, "up", 130.0, 125.0, Modifiers::NONE);+ assert!(h.state().drag.is_none());+ assert_eq!(bounds(h.state()), Some(photocraft_geom::Rect::new(110, 105, 160, 145)));+}diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex d3fbb97fa..9fa109998 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -61,6 +61,7 @@ pub mod i18n;mod icon_data;pub mod icons;pub mod jobs_ui;+pub mod lasso_ui;pub mod layer_menu_ui;pub mod layer_pick_ui;pub mod layer_props_ui;@@ -594,6 +595,7 @@ impl PhotocraftApp {/// Keep one view per document.pub fn sync_views(&mut self) {+ crate::lasso_ui::cancel_stale(self);let n = self.session.documents().len();self.ui.views.resize_with(n, Default::default);self.ui.windows.retain(|w| w.document < n);diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rsindex a60b99345..d05eb3d15 100644--- a/crates/ui-egui/src/panels.rs+++ b/crates/ui-egui/src/panels.rs@@ -592,7 +592,7 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {if widgets::secondary_button(ui, tl!("Select and Mask…"), 0.0).clicked() {let _ = crate::menus::invoke(app, ui.ctx(), "select.selectAndMask", json!({}));}- if app.ui.tool == Tool::PolygonLasso && !app.ui.polygon.is_empty() {+ if crate::lasso_ui::active(app) || (app.ui.tool == Tool::PolygonLasso && !app.ui.polygon.is_empty()) {hint(ui,&crate::i18n::fmt(@@ -600,6 +600,8 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {&[("key", &crate::shortcuts::pretty("Enter"))],),);+ } else if app.ui.tool == Tool::Lasso {+ hint(ui, tl!("Hold Alt while drawing for straight segments"));}}Tool::MagicWand => {@@ -792,7 +794,7 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {Tool::Lasso | Tool::PolygonLasso => hint(ui,&crate::i18n::fmt(- tl!("Drag (lasso) or click points (polygonal) · {add} add · {sub} subtract"),+ tl!("Drag or click polygon points · hold Alt during lasso for straight segments · {add} add · {sub} before drawing subtracts"),&[("add", &crate::shortcuts::pretty("Shift")), ("sub", &crate::shortcuts::pretty("Alt"))],),),diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rsindex d6e52e6f5..da3e69bf0 100644--- a/crates/ui-egui/src/shortcuts.rs+++ b/crates/ui-egui/src/shortcuts.rs@@ -304,6 +304,17 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context) {// `tools.swapColors`), dispatched above with any Keyboard Shortcuts override.let pressed = |k: Key| ctx.input_mut(|i| i.consume_key(Modifiers::NONE, k));// Enter / Escape commit or cancel in-progress tool state (polygonal lasso, crop).+ if crate::lasso_ui::active(app) {+ let mods = ctx.input(|i| i.modifiers);+ if ctx.input_mut(|i| i.consume_key(mods, Key::Escape)) {+ app.drag = None;+ return;+ }+ if ctx.input_mut(|i| i.consume_key(mods, Key::Enter)) {+ crate::lasso_ui::commit(app);+ return;+ }+ }if !app.ui.polygon.is_empty() || app.ui.crop_rect.is_some() {if pressed(Key::Enter) {if !app.ui.polygon.is_empty() {diff --git a/crates/ui-egui/src/tool_feedback.rs b/crates/ui-egui/src/tool_feedback.rsindex d8fc6a47f..58851b789 100644--- a/crates/ui-egui/src/tool_feedback.rs+++ b/crates/ui-egui/src/tool_feedback.rs@@ -77,6 +77,7 @@ pub fn badge(app: &PhotocraftApp, tool: Tool, m: egui::Modifiers) -> Option<Badgif !is_selection_tool(tool) {return None;}+ let m = app.drag.as_ref().filter(|d| d.tool == Tool::Lasso && tool == Tool::Lasso).map_or(m, |d| d.modifiers);Badge::from_mode(selection_mode(tool, app.ui.selection_mode, m))}