Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

History: set the History Brush source from the panel (history.setSource) (#2966)

David Mannb5e3e80a3b76
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs
index 01f669f14..9b781aeec 100644
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@ -1174,6 +1174,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_source_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/fill_cmds.rs b/crates/engine/src/fill_cmds.rs
index 78a28b048..b1e1e8ad3 100644
--- a/crates/engine/src/fill_cmds.rs
+++ b/crates/engine/src/fill_cmds.rs
@@ -121,8 +121,8 @@ pub fn fill(s: &mut Session, p: &Value) -> Result<Value> {
let source_doc = match explicit {
Some(i) if i == past => st.doc.clone(),
Some(i) => st.history.state(i).ok_or_else(|| bad(format!("no history state {i} (0..={past})")))?,
- // The History Brush's default source: the oldest state still held.
- None => st.history.state(0).unwrap_or_else(|| st.doc.clone()),
+ // The History Brush's source (History panel), by default the oldest state held.
+ None => crate::history_source_cmds::source_doc(st)?,
};
let mut source_doc = (*source_doc).clone();
let (src, _) = crate::channel_cmds::target_surface(&mut source_doc, id, p)
diff --git a/crates/engine/src/history_source_cmds.rs b/crates/engine/src/history_source_cmds.rs
new file mode 100644
index 000000000..6457dd256
--- /dev/null
+++ b/crates/engine/src/history_source_cmds.rs
@@ -0,0 +1,206 @@
+//! The History Brush's source (#2966): the History panel's source column, at the left of every
+//! state, sets which state the History Brush (and Fill › History) restores from. Exactly one
+//! source per document; by default the oldest state held (Photoshop's default is the first
+//! snapshot, the document as opened, which that state is until it falls off the history).
+//!
+//! The source is kept by state, not by index ([`photocraft_ops::History::set_brush_source`]), so
+//! it stays on its state while older states fall off, and that state is kept when it would fall
+//! off the history itself. Once it is deleted, or discarded by a new step after stepping back,
+//! there is no source until one is set, and the History Brush refuses to paint without an
+//! explicit `state`, as Photoshop does. (Photoshop keeps a source discarded by a new step in the
+//! list; that needs states outside the linear history, so here it is gone.)
+
+use std::sync::Arc;
+
+use photocraft_doc::Document;
+use serde_json::{Value, json};
+
+use crate::commands::CommandSpec;
+use crate::{DocState, EngineError, Result, Session};
+
+const CMD: &str = "history.setSource";
+
+fn bad(msg: impl Into<String>) -> EngineError {
+ EngineError::BadParams { cmd: CMD.into(), msg: msg.into() }
+}
+
+/// The document the History Brush paints from when no `state` is passed: the source state set in
+/// the History panel, or the default (the oldest state held).
+pub(crate) fn source_doc(st: &DocState) -> Result<Arc<Document>> {
+ st.history
+ .brush_source()
+ .and_then(|i| st.history.row_doc(i, &st.doc))
+ .ok_or_else(|| EngineError::Other("the History Brush source state was deleted: set a new source in the History panel".into()))
+}
+
+/// `history.setSource {state}`: make a History panel row the History Brush's source. Rows are
+/// numbered as the panel lists them: the states (0 = oldest, then the current one), then the
+/// greyed states a step back left redoable.
+fn set_source(s: &mut Session, p: &Value) -> Result<Value> {
+ if p.get("snapshot").is_some_and(|v| !v.is_null()) {
+ return Err(EngineError::Other("History snapshots are not supported yet: set the source to a `state`".into()));
+ }
+ let v = match p.get("state") {
+ None | Some(Value::Null) => return Err(bad("pass the `state` to paint from (a History panel row, 0 = oldest)")),
+ Some(v) => v,
+ };
+ let st = s.active_mut().ok_or(EngineError::NoDocument)?;
+ let rows = st.history.entries().len() + st.history.redo_labels().count();
+ let i = v.as_u64().and_then(|i| usize::try_from(i).ok()).ok_or_else(|| bad(format!("`state` must be a History panel row (0..{rows}), not {v}")))?;
+ if !st.history.set_brush_source(i) {
+ return Err(bad(format!("no history state {i} (0..{rows})")));
+ }
+ Ok(source_json(st))
+}
+
+/// The source as `doc_inspect` reports it: its History panel row and label (`null` when its state
+/// was deleted).
+pub fn source_json(st: &DocState) -> Value {
+ let Some(i) = st.history.brush_source() else { return Value::Null };
+ let label = st.history.entries().into_iter().chain(st.history.redo_labels().map(str::to_string)).nth(i);
+ json!({ "state": i, "label": label })
+}
+
+fn has_doc(s: &Session) -> std::result::Result<(), String> {
+ s.active().map(|_| ()).ok_or_else(|| "no document open".into())
+}
+
+pub fn specs() -> Vec<CommandSpec> {
+ vec![CommandSpec {
+ id: CMD,
+ label: "Set History Brush Source",
+ menu: &[],
+ shortcut: None,
+ params: r##"{"state":index} (History panel row: 0 = oldest state, then the current one, then the greyed redo states; `snapshot` is not supported yet) → {state,label}: paint.historyBrush and Fill › History use this state when no `state` is passed"##,
+ enabled: has_doc,
+ run: set_source,
+ journal: true,
+ }]
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// A white 8×8 document filled red, then green: rows Open, Fill (red), Fill (green).
+ fn session() -> Session {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 8, "height": 8, "depth": 16, "background": "white"})).unwrap();
+ s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap();
+ s.execute("edit.fill", json!({"color": "#00ff00"})).unwrap();
+ s
+ }
+
+ fn rgb(s: &Session) -> [f32; 3] {
+ let st = s.active().unwrap();
+ let px = st.doc.layers[0].surface().unwrap().rgba(4, 4);
+ [px[0], px[1], px[2]]
+ }
+
+ fn brush(s: &mut Session, extra: Value) {
+ let mut p = json!({"points": [[4, 4]], "size": 40, "hardness": 100});
+ if let (Some(p), Some(e)) = (p.as_object_mut(), extra.as_object()) {
+ p.extend(e.clone());
+ }
+ s.execute("paint.historyBrush", p).unwrap();
+ }
+
+ fn close(a: [f32; 3], b: [f32; 3]) -> bool {
+ a.iter().zip(b).all(|(x, y)| (x - y).abs() < 0.01)
+ }
+
+ #[test]
+ fn default_source_is_the_oldest_state() {
+ let mut s = session();
+ assert_eq!(crate::inspect::document(s.active().unwrap())["historySource"], json!({"state": 0, "label": "Open"}));
+ brush(&mut s, json!({}));
+ assert!(close(rgb(&s), [1.0, 1.0, 1.0]), "{:?}", rgb(&s));
+ }
+
+ #[test]
+ fn the_history_brush_and_fill_paint_from_the_set_source() {
+ let mut s = session();
+ let r = s.execute(CMD, json!({"state": 1})).unwrap();
+ assert_eq!(r, json!({"state": 1, "label": "Fill"}));
+ assert_eq!(crate::inspect::document(s.active().unwrap())["historySource"]["state"], 1);
+ brush(&mut s, json!({}));
+ assert!(close(rgb(&s), [1.0, 0.0, 0.0]), "the red state: {:?}", rgb(&s));
+ // An explicit `state` still wins.
+ brush(&mut s, json!({"state": 0}));
+ assert!(close(rgb(&s), [1.0, 1.0, 1.0]), "{:?}", rgb(&s));
+ s.execute("edit.fill", json!({"contents": "history"})).unwrap();
+ assert!(close(rgb(&s), [1.0, 0.0, 0.0]), "Fill › History uses the source too: {:?}", rgb(&s));
+ // Setting the source is not a step.
+ assert_eq!(s.active().unwrap().history.entries().len(), 6);
+ }
+
+ /// The common Photoshop workflow: apply, step back, set the source on the greyed state, paint.
+ #[test]
+ fn a_redo_state_can_be_the_source_until_a_new_step_discards_it() {
+ let mut s = session();
+ assert!(s.undo());
+ s.execute(CMD, json!({"state": 2})).unwrap();
+ brush(&mut s, json!({}));
+ assert!(close(rgb(&s), [0.0, 1.0, 0.0]), "the greyed green state: {:?}", rgb(&s));
+ // Painting was a new step, which discarded the green state: no source until one is set.
+ assert!(crate::inspect::document(s.active().unwrap())["historySource"].is_null());
+ let before = rgb(&s);
+ assert!(s.execute("paint.historyBrush", json!({"points": [[4, 4]], "size": 40})).is_err());
+ assert!(s.execute("edit.fill", json!({"contents": "history"})).is_err());
+ assert!(close(rgb(&s), before), "nothing painted");
+ brush(&mut s, json!({"state": 0}));
+ assert!(close(rgb(&s), [1.0, 1.0, 1.0]), "an explicit state still paints: {:?}", rgb(&s));
+ s.execute(CMD, json!({"state": 0})).unwrap();
+ brush(&mut s, json!({}));
+ }
+
+ #[test]
+ fn the_source_follows_its_state_as_older_states_fall_off() {
+ let mut s = session();
+ s.active_mut().unwrap().history.max_states = 2;
+ s.execute(CMD, json!({"state": 1})).unwrap();
+ s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap();
+ // Open fell off: the red state is row 0 now and still the source.
+ let st = s.active().unwrap();
+ assert_eq!((st.history.entries().len(), st.history.brush_source()), (3, Some(0)));
+ // It would fall off next: it is kept, as in Photoshop, and paints red.
+ s.execute("edit.fill", json!({"color": "#ffffff"})).unwrap();
+ brush(&mut s, json!({}));
+ let st = s.active().unwrap();
+ assert_eq!((st.history.entries()[0].as_str(), st.history.brush_source()), ("Fill", Some(0)));
+ assert!(close(rgb(&s), [1.0, 0.0, 0.0]), "{:?}", rgb(&s));
+ }
+
+ #[test]
+ fn deleting_the_source_state_leaves_no_source() {
+ let mut s = session();
+ s.execute(CMD, json!({"state": 2})).unwrap();
+ s.execute("history.deleteState", json!({"state": 2})).unwrap();
+ assert!(crate::inspect::document(s.active().unwrap())["historySource"].is_null());
+ assert!(s.execute("paint.historyBrush", json!({"points": [[4, 4]], "size": 40})).is_err());
+ s.execute(CMD, json!({"state": 1})).unwrap();
+ brush(&mut s, json!({}));
+ assert!(close(rgb(&s), [1.0, 0.0, 0.0]), "{:?}", rgb(&s));
+ }
+
+ #[test]
+ fn bad_params_and_no_document_are_errors() {
+ assert!(matches!(Session::new().execute(CMD, json!({"state": 0})), Err(EngineError::NoDocument | EngineError::Disabled(..))));
+ let mut s = session();
+ for p in [
+ json!({}),
+ json!({"state": null}),
+ json!({"state": -1}),
+ json!({"state": 3}),
+ json!({"state": 1e300}),
+ json!({"state": 1.5}),
+ json!({"state": "1"}),
+ json!({"state": [1]}),
+ json!({"snapshot": 0}),
+ json!({"snapshot": "Open", "state": 1}),
+ ] {
+ assert!(s.execute(CMD, p.clone()).is_err(), "{p}");
+ }
+ assert_eq!(s.active().unwrap().history.brush_source(), Some(0), "nothing changed");
+ }
+}
diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs
index 1d1c7e0c7..576b19d08 100644
--- a/crates/engine/src/inspect.rs
+++ b/crates/engine/src/inspect.rs
@@ -39,6 +39,7 @@ pub fn document(d: &DocState) -> Value {
"selectionBounds": doc.selection.as_ref().map(|s| { let r = s.content_bounds(); [r.x0, r.y0, r.width() as i32, r.height() as i32] }),
"layers": doc.layers.iter().rev().map(|l| layer_sel(l, &selected)).collect::<Vec<_>>(),
"history": d.history.entries(),
+ "historySource": crate::history_source_cmds::source_json(d),
"canUndo": d.history.can_undo(),
"canRedo": d.history.can_redo(),
"revision": d.revision,
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 6a4354a2b..44181eef0 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_source_cmds;
pub mod image_cmds;
pub mod inspect;
pub mod jobs;
diff --git a/crates/engine/src/retouch_cmds.rs b/crates/engine/src/retouch_cmds.rs
index 0da474c22..e92306589 100644
--- a/crates/engine/src/retouch_cmds.rs
+++ b/crates/engine/src/retouch_cmds.rs
@@ -501,14 +501,15 @@ fn healing_brush(s: &mut Session, p: &Value) -> Result<Value> {
}
/// The History Brush's source: the targeted surface (pixels, mask, channel) as it was in history
-/// state `state` (default: the oldest state still held, the "Open" snapshot unless trimmed).
+/// state `state` (default: the source set in the History panel, `history.setSource`, else the
+/// oldest state still held, the "Open" snapshot unless trimmed).
fn history_source(s: &Session, id: Option<LayerId>, p: &Value, cmd: &str) -> Result<Surface> {
let st = s.active().ok_or(EngineError::NoDocument)?;
let explicit = p.get("state").and_then(Value::as_u64).map(|v| v as usize);
let source_doc = match explicit {
Some(i) if i == st.history.past_len() => st.doc.clone(),
Some(i) => st.history.state(i).ok_or_else(|| bad(cmd, format!("no history state {i} (0..={})", st.history.past_len())))?,
- None => st.history.state(0).unwrap_or_else(|| st.doc.clone()),
+ None => crate::history_source_cmds::source_doc(st)?,
};
let mut source_doc = (*source_doc).clone();
crate::channel_cmds::target_surface(&mut source_doc, id, p)
@@ -1242,7 +1243,9 @@ pub fn specs() -> Vec<CommandSpec> {
label: "History Brush",
menu: &[],
shortcut: None,
- params: brush_params!(r#","state":index (into history.entries; default 0 = the oldest held state, normally the Open snapshot)"#),
+ params: brush_params!(
+ r#","state":index (into history.entries; default the History panel's source, history.setSource, else 0 = the oldest held state)"#
+ ),
enabled: has_pixel_layer,
run: history_brush,
journal: true,
diff --git a/crates/ops/src/lib.rs b/crates/ops/src/lib.rs
index 0f29cf8e9..743134f96 100644
--- a/crates/ops/src/lib.rs
+++ b/crates/ops/src/lib.rs
@@ -33,6 +33,8 @@ pub struct HistoryState {
pub doc: Arc<Document>,
/// The layers targeted when this state was created.
pub layers: LayerTarget,
+ /// Stable while the state is held: indices shift when older states fall off, ids don't.
+ pub id: u64,
}
#[derive(Clone, Debug)]
@@ -50,6 +52,12 @@ pub struct History {
current_label: String,
/// The layers targeted when the current document was created (opened or edited).
current_layers: LayerTarget,
+ /// [`HistoryState::id`] of the current state.
+ current_id: u64,
+ /// The id the next state gets: never reused, so a discarded state's id names no other.
+ next_id: u64,
+ /// The History Brush's source state, set in the History panel (`None`: the default).
+ brush_source: Option<u64>,
}
impl Default for History {
@@ -68,6 +76,9 @@ impl History {
max_bytes: 0,
current_label: "Open".into(),
current_layers: LayerTarget::default(),
+ current_id: 0,
+ next_id: 1,
+ brush_source: None,
}
}
@@ -82,10 +93,14 @@ 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 });
+ let prev_id = std::mem::replace(&mut self.current_id, self.next_id);
+ self.next_id = self.next_id.wrapping_add(1);
+ self.undo.push_back(HistoryState { label: prev_label, doc: before, layers: prev_layers, id: prev_id });
self.clear_redo();
while self.undo.len() > self.max_states {
- if let Some(state) = self.undo.pop_front()
+ // The History Brush's source doesn't fall off (as in Photoshop): the next oldest does.
+ let pinned = self.max_states > 1 && self.undo.front().is_some_and(|s| Some(s.id) == self.brush_source);
+ if let Some(state) = self.undo.remove(usize::from(pinned))
&& let Some(tiles) = &mut self.tiles
{
tiles.remove(&state.doc);
@@ -126,7 +141,8 @@ impl History {
}
let label = std::mem::replace(&mut self.current_label, prev.label);
let layers = std::mem::replace(&mut self.current_layers, prev.layers.clone());
- self.redo.push(HistoryState { label, doc: current, layers });
+ let id = std::mem::replace(&mut self.current_id, prev.id);
+ self.redo.push(HistoryState { label, doc: current, layers, id });
Some((prev.doc, prev.layers))
}
@@ -139,7 +155,8 @@ impl History {
}
let label = std::mem::replace(&mut self.current_label, next.label);
let layers = std::mem::replace(&mut self.current_layers, next.layers.clone());
- self.undo.push_back(HistoryState { label, doc: current, layers });
+ let id = std::mem::replace(&mut self.current_id, next.id);
+ self.undo.push_back(HistoryState { label, doc: current, layers, id });
Some((next.doc, next.layers))
}
@@ -154,6 +171,59 @@ impl History {
self.undo.get(i).map(|s| s.doc.clone())
}
+ /// Id of History panel row `i`: the [`History::entries`] (0 = oldest, then the current state),
+ /// then the redo states, the next redo first ([`History::redo_labels`]). `None` past the end.
+ pub fn row_id(&self, i: usize) -> Option<u64> {
+ let past = self.undo.len();
+ match i.checked_sub(past) {
+ None => self.undo.get(i).map(|s| s.id),
+ Some(0) => Some(self.current_id),
+ Some(k) => self.redo.iter().rev().nth(k - 1).map(|s| s.id),
+ }
+ }
+
+ /// The History panel row of the state with id `id`, if it is still held.
+ pub fn row_of(&self, id: u64) -> Option<usize> {
+ let past = self.undo.len();
+ if id == self.current_id {
+ return Some(past);
+ }
+ if let Some(i) = self.undo.iter().position(|s| s.id == id) {
+ return Some(i);
+ }
+ self.redo.iter().rev().position(|s| s.id == id).map(|k| past + 1 + k)
+ }
+
+ /// Document of History panel row `i` (see [`History::row_id`]); `current` is the current
+ /// document, which the history does not hold.
+ pub fn row_doc(&self, i: usize, current: &Arc<Document>) -> Option<Arc<Document>> {
+ let past = self.undo.len();
+ match i.checked_sub(past) {
+ None => self.state(i),
+ Some(0) => Some(current.clone()),
+ Some(k) => self.redo.iter().rev().nth(k - 1).map(|s| s.doc.clone()),
+ }
+ }
+
+ /// Make row `i` the History Brush's source (the History panel's source column). It stays on
+ /// that state while older states fall off, and the state itself is kept when it would fall off
+ /// the history (by count or memory); `false` if there is no such row.
+ pub fn set_brush_source(&mut self, i: usize) -> bool {
+ let Some(id) = self.row_id(i) else { return false };
+ self.brush_source = Some(id);
+ true
+ }
+
+ /// The History Brush's source row: the oldest state held by default, else the state set with
+ /// [`History::set_brush_source`]. `None` once that state is gone (deleted, or discarded by a
+ /// new step after stepping back): as in Photoshop, there is then no source until one is set.
+ pub fn brush_source(&self) -> Option<usize> {
+ match self.brush_source {
+ None => Some(0),
+ Some(id) => self.row_of(id),
+ }
+ }
+
/// Number of past states (entries before the current one).
pub fn past_len(&self) -> usize {
self.undo.len()
@@ -241,10 +311,20 @@ impl History {
keep += 1;
}
let drop = self.undo.len() - keep;
+ let mut pinned = None;
for state in self.undo.drain(..drop) {
- tiles.remove(&state.doc);
+ // The History Brush's source is kept, as when states fall off the count limit.
+ if Some(state.id) == self.brush_source {
+ pinned = Some(state);
+ } else {
+ tiles.remove(&state.doc);
+ }
}
- drop
+ let kept = usize::from(pinned.is_some());
+ if let Some(state) = pinned {
+ self.undo.push_front(state);
+ }
+ drop - kept
}
}
@@ -337,6 +417,69 @@ mod tests {
assert_eq!(h.redo_labels().collect::<Vec<_>>(), ["A", "B"], "next redo first");
}
+ /// The History Brush source is a state, not an index: it stays on its state through undo,
+ /// redo and older states falling off, is kept when it would fall off itself, and is gone
+ /// (no source) once a new step discards it.
+ #[test]
+ fn brush_source_follows_its_state() {
+ let mut h = History::new(3);
+ let mut cur = Arc::new(base());
+ assert_eq!(h.brush_source(), Some(0), "default: the oldest state");
+ assert!(!h.set_brush_source(1), "no such row yet");
+ edit(&mut h, &mut cur, "A", |d| d.name = "a".into());
+ edit(&mut h, &mut cur, "B", |d| d.name = "b".into());
+ assert!(h.set_brush_source(1));
+ assert_eq!(h.row_doc(1, &cur).unwrap().name, "a");
+ // Undo / redo: the rows stay put, and A's state is still row 1.
+ cur = h.undo(cur).unwrap().0;
+ assert_eq!((h.brush_source(), h.row_doc(1, &cur).unwrap().name.as_str()), (Some(1), "a"));
+ assert_eq!(h.row_doc(2, &cur).unwrap().name, "b", "a redo row");
+ cur = h.redo(cur).unwrap().0;
+ // Open falls off the 3-state limit: A's state moves up to row 0 and stays the source.
+ edit(&mut h, &mut cur, "C", |d| d.name = "c".into());
+ edit(&mut h, &mut cur, "D", |d| d.name = "d".into());
+ assert_eq!(h.entries(), ["A", "B", "C", "D"]);
+ assert_eq!(h.brush_source(), Some(0));
+ // A would fall off next: it is kept, and the states after it fall off instead.
+ edit(&mut h, &mut cur, "E", |d| d.name = "e".into());
+ edit(&mut h, &mut cur, "F", |d| d.name = "f".into());
+ assert_eq!(h.entries(), ["A", "D", "E", "F"]);
+ assert_eq!((h.brush_source(), h.row_doc(0, &cur).unwrap().name.as_str()), (Some(0), "a"));
+ // A redo state as the source, discarded by a new step: no source until one is set.
+ cur = h.undo(cur).unwrap().0;
+ assert!(h.set_brush_source(3), "the greyed F row");
+ assert_eq!((h.brush_source(), h.row_doc(3, &cur).unwrap().name.as_str()), (Some(3), "f"));
+ assert!(h.row_doc(4, &cur).is_none() && h.row_id(4).is_none());
+ edit(&mut h, &mut cur, "G", |d| d.name = "g".into());
+ assert_eq!(h.brush_source(), None);
+ // The current state as the source keeps it once it becomes a past state; once it is no
+ // longer the source, it falls off as usual.
+ assert!(h.set_brush_source(3));
+ edit(&mut h, &mut cur, "H", |d| d.name = "h".into());
+ assert_eq!((h.brush_source(), h.row_doc(2, &cur).unwrap().name.as_str()), (Some(2), "g"));
+ assert!(h.set_brush_source(1));
+ edit(&mut h, &mut cur, "I", |d| d.name = "i".into());
+ assert_eq!(h.entries(), ["E", "G", "H", "I"]);
+ }
+
+ #[test]
+ fn byte_budget_keeps_the_brush_source() {
+ let mut h = History::new(50);
+ let mut cur = Arc::new(base());
+ for i in 0..5 {
+ edit(&mut h, &mut cur, &format!("paint {i}"), |d| {
+ let id = d.layers[0].id;
+ d.layer_mut(id).unwrap().surface_mut().unwrap().write_pixel(1, 1, &[i as f32 / 8.0, 0.0, 0.0, 1.0]);
+ });
+ }
+ assert!(h.set_brush_source(1));
+ h.max_bytes = 1;
+ let dropped = h.trim(&cur);
+ assert_eq!(h.entries(), ["paint 0", "paint 3", "paint 4"], "the source is kept with the last step");
+ assert_eq!(dropped, 3);
+ assert_eq!(h.brush_source(), Some(0));
+ }
+
#[test]
fn new_edit_clears_redo() {
let mut h = History::default();
diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs
index 49318f84c..4ea94ee21 100644
--- a/crates/ui-egui/src/panels.rs
+++ b/crates/ui-egui/src/panels.rs
@@ -2799,6 +2799,7 @@ fn history(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
let entries = st.history.entries();
let current = entries.len() - 1;
let redo: Vec<String> = st.history.redo_labels().map(str::to_string).collect();
+ let source = st.history.brush_source();
// Snapshot row (Photoshop shows the document's opening state with a thumbnail).
{
let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), 38.0), Sense::hover());
@@ -2814,6 +2815,7 @@ fn history(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
ui.painter().line_segment([rect.left_bottom(), rect.right_bottom()], Stroke::new(1.0, t.separator));
}
let mut target: Option<isize> = None;
+ let mut set_source: Option<usize> = None;
let all = entries.iter().map(|e| (e.clone(), false)).chain(redo.iter().map(|e| (e.clone(), true)));
// The dock gives History a fixed height: the rows scroll above the footer.
let footer = if t.pro { widgets::footer_height(ui) + ui.spacing().item_spacing.y } else { 0.0 };
@@ -2843,11 +2845,20 @@ fn history(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
if is_redo { t.text_faint } else { t.icon },
);
ui.painter().text(pos2(rect.left() + 58.0, rect.center().y), Align2::LEFT_CENTER, &e, egui::FontId::proportional(12.0), color);
+ if history_source_column(ui, rect, i, source == Some(i)) {
+ set_source = Some(i);
+ }
if resp.clicked() {
target = Some(i as isize - current as isize);
}
}
});
+ if let Some(i) = set_source
+ && let Err(e) = app.run("history.setSource", json!({"state": i}))
+ {
+ app.ui.status = e;
+ app.ui.status_error = true;
+ }
let mut footer_cmd: Option<&str> = None;
if t.pro {
let can_delete = app.session.is_enabled("history.deleteState");
@@ -2881,6 +2892,21 @@ fn history(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
}
}
+/// The History panel's source column at the left of a state row: the History Brush icon on the
+/// source state; a click makes the row the source (`history.setSource`). It sits above the row, so
+/// the click doesn't also step to the state.
+fn history_source_column(ui: &mut egui::Ui, row: Rect, i: usize, is_source: bool) -> bool {
+ let t = Tokens::get(ui.ctx());
+ let cell = Rect::from_min_size(row.min, vec2(24.0, row.height()));
+ let resp = ui.interact(cell, ui.id().with(("history-source", i)), Sense::click()).on_hover_text(tl!("Sets the source for the history brush"));
+ if is_source {
+ icons::paint(ui, cell.shrink(4.0), icons::tool_icon(Tool::HistoryBrush), 12.0, t.icon);
+ } else if resp.hovered() {
+ icons::paint(ui, cell.shrink(4.0), icons::tool_icon(Tool::HistoryBrush), 12.0, t.text_faint);
+ }
+ resp.clicked()
+}
+
// ----------------------------------------------------------------------------- properties
/// Floating Properties card anchored to the canvas' top-right corner.
@@ -4082,6 +4108,30 @@ mod history_transform_tests {
assert_eq!(st.history.entries().len(), steps - 1, "trash deletes the current state");
assert!(!st.history.can_redo(), "and it can't be redone");
}
+
+ /// The source column at the left of each state (#2966): a click makes that state the History
+ /// Brush's source through `history.setSource`, without stepping to it.
+ #[test]
+ fn history_source_column_sets_the_history_brush_source() {
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({"width": 200, "height": 150})).unwrap();
+ app.run("edit.fill", json!({"color": "#ff0000"})).unwrap();
+ app.run("edit.fill", json!({"color": "#00ff00"})).unwrap();
+ let mut h = Harness::builder().with_size(vec2(300.0, 400.0)).build_ui_state(|ui, app: &mut PhotocraftApp| history(app, ui), app);
+ h.run_steps(2);
+ // The column cells are the only 24 pt squares, one per state, top to bottom.
+ let mut cells: Vec<Rect> = h
+ .ctx
+ .viewport(|v| v.prev_pass.widgets.layers().flat_map(|(_, w)| w.iter()).filter(|w| w.rect.size() == vec2(24.0, 24.0)).map(|w| w.rect).collect());
+ cells.sort_by(|a, b| a.center().y.total_cmp(&b.center().y));
+ cells.dedup();
+ assert_eq!(cells.len(), 3, "Open, Fill, Fill: {cells:?}");
+ assert_eq!(h.state().session.active().unwrap().history.brush_source(), Some(0), "the default source");
+ click(&mut h, cells[1].center());
+ let st = h.state().session.active().unwrap();
+ assert_eq!(st.history.brush_source(), Some(1), "the clicked state is the source");
+ assert_eq!((st.history.entries().len(), st.history.can_redo()), (3, false), "and the document did not step back");
+ }
}
#[cfg(test)]
diff --git a/crates/ui-egui/src/retouch_ui.rs b/crates/ui-egui/src/retouch_ui.rs
index 8e78a5dd9..e018584e2 100644
--- a/crates/ui-egui/src/retouch_ui.rs
+++ b/crates/ui-egui/src/retouch_ui.rs
@@ -459,7 +459,7 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo
crate::widgets::value_field(ui, &mut o.cr_tolerance, 0.0..=100.0, "%", 62.0);
crate::widgets::checkbox(ui, &mut o.cr_anti_alias, tl!("Anti-alias"));
}
- Tool::HistoryBrush => opt(ui, "Paints from the document's opening state"),
+ Tool::HistoryBrush => opt(ui, tl!("Paints from the History panel's source state")),
Tool::QuickSelection => {
crate::widgets::checkbox(ui, &mut o.sample_all_layers, tl!("Sample All Layers"));
crate::widgets::checkbox(ui, &mut o.enhance_edge, tl!("Enhance Edge"));