feat(photocraft): 让编辑来源随撤销和重做恢复

This commit is contained in:
WuYongJie 2026-12-05 20:26:00 +08:00
parent b7bc21aaf1
commit 1e2efaa271
9 changed files with 321 additions and 22 deletions

View File

@ -64,6 +64,15 @@ impl LayerId {
}
}
/// Who initiated an undoable document edit.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum MutationOrigin {
#[default]
User,
Agent,
System,
}
/// Identity of the source contents shared by smart-object instances, independent of their bytes.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct SmartContentsId(pub u64);

View File

@ -1407,8 +1407,7 @@ mod set_props_tests {
use super::*;
#[test]
fn opacity_and_fill_outside_zero_to_one_are_refused_not_clamped() {
// #5242: `55` (a percentage, as the Layer Style commands take) used to become 100 %.
fn opacity_and_fill_normalize_percentages_and_reject_invalid_values() {
let mut s = Session::new();
s.execute("file.new", json!({"width": 8, "height": 8})).unwrap();
s.execute("layer.new.layer", json!({})).unwrap();
@ -1419,10 +1418,12 @@ mod set_props_tests {
(l.opacity, l.fill_opacity)
};
assert_eq!(layer(&s), (0.55, 0.4));
for bad in [json!({"opacity": 55}), json!({"opacity": -0.1}), json!({"fill": 1.5}), json!({"opacity": "50%"}), json!({"opacity": 0.5, "fill": 40})] {
s.execute("layer.setProps", json!({"opacity": 65, "fill": 30})).unwrap();
assert_eq!(layer(&s), (0.65, 0.3));
for bad in [json!({"opacity": 101}), json!({"opacity": -0.1}), json!({"fill": 101}), json!({"opacity": "50%"}), json!({"opacity": 0.5, "fill": 140})] {
let e = s.execute("layer.setProps", bad.clone()).unwrap_err().to_string();
assert!(e.contains("0..1"), "{bad}: {e}");
assert_eq!(layer(&s), (0.55, 0.4), "{bad} left the layer alone");
assert_eq!(layer(&s), (0.65, 0.3), "{bad} left the layer alone");
}
s.execute("layer.setProps", json!({"opacity": 0, "fill": 1})).unwrap();
assert_eq!(layer(&s), (0.0, 1.0));

View File

@ -177,6 +177,7 @@ fn set_quiet(s: &mut Session, f: impl FnOnce(&mut Document)) -> Result<()> {
pub(crate) fn compound<R>(s: &mut Session, label: &str, f: impl FnOnce(&mut Session) -> Result<R>) -> Result<R> {
let st = s.active().ok_or(EngineError::NoDocument)?;
let (before, history, prior) = (st.doc.clone(), st.history.clone(), st.layer_target());
let mutation_history = st.mutation_history.clone();
// An inner command may select a layer that disappears when the compound rolls back.
// Selection, channel targeting and coalescing must roll back with the document (#4975).
let anchor = st.layer_anchor;
@ -193,13 +194,11 @@ pub(crate) fn compound<R>(s: &mut Session, label: &str, f: impl FnOnce(&mut Sess
}
let st = s.active_mut().ok_or(EngineError::NoDocument)?;
st.history = history;
st.mutation_history = mutation_history;
let result = match r {
Ok(v) => {
// As in `Session::edit`: undo targets what was selected just before the step (#1356).
st.history.set_current_layers(prior);
st.history.record(label, before.clone(), st.layer_target());
st.history.add_current_visibility(&crate::visibility_changes(&before, &st.doc));
st.trim_history();
st.record_mutation(label, before, prior, crate::MutationOrigin::User, None);
st.coalesce = None;
Ok(v)
}

View File

@ -5,6 +5,7 @@ use super::{Arc, Document, History, LayerId, LayerTarget, channel_cmds, float_cm
pub struct DocState {
pub doc: Arc<Document>,
pub history: History,
pub(crate) mutation_history: crate::session::MutationHistory,
/// The primary ("key") layer: what single-layer commands act on. Always a member of
/// `selected_layers` when set.
pub active_layer: Option<LayerId>,
@ -85,6 +86,7 @@ impl DocState {
Self {
doc,
history,
mutation_history: Default::default(),
active_layer,
selected_layers: active_layer.into_iter().collect(),
layer_anchor: active_layer,

View File

@ -53,6 +53,7 @@ use photocraft_ops::{History, LayerTarget};
use serde_json::Value;
pub use commands::{CommandSpec, command_specs};
pub use photocraft_doc::MutationOrigin;
pub use photocraft_doc as doc;
pub use photocraft_paint as paint;
pub use photocraft_paint::BrushSettings;
@ -171,7 +172,7 @@ pub use doc_state::{CopiedStyle, DocState, PRECHECKED, ToolState};
pub use error::{EngineError, Result};
pub use session::move_item;
use session::restore_target;
pub(crate) use session::{carry_visibility, fix_selection, visibility_changes};
pub(crate) use session::{carry_visibility, fix_selection};
/// The pixels of a raster layer (typically one a command just created), as an error instead
/// of a panic if the layer has none.

View File

@ -9,6 +9,8 @@ mod documents;
mod execute;
mod history;
mod layers;
mod mutation;
pub use documents::move_item;
pub(crate) use history::{carry_visibility, fix_selection, restore_target, visibility_changes};
pub(crate) use history::{carry_visibility, fix_selection, restore_target};
pub(crate) use mutation::MutationHistory;

View File

@ -1,9 +1,9 @@
use super::history::{fix_selection, visibility_changes};
use super::history::fix_selection;
use super::{
Arc, Document, EngineError, LayerId, Result, Session, Value, brush_cmds, channel_cmds, commands, hidden_target, jobs, layer_multi_cmds, retouch_cmds,
smart_cmds,
};
use crate::color_channels;
use crate::{MutationOrigin, color_channels};
impl Session {
/// Run a command by id with JSON params. Returns a JSON result.
@ -210,6 +210,18 @@ impl Session {
self.edit_with(label, true, f)
}
/// Apply an edit and record its source for the named layers in the same history step.
/// Supply the IDs the edit writes or removes. An empty slice records only the step's source.
pub fn edit_with_origin<R>(
&mut self,
label: &str,
origin: MutationOrigin,
affected_layers: &[LayerId],
f: impl FnOnce(&mut Document, &mut Option<LayerId>) -> Result<R>,
) -> Result<R> {
self.edit_transaction(label, true, origin, Some(affected_layers), 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.
@ -226,6 +238,17 @@ impl Session {
/// [`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<R>(&mut self, label: &str, record: bool, f: impl FnOnce(&mut Document, &mut Option<LayerId>) -> Result<R>) -> Result<R> {
self.edit_transaction(label, record, MutationOrigin::User, None, f)
}
fn edit_transaction<R>(
&mut self,
label: &str,
record: bool,
origin: MutationOrigin,
affected_layers: Option<&[LayerId]>,
f: impl FnOnce(&mut Document, &mut Option<LayerId>) -> Result<R>,
) -> Result<R> {
let command_scope = self.command_scope.clone();
if let Some(scope) = &command_scope { scope.check_active(self)?; }
// Every mutation path (linked-file refresh, transform, place) re-renders smart objects
@ -290,19 +313,15 @@ impl Session {
let hint_before = before.clone();
let key = self.coalesce_request.clone();
let st = self.active_mut().ok_or(EngineError::NoDocument)?;
let layers = st.layer_target();
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.clone(), layers);
st.history.add_current_visibility(&visibility_changes(&before, &st.doc));
st.trim_history();
st.coalesce = key;
} else {
st.history.set_current_layers(layers);
st.history.add_current_visibility(&visibility_changes(&before, &st.doc));
if key.is_some() && st.coalesce == key && st.history.can_undo() && st.last_origin() == Some(origin) {
st.coalesce_mutation(&before, origin, affected_layers);
} else {
st.record_mutation(label, before, prior, origin, affected_layers);
}
st.coalesce = key;
}
st.bump_revision(keep_clean);

View File

@ -0,0 +1,266 @@
use std::collections::HashMap;
use std::sync::Arc;
use photocraft_doc::{Document, LayerId, MutationOrigin};
use photocraft_ops::LayerTarget;
use super::history::visibility_changes;
use crate::{DocState, Session};
// History owns the state IDs and moves them with the document. Index provenance by those IDs
// so undo, redo, rollback and history panel jumps all read the state they landed on.
#[derive(Clone, Debug, Default)]
pub(crate) struct MutationHistory {
states: HashMap<u64, MutationState>,
}
#[derive(Clone, Debug, Default)]
struct MutationState {
origin: MutationOrigin,
layers: Option<Arc<HashMap<LayerId, MutationOrigin>>>,
}
impl Session {
/// Source of the current undoable edit, or `None` before the first edit.
pub fn last_origin(&self) -> Option<MutationOrigin> {
self.active()?.last_origin()
}
/// Most recent recorded source for a live layer in the current history state.
/// Layer tracking starts when an edit names the layer in `edit_with_origin`.
pub fn layer_last_origin(&self, layer: LayerId) -> Option<MutationOrigin> {
let st = self.active()?;
let origin = *st.current_mutation()?.layers.as_ref()?.get(&layer)?;
st.doc.layer(layer).map(|_| origin)
}
}
impl DocState {
fn current_mutation(&self) -> Option<&MutationState> {
self.mutation_history.states.get(&self.history.row_id(self.history.past_len())?)
}
pub(crate) fn last_origin(&self) -> Option<MutationOrigin> {
let id = self.history.row_id(self.history.past_len())?;
(id != 0).then(|| self.current_mutation().map_or(MutationOrigin::User, |step| step.origin))
}
pub(crate) fn record_mutation(
&mut self,
label: &str,
before: Arc<Document>,
prior: LayerTarget,
origin: MutationOrigin,
affected_layers: Option<&[LayerId]>,
) {
let mutation = self.mutation_for_edit(&before, origin, affected_layers);
// The previous record can still be rolled back, including its evictions. A new record
// supersedes it and releases any states hidden by Clear History as well.
self.mutation_history.states.retain(|id, _| self.history.row_of(*id).is_some());
self.history.set_current_layers(prior);
self.history.record(label, before.clone(), self.layer_target());
self.history.add_current_visibility(&visibility_changes(&before, &self.doc));
self.set_current_mutation(mutation);
self.trim_history();
}
pub(crate) fn coalesce_mutation(&mut self, before: &Document, origin: MutationOrigin, affected_layers: Option<&[LayerId]>) {
let mutation = self.mutation_for_edit(before, origin, affected_layers);
self.history.set_current_layers(self.layer_target());
self.history.add_current_visibility(&visibility_changes(before, &self.doc));
self.set_current_mutation(mutation);
}
fn mutation_for_edit(&self, before: &Document, origin: MutationOrigin, affected_layers: Option<&[LayerId]>) -> MutationState {
let previous = self.current_mutation().and_then(|step| step.layers.as_ref());
let mut state = MutationState { origin, layers: previous.cloned() };
if let Some(ids) = affected_layers {
for &id in ids {
state.set_layer(id, self.doc.layer(id).map(|_| origin));
}
} else if let Some(tracked) = previous {
// Legacy edits have no affected-layer list. Refresh only layers already tracked.
for &id in tracked.keys() {
let current = self.doc.layer(id);
if current != before.layer(id) {
state.set_layer(id, current.map(|_| origin));
}
}
}
state
}
fn set_current_mutation(&mut self, state: MutationState) {
if let Some(id) = self.history.row_id(self.history.past_len()) {
if state.origin == MutationOrigin::User && state.layers.is_none() {
self.mutation_history.states.remove(&id);
} else {
self.mutation_history.states.insert(id, state);
}
}
}
}
impl MutationState {
fn set_layer(&mut self, id: LayerId, origin: Option<MutationOrigin>) {
let previous = self.layers.as_ref().and_then(|layers| layers.get(&id)).copied();
if previous == origin {
return;
}
if let Some(origin) = origin {
Arc::make_mut(self.layers.get_or_insert_with(Arc::default)).insert(id, origin);
} else if let Some(layers) = &mut self.layers {
let layers = Arc::make_mut(layers);
layers.remove(&id);
if layers.is_empty() {
self.layers = None;
}
}
}
}
#[cfg(test)]
mod tests {
use photocraft_doc::{ColorMode, Document, Layer, LayerId, MutationOrigin, SampleType, Size};
use crate::{EngineError, Session};
fn session() -> (Session, LayerId, LayerId) {
let mut doc = Document::new("Origins", Size::new(8, 8), ColorMode::Rgb, SampleType::U8);
let first = Layer::raster("First", doc.pixel_format());
let second = Layer::raster("Second", doc.pixel_format());
let (first_id, second_id) = (first.id, second.id);
doc.layers = vec![first, second];
let mut session = Session::new();
session.add_document(doc, None);
(session, first_id, second_id)
}
fn rename(s: &mut Session, layer: LayerId, origin: MutationOrigin, name: &str) {
s.edit_with_origin(name, origin, &[layer], |doc, _| {
doc.layer_mut(layer).unwrap().name = name.into();
Ok(())
})
.unwrap();
}
fn assert_state(s: &Session, layer: LayerId, name: &str, step: Option<MutationOrigin>, source: Option<MutationOrigin>) {
assert_eq!(s.active().unwrap().doc.layer(layer).unwrap().name, name);
assert_eq!(s.last_origin(), step);
assert_eq!(s.layer_last_origin(layer), source);
}
#[test]
fn mixed_origins_follow_each_layer_through_undo_and_redo() {
use MutationOrigin::{Agent, System, User};
let (mut s, first, second) = session();
assert_state(&s, first, "First", None, None);
rename(&mut s, first, User, "User edit");
rename(&mut s, first, Agent, "Agent edit");
rename(&mut s, second, System, "System edit");
assert_state(&s, first, "Agent edit", Some(System), Some(Agent));
assert_eq!(s.layer_last_origin(second), Some(System));
s.edit("Legacy user edit", |doc, _| {
doc.layer_mut(first).unwrap().name = "User again".into();
Ok(())
})
.unwrap();
assert_state(&s, first, "User again", Some(User), Some(User));
assert_eq!(s.layer_last_origin(second), Some(System));
assert!(s.undo());
assert_state(&s, first, "Agent edit", Some(System), Some(Agent));
assert!(s.undo());
assert_eq!(s.layer_last_origin(second), None);
assert_state(&s, first, "Agent edit", Some(Agent), Some(Agent));
assert!(s.undo());
assert_state(&s, first, "User edit", Some(User), Some(User));
assert!(s.undo());
assert_state(&s, first, "First", None, None);
for (name, step, source) in [
("User edit", User, User),
("Agent edit", Agent, Agent),
("Agent edit", System, Agent),
("User again", User, User),
] {
assert!(s.redo());
assert_state(&s, first, name, Some(step), Some(source));
}
}
#[test]
fn uncommitted_and_deleted_layers_do_not_leave_an_origin_in_the_current_state() {
use MutationOrigin::{Agent, User};
let (mut s, layer, _) = session();
rename(&mut s, layer, Agent, "Agent edit");
let result = s.edit_with_origin("Fail", User, &[layer], |doc, _| {
doc.layer_mut(layer).unwrap().name = "Discard this".into();
Err::<(), _>(EngineError::Cancelled)
});
assert!(matches!(result, Err(EngineError::Cancelled)));
assert_state(&s, layer, "Agent edit", Some(Agent), Some(Agent));
s.edit_with_origin("Delete", User, &[layer], |doc, _| {
doc.layers.retain(|entry| entry.id != layer);
Ok(())
})
.unwrap();
assert_eq!(s.last_origin(), Some(User));
assert_eq!(s.layer_last_origin(layer), None);
assert!(s.undo());
assert_state(&s, layer, "Agent edit", Some(Agent), Some(Agent));
assert!(s.redo());
assert_eq!(s.layer_last_origin(layer), None);
}
#[test]
fn non_linear_history_keeps_branch_origins_and_rollback_restores_the_branch_point() {
use MutationOrigin::{Agent, System, User};
let (mut s, layer, _) = session();
let history = &mut s.active_mut().unwrap().history;
history.non_linear = true;
history.max_states = 2;
rename(&mut s, layer, Agent, "Agent edit");
rename(&mut s, layer, User, "User edit");
assert!(s.undo());
rename(&mut s, layer, System, "Branch");
assert!(s.rollback());
assert_state(&s, layer, "Agent edit", Some(Agent), Some(Agent));
assert!(s.redo());
assert_state(&s, layer, "User edit", Some(User), Some(User));
assert!(s.undo());
rename(&mut s, layer, System, "Branch again");
assert!(s.undo());
assert_state(&s, layer, "User edit", Some(User), Some(User));
assert!(s.undo());
assert_state(&s, layer, "Agent edit", Some(Agent), Some(Agent));
assert!(s.redo());
assert!(s.redo());
assert_state(&s, layer, "Branch again", Some(System), Some(System));
}
#[test]
fn a_coalescing_key_does_not_join_edits_from_different_origins() {
use MutationOrigin::{Agent, User};
let (mut s, first, second) = session();
s.coalesce_request = Some("gesture".into());
rename(&mut s, first, Agent, "Agent first");
rename(&mut s, second, Agent, "Agent second");
assert_eq!(s.active().unwrap().history.past_len(), 1);
rename(&mut s, first, User, "User first");
assert_eq!(s.active().unwrap().history.past_len(), 2);
assert!(s.undo());
assert_state(&s, first, "Agent first", Some(Agent), Some(Agent));
assert_state(&s, second, "Agent second", Some(Agent), Some(Agent));
assert!(s.undo());
assert_state(&s, first, "First", None, None);
assert_state(&s, second, "Second", None, None);
}
}

View File

@ -50,7 +50,7 @@ fn bad_layer_lists_change_nothing() {
json!({"layers": ["x"], "opacity": 0.5}),
json!({"layers": [ids[0], 999_999], "opacity": 0.5}),
json!({"layers": [ids[0], ids[1]], "name": "Both"}),
json!({"layers": [ids[0], ids[1]], "opacity": 2.0}),
json!({"layers": [ids[0], ids[1]], "opacity": 101.0}),
] {
assert!(s.execute("layer.setProps", p.clone()).is_err(), "{p}");
assert_eq!(s.active().unwrap().doc.layers, before.layers, "{p}");