diff --git a/crates/engine-core/src/cmd/actions_cmds.rs b/crates/engine-core/src/cmd/actions_cmds.rs index 66543cd1d6..6ddc1951f3 100644 --- a/crates/engine-core/src/cmd/actions_cmds.rs +++ b/crates/engine-core/src/cmd/actions_cmds.rs @@ -158,6 +158,9 @@ pub fn playback_params(s: &Session, id: &str, p: &Value) -> Result { { object.remove("__atnCustom"); } + if id == "edit.contentAwareFill" { + crate::atn_cmds::caf_remembered(&mut p, s.prefs())?; + } if id == "layer.setProps" && let Some(target) = p.get("_actionLayer") { diff --git a/crates/engine-core/src/cmd/atn_cmds.rs b/crates/engine-core/src/cmd/atn_cmds.rs index 4b9d2ef489..25c0003d5d 100644 --- a/crates/engine-core/src/cmd/atn_cmds.rs +++ b/crates/engine-core/src/cmd/atn_cmds.rs @@ -85,6 +85,8 @@ use events::{EVENTS, event_and_descriptor, event_for}; use fields::Mapped; use files::{load, save}; pub use menu_item::{MENU_ITEM, menu_item_command, menu_item_commands, menu_item_needs_settings}; +pub(crate) use steps_content_aware::caf_remembered; +pub use steps_content_aware::{CAF_CUSTOM_AREA_NOT_REMEMBERED, CAF_WORKSPACE_PREFS}; #[cfg(test)] use steps_doc::crop_from; pub(crate) use steps_gallery::RECORDED_EVENT; @@ -197,6 +199,9 @@ pub fn specs() -> Vec { #[cfg(test)] mod tests; +#[cfg(test)] +mod caf_action_values_tests; + #[cfg(test)] mod layer_props_tests; diff --git a/crates/engine-core/src/cmd/atn_cmds/caf_action_values_tests.rs b/crates/engine-core/src/cmd/atn_cmds/caf_action_values_tests.rs new file mode 100644 index 0000000000..1f4e52822b --- /dev/null +++ b/crates/engine-core/src/cmd/atn_cmds/caf_action_values_tests.rs @@ -0,0 +1,251 @@ +//! Recorded `cafWorkspace` steps: every measured value maps to the command and back, and an +//! empty step plays with the workspace's remembered settings (#14254). +use super::*; +use crate::actions_cmds::{ActionList, ActionStep, ActionsExt}; + +const CMD: &str = "edit.contentAwareFill"; +const MARK: &str = "_atnCafRemembered"; + +/// A seven-key step with these enumerations and every boolean off. +fn workspace(sampling: &str, color: &str, rotation: &str, output: &str) -> Descriptor { + desc("null") + .with("cafSamplingRegion", enm("cafSamplingRegion", sampling)) + .with("cafSampleAllLayers", D::Boolean(false)) + .with("cafColorAdaptationLevel", enm("cafColorAdaptationLevel", color)) + .with("cafRotationAmount", enm("cafRotationAmount", rotation)) + .with("cafScale", D::Boolean(false)) + .with("cafMirror", D::Boolean(false)) + .with("cafOutput", enm("cafOutput", output)) +} + +/// The params [`workspace`] imports as. +fn params(sampling: &str, color: &str, rotation: &str, output: &str) -> Value { + json!({"sampling":sampling,"sampleAllLayers":false,"colorAdaptation":color, + "rotationAdaptation":rotation,"scale":false,"mirror":false,"output":output}) +} + +fn item(d: Descriptor) -> AtnItem { + AtnItem { event: AtnEvent::name("cafWorkspace"), dictionary: b"Content-Aware Fill".to_vec(), descriptor: Some(d), ..Default::default() } +} + +fn file(d: Descriptor) -> Vec { + atn::write(&AtnFile { + name: UnicodeString::new_nul("S"), + actions: vec![AtnAction { name: UnicodeString::new_nul("A"), items: vec![item(d)], ..Default::default() }], + ..Default::default() + }) + .unwrap() +} + +/// The single step a one-step file imports as. +fn load(d: Descriptor) -> Action { + let loaded = import(&file(d)).unwrap(); + assert!(loaded.unsupported.is_empty(), "{:?}", loaded.unsupported); + loaded.actions.into_iter().next().unwrap() +} + +/// The item Save Actions writes for one step, or `None` when it refuses the step. A save that succeeds must +/// write a readable file holding the item. +fn exported(p: Value) -> Option { + let a = Action::new("A", vec![ActionStep::new(CMD, p)]); + let (bytes, skipped) = export("S", &[&a], &[], false).ok()?; + assert!(skipped.is_empty()); + let saved = atn::parse(&bytes).expect("a successful save writes a readable file"); + Some(saved.actions.into_iter().next().and_then(|a| a.items.into_iter().next()).expect("the saved file holds the step")) +} + +#[test] +fn every_measured_value_imports_to_its_param_and_saves_back_unchanged() { + let base = ("cafSamplingRegionRectangular", "cafColorAdaptationDefault", "cafRotationAmountNone", "cafOutputToNewLayer"); + let mut cases = Vec::new(); + for (wire, value) in [("cafSamplingRegionAuto", "auto"), ("cafSamplingRegionRectangular", "rectangular"), ("cafSamplingRegionCustom", "custom")] { + cases.push((workspace(wire, base.1, base.2, base.3), params(value, "default", "none", "new"))); + } + for (wire, value) in [ + ("cafColorAdaptationNone", "none"), + ("cafColorAdaptationDefault", "default"), + ("cafColorAdaptationHigh", "high"), + ("cafColorAdaptationVeryHigh", "veryHigh"), + ] { + cases.push((workspace(base.0, wire, base.2, base.3), params("rectangular", value, "none", "new"))); + } + for (wire, value) in [ + ("cafRotationAmountNone", "none"), + ("cafRotationAmountLow", "low"), + ("cafRotationAmountMedium", "medium"), + ("cafRotationAmountHigh", "high"), + ("cafRotationAmountFull", "full"), + ] { + cases.push((workspace(base.0, base.1, wire, base.3), params("rectangular", "default", value, "new"))); + } + for (wire, value) in [("cafOutputToCurrentLayer", "current"), ("cafOutputToNewLayer", "new"), ("cafOutputToDuplicateLayer", "duplicate")] { + cases.push((workspace(base.0, base.1, base.2, wire), params("rectangular", "default", "none", value))); + } + for (d, p) in cases { + let action = load(d.clone()); + assert_eq!(action.steps, vec![ActionStep::new(CMD, p.clone())]); + assert_eq!(exported(p.clone()), Some(item(d.clone())), "{p}"); + let bytes = export("S", &[&action], &[], false).unwrap().0; + assert_eq!(atn::parse(&bytes).unwrap().actions[0].items[0], item(d)); + } +} + +#[test] +fn an_empty_step_imports_as_remembered_and_saves_back_empty() { + let action = load(desc("null")); + assert_eq!(action.steps, vec![ActionStep::new(CMD, json!({MARK: true}))]); + assert_eq!(exported(json!({MARK: true})), Some(item(desc("null")))); + // A differently named empty descriptor comes back as recorded. + let mut named = desc("null"); + named.name = UnicodeString::new_nul("Recorded CAF"); + let action = load(named.clone()); + assert_eq!(action.steps[0].params[MARK], json!(true)); + let bytes = export("S", &[&action], &[], false).unwrap().0; + assert_eq!(atn::parse(&bytes).unwrap().actions[0].items[0], item(named)); +} + +#[test] +fn a_remembered_step_with_values_of_its_own_is_not_saved_as_an_empty_step() { + for p in [json!({MARK: true, "output": "current"}), json!({MARK: false}), json!({MARK: "yes"}), json!({MARK: true, "seed": 2})] { + assert_eq!(exported(p.clone()), None, "{p}"); + } +} + +/// White 8 x 8 with a red square selected for the fill. +fn session() -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width":8,"height":8,"background":"white"})).unwrap(); + s.execute("select.rect", json!({"x":3,"y":3,"width":2,"height":2})).unwrap(); + // Painted directly: Edit › Fill is registered by another engine crate. + s.edit("paint", |doc, active| { + let surface = doc.layer_mut(active.ok_or(crate::EngineError::NoDocument)?).and_then(|l| l.surface_mut()).ok_or(crate::EngineError::NoDocument)?; + for (x, y) in [(3, 3), (4, 3), (3, 4), (4, 4)] { + surface.write_pixel(x, y, &[1.0, 0.0, 0.0, 1.0]); + } + Ok(()) + }) + .unwrap(); + s +} + +fn remember(s: &mut Session, settings: Value) { + s.edit_prefs(|p| p.dialogs.insert(CAF_WORKSPACE_PREFS.into(), settings)); +} + +/// Play `d` as a one-step action and return the result. +fn play(s: &mut Session, d: Descriptor) -> Value { + s.actions_mut().list = ActionList::new(); + s.actions_mut().list.push(load(d)).unwrap(); + let result = s.execute("actions.play", json!({"action":0})).unwrap(); + assert!(result.get("failed").is_none(), "{result}"); + assert_eq!(result["ran"], 1); + result +} + +/// Every layer's pixels, in stack order. +fn pixels(s: &Session) -> Vec> { + let doc = &s.active().unwrap().doc; + doc.layers.iter().map(|l| (0..64).map(|i| l.surface().unwrap().rgba(i % 8, i / 8)).collect()).collect() +} + +/// What running the command itself with `p` leaves. +fn native(p: Value) -> Vec> { + let mut s = session(); + s.execute(CMD, p).unwrap(); + pixels(&s) +} + +#[test] +fn an_empty_step_fills_a_new_layer_before_anything_is_remembered() { + let mut s = session(); + let layers = s.active().unwrap().doc.layers.len(); + let past = s.active().unwrap().history.past_len(); + play(&mut s, desc("null")); + assert_eq!(s.active().unwrap().doc.layers.len(), layers + 1); + assert_eq!(s.active().unwrap().history.past_len(), past + 1); + assert_eq!(pixels(&s), native(json!({"output":"new"}))); + assert!(!s.prefs().dialogs.contains_key(CAF_WORKSPACE_PREFS), "playing remembers nothing"); +} + +#[test] +fn an_empty_step_plays_with_the_remembered_settings_and_steps_never_change_them() { + let settings = json!({"showOverlay":false,"opacity":20.0,"sampling":"rectangular","sampleAllLayers":false, + "colorAdaptation":"high","rotationAdaptation":"full","scale":true,"mirror":true,"output":"current"}); + let mut s = session(); + remember(&mut s, settings.clone()); + let layers = s.active().unwrap().doc.layers.len(); + play(&mut s, desc("null")); + assert_eq!(s.active().unwrap().doc.layers.len(), layers, "remembered Current Layer"); + let used = json!({"sampling":"rectangular","sampleAllLayers":false,"colorAdaptation":"high", + "rotationAdaptation":"full","scale":true,"mirror":true,"output":"current"}); + assert_eq!(pixels(&s), native(used)); + assert_eq!(s.prefs().dialogs.get(CAF_WORKSPACE_PREFS), Some(&settings)); + + // A step's own values are not remembered: the next empty step still uses Current Layer. + let mut s = session(); + remember(&mut s, settings.clone()); + let layers = s.active().unwrap().doc.layers.len(); + play(&mut s, workspace("cafSamplingRegionAuto", "cafColorAdaptationNone", "cafRotationAmountLow", "cafOutputToNewLayer")); + assert_eq!(s.active().unwrap().doc.layers.len(), layers + 1); + assert_eq!(s.prefs().dialogs.get(CAF_WORKSPACE_PREFS), Some(&settings)); + let next = crate::actions_cmds::playback_params(&s, CMD, &json!({MARK: true})).unwrap(); + assert_eq!(next["output"], "current"); +} + +#[test] +fn remembered_settings_fill_only_what_the_step_does_not_name() { + let resolve = |s: &Session, p: Value| crate::actions_cmds::playback_params(s, CMD, &p).unwrap(); + let mut s = crate::session(); + assert_eq!(resolve(&s, json!({MARK: true})), json!({"output":"new"})); + // Only the command's settings come over, never the overlay's. + remember(&mut s, json!({"showOverlay":true,"opacity":50.0,"color":[1,2,3],"excluded":true,"sampling":"auto","output":"duplicate"})); + assert_eq!(resolve(&s, json!({MARK: true})), json!({"sampling":"auto","output":"duplicate"})); + assert_eq!(resolve(&s, json!({MARK: true, "output": "current"})), json!({"sampling":"auto","output":"current"})); + // A mark that isn't `true` is dropped without bringing the remembered settings in. + assert_eq!(resolve(&s, json!({MARK: false, "output": "current"})), json!({"output":"current"})); + // Steps without the mark and other commands are left alone. + assert_eq!(resolve(&s, json!({"output":"current"})), json!({"output":"current"})); + let other = crate::actions_cmds::playback_params(&s, "edit.fill", &json!({MARK: true})).unwrap(); + assert_eq!(other, json!({MARK: true})); +} + +#[test] +fn damaged_remembered_settings_are_skipped_without_a_panic() { + let resolve = |s: &Session| crate::actions_cmds::playback_params(s, CMD, &json!({MARK: true})).unwrap(); + let mut s = crate::session(); + for damaged in [json!(3), json!(null), json!([]), json!({"output":5,"scale":"yes","sampling":true,"mirror":null})] { + remember(&mut s, damaged.clone()); + assert_eq!(resolve(&s), json!({"output":"new"}), "{damaged}"); + } + // A remembered value the command refuses fails the step with an error, not a panic. + let mut s = session(); + remember(&mut s, json!({"output":"sideways"})); + s.actions_mut().list = ActionList::new(); + s.actions_mut().list.push(load(desc("null"))).unwrap(); + let before = s.active().unwrap().doc.clone(); + let result = s.execute("actions.play", json!({"action":0})).unwrap(); + assert!(result.get("failed").is_some(), "{result}"); + assert_eq!(s.active().unwrap().doc, before); +} + +#[test] +fn folder_batch_plays_an_empty_step_with_the_remembered_settings() { + let dir = tempfile::tempdir().unwrap(); + let join = |name: &str| dir.path().join(name).to_string_lossy().into_owned(); + let mut source = session(); + source.execute("file.saveACopy", json!({"path": join("in.png")})).unwrap(); + let steps = json!([["select.rect", {"x":3,"y":3,"width":2,"height":2}], [CMD, {MARK: true}]]); + // The layer count of each output: Current Layer fills the background, New Layer adds one. + let layers = |s: &mut Session, out: &str| { + let result = s.execute("file.automate.batch", json!({"input":[join("in.png")],"output":join(out),"format":"psd","steps":steps})).unwrap(); + assert!(result["errors"].as_array().unwrap().is_empty(), "{result}"); + let bytes = std::fs::read(dir.path().join(out).join("in.psd")).unwrap(); + photocraft_io::import("in.psd", &bytes).unwrap().document.layers.len() + }; + let mut s = crate::session(); + assert_eq!(layers(&mut s, "default"), 2, "nothing remembered: a new layer"); + remember(&mut s, json!({"output":"current"})); + assert_eq!(layers(&mut s, "remembered"), 1, "the remembered Current Layer"); + // Playing in Batch remembers nothing in the caller either. + assert_eq!(s.prefs().dialogs.get(CAF_WORKSPACE_PREFS), Some(&json!({"output":"current"}))); +} diff --git a/crates/engine-core/src/cmd/atn_cmds/steps_content_aware.rs b/crates/engine-core/src/cmd/atn_cmds/steps_content_aware.rs index 3e30609ea2..958fd1961b 100644 --- a/crates/engine-core/src/cmd/atn_cmds/steps_content_aware.rs +++ b/crates/engine-core/src/cmd/atn_cmds/steps_content_aware.rs @@ -3,20 +3,42 @@ use super::descriptors::{desc, enm, jstr}; use super::fields::{Mapped, step}; use super::tables::lookup_back; use super::{D, Descriptor, Map, Value}; +use crate::EngineError; const CMD: &str = "edit.contentAwareFill"; const SOURCE: &str = "_atnCafDescriptor"; -// The measured row bounds these values; its ellipses are not additional enum bindings. -const SAMPLING: &[(&str, &str)] = &[("cafSamplingRegionRectangular", "rectangular")]; -const COLOR: &[(&str, &str)] = &[("cafColorAdaptationDefault", "default")]; -const ROTATION: &[(&str, &str)] = &[("cafRotationAmountNone", "none")]; -// Current Layer is also explicit in the primary Action Manager example cited in docs/atn.md. -const OUTPUT: &[(&str, &str)] = &[("cafOutputToNewLayer", "new"), ("cafOutputToCurrentLayer", "current")]; +// Every value the workspace showed when such a step was played with dialogs on (#14254). +const SAMPLING: &[(&str, &str)] = &[("cafSamplingRegionAuto", "auto"), ("cafSamplingRegionRectangular", "rectangular"), ("cafSamplingRegionCustom", "custom")]; +const COLOR: &[(&str, &str)] = &[ + ("cafColorAdaptationNone", "none"), + ("cafColorAdaptationDefault", "default"), + ("cafColorAdaptationHigh", "high"), + ("cafColorAdaptationVeryHigh", "veryHigh"), +]; +const ROTATION: &[(&str, &str)] = &[ + ("cafRotationAmountNone", "none"), + ("cafRotationAmountLow", "low"), + ("cafRotationAmountMedium", "medium"), + ("cafRotationAmountHigh", "high"), + ("cafRotationAmountFull", "full"), +]; +const OUTPUT: &[(&str, &str)] = &[("cafOutputToCurrentLayer", "current"), ("cafOutputToNewLayer", "new"), ("cafOutputToDuplicateLayer", "duplicate")]; const KEYS: &[&str] = &["cafSamplingRegion", "cafSampleAllLayers", "cafColorAdaptationLevel", "cafRotationAmount", "cafScale", "cafMirror", "cafOutput"]; const PARAMS: &[&str] = &["sampling", "sampleAllLayers", "colorAdaptation", "rotationAdaptation", "scale", "mirror", "output"]; +/// Marks a step recorded with an empty descriptor: it plays with the workspace's remembered +/// settings ([`caf_remembered`]) instead of fixed values. +const REMEMBERED: &str = "_atnCafRemembered"; +/// The `prefs.dialogs` key under which the Content-Aware Fill workspace remembers its settings. +pub const CAF_WORKSPACE_PREFS: &str = "edit.contentAwareFill.workspace"; -/// All seven settings are recorded. Missing keys have no measured Photoshop default here. +/// All seven settings are recorded, or none: an empty descriptor uses the remembered settings. +/// Other missing keys have no measured Photoshop default here. fn recorded(d: &Descriptor) -> Option { + if d.items.is_empty() { + let mut p = Map::new(); + p.insert(REMEMBERED.into(), true.into()); + return Some(Value::Object(p)); + } if d.items.len() != KEYS.len() || KEYS.iter().any(|name| d.items.iter().filter(|(key, _)| key.is(name)).count() != 1) { return None; } @@ -35,15 +57,24 @@ fn recorded(d: &Descriptor) -> Option { Some(Value::Object(p)) } -/// Write only represented native options, making their defaults explicit in all seven fields. +/// Write only represented native options, making their defaults explicit in all seven fields. A step without +/// `sampleAllLayers` is refused: the command then samples the composite when the layer is empty, which neither +/// recorded value says. fn descriptor(p: &Value) -> Option { let object = p.as_object()?; if !super::events::pixel_target(p) - || object.keys().any(|key| !PARAMS.contains(&key.as_str()) && !matches!(key.as_str(), "target" | "seed" | SOURCE)) + || object.keys().any(|key| !PARAMS.contains(&key.as_str()) && !matches!(key.as_str(), "target" | "seed" | SOURCE | REMEMBERED)) || p.get("seed").is_some_and(|seed| seed.as_u64() != Some(1)) { return None; } + if let Some(remembered) = p.get(REMEMBERED) { + // Values next to the mark would be dropped by an empty descriptor. + return (remembered.as_bool() == Some(true) && !PARAMS.iter().any(|param| object.contains_key(*param))).then(|| desc("null")); + } + if !object.contains_key(PARAMS[1]) { + return None; + } let enumeration = |key: &str, param: &str, table: &[(&str, &str)], default: &str| { let value = match p.get(param) { None => default, @@ -67,6 +98,33 @@ fn descriptor(p: &Value) -> Option { ) } +/// Why an empty recorded step refuses remembered Custom sampling ([`caf_remembered`]). The shell shows it translated. +pub const CAF_CUSTOM_AREA_NOT_REMEMBERED: &str = "This step plays with the remembered Content-Aware Fill settings, and their Custom sampling area isn't remembered. Fill once with Auto or Rectangular sampling in Content-Aware Fill, then play it again."; + +/// Resolve an empty recorded step: the remembered settings fill what the step doesn't name, and +/// before any were remembered it writes to a new layer. Playing never changes what is remembered. +/// Remembered Custom sampling is refused: its area is painted in the workspace, which keeps none +/// (Custom reopens empty), and the step must not sample another area instead. +pub(crate) fn caf_remembered(p: &mut Value, prefs: &crate::prefs::Preferences) -> Result<(), EngineError> { + let Some(object) = p.as_object_mut() else { return Ok(()) }; + if object.remove(REMEMBERED).and_then(|v| v.as_bool()) != Some(true) { + return Ok(()); + } + let saved = prefs.dialogs.get(CAF_WORKSPACE_PREFS); + for (param, flag) in PARAMS.iter().map(|param| (*param, matches!(*param, "sampleAllLayers" | "scale" | "mirror"))) { + // Only well-typed values: a damaged entry must not turn into another setting. + let value = saved.and_then(|v| v.get(param)).filter(|v| if flag { v.is_boolean() } else { v.is_string() }); + if let Some(value) = value.filter(|_| !object.contains_key(param)) { + object.insert(param.into(), value.clone()); + } + } + object.entry("output").or_insert_with(|| "new".into()); + if object.get("sampling").and_then(Value::as_str) == Some("custom") && !["area", "channel", "samplingStrokes"].iter().any(|key| object.contains_key(*key)) { + return Err(EngineError::BadParams { cmd: CMD.into(), msg: CAF_CUSTOM_AREA_NOT_REMEMBERED.into() }); + } + Ok(()) +} + /// Import the verified seven-field form, retaining noncanonical wire data for an unchanged save. pub(super) fn caf_from(d: &Descriptor) -> Mapped { let Some(mut p) = recorded(d) else { return Mapped::Unsupported { harmless: false } }; diff --git a/crates/engine-core/src/cmd/file_cmds/batch_run.rs b/crates/engine-core/src/cmd/file_cmds/batch_run.rs index 97b0d9fdf9..6506ce7fdc 100644 --- a/crates/engine-core/src/cmd/file_cmds/batch_run.rs +++ b/crates/engine-core/src/cmd/file_cmds/batch_run.rs @@ -1030,6 +1030,8 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { let authorize = s.authorize; let raw_ppi = super::open::raw_open_resolution(s); let action_prefs = s.prefs().actions.clone(); + // An empty recorded Content-Aware Fill step plays with the remembered workspace settings. + let caf_workspace = s.prefs().dialogs.get(crate::atn_cmds::CAF_WORKSPACE_PREFS).cloned(); let prefs = s.prefs.clone(); let color_settings = s.color().settings.clone(); let raw_settings = s.batch_raw_open.as_ref().unwrap_or(&s.prefs().raw_defaults).clone(); @@ -1165,7 +1167,13 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { scratch.recording = run.clone(); scratch.recording.playback_steps = carried.get(); scratch.recording.script_steps = script_steps.get(); - scratch.prefs.edit(|prefs| prefs.actions = action_prefs.clone()); + scratch.prefs.edit(|prefs| { + prefs.actions = action_prefs.clone(); + // Only this entry: the scratch session keeps every other remembered dialog value at its default. + if let Some(workspace) = &caf_workspace { + prefs.dialogs.insert(crate::atn_cmds::CAF_WORKSPACE_PREFS.into(), workspace.clone()); + } + }); let owns_history = scratch.action_history.is_none() && scratch.prefs().actions.create_single_history_state; if owns_history { crate::actions_cmds::begin_document_history(scratch, &action_name); diff --git a/crates/engine/tests/it/atn_content_aware_fill.rs b/crates/engine/tests/it/atn_content_aware_fill.rs index 3c7c4b7c52..736508633d 100644 --- a/crates/engine/tests/it/atn_content_aware_fill.rs +++ b/crates/engine/tests/it/atn_content_aware_fill.rs @@ -152,10 +152,11 @@ fn caf_edited_settings_export_without_stale_wire_metadata() { } /// Missing defaults, malformed/repeated fields and unrepresented workspace state stay complete. +/// An empty descriptor plays with the remembered settings (`atn_cmds/caf_action_values_tests.rs`). #[test] fn caf_unrepresented_descriptors_are_kept_and_never_partially_play() { let base = descriptor(); - let mut cases = vec![Descriptor::new("null"), base.clone().with("extra", D::Boolean(true))]; + let mut cases = vec![base.clone().with("extra", D::Boolean(true))]; for i in 0..base.items.len() { let mut missing = base.clone(); missing.items.remove(i); @@ -167,20 +168,9 @@ fn caf_unrepresented_descriptors_are_kept_and_never_partially_play() { wrong.items[i].1 = D::Integer(0); cases.push(wrong); } - for (i, key, value) in [ - (0, "cafSamplingRegion", "cafSamplingRegionAuto"), - (0, "cafSamplingRegion", "cafSamplingRegionCustom"), - (2, "cafColorAdaptationLevel", "cafColorAdaptationNone"), - (2, "cafColorAdaptationLevel", "cafColorAdaptationHigh"), - (2, "cafColorAdaptationLevel", "cafColorAdaptationVeryHigh"), - (2, "cafColorAdaptationLevel", "unknown"), - (3, "cafRotationAmount", "cafRotationAmountLow"), - (3, "cafRotationAmount", "cafRotationAmountMedium"), - (3, "cafRotationAmount", "cafRotationAmountHigh"), - (3, "cafRotationAmount", "cafRotationAmountFull"), - (3, "cafRotationAmount", "unknown"), - (6, "cafOutput", "cafOutputToDuplicateLayer"), - ] { + for (i, key, value) in + [(0, "cafSamplingRegion", "unknown"), (2, "cafColorAdaptationLevel", "unknown"), (3, "cafRotationAmount", "unknown"), (6, "cafOutput", "unknown")] + { let mut d = base.clone(); d.items[i].1 = enm(key, value); cases.push(d); @@ -213,28 +203,25 @@ fn caf_unrepresented_descriptors_are_kept_and_never_partially_play() { /// Known native defaults become explicit values; unsupported defaults/options cannot disappear. #[test] fn caf_native_exports_preserve_effective_defaults_and_refuse_unrepresented_options() { - for p in [json!({"sampling":"rectangular","output":"new"}), json!({"sampling":"rectangular","output":"new","seed":1,"target":"pixels"}), params()] { + for p in [ + json!({"sampling":"rectangular","sampleAllLayers":false,"output":"new"}), + json!({"sampling":"rectangular","sampleAllLayers":false,"output":"new","seed":1,"target":"pixels"}), + params(), + ] { let a = load(exported(p).unwrap().descriptor.unwrap()); assert_eq!(a.steps, vec![ActionStep::new(CMD, params())]); } let mut current = params(); current["output"] = json!("current"); - for p in [json!({"sampling":"rectangular"}), current.clone()] { + for p in [json!({"sampling":"rectangular","sampleAllLayers":false}), current.clone()] { let a = load(exported(p).unwrap().descriptor.unwrap()); assert_eq!(a.steps, vec![ActionStep::new(CMD, current.clone())]); } for (key, value) in [ - ("sampling", json!("auto")), - ("sampling", json!("custom")), ("sampling", json!("unknown")), - ("output", json!("duplicate")), - ("colorAdaptation", json!("none")), - ("colorAdaptation", json!("high")), - ("colorAdaptation", json!("veryHigh")), - ("rotationAdaptation", json!("low")), - ("rotationAdaptation", json!("medium")), - ("rotationAdaptation", json!("high")), - ("rotationAdaptation", json!("full")), + ("output", json!("unknown")), + ("colorAdaptation", json!("unknown")), + ("rotationAdaptation", json!("unknown")), ("sampleAllLayers", json!(0)), ("scale", Value::Null), ("mirror", json!("true")), @@ -252,8 +239,19 @@ fn caf_native_exports_preserve_effective_defaults_and_refuse_unrepresented_optio p[key] = value; assert!(exported(p.clone()).is_none(), "{p}"); } - for p in [json!({}), json!({"output":"new"}), json!([])] { - assert!(exported(p.clone()).is_none(), "unrepresented native default: {p}"); + // The command's own defaults (Auto, Current Layer) are written out explicitly. + let mut defaults = params(); + defaults["sampling"] = json!("auto"); + defaults["output"] = json!("current"); + let a = load(exported(json!({"sampleAllLayers":false})).unwrap().descriptor.unwrap()); + assert_eq!(a.steps, vec![ActionStep::new(CMD, defaults.clone())]); + defaults["output"] = json!("new"); + let a = load(exported(json!({"sampleAllLayers":false,"output":"new"})).unwrap().descriptor.unwrap()); + assert_eq!(a.steps, vec![ActionStep::new(CMD, defaults)]); + assert!(exported(json!([])).is_none()); + // Without `sampleAllLayers` an empty layer samples the composite, and a recorded false would not. + for p in [json!({}), json!({"output":"new"}), json!({"colorAdaptation":"none"}), json!({"sampling":"rectangular"})] { + assert!(exported(p.clone()).is_none(), "unrepresented sampling: {p}"); } } diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 5530ed0ec4..6a26256f4f 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -633,6 +633,10 @@ pub fn open_command_dialog(app: &mut PhotocraftApp, command: &str, label: &str) /// Preference entries the engine reads itself, by key: the engine has no settings store, so they cannot move. const ENGINE_READ: &[&str] = &["ui.layersPanelOptions", "file.print", "file.export.saveForWebLegacy"]; +/// Preference entries the engine reads that a workspace also remembers in the framework's store: they stay, and are +/// copied there only while it holds none. An empty recorded Content-Aware Fill step plays with the engine's copy (#14254). +const ENGINE_READ_SHARED: &[&str] = &[photocraft_engine::atn_cmds::CAF_WORKSPACE_PREFS]; + /// The "Don't show again" entries (`{"skip": true}`), by key, as their prompt modules read them. Told apart by key, not /// by the shape of the value. fn dont_show_again_keys() -> [&'static str; 5] { @@ -686,7 +690,9 @@ fn convert_blend_mode(key: &str, value: &mut Value) { /// Moves the dialogs' last-used values out of `Preferences.dialogs` into the remembered section of `host`, once, before /// the first frame. Entries the engine reads and the don't-show-again entries stay; a second run finds nothing to move -/// because every moved entry left `Preferences.dialogs`. An entry that has no table form stays too. +/// because every moved entry left `Preferences.dialogs`. An entry that has no table form stays too, and a shared entry +/// ([`ENGINE_READ_SHARED`]) never replaces what the framework already remembers; a profile without one gets it from +/// what the framework remembers ([`carry_forward_shared`]). pub(crate) fn move_memories(prefs: &mut Preferences, host: &Host) { let keys: Vec = prefs.dialogs.keys().cloned().collect(); for key in keys { @@ -694,10 +700,38 @@ pub(crate) fn move_memories(prefs: &mut Preferences, host: &Host) { let Some(old) = prefs.dialogs.get(&key) else { continue }; let mut value = without_nulls(old.clone()); convert_blend_mode(&key, &mut value); + if key == photocraft_engine::atn_cmds::CAF_WORKSPACE_PREFS { + crate::caf_ui::recorded_to_workspace(&mut value); + } let Ok(table) = toml::Table::try_from(&value) else { continue }; - Remembered::::new(scope).store(host, &table); + let remembered = Remembered::::new(scope); + if ENGINE_READ_SHARED.contains(&key.as_str()) { + // An empty entry holds no settings yet (see `carry_forward_shared`). + if !table.is_empty() && remembered.recall(host).is_none() { + remembered.store(host, &table); + } + continue; + } + remembered.store(host, &table); prefs.dialogs.remove(&key); } + carry_forward_shared(prefs, host); +} + +/// Gives a profile without the engine's copy of a shared entry one, once (#14254). An earlier version moved the +/// Content-Aware Fill settings into the workspace's own memory and kept no copy, so that memory is carried forward: +/// it is all such a profile has, although it also holds settings the workspace closed with and never filled. With no +/// memory the copy starts empty. From then on only a fill that ran sets the copy, so settings closed without a fill +/// are never carried forward. +fn carry_forward_shared(prefs: &mut Preferences, host: &Host) { + for key in ENGINE_READ_SHARED { + if prefs.dialogs.contains_key(*key) { + continue; + } + let Some(scope) = memory_destination(key) else { continue }; + let memory = Remembered::::new(scope).recall(host).and_then(|table| serde_json::to_value(table).ok()); + prefs.dialogs.insert((*key).into(), memory.map_or_else(|| serde_json::json!({}), crate::caf_ui::recorded_from_workspace)); + } } pub mod adjust_dialog; diff --git a/crates/ui-egui/src/dialogs/caf_ui.rs b/crates/ui-egui/src/dialogs/caf_ui.rs index da0f6c0d67..8cd947511d 100644 --- a/crates/ui-egui/src/dialogs/caf_ui.rs +++ b/crates/ui-egui/src/dialogs/caf_ui.rs @@ -37,7 +37,7 @@ mod lifecycle; mod preview; pub use lifecycle::open; -pub(crate) use lifecycle::{describe, take}; +pub(crate) use lifecycle::{describe, on_job_event, recorded_from_workspace, recorded_to_workspace, take}; use preview::{Base, compute_preview, plan_params}; /// Longest side of the document proxy shown in the view (px). diff --git a/crates/ui-egui/src/dialogs/caf_ui/lifecycle.rs b/crates/ui-egui/src/dialogs/caf_ui/lifecycle.rs index 36e538eec6..e2007c3d70 100644 --- a/crates/ui-egui/src/dialogs/caf_ui/lifecycle.rs +++ b/crates/ui-egui/src/dialogs/caf_ui/lifecycle.rs @@ -6,6 +6,7 @@ use craft::imaging::ui::fill::{FillCommand, FillEvent, FillLimits, FillOpen, Fil use craft::ui::dialog::{DialogId, dialog_id}; use craft::ui::runtime::env::Label; use photocraft_engine::edit_menu_cmds::{MAX_CAF_EDITS, MAX_CAF_POINTS}; +use photocraft_engine::jobs::{JobEvent, JobId, JobOutcome}; use photocraft_geom::Rect; use serde_json::{Value, json}; @@ -128,11 +129,74 @@ fn report(app: &mut PhotocraftApp, e: &str) { app.ui.status_error = true; } -/// Fills with `command` (one history step); the workspace stays as it is. A refusal is reported. +/// The settings an empty recorded Content-Aware Fill step plays with (#14254). +const RECORDED_SETTINGS: [&str; 7] = ["sampling", "sampleAllLayers", "colorAdaptation", "rotationAdaptation", "scale", "mirror", "output"]; + +/// The workspace's own memory names Rotation Adaptation `rotation`; an empty recorded step reads `rotationAdaptation`. +const WORKSPACE_ROTATION: &str = "rotation"; + +/// The settings an empty recorded step plays with, from what the workspace remembers (#14254). +pub(crate) fn recorded_from_workspace(memory: Value) -> Value { + let Value::Object(mut settings) = memory else { return json!({}) }; + if let Some(rotation) = settings.remove(WORKSPACE_ROTATION) { + settings.insert("rotationAdaptation".into(), rotation); + } + settings.retain(|key, _| RECORDED_SETTINGS.contains(&key.as_str())); + Value::Object(settings) +} + +/// The settings an empty recorded step plays with, in the form the workspace remembers them. +pub(crate) fn recorded_to_workspace(settings: &mut Value) { + if let Some(settings) = settings.as_object_mut() + && let Some(rotation) = settings.remove("rotationAdaptation") + { + settings.insert(WORKSPACE_ROTATION.into(), rotation); + } +} + +/// `command`'s settings that an empty recorded step plays with. +fn recorded(command: &FillCommand) -> Option { + let Ok(Value::Object(mut settings)) = serde_json::to_value(command) else { return None }; + settings.retain(|key, _| RECORDED_SETTINGS.contains(&key.as_str())); + Some(Value::Object(settings)) +} + +/// Keeps `settings` in `prefs.dialogs` too, where an empty recorded step reads them: the workspace remembers its +/// own copy in the framework's store, which the engine can't see. +fn remember(app: &mut PhotocraftApp, settings: Value) { + app.session.prefs.edit(|p| p.dialogs.insert(photocraft_engine::atn_cmds::CAF_WORKSPACE_PREFS.into(), settings)); +} + +/// The background job a command's reply says is still running. +fn pending_job(reply: &Value) -> Option { + (reply.get("pending") == Some(&Value::Bool(true))).then(|| reply.get("job").and_then(Value::as_u64).map(JobId)).flatten() +} + +/// A background fill ended: its settings are remembered only when it was applied, not when it failed or was +/// cancelled (#14254). +pub(crate) fn on_job_event(app: &mut PhotocraftApp, e: &JobEvent) { + let Some(i) = app.jobs.caf_settings.iter().position(|(job, _)| *job == e.id) else { return }; + let (_, settings) = app.jobs.caf_settings.remove(i); + if matches!(e.outcome, JobOutcome::Done(_)) { + remember(app, settings); + } +} + +/// Fills with `command` (one history step); the workspace stays as it is. A refusal is reported and keeps the +/// settings of the last fill that ran. pub(super) fn apply(app: &mut PhotocraftApp, command: &FillCommand) -> Result<(), String> { let layer = app.caf.as_ref().ok_or("Content-Aware Fill is not open")?.layer; match app.run(CMD, plan_params(command, layer)) { - Ok(_) => Ok(()), + Ok(reply) => { + if let Some(settings) = recorded(command) { + match pending_job(&reply) { + // A background fill can still fail or be cancelled: its settings wait for the job's end. + Some(job) => app.jobs.caf_settings.push((job, settings)), + None => remember(app, settings), + } + } + Ok(()) + } Err(e) => { report(app, &e); Err(e) diff --git a/crates/ui-egui/src/dialogs/caf_ui/tests.rs b/crates/ui-egui/src/dialogs/caf_ui/tests.rs index 74d097e122..e2d2031ac3 100644 --- a/crates/ui-egui/src/dialogs/caf_ui/tests.rs +++ b/crates/ui-egui/src/dialogs/caf_ui/tests.rs @@ -1,6 +1,7 @@ use craft::imaging::ui::fill::FillOp; use craft::ui::canvas::PixelRect; use photocraft_doc::LayerId; +use photocraft_engine::actions_cmds::ActionsExt; use serde_json::{Value, json}; use super::preview::{compute_preview, plan_params}; @@ -251,6 +252,191 @@ fn apply_fills_and_stays_open_ok_closes_cancel_keeps_what_was_applied() { assert!(px(&app, top, 100, 80)[3] > 0.99, "the new layer holds the fill"); } +/// Apply and OK keep the settings where an empty recorded step reads them (#14254), as the workspace's own store +/// is out of the engine's reach. +#[test] +fn apply_and_ok_keep_the_settings_for_an_empty_recorded_step() { + let mut app = app_with_selection(); + let saved = |app: &PhotocraftApp| app.session.prefs().dialogs.get(photocraft_engine::atn_cmds::CAF_WORKSPACE_PREFS).cloned(); + assert_eq!(saved(&app), Some(json!({})), "a new profile has no settings yet"); + open(&mut app).unwrap(); + ui(&mut app, json!({"output": "current", "colorAdaptation": "high", "rotation": "medium", "mirror": true})).unwrap(); + ui(&mut app, json!({"apply": true})).unwrap(); + let after_apply = saved(&app).expect("Apply remembers the settings"); + assert_eq!(after_apply["output"], "current"); + assert_eq!(after_apply["colorAdaptation"], "high"); + assert_eq!(after_apply["rotationAdaptation"], "medium"); + assert_eq!(after_apply["mirror"], true); + let keys: Vec<&str> = after_apply.as_object().unwrap().keys().map(String::as_str).collect(); + assert_eq!(keys.len(), 7, "only the seven recorded settings: {keys:?}"); + ui(&mut app, json!({"output": "duplicate"})).unwrap(); + ui(&mut app, json!({"commit": true})).unwrap(); + close_all(&mut app); + assert_eq!(saved(&app).unwrap()["output"], "duplicate", "OK remembers too"); +} + +/// A fill the engine refuses leaves the settings of the last fill that ran for an empty recorded step (#14254). +#[test] +fn a_refused_fill_keeps_the_last_remembered_settings() { + let mut app = app_with_selection(); + let saved = |app: &PhotocraftApp| app.session.prefs().dialogs.get(photocraft_engine::atn_cmds::CAF_WORKSPACE_PREFS).cloned(); + open(&mut app).unwrap(); + ui(&mut app, json!({"output": "current", "colorAdaptation": "none", "apply": true})).unwrap(); + let remembered = saved(&app).expect("the Apply that ran remembers its settings"); + // The workspace's layer: the fill may have left another layer active. + let layer = app.caf.as_ref().unwrap().layer; + app.session.execute("layer.setProps", json!({"layer": layer.0, "locks": {"pixels": true}})).unwrap(); + let before = facts(&app)["previewRevision"].as_u64().unwrap(); + ui(&mut app, json!({"colorAdaptation": "high", "mirror": true})).unwrap(); + settle(&mut app, |d| d["previewRevision"].as_u64().unwrap() > before && d["previewError"].is_null()); + ui(&mut app, json!({"apply": true})).unwrap(); + assert!(facts(&app)["error"].as_str().is_some_and(|e| e.contains("locked")), "the engine refuses the locked layer: {}", facts(&app)); + assert_eq!(saved(&app), Some(remembered.clone()), "a refused Apply remembers nothing"); + assert!(ui(&mut app, json!({"commit": true})).is_err(), "the engine refuses OK too"); + assert_eq!(saved(&app), Some(remembered), "a refused OK remembers nothing"); +} + +/// A background fill (the desktop app) remembers its settings once its job is applied; a job that fails or is +/// cancelled leaves the last remembered ones (#14254). +#[test] +fn a_background_fill_remembers_its_settings_only_when_its_job_is_applied() { + use photocraft_engine::jobs::{JobEvent, JobId, JobOutcome}; + let mut app = app_with_selection(); + let saved = |app: &PhotocraftApp| app.session.prefs().dialogs.get(photocraft_engine::atn_cmds::CAF_WORKSPACE_PREFS).cloned(); + open(&mut app).unwrap(); + ui(&mut app, json!({"output": "current", "colorAdaptation": "none", "apply": true})).unwrap(); + let remembered = saved(&app).expect("the Apply that ran remembers its settings"); + app.background_jobs = true; + ui(&mut app, json!({"colorAdaptation": "high", "mirror": true})).unwrap(); + let id = app.caf.as_ref().unwrap().id; + let command = app.framework.dialogs.get_by_id::(id).unwrap().workspace().command(); + super::lifecycle::apply(&mut app, &command).unwrap(); + assert_eq!(saved(&app), Some(remembered), "nothing is remembered while the fill runs"); + assert_eq!(app.jobs.caf_settings.len(), 1, "the fill runs as a background job"); + let ctx = ctx(&app); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); + while app.session.has_jobs() { + assert!(std::time::Instant::now() < deadline, "the fill job did not end"); + crate::jobs_ui::tick(&mut app, &ctx); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + let applied = saved(&app).expect("the applied fill remembers its settings"); + assert_eq!((&applied["colorAdaptation"], &applied["mirror"]), (&json!("high"), &json!(true))); + assert!(app.jobs.caf_settings.is_empty()); + for outcome in [JobOutcome::Failed("refused".into()), JobOutcome::Cancelled] { + let job = JobId(u64::MAX); + app.jobs.caf_settings.push((job, json!({"output": "duplicate"}))); + let event = JobEvent { id: job, command: CMD.into(), label: String::new(), document: None, outcome: outcome.clone(), error: None }; + crate::caf_ui::on_job_event(&mut app, &event); + assert_eq!(saved(&app), Some(applied.clone()), "{outcome:?} remembers nothing"); + assert!(app.jobs.caf_settings.is_empty(), "{outcome:?} ends the wait"); + } +} + +/// After a restart an empty recorded step still plays with the last fill's settings: the startup move of the dialogs' +/// memories leaves the engine's copy in the preferences (#14254). +#[test] +fn an_empty_recorded_step_plays_with_the_last_settings_after_a_restart() { + let mut app = app_with_selection(); + open(&mut app).unwrap(); + ui(&mut app, json!({"output": "current", "commit": true})).unwrap(); + close_all(&mut app); + let mut restarted = restart(app.session.prefs().clone()); + assert_eq!(play_empty_recorded_step(&mut restarted), 0, "Current Layer, not a new layer"); +} + +/// A profile from an earlier version, which kept the Content-Aware Fill settings only in the workspace's own memory, +/// carries them forward for an empty recorded step on its first start (#14254). +#[test] +fn an_earlier_versions_workspace_settings_carry_forward_to_an_empty_recorded_step() { + let mut app = app_with_selection(); + open(&mut app).unwrap(); + ui(&mut app, json!({"output": "current", "rotation": "medium"})).unwrap(); + ui(&mut app, json!({"cancel": true})).unwrap(); + close_all(&mut app); + // That version moved the engine's copy into the workspace's memory and kept none. + let mut prefs = app.session.prefs().clone(); + prefs.dialogs.remove(photocraft_engine::atn_cmds::CAF_WORKSPACE_PREFS); + let mut restarted = restart(prefs); + let carried = restarted.session.prefs().dialogs.get(photocraft_engine::atn_cmds::CAF_WORKSPACE_PREFS).cloned().unwrap(); + assert_eq!((&carried["output"], &carried["rotationAdaptation"]), (&json!("current"), &json!("medium")), "{carried}"); + assert_eq!(play_empty_recorded_step(&mut restarted), 0, "Current Layer, as the workspace remembers"); +} + +/// Settings the workspace closed with but never filled are not carried to an empty recorded step: only a fill that ran +/// sets what it plays with (#14254). +#[test] +fn settings_closed_without_a_fill_are_not_carried_forward() { + let mut app = app_with_selection(); + open(&mut app).unwrap(); + ui(&mut app, json!({"output": "current"})).unwrap(); + ui(&mut app, json!({"cancel": true})).unwrap(); + close_all(&mut app); + let mut restarted = restart(app.session.prefs().clone()); + assert_eq!(play_empty_recorded_step(&mut restarted), 1, "New Layer: no fill has run"); +} + +/// After a confirmed Custom fill an empty recorded step stops and says why, instead of filling from another area: the +/// workspace remembers Custom but not its painted area (Custom reopens empty), so the step has none (#14254). +#[test] +fn an_empty_recorded_step_after_a_custom_fill_stops_and_says_why() { + let mut app = app_with_selection(); + open(&mut app).unwrap(); + ui(&mut app, json!({"sampling": "custom", "output": "current"})).unwrap(); + ui(&mut app, json!({"stroke": {"points": [[20.0, 120.0], [60.0, 120.0]], "size": 8}})).unwrap(); + ui(&mut app, json!({"commit": true})).unwrap(); + close_all(&mut app); + let remembered = app.session.prefs().dialogs.get(photocraft_engine::atn_cmds::CAF_WORKSPACE_PREFS).cloned().unwrap(); + assert_eq!(remembered["sampling"], "custom", "the confirmed fill remembers Custom: {remembered}"); + let revision = app.session.active().unwrap().revision; + let result = play_empty_step(&mut app); + assert_eq!(result["ran"], 0, "{result}"); + let error = result["failed"]["error"].as_str().unwrap_or_default(); + assert!(error.contains("Custom sampling area isn't remembered"), "{result}"); + // The status bar shows the shell's translatable copy of the message, not the engine's parameter error. + crate::actions::report_play(&mut app, &result); + let status = &app.ui.status; + assert!(status.contains(photocraft_engine::atn_cmds::CAF_CUSTOM_AREA_NOT_REMEMBERED) && !status.contains("invalid parameters"), "{status}"); + assert_eq!(app.session.active().unwrap().revision, revision, "the document is unchanged"); + assert_eq!(app.session.prefs().dialogs.get(photocraft_engine::atn_cmds::CAF_WORKSPACE_PREFS), Some(&remembered), "playing remembers nothing"); +} + +/// A new app over the saved preferences `prefs`, moved as startup does. +fn restart(prefs: photocraft_engine::prefs::Preferences) -> Box { + let mut restarted = app_with_selection(); + restarted.session.edit_prefs(|p| *p = prefs); + restarted.framework.move_memories(&mut restarted.session); + restarted +} + +/// Plays an action of one empty recorded Content-Aware Fill step and returns how many layers it added. +fn play_empty_recorded_step(app: &mut PhotocraftApp) -> usize { + let layers = app.session.active().unwrap().doc.layers.len(); + let result = play_empty_step(app); + assert_eq!(result["ran"], 1, "{result}"); + app.session.active().unwrap().doc.layers.len() - layers +} + +/// Plays an action of one empty recorded Content-Aware Fill step and returns what `actions.play` answers. +fn play_empty_step(app: &mut PhotocraftApp) -> Value { + use craft_psd::atn::{AtnAction, AtnEvent, AtnFile, AtnItem}; + use craft_psd::descriptor::{Descriptor, UnicodeString}; + let item = AtnItem { + event: AtnEvent::name("cafWorkspace"), + dictionary: b"Content-Aware Fill".to_vec(), + descriptor: Some(Descriptor::new("null")), + ..Default::default() + }; + let file = AtnFile { + name: UnicodeString::new_nul("S"), + actions: vec![AtnAction { name: UnicodeString::new_nul("A"), items: vec![item], ..Default::default() }], + ..Default::default() + }; + let imported = photocraft_engine::atn_cmds::import(&craft_psd::atn::write(&file).unwrap()).unwrap(); + app.session.actions_mut().list.push(imported.actions.into_iter().next().unwrap()).unwrap(); + app.session.execute("actions.play", json!({"action": 0})).unwrap() +} + /// The engine's sampling area over the plan's rectangle (what the fill samples) and its fill area. fn engine_source(app: &PhotocraftApp) -> (Rect, Vec, Vec) { let c = app.caf.as_ref().unwrap(); diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index dec11d58b4..715f308bf9 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -148,9 +148,12 @@ fn the_one_time_move_stores_owned_dialog_values_once_and_leaves_engine_read_keys assert_eq!(table("photocraft.edit.fill").unwrap().get("mode"), Some(&toml::Value::String(photocraft_color::BlendMode::ColorBurn.key().to_string()))); let mut left: Vec<&str> = prefs.dialogs.keys().map(String::as_str).collect(); left.sort_unstable(); - let mut kept = vec!["file.print", "ui.layersPanelOptions", "file.export.saveForWebLegacy", live_shape_prompt::PREF]; + // The Content-Aware Fill entry an empty recorded step reads is given to every profile, empty here (#14254). + let mut kept = + vec!["file.print", "ui.layersPanelOptions", "file.export.saveForWebLegacy", live_shape_prompt::PREF, photocraft_engine::atn_cmds::CAF_WORKSPACE_PREFS]; kept.sort_unstable(); assert_eq!(left, kept, "only the kept entries stay in the preferences"); + assert_eq!(prefs.dialogs.get(photocraft_engine::atn_cmds::CAF_WORKSPACE_PREFS), Some(&json!({}))); // A second run finds nothing to move: a value changed since is not overwritten. Remembered::::new("photocraft.filter.gaussianBlur").store(&host, &toml::Table::new()); @@ -158,6 +161,26 @@ fn the_one_time_move_stores_owned_dialog_values_once_and_leaves_engine_read_keys assert_eq!(table("photocraft.filter.gaussianBlur"), Some(toml::Table::new())); } +/// The Content-Aware Fill settings an empty recorded step reads stay in the preferences; the workspace's own memory +/// gets them only while it has none (#14254). +#[test] +fn the_move_keeps_the_content_aware_fill_settings_and_never_replaces_the_workspaces() { + let host = Host::builder(AppInfo { id: "photocraft", name: "PhotoCraft", version: "0" }).settings(Arc::new(MemorySections::default())).build(); + let key = photocraft_engine::atn_cmds::CAF_WORKSPACE_PREFS; + let workspace = Remembered::::new(params::memory_scope(key)); + let output = |table: Option| table.and_then(|t| t.get("output").cloned()); + let mut prefs = photocraft_engine::prefs::Preferences::default(); + prefs.dialogs.insert(key.into(), json!({"output": "current"})); + move_memories(&mut prefs, &host); + assert_eq!(prefs.dialogs.get(key), Some(&json!({"output": "current"})), "the engine's copy stays"); + assert_eq!(output(workspace.recall(&host)), Some(toml::Value::String("current".into())), "an empty workspace memory gets it"); + + prefs.dialogs.insert(key.into(), json!({"output": "new"})); + move_memories(&mut prefs, &host); + assert_eq!(output(workspace.recall(&host)), Some(toml::Value::String("current".into())), "the workspace's own memory wins"); + assert_eq!(prefs.dialogs.get(key), Some(&json!({"output": "new"}))); +} + struct MarkA; struct MarkB; diff --git a/crates/ui-egui/src/jobs_ui.rs b/crates/ui-egui/src/jobs_ui.rs index ef932e8bbd..f01e730403 100644 --- a/crates/ui-egui/src/jobs_ui.rs +++ b/crates/ui-egui/src/jobs_ui.rs @@ -183,6 +183,8 @@ pub struct JobsUi { /// The file being placed in the background, if any. One at a time: files dropped meanwhile /// wait in the app's drop queue. pub place: Option, + /// Content-Aware Fill settings waiting for their background fill: remembered when it is applied (#14254). + pub(crate) caf_settings: Vec<(JobId, Value)>, } /// Run command `id`: in the background when background jobs are on and the command is a job @@ -607,6 +609,7 @@ fn on_event(app: &mut PhotocraftApp, ctx: &egui::Context, e: JobEvent) { } // A Free Transform commit's session ends with its job (then reported like any job). crate::transform_tool::on_job_event(app, &e); + crate::caf_ui::on_job_event(app, &e); if crate::prefs_ui::on_recovery_event(app, &e) { return; } diff --git a/crates/ui-egui/src/panels/actions/runner.rs b/crates/ui-egui/src/panels/actions/runner.rs index 96cc04fcd3..e7ef3a91a1 100644 --- a/crates/ui-egui/src/panels/actions/runner.rs +++ b/crates/ui-egui/src/panels/actions/runner.rs @@ -772,12 +772,24 @@ pub(crate) fn report_play(app: &mut PhotocraftApp, v: &Value) { }; let step = failed.get("step").and_then(Value::as_u64).unwrap_or(0); let id = failed.get("id").and_then(Value::as_str).unwrap_or(""); - let error = failed.get("error").and_then(Value::as_str).unwrap_or(""); + let error = step_error(failed.get("error").and_then(Value::as_str).unwrap_or("")); let template = "Step {step} ({id}) failed: {error}"; app.ui.status = crate::i18n::fmt(tl!(template), &[("step", &(step + 1).to_string()), ("id", id), ("error", error)]); app.ui.status_error = true; } +/// A failed step's `error` in the UI language when the engine's message is one the shell spells out, otherwise as the +/// engine gave it. Automation clients keep the engine's English. +fn step_error(error: &str) -> &str { + if error.ends_with(photocraft_engine::atn_cmds::CAF_CUSTOM_AREA_NOT_REMEMBERED) { + // The engine's text, as a literal the translation coverage report collects (#14254). + return tl!( + "This step plays with the remembered Content-Aware Fill settings, and their Custom sampling area isn't remembered. Fill once with Auto or Rectangular sampling in Content-Aware Fill, then play it again." + ); + } + error +} + /// Resume the recording a paused call suspended and journal that call, once. fn restore_recording(app: &mut PhotocraftApp, owner: Option<&Value>) { let Some(owner) = owner else { return }; diff --git a/docs/atn.md b/docs/atn.md index 7609096314..87a3de3701 100644 --- a/docs/atn.md +++ b/docs/atn.md @@ -411,35 +411,42 @@ stored descriptor no longer describes it. ### Content-Aware Fill recordings -`cafWorkspace` maps Rectangular / Default color adaptation / None rotation with New Layer or -Current Layer output to `edit.contentAwareFill`, retaining all seven keys and the three booleans: -Sample All Layers, Scale and Mirror. The selection comes from the preceding selection step. -New Layer is in the measured reference; Current Layer and the enumeration type IDs are explicit -in [Stephen Marsh's published Action Manager example](https://community.adobe.com/questions-712/expand-and-content-aware-fill-functions-are-not-working-via-javascript-1172085). +`cafWorkspace` maps every value the reference workspace shows to `edit.contentAwareFill`, +retaining all seven keys and the three booleans: Sample All Layers, Scale and Mirror. The +selection comes from the preceding selection step. The values were measured by playing each +step with dialogs on (#14254); the enumeration type IDs are explicit in +[Stephen Marsh's published Action Manager example](https://community.adobe.com/questions-712/expand-and-content-aware-fill-functions-are-not-working-via-javascript-1172085). -| Recorded key, in order | Supported value | Native parameter | +| Recorded key, in order | Supported values | Native parameter | |---|---|---| -| `cafSamplingRegion` | `cafSamplingRegionRectangular` | `sampling: "rectangular"` | +| `cafSamplingRegion` | `cafSamplingRegionAuto`, `…Rectangular`, `…Custom` | `sampling: "auto"`, `"rectangular"`, `"custom"` | | `cafSampleAllLayers` | boolean | `sampleAllLayers` | -| `cafColorAdaptationLevel` | `cafColorAdaptationDefault` | `colorAdaptation: "default"` | -| `cafRotationAmount` | `cafRotationAmountNone` | `rotationAdaptation: "none"` | +| `cafColorAdaptationLevel` | `cafColorAdaptationNone`, `…Default`, `…High`, `…VeryHigh` | `colorAdaptation: "none"`, `"default"`, `"high"`, `"veryHigh"` | +| `cafRotationAmount` | `cafRotationAmountNone`, `…Low`, `…Medium`, `…High`, `…Full` | `rotationAdaptation: "none"`, `"low"`, `"medium"`, `"high"`, `"full"` | | `cafScale` | boolean | `scale` | | `cafMirror` | boolean | `mirror` | -| `cafOutput` | `cafOutputToNewLayer`, `cafOutputToCurrentLayer` | `output: "new"`, `"current"` | +| `cafOutput` | `cafOutputToCurrentLayer`, `…NewLayer`, `…DuplicateLayer` | `output: "current"`, `"new"`, `"duplicate"` | + +An empty descriptor (no keys) plays with the settings the fill workspace remembers +(`prefs.dialogs["edit.contentAwareFill.workspace"]`), New Layer before any are remembered; it +imports as `{"_atnCafRemembered": true}`, which `playback_params` resolves, and saves back +empty. Playing a step never changes what is remembered. When the remembered sampling is Custom, +the step stops with a message instead of filling: the workspace doesn't remember the painted +Custom area (Custom reopens empty), and the step must not sample another area instead. Descriptor types, source identity and key order survive save while its native settings are unchanged. Editing a supported setting exports the new values in canonical form instead of restoring stale source values; malformed preservation data still refuses export. -Native export writes the seven keys explicitly; the known native boolean, color -adaptation, rotation and Current Layer output defaults are supported when sampling is explicitly -Rectangular. A native call using the Auto sampling default cannot yet be exported. +Native export writes the seven keys explicitly, including the command's own defaults (Auto +sampling, Current Layer output). A native step without `sampleAllLayers` refuses export: on an +empty layer the command then samples the visible composite, which neither recorded value says. -The reference's ellipses do not establish additional enum forms. Auto/Custom sampling, -other adaptation levels, Duplicate Layer output, absent keys, unknown settings and -malformed or repeated fields remain complete kept steps. Native layer targets, sampling/fill -edits and nondefault seeds also refuse export rather than lose their settings. Playback uses -the existing native fill and its selection, authorization, job and Undo/Redo behavior. The -remaining CAF forms and the other recorded tools in #10710 are still separate work. +Steps that carry only some of the seven keys (not measured), unknown settings and malformed +or repeated fields remain complete kept steps. Native layer targets, sampling/fill edits and +nondefault seeds also refuse export rather than lose their settings. Playback uses the existing +native fill and its selection, authorization, job and Undo/Redo behavior; Custom sampling +without a painted sampling area fails the step with the command's error. The other recorded +tools in #10710 are still separate work. ### Layer Style menu recordings