PhotoCraft: An open-source, photo editor written by scratch in pure Rust
History: panel menu, Step Forward/Backward and Clear History (#2966)
David Mann2b738e0c7c8e
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rsindex 3d4b73f4d..41da78160 100644--- a/crates/engine/src/commands.rs+++ b/crates/engine/src/commands.rs@@ -1179,6 +1179,7 @@ fn build() -> Vec<CommandSpec> {v.extend(crate::analysis_cmds::specs());v.extend(crate::notes_cmds::specs());v.extend(crate::history_cmds::specs());+ v.extend(crate::history_menu_cmds::specs());v.extend(crate::proof_sim::specs());v.extend(crate::presets::specs());v.extend(crate::document_preset_cmds::specs());diff --git a/crates/engine/src/edit_menu_cmds.rs b/crates/engine/src/edit_menu_cmds.rsindex 93ecd479c..7af2b192a 100644--- a/crates/engine/src/edit_menu_cmds.rs+++ b/crates/engine/src/edit_menu_cmds.rs@@ -201,7 +201,7 @@ fn fade(s: &mut Session, p: &Value) -> Result<Value> {let opacity = f32_or(p, "opacity", 100.0).clamp(0.0, 100.0) / 100.0;let mode = blend_from_str(str_or(p, "mode", "normal")).ok_or_else(|| bad(cmd, "unknown blend mode"))?;let st = s.active().ok_or(EngineError::NoDocument)?;- let prev = st.history.state(st.history.past_len() - 1).ok_or_else(|| bad(cmd, "no previous state"))?;+ let prev = st.history.past_len().checked_sub(1).and_then(|i| st.history.state(i)).ok_or_else(|| bad(cmd, "no previous state"))?;let before = surface_of(&prev, src.layer, src.mask).cloned().ok_or_else(|| EngineError::Other("the layer did not exist before this step".into()))?;let now = surface_of(&st.doc, src.layer, src.mask).ok_or(EngineError::NoLayer(src.layer))?;if now.format() != before.format() {diff --git a/crates/engine/src/history_cmds.rs b/crates/engine/src/history_cmds.rsindex d9ca98f96..d3b2ab3f7 100644--- a/crates/engine/src/history_cmds.rs+++ b/crates/engine/src/history_cmds.rs@@ -73,7 +73,7 @@ fn new_document(s: &mut Session, p: &Value) -> Result<Value> {}fn can_delete(s: &Session) -> std::result::Result<(), String> {- s.active().filter(|d| d.history.can_undo()).map(|_| ()).ok_or_else(|| "the oldest state can't be deleted".into())+ s.active().filter(|d| d.history.past_len() > 0).map(|_| ()).ok_or_else(|| "the oldest state can't be deleted".into())}fn has_doc(s: &Session) -> std::result::Result<(), String> {diff --git a/crates/engine/src/history_menu_cmds.rs b/crates/engine/src/history_menu_cmds.rsnew file mode 100644index 000000000..7154addbf--- /dev/null+++ b/crates/engine/src/history_menu_cmds.rs@@ -0,0 +1,210 @@+//! The History panel menu (☰, #2966): Step Forward, Step Backward and Clear History. Delete and+//! New Document are [`crate::history_cmds`]; New Snapshot and History Options live elsewhere.+//!+//! Step Forward / Step Backward move one state along the History list, like Edit › Redo / Undo+//! (which step through the list too), but report a step that isn't there as an error. Clear+//! History takes every state but the current one off the list without changing the image; it is+//! undoable: Edit › Undo puts the states back until the next step is recorded.++use serde_json::{Value, json};++use crate::commands::CommandSpec;+use crate::{EngineError, Result, Session};++/// `{states, current, label}`: the list length, the current state's index (0 = oldest) and its+/// name, after a History panel menu command.+fn list(s: &Session) -> Result<Value> {+ let st = s.active().ok_or(EngineError::NoDocument)?;+ let entries = st.history.entries();+ Ok(json!({ "states": entries.len() + st.history.redo_labels().count(), "current": st.history.past_len(), "label": entries.last() }))+}++fn step(s: &mut Session, forward: bool) -> Result<Value> {+ let st = s.active().ok_or(EngineError::NoDocument)?;+ let possible = if forward { st.history.can_redo() } else { st.history.can_undo() };+ if !possible {+ return Err(EngineError::Other(if forward { "no later state to step forward to" } else { "no earlier state to step back to" }.into()));+ }+ let moved = if forward { s.redo() } else { s.undo() };+ if !moved {+ return Err(EngineError::Other("the history can't step right now".into()));+ }+ list(s)+}++/// History panel › Clear History: only the current state stays in the list; the image doesn't+/// change. Edit › Undo brings the states back.+fn clear(s: &mut Session, _p: &Value) -> Result<Value> {+ if s.active_job().is_some() {+ return Err(EngineError::Other("the history can't change while a job runs".into()));+ }+ let st = s.active_mut().ok_or(EngineError::NoDocument)?;+ st.coalesce = None;+ if !st.history.clear_states() {+ return Err(EngineError::Other("the current state is the only state".into()));+ }+ // Edit › Fade blends against the previous state, which is no longer in the list.+ s.edit_state.fade = None;+ list(s)+}++fn can_step_forward(s: &Session) -> std::result::Result<(), String> {+ let st = s.active().ok_or("no document open")?;+ if st.history.can_redo() { Ok(()) } else { Err("no later state".into()) }+}++fn can_step_backward(s: &Session) -> std::result::Result<(), String> {+ let st = s.active().ok_or("no document open")?;+ if st.history.can_undo() { Ok(()) } else { Err("no earlier state".into()) }+}++fn can_clear(s: &Session) -> std::result::Result<(), String> {+ let st = s.active().ok_or("no document open")?;+ if st.history.past_len() > 0 || st.history.can_redo() { Ok(()) } else { Err("the current state is the only state".into()) }+}++pub fn specs() -> Vec<CommandSpec> {+ vec![+ CommandSpec {+ id: "history.stepForward",+ label: "Step Forward",+ menu: &[],+ shortcut: None,+ params: r##"{} → {states,current,label}: makes the next History state current (Err when there is none)"##,+ enabled: can_step_forward,+ run: |s, _| step(s, true),+ journal: true,+ },+ CommandSpec {+ id: "history.stepBackward",+ label: "Step Backward",+ menu: &[],+ shortcut: None,+ params: r##"{} → {states,current,label}: makes the previous History state current (Err when there is none)"##,+ enabled: can_step_backward,+ run: |s, _| step(s, false),+ journal: true,+ },+ CommandSpec {+ id: "history.clear",+ label: "Clear History",+ menu: &[],+ shortcut: None,+ params: r##"{} → {states,current,label}: removes every History state but the current one without changing the image; Edit › Undo restores them"##,+ enabled: can_clear,+ run: clear,+ journal: true,+ },+ ]+}++#[cfg(test)]+mod tests {+ use std::sync::Arc;++ use super::*;++ /// A document with three steps after Open: entries Open, New Layer, Fill, Fill.+ fn session() -> Session {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 20, "height": 10})).unwrap();+ s.execute("layer.new.layer", json!({})).unwrap();+ s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap();+ s.execute("edit.fill", json!({"color": "#00ff00"})).unwrap();+ s+ }++ fn entries(s: &Session) -> Vec<String> {+ s.active().unwrap().history.entries()+ }++ #[test]+ fn step_backward_and_forward_move_one_state() {+ let mut s = session();+ let all = entries(&s);+ let last = s.active().unwrap().doc.clone();+ assert!(!s.is_enabled("history.stepForward"), "no later state yet");+ assert!(s.is_enabled("history.stepBackward"));+ let r = s.execute("history.stepBackward", json!({})).unwrap();+ assert_eq!((r["states"].as_u64(), r["current"].as_u64()), (Some(all.len() as u64), Some(all.len() as u64 - 2)));+ assert_eq!(r["label"], json!(all[all.len() - 2]));+ assert_eq!(entries(&s), all[..all.len() - 1].to_vec());+ assert!(s.is_enabled("history.stepForward"));+ s.execute("history.stepBackward", json!({})).unwrap();+ s.execute("history.stepForward", json!({})).unwrap();+ let r = s.execute("history.stepForward", json!({})).unwrap();+ assert_eq!(r["current"].as_u64(), Some(all.len() as u64 - 1));+ assert_eq!(entries(&s), all);+ assert!(Arc::ptr_eq(&s.active().unwrap().doc, &last), "back at the last state");+ assert!(s.execute("history.stepForward", json!({})).is_err(), "nothing to step forward to");+ }++ #[test]+ fn step_backward_stops_at_the_oldest_state() {+ let mut s = session();+ while s.is_enabled("history.stepBackward") {+ s.execute("history.stepBackward", json!({})).unwrap();+ }+ assert_eq!(entries(&s), ["Open"]);+ assert!(s.execute("history.stepBackward", json!({})).is_err());+ assert_eq!(entries(&s), ["Open"], "a refused step changes nothing");+ }++ #[test]+ fn clear_history_keeps_the_image_and_leaves_one_state() {+ let mut s = session();+ s.execute("history.stepBackward", json!({})).unwrap();+ let all = entries(&s);+ let doc = s.active().unwrap().doc.clone();+ let revision = s.active().unwrap().revision;+ let r = s.execute("history.clear", json!({})).unwrap();+ assert_eq!((r["states"].as_u64(), r["current"].as_u64()), (Some(1), Some(0)));+ let st = s.active().unwrap();+ assert_eq!(st.history.entries(), [all.last().unwrap().clone()], "the current state is the only one");+ assert!(!st.history.can_redo(), "redo states are cleared too");+ assert!(Arc::ptr_eq(&st.doc, &doc) && st.revision == revision, "the image doesn't change");+ assert!(!s.is_enabled("history.clear"), "nothing left to clear");+ assert!(s.execute("history.clear", json!({})).is_err());+ assert!(!s.is_enabled("history.stepForward") && !s.is_enabled("history.deleteState"));+ assert!(!s.is_enabled("edit.fade"));+ }++ #[test]+ fn undo_after_clear_history_brings_the_states_back() {+ let mut s = session();+ s.execute("history.stepBackward", json!({})).unwrap();+ let all = entries(&s);+ let redo: Vec<String> = s.active().unwrap().history.redo_labels().map(str::to_string).collect();+ let doc = s.active().unwrap().doc.clone();+ s.execute("history.clear", json!({})).unwrap();+ assert!(s.is_enabled("edit.undo") && s.is_enabled("history.stepBackward"), "Clear History is undoable");+ s.execute("edit.undo", json!({})).unwrap();+ let st = s.active().unwrap();+ assert_eq!(st.history.entries(), all);+ assert_eq!(st.history.redo_labels().map(str::to_string).collect::<Vec<_>>(), redo);+ assert!(Arc::ptr_eq(&st.doc, &doc), "undoing it doesn't change the image either");+ // A step after Clear History forgets the cleared states.+ s.execute("history.clear", json!({})).unwrap();+ s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap();+ assert_eq!(entries(&s).len(), 2);+ s.execute("edit.undo", json!({})).unwrap();+ assert!(!s.is_enabled("edit.undo"), "the cleared states are gone");+ }++ #[test]+ fn history_menu_commands_refuse_without_a_document_and_ignore_odd_params() {+ let mut s = Session::new();+ for id in ["history.stepForward", "history.stepBackward", "history.clear"] {+ assert!(!s.is_enabled(id), "{id}");+ assert!(s.execute(id, json!({})).is_err(), "{id} without a document");+ }+ s.execute("file.new", json!({"width": 8, "height": 8})).unwrap();+ for id in ["history.stepForward", "history.stepBackward", "history.clear"] {+ assert!(!s.is_enabled(id), "{id}: only the opening state");+ for p in [json!({}), json!(null), json!([1]), json!({"state": -1}), json!("x")] {+ assert!(s.execute(id, p.clone()).is_err(), "{id} {p}");+ }+ assert_eq!(entries(&s), ["Open"]);+ }+ }+}diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex 1fffd0bdc..21916ba24 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -51,6 +51,7 @@ pub mod group_view_cmds;pub mod guide_layout;pub mod hidden_target;pub mod history_cmds;+pub mod history_menu_cmds;pub mod image_cmds;pub mod inspect;pub mod jobs;diff --git a/crates/ops/src/lib.rs b/crates/ops/src/lib.rsindex 0f29cf8e9..b0ca32b90 100644--- a/crates/ops/src/lib.rs+++ b/crates/ops/src/lib.rs@@ -50,8 +50,21 @@ pub struct History {current_label: String,/// The layers targeted when the current document was created (opened or edited).current_layers: LayerTarget,+ /// The states History panel › Clear History took off the list, kept so the next undo puts+ /// them back (Clear History is itself undoable). Any new step drops them.+ cleared: Option<Box<Cleared>>,}+/// The undo and redo states [`History::clear_states`] removed.+#[derive(Clone, Debug)]+struct Cleared {+ undo: VecDeque<HistoryState>,+ redo: Vec<HistoryState>,+}++/// The undo label of the step [`History::clear_states`] adds (Edit › Undo Clear History).+pub const CLEAR_HISTORY_LABEL: &str = "Clear History";+impl Default for History {fn default() -> Self {Self::new(50)@@ -68,6 +81,7 @@ impl History {max_bytes: 0,current_label: "Open".into(),current_layers: LayerTarget::default(),+ cleared: None,}}@@ -80,6 +94,7 @@ impl History {if let Some(tiles) = &mut self.tiles {tiles.add(&before);}+ self.cleared = None;let prev_label = std::mem::replace(&mut self.current_label, label.into());let prev_layers = std::mem::replace(&mut self.current_layers, layers);self.undo.push_back(HistoryState { label: prev_label, doc: before, layers: prev_layers });@@ -94,12 +109,15 @@ impl History {}pub fn can_undo(&self) -> bool {- !self.undo.is_empty()+ !self.undo.is_empty() || self.cleared.is_some()}pub fn can_redo(&self) -> bool {!self.redo.is_empty()}pub fn undo_label(&self) -> Option<&str> {+ if self.cleared.is_some() {+ return Some(CLEAR_HISTORY_LABEL);+ }self.can_undo().then_some(self.current_label.as_str())}pub fn redo_label(&self) -> Option<&str> {@@ -119,6 +137,14 @@ impl History {/// Undo: `current` becomes redoable; returns the document to make current and the layers it/// targeted when it was created.pub fn undo(&mut self, current: Arc<Document>) -> Option<(Arc<Document>, LayerTarget)> {+ // Undo Clear History: the cleared states come back; the document doesn't change.+ if let Some(cleared) = self.cleared.take() {+ let Cleared { undo, redo } = *cleared;+ self.undo = undo;+ self.redo = redo;+ self.tiles = None;+ return Some((current, self.current_layers.clone()));+ }let prev = self.undo.pop_back()?;if let Some(tiles) = &mut self.tiles {tiles.remove(&prev.doc);@@ -168,6 +194,9 @@ impl History {/// last step can no longer be undone and its pixels are released.pub fn purge_last(&mut self) -> bool {self.clear_redo();+ if self.cleared.take().is_some() {+ return true;+ }let Some(state) = self.undo.pop_back() else { return false };if let Some(tiles) = &mut self.tiles {tiles.remove(&state.doc);@@ -189,6 +218,27 @@ impl History {self.undo.clear();self.redo.clear();self.tiles = None;+ self.cleared = None;+ }++ /// History panel › Clear History: take every state but the current one off the list without+ /// changing the document. Unlike [`Self::clear`] (Edit › Purge › Histories) it is undoable:+ /// the next [`Self::undo`] puts the states back, and the next recorded step forgets them.+ /// Returns false (and changes nothing) when the current state is the only one.+ pub fn clear_states(&mut self) -> bool {+ if self.undo.is_empty() && self.redo.is_empty() {+ return false;+ }+ let undo = std::mem::take(&mut self.undo);+ let redo = std::mem::take(&mut self.redo);+ self.cleared = Some(Box::new(Cleared { undo, redo }));+ self.tiles = None;+ true+ }++ /// Whether the last change to the list was Clear History (so undo restores the states).+ pub fn is_cleared(&self) -> bool {+ self.cleared.is_some()}/// Approximate unique pixel bytes held by history (tiles not shared with `current`).@@ -530,4 +580,47 @@ mod tests {assert_eq!(h.trim(¤t), 1, "current alone exceeds the budget; only the mandatory undo survives");assert_counter(&h, ¤t);}++ #[test]+ fn clear_states_keeps_the_document_and_undo_brings_the_list_back() {+ let mut h = History::new(10);+ let mut cur = Arc::new(base());+ edit(&mut h, &mut cur, "A", |d| d.name = "a".into());+ edit(&mut h, &mut cur, "B", |d| d.name = "b".into());+ edit(&mut h, &mut cur, "C", |d| d.name = "c".into());+ let (d, _) = h.undo(cur.clone()).unwrap();+ cur = d;+ let entries = h.entries();+ assert_eq!(entries, ["Open", "A", "B"]);+ assert!(h.clear_states());+ assert_eq!(h.entries(), ["B"], "only the current state is left");+ assert!(!h.can_redo() && h.can_undo() && h.is_cleared());+ assert_eq!(h.undo_label(), Some(CLEAR_HISTORY_LABEL));+ assert!(!h.clear_states(), "nothing left to clear");+ assert!(h.is_cleared(), "and the cleared states are still held");+ let (d, _) = h.undo(cur.clone()).unwrap();+ assert!(Arc::ptr_eq(&d, &cur), "undoing Clear History doesn't change the document");+ assert_eq!(h.entries(), entries);+ assert_eq!(h.redo_labels().collect::<Vec<_>>(), ["C"], "the redo state is back too");+ assert!(!h.is_cleared());+ }++ #[test]+ fn a_new_step_or_purge_forgets_the_cleared_states() {+ let mut h = History::new(10);+ let mut cur = Arc::new(base());+ edit(&mut h, &mut cur, "A", |d| d.name = "a".into());+ assert!(h.clear_states());+ edit(&mut h, &mut cur, "B", |d| d.name = "b".into());+ assert_eq!(h.entries(), ["A", "B"]);+ assert!(!h.is_cleared());+ assert!(h.undo(cur.clone()).is_some());+ assert!(!h.can_undo(), "the cleared states are gone");+ let mut h = History::new(10);+ edit(&mut h, &mut cur, "A", |d| d.name = "a".into());+ assert!(h.clear_states());+ assert!(h.purge_last());+ assert!(!h.can_undo() && !h.is_cleared());+ assert!(!h.clear_states(), "a single state can't be cleared");+ }}diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rsindex 944842de1..2d7511b82 100644--- a/crates/ui-egui/src/dock.rs+++ b/crates/ui-egui/src/dock.rs@@ -554,6 +554,10 @@ pub fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui, shown: &[Group], mut bodcrate::swatches_ui::panel_menu(app, ui);ui.separator();}+ if tabs.get(sel) == Some(&"History") {+ crate::history_menu_ui::panel_menu(app, ui);+ ui.separator();+ }if let Some(label) = tabs.get(sel) {crate::panel_docking::legacy_menu(app, ui, label);}diff --git a/crates/ui-egui/src/history_menu_ui.rs b/crates/ui-egui/src/history_menu_ui.rsnew file mode 100644index 000000000..6a7912e34--- /dev/null+++ b/crates/ui-egui/src/history_menu_ui.rs@@ -0,0 +1,161 @@+//! The History panel's own items at the top of its panel menu (☰, #2966), in Photoshop's order:+//! Step Forward, Step Backward, New Snapshot…, Delete, Clear History, New Document, History+//! Options…, Close. Every item runs an engine command (or the dock's `window.panel.close`); the+//! dock appends its group items (Close Tab Group …) after them.++use serde_json::{Value, json};++use crate::PhotocraftApp;++/// The menu's items: label and command (None = shown greyed; not built yet).+pub const ITEMS: &[(&str, Option<&str>)] = &[+ ("Step Forward", Some("history.stepForward")),+ ("Step Backward", Some("history.stepBackward")),+ ("---", None),+ // Snapshots are not implemented yet.+ ("New Snapshot…", None),+ ("Delete", Some("history.deleteState")),+ ("Clear History", Some("history.clear")),+ ("New Document", Some("history.newDocument")),+ ("---", None),+ // The History Options dialog is not built yet.+ ("History Options…", None),+ ("---", None),+ ("Close", Some("window.panel.close")),+];++fn params(cmd: &str) -> Value {+ if cmd == "window.panel.close" { json!({"panel": "history"}) } else { json!({}) }+}++fn enabled(app: &PhotocraftApp, cmd: &str) -> bool {+ if cmd == "window.panel.close" {+ return !app.session.prefs().workspace_locked;+ }+ // An open Free Transform owns the history (see `panels::history`).+ app.ui.transform.is_none() && app.session.is_enabled(cmd)+}++/// Draw the History items of the panel menu and run the one clicked.+pub fn panel_menu(app: &mut PhotocraftApp, ui: &mut egui::Ui) {+ let mut clicked: Option<&str> = None;+ for &(label, cmd) in ITEMS {+ if label == "---" {+ ui.separator();+ continue;+ }+ let on = cmd.is_some_and(|c| enabled(app, c));+ if ui.add_enabled(on, egui::Button::new(crate::i18n::t(label))).clicked() {+ clicked = cmd;+ }+ }+ let Some(cmd) = clicked else { return };+ ui.close();+ if let Err(e) = app.run(cmd, params(cmd)) {+ app.ui.status = e;+ app.ui.status_error = true;+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use egui_kittest::Harness;+ use egui_kittest::kittest::{NodeT, Queryable};++ fn app() -> PhotocraftApp {+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({"width": 64, "height": 48})).unwrap();+ app.run("layer.new.layer", json!({})).unwrap();+ app.run("edit.fill", json!({"color": "#ff0000"})).unwrap();+ app.run("edit.fill", json!({"color": "#00ff00"})).unwrap();+ app+ }++ fn harness(app: PhotocraftApp) -> Harness<'static, PhotocraftApp> {+ let mut h = Harness::builder().with_size(egui::vec2(260.0, 420.0)).build_ui_state(|ui, app: &mut PhotocraftApp| panel_menu(app, ui), app);+ h.run_steps(2);+ h+ }++ fn states(h: &Harness<'static, PhotocraftApp>) -> (usize, usize) {+ let st = h.state().session.active().unwrap();+ (st.history.entries().len(), st.history.redo_labels().count())+ }++ fn click(h: &mut Harness<'static, PhotocraftApp>, label: &str) {+ h.get_by_label(label).click();+ h.run_steps(2);+ }++ fn is_disabled(h: &Harness<'static, PhotocraftApp>, label: &str) -> bool {+ h.get_by_label(label).accesskit_node().is_disabled()+ }++ #[test]+ fn menu_items_run_their_commands() {+ let mut h = harness(app());+ assert_eq!(states(&h), (4, 0));+ assert!(is_disabled(&h, "Step Forward") && !is_disabled(&h, "Step Backward"));+ assert!(is_disabled(&h, "New Snapshot…") && is_disabled(&h, "History Options…"), "not built yet: greyed");+ click(&mut h, "Step Backward");+ assert_eq!(states(&h), (3, 1));+ assert!(!is_disabled(&h, "Step Forward"));+ click(&mut h, "Step Forward");+ assert_eq!(states(&h), (4, 0));+ click(&mut h, "Delete");+ assert_eq!(states(&h), (3, 0), "Delete removes the current state");+ let doc = h.state().session.active().unwrap().doc.clone();+ click(&mut h, "Clear History");+ assert_eq!(states(&h), (1, 0), "only the current state is left");+ assert!(std::sync::Arc::ptr_eq(&h.state().session.active().unwrap().doc, &doc), "the image is unchanged");+ assert!(is_disabled(&h, "Clear History") && is_disabled(&h, "Delete") && is_disabled(&h, "Step Forward"));+ click(&mut h, "New Document");+ assert_eq!(h.state().session.documents().len(), 2);+ assert!(!h.state().ui.status_error);+ }++ #[test]+ fn close_hides_the_history_panel() {+ let mut app = app();+ app.run("window.panel.activate", json!({"panel": "history"})).unwrap();+ assert!(app.ui.docking.as_ref().unwrap().contains(&"history".to_string()));+ let mut h = harness(app);+ click(&mut h, "Close");+ assert!(!h.state().ui.status_error, "{}", h.state().ui.status);+ let layout = h.state().ui.docking.clone().unwrap();+ assert!(!layout.contains(&"history".to_string()), "the History panel is closed");+ }++ #[test]+ fn items_wait_for_an_open_transform() {+ let mut app = app();+ app.run("select.rect", json!({"x": 4, "y": 4, "width": 20, "height": 20})).unwrap();+ let mut h = harness(app);+ let ctx = h.ctx.clone();+ crate::transform_tool::begin(h.state_mut(), &ctx).unwrap();+ h.run_steps(2);+ for label in ["Step Backward", "Delete", "Clear History", "New Document"] {+ assert!(is_disabled(&h, label), "{label}");+ }+ }++ /// The labels aren't `tl!` literals, so the catalog scan can't see them: every language that+ /// claims complete menus must still translate them.+ #[test]+ fn menu_labels_are_translated() {+ for lang in crate::i18n::Lang::all().filter(|l| l.complete_menus()) {+ for &(label, _) in ITEMS.iter().filter(|(l, _)| *l != "---") {+ assert!(crate::i18n::has(lang, label), "{}: {label}", lang.code());+ }+ }+ }++ #[test]+ fn without_a_document_only_close_is_enabled() {+ let h = harness(PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()));+ for &(label, cmd) in ITEMS.iter().filter(|(l, _)| *l != "---") {+ assert_eq!(is_disabled(&h, label), cmd != Some("window.panel.close"), "{label}");+ }+ }+}diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsvindex 9dd0c2f72..99dfdcc95 100644--- a/crates/ui-egui/src/i18n/cs.tsv+++ b/crates/ui-egui/src/i18n/cs.tsv@@ -2578,3 +2578,10 @@ cameraData Lens ObjektivClick to place · Alt-click or drag off-canvas to remove Kliknutím umístíte · Alt-kliknutím nebo přetažením mimo plátno odebereteNo document open Není otevřen žádný dokument{n} of {max} sample points {n} z {max} bodů měření++# History panel menu (#2966)+ Step Forward Krok vpřed+ Step Backward Krok zpět+ Clear History Vymazat historii+ New Snapshot… Nový snímek…+ History Options… Volby historie…diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsvindex 457e18323..d0622cbc9 100644--- a/crates/ui-egui/src/i18n/de.tsv+++ b/crates/ui-egui/src/i18n/de.tsv@@ -2609,3 +2609,10 @@ cameraData Lens ObjektivClick to place · Alt-click or drag off-canvas to remove Klicken zum Platzieren · Alt-Klick oder Ziehen außerhalb der Arbeitsfläche zum EntfernenNo document open Kein Dokument geöffnet{n} of {max} sample points {n} von {max} Messpunkten++# History panel menu (#2966)+ Step Forward Schritt vorwärts+ Step Backward Schritt zurück+ Clear History Protokoll löschen+ New Snapshot… Neuer Schnappschuss…+ History Options… Protokolloptionen…diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsvindex 5cb839339..158c91496 100644--- a/crates/ui-egui/src/i18n/el.tsv+++ b/crates/ui-egui/src/i18n/el.tsv@@ -3669,3 +3669,7 @@ cameraData Lens Φακός# Color Sampler (added with the i18n coverage repair)Click to place · Alt-click or drag off-canvas to remove Κλικ για τοποθέτηση · Alt-κλικ ή σύρσιμο εκτός καμβά για αφαίρεση{n} of {max} sample points {n} από {max} σημεία δειγματοληψίας++# History panel menu (#2966)+ New Snapshot… Νέο στιγμιότυπο…+ History Options… Επιλογές ιστορικού…diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsvindex d331384bc..325af40af 100644--- a/crates/ui-egui/src/i18n/es.tsv+++ b/crates/ui-egui/src/i18n/es.tsv@@ -2650,3 +2650,10 @@ cameraData Lens ObjetivoClick to place · Alt-click or drag off-canvas to remove Clic para colocar · Alt-clic o arrastrar fuera del lienzo para quitarNo document open Ningún documento abierto{n} of {max} sample points {n} de {max} puntos de muestreo++# History panel menu (#2966)+ Step Forward Paso adelante+ Step Backward Paso atrás+ Clear History Borrar historia+ New Snapshot… Nueva instantánea…+ History Options… Opciones de historia…diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsvindex 208713987..00a687870 100644--- a/crates/ui-egui/src/i18n/fr.tsv+++ b/crates/ui-egui/src/i18n/fr.tsv@@ -2987,3 +2987,7 @@ cameraData Lens ObjectifClick to place · Alt-click or drag off-canvas to remove Cliquez pour placer · Alt-clic ou glisser hors du canevas pour supprimerNo document open Aucun document ouvert{n} of {max} sample points {n} sur {max} points d'échantillonnage++# History panel menu (#2966)+ New Snapshot… Nouvel instantané…+ History Options… Options d'historique…diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsvindex 248865b83..057490fb6 100644--- a/crates/ui-egui/src/i18n/id.tsv+++ b/crates/ui-egui/src/i18n/id.tsv@@ -2974,3 +2974,7 @@ cameraData Lens LensaClick to place · Alt-click or drag off-canvas to remove Klik untuk menempatkan · Alt-klik atau seret ke luar kanvas untuk menghapusNo document open Tidak ada dokumen yang terbuka{n} of {max} sample points {n} dari {max} titik sampel++# History panel menu (#2966)+ New Snapshot… Snapshot Baru…+ History Options… Opsi Riwayat…diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsvindex 398a11f45..77dd75cf1 100644--- a/crates/ui-egui/src/i18n/it.tsv+++ b/crates/ui-egui/src/i18n/it.tsv@@ -2641,3 +2641,10 @@ cameraData Lens ObiettivoClick to place · Alt-click or drag off-canvas to remove Fai clic per posizionare · Alt-clic o trascina fuori dalla tela per rimuovereNo document open Nessun documento aperto{n} of {max} sample points {n} di {max} punti di campionamento++# History panel menu (#2966)+ Step Forward Passo avanti+ Step Backward Passo indietro+ Clear History Cancella cronologia+ New Snapshot… Nuova istantanea…+ History Options… Opzioni cronologia…diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsvindex b1fcbeea4..331b51984 100644--- a/crates/ui-egui/src/i18n/ja.tsv+++ b/crates/ui-egui/src/i18n/ja.tsv@@ -3584,3 +3584,7 @@ cameraData Lens レンズClick to place · Alt-click or drag off-canvas to remove クリックで配置 · Alt キーを押しながらクリック、またはカンバス外へドラッグで削除No document open ドキュメントが開かれていません{n} of {max} sample points {max} 個中 {n} 個のサンプルポイント++# History panel menu (#2966)+ New Snapshot… 新規スナップショット…+ History Options… ヒストリーオプション…diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsvindex 78c75e4e2..e1a612523 100644--- a/crates/ui-egui/src/i18n/ko.tsv+++ b/crates/ui-egui/src/i18n/ko.tsv@@ -3153,3 +3153,10 @@ cameraData Lens 렌즈Click to place · Alt-click or drag off-canvas to remove 클릭하여 배치 · Alt-클릭 또는 캔버스 밖으로 드래그하여 제거No document open 열린 문서 없음{n} of {max} sample points {max}개 중 {n}개의 샘플 지점++# History panel menu (#2966)+ Step Forward 한 단계 앞으로+ Step Backward 한 단계 뒤로+ Clear History 작업 내역 지우기+ New Snapshot… 새 스냅샷…+ History Options… 작업 내역 옵션…diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsvindex f883800f5..0a66a4ba6 100644--- a/crates/ui-egui/src/i18n/nl.tsv+++ b/crates/ui-egui/src/i18n/nl.tsv@@ -3735,3 +3735,7 @@ cameraData Lens Lens# Color Sampler (added with the i18n coverage repair)Click to place · Alt-click or drag off-canvas to remove Klik om te plaatsen · Alt-klik of sleep buiten het canvas om te verwijderen{n} of {max} sample points {n} van {max} steekproefpunten++# History panel menu (#2966)+ New Snapshot… Nieuwe momentopname…+ History Options… Geschiedenisopties…diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsvindex a67617172..cea20696a 100644--- a/crates/ui-egui/src/i18n/pl.tsv+++ b/crates/ui-egui/src/i18n/pl.tsv@@ -3585,3 +3585,7 @@ cameraData Lens ObiektywClick to place · Alt-click or drag off-canvas to remove Kliknij, aby umieścić · Alt-kliknij lub przeciągnij poza obszar roboczy, aby usunąćNo document open Brak otwartego dokumentu{n} of {max} sample points {n} z {max} punktów próbkowania++# History panel menu (#2966)+ New Snapshot… Nowa migawka…+ History Options… Opcje historii…diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsvindex b26081f4a..66acd7ab5 100644--- a/crates/ui-egui/src/i18n/pt-br.tsv+++ b/crates/ui-egui/src/i18n/pt-br.tsv@@ -2994,3 +2994,7 @@ cameraData Lens LenteClick to place · Alt-click or drag off-canvas to remove Clique para posicionar · Alt-clique ou arraste para fora da tela para removerNo document open Nenhum documento aberto{n} of {max} sample points {n} de {max} pontos de amostragem++# History panel menu (#2966)+ New Snapshot… Novo instantâneo…+ History Options… Opções de histórico…diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsvindex 419c25b7f..6e4f988a2 100644--- a/crates/ui-egui/src/i18n/ru.tsv+++ b/crates/ui-egui/src/i18n/ru.tsv@@ -2916,3 +2916,7 @@ cameraData Lens ОбъективClick to place · Alt-click or drag off-canvas to remove Щёлкните, чтобы разместить · Alt-щелчок или перетаскивание за пределы холста для удаленияNo document open Документ не открыт{n} of {max} sample points {n} из {max} точек замера++# History panel menu (#2966)+ New Snapshot… Новый снимок…+ History Options… Параметры истории…diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsvindex 16a41e350..0927c9863 100644--- a/crates/ui-egui/src/i18n/uk.tsv+++ b/crates/ui-egui/src/i18n/uk.tsv@@ -3672,3 +3672,7 @@ cameraData Lens Об'єктивClick to place · Alt-click or drag off-canvas to remove Клацніть, щоб розмістити · Alt-клацання або перетягування за межі полотна для видаленняNo document open Документ не відкрито{n} of {max} sample points {n} з {max} точок вимірювання++# History panel menu (#2966)+ New Snapshot… Новий знімок стану…+ History Options… Параметри історії…diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsvindex 0594427f8..dae6ccaae 100644--- a/crates/ui-egui/src/i18n/zh-hans.tsv+++ b/crates/ui-egui/src/i18n/zh-hans.tsv@@ -2585,3 +2585,10 @@ cameraData Lens 镜头Click to place · Alt-click or drag off-canvas to remove 单击以放置 · Alt 单击或拖到画布外以移除No document open 未打开任何文档{n} of {max} sample points {max} 个取样点中的 {n} 个++# History panel menu (#2966)+ Step Forward 前进一步+ Step Backward 后退一步+ Clear History 清除历史记录+ New Snapshot… 新建快照…+ History Options… 历史记录选项…diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsvindex 80458d294..d8a5e174d 100644--- a/crates/ui-egui/src/i18n/zh-hant.tsv+++ b/crates/ui-egui/src/i18n/zh-hant.tsv@@ -2555,3 +2555,10 @@ cameraData Lens 鏡頭Click to place · Alt-click or drag off-canvas to remove 按一下以放置 · Alt 按一下或拖曳至畫布外以移除No document open 未開啟任何文件{n} of {max} sample points {max} 個取樣點中的 {n} 個++# History panel menu (#2966)+ Step Forward 向前一步+ Step Backward 向後一步+ Clear History 清除步驟記錄+ New Snapshot… 新增快照…+ History Options… 步驟記錄選項…diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex 49a0332bc..18d0a7318 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -85,6 +85,7 @@ pub mod gpu_canvas;pub mod gpu_status;pub mod gradient_ui;pub mod guide_layout_ui;+pub mod history_menu_ui;pub mod hold_keys;pub mod i18n;mod icon_data;diff --git a/crates/ui-egui/src/panel_docking.rs b/crates/ui-egui/src/panel_docking.rsindex 8c219bdd6..d3fba3515 100644--- a/crates/ui-egui/src/panel_docking.rs+++ b/crates/ui-egui/src/panel_docking.rs@@ -842,6 +842,10 @@ fn panel_menu(app: &mut PhotocraftApp, ui: &mut egui::Ui, panel: &str) {crate::swatches_ui::panel_menu(app, ui);ui.separator();}+ "history" => {+ crate::history_menu_ui::panel_menu(app, ui);+ ui.separator();+ }_ => {}}}