PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Isolate live distortion tools per document (#5115) (#5447)
Vikram Bhaskaran117faadb7911
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rsindex d2543a54c..4a885afcf 100644--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@ -1385,6 +1385,7 @@ pub(crate) fn display_doc(app: &mut PhotocraftApp, idx: usize) -> (std::sync::Ar}if let (Some(t), Some(pv)) = (&app.ui.transform, &app.transform_preview)&& app.session.active_index() == Some(idx)+ && pv.doc.id == st.doc.id&& st.doc.layer(photocraft_doc::LayerId(t.layer)).is_some(){return (pv.doc.clone(), (1 << 40) + pv.session);diff --git a/crates/ui-egui/src/distort_ui.rs b/crates/ui-egui/src/distort_ui.rsindex 5441a971e..be1c0ddbc 100644--- a/crates/ui-egui/src/distort_ui.rs+++ b/crates/ui-egui/src/distort_ui.rs@@ -10,7 +10,7 @@use std::sync::Arc;use egui::{Color32, ColorImage};-use photocraft_doc::{Document, LayerContent, LayerId};+use photocraft_doc::{DocId, Document, LayerContent, LayerId};use photocraft_geom::Rect;use photocraft_raster::Surface;use serde_json::{Value, json};@@ -91,15 +91,50 @@ pub(crate) fn surface_image(surf: &Surface, r: Rect, max_side: usize) -> ColorImColorImage::new([tw, th], px)}+fn active_doc(app: &PhotocraftApp) -> Option<DocId> {+ app.session.active().map(|st| st.doc.id)+}++fn on_doc(app: &PhotocraftApp, document: DocId) -> bool {+ active_doc(app) == Some(document)+}++/// Drops Liquify / Puppet / Perspective Warp / Vanishing Point / Filter Gallery when the+/// document they were opened on is no longer active, so they cannot steal undo, block layer+/// delete, or draw another document's pixels (#5115).+pub fn cancel_stale(app: &mut PhotocraftApp) {+ let active = active_doc(app);+ if app.distort.liquify.as_ref().is_some_and(|d| Some(d.document) != active) {+ crate::liquify_ui::cancel(app);+ }+ if app.distort.puppet.as_ref().is_some_and(|p| Some(p.document) != active) {+ app.distort.puppet = None;+ }+ if app.distort.perspective.as_ref().is_some_and(|p| Some(p.document) != active) {+ app.distort.perspective = None;+ }+ if app.distort.vanishing.as_ref().is_some_and(|v| Some(v.document) != active) {+ app.distort.vanishing = None;+ }+ if app.distort.gallery.as_ref().is_some_and(|g| Some(g.document) != active) {+ app.distort.gallery = None;+ }+}+/// The document shown on the canvas while Puppet or Perspective Warp previews a layer.pub fn display_doc(app: &PhotocraftApp, idx: usize) -> Option<(Arc<Document>, u64)> {if app.session.active_index() != Some(idx) {return None;}- if let Some(p) = &app.distort.puppet {+ let id = app.session.documents().get(idx).map(|st| st.doc.id)?;+ if let Some(p) = &app.distort.puppet+ && p.document == id+ {return Some((p.preview_doc.clone(), (1 << 42) + p.key));}- if let Some(p) = &app.distort.perspective {+ if let Some(p) = &app.distort.perspective+ && p.document == id+ {return Some((p.preview_doc.clone(), (1 << 42) + p.key));}None@@ -137,23 +172,24 @@ pub fn menu(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &Val/// Pointer events (document coordinates) while a mode is active. True when consumed.pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> bool {+ cancel_stale(app);if app.distort.caf.is_some() {crate::caf_ui::pointer(app, ev, mods);return true;}- if app.distort.liquify.is_some() {+ if app.distort.liquify.as_ref().is_some_and(|d| on_doc(app, d.document)) {crate::liquify_ui::pointer(app, ev, mods);return true;}- if app.distort.puppet.is_some() {+ if app.distort.puppet.as_ref().is_some_and(|p| on_doc(app, p.document)) {crate::puppet_ui::pointer(app, ev, mods);return true;}- if app.distort.perspective.is_some() {+ if app.distort.perspective.as_ref().is_some_and(|p| on_doc(app, p.document)) {crate::perspective_ui::pointer(app, ev, mods);return true;}- if app.distort.vanishing.is_some() {+ if app.distort.vanishing.as_ref().is_some_and(|v| on_doc(app, v.document)) {crate::vp_ui::pointer(app, ev, mods);return true;}@@ -164,6 +200,7 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) ->/// of the rest of the app should be skipped.pub fn keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool {use egui::{Key, Modifiers};+ cancel_stale(app);let enter = |ctx: &egui::Context| ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Enter));let esc = |ctx: &egui::Context| ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Escape));if app.distort.gallery.is_some() {@@ -245,19 +282,26 @@ pub fn draw_content(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform/// Canvas overlay for the on-canvas modes: pins, planes and meshes over the guides.pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform) {- if let Some(p) = &app.distort.puppet {+ if let Some(p) = &app.distort.puppet+ && on_doc(app, p.document)+ {crate::puppet_ui::draw(p, painter, xf);}- if let Some(p) = &app.distort.perspective {+ if let Some(p) = &app.distort.perspective+ && on_doc(app, p.document)+ {crate::perspective_ui::draw(p, painter, xf);}- if let Some(v) = &app.distort.vanishing {+ if let Some(v) = &app.distort.vanishing+ && on_doc(app, v.document)+ {crate::vp_ui::draw(v, painter, xf);}}/// Options bar for the on-canvas modes. True when drawn.pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> bool {+ cancel_stale(app);if app.distort.puppet.is_some() {crate::puppet_ui::options_bar(app, ui);return true;@@ -295,6 +339,7 @@ pub fn drop_foreign(app: &mut PhotocraftApp) {/// Full-window dialogs (Liquify, Content-Aware Fill, Filter Gallery).pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {+ cancel_stale(app);drop_foreign(app);if app.distort.caf.is_some() {crate::caf_ui::show(app, ctx);@@ -312,3 +357,93 @@ pub(crate) fn tolerance(app: &PhotocraftApp) -> f64 {let z = app.point_zoom().max(0.01);8.0 / f64::from(z)}++#[cfg(test)]+mod tests {+ use super::*;+ use photocraft_geom::Rect;+ use serde_json::json;++ fn paint_bar(app: &mut PhotocraftApp) {+ app.session+ .edit("paint", |doc, active| {+ doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(20, 30, 80, 50), &[1.0, 0.0, 0.0, 1.0]);+ Ok(())+ })+ .unwrap();+ }++ /// #5115: Puppet Warp is per-document. Switching tabs drops the session so Ctrl+Z and+ /// layer delete apply to the new document, and the warp mesh does not leak onto it.+ #[test]+ fn switching_documents_drops_puppet_and_restores_undo_and_delete() {+ let ctx = egui::Context::default();+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());+ app.session.execute("file.new", json!({"width": 100, "height": 80, "depth": 8})).unwrap();+ app.session.execute("layer.new.layer", json!({})).unwrap();+ paint_bar(&mut app);+ app.sync_views();+ menu(&mut app, &ctx, "edit.puppetWarp", &json!({})).unwrap().unwrap();+ pointer(&mut app, ToolEvent::Down { x: 50.0, y: 40.0, pressure: 1.0 }, egui::Modifiers::NONE);+ pointer(&mut app, ToolEvent::Up { x: 50.0, y: 40.0 }, egui::Modifiers::NONE);+ assert!(app.distort.puppet.is_some());+ let first = app.session.active().unwrap().doc.id;+ app.session.execute("file.new", json!({"width": 60, "height": 40, "depth": 8})).unwrap();+ app.session.execute("layer.new.layer", json!({})).unwrap();+ app.sync_views();+ assert!(app.distort.puppet.is_none(), "puppet does not follow the new document");+ assert!(display_doc(&app, app.session.active_index().unwrap()).is_none());+ let layers_before = app.session.active().unwrap().doc.layers.len();+ app.session.execute("layer.delete", json!({})).unwrap();+ assert_eq!(app.session.active().unwrap().doc.layers.len(), layers_before - 1);+ assert!(app.session.set_active(0));+ app.sync_views();+ assert_eq!(app.session.active().unwrap().doc.id, first);+ let past = app.session.active().unwrap().history.past_len();+ app.session.execute("edit.undo", json!({})).unwrap();+ assert_eq!(app.session.active().unwrap().history.past_len(), past - 1);+ }++ #[test]+ fn committed_puppet_is_one_undo_step_and_the_layer_stays_deletable() {+ let ctx = egui::Context::default();+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());+ app.session.execute("file.new", json!({"width": 100, "height": 80, "depth": 8})).unwrap();+ app.session.execute("layer.new.layer", json!({})).unwrap();+ paint_bar(&mut app);+ app.sync_views();+ menu(&mut app, &ctx, "edit.puppetWarp", &json!({})).unwrap().unwrap();+ pointer(&mut app, ToolEvent::Down { x: 25.0, y: 40.0, pressure: 1.0 }, egui::Modifiers::NONE);+ pointer(&mut app, ToolEvent::Up { x: 25.0, y: 40.0 }, egui::Modifiers::NONE);+ pointer(&mut app, ToolEvent::Down { x: 75.0, y: 40.0, pressure: 1.0 }, egui::Modifiers::NONE);+ pointer(&mut app, ToolEvent::Move { x: 75.0, y: 30.0, pressure: 1.0 }, egui::Modifiers::NONE);+ pointer(&mut app, ToolEvent::Up { x: 75.0, y: 20.0 }, egui::Modifiers::NONE);+ let before = app.session.active().unwrap().history.past_len();+ crate::puppet_ui::commit(&mut app);+ assert!(app.distort.puppet.is_none());+ assert_eq!(app.session.active().unwrap().history.past_len(), before + 1);+ app.session.execute("edit.undo", json!({})).unwrap();+ assert_eq!(app.session.active().unwrap().history.past_len(), before);+ let layers = app.session.active().unwrap().doc.layers.len();+ app.session.execute("layer.delete", json!({})).unwrap();+ assert_eq!(app.session.active().unwrap().doc.layers.len(), layers - 1);+ }++ #[test]+ fn switching_documents_drops_liquify() {+ let ctx = egui::Context::default();+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());+ app.session.execute("file.new", json!({"width": 100, "height": 80, "depth": 8})).unwrap();+ app.session.execute("layer.new.layer", json!({})).unwrap();+ paint_bar(&mut app);+ crate::liquify_ui::open(&mut app, &ctx).unwrap();+ assert!(app.distort.liquify.is_some());+ app.session.execute("file.new", json!({"width": 40, "height": 40, "depth": 8})).unwrap();+ app.session.execute("layer.new.layer", json!({})).unwrap();+ app.sync_views();+ assert!(app.distort.liquify.is_none());+ let past = app.session.active().unwrap().history.past_len();+ app.session.execute("edit.undo", json!({})).unwrap();+ assert_eq!(app.session.active().unwrap().history.past_len(), past - 1);+ }+}diff --git a/crates/ui-egui/src/gallery_ui.rs b/crates/ui-egui/src/gallery_ui.rsindex 89eac953e..b5e50734f 100644--- a/crates/ui-egui/src/gallery_ui.rs+++ b/crates/ui-egui/src/gallery_ui.rs@@ -15,7 +15,7 @@ use std::hash::{Hash, Hasher};use egui::{Align2, Color32, FontId, Rect as ERect, Sense, Stroke, TextureHandle, pos2, vec2};use photocraft_algo::{FilterParams, GALLERY_CATEGORIES, GalleryFilter};-use photocraft_doc::LayerId;+use photocraft_doc::{DocId, LayerId};use photocraft_geom::Rect;use photocraft_raster::{Interrupt, Surface};use serde_json::{Map, Value, json};@@ -66,6 +66,8 @@ fn default_params(f: GalleryFilter) -> Map<String, Value> {}pub struct GalleryDialog {+ /// Document this dialog belongs to (#5115).+ pub document: DocId,pub layer: LayerId,layer_name: String,canvas: Rect,@@ -100,6 +102,7 @@ pub struct GalleryDialog {impl GalleryDialog {pub fn describe(&self) -> Value {json!({+ "document": self.document.0,"layer": self.layer.0,"effects": self.effects.iter().map(EffectLayer::to_json).collect::<Vec<_>>(),"selected": self.selected,@@ -351,6 +354,7 @@ fn open_on(let open_cats = std::array::from_fn(|i| effects[sel].filter.category() == GALLERY_CATEGORIES[i]);let history = EditHistory::new(&effects);app.distort.gallery = Some(GalleryDialog {+ document: st.doc.id,layer,layer_name,canvas,diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex 886fffeca..6e17af0a6 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -1489,6 +1489,7 @@ impl PhotocraftApp {// ... and to the document it was started on.crate::canvas::polygon_cancel_stale(self);crate::crop_ui::cancel_stale(self);+ crate::distort_ui::cancel_stale(self);crate::perspective_crop_ui::cancel_stale(self);// A pen path under construction belongs to the document it was started on too.vector_ui::cancel_stale(self);diff --git a/crates/ui-egui/src/liquify_ui.rs b/crates/ui-egui/src/liquify_ui.rsindex cf1c93251..43a792d3f 100644--- a/crates/ui-egui/src/liquify_ui.rs+++ b/crates/ui-egui/src/liquify_ui.rs@@ -10,7 +10,7 @@use egui::{Align2, Color32, FontId, Pos2, Rect as ERect, Sense, Stroke, TextureHandle, pos2, vec2};use photocraft_algo::liquify::{LiquifyField, LiquifyStroke, LiquifyTool, ProxyImage, auto_cell};-use photocraft_doc::{Document, LayerId};+use photocraft_doc::{DocId, Document, LayerId};use photocraft_geom::Rect;use photocraft_raster::Surface;use serde_json::{Value, json};@@ -153,6 +153,8 @@ impl LiquifyOpts {}pub struct LiquifyDialog {+ /// Document this dialog belongs to (#5115).+ pub document: DocId,pub layer: LayerId,layer_name: String,canvas: Rect,@@ -219,6 +221,7 @@ fn union_rect(a: Option<Rect>, b: Rect) -> Option<Rect> {impl LiquifyDialog {pub fn describe(&self) -> Value {json!({+ "document": self.document.0,"layer": self.layer.0,"tool": self.opts.tool,"size": self.opts.size,@@ -529,6 +532,7 @@ fn open_on(let out = vec![[0u8; 4]; proxy.w * proxy.h];let center = [f64::from(canvas.x0 + canvas.x1) / 2.0, f64::from(canvas.y0 + canvas.y1) / 2.0];let mut d = LiquifyDialog {+ document: st.doc.id,layer,layer_name: name,canvas,diff --git a/crates/ui-egui/src/perspective_ui.rs b/crates/ui-egui/src/perspective_ui.rsindex e39a791d4..b38318497 100644--- a/crates/ui-egui/src/perspective_ui.rs+++ b/crates/ui-egui/src/perspective_ui.rs@@ -11,7 +11,7 @@ use std::sync::Arc;use egui::{Color32, Pos2, Stroke, TextureHandle, pos2};use photocraft_algo::perspective::{PerspectiveMap, Plane, Straighten, linked_corners, plane_point, straighten};-use photocraft_doc::{Document, LayerId};+use photocraft_doc::{DocId, Document, LayerId};use photocraft_geom::Rect;use serde_json::{Value, json};@@ -39,6 +39,8 @@ enum Drag {pub struct PerspSession {pub key: u64,+ /// Document this session belongs to (#5115).+ pub document: DocId,pub layer: LayerId,command: String,bounds: Rect,@@ -56,7 +58,7 @@ const GRID: usize = 40;impl PerspSession {pub fn describe(&self) -> Value {- json!({"layer": self.layer.0, "mode": self.mode, "planes": self.planes})+ json!({"document": self.document.0, "layer": self.layer.0, "mode": self.mode, "planes": self.planes})}fn update_grid(&mut self) {@@ -134,6 +136,7 @@ pub fn begin(app: &mut PhotocraftApp, ctx: &egui::Context, command: &str) -> Reslet texture = ctx.load_texture(format!("persp-{key}"), crate::distort_ui::surface_image(&surface, bounds, 2048), egui::TextureOptions::LINEAR);let mut s = PerspSession {key,+ document: st.doc.id,layer,command: command.to_string(),bounds,diff --git a/crates/ui-egui/src/puppet_ui.rs b/crates/ui-egui/src/puppet_ui.rsindex 3045ca1ca..831c8bad3 100644--- a/crates/ui-egui/src/puppet_ui.rs+++ b/crates/ui-egui/src/puppet_ui.rs@@ -13,7 +13,7 @@ use std::sync::Arc;use egui::{Color32, Stroke, TextureHandle, pos2, vec2};use photocraft_algo::puppet::{ITERATIONS, PuppetDensity, PuppetMesh, PuppetMode, PuppetPin, PuppetSolver, PuppetWarp, build_mesh};-use photocraft_doc::{Document, LayerId};+use photocraft_doc::{DocId, Document, LayerId};use photocraft_geom::Rect;use photocraft_raster::Surface;use serde_json::{Value, json};@@ -23,6 +23,8 @@ use crate::canvas::{ToolEvent, ViewXform};pub struct PuppetSession {pub key: u64,+ /// Document this session belongs to (#5115).+ pub document: DocId,pub layer: LayerId,/// Command to commit with (`edit.puppetWarp` or `layer.smartObjects.puppetWarp`).command: String,@@ -98,6 +100,7 @@ impl PuppetSession {pub fn describe(&self) -> Value {json!({+ "document": self.document.0,"layer": self.layer.0,"pins": self.warp.pins,"mode": self.warp.mode,@@ -202,6 +205,7 @@ pub fn begin(app: &mut PhotocraftApp, ctx: &egui::Context, command: &str) -> Reslet texture = ctx.load_texture(format!("puppet-{key}"), img, egui::TextureOptions::LINEAR);let mut s = PuppetSession {key,+ document: st.doc.id,layer,command: command.to_string(),surface,@@ -760,10 +764,13 @@ mod tests {crate::distort_ui::drop_foreign(&mut app);assert!(app.distort.puppet.is_some());app.session.execute("file.new", json!({"width": 32, "height": 32, "depth": 8})).unwrap();- assert!(crate::distort_ui::display_doc(&app, 1).is_some());+ let active = app.session.active_index().unwrap();+ // The session stays until drop_foreign; the preview must not follow this document (#5115).+ assert!(app.distort.puppet.is_some());+ assert!(crate::distort_ui::display_doc(&app, active).is_none());crate::distort_ui::drop_foreign(&mut app);assert!(app.distort.puppet.is_none());- assert!(crate::distort_ui::display_doc(&app, 1).is_none());+ assert!(crate::distort_ui::display_doc(&app, active).is_none());// Closing the document it was started on drops it too.assert!(app.session.set_active(0));crate::distort_ui::menu(&mut app, &ctx, "edit.puppetWarp", &json!({})).unwrap().unwrap();diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rsindex 3300b9d92..023bbb4d7 100644--- a/crates/ui-egui/src/shortcuts.rs+++ b/crates/ui-egui/src/shortcuts.rs@@ -459,6 +459,7 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context) {// Liquify is a full-window custom dialog with focusable sliders. egui can therefore claim// keyboard input before the distortion-mode handler below runs. Give Liquify's local// shortcuts first refusal (Undo, brush size, tool keys), but never steal keys from text edits.+ crate::distort_ui::cancel_stale(app);if app.distort.liquify.is_some() {// Undo and redo still apply while a numeric field (Size, Pressure, …) has focus.// Other Liquify keys must not steal characters from that field (#4027).diff --git a/crates/ui-egui/src/vp_ui.rs b/crates/ui-egui/src/vp_ui.rsindex 3034c1c5f..61ad0a442 100644--- a/crates/ui-egui/src/vp_ui.rs+++ b/crates/ui-egui/src/vp_ui.rs@@ -12,7 +12,7 @@use egui::{Color32, Pos2, Stroke, TextureHandle, pos2};use photocraft_algo::transform::Homography;use photocraft_algo::vanishing::{PlaneCheck, Scene, VpPlane};-use photocraft_doc::{LayerContent, LayerId};+use photocraft_doc::{DocId, LayerContent, LayerId};use photocraft_engine::vp_cmds::VP;use photocraft_geom::Rect;use serde_json::{Value, json};@@ -46,6 +46,8 @@ struct Clip {}pub struct VpSession {+ /// Document this session belongs to (#5115).+ pub document: DocId,pub layer: LayerId,canvas: Rect,pub planes: Vec<VpPlane>,@@ -80,6 +82,7 @@ impl VpSession {let center = self.center();let planes: Vec<Value> = self.planes.iter().map(|p| json!({"corners": p.corners, "check": p.check(center)})).collect();json!({+ "document": self.document.0,"layer": self.layer.0,"tool": self.tool,"planes": planes,@@ -310,6 +313,7 @@ pub fn begin(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String>})});app.distort.vanishing = Some(VpSession {+ document: st.doc.id,layer,canvas,planes: Vec::new(),