PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Merge PR #7249: fix(atn): reject non-replace select.rect modes in .atn export (#7194)
aiongg79ff67c3f2e5
diff --cc crates/engine/src/atn_cmds.rsindex 7bc402c34,3441f8d95..8df9be10f--- a/crates/engine/src/atn_cmds.rs+++ b/crates/engine/src/atn_cmds.rs@@@ -1493,22 -1353,11 +1493,26 @@@ fn set_to(id: &str, p: &Value) -> Optio}desc("null").with("null", quick_mask_ref())}+ "tools.setColors" => {+ // One colour per Photoshop step: a step that sets both (or any other key) doesn't+ // export rather than lose one.+ if p.as_object().is_some_and(|o| o.keys().any(|k| k != "foreground" && k != "background")) {+ return None;+ }+ let (key, hex) = match (jstr(p, "foreground"), jstr(p, "background")) {+ (Some(f), None) => ("FrgC", f),+ (None, Some(b)) => ("BckC", b),+ _ => return None,+ };+ desc("null")+ .with("null", D::Reference(vec![ReferenceItem::Property { class: class("Clr "), key: code(key) }]))+ .with("T ", D::Descriptor(color_desc(hex)?))+ }"select.rect" => {+ match jstr(p, "mode") {+ None | Some("replace") => {}+ Some(_) => return None,+ }let (x, y, w, h) = (jnum(p, "x")?, jnum(p, "y")?, jnum(p, "width")?, jnum(p, "height")?);let cls = if jbool(p, "ellipse") == Some(true) { "Elps" } else { "Rctn" };sel(D::Descriptor(desc(cls).with("Top ", px(y)).with("Left", px(x)).with("Btom", px(y + h)).with("Rght", px(x + w))))diff --cc crates/engine/src/atn_cmds/tests.rsindex 39a6cbe30,2106123a7..2eeafaecb--- a/crates/engine/src/atn_cmds/tests.rs+++ b/crates/engine/src/atn_cmds/tests.rs@@@ -1901,155 -1388,32 +1901,185 @@@ fn function_keys_keep_shift_and_commandassert_eq!(super::function_key_name(7, false, false), "F7");}+/// A param a PhotoCraft step leaves out exports as PhotoCraft's default wherever Photoshop plays+/// the missing key differently (checked against Photoshop): Canvas Size anchors top left,+/// Apply Image blends Normal, Color Balance turns preserve luminosity off, and a Paint Bucket+/// step without a tolerance doesn't play at all.+#[test]+fn defaults_photoshop_plays_differently_are_written() {+ let exported = |id: &str, p: Value| export_item(id, &p, "S").and_then(|i| i.descriptor).unwrap_or_else(|| panic!("{id} does not export"));+ let bucket = exported("paint.bucket", json!({"x": 1, "y": 2}));+ assert_eq!((get_num(&bucket, "Tlrn"), get_bool(&bucket, "AntA")), (Some(32.0), Some(true)));+ let canvas = exported("image.canvasSize", json!({"width": 10, "height": 10}));+ assert_eq!((get_enum(&canvas, "Hrzn").as_deref(), get_enum(&canvas, "Vrtc").as_deref()), (Some("Cntr"), Some("Cntr")));+ let apply = exported("image.applyImage", json!({}));+ assert_eq!(get_obj(&apply, "With").and_then(|w| get_enum(w, "Clcl")).as_deref(), Some("Mltp"));+ let balance = exported("image.adjustments.colorBalance", json!({"midtones": [10, 0, 0]}));+ assert_eq!(get_bool(&balance, "PrsL"), Some(true));+ assert_eq!(get_list(&balance, "ShdL").map(<[D]>::len), Some(3));+}++/// Photoshop sets one colour per step: a step that sets both doesn't export rather than drop one.+#[test]+fn set_colors_exports_only_a_single_colour() {+ assert!(export_item("tools.setColors", &json!({"foreground": "#ff0000", "background": "#0000ff"}), "S").is_none());+ assert!(export_item("tools.setColors", &json!({"foregroundCmyk": [0, 0, 0, 100], "background": "#0000ff"}), "S").is_none());+ assert!(export_item("tools.setColors", &json!({"background": "#0000ff"}), "S").is_some());+}++/// Photoshop's reset of an adjustment layer (`set` with an empty `T`) stays a reset: `kind`+/// only joins params that edit something, as any key makes `layer.setAdjustment` merge.+#[test]+fn adjustment_layer_reset_still_resets() {+ let set = |t: Descriptor| desc("null").with("null", target_ref("AdjL")).with("T ", D::Descriptor(t));+ let reset = set(desc("HStr").with("presetKind", enm("presetKindType", "presetKindDefault")));+ let edit = set(desc("ClrB").with("MdtL", D::List(vec![long(10.0), long(0.0), long(0.0)])));+ let file = AtnFile {+ name: UnicodeString::new_nul("Reset"),+ expanded: false,+ actions: vec![AtnAction {+ name: UnicodeString::new_nul("A"),+ items: vec![item("setd", "Set", Some(reset)), item("setd", "Set", Some(edit))],+ ..Default::default()+ }],+ warnings: vec![],+ };+ let steps = import(&atn::write(&file).unwrap()).unwrap().actions.remove(0).steps;+ assert_eq!(steps[0], ("layer.setAdjustment".to_string(), json!({})));+ assert_eq!(steps[1].1, json!({"midtones": [10, 0, 0], "kind": "colorBalance"}));+}++/// A Free Transform recorded against an unlinked mask or an alpha channel must not export as a+/// layer transform that moves the layer's pixels on replay (#7195).+#[test]+fn transform_with_mask_or_channel_target_is_not_exported_as_layer_transform() {+ for target in [json!("mask"), json!({"channel": 0}), json!("quickMask")] {+ let a = Action {+ name: "Probe".into(),+ steps: vec![("edit.transform".into(), json!({"target": target, "dx": 3, "dy": 2, "scaleX": 100, "interpolation": "nearest"}))],+ ..Default::default()+ };+ assert!(export("Targets", &[&a], &[], false).is_err(), "{target} exported");+ let (_, skipped) = export("Targets", &[&a], &[], true).unwrap();+ assert_eq!(skipped, vec![Skipped { action: "Probe".into(), step: 0, id: "edit.transform".into() }]);+ }+ for params in [+ json!({"dx": 3, "dy": 2, "scaleX": 50, "interpolation": "nearest"}),+ json!({"target": "pixels", "dx": 3, "dy": 2, "scaleX": 50, "interpolation": "nearest"}),+ ] {+ let plain = Action { name: "Plain".into(), steps: vec![("edit.transform".into(), params)], ..Default::default() };+ let (bytes, skipped) = export("Targets", &[&plain], &[], false).unwrap();+ assert!(skipped.is_empty());+ let imported = import(&bytes).unwrap();+ assert_eq!(imported.actions[0].steps, vec![("edit.transform".to_string(), json!({"dx": 3, "dy": 2, "scaleX": 50, "interpolation": "nearest"}))]);+ }+ for form in [json!({"quad": [[0, 0], [1, 0], [1, 1], [0, 1]]}), json!({"matrix": [1, 0, 0, 1, 0, 0]}), json!({"rect": [0, 0, 1, 1]})] {+ assert!(transform_to("edit.transform", &form).is_none());+ }+}++/// Apply Image's optional blending mask has no `.atn` mapping: a strict export must refuse the+/// step rather than drop the mask and widen the edit to the whole layer.+#[test]+fn apply_image_with_blending_mask_is_not_exported_without_its_mask() {+ let source = json!({"layer": "Pixels", "channel": "green", "invert": true});+ for params in [json!({"source": source, "blending": "normal", "mask": {"channel": 0}}), json!({"source": source, "blending": "normal", "maskChannel": 0})] {+ let masked = Action { name: "Masked".into(), steps: vec![("image.applyImage".into(), params.clone())], ..Default::default() };+ assert!(export("Audit5", &[&masked], &[], false).is_err(), "{params}");+ let (_, skipped) = export("Audit5", &[&masked], &[], true).unwrap();+ assert_eq!(skipped, vec![Skipped { action: "Masked".into(), step: 0, id: "image.applyImage".into() }]);+ }+ for params in [json!({"source": source, "blending": "normal"}), json!({"source": source, "blending": "normal", "mask": {"channel": "none"}})] {+ let plain = Action { name: "Plain".into(), steps: vec![("image.applyImage".into(), params.clone())], ..Default::default() };+ let (bytes, skipped) = export("Audit5", &[&plain], &[], false).unwrap();+ assert!(skipped.is_empty());+ let imported = import(&bytes).unwrap();+ assert_eq!(imported.actions[0].steps, vec![("image.applyImage".to_string(), json!({"source": source, "blending": "normal"}))]);+ }+}++fn image_size_round_trip(params: &Value) -> Option<Value> {+ let item = export_item("image.imageSize", params, "S")?;+ let e = event_for(&item.event).unwrap();+ match (e.from)(item.descriptor.as_ref().unwrap()) {+ Mapped::Steps(steps) => Some(steps[0].1.clone()),+ _ => panic!("image size descriptor did not import as steps"),+ }+}++#[test]+fn image_size_resolution_only_does_not_gain_keep_print_size() {+ // The .atn cannot tell resolution-only from keepPrintSize:true, so the former must not+ // export as a descriptor that imports back as keep-print-size.+ let params = json!({"resolution": 144, "resample": "nearest"});+ assert_eq!(image_size_round_trip(¶ms), None);+}++#[test]+fn image_size_intentional_controls_still_round_trip() {+ for params in [+ json!({"resolution": 144.0, "resample": "nearest", "keepPrintSize": true}),+ json!({"width": 12.0, "height": 10.0, "resolution": 144.0, "resample": "nearest"}),+ ] {+ assert_eq!(image_size_round_trip(¶ms), Some(params.clone()));+ }+}++#[test]+fn recorded_layer_select_exports_to_atn() {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 8, "height": 8})).unwrap();+ let l = s.execute("layer.new.layer", json!({"name": "Wanted"})).unwrap();+ let wanted_id = l["layer"].as_u64().unwrap();+ s.execute("actions.record", json!({"name": "SelectWanted"})).unwrap();+ s.execute("layer.select", json!({"layer": wanted_id})).unwrap();+ s.execute("actions.stop", json!({})).unwrap();++ let action = s.execute("actions.get", json!({"action": "SelectWanted"})).unwrap();+ assert_eq!(action["steps"][0], json!(["layer.select", {"name": "Wanted"}]));++ // Strict export should succeed and produce bytes without skipUnsupported+ let saved = s.execute("actions.save", json!({"action": "SelectWanted"})).unwrap();+ assert_eq!(saved["steps"], 1);+ assert_eq!(saved["skipped"], json!([]));++ // When exported with skipUnsupported: true, it shouldn't skip the step either+ let saved_skip = s.execute("actions.save", json!({"action": "SelectWanted", "skipUnsupported": true})).unwrap();+ assert_eq!(saved_skip["steps"], 1);+ assert_eq!(saved_skip["skipped"], json!([]));++ // If an action has an occurrence target (duplicate names), it cannot be represented unambiguously in .atn+ let bad_action = Action::new("Dup", vec![("layer.select".into(), json!({"name": "Wanted", "occurrence": 1}))]);+ let err = export("Set", &[&bad_action], &[], false);+ assert!(err.is_err(), "occurrence without representation must fail strict export");+}+++ #[test]+ fn select_rect_mode_strict_export_rejects_unrepresentable_modes() {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 8, "height": 8})).unwrap();++ // Default or "replace" mode succeeds+ s.actions.list.push(Action::new("ReplaceAct", vec![("select.rect".into(), json!({"x": 4, "y": 4, "width": 2, "height": 2, "mode": "replace"}))]));+ let saved = s.execute("actions.save", json!({"action": "ReplaceAct"})).unwrap();+ assert_eq!(saved["steps"], 1);++ // "add" mode cannot be silently converted to replace (set) in strict export+ s.actions.list.push(Action::new("AddAct", vec![("select.rect".into(), json!({"x": 4, "y": 4, "width": 2, "height": 2, "mode": "add"}))]));+ let before_actions = s.actions.list.clone();+ let err = s.execute("actions.save", json!({"action": "AddAct"}));+ assert!(err.is_err(), "strict export must reject select.rect with add mode rather than converting to replace");+ assert_eq!(s.actions.list, before_actions, "actions list must remain unchanged after rejected save");++ // "subtract" mode cannot be silently converted to replace either+ s.actions.list.push(Action::new("SubtractAct", vec![("select.rect".into(), json!({"x": 4, "y": 4, "width": 2, "height": 2, "mode": "subtract"}))]));+ let before_actions_sub = s.actions.list.clone();+ let err_subtract = s.execute("actions.save", json!({"action": "SubtractAct"}));+ assert!(err_subtract.is_err(), "strict export must reject select.rect with subtract mode rather than converting to replace");+ assert_eq!(s.actions.list, before_actions_sub, "actions list must remain unchanged after rejected save");++ // With skipUnsupported: true, unrepresentable modes are reported in skipped+ let skipped = s.execute("actions.save", json!({"action": "AddAct", "skipUnsupported": true})).unwrap();+ assert_eq!(skipped["steps"], 0);+ assert_eq!(skipped["skipped"][0]["id"], "select.rect");+ }