History: tool and preset names, Frame from Layers as one step, undo/redo restore the targeted layers (#513, #528, #446, #496, #495) (#551)

* Elliptical Marquee selections record "Elliptical Marquee" in History (#513)

Both marquee tools commit through `select.rect`, which named every step
"Rectangular Marquee" whatever its `ellipse` param. The step is now named
after the tool that made it; the rectangular marquee keeps its name.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Preset filters record their own names in History (#528)

Blur, Blur More, Sharpen, Sharpen More, Sharpen Edges and Despeckle run
a generic algorithm with fixed parameters and recorded its name
("Gaussian Blur", "Unsharp Mask", "Surface Blur"). The presets now live
in one table with their names, used for the history step and the job
progress text; Gaussian Blur, Unsharp Mask and Surface Blur keep theirs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Vertical type command no longer claims it renders horizontally (#446)

Vertical type has rendered in columns since #199, but the params text of
`type.orientation.vertical` still said it was "rendered horizontally for
now". It now documents the same `{"layer":id?}` as Horizontal.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Frame from Layers is one history step (#496)

It grouped the layers through `layer.new.groupFromLayers` (its own
"Group Layers" step) and then recorded "Frame from Layers", so one undo
left the group behind. The grouping step is now folded into the frame
step with `purge_last`, as Transform Again on a copy does; if the group
can't be framed, the grouping is undone with nothing left to redo.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Undo and redo restore the layers each history state targeted (#495)

History states held only the document, so after undo or redo the active
layer stayed whatever it was: redoing New Layer left the old layer
active (a Fill then painted it), and undoing Delete Layer left the
restored layer unselected. Each state now also keeps the active and
selected layers it had when it was created (when the document was
opened, or right after the step that made it), and undo and redo target
them again where they still exist. Selecting a layer is still not a
step and doesn't change any state's target, so selecting another layer
and then undoing or redoing goes back to that state's target, as the
reference app's Step Backward does.

The History panel lists redo labels from a new `redo_labels` accessor
instead of cloning and replaying the history every frame.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
This commit is contained in:
BFlatandClaude Opus 5.5 authored and GitHub committed 2026-10-07 13:54:10 +07:00
1 parent bd1322a5e4
commit e30b121969
13 files changed
+302 -62

No files matched your search

+1 -1
View File
@@ -180,7 +180,7 @@ fn compound<R>(s: &mut Session, label: &str, f: impl FnOnce(&mut Session) -> Res
st.history = history;
match r {
Ok(v) => {
st.history.record(label, before);
st.history.record(label, before, st.layer_target());
st.history.trim(&st.doc);
st.coalesce = None;
Ok(v)
+1 -1
View File
@@ -331,7 +331,7 @@ fn build() -> Vec<CommandSpec> {
// Options bar: anti-aliased ellipse edges (4x4 supersampled) and Feather (applied to the new shape only).
let aa = p.get("antiAlias").and_then(Value::as_bool).unwrap_or(true);
let feather = p.get("feather").and_then(Value::as_f64).unwrap_or(0.0).clamp(0.0, 1000.0) as f32;
s.edit("Rectangular Marquee", |doc, _| {
s.edit(if ellipse { "Elliptical Marquee" } else { "Rectangular Marquee" }, |doc, _| {
let area = doc.bounds();
// A marquee dragged past the canvas stops at its edge (Photoshop); the ellipse
// keeps the dragged shape and is only cut there.
+45 -9
View File
@@ -36,18 +36,28 @@ fn preserve(p: &Value) -> Preserve {
if s(p, "preserve", "squareness") == "roundness" { Preserve::Roundness } else { Preserve::Squareness }
}
/// One-step presets (no dialog): the history step they record (their own name, not the generic
/// algorithm's) and the fixed parameters, tuned to match the reference app's fixed-strength filters.
fn preset(id: &str) -> Option<(&'static str, FilterParams)> {
Some(match id {
"filter.blur.blur" => ("Blur", FilterParams::GaussianBlur { radius: 0.6 }),
"filter.blur.blurMore" => ("Blur More", FilterParams::GaussianBlur { radius: 1.4 }),
"filter.sharpen.sharpen" => ("Sharpen", FilterParams::UnsharpMask { amount: 60.0, radius: 0.5, threshold: 0.0 }),
"filter.sharpen.sharpenMore" => ("Sharpen More", FilterParams::UnsharpMask { amount: 150.0, radius: 0.6, threshold: 0.0 }),
"filter.sharpen.sharpenEdges" => ("Sharpen Edges", FilterParams::UnsharpMask { amount: 100.0, radius: 0.8, threshold: 6.0 }),
"filter.noise.despeckle" => ("Despeckle", FilterParams::SurfaceBlur { radius: 2.0, threshold: 12.0 }),
_ => return None,
})
}
/// Builds the algorithm parameters for a filter command id from JSON params
/// (Photoshop dialog units).
pub fn params_for(id: &str, p: &Value) -> Option<FilterParams> {
if let Some((_, fp)) = preset(id) {
return Some(fp);
}
Some(match id {
"filter.blur.gaussianBlur" => FilterParams::GaussianBlur { radius: f(p, "radius", 1.0).clamp(0.1, 1000.0) },
// One-step presets (no dialog), tuned to match Photoshop's fixed-strength filters.
"filter.blur.blur" => FilterParams::GaussianBlur { radius: 0.6 },
"filter.blur.blurMore" => FilterParams::GaussianBlur { radius: 1.4 },
"filter.sharpen.sharpen" => FilterParams::UnsharpMask { amount: 60.0, radius: 0.5, threshold: 0.0 },
"filter.sharpen.sharpenMore" => FilterParams::UnsharpMask { amount: 150.0, radius: 0.6, threshold: 0.0 },
"filter.sharpen.sharpenEdges" => FilterParams::UnsharpMask { amount: 100.0, radius: 0.8, threshold: 6.0 },
"filter.noise.despeckle" => FilterParams::SurfaceBlur { radius: 2.0, threshold: 12.0 },
"filter.blur.boxBlur" => FilterParams::BoxBlur { radius: f(p, "radius", 1.0).clamp(1.0, 2000.0) },
"filter.blur.motionBlur" => FilterParams::MotionBlur { angle: f(p, "angle", 0.0), distance: f(p, "distance", 10.0).clamp(1.0, 2000.0) },
"filter.blur.radialBlur" => FilterParams::RadialBlur {
@@ -189,7 +199,8 @@ pub(crate) fn run_filter(s: &mut Session, id: &str, p: &Value) -> Result<Value>
Some(l) => photocraft_doc::LayerId(l),
None => s.active().and_then(|d| d.active_layer).ok_or(EngineError::Other("no active layer".into()))?,
};
let label = fp.label().to_string();
let label = preset(id).map_or(fp.label(), |(name, _)| name).to_string();
let msg = label.clone();
let mut params = p.clone();
if let Value::Object(m) = &mut params {
m.remove("__kind");
@@ -203,7 +214,6 @@ pub(crate) fn run_filter(s: &mut Session, id: &str, p: &Value) -> Result<Value>
s,
&label,
move |doc, _, ctx| {
let msg = fp.label().to_string();
let filter = |surf: &photocraft_raster::Surface, fp: &FilterParams, area, bounds, sel: Option<&photocraft_raster::Surface>, extent| {
ctx.stage(0.0, 1.0, &msg, |ctl| algo::apply_in_with(surf, fp, area, bounds, sel, extent, ctl)).ok_or(EngineError::Cancelled)
};
@@ -424,6 +434,32 @@ mod tests {
}
}
#[test]
fn preset_filters_record_their_own_name() {
// #528: one-step presets run a generic algorithm but name the step after themselves;
// the generic commands keep the algorithm's name.
let specs = specs();
for (id, name) in [
("filter.blur.blur", "Blur"),
("filter.blur.blurMore", "Blur More"),
("filter.sharpen.sharpen", "Sharpen"),
("filter.sharpen.sharpenMore", "Sharpen More"),
("filter.sharpen.sharpenEdges", "Sharpen Edges"),
("filter.noise.despeckle", "Despeckle"),
("filter.blur.gaussianBlur", "Gaussian Blur"),
("filter.sharpen.unsharpMask", "Unsharp Mask"),
("filter.blur.surfaceBlur", "Surface Blur"),
] {
let mut s = session();
let steps = s.active().unwrap().history.past_len();
s.execute(id, json!({})).unwrap();
let h = &s.active().unwrap().history;
assert_eq!((h.past_len(), h.undo_label()), (steps + 1, Some(name)), "{id}");
let label = specs.iter().find(|c| c.id == id).unwrap().label;
assert_eq!(label.trim_end_matches('…'), name, "{id}: the step is named like the command");
}
}
#[test]
fn specs_are_complete_and_documented() {
let specs = specs();
+43 -1
View File
@@ -32,13 +32,35 @@ fn clip_mask(rect: Rect) -> LayerMask {
mask
}
/// Groups the selected layers, then turns the group into a frame, as one history step: one undo
/// takes the whole command back (#496).
fn frame_from_layers(s: &mut Session, p: &Value) -> Result<Value> {
// Group the selected layers (one step), then turn the group into a frame.
let mut gp = serde_json::Map::new();
if let Some(name) = p.get("name") {
gp.insert("name".into(), name.clone());
}
let grouped = s.execute("layer.new.groupFromLayers", Value::Object(gp))?;
match frame_group(s, &grouped) {
Ok(r) => {
// Fold the grouping step into the frame step.
if let Some(st) = s.active_mut() {
st.history.purge_last();
}
Ok(r)
}
Err(e) => {
// The group couldn't be framed: take the grouping back, leaving nothing to redo.
s.undo();
if let Some(st) = s.active_mut() {
st.history.clear_redo();
}
Err(e)
}
}
}
/// Clips the group `layer.new.groupFromLayers` returned (`grouped`) to its contents' bounds.
fn frame_group(s: &mut Session, grouped: &Value) -> Result<Value> {
let gid = LayerId(grouped.get("layer").and_then(Value::as_u64).ok_or_else(|| EngineError::Other("grouping did not return a layer".into()))?);
let d = s.active().ok_or(EngineError::NoDocument)?;
let rect =
@@ -109,6 +131,26 @@ mod tests {
assert_eq!(st.history.entries().last().map(|e| e.as_str()), Some("Frame from Layers"));
}
#[test]
fn frame_from_layers_is_one_history_step() {
// #496: grouping and framing undo together.
let (mut s, a, b) = session();
let entries = s.active().unwrap().history.entries();
let layers = |s: &Session| s.active().unwrap().doc.layers.iter().map(|l| l.id).collect::<Vec<_>>();
let before = layers(&s);
s.execute("layer.select", json!({"layer": a.0, "mode": "replace"})).unwrap();
s.execute("layer.select", json!({"layer": b.0, "mode": "add"})).unwrap();
let gid = LayerId(s.execute("layer.new.frameFromLayers", json!({})).unwrap()["layer"].as_u64().unwrap());
let mut framed = entries.clone();
framed.push("Frame from Layers".into());
assert_eq!(s.active().unwrap().history.entries(), framed);
assert!(s.undo());
assert_eq!(s.active().unwrap().history.entries(), entries);
assert_eq!(layers(&s), before, "one undo leaves no group behind");
assert!(s.redo());
assert!(s.active().unwrap().doc.layer(gid).is_some_and(|g| g.mask.is_some()), "redo brings back the framed group");
}
#[test]
fn needs_a_selected_layer() {
let mut s = Session::new();
+11
View File
@@ -157,6 +157,17 @@ fn progress_is_monotonic_and_reaches_one() {
assert_eq!((info.state, info.progress), ("done", 1.0));
}
#[test]
fn a_preset_filter_job_is_named_after_the_preset() {
// #528: the job (progress UI) and its history step say "Blur More", not "Gaussian Blur".
let mut s = session(300, 200);
let id = job(s.start("filter.blur.blurMore", json!({})).unwrap());
let e = wait_event(&mut s, id);
assert!(matches!(e.outcome, JobOutcome::Done(_)), "{e:?}");
assert_eq!(e.label, "Blur More");
assert_eq!(s.active().unwrap().history.undo_label(), Some("Blur More"));
}
/// A fake document job that runs until `gate` opens (or it is cancelled), then inverts nothing
/// but records one undo step named "Gated Job".
pub(super) fn gated_job(s: &mut Session, gate: &Arc<std::sync::atomic::AtomicBool>) -> JobId {
+11 -1
View File
@@ -58,7 +58,8 @@ pub fn set_selection(s: &mut Session, ids: Vec<LayerId>, active: Option<LayerId>
Ok(())
}
/// After a structural edit, make `ids` the selection (dropping any that no longer exist).
/// After a structural edit, make `ids` the selection (dropping any that no longer exist), which
/// is also what the edit's history state targets.
fn reselect(s: &mut Session, ids: Vec<LayerId>, active: Option<LayerId>) {
if let Some(st) = s.active_mut() {
st.selected_layers = ids;
@@ -67,6 +68,8 @@ fn reselect(s: &mut Session, ids: Vec<LayerId>, active: Option<LayerId>) {
st.layer_anchor = Some(a);
}
crate::fix_selection(st);
let layers = st.layer_target();
st.history.set_current_layers(layers);
}
}
@@ -1023,18 +1026,22 @@ mod tests {
let b = rect_layer(&mut s, Rect::new(12, 0, 32, 10)); // 20 wide
let c = rect_layer(&mut s, Rect::new(70, 0, 100, 10)); // 30 wide
select_all(&mut s, &[a, b, c]);
// Undo targets the layers its state had when it was created (#495): reselect.
assert!(s.is_enabled("layer.distribute.leftEdges"));
s.execute("layer.distribute.leftEdges", json!({})).unwrap();
assert_eq!(bounds(&s, b), Rect::new(35, 0, 55, 10), "left edges 0, 35, 70");
s.undo();
select_all(&mut s, &[a, b, c]);
s.execute("layer.distribute.horizontalCenters", json!({})).unwrap();
// centres 5 and 85 → middle centre 45
assert_eq!(bounds(&s, b), Rect::new(35, 0, 55, 10));
s.undo();
select_all(&mut s, &[a, b, c]);
s.execute("layer.distribute.rightEdges", json!({})).unwrap();
// right edges 10 and 100 → 55
assert_eq!(bounds(&s, b), Rect::new(35, 0, 55, 10));
s.undo();
select_all(&mut s, &[a, b, c]);
s.execute("layer.distribute.horizontally", json!({})).unwrap();
// span 100, widths 60 → gaps of 20: b at 30..50
assert_eq!(bounds(&s, b), Rect::new(30, 0, 50, 10));
@@ -1053,12 +1060,15 @@ mod tests {
// span 80, heights 34 → gaps 23: b at 33..37
assert_eq!(bounds(&s, b), Rect::new(0, 33, 10, 37));
s.undo();
select_all(&mut s, &[a, b, c]);
s.execute("layer.distribute.topEdges", json!({})).unwrap();
assert_eq!(bounds(&s, b), Rect::new(0, 30, 10, 34));
s.undo();
select_all(&mut s, &[a, b, c]);
s.execute("layer.distribute.bottomEdges", json!({})).unwrap();
assert_eq!(bounds(&s, b), Rect::new(0, 41, 10, 45));
s.undo();
select_all(&mut s, &[a, b, c]);
s.execute("layer.distribute.verticalCenters", json!({})).unwrap();
// centres 5 and 70 → 37.5, b is 4 tall → top 35.5 → rounds to 36 (35 for ties down)
let y0 = bounds(&s, b).y0;
+27 -8
View File
@@ -89,7 +89,7 @@ mod wia_cmds;
use std::sync::Arc;
use photocraft_doc::{Document, LayerId};
use photocraft_ops::History;
use photocraft_ops::{History, LayerTarget};
use serde_json::Value;
pub use commands::{CommandSpec, command_specs};
@@ -140,7 +140,8 @@ pub struct DocState {
/// `selected_layers` when set.
pub active_layer: Option<LayerId>,
/// Every selected layer in the Layers panel (⌘/⇧-click), in selection order. Like
/// `active_layer` this is UI state, not history; see [`DocState::selected_layers`].
/// `active_layer`, selecting is not a history step, but undo and redo restore the layers each
/// state targeted when it was created; see [`DocState::selected_layers`].
pub selected_layers: Vec<LayerId>,
/// Anchor of ⇧-click range selection (the last plainly or ⌘-clicked layer).
pub layer_anchor: Option<LayerId>,
@@ -164,9 +165,11 @@ pub struct DocState {
impl DocState {
pub fn new(doc: Document, path: Option<String>) -> Self {
let active_layer = doc.top_layer();
let mut history = History::default();
history.set_current_layers(LayerTarget { active: active_layer, selected: active_layer.into_iter().collect() });
Self {
doc: Arc::new(doc),
history: History::default(),
history,
active_layer,
selected_layers: active_layer.into_iter().collect(),
layer_anchor: active_layer,
@@ -194,6 +197,10 @@ impl DocState {
pub fn is_dirty(&self) -> bool {
self.revision != self.saved_revision
}
/// The targeted layers, as history stores them with each state.
fn layer_target(&self) -> LayerTarget {
LayerTarget { active: self.active_layer, selected: self.selected_layers.clone() }
}
}
/// App-wide tool state that commands read (foreground colour, brush…).
@@ -376,9 +383,12 @@ impl Session {
channel_cmds::fix_view(st);
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() {
st.history.record(label, before);
st.history.record(label, before, layers);
st.history.trim(&st.doc);
} else {
st.history.set_current_layers(layers);
}
st.coalesce = key;
st.revision += 1;
@@ -413,9 +423,9 @@ impl Session {
let Some(st) = self.active_mut() else { return false };
st.coalesce = None;
match st.history.undo(st.doc.clone()) {
Some(d) => {
Some((d, layers)) => {
st.doc = d;
fix_active(st);
restore_target(st, layers);
st.revision += 1;
st.last_damage = None;
true
@@ -431,9 +441,9 @@ impl Session {
let Some(st) = self.active_mut() else { return false };
st.coalesce = None;
match st.history.redo(st.doc.clone()) {
Some(d) => {
Some((d, layers)) => {
st.doc = d;
fix_active(st);
restore_target(st, layers);
st.revision += 1;
st.last_damage = None;
true
@@ -443,6 +453,15 @@ impl Session {
}
}
/// Undo / redo: target the layers the restored state targeted, as far as they still exist.
fn restore_target(st: &mut DocState, layers: LayerTarget) {
if layers.active.is_some_and(|id| st.doc.layer(id).is_some()) {
st.active_layer = layers.active;
st.selected_layers = layers.selected;
}
fix_active(st);
}
fn fix_active(st: &mut DocState) {
if st.active_layer.is_none_or(|id| st.doc.layer(id).is_none()) {
st.active_layer = st.doc.top_layer();
+67
View File
@@ -151,6 +151,73 @@ fn marquee_dragged_past_the_canvas_stops_at_its_edge() {
assert_eq!(bounds(&mut s), Value::Null);
}
#[test]
fn marquee_steps_are_named_after_their_tool() {
// #513: the elliptical marquee shares `select.rect` but records its own step name.
let mut s = session_with_doc();
let last = |s: &Session| s.active().unwrap().history.undo_label().map(str::to_string);
s.execute("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 10, "ellipse": true})).unwrap();
assert_eq!(last(&s).as_deref(), Some("Elliptical Marquee"));
s.execute("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 10})).unwrap();
assert_eq!(last(&s).as_deref(), Some("Rectangular Marquee"));
}
#[test]
fn undo_and_redo_restore_the_targeted_layers() {
// #495: each history state brings back the layers it targeted when it was created.
let mut s = session_with_doc();
let target = |s: &Session| {
let st = s.active().unwrap();
(st.active_layer.unwrap(), st.selected_layers())
};
let select = |s: &mut Session, id: LayerId, mode: &str| {
let steps = s.active().unwrap().history.past_len();
s.execute("layer.select", json!({"layer": id.0, "mode": mode})).unwrap();
assert_eq!(s.active().unwrap().history.past_len(), steps, "selecting is not a step");
};
let bg = target(&s).0;
s.execute("layer.new.layer", json!({})).unwrap();
let new = target(&s).0;
assert!(s.undo());
assert_eq!(target(&s), (bg, vec![bg]), "the new document's target");
assert!(s.redo());
assert_eq!(target(&s), (new, vec![new]), "redo targets the new layer again");
// So Fill paints the new layer, not the background.
s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap();
let doc = &s.active().unwrap().doc;
assert!(!doc.layer(new).unwrap().surface().unwrap().content_bounds().is_empty());
let mut v = [0.0f32; 4];
doc.layer(bg).unwrap().surface().unwrap().read_pixel(5, 5, &mut v);
assert_eq!(v, [1.0; 4], "the background is untouched");
// Selecting another layer doesn't change what a state targets: undo returns to New Layer's
// target and redo to Fill's.
select(&mut s, bg, "replace");
assert!(s.undo());
assert_eq!(target(&s), (new, vec![new]));
select(&mut s, bg, "replace");
assert!(s.redo());
assert_eq!(target(&s), (new, vec![new]), "redo targets the filled layer");
// Undoing a delete targets the restored layer.
s.execute("layer.delete", json!({})).unwrap();
assert_eq!(target(&s).0, bg);
assert!(s.undo());
assert_eq!(target(&s), (new, vec![new]));
// A multi-layer target comes back too: a step taken with both layers selected...
select(&mut s, bg, "add");
s.execute("select.all", json!({})).unwrap();
s.execute("layer.new.layer", json!({})).unwrap();
assert!(s.undo());
assert_eq!(target(&s), (bg, vec![bg, new]));
// ...and the copies a multi-layer duplicate selects after its edit.
s.execute("layer.duplicate", json!({})).unwrap();
let copies = target(&s);
assert_eq!(copies.1.len(), 2);
select(&mut s, bg, "replace");
assert!(s.undo());
assert!(s.redo());
assert_eq!(target(&s), copies);
}
#[test]
fn selection_modes() {
let mut s = session_with_doc();
+1 -8
View File
@@ -519,14 +519,7 @@ pub fn specs() -> Vec<CommandSpec> {
spec!("type.antiAlias.windowsLcd", "Windows LCD", &["Type", "Anti-Alias"], LP, has_text, |s, p| set_aa(s, p, AntiAlias::WindowsLcd)),
spec!("type.antiAlias.windows", "Windows", &["Type", "Anti-Alias"], LP, has_text, |s, p| set_aa(s, p, AntiAlias::Windows)),
spec!("type.orientation.horizontal", "Horizontal", &["Type", "Orientation"], LP, has_text, |s, p| set_orientation(s, p, Orientation::Horizontal)),
spec!(
"type.orientation.vertical",
"Vertical",
&["Type", "Orientation"],
r##"{"layer":id?} (stored and saved; rendered horizontally for now)"##,
has_text,
|s, p| set_orientation(s, p, Orientation::Vertical)
),
spec!("type.orientation.vertical", "Vertical", &["Type", "Orientation"], LP, has_text, |s, p| set_orientation(s, p, Orientation::Vertical)),
spec!("type.openType.standardLigatures", "Standard Ligatures", &["Type", "OpenType"], OT, has_text, |s, p| toggle_opentype(s, p, "liga")),
spec!("type.openType.contextualAlternates", "Contextual Alternates", &["Type", "OpenType"], OT, has_text, |s, p| toggle_opentype(s, p, "calt")),
spec!("type.openType.discretionaryLigatures", "Discretionary Ligatures", &["Type", "OpenType"], OT, has_text, |s, p| toggle_opentype(s, p, "dlig")),
@@ -73,6 +73,15 @@ fn point_and_paragraph_conversion_keep_the_text_in_place() {
}
}
/// Issue #446: vertical type renders vertically (see the test below), so the command's description
/// must not claim it stays horizontal.
#[test]
fn vertical_orientation_params_match_horizontal() {
let specs = specs();
let params = |id: &str| specs.iter().find(|c| c.id == id).unwrap().params;
assert_eq!(params("type.orientation.vertical"), params("type.orientation.horizontal"));
}
/// Issue #199: vertical type is laid out top to bottom, columns right to left, on the canvas.
#[test]
fn vertical_orientation_renders_columns_inside_the_canvas() {
+84 -20
View File
@@ -13,12 +13,23 @@
use std::collections::{HashSet, VecDeque};
use std::sync::Arc;
use photocraft_doc::Document;
use photocraft_doc::{Document, LayerId};
/// The layers a state targeted when it was created: the active ("key") layer and every selected
/// layer. Undo and redo bring them back with the state's document, as the reference app does;
/// selecting layers is not a step of its own, so it doesn't change a state's target.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct LayerTarget {
pub active: Option<LayerId>,
pub selected: Vec<LayerId>,
}
#[derive(Clone, Debug)]
pub struct HistoryState {
pub label: String,
pub doc: Arc<Document>,
/// The layers targeted when this state was created.
pub layers: LayerTarget,
}
#[derive(Clone, Debug)]
@@ -32,6 +43,8 @@ pub struct History {
pub max_bytes: usize,
/// Label of the step that produced the current document.
current_label: String,
/// The layers targeted when the current document was created (opened or edited).
current_layers: LayerTarget,
}
impl Default for History {
@@ -42,13 +55,22 @@ impl Default for History {
impl History {
pub fn new(max_states: usize) -> Self {
Self { undo: VecDeque::new(), redo: Vec::new(), max_states: max_states.max(1), max_bytes: 0, current_label: "Open".into() }
Self {
undo: VecDeque::new(),
redo: Vec::new(),
max_states: max_states.max(1),
max_bytes: 0,
current_label: "Open".into(),
current_layers: LayerTarget::default(),
}
}
/// Record that `before` was replaced by a new current document via step `label`.
pub fn record(&mut self, label: impl Into<String>, before: Arc<Document>) {
/// Record that `before` was replaced by a new current document via step `label`, which left
/// `layers` targeted.
pub fn record(&mut self, label: impl Into<String>, before: Arc<Document>, layers: LayerTarget) {
let prev_label = std::mem::replace(&mut self.current_label, label.into());
self.undo.push_back(HistoryState { label: prev_label, doc: before });
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.redo.clear();
while self.undo.len() > self.max_states {
self.undo.pop_front();
@@ -67,20 +89,34 @@ impl History {
pub fn redo_label(&self) -> Option<&str> {
self.redo.last().map(|s| s.label.as_str())
}
/// Undo: returns the document to make current.
pub fn undo(&mut self, current: Arc<Document>) -> Option<Arc<Document>> {
let prev = self.undo.pop_back()?;
let label = std::mem::replace(&mut self.current_label, prev.label);
self.redo.push(HistoryState { label, doc: current });
Some(prev.doc)
/// Labels of the redo states, the next redo first (the History panel's greyed rows).
pub fn redo_labels(&self) -> impl Iterator<Item = &str> {
self.redo.iter().rev().map(|s| s.label.as_str())
}
pub fn redo(&mut self, current: Arc<Document>) -> Option<Arc<Document>> {
/// Set the layers the current document targets from its creation on: when it is first
/// opened, or when its step coalesces or changes the selection after recording.
pub fn set_current_layers(&mut self, layers: LayerTarget) {
self.current_layers = layers;
}
/// 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)> {
let prev = self.undo.pop_back()?;
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 });
Some((prev.doc, prev.layers))
}
/// Redo: the mirror of [`Self::undo`].
pub fn redo(&mut self, current: Arc<Document>) -> Option<(Arc<Document>, LayerTarget)> {
let next = self.redo.pop()?;
let label = std::mem::replace(&mut self.current_label, next.label);
self.undo.push_back(HistoryState { label, doc: current });
Some(next.doc)
let layers = std::mem::replace(&mut self.current_layers, next.layers.clone());
self.undo.push_back(HistoryState { label, doc: current, layers });
Some((next.doc, next.layers))
}
/// Entries for a History panel: past labels oldest→newest, then the current label.
@@ -196,7 +232,7 @@ mod tests {
let mut d = (**cur).clone();
f(&mut d);
*cur = Arc::new(d);
h.record(label, before);
h.record(label, before, LayerTarget::default());
}
#[test]
@@ -208,14 +244,39 @@ mod tests {
});
assert_eq!(cur.layers.len(), 2);
assert_eq!(h.undo_label(), Some("New Layer"));
cur = h.undo(cur).unwrap();
cur = h.undo(cur).unwrap().0;
assert_eq!(cur.layers.len(), 1);
assert_eq!(h.redo_label(), Some("New Layer"));
cur = h.redo(cur).unwrap();
cur = h.redo(cur).unwrap().0;
assert_eq!(cur.layers.len(), 2);
assert!(h.redo(cur.clone()).is_none());
}
#[test]
fn undo_and_redo_return_the_layers_each_state_targeted_when_created() {
let mut h = History::default();
let open = Arc::new(base());
let bg = open.layers[0].id;
let target = |id: LayerId| LayerTarget { active: Some(id), selected: vec![id] };
h.set_current_layers(target(bg));
// New Layer targets the new layer; the background is then selected (not a step) and filled.
let mut d = (*open).clone();
let new = d.insert_above(None, Layer::raster("L", d.pixel_format()));
let layered = Arc::new(d);
h.record("New Layer", open, target(new));
let mut d = (*layered).clone();
d.name = "filled".into();
h.record("Fill", layered, target(bg));
let (d, layers) = h.undo(Arc::new(d)).unwrap();
assert_eq!(layers, target(new), "New Layer's state targeted the new layer when created");
let (d, layers) = h.undo(d).unwrap();
assert_eq!(layers, target(bg), "the opened document's target");
let (d, layers) = h.redo(d).unwrap();
assert_eq!(layers, target(new));
let (_, layers) = h.redo(d).unwrap();
assert_eq!(layers, target(bg), "Fill's state targeted the background");
}
#[test]
fn state_accessor_matches_entries() {
let mut h = History::default();
@@ -227,6 +288,9 @@ mod tests {
assert!(Arc::ptr_eq(&h.state(0).unwrap(), &open));
assert_eq!(h.state(1).unwrap().name, "a");
assert!(h.state(2).is_none(), "the current document is not held");
cur = h.undo(cur).unwrap().0;
h.undo(cur).unwrap();
assert_eq!(h.redo_labels().collect::<Vec<_>>(), ["A", "B"], "next redo first");
}
#[test]
@@ -234,7 +298,7 @@ mod tests {
let mut h = History::default();
let mut cur = Arc::new(base());
edit(&mut h, &mut cur, "A", |d| d.name = "a".into());
cur = h.undo(cur).unwrap();
cur = h.undo(cur).unwrap().0;
edit(&mut h, &mut cur, "B", |d| d.name = "b".into());
assert!(!h.can_redo());
assert_eq!(h.entries(), vec!["Open".to_string(), "B".to_string()]);
@@ -248,7 +312,7 @@ mod tests {
edit(&mut h, &mut cur, &format!("step {i}"), |d| d.name = format!("{i}"));
}
let mut n = 0;
while let Some(d) = h.undo(cur.clone()) {
while let Some((d, _)) = h.undo(cur.clone()) {
cur = d;
n += 1;
}
+1 -13
View File
@@ -1801,19 +1801,7 @@ fn history(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
let doc = st.doc.clone();
let entries = st.history.entries();
let current = entries.len() - 1;
let redo: Vec<String> = {
let mut v = Vec::new();
let mut h = st.history.clone();
let mut d = st.doc.clone();
while let Some(label) = h.redo_label().map(str::to_string) {
v.push(label);
match h.redo(d.clone()) {
Some(n) => d = n,
None => break,
}
}
v
};
let redo: Vec<String> = st.history.redo_labels().map(str::to_string).collect();
// 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());
+1
View File
@@ -281,6 +281,7 @@ pub enum LayerContent {
- **Every mutation is an `Op`**, such as `SetLayerProps`, `PaintTiles{layer, tiles_before, tiles_after}`, `AddLayer`, `MoveLayer` or `ApplyFilter`.
- **A command produces a `Transaction` of ops** with a label ("Gaussian Blur").
- **History stores transactions.** Because tiles are `Arc`-shared, "before" states cost only the tiles that actually changed. Undo means swapping `Arc`s, so no pixel copies are made.
- **Each state remembers its targeted layers** (the active layer and the layer selection, as they were when the state was created: when the document was opened, or right after the step that made it). Selecting layers is not a step and doesn't change any state's target, but undo and redo target the restored state's layers again, as Photoshop does.
- **Brush strokes** accumulate into one transaction per stroke. Tiles are published incrementally with damage regions, so the viewport updates live.
- **Snapshots for readers.** After each committed op the engine publishes a new `Arc<DocSnapshot>` through `arc-swap`. The UI, background jobs (filters, AI inference, export) and autosave read snapshots without locks.
- **Background jobs** compute from snapshot N and commit as a transaction. If the doc changed meanwhile, the job rebases, meaning it re-targets the same layer id if it still exists, or reports a conflict.