diff --git a/crates/engine-core/src/cmd/atn_cmds/steps_doc.rs b/crates/engine-core/src/cmd/atn_cmds/steps_doc.rs index b91bca14b8..9dcc36a101 100644 --- a/crates/engine-core/src/cmd/atn_cmds/steps_doc.rs +++ b/crates/engine-core/src/cmd/atn_cmds/steps_doc.rs @@ -326,10 +326,12 @@ pub(super) fn convert_mode_to(id: &str, p: &Value) -> Option { pub(super) fn canvas_size_from(d: &Descriptor) -> Mapped { let mut p = Map::new(); let mut units = None; + // A relative percentage is a change, so zero and below (a shrink) are valid there. + let relative = matches!(d.get("Rltv"), Some(D::Boolean(true))); for (k, param) in [("Wdth", "width"), ("Hght", "height")] { match d.get(k) { Some(D::UnitFloat { unit, value }) if (*unit == PX || *unit == PCT) && value.is_finite() => { - if units.is_some_and(|previous| previous != *unit) || (*unit == PCT && *value <= 0.0) { + if units.is_some_and(|previous| previous != *unit) || (*unit == PCT && !relative && *value <= 0.0) { return Mapped::Unsupported { harmless: false }; } units = Some(*unit); @@ -340,7 +342,7 @@ pub(super) fn canvas_size_from(d: &Descriptor) -> Mapped { } } if units == Some(PCT) { - if !matches!(d.get("Rltv"), None | Some(D::Boolean(false))) { + if !matches!(d.get("Rltv"), None | Some(D::Boolean(_))) { return Mapped::Unsupported { harmless: false }; } p.insert("units".into(), "percent".into()); @@ -389,12 +391,14 @@ pub(super) fn canvas_size_to(_: &str, p: &Value) -> Option { let units = match p.get("units") { None => PX, Some(Value::String(unit)) if unit == "px" => PX, - Some(Value::String(unit)) if unit == "percent" && jbool(p, "relative") != Some(true) => PCT, + Some(Value::String(unit)) if unit == "percent" => PCT, _ => return None, }; + // A relative percentage may be zero or negative (a shrink); an absolute one is a size. + let relative = jbool(p, "relative") == Some(true); if units == PCT { for key in ["width", "height"] { - if p.get(key).is_some_and(|value| !value.is_null() && value.as_f64().is_none_or(|number| !number.is_finite() || number <= 0.0)) { + if p.get(key).is_some_and(|value| !value.is_null() && value.as_f64().is_none_or(|number| !number.is_finite() || (!relative && number <= 0.0))) { return None; } } @@ -422,13 +426,13 @@ pub(super) fn canvas_size_to(_: &str, p: &Value) -> Option { d = d.with("Rltv", D::Boolean(r)); } if let Some(w) = jnum(p, "width") { - if units == PCT && w <= 0.0 { + if units == PCT && !relative && w <= 0.0 { return None; } d = d.with("Wdth", D::UnitFloat { unit: units, value: w }); } if let Some(hh) = jnum(p, "height") { - if units == PCT && hh <= 0.0 { + if units == PCT && !relative && hh <= 0.0 { return None; } d = d.with("Hght", D::UnitFloat { unit: units, value: hh }); diff --git a/crates/engine-core/src/cmd/image_cmds.rs b/crates/engine-core/src/cmd/image_cmds.rs index cbc91c51d9..ad5178fbae 100644 --- a/crates/engine-core/src/cmd/image_cmds.rs +++ b/crates/engine-core/src/cmd/image_cmds.rs @@ -717,12 +717,22 @@ fn canvas_size(s: &mut Session, p: &Value) -> Result { let relative = p.get("relative").and_then(Value::as_bool).unwrap_or(false); let (w, h) = if size_units(p, "image.canvasSize", &["px", "percent"])? == "percent" { if relative { - return Err(bad("image.canvasSize", "percentage dimensions require an absolute canvas size")); + // A share of each current side, added to it: 50 grows a side by half, -50 halves it. + let delta = |key: &str, side: f64| match p.get(key).filter(|value| !value.is_null()) { + None => Ok(0.0), + Some(value) => value + .as_f64() + .filter(|value| value.is_finite()) + .map(|value| value * side / 100.0) + .ok_or_else(|| bad("image.canvasSize", format!("`{key}` must be a number"))), + }; + (delta("width", ow)?, delta("height", oh)?) + } else { + ( + scaled_dimension(p, "width", ow / 100.0, "image.canvasSize")?.unwrap_or(ow), + scaled_dimension(p, "height", oh / 100.0, "image.canvasSize")?.unwrap_or(oh), + ) } - ( - scaled_dimension(p, "width", ow / 100.0, "image.canvasSize")?.unwrap_or(ow), - scaled_dimension(p, "height", oh / 100.0, "image.canvasSize")?.unwrap_or(oh), - ) } else { ( p.get("width").and_then(Value::as_f64).unwrap_or(if relative { 0.0 } else { ow }), @@ -1268,7 +1278,7 @@ pub fn specs() -> Vec { "image.canvasSize", "Canvas Size…", ["Image"], - r##"{"width":number,"height":number,"units":"px|percent"="px" (percent uses each current side; absolute sizes only),"relative":bool=false,"anchor":"topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight"="center","extensionColor":"background|foreground|white|black|gray|transparent|#rrggbb"="background"}"##, + r##"{"width":number,"height":number,"units":"px|percent"="px" (percent uses each current side; relative percent adds that share, so -50 halves a side),"relative":bool=false,"anchor":"topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight"="center","extensionColor":"background|foreground|white|black|gray|transparent|#rrggbb"="background"}"##, has_doc, canvas_size ), @@ -1334,6 +1344,9 @@ mod duplicate_selection_tests; #[cfg(test)] mod tests; +#[cfg(test)] +mod canvas_size_relative_percent_tests; + #[cfg(test)] mod canvas_size_selection_tests; diff --git a/crates/engine-core/src/cmd/image_cmds/canvas_size_relative_percent_tests.rs b/crates/engine-core/src/cmd/image_cmds/canvas_size_relative_percent_tests.rs new file mode 100644 index 0000000000..e219bdad2d --- /dev/null +++ b/crates/engine-core/src/cmd/image_cmds/canvas_size_relative_percent_tests.rs @@ -0,0 +1,117 @@ +//! #14541: Canvas Size with Relative on takes Percent, as the reference application does. The +//! percentage is of each current side and is added to it, so +50 % on 400 x 300 px gives +//! 600 x 450 px and -50 % gives 200 x 150 px. A recorded step with `Rltv` and percent plays back +//! the same way, and the result is clamped to 1..=300000 px as in absolute mode. + +use craft_psd::atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}; +use craft_psd::descriptor::{Descriptor, UnicodeString, Value as D}; +use serde_json::{Value, json}; + +use crate::Session; +use crate::actions_cmds::{Action, ActionStep}; + +fn doc(width: u32, height: u32) -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": width, "height": height, "background": "white"})).unwrap(); + s +} + +fn size(s: &Session) -> (u32, u32) { + let d = &s.active().unwrap().doc; + (d.size.width, d.size.height) +} + +fn relative_percent(width: f64, height: f64) -> Value { + json!({"units": "percent", "relative": true, "width": width, "height": height}) +} + +/// A recorded Canvas Size step with Relative on and both sides in percent. +fn recorded_step(width: f64, height: f64) -> Descriptor { + Descriptor::new("null") + .with("Rltv", D::Boolean(true)) + .with("Wdth", D::UnitFloat { unit: *b"#Prc", value: width }) + .with("Hght", D::UnitFloat { unit: *b"#Prc", value: height }) +} + +/// One action file holding a single recorded Canvas Size step. +fn action_file(descriptor: Descriptor) -> Vec { + atn::write(&AtnFile { + name: UnicodeString::new_nul("Canvas"), + actions: vec![AtnAction { + name: UnicodeString::new_nul("Step"), + items: vec![AtnItem { event: AtnEvent::Code(*b"CnvS"), dictionary: b"CnvS".to_vec(), descriptor: Some(descriptor), ..Default::default() }], + ..Default::default() + }], + ..Default::default() + }) + .unwrap() +} + +#[test] +fn a_relative_percentage_is_added_to_each_side() { + let mut s = doc(400, 300); + s.execute("image.canvasSize", relative_percent(50.0, 50.0)).unwrap(); + assert_eq!(size(&s), (600, 450)); + + let mut s = doc(400, 300); + s.execute("image.canvasSize", relative_percent(-50.0, -50.0)).unwrap(); + assert_eq!(size(&s), (200, 150)); + + // An omitted side keeps its size. + let mut s = doc(400, 300); + s.execute("image.canvasSize", json!({"units": "percent", "relative": true, "width": 25})).unwrap(); + assert_eq!(size(&s), (500, 300)); +} + +#[test] +fn a_relative_percentage_is_clamped_like_an_absolute_size() { + let mut s = doc(400, 300); + s.execute("image.canvasSize", relative_percent(-100.0, -1000.0)).unwrap(); + assert_eq!(size(&s), (1, 1)); + + let mut s = doc(1, 1); + s.execute("image.canvasSize", json!({"units": "percent", "relative": true, "width": 1e12})).unwrap(); + assert_eq!(size(&s), (300_000, 1)); +} + +#[test] +fn a_relative_percentage_that_is_not_a_number_is_refused_without_a_change() { + let mut s = doc(400, 300); + for bad in [json!("50"), json!(true), json!([50])] { + let err = s.execute("image.canvasSize", json!({"units": "percent", "relative": true, "width": bad})).unwrap_err(); + assert!(err.to_string().contains("`width`"), "{err}"); + assert_eq!(size(&s), (400, 300)); + } +} + +#[test] +fn a_recorded_relative_percent_step_plays_back_as_the_command() { + // A width-only step grows the width and keeps the omitted height. + let width_only = Descriptor::new("null").with("Rltv", D::Boolean(true)).with("Wdth", D::UnitFloat { unit: *b"#Prc", value: 200.0 }); + for (case, step, expected) in + [("+50 %", recorded_step(50.0, 50.0), (600, 450)), ("-50 %", recorded_step(-50.0, -50.0), (200, 150)), ("width +200 %", width_only, (1200, 300))] + { + let mut s = doc(400, 300); + let data = photocraft_paint::tile::b64_encode(&action_file(step)); + let loaded = s.execute("actions.load", json!({"data": data})).unwrap(); + assert_eq!(loaded["unsupported"], json!([]), "{case}"); + let result = s.execute("actions.play", json!({"action": loaded["actions"][0]})).unwrap(); + assert!(result.get("failed").is_none(), "{result}"); + assert_eq!(size(&s), expected, "{case}"); + } +} + +#[test] +fn a_relative_percent_step_saves_and_reloads_unchanged() { + for pct in [50.0, -50.0] { + let step = ActionStep::new("image.canvasSize", json!({"units": "percent", "relative": true, "width": pct, "height": pct, "anchor": "center"})); + let action = Action::new("Recorded", vec![step.clone()]); + let (bytes, _) = crate::atn_cmds::export("Canvas", &[&action], &[], false).unwrap(); + let imported = crate::atn_cmds::import(&bytes).unwrap(); + assert!(imported.unsupported.is_empty(), "{pct} %"); + assert_eq!(imported.actions[0].steps[0].command, "image.canvasSize", "{pct} %"); + let params = &imported.actions[0].steps[0].params; + assert_eq!((¶ms["units"], ¶ms["relative"]), (&json!("percent"), &json!(true)), "{pct} %"); + assert_eq!((params["width"].as_f64(), params["height"].as_f64()), (Some(pct), Some(pct)), "{pct} %"); + } +} diff --git a/crates/engine/tests/it/atn_mapped_identifiers.rs b/crates/engine/tests/it/atn_mapped_identifiers.rs index 23c884a11a..7137db1c98 100644 --- a/crates/engine/tests/it/atn_mapped_identifiers.rs +++ b/crates/engine/tests/it/atn_mapped_identifiers.rs @@ -317,7 +317,8 @@ fn unrepresented_units_and_mode_choices_stay_verbatim() { (*b"CnvM", mode().with("Rstr", D::Boolean(true))), (*b"CnvM", mode().with("Rstr", D::Integer(0))), (*b"CnvS", canvas().with("Hght", D::UnitFloat { unit: *b"#Pxl", value: 40.0 })), - (*b"CnvS", canvas().with("Rltv", D::Boolean(true))), + // Relative percent maps since #14541; a Relative flag that is not a boolean still doesn't. + (*b"CnvS", canvas().with("Rltv", D::Integer(1))), (*b"ImgS", point().with("Hght", D::UnitFloat { unit: *b"#Pxl", value: 40.0 })), (*b"ImgS", point().with("Rslt", D::UnitFloat { unit: *b"#Rsl", value: 144.0 })), (*b"ImgS", point().with("CnsP", D::Boolean(false))), @@ -473,7 +474,7 @@ fn native_units_validate_before_edit_and_no_resample_remains_resolution_only() { for (id, params, refuse_export) in [ ("image.canvasSize", json!({"width":200,"units":"unknown"}), true), ("image.canvasSize", json!({"width":"200","units":"percent"}), true), - ("image.canvasSize", json!({"width":200,"units":"percent","relative":true}), true), + ("image.canvasSize", json!({"width":"200","units":"percent","relative":true}), true), ("image.imageSize", json!({"width":72,"units":1}), true), ("image.imageSize", json!({"width":"72","units":"pt"}), true), // A finite recorded point value is representable; overflow depends on playback dpi.