PhotoCraft: An open-source, photo editor written by scratch in pure Rust
fix(type): commit a type edit when another layer or document becomes active (#6483)
Khawar Zamman Wani3c91200d88fe
diff --git a/crates/ui-egui/src/hold_keys/tests.rs b/crates/ui-egui/src/hold_keys/tests.rsindex cfe89d464..8c1f753e7 100644--- a/crates/ui-egui/src/hold_keys/tests.rs+++ b/crates/ui-egui/src/hold_keys/tests.rs@@ -186,6 +186,7 @@ fn space_while_editing_type_is_not_the_hand_tool() {let id = h.state_mut().run("type.create", json!({"text": "ئا", "size": 20, "x": 100, "y": 100})).unwrap()["layer"].as_u64().unwrap();h.state_mut().ui.text_edit = Some(crate::state::TextEdit {layer: id,+ document: None,caret: 2,anchor: 2,session: "t".into(),diff --git a/crates/ui-egui/src/input_tests.rs b/crates/ui-egui/src/input_tests.rsindex 3754e821f..15bf88dc5 100644--- a/crates/ui-egui/src/input_tests.rs+++ b/crates/ui-egui/src/input_tests.rs@@ -474,6 +474,7 @@ fn type_tool_alt_arrows_kern_the_pair() {let metric = photocraft_text::shared().lock().unwrap().pair_kerning(&text(&h), 72.0, 0).unwrap().round();h.state_mut().ui.text_edit = Some(crate::state::TextEdit {layer: id,+ document: None,caret: 1,anchor: 1,session: "kern-test".into(),@@ -524,6 +525,7 @@ fn type_tool_alt_arrows_kern_the_pair() {fn edit_type(h: &mut Harness<'static, PhotocraftApp>, layer: u64, anchor: usize, caret: usize) {h.state_mut().ui.text_edit = Some(crate::state::TextEdit {layer,+ document: None,caret,anchor,session: "format-keys".into(),@@ -742,6 +744,7 @@ fn type_tool_format_keys_survive_hostile_state() {for ed in [None, Some(1)] {app.ui.text_edit = ed.map(|layer| crate::state::TextEdit {layer,+ document: None,caret: 4,anchor: 0,session: "x".into(),diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex bde51ff27..16722fe47 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -1836,6 +1836,8 @@ impl eframe::App for PhotocraftApp {if self.ui.text_edit.as_ref().is_some_and(|ed| !self.ui.tool.is_type() || ed.mask != self.ui.tool.is_type_mask()) {type_tool::commit(self);}+ // So does selecting another layer or document by any route (#6483).+ type_tool::end_if_left(self);if self.ui.pen.as_ref().is_some_and(|p| !p.drawn_with(self.ui.tool)) {vector_ui::pen_commit(self, false);}diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rsindex 479355415..346842618 100644--- a/crates/ui-egui/src/panels.rs+++ b/crates/ui-egui/src/panels.rs@@ -4383,6 +4383,7 @@ mod color_tests {let anchor = if selected { 6 } else { 11 };app.ui.text_edit = Some(crate::state::TextEdit {layer: id.0,+ document: None,caret: 11,anchor,session: "s".into(),@@ -5076,6 +5077,7 @@ mod swatch_type_tests {app.ui.tool = Tool::Type;app.ui.text_edit = Some(crate::state::TextEdit {layer: id,+ document: None,caret: 0,anchor: 5,session: "s".into(),diff --git a/crates/ui-egui/src/spring_tools/tests.rs b/crates/ui-egui/src/spring_tools/tests.rsindex eef327c09..e3d13a043 100644--- a/crates/ui-egui/src/spring_tools/tests.rs+++ b/crates/ui-egui/src/spring_tools/tests.rs@@ -210,6 +210,7 @@ fn letters_type_while_editing_text() {let id = h.state_mut().run("type.create", json!({"x": 20, "y": 80, "text": "a", "size": 40})).unwrap()["layer"].as_u64().unwrap();h.state_mut().ui.text_edit = Some(crate::state::TextEdit {layer: id,+ document: None,caret: 1,anchor: 1,session: "spring-test".into(),diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rsindex 5cbda434e..a0db32fa4 100644--- a/crates/ui-egui/src/state.rs+++ b/crates/ui-egui/src/state.rs@@ -971,6 +971,10 @@ pub enum MadeLayer {#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]pub struct TextEdit {pub layer: u64,+ /// Id of the document being edited (layer ids can repeat across documents, e.g. one .pcraft+ /// opened twice). `None`: the active document.+ #[serde(default)]+ pub document: Option<u64>,pub caret: usize,pub anchor: usize,/// History coalescing key: the whole editing session is one "Edit Type Layer" step.diff --git a/crates/ui-egui/src/swatches_ui.rs b/crates/ui-egui/src/swatches_ui.rsindex a18ddee64..e3a4b4636 100644--- a/crates/ui-egui/src/swatches_ui.rs+++ b/crates/ui-egui/src/swatches_ui.rs@@ -327,6 +327,7 @@ mod tests {app.ui.tool = Tool::Type;app.ui.text_edit = Some(crate::state::TextEdit {layer: id,+ document: None,caret: 0,anchor: 5,session: "s".into(),diff --git a/crates/ui-egui/src/type_commit_tests.rs b/crates/ui-egui/src/type_commit_tests.rsnew file mode 100644index 000000000..551706ec0--- /dev/null+++ b/crates/ui-egui/src/type_commit_tests.rs@@ -0,0 +1,157 @@+//! A type edit ends when its layer stops being the one worked on (#6483): another layer or+//! another document became active. Photoshop commits the text then; left open, the session kept+//! taking single-key shortcuts as typing and could type into a layer of the wrong document.++use egui_kittest::Harness;+use photocraft_doc::{LayerContent, LayerId};+use serde_json::json;++use crate::PhotocraftApp;++fn new_app() -> PhotocraftApp {+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({"width": 400, "height": 200})).unwrap();+ app.sync_views();+ app.ui.tool = crate::state::Tool::Type;+ app+}++fn text_of(app: &PhotocraftApp, doc: usize, id: LayerId) -> Option<String> {+ match &app.session.documents().get(doc)?.doc.layer(id)?.content {+ LayerContent::Text(t) => Some(t.text.clone()),+ _ => None,+ }+}++/// Start a new type layer with a click and type `s` into it, as the canvas does.+fn type_new(app: &mut PhotocraftApp, s: &str) -> LayerId {+ super::pointer_up(app, [50.0, 100.0], [50.0, 100.0]);+ super::insert(app, s);+ LayerId(app.ui.text_edit.as_ref().unwrap().layer)+}++/// Feed one frame of key handling with `events`.+fn keys(app: PhotocraftApp, events: Vec<egui::Event>) -> PhotocraftApp {+ let mut h = Harness::builder().build_ui_state(+ |ui, app: &mut PhotocraftApp| {+ super::handle_keys(app, ui.ctx());+ },+ app,+ );+ h.run_steps(1);+ for e in events {+ h.event(e);+ }+ h.run_steps(1);+ h.into_state()+}++#[test]+fn typing_after_a_document_switch_never_edits_the_other_document() {+ let mut app = new_app();+ let id = app.run("type.create", json!({"text": "Bee", "size": 24, "x": 20, "y": 80})).unwrap()["layer"].as_u64().map(LayerId).unwrap();+ // A second document with the same layer ids, as when one .pcraft is opened twice (its saved+ // ids are kept; only the document id is made unique).+ let copy = (*app.session.active().unwrap().doc).clone();+ app.session.add_document(copy, None);+ app.sync_views();+ // Edit the copy's type layer (index 1), then switch to the first document's tab and type.+ crate::type_tool::edit_active(&mut app).unwrap();+ super::insert(&mut app, "Ay");+ assert!(app.session.set_active(0));+ super::end_if_left(&mut app);+ let app = keys(app, vec![egui::Event::Text("Z".into())]);+ assert_eq!(text_of(&app, 0, id).as_deref(), Some("Bee"), "the other document is untouched");+ assert_eq!(text_of(&app, 1, id).as_deref(), Some("Ay"), "the edited copy keeps its text");+ assert!(app.ui.text_edit.is_none(), "the copy's edit was committed");+ assert_eq!(app.session.active_index(), Some(0), "and the document switched to stays active");+}++#[test]+fn selecting_another_layer_commits_the_edit() {+ let mut app = new_app();+ let other = LayerId(app.run("layer.new.layer", json!({"name": "Other pixels"})).unwrap()["layer"].as_u64().unwrap());+ let text = type_new(&mut app, "Hello");+ super::end_if_left(&mut app);+ assert!(app.ui.text_edit.is_some(), "a session's own layer is active: it goes on");+ // The Layers panel menus, the canvas layer picker, ⌥[ / ⌥] and automation all select this way.+ app.run("layer.select", json!({"layer": other.0})).unwrap();+ super::end_if_left(&mut app);+ assert!(app.ui.text_edit.is_none());+ let st = app.session.active().unwrap();+ assert_eq!(st.active_layer, Some(other), "the selection stands");+ assert_eq!(st.doc.layer(text).unwrap().name, "Hello", "committed: the new layer is named after its text");+ assert_eq!(text_of(&app, 0, text).as_deref(), Some("Hello"));+}++#[test]+fn an_empty_new_layer_goes_when_another_layer_is_selected() {+ let mut app = new_app();+ let other = LayerId(app.run("layer.new.layer", json!({"name": "Other pixels"})).unwrap()["layer"].as_u64().unwrap());+ let text = type_new(&mut app, "");+ app.run("layer.select", json!({"layer": other.0})).unwrap();+ super::end_if_left(&mut app);+ assert!(app.ui.text_edit.is_none());+ assert!(app.session.active().unwrap().doc.layer(text).is_none(), "an empty new type layer is deleted on commit");+}++#[test]+fn deselecting_all_layers_commits_the_edit() {+ let mut app = new_app();+ type_new(&mut app, "Hello");+ app.run("select.deselectLayers", json!({})).unwrap();+ super::end_if_left(&mut app);+ assert!(app.ui.text_edit.is_none());+}++#[test]+fn a_type_mask_session_goes_on_while_its_layer_is_active() {+ let mut app = new_app();+ app.ui.tool = crate::state::Tool::HorizontalTypeMask;+ type_new(&mut app, "Mask");+ super::end_if_left(&mut app);+ let ed = app.ui.text_edit.as_ref().expect("the Type Mask session is still open");+ assert!(ed.mask);+}++#[test]+fn closing_the_edited_document_drops_the_edit_without_touching_another() {+ let mut app = new_app();+ let id = app.run("type.create", json!({"text": "Bee", "size": 24, "x": 20, "y": 80})).unwrap()["layer"].as_u64().map(LayerId).unwrap();+ let copy = (*app.session.active().unwrap().doc).clone();+ app.session.add_document(copy, None);+ app.sync_views();+ crate::type_tool::edit_active(&mut app).unwrap();+ super::insert(&mut app, "");+ assert!(app.session.close(1).is_some());+ let before = app.session.active().unwrap().revision;+ super::end_if_left(&mut app);+ assert!(app.ui.text_edit.is_none());+ assert_eq!(app.session.active().unwrap().revision, before, "nothing ran in the remaining document");+ assert_eq!(text_of(&app, 0, id).as_deref(), Some("Bee"), "its same-id type layer keeps its text");+}++/// The issue's second symptom: after a layer is selected, single-key tool shortcuts work again+/// instead of typing into the type layer.+#[test]+fn tool_shortcuts_work_after_another_layer_is_selected() {+ let mut s = photocraft_engine::Session::new();+ s.execute("file.new", json!({"width": 400, "height": 300})).unwrap();+ let mut h = Harness::builder().with_size(egui::vec2(1440.0, 900.0)).with_max_steps(64).build_eframe(move |cc| {+ PhotocraftApp::setup_context(&cc.egui_ctx, Default::default());+ PhotocraftApp::new(s, crate::Services::default())+ });+ h.run_steps(8);+ let app = h.state_mut();+ app.ui.tool = crate::state::Tool::Type;+ let other = app.run("layer.new.layer", json!({"name": "Other pixels"})).unwrap()["layer"].as_u64().unwrap();+ let text = type_new(app, "Hello");+ app.run("layer.select", json!({"layer": other})).unwrap();+ h.run_steps(2);+ assert!(h.state().ui.text_edit.is_none(), "the frame commits the edit");+ h.key_press(egui::Key::V);+ h.event(egui::Event::Text("v".into()));+ h.run_steps(2);+ assert_eq!(h.state().ui.tool, crate::state::Tool::Move, "V picks the Move tool");+ assert_eq!(text_of(h.state(), 0, text).as_deref(), Some("Hello"), "and types nothing");+}diff --git a/crates/ui-egui/src/type_font_picker_tests.rs b/crates/ui-egui/src/type_font_picker_tests.rsindex 176e683a9..e542db208 100644--- a/crates/ui-egui/src/type_font_picker_tests.rs+++ b/crates/ui-egui/src/type_font_picker_tests.rs@@ -361,6 +361,7 @@ fn hovering_a_font_previews_only_the_selected_characters() {app.run("type.setStyle", json!({"layer": layer.0, "range": [0, 2], "font": "JetBrains Mono"})).unwrap();app.ui.text_edit = Some(crate::state::TextEdit {layer: layer.0,+ document: None,caret: 5,anchor: 3,session: "font-preview-test".into(),diff --git a/crates/ui-egui/src/type_tool.rs b/crates/ui-egui/src/type_tool.rsindex d73bb2e2c..1bed24c2c 100644--- a/crates/ui-egui/src/type_tool.rs+++ b/crates/ui-egui/src/type_tool.rs@@ -114,8 +114,18 @@ pub fn edit_active(app: &mut PhotocraftApp) -> Result<(), String> {commit(app);let key = session_key(app);begin_edit(app, id, &key)?;- app.ui.text_edit =- Some(TextEdit { layer: id.0, caret: n, anchor: 0, session: key, created: false, mask: false, dragging: false, resize: None, preedit: None });+ app.ui.text_edit = Some(TextEdit {+ layer: id.0,+ document: active_doc_id(app),+ caret: n,+ anchor: 0,+ session: key,+ created: false,+ mask: false,+ dragging: false,+ resize: None,+ preedit: None,+ });} else if let Some(ed) = app.ui.text_edit.as_mut() {ed.anchor = 0;ed.caret = n;@@ -143,8 +153,18 @@ pub fn edit_at(app: &mut PhotocraftApp, x: f64, y: f64) -> bool {return false;}let off = hit_offset(app, id, x, y);- app.ui.text_edit =- Some(TextEdit { layer: id.0, caret: off, anchor: off, session: key, created: false, mask: false, dragging: false, resize: None, preedit: None });+ app.ui.text_edit = Some(TextEdit {+ layer: id.0,+ document: active_doc_id(app),+ caret: off,+ anchor: off,+ session: key,+ created: false,+ mask: false,+ dragging: false,+ resize: None,+ preedit: None,+ });let vertical = app.session.active().and_then(|st| text_layer(&st.doc, id)).is_some_and(|t| t.orientation == photocraft_doc::text::Orientation::Vertical);if !previous_tool.is_type() {app.ui.text_edit_return_tool = Some(previous_tool);@@ -274,8 +294,18 @@ pub fn pointer_down(app: &mut PhotocraftApp, x: f64, y: f64, mods: egui::Modifiereturn true;}let off = hit_offset(app, id, x, y);- app.ui.text_edit =- Some(TextEdit { layer: id.0, caret: off, anchor: off, session: key, created: false, mask: false, dragging: true, resize: None, preedit: None });+ app.ui.text_edit = Some(TextEdit {+ layer: id.0,+ document: active_doc_id(app),+ caret: off,+ anchor: off,+ session: key,+ created: false,+ mask: false,+ dragging: true,+ resize: None,+ preedit: None,+ });app.ui.text_edit_return_tool = None;return true;}@@ -340,7 +370,18 @@ pub fn pointer_up(app: &mut PhotocraftApp, start: [f64; 2], end: [f64; 2]) {}// Like Photoshop: the placeholder is selected, so typing replaces it.let n = text.chars().count();- app.ui.text_edit = Some(TextEdit { layer: id, caret: n, anchor: 0, session: key, created: true, mask, dragging: false, resize: None, preedit: None });+ app.ui.text_edit = Some(TextEdit {+ layer: id,+ document: active_doc_id(app),+ caret: n,+ anchor: 0,+ session: key,+ created: true,+ mask,+ dragging: false,+ resize: None,+ preedit: None,+ });app.ui.text_edit_return_tool = None;}}@@ -349,6 +390,10 @@ fn session_key(app: &mut PhotocraftApp) -> String {format!("type-{}", app.ui.alloc_id())}+fn active_doc_id(app: &PhotocraftApp) -> Option<u64> {+ app.session.active().map(|st| st.doc.id.0)+}+fn current_text(app: &PhotocraftApp, id: LayerId) -> Option<String> {Some(text_layer(&app.session.active()?.doc, id)?.text.clone())}@@ -768,6 +813,7 @@ fn line_edge(app: &mut PhotocraftApp, id: LayerId, caret: usize, end: bool) -> u/// Keyboard input while editing. Returns true when a type edit session is active (single-key/// tool shortcuts must then be skipped). Handled events are removed from the frame's input.pub fn handle_keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool {+ end_if_left(app);crate::type_transform::cancel_stale(app);if !ctx.input(|i| i.focused) {crate::type_transform::cancel_drag(app);@@ -963,6 +1009,40 @@ pub fn commit(app: &mut PhotocraftApp) {/// selection with ⇧, subtracts them with ⌥ and intersects with ⇧⌥ (Photoshop); with none it/// replaces the selection.pub fn commit_with(app: &mut PhotocraftApp, mods: egui::Modifiers) {+ let current = app.session.active_index();+ let Some(home) = app.ui.text_edit.as_ref().map(|ed| edit_home(app, ed)) else {+ return commit_here(app, mods);+ };+ match home {+ Some(home) if Some(home) != current => {+ // An edit left in a background document commits there, in its own history (#6483).+ app.session.set_active(home);+ commit_here(app, mods);+ if let Some(i) = current {+ app.session.set_active(i);+ }+ }+ Some(_) => commit_here(app, mods),+ // Its document closed: there is nothing to commit into, and the layer id may name a+ // layer of another document.+ None => {+ crate::type_transform::reset(app);+ app.ui.text_edit = None;+ app.ui.text_edit_return_tool = None;+ }+ }+}++/// Index of the document an edit belongs to; `None` once it is closed.+fn edit_home(app: &PhotocraftApp, ed: &TextEdit) -> Option<usize> {+ match ed.document {+ Some(d) => app.session.documents().iter().position(|st| st.doc.id.0 == d),+ None => app.session.active_index(),+ }+}++/// [`commit_with`] in the active document, which is the edit's own.+fn commit_here(app: &mut PhotocraftApp, mods: egui::Modifiers) {if app.ui.tool.is_type() {crate::type_transform::finish(app);}@@ -997,9 +1077,25 @@ pub fn commit_with(app: &mut PhotocraftApp, mods: egui::Modifiers) {}}+/// Commit the edit once its layer is no longer the one worked on (#6483): another layer became+/// active (a Layers panel menu, the canvas layer picker, automation) or another document did (a+/// tab, File ▸ New/Open). Photoshop commits then; left open, the session took single-key+/// shortcuts as typing and typed into whichever document was active.+pub fn end_if_left(app: &mut PhotocraftApp) {+ let Some(ed) = app.ui.text_edit.as_ref() else { return };+ let here = edit_home(app, ed).is_some_and(|h| Some(h) == app.session.active_index());+ if !here || app.session.active().is_some_and(|st| st.active_layer != Some(LayerId(ed.layer))) {+ commit(app);+ }+}+/// Selection highlight, caret and text frame over the canvas.pub fn draw_overlay(app: &mut PhotocraftApp, painter: &egui::Painter, xf: &ViewXform) {let Some(ed) = app.ui.text_edit.clone() else { return };+ // Until it commits, an edit in a document no longer active draws nothing over this one.+ if edit_home(app, &ed) != app.session.active_index() {+ return;+ }let id = LayerId(ed.layer);let Some((l, aff, text)) = layout(app, id) else { return };if ed.mask {@@ -2738,3 +2834,7 @@ mod tests {assert_eq!(app.ui.tool, crate::state::Tool::Type, "Layers-thumbnail edit stays on Type tool");}}++#[cfg(test)]+#[path = "type_commit_tests.rs"]+mod commit_tests;diff --git a/crates/ui-egui/src/type_tool_tests.rs b/crates/ui-egui/src/type_tool_tests.rsindex 7a23c9ccc..90904b8a7 100644--- a/crates/ui-egui/src/type_tool_tests.rs+++ b/crates/ui-egui/src/type_tool_tests.rs@@ -20,6 +20,7 @@ fn focused_font_search_does_not_type_into_the_canvas_layer() {let id = app.run("type.create", json!({"text": "Sample", "size": 24})).unwrap()["layer"].as_u64().unwrap();app.ui.text_edit = Some(crate::state::TextEdit {layer: id,+ document: None,caret: 6,anchor: 6,session: "s".into(),@@ -357,6 +358,7 @@ fn size_applies_at_layer_and_selection_scope() {// Selection scope: "world" only.app.ui.text_edit = Some(crate::state::TextEdit {layer: id.0,+ document: None,caret: 11,anchor: 6,session: "s".into(),@@ -504,6 +506,7 @@ fn foreground_colour_recolours_only_selected_type() {assert_eq!(rgb_at(&app, id, 0), [0, 0, 0, 255], "not editing: unchanged");let edit = |caret, anchor| crate::state::TextEdit {layer: id.0,+ document: None,caret,anchor,session: "s".into(),@@ -593,6 +596,7 @@ fn text_color_dialog_edits_only_the_selected_range_and_cancel_is_inert() {app.run("layer.select", json!({"layer": id.0, "mode": "add"})).unwrap();app.ui.text_edit = Some(crate::state::TextEdit {layer: id.0,+ document: None,caret: 11,anchor: 6,session: "text-color-dialog-test".into(),@@ -650,6 +654,7 @@ fn empty_ime_events_never_delete_the_selection() {let id = LayerId(app.run("type.create", json!({"text": "Hello", "size": 40, "x": 300, "y": 420})).unwrap()["layer"].as_u64().unwrap());app.ui.text_edit = Some(crate::state::TextEdit {layer: id.0,+ document: None,caret: 5,anchor: 0,session: "s".into(),@@ -1427,6 +1432,7 @@ mod multi_layer_formatting {fn editing(app: &mut PhotocraftApp, id: LayerId) {app.ui.text_edit = Some(crate::state::TextEdit {layer: id.0,+ document: None,caret: 3,anchor: 1,session: "batch-type-edit".into(),@@ -2014,6 +2020,7 @@ fn multi_click_without_a_session_does_nothing() {assert!(app.ui.text_edit.is_none() && app.type_clicks.is_none());app.ui.text_edit = Some(crate::state::TextEdit {layer: 999_999,+ document: None,caret: 5,anchor: 5,session: "stale".into(),