diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index a47bde9fff..fbe4015212 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -647,7 +647,10 @@ fn build() -> Vec { let before = s.active().ok_or(EngineError::NoDocument)?.doc.clone(); // Clipping and channel changes reach the layers around it: recomposite everything. let local = p.get("clipped").is_none() && p.get("channels").is_none(); - s.edit(label, |doc, _| { + // The eye: a history state only with History Options › Make Layer Visibility + // Changes Undoable. + let record = !only_visibility || s.visibility_undoable(); + s.edit_with(label, record, |doc, _| { let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; if let Some(v) = p.get("name").and_then(Value::as_str) { l.name = v.to_string(); @@ -1238,6 +1241,7 @@ fn build() -> Vec { v.extend(crate::analysis_cmds::specs()); v.extend(crate::notes_cmds::specs()); v.extend(crate::history_cmds::specs()); + v.extend(crate::history_options_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/extra_cmds.rs b/crates/engine/src/extra_cmds.rs index 1399784b1d..7a0c2f0b93 100644 --- a/crates/engine/src/extra_cmds.rs +++ b/crates/engine/src/extra_cmds.rs @@ -559,7 +559,7 @@ fn set_visible(s: &mut Session, p: &Value, visible: bool) -> Result { return crate::layer_multi_cmds::set_visible_selected(s, visible); } let id = layer_param(s, p)?; - s.edit(if visible { "Show Layer" } else { "Hide Layer" }, |doc, _| { + s.edit_visibility(if visible { "Show Layer" } else { "Hide Layer" }, |doc, _| { doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?.visible = visible; Ok(()) })?; @@ -625,7 +625,7 @@ fn show_only(s: &mut Session, p: &Value) -> Result { let rows = walk.iter().map(|(p, _, l)| (p.clone(), before.as_ref().is_none_or(|b| b.get(&l.id).copied().unwrap_or(l.visible)))).collect(); ("Show Layers", rows, None) }; - s.edit(label, |doc, _| { + s.edit_visibility(label, |doc, _| { for (p, visible) in &rows { if let Some(l) = doc.layer_at_mut(p) { l.visible = *visible; diff --git a/crates/engine/src/history_cmds.rs b/crates/engine/src/history_cmds.rs index 9777031d21..478e696f7f 100644 --- a/crates/engine/src/history_cmds.rs +++ b/crates/engine/src/history_cmds.rs @@ -50,7 +50,7 @@ fn state_index(s: &Session, cmd: &str, p: &Value) -> Result<(usize, usize)> { } /// History panel › Delete: drop the state and every state after it, as Photoshop does in linear -/// history. The document returns to the state before it, and the deleted steps can't be redone. +/// history (in non-linear history only that state, `history_options_cmds::delete_state`). The document returns to the state before it, and the deleted steps can't be redone. /// The oldest state (the document as opened) can't be deleted. fn delete_state(s: &mut Session, p: &Value) -> Result { const CMD: &str = "history.deleteState"; @@ -58,6 +58,12 @@ fn delete_state(s: &mut Session, p: &Value) -> Result { if i == 0 { return Err(bad(CMD, "the oldest state can't be deleted")); } + // History Options › Allow Non-Linear History: only that state goes. + if s.active().is_some_and(|st| st.history.non_linear) { + crate::history_options_cmds::delete_state(s, i, current)?; + let entries = s.active().ok_or(EngineError::NoDocument)?.history.entries(); + return Ok(json!({ "states": entries.len(), "current": entries.last() })); + } // Step back to the state before `i`; the steps from `i` on are then redo states. for _ in i..=current { if !s.undo() { diff --git a/crates/engine/src/history_options_cmds.rs b/crates/engine/src/history_options_cmds.rs new file mode 100644 index 0000000000..88cec69f6e --- /dev/null +++ b/crates/engine/src/history_options_cmds.rs @@ -0,0 +1,251 @@ +//! History panel › History Options… (#2966): Allow Non-Linear History and Make Layer Visibility +//! Changes Undoable. The values are preferences (`historyOptions.*`, also `prefs.set`), applied +//! by [`Session::apply_prefs`] and [`Session::edit_visibility`]. Without params the command +//! reports them; the GUI opens its dialog instead and runs it with the dialog's values on OK. +//! +//! Photoshop's three snapshot options (Automatically Create First Snapshot, Automatically +//! Create New Snapshot When Saving, Show New Snapshot Dialog by Default) are not here: snapshots +//! are not implemented, and a checkbox that does nothing is worse than a missing one. + +use serde_json::{Map, Value}; + +use crate::commands::CommandSpec; +use crate::{EngineError, Result, Session}; + +const CMD: &str = "history.options"; + +/// The option keys, as in `prefs.get historyOptions` and the command's params. +pub const OPTIONS: [&str; 2] = ["allowNonLinearHistory", "makeLayerVisibilityChangesUndoable"]; + +fn bad(msg: impl Into) -> EngineError { + EngineError::BadParams { cmd: CMD.into(), msg: msg.into() } +} + +/// The current History Options as `{allowNonLinearHistory, makeLayerVisibilityChangesUndoable}`. +pub fn current(s: &Session) -> Value { + let o = &s.prefs().history_options; + serde_json::json!({ + "allowNonLinearHistory": o.allow_non_linear_history, + "makeLayerVisibilityChangesUndoable": o.make_layer_visibility_changes_undoable, + }) +} + +fn options(s: &mut Session, p: &Value) -> Result { + let given: Map = match p { + Value::Null => Map::new(), + Value::Object(m) => m.clone(), + _ => return Err(bad("params must be an object")), + }; + // Validate everything before changing anything. + let mut set = Vec::new(); + for (k, v) in &given { + if !OPTIONS.contains(&k.as_str()) { + return Err(bad(format!("unknown option `{k}` (expected {})", OPTIONS.join(", ")))); + } + let b = v.as_bool().ok_or_else(|| bad(format!("`{k}` must be true or false")))?; + set.push((k.clone(), b)); + } + if !set.is_empty() { + s.edit_prefs(|prefs| { + for (k, b) in &set { + match k.as_str() { + "allowNonLinearHistory" => prefs.history_options.allow_non_linear_history = *b, + _ => prefs.history_options.make_layer_visibility_changes_undoable = *b, + } + } + }); + } + Ok(current(s)) +} + +/// History panel › Delete in non-linear history: delete state `i` (indexed like +/// [`photocraft_ops::History::entries`], `current` = the current state's index) and nothing +/// else. Deleting the current state steps back to the one before it; the later states stay. +pub(crate) fn delete_state(s: &mut Session, i: usize, current: usize) -> Result<()> { + if i == 0 { + return Err(EngineError::BadParams { cmd: "history.deleteState".into(), msg: "the oldest state can't be deleted".into() }); + } + // A background job is computing from the current state: it must not move under it. + if s.active_job().is_some() { + return Err(EngineError::Other("the history can't step back right now".into())); + } + let st = s.active_mut().ok_or(EngineError::NoDocument)?; + st.coalesce = None; + if i < current { + if !st.history.remove(i) { + return Err(EngineError::Other(format!("state {i} is not held"))); + } + // The document is unchanged, but the History panel's rows are not. + st.revision += 1; + st.last_damage = Some(photocraft_geom::Rect::EMPTY); + return Ok(()); + } + let (mut d, layers) = st.history.drop_current().ok_or_else(|| EngineError::Other("the history can't step back right now".into()))?; + // As Undo does: Save As changes file identity outside history. + if d.name != st.doc.name { + std::sync::Arc::make_mut(&mut d).name.clone_from(&st.doc.name); + } + let damage = crate::layer_multi_cmds::step_damage(&d, &st.doc); + st.doc = d; + crate::restore_target(st, layers); + st.revision += 1; + st.last_damage = damage; + Ok(()) +} + +fn always(_: &Session) -> std::result::Result<(), String> { + Ok(()) +} + +pub fn specs() -> Vec { + vec![CommandSpec { + id: CMD, + label: "History Options…", + menu: &[], + shortcut: None, + params: r##"{"allowNonLinearHistory":bool?,"makeLayerVisibilityChangesUndoable":bool?} → both values (no params: report them). Allow Non-Linear History: an edit after stepping back keeps the later states and is appended at the end; deleting a state deletes only it (default off). Make Layer Visibility Changes Undoable: showing or hiding a layer is a history state (default on). Also `prefs.set historyOptions.*`"##, + enabled: always, + run: options, + journal: false, + }] +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn entries(s: &Session) -> Vec { + s.active().unwrap().history.entries() + } + + /// A document with a layer above the background: entries Open, New Layer. + fn doc() -> (Session, u64) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + let id = s.active().unwrap().active_layer.unwrap().0; + (s, id) + } + + #[test] + fn defaults_match_photoshop_and_round_trip_through_prefs() { + let mut s = Session::new(); + assert_eq!(s.execute(CMD, json!({})).unwrap(), json!({"allowNonLinearHistory": false, "makeLayerVisibilityChangesUndoable": true})); + assert_eq!(s.execute("prefs.get", json!({"path": "historyOptions"})).unwrap(), current(&s)); + let r = s.execute(CMD, json!({"allowNonLinearHistory": true, "makeLayerVisibilityChangesUndoable": false})).unwrap(); + assert_eq!(r, json!({"allowNonLinearHistory": true, "makeLayerVisibilityChangesUndoable": false})); + assert_eq!(s.execute("prefs.get", json!({"path": "historyOptions.allowNonLinearHistory"})).unwrap(), json!(true)); + // Saved and restored with the other preferences. + let saved = s.prefs_to_json(); + let mut t = Session::new(); + t.load_prefs_json(&saved).unwrap(); + assert_eq!(current(&t), r); + // prefs.set and prefs.reset reach them too. + t.execute("prefs.set", json!({"path": "historyOptions.allowNonLinearHistory", "value": false})).unwrap(); + assert_eq!(t.execute(CMD, Value::Null).unwrap()["allowNonLinearHistory"], json!(false)); + t.execute("prefs.reset", json!({"path": "historyOptions"})).unwrap(); + assert_eq!(current(&t), current(&Session::new())); + // Older preference files without the section load with the defaults. + t.load_prefs_json("{}").unwrap(); + assert_eq!(current(&t), current(&Session::new())); + } + + #[test] + fn bad_params_are_refused_and_change_nothing() { + let mut s = Session::new(); + let before = current(&s); + for p in [ + json!({"allowNonLinearHistory": "yes"}), + json!({"allowNonLinearHistory": 1}), + json!({"makeLayerVisibilityChangesUndoable": null}), + json!({"allowNonLinearHistory": true, "snapshots": true}), + json!([true]), + json!("x"), + json!(3), + ] { + assert!(s.execute(CMD, p.clone()).is_err(), "{p}"); + assert_eq!(current(&s), before, "{p} changed nothing"); + } + assert!(s.execute("prefs.set", json!({"path": "historyOptions.allowNonLinearHistory", "value": "on"})).is_err()); + assert_eq!(current(&s), before); + } + + #[test] + fn layer_visibility_is_a_history_state_only_when_undoable() { + // On (the default): the eye, Hide/Show Layers and ⌥-click each add a state. + let (mut s, id) = doc(); + s.execute("layer.setProps", json!({"layer": id, "visible": false})).unwrap(); + assert_eq!(entries(&s).last().map(String::as_str), Some("Layer Visibility")); + s.execute("edit.undo", json!({})).unwrap(); + assert!(s.active().unwrap().doc.layer(photocraft_doc::LayerId(id)).unwrap().visible); + + // Off: the document changes (and is modified) but History doesn't. + let (mut s, id) = doc(); + s.execute(CMD, json!({"makeLayerVisibilityChangesUndoable": false})).unwrap(); + let before = entries(&s); + let rev = s.active().unwrap().revision; + s.execute("layer.setProps", json!({"layer": id, "visible": false})).unwrap(); + s.execute("layer.showLayers", json!({"layer": id})).unwrap(); + s.execute("layer.hideLayers", json!({"layer": id})).unwrap(); + s.execute("layer.showOnly", json!({"layer": id})).unwrap(); + s.execute("layer.showOnly", json!({"layer": id})).unwrap(); + // Hide Layers toggles (⌘,), so show the layer first for it to hide. + s.execute("layer.showLayers", json!({"layer": id})).unwrap(); + s.execute("layer.hideLayers", json!({"layer": id})).unwrap(); + assert_eq!(entries(&s), before, "no visibility state was recorded"); + let st = s.active().unwrap(); + assert!(!st.doc.layer(photocraft_doc::LayerId(id)).unwrap().visible, "the change still applies"); + assert!(st.revision > rev && st.is_dirty()); + // Other properties still record a state. + s.execute("layer.setProps", json!({"layer": id, "opacity": 0.5})).unwrap(); + assert_eq!(entries(&s).len(), before.len() + 1); + // An unrecorded change leaves the redo states alone. + s.execute("edit.undo", json!({})).unwrap(); + s.execute("layer.setProps", json!({"layer": id, "visible": true})).unwrap(); + assert!(s.active().unwrap().history.can_redo()); + } + + #[test] + fn non_linear_history_keeps_later_states_and_delete_removes_only_one() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16})).unwrap(); + s.execute(CMD, json!({"allowNonLinearHistory": true})).unwrap(); + for c in ["#ff0000", "#00ff00", "#0000ff"] { + s.execute("edit.fill", json!({"color": c})).unwrap(); + } + let filled = entries(&s); + assert_eq!(filled.len(), 4); + s.execute("edit.undo", json!({})).unwrap(); + s.execute("edit.undo", json!({})).unwrap(); + s.execute("image.adjustments.invert", json!({})).unwrap(); + let after = entries(&s); + assert_eq!(after.len(), 5, "the two later fills are kept: {after:?}"); + assert_eq!(after[..4], filled[..]); + // Delete the second fill only: the states after it stay. + s.execute("history.deleteState", json!({"state": 2})).unwrap(); + let mut expected = after.clone(); + expected.remove(2); + assert_eq!(entries(&s), expected); + // Deleting the current state steps back to the one before; nothing else goes. + let doc_before = s.active().unwrap().history.state(expected.len() - 2).unwrap(); + s.execute("history.deleteState", json!({})).unwrap(); + assert_eq!(entries(&s), expected[..expected.len() - 1].to_vec()); + assert!(std::sync::Arc::ptr_eq(&s.active().unwrap().doc, &doc_before)); + // After stepping back, deleting the current state keeps the later (redo) states. + s.execute("edit.undo", json!({})).unwrap(); + let redo: Vec = s.active().unwrap().history.redo_labels().map(str::to_string).collect(); + s.execute("history.deleteState", json!({})).unwrap(); + assert_eq!(s.active().unwrap().history.redo_labels().map(str::to_string).collect::>(), redo); + + // Turning it off applies to open documents: the next edit after stepping back discards. + s.execute(CMD, json!({"allowNonLinearHistory": false})).unwrap(); + assert!(!s.active().unwrap().history.non_linear); + s.execute("edit.fill", json!({"color": "#808080"})).unwrap(); + assert!(!s.active().unwrap().history.can_redo()); + // New documents pick the option up too. + s.execute(CMD, json!({"allowNonLinearHistory": true})).unwrap(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + assert!(s.active().unwrap().history.non_linear); + } +} diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index d0b2a72e98..0e5147e2ed 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -19,6 +19,8 @@ pub fn session(s: &Session) -> Value { })).collect::>(), "foreground": s.tools.foreground, "background": s.tools.background, + // History panel › History Options… (`history.options`). + "historyOptions": crate::history_options_cmds::current(s), }) } diff --git a/crates/engine/src/layer_multi_cmds.rs b/crates/engine/src/layer_multi_cmds.rs index 2d51dfdf0c..09fa057d79 100644 --- a/crates/engine/src/layer_multi_cmds.rs +++ b/crates/engine/src/layer_multi_cmds.rs @@ -1329,7 +1329,7 @@ pub fn duplicate_selected(s: &mut Session, in_place: bool, label: &str) -> Resul /// Show/hide every selected layer in one step. pub fn set_visible_selected(s: &mut Session, visible: bool) -> Result { let sel = selected(s); - s.edit(if visible { "Show Layers" } else { "Hide Layers" }, |doc, _| { + s.edit_visibility(if visible { "Show Layers" } else { "Hide Layers" }, |doc, _| { for id in &sel { doc.layer_mut(*id).ok_or(EngineError::NoLayer(*id))?.visible = visible; } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 3c455bc323..626c80f76c 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -52,6 +52,7 @@ pub mod group_view_cmds; pub mod guide_layout; pub mod hidden_target; pub mod history_cmds; +pub mod history_options_cmds; pub mod image_cmds; pub mod inspect; pub mod installed_profiles; @@ -495,6 +496,7 @@ impl Session { let mut st = DocState::new(doc, path); st.history.max_states = self.prefs.get().performance.history_states.max(1) as usize; st.history.max_bytes = self.prefs.get().performance.history_budget_bytes(); + st.history.non_linear = self.prefs.get().history_options.allow_non_linear_history; self.docs.push(st); let i = self.docs.len() - 1; self.active = Some(i); @@ -613,6 +615,25 @@ impl Session { /// Apply an undoable edit to the active document. pub fn edit(&mut self, label: &str, f: impl FnOnce(&mut Document, &mut Option) -> Result) -> Result { + self.edit_with(label, true, f) + } + + /// Apply a change of layer visibility (and nothing else): a history state when History + /// Options › Make Layer Visibility Changes Undoable is on (the default, as in Photoshop), + /// otherwise the document changes without one, so the History panel and Undo skip it. + pub fn edit_visibility(&mut self, label: &str, f: impl FnOnce(&mut Document, &mut Option) -> Result) -> Result { + let record = self.visibility_undoable(); + self.edit_with(label, record, f) + } + + /// History Options › Make Layer Visibility Changes Undoable. + pub fn visibility_undoable(&self) -> bool { + self.prefs().history_options.make_layer_visibility_changes_undoable + } + + /// [`Self::edit`], recording a history state only when `record` is set. An unrecorded change + /// still marks the document modified and leaves the redo states alone. + pub(crate) fn edit_with(&mut self, label: &str, record: bool, f: impl FnOnce(&mut Document, &mut Option) -> Result) -> Result { let restrict = self.color_restrict; let sampler_map = self.sampler_map.take(); let st = self.active_mut().ok_or(EngineError::NoDocument)?; @@ -659,14 +680,18 @@ impl Session { let key = self.coalesce_request.clone(); let st = self.active_mut().ok_or(EngineError::NoDocument)?; let layers = st.layer_target(); - if key.is_none() || st.coalesce != key || !st.history.can_undo() { + if !record { + // Nothing to coalesce with: the next recorded step starts a state of its own. + st.coalesce = None; + } else if key.is_none() || st.coalesce != key || !st.history.can_undo() { st.history.set_current_layers(prior); st.history.record(label, before, layers); st.history.trim(&st.doc); + st.coalesce = key; } else { st.history.set_current_layers(layers); + st.coalesce = key; } - st.coalesce = key; st.revision += 1; st.last_damage = damage; self.samplers_removed += samplers_removed; diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index cffc39bccf..365b57fa6b 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -12,8 +12,9 @@ //! OS config directory; the web shell: browser storage) and restore it with //! [`Session::load_prefs_json`]. //! -//! Engine-side values are applied by [`Session::apply_prefs`]: the history state limit (every -//! open document), the effect-cache memory budget, and units for commands that report lengths. +//! Engine-side values are applied by [`Session::apply_prefs`]: the history state limit and +//! History Options › Allow Non-Linear History (every open document), the effect-cache memory +//! budget, and units for commands that report lengths. //! Colour settings (`colorSettings`) are stored with the colour state //! ([`crate::color_cmds::ColorSettings`]) and persisted in the same document. @@ -945,6 +946,24 @@ impl Default for Integrations { } } +/// The History panel's History Options… (not part of Edit › Preferences in Photoshop either). +/// Photoshop's snapshot options are not here yet: snapshots are not implemented. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct HistoryOptions { + /// Allow Non-Linear History: editing after selecting an earlier state keeps the later + /// states (the new step is appended at the end), and deleting a state deletes only it. + pub allow_non_linear_history: bool, + /// Make Layer Visibility Changes Undoable: showing or hiding a layer is a history state. + pub make_layer_visibility_changes_undoable: bool, +} + +impl Default for HistoryOptions { + fn default() -> Self { + Self { allow_non_linear_history: false, make_layer_visibility_changes_undoable: true } + } +} + /// Edit › Menus: hidden items and item colours, by command id. #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] @@ -985,6 +1004,8 @@ pub struct Preferences { pub enhanced_controls: EnhancedControls, pub raw_defaults: RawDefaults, pub integrations: Integrations, + /// History panel › History Options… (`history.options`). + pub history_options: HistoryOptions, /// Edit › Keyboard Shortcuts: command id → shortcut (`Cmd+Shift+N` notation); an empty /// string removes the default shortcut. pub shortcuts: BTreeMap, @@ -1498,15 +1519,17 @@ impl Session { r } - /// Push engine-relevant preferences into live state: every document's history limit, the - /// layer-effect cache budget and the text engine's missing-glyph protection. + /// Push engine-relevant preferences into live state: every document's history limit and + /// linearity, the layer-effect cache budget and the text engine's missing-glyph protection. pub fn apply_prefs(&mut self) { let n = self.prefs().performance.history_states.max(1) as usize; let bytes = self.prefs().performance.history_budget_bytes(); let budget = self.prefs().performance.effect_cache_mb as usize; + let non_linear = self.prefs().history_options.allow_non_linear_history; for st in &mut self.docs { st.history.max_states = n; st.history.max_bytes = bytes; + st.history.non_linear = non_linear; st.history.trim(&st.doc); } photocraft_compose::set_effect_cache_budget(budget << 20); diff --git a/crates/ops/src/lib.rs b/crates/ops/src/lib.rs index 0f29cf8e98..1af3468fb0 100644 --- a/crates/ops/src/lib.rs +++ b/crates/ops/src/lib.rs @@ -50,6 +50,10 @@ pub struct History { current_label: String, /// The layers targeted when the current document was created (opened or edited). current_layers: LayerTarget, + /// History Options › Allow Non-Linear History: a step recorded while later states exist + /// (after stepping back) keeps them and goes to the end of the list, instead of discarding + /// them; see [`History::record`] and [`History::remove`]. + pub non_linear: bool, } impl Default for History { @@ -68,11 +72,17 @@ impl History { max_bytes: 0, current_label: "Open".into(), current_layers: LayerTarget::default(), + non_linear: false, } } /// Record that `before` was replaced by a new current document via step `label`, which left /// `layers` targeted. + /// + /// Linear history (the default) discards the redo states, as Photoshop does when you edit + /// after selecting an earlier state. With [`History::non_linear`] they are kept: the list + /// reads `…, before, the former redo states (oldest first), the new step`, so the new step is + /// appended at the end and every earlier state can still be stepped to. pub fn record(&mut self, label: impl Into, before: Arc, layers: LayerTarget) { if self.max_bytes == 0 { self.tiles = None; @@ -83,7 +93,15 @@ impl History { 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 }); - self.clear_redo(); + if self.non_linear { + // `redo` holds the next state last; the list order is oldest first. Their tiles stay + // counted: they only move from the redo side to the undo side. + while let Some(state) = self.redo.pop() { + self.undo.push_back(state); + } + } else { + self.clear_redo(); + } while self.undo.len() > self.max_states { if let Some(state) = self.undo.pop_front() && let Some(tiles) = &mut self.tiles @@ -175,6 +193,35 @@ impl History { true } + /// Delete the past state at entry `i` (indexed like [`History::entries`]) and nothing else, + /// as the History panel's Delete does in non-linear history. The current state is not held + /// here (the session steps back first) and the oldest state can't be removed this way + /// either, since every later state would lose its starting point in the list. Returns + /// whether a state was removed. + pub fn remove(&mut self, i: usize) -> bool { + if i == 0 { + return false; + } + let Some(state) = self.undo.remove(i) else { return false }; + if let Some(tiles) = &mut self.tiles { + tiles.remove(&state.doc); + } + true + } + + /// Step back like [`History::undo`] but drop the current document instead of making it + /// redoable: the current state is deleted while the redo states (later states in the + /// list) stay. Returns the document to make current and the layers it targeted. + pub fn drop_current(&mut self) -> Option<(Arc, LayerTarget)> { + let prev = self.undo.pop_back()?; + if let Some(tiles) = &mut self.tiles { + tiles.remove(&prev.doc); + } + self.current_label = prev.label; + self.current_layers = prev.layers.clone(); + Some((prev.doc, prev.layers)) + } + /// Forget the redo states, e.g. after undoing half of a compound step that failed. pub fn clear_redo(&mut self) { if let Some(tiles) = &mut self.tiles { @@ -348,6 +395,95 @@ mod tests { assert_eq!(h.entries(), vec!["Open".to_string(), "B".to_string()]); } + /// Open, A, B, C, then two steps back: A is current, B and C are redo states. + fn stepped_back(non_linear: bool) -> (History, Arc) { + let mut h = History { non_linear, ..History::default() }; + let mut cur = Arc::new(base()); + for n in ["A", "B", "C"] { + edit(&mut h, &mut cur, n, |d| d.name = n.to_lowercase()); + } + cur = h.undo(cur).unwrap().0; + cur = h.undo(cur).unwrap().0; + assert_eq!(cur.name, "a"); + (h, cur) + } + + #[test] + fn non_linear_history_keeps_later_states_and_appends_the_new_step() { + let (mut h, mut cur) = stepped_back(true); + edit(&mut h, &mut cur, "D", |d| d.name = format!("{}+d", d.name)); + assert_eq!(h.entries(), ["Open", "A", "B", "C", "D"], "B and C are kept, D goes to the end"); + assert!(!h.can_redo()); + assert_eq!(cur.name, "a+d", "D was made from the state selected (A), not from C"); + // Stepping back walks the list: C, B, A, Open, each with its own document. + let mut names = Vec::new(); + while let Some((d, _)) = h.undo(cur.clone()) { + cur = d; + names.push(cur.name.clone()); + } + assert_eq!(names, ["c", "b", "a", "h"]); + // Linear history (the default) discards them. + let (mut h, mut cur) = stepped_back(false); + edit(&mut h, &mut cur, "D", |d| d.name = "d".into()); + assert_eq!(h.entries(), ["Open", "A", "D"]); + } + + #[test] + fn non_linear_steps_respect_the_state_limit_and_the_tile_counter() { + let mut h = History::new(3); + h.non_linear = true; + h.max_bytes = usize::MAX; + let mut cur = Arc::new(base()); + for i in 0..4 { + edit(&mut h, &mut cur, &format!("paint {i}"), |d| { + d.layers[0].surface_mut().unwrap().write_pixel(1, 1, &[i as f32 / 8.0, 0.0, 0.0, 1.0]); + }); + h.trim(&cur); + } + cur = h.undo(cur).unwrap().0; + cur = h.undo(cur).unwrap().0; + edit(&mut h, &mut cur, "branch", |d| d.name = "branch".into()); + assert_eq!(h.past_len(), 3, "the oldest states beyond the limit go"); + assert_eq!(h.entries(), ["paint 1", "paint 2", "paint 3", "branch"]); + assert_counter(&h, &cur); + } + + #[test] + fn remove_deletes_one_past_state_and_drop_current_keeps_the_redo_states() { + let (mut h, _) = stepped_back(true); + assert!(!h.remove(0), "the oldest state stays"); + assert!(!h.remove(1), "the current state (A) is not held"); + assert!(!h.remove(99)); + let (mut h, mut cur) = stepped_back(true); + edit(&mut h, &mut cur, "D", |d| d.name = "d".into()); + assert!(h.remove(1)); + assert_eq!(h.entries(), ["Open", "B", "C", "D"]); + assert_eq!(h.state(1).unwrap().name, "b", "each state keeps its own document"); + // Deleting the current state: the one before becomes current, the later ones stay. + let (mut h, _) = stepped_back(true); + let (d, _) = h.drop_current().unwrap(); + assert_eq!(d.name, "h"); + assert_eq!(h.entries(), ["Open"]); + assert_eq!(h.redo_labels().collect::>(), ["B", "C"]); + assert!(h.drop_current().is_none(), "nothing before Open"); + // The tile counter follows both. + let mut h = History::new(50); + h.non_linear = true; + h.max_bytes = usize::MAX; + let mut cur = Arc::new(base()); + for i in 0..4 { + edit(&mut h, &mut cur, "Paint", |d| { + d.layers[0].surface_mut().unwrap().write_pixel(1, 1, &[i as f32 / 8.0, 0.0, 0.0, 1.0]); + }); + h.trim(&cur); + } + cur = h.undo(cur).unwrap().0; + assert!(h.remove(2)); + assert_counter(&h, &cur); + cur = h.drop_current().unwrap().0; + assert_counter(&h, &cur); + } + #[test] fn max_states_bound() { let mut h = History::new(3); diff --git a/crates/ui-egui/src/history_options_ui.rs b/crates/ui-egui/src/history_options_ui.rs new file mode 100644 index 0000000000..2d4756543b --- /dev/null +++ b/crates/ui-egui/src/history_options_ui.rs @@ -0,0 +1,98 @@ +//! The History Options dialog (History panel menu › History Options…, #2966): a form over the +//! engine's `history.options` with its two checkboxes, filled with the current values. OK runs +//! the command with the dialog's values (the generic command-dialog confirm), Cancel changes +//! nothing. Agents can also run `history.options` with params directly, or `prefs.set +//! historyOptions.*`; a call with params skips the dialog. + +use serde_json::{Map, Value, json}; + +use crate::PhotocraftApp; +use crate::state::DialogKind; + +pub const COMMAND: &str = "history.options"; + +/// Opens the dialog for a parameterless `history.options`; anything else is not handled here. +pub fn menu(app: &mut PhotocraftApp, id: &str, params: &Value) -> Option> { + if id != COMMAND || params.as_object().is_some_and(|m| m.keys().any(|k| !k.starts_with("__"))) { + return None; + } + Some(Ok(json!({ "dialog": open(app) }))) +} + +/// Open the dialog on the current options; returns its id. +pub fn open(app: &mut PhotocraftApp) -> u64 { + let current = photocraft_engine::history_options_cmds::current(&app.session); + let mut f = Map::new(); + f.insert("__command".into(), json!(COMMAND)); + f.insert("__label".into(), json!("History Options…")); + f.insert("__form".into(), json!(true)); + f.insert("__choices".into(), json!({})); + // Photoshop's capitalised labels, in the UI language (the form would sentence-case the keys). + f.insert( + "__labels".into(), + json!({ + "allowNonLinearHistory": tl!("Allow Non-Linear History"), + "makeLayerVisibilityChangesUndoable": tl!("Make Layer Visibility Changes Undoable"), + }), + ); + for key in photocraft_engine::history_options_cmds::OPTIONS { + f.insert(key.into(), current.get(key).cloned().unwrap_or(Value::Bool(false))); + } + app.ui.open_dialog(DialogKind::Command, f) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn app() -> PhotocraftApp { + PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()) + } + + #[test] + fn the_command_opens_the_dialog_on_the_current_values_and_ok_applies_them() { + let mut app = app(); + let ctx = egui::Context::default(); + let r = crate::menus::invoke(&mut app, &ctx, COMMAND, json!({})).unwrap(); + let id = r["dialog"].as_u64().unwrap(); + let d = app.ui.dialogs.iter().find(|d| d.id == id).unwrap(); + assert_eq!(d.fields["allowNonLinearHistory"], json!(false)); + assert_eq!(d.fields["makeLayerVisibilityChangesUndoable"], json!(true)); + assert_eq!(crate::dialogs::title(d), "History Options"); + // Cancel changes nothing. + app.ui.dialog_mut(id).unwrap().fields.insert("allowNonLinearHistory".into(), json!(true)); + crate::dialogs::cancel(&mut app, id).unwrap(); + assert!(!app.session.prefs().history_options.allow_non_linear_history); + // OK applies both checkboxes. + let id = open(&mut app); + let fields = &mut app.ui.dialog_mut(id).unwrap().fields; + fields.insert("allowNonLinearHistory".into(), json!(true)); + fields.insert("makeLayerVisibilityChangesUndoable".into(), json!(false)); + crate::dialogs::confirm(&mut app, id).unwrap(); + let o = &app.session.prefs().history_options; + assert!(o.allow_non_linear_history && !o.make_layer_visibility_changes_undoable); + assert!(app.ui.dialogs.is_empty()); + // Reopened, it shows what was chosen; with params the command runs without a dialog. + let id = open(&mut app); + assert_eq!(app.ui.dialogs.iter().find(|d| d.id == id).unwrap().fields["allowNonLinearHistory"], json!(true)); + crate::dialogs::cancel(&mut app, id).unwrap(); + let r = crate::menus::invoke(&mut app, &ctx, COMMAND, json!({"allowNonLinearHistory": false})).unwrap(); + assert_eq!(r["allowNonLinearHistory"], json!(false)); + assert!(app.ui.dialogs.is_empty()); + assert!(crate::menus::invoke(&mut app, &ctx, COMMAND, json!({"allowNonLinearHistory": "no"})).is_err()); + } + + #[test] + fn the_dialog_draws_both_checkboxes_with_photoshops_labels() { + use egui_kittest::{Harness, kittest::Queryable}; + let mut h = Harness::builder().with_size(egui::vec2(700.0, 400.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app()); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + open(h.state_mut()); + h.run_steps(3); + h.get_by_label("History Options"); + h.get_by_label("Allow Non-Linear History"); + h.get_by_label("Make Layer Visibility Changes Undoable"); + h.get_by_label("OK"); + h.get_by_label("Cancel"); + } +} diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 66ebdf6440..8c482c864d 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -3476,6 +3476,11 @@ curves Smooth Vyhladit Click 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 odeberete No document open Není otevřen žádný dokument {n} of {max} sample points {n} z {max} bodů měření + +# History panel › History Options… (#2966) + History Options… Volby historie… + Allow Non-Linear History Povolit nelineární historii + Make Layer Visibility Changes Undoable Umožnit vrácení změn viditelnosti vrstev Drag (lasso) or click points (polygonal) · {add} add · {sub} subtract Táhněte (laso) nebo klikejte na body (mnohoúhelník) · {add} přidat · {sub} odečíst The current gradient (pick one in Window › Gradients) Aktuální přechod (vyberte v Okno › Přechody) # Canvas context menus, Channels panel menu, Layer Style blending page (labels rendered through a variable). diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index c2b2f3a8f4..211262dbf2 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -2659,6 +2659,11 @@ curves Smooth Glätten Click to place · Alt-click or drag off-canvas to remove Klicken zum Platzieren · Alt-Klick oder Ziehen außerhalb der Arbeitsfläche zum Entfernen No document open Kein Dokument geöffnet {n} of {max} sample points {n} von {max} Messpunkten + +# History panel › History Options… (#2966) + History Options… Protokolloptionen… + Allow Non-Linear History Nicht-lineare Protokolle zulassen + Make Layer Visibility Changes Undoable Änderungen der Ebenensichtbarkeit widerrufbar machen # Print dialog (#2697) Emulsion Down Schichtseite unten Functions Funktionen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 27fa97ff7e..9f7f58786a 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -3716,6 +3716,11 @@ curves Smooth Εξομάλυνση # 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 › History Options… (#2966) + History Options… Επιλογές ιστορικού… + Allow Non-Linear History Να επιτρέπεται μη γραμμικό ιστορικό + Make Layer Visibility Changes Undoable Οι αλλαγές ορατότητας επιπέδων να αναιρούνται # Print dialog (#2697) Emulsion Down Γαλάκτωμα προς τα κάτω Functions Λειτουργίες diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 05d4302939..e4a1cdb050 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -2700,6 +2700,11 @@ curves Smooth Suavizar Click to place · Alt-click or drag off-canvas to remove Clic para colocar · Alt-clic o arrastrar fuera del lienzo para quitar No document open Ningún documento abierto {n} of {max} sample points {n} de {max} puntos de muestreo + +# History panel › History Options… (#2966) + History Options… Opciones de historia… + Allow Non-Linear History Permitir historia no lineal + Make Layer Visibility Changes Undoable Permitir deshacer los cambios de visibilidad de capas # Print dialog (#2697) Emulsion Down Emulsión hacia abajo Functions Funciones diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 122afec499..47f2d02d3e 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3034,6 +3034,11 @@ curves Smooth Lisser Click to place · Alt-click or drag off-canvas to remove Cliquez pour placer · Alt-clic ou glisser hors du canevas pour supprimer No document open Aucun document ouvert {n} of {max} sample points {n} sur {max} points d'échantillonnage + +# History panel › History Options… (#2966) + History Options… Options d'historique… + Allow Non-Linear History Autoriser l'historique non linéaire + Make Layer Visibility Changes Undoable Permettre d'annuler les changements de visibilité des calques # Print dialog (#2697) Emulsion Down Émulsion verso Functions Fonctions diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index a160a718a0..c539347b7e 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -3021,6 +3021,11 @@ curves Smooth Haluskan Click to place · Alt-click or drag off-canvas to remove Klik untuk menempatkan · Alt-klik atau seret ke luar kanvas untuk menghapus No document open Tidak ada dokumen yang terbuka {n} of {max} sample points {n} dari {max} titik sampel + +# History panel › History Options… (#2966) + History Options… Opsi Riwayat… + Allow Non-Linear History Izinkan Riwayat Non-Linier + Make Layer Visibility Changes Undoable Perubahan Visibilitas Layer Dapat Diurungkan # Print dialog (#2697) Emulsion Down Emulsi di Bawah Functions Fungsi diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index f4c5a2289c..58768806da 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -2690,6 +2690,11 @@ curves Smooth Leviga Click to place · Alt-click or drag off-canvas to remove Fai clic per posizionare · Alt-clic o trascina fuori dal quadro per rimuovere No document open Nessun documento aperto {n} of {max} sample points {n} di {max} punti di campionamento + +# History panel › History Options… (#2966) + History Options… Opzioni cronologia… + Allow Non-Linear History Consenti cronologia non lineare + Make Layer Visibility Changes Undoable Rendi annullabili le modifiche di visibilità dei livelli # Print dialog (#2697) Emulsion Down Emulsione sotto Functions Funzioni diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index e938ce8d1d..47d9335bb5 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3628,6 +3628,11 @@ curves Smooth スムーズ Click to place · Alt-click or drag off-canvas to remove クリックで配置 · Alt キーを押しながらクリック、またはカンバス外へドラッグで削除 No document open ドキュメントが開かれていません {n} of {max} sample points {max} 個中 {n} 個のサンプルポイント + +# History panel › History Options… (#2966) + History Options… ヒストリーオプション… + Allow Non-Linear History 非線形のヒストリーを許可 + Make Layer Visibility Changes Undoable レイヤーの表示/非表示の変更を取り消し可能にする # Print dialog (#2697) Emulsion Down 乳剤面を下 Functions 機能 diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index bd0fd8e29c..256a21ab63 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3204,6 +3204,11 @@ curves Smooth 매끄럽게 Click to place · Alt-click or drag off-canvas to remove 클릭하여 배치 · Alt-클릭 또는 캔버스 밖으로 드래그하여 제거 No document open 열린 문서 없음 {n} of {max} sample points {max}개 중 {n}개의 샘플 지점 + +# History panel › History Options… (#2966) + History Options… 작업 내역 옵션… + Allow Non-Linear History 비선형 작업 내역 허용 + Make Layer Visibility Changes Undoable 레이어 표시 여부 변경을 실행 취소할 수 있게 하기 # Print dialog (#2697) Emulsion Down 감광면 아래로 Functions 기능 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index b2745ec39b..0dff55d6fd 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -3778,6 +3778,11 @@ curves Smooth Vloeiend maken # 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 › History Options… (#2966) + History Options… Geschiedenisopties… + Allow Non-Linear History Niet-lineaire geschiedenis toestaan + Make Layer Visibility Changes Undoable Wijzigingen in laagzichtbaarheid ongedaan kunnen maken # Print dialog (#2697) Emulsion Down Emulsie omlaag Functions Functies diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index c3186de02d..ffcb568bee 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -3630,6 +3630,11 @@ curves Smooth Wygładź Click 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 › History Options… (#2966) + History Options… Opcje historii… + Allow Non-Linear History Zezwalaj na nieliniową historię + Make Layer Visibility Changes Undoable Pozwalaj cofać zmiany widoczności warstw # Print dialog (#2697) Emulsion Down Emulsja w dół Functions Funkcje diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index daba1a7893..246f56fe77 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -3808,6 +3808,11 @@ layerLabel No Color Sem cor Set Colors Definir cores Switch Foreground and Background Colors Alternar cores de primeiro plano e plano de fundo Target Alvo + +# History panel › History Options… (#2966) + History Options… Opções do histórico… + Allow Non-Linear History Permitir histórico não linear + Make Layer Visibility Changes Undoable Permitir desfazer alterações de visibilidade das camadas # Print dialog (#2697) Emulsion Down Emulsão para baixo Functions Funções diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 87ef0be0ae..fbe74d98e1 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -2963,6 +2963,11 @@ curves Smooth Сгладить Click to place · Alt-click or drag off-canvas to remove Щёлкните, чтобы разместить · Alt-щелчок или перетаскивание за пределы холста для удаления No document open Документ не открыт {n} of {max} sample points {n} из {max} точек замера + +# History panel › History Options… (#2966) + History Options… Параметры истории… + Allow Non-Linear History Разрешить нелинейную историю + Make Layer Visibility Changes Undoable Разрешить отмену изменений видимости слоёв # Print dialog (#2697) Emulsion Down Эмульсией вниз Functions Функции diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index c2d76978f3..ebf9d7fc45 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -3716,6 +3716,11 @@ curves Smooth Згладити Click to place · Alt-click or drag off-canvas to remove Клацніть, щоб розмістити · Alt-клацання або перетягування за межі полотна для видалення No document open Документ не відкрито {n} of {max} sample points {n} з {max} точок вимірювання + +# History panel › History Options… (#2966) + History Options… Параметри історії… + Allow Non-Linear History Дозволити нелінійну історію + Make Layer Visibility Changes Undoable Дозволити скасування змін видимості шарів # Print dialog (#2697) Emulsion Down Емульсією донизу Functions Функції diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index f0c5e7bd2b..710709a82e 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -3538,3 +3538,8 @@ curves Smooth Làm mượt Remove after each stroke Xóa sau mỗi nét vẽ Apply the removal ({key}) Áp dụng việc xóa ({key}) Strokes to remove: {n} (Enter applies, Esc cancels) Nét vẽ cần xóa: {n} (Enter áp dụng, Esc hủy) + +# History panel › History Options… (#2966) + History Options… Tùy chọn lịch sử… + Allow Non-Linear History Cho phép lịch sử không tuyến tính + Make Layer Visibility Changes Undoable Cho phép hoàn tác thay đổi hiển thị lớp diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index f7e4c60c00..4294d08cdd 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -2639,6 +2639,11 @@ curves Smooth 平滑 Click to place · Alt-click or drag off-canvas to remove 单击以放置 · Alt 单击或拖到画布外以移除 No document open 未打开任何文档 {n} of {max} sample points {max} 个取样点中的 {n} 个 + +# History panel › History Options… (#2966) + History Options… 历史记录选项… + Allow Non-Linear History 允许非线性历史记录 + Make Layer Visibility Changes Undoable 允许撤销图层可见性更改 # Print dialog (#2697) Emulsion Down 药膜朝下 Functions 功能 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index dec257895b..42bd150bca 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2609,6 +2609,11 @@ curves Smooth 平滑 Click to place · Alt-click or drag off-canvas to remove 按一下以放置 · Alt 按一下或拖曳至畫布外以移除 No document open 未開啟任何文件 {n} of {max} sample points {max} 個取樣點中的 {n} 個 + +# History panel › History Options… (#2966) + History Options… 步驟記錄選項… + Allow Non-Linear History 允許非線性步驟記錄 + Make Layer Visibility Changes Undoable 允許復原圖層可見度變更 # Print dialog (#2697) Emulsion Down 感光乳劑面朝下 Functions 功能 diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 8d34fc2aa9..73c02ac426 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -91,6 +91,7 @@ pub mod gpu_canvas; pub mod gpu_status; pub mod gradient_ui; pub mod guide_layout_ui; +pub mod history_options_ui; pub mod hold_keys; pub mod i18n; mod icon_data; diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 4e6c9ba188..326bf472bb 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -214,6 +214,10 @@ pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id: if let Some(r) = crate::plugin_ui::menu(app, id, ¶ms) { return r; } + // History panel menu › History Options… (without params: its dialog). + if let Some(r) = crate::history_options_ui::menu(app, id, ¶ms) { + return r; + } if id == "window.panel.brushes" { // Window › Brushes opens the Brush Settings window on its presets tab. app.ui.panels.brush_settings = true; diff --git a/docs/scorecard.md b/docs/scorecard.md index 78a0864549..ff0188d419 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -9,7 +9,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js | [Performance](#performance) | 3 | 22 | 22 | 56 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 17 not run, 5 not measurable yet (baseline 2026-10-05) | | [File compatibility](#file-compatibility) | 6 | 13 | 8 | io corpus: oracle ≥ 146/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 236/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 133/256, round trip ≥ 258/256 | | [Tools](#tools) | 28 | 14 | 1 | | -| [Workspace and UI](#workspace-and-ui) | 13 | 5 | 5 | settings that do nothing: 27 of 156 (target 0) | +| [Workspace and UI](#workspace-and-ui) | 13 | 5 | 5 | settings that do nothing: 27 of 158 (target 0) | | [Type](#type) | 4 | 2 | 3 | | | [Automation](#automation) | 4 | 2 | 5 | 631 of 631 menu items live (100.0%) | | [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 28 of 28 crates; panic_hunt present | @@ -176,7 +176,7 @@ Corpus floors (`crates/io/tests/corpus.rs`): the enforced minimums; the corpus t ## Workspace and UI -**Settings that do nothing: 27 of 156** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. +**Settings that do nothing: 27 of 158** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. Unread: `general.color_picker`, `general.animated_zoom`, `general.zoom_resizes_windows`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `file_handling.save_in_background`, `file_handling.maximize_psd_compatibility`, `performance.cache_levels`, `performance.legacy_compositing`, `scratch_disks.disks`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `plug_ins.generator_enabled`, `type_.text_engine`, `type_.recent_fonts`, `enhanced_controls.scrubby_slider_acceleration`, `enhanced_controls.touch_gestures`, `raw_defaults.color_space`, `raw_defaults.bit_depth`, `raw_defaults.resolution`, `raw_defaults.sharpen_for`, `raw_defaults.open_as_smart_object`, `raw_defaults.apply_auto_tone`, `integrations.allow_agent_control`, `integrations.control_port`.