From 5f63b3fe4c4f524e91fd74bdc65378fa04481375 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 1 Nov 2026 17:51:02 +0100 Subject: [PATCH] Integration: address CodeRabbit review of batch 11 - #8714: a Camera Raw Filter step imports only with a process version the PSD mapping has verified (PrVN/PrVe 5/184549376 or 6/251920384) and a CrVe text; other steps stay kept steps that save back unchanged. - #7642: the patternName fallback matches names only, so a pattern whose id equals that text no longer wins. A step that names its pattern only by patternName exports that name. - #8327: the iso-2022-jp label is refused (its names are 7-bit escape sequences that would pass through as ASCII). - #10417: the Levels export gate also refuses endpoints of the wrong shape (both ends text, a text gamma) and channels that aren't objects. - #10459: a set paused at a step dialog keeps the rest of the set by action name, so actions.move while the dialog is open neither plays a foreign action nor skips one; "Played N steps" covers the whole Play (steps before the pause and the dialog's own step); the suggested .atn name is cut to 255 bytes at a character boundary; actions.list returns every set, empty ones too; set_names dedups with a HashSet. Co-authored-by: FinnNk <1424666+FinnNk@users.noreply.github.com> Co-authored-by: Silvertree2010 <133535268+Silvertree2010@users.noreply.github.com> Co-authored-by: regexer <3689390+regexer@users.noreply.github.com> Co-authored-by: marshiyar <57055687+marshiyar@users.noreply.github.com> Co-authored-by: hectorviov <1501713+hectorviov@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/actions_cmds.rs | 4 +- crates/engine/src/cmd/actions_edit_cmds.rs | 11 +-- crates/engine/src/cmd/atn_cmds/adjustments.rs | 8 +- crates/engine/src/cmd/atn_cmds/steps_image.rs | 8 +- crates/engine/src/cmd/atn_cmds/steps_make.rs | 4 +- crates/engine/src/cmd/atn_cmds/tests.rs | 91 ++++++++++++++----- crates/engine/src/cmd/pattern_cmds.rs | 6 +- crates/psd/src/codepage.rs | 10 +- crates/ui-egui/src/panels/actions.rs | 60 ++++++++---- crates/ui-egui/src/panels/actions/tests.rs | 63 ++++++++++++- 10 files changed, 204 insertions(+), 61 deletions(-) diff --git a/crates/engine/src/cmd/actions_cmds.rs b/crates/engine/src/cmd/actions_cmds.rs index b9f98b98297..ea68d86b509 100644 --- a/crates/engine/src/cmd/actions_cmds.rs +++ b/crates/engine/src/cmd/actions_cmds.rs @@ -339,7 +339,7 @@ fn from_step(p: &Value, len: usize) -> Result { fn list(s: &mut Session, _p: &Value) -> Result { let actions: Vec = s.actions.list.iter().map(|a| json!({"name": a.name, "steps": a.steps.len(), "set": a.set})).collect(); let recording = s.actions.recording.and_then(|(_, i)| s.actions.list.get(i).map(|a| a.name.clone())); - Ok(json!({"actions": actions, "recording": recording})) + Ok(json!({"actions": actions, "sets": crate::actions_edit_cmds::set_names(s), "recording": recording})) } fn get(s: &mut Session, p: &Value) -> Result { @@ -760,7 +760,7 @@ pub fn specs() -> Vec { label: "List Actions", menu: &[], shortcut: None, - params: "{} → {actions:[{name, steps:count, set:name|null}], recording:name|null}", + params: "{} → {actions:[{name, steps:count, set:name|null}], sets:[name…] (every set in panel order, empty ones too), recording:name|null}", enabled: always, run: list, journal: false, diff --git a/crates/engine/src/cmd/actions_edit_cmds.rs b/crates/engine/src/cmd/actions_edit_cmds.rs index 380fc764e9d..f8e4da4f54d 100644 --- a/crates/engine/src/cmd/actions_edit_cmds.rs +++ b/crates/engine/src/cmd/actions_edit_cmds.rs @@ -130,13 +130,8 @@ fn assign_set(s: &mut Session, p: &Value) -> Result { /// Every set name, in the Actions panel's order: the sets of the actions as they first appear, /// then the empty ones New Set made. pub fn set_names(s: &Session) -> Vec { - let mut names: Vec = Vec::new(); - for set in s.actions.list.iter().filter_map(|a| a.set.as_ref()).chain(&s.actions.sets) { - if !names.contains(set) { - names.push(set.clone()); - } - } - names + let mut seen = std::collections::HashSet::new(); + s.actions.list.iter().filter_map(|a| a.set.as_ref()).chain(&s.actions.sets).filter(|set| seen.insert(set.as_str())).cloned().collect() } /// New Set…: an empty set folder, named `name` or "Set N" (the first number no set has), that New @@ -463,6 +458,8 @@ mod tests { assert_eq!(s.execute("actions.newSet", json!({})).unwrap()["set"], "Set 2"); assert_eq!(s.execute("actions.newSet", json!({"name": " Retouch "})).unwrap()["set"], "Retouch"); assert_eq!(set_names(&s), ["Set 1", "Set 2", "Retouch"]); + // CodeRabbit on batch 11: Actions List names the empty sets too, so an agent can find them. + assert_eq!(s.execute("actions.list", json!({})).unwrap()["sets"], json!(["Set 1", "Set 2", "Retouch"])); assert!(s.execute("actions.newSet", json!({"name": "Set 1"})).is_err(), "a set an action is in"); assert!(s.execute("actions.newSet", json!({"name": "Retouch"})).is_err(), "an empty set"); assert!(s.execute("actions.newSet", json!({"name": " "})).is_err()); diff --git a/crates/engine/src/cmd/atn_cmds/adjustments.rs b/crates/engine/src/cmd/atn_cmds/adjustments.rs index 640d243f4e4..4b66e586586 100644 --- a/crates/engine/src/cmd/atn_cmds/adjustments.rs +++ b/crates/engine/src/cmd/atn_cmds/adjustments.rs @@ -69,11 +69,15 @@ fn levels_entry(chan: Option<&str>, p: &Value) -> Descriptor { /// Whether the Levels settings in `p` (the master curve and every channel object) name both ends /// of each range they touch, or neither. `levels_entry` writes a whole `Inpt` or `Otpt` pair and /// fills the end a partial edit left out with 0 or 255, so replaying `inBlack: 31` alone would -/// also reset a retained Input White (#8530). +/// also reset a retained Input White (#8530). A value given in a shape the writer can't read (a +/// text endpoint, a channel that isn't an object) would be left out, so it isn't complete either. pub(super) fn levels_complete(p: &Value) -> bool { + let shaped = + |v: &Value| ["inBlack", "inWhite", "gamma", "outBlack", "outWhite"].iter().all(|k| v.get(*k).is_none_or(|x| x.is_null() || jnum(v, k).is_some())); let pairs_whole = |v: &Value| [("inBlack", "inWhite"), ("outBlack", "outWhite")].iter().all(|(low, high)| jnum(v, low).is_some() == jnum(v, high).is_some()); - pairs_whole(p) && CHANNELS.iter().filter_map(|(_, k)| p.get(*k).filter(|v| v.is_object())).all(pairs_whole) + let whole = |v: &Value| shaped(v) && pairs_whole(v); + whole(p) && CHANNELS.iter().filter_map(|(_, k)| p.get(*k).filter(|v| !v.is_null())).all(|v| v.is_object() && whole(v)) } pub(super) fn levels_to(p: &Value) -> Option { diff --git a/crates/engine/src/cmd/atn_cmds/steps_image.rs b/crates/engine/src/cmd/atn_cmds/steps_image.rs index d3a0ec3465f..897544b1092 100644 --- a/crates/engine/src/cmd/atn_cmds/steps_image.rs +++ b/crates/engine/src/cmd/atn_cmds/steps_image.rs @@ -316,7 +316,8 @@ const CAMERA_RAW_GRADES: &[&str] = /// Settings the command has no counterpart for refuse the step rather than replaying a different /// look: the Calibration panel, a white balance other than Custom, the controls the PSD mapping /// keeps only at their neutral values, and any key outside this table (lens, geometry, profile, -/// masks…), as the PSD mapping's `known_key` does. +/// masks…), as the PSD mapping's `known_key` does, and a process version the PSD mapping hasn't +/// verified (Camera Raw renders each version differently). pub(super) fn camera_raw_from(d: &Descriptor) -> Mapped { const CALIBRATION: &[&str] = &["RHue", "RSat", "GHue", "GSat", "BHue", "BSat", "BlkB"]; const NEUTRAL_ONLY: &[(&str, f64)] = @@ -335,6 +336,11 @@ pub(super) fn camera_raw_from(d: &Descriptor) -> Mapped { if d.items.is_empty() || d.items.iter().any(|(k, _)| !std::str::from_utf8(k.as_bytes()).is_ok_and(known)) { return Mapped::Unsupported { harmless: false }; } + let version = (get_num(d, "PrVN"), get_num(d, "PrVe")); + let verified = [(5.0, 184_549_376.0), (6.0, 251_920_384.0)].iter().any(|(n, v)| version == (Some(*n), Some(*v))); + if !verified || !matches!(d.get("CrVe"), Some(D::Text(_))) { + return Mapped::Unsupported { harmless: false }; + } let active = |k: &str, neutral: f64| d.get(k).is_some() && get_num(d, k) != Some(neutral); let custom_wb = d.get("WBal").is_none() || get_enum(d, "WBal").as_deref() == Some("Cst"); if !custom_wb || CALIBRATION.iter().any(|k| active(k, 0.0)) || NEUTRAL_ONLY.iter().any(|(k, n)| active(k, *n)) { diff --git a/crates/engine/src/cmd/atn_cmds/steps_make.rs b/crates/engine/src/cmd/atn_cmds/steps_make.rs index c56d0a112f2..4a0fad4ef03 100644 --- a/crates/engine/src/cmd/atn_cmds/steps_make.rs +++ b/crates/engine/src/cmd/atn_cmds/steps_make.rs @@ -44,8 +44,8 @@ fn pattern_desc(p: &Value) -> Option { let mut t = desc("patternLayer"); match (jstr(p, "pattern"), jstr(p, "patternName")) { (Some(id), Some(n)) => t = t.with("Ptrn", D::Descriptor(desc("Ptrn").with("Nm ", text(n)).with("Idnt", text(id)))), - (Some(n), None) => t = t.with("Ptrn", D::Descriptor(desc("Ptrn").with("Nm ", text(n)))), - _ => {} + (Some(n), None) | (None, Some(n)) => t = t.with("Ptrn", D::Descriptor(desc("Ptrn").with("Nm ", text(n)))), + (None, None) => {} } if let Some(s) = jnum(p, "scale") { t = t.with("Scl ", pct(s)); diff --git a/crates/engine/src/cmd/atn_cmds/tests.rs b/crates/engine/src/cmd/atn_cmds/tests.rs index c06dd1576fb..5de59280525 100644 --- a/crates/engine/src/cmd/atn_cmds/tests.rs +++ b/crates/engine/src/cmd/atn_cmds/tests.rs @@ -2336,6 +2336,13 @@ fn partial_levels_edits_refuse_strict_export() { json!({"kind": "levels", "inBlack": 1, "inWhite": 250, "blue": {"outBlack": 3}}), // A value of the wrong shape is no value: the other end is then alone. json!({"kind": "levels", "inBlack": 31, "inWhite": "239"}), + // CodeRabbit on batch 11: both ends of the wrong shape, or a channel that isn't an object, + // would be written as nothing too. + json!({"kind": "levels", "inBlack": "31", "inWhite": "239"}), + json!({"kind": "levels", "gamma": "1.2"}), + json!({"kind": "levels", "red": 5}), + json!({"kind": "levels", "green": [0, 255]}), + json!({"kind": "levels", "blue": {"outBlack": "3", "outWhite": "250"}}), ] { let err = export("Audit8", &[&one(p.clone())], &[], false).unwrap_err(); assert!(err.contains("`layer.setAdjustment`"), "{p}: {err}"); @@ -3244,9 +3251,9 @@ fn hue_saturation_uses_photoshops_hue_key() { #[test] fn camera_raw_filter_steps_import_as_filter_camera_raw() { let int = |v: i32| D::Integer(v); - let mut d = desc("null") - .with("CrVe", D::Text(UnicodeString::new_nul("16.1.1"))) - .with("PrVe", int(184_549_376)) + // Every step carries the version keys a recording has (a verified process version). + let cr = || desc("null").with("CrVe", D::Text(UnicodeString::new_nul("16.1.1"))).with("PrVN", int(5)).with("PrVe", int(184_549_376)); + let mut d = cr() .with("WBal", enm("WBal", "Cst ")) .with("Temp", int(12)) .with("Tint", int(-4)) @@ -3278,21 +3285,28 @@ fn camera_raw_filter_steps_import_as_filter_camera_raw() { d = d.with(&format!("HA_{k}"), int(v)); } d = d.with("SA_O", int(-15)); - let calibrated = desc("null").with("Ex12", D::Double(0.2)).with("RHue", int(8)); - let smoothed = desc("null").with("CNR ", int(25)).with("CNRS", int(70)); - let auto_wb = desc("null").with("WBal", enm("WBal", "Atmt")).with("Temp", int(5)); - let partial_splits = desc("null").with("PC_1", int(20)); - let odd_curve = desc("null").with("Crv ", int(3)); + let calibrated = cr().with("Ex12", D::Double(0.2)).with("RHue", int(8)); + let smoothed = cr().with("CNR ", int(25)).with("CNRS", int(70)); + let auto_wb = cr().with("WBal", enm("WBal", "Atmt")).with("Temp", int(5)); + let partial_splits = cr().with("PC_1", int(20)); + let odd_curve = cr().with("Crv ", int(3)); // Review of #8714: values that would replay differently, or fail to play, stay Photoshop steps. - let reversed_splits = desc("null").with("PC_1", int(80)).with("PC_2", int(50)).with("PC_3", int(20)); - let split_past_100 = desc("null").with("PC_1", int(20)).with("PC_2", int(50)).with("PC_3", int(120)); - let one_point_curve = desc("null").with("Crv ", D::List([0, 0].map(int).to_vec())); - let unordered_curve = desc("null").with("CrvG", D::List([0, 0, 128, 90, 64, 50, 255, 255].map(int).to_vec())); - let text_contrast = desc("null").with("Cr12", D::Text(UnicodeString::new_nul("ten"))); - let text_hue = desc("null").with("HA_R", D::Text(UnicodeString::new_nul("red"))); - let text_grade = desc("null").with("STSH", D::Text(UnicodeString::new_nul("blue"))); - let exposure_past_5 = desc("null").with("Ex12", D::Double(6.0)); - let negative_sharpening = desc("null").with("Shrp", int(-10)); + let reversed_splits = cr().with("PC_1", int(80)).with("PC_2", int(50)).with("PC_3", int(20)); + let split_past_100 = cr().with("PC_1", int(20)).with("PC_2", int(50)).with("PC_3", int(120)); + let one_point_curve = cr().with("Crv ", D::List([0, 0].map(int).to_vec())); + let unordered_curve = cr().with("CrvG", D::List([0, 0, 128, 90, 64, 50, 255, 255].map(int).to_vec())); + let text_contrast = cr().with("Cr12", D::Text(UnicodeString::new_nul("ten"))); + let text_hue = cr().with("HA_R", D::Text(UnicodeString::new_nul("red"))); + let text_grade = cr().with("STSH", D::Text(UnicodeString::new_nul("blue"))); + let exposure_past_5 = cr().with("Ex12", D::Double(6.0)); + let negative_sharpening = cr().with("Shrp", int(-10)); + // CodeRabbit on batch 11: a process version the PSD mapping hasn't verified renders differently. + let unknown_version = + desc("null").with("CrVe", D::Text(UnicodeString::new_nul("16.1.1"))).with("PrVN", int(4)).with("PrVe", int(184_549_376)).with("Ex12", D::Double(0.2)); + let no_version_number = desc("null").with("CrVe", D::Text(UnicodeString::new_nul("16.1.1"))).with("PrVe", int(184_549_376)).with("Ex12", D::Double(0.2)); + let mismatched_pair = + desc("null").with("CrVe", D::Text(UnicodeString::new_nul("16.1.1"))).with("PrVN", int(6)).with("PrVe", int(184_549_376)).with("Ex12", D::Double(0.2)); + let no_camera_raw_version = desc("null").with("PrVN", int(5)).with("PrVe", int(184_549_376)).with("Ex12", D::Double(0.2)); let items = vec![ item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(d)), item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(calibrated)), @@ -3309,6 +3323,10 @@ fn camera_raw_filter_steps_import_as_filter_camera_raw() { item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(text_grade)), item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(exposure_past_5)), item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(negative_sharpening)), + item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(unknown_version)), + item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(no_version_number)), + item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(mismatched_pair)), + item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(no_camera_raw_version)), ]; let file = AtnFile { name: UnicodeString::new_nul("Looks"), @@ -3338,7 +3356,7 @@ fn camera_raw_filter_steps_import_as_filter_camera_raw() { for (k, (id, _)) in steps.iter().enumerate().skip(1) { assert_eq!(id, PHOTOSHOP_STEP, "step {k}"); } - assert_eq!(imp.unsupported.iter().map(|u| u.step).collect::>(), (1..=14).collect::>()); + assert_eq!(imp.unsupported.iter().map(|u| u.step).collect::>(), (1..=18).collect::>()); // The imported step plays. let mut s = Session::new(); s.execute("file.new", json!({"width": 16, "height": 12})).unwrap(); @@ -3354,6 +3372,7 @@ fn camera_raw_filter_steps_import_as_filter_camera_raw() { fn loaded_camera_raw_filter_steps_save_back_unchanged() { let recorded = desc("null") .with("CrVe", D::Text(UnicodeString::new_nul("16.1.1"))) + .with("PrVN", D::Integer(5)) .with("PrVe", D::Integer(184_549_376)) .with("WBal", enm("WBal", "Cst ")) .with("Ex12", D::Double(0.35)) @@ -3398,13 +3417,14 @@ fn loaded_camera_raw_filter_steps_save_back_unchanged() { /// and is reported, rather than replaying without that processing. #[test] fn camera_raw_filter_steps_with_unknown_keys_stay_photoshop_steps() { - let upright = desc("null").with("Ex12", D::Double(0.2)).with("PerV", D::Integer(20)); - let profile = desc("null").with("Cr12", D::Integer(10)).with("LookName", D::Text(UnicodeString::new_nul("B&W 05"))); + let cr = || desc("null").with("CrVe", D::Text(UnicodeString::new_nul("16.1.1"))).with("PrVN", D::Integer(5)).with("PrVe", D::Integer(184_549_376)); + let upright = cr().with("Ex12", D::Double(0.2)).with("PerV", D::Integer(20)); + let profile = cr().with("Cr12", D::Integer(10)).with("LookName", D::Text(UnicodeString::new_nul("B&W 05"))); let file = one_action(vec![ item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(upright.clone())), item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(profile)), item("Adobe Camera Raw Filter", "Camera Raw Filter", None), - item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(desc("null").with("Ex12", D::Double(0.2)))), + item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(cr().with("Ex12", D::Double(0.2)))), ]); let mut s = Session::new(); let loaded = s.execute("actions.load", json!({"data": b64(&atn::write(&file).unwrap())})).unwrap(); @@ -3623,6 +3643,35 @@ fn pattern_fill_ids_beat_names_across_document_and_library() { } } +/// CodeRabbit on batch 11: a pattern step that names its pattern only by `patternName` exports +/// that name, rather than a step with no pattern (which plays the current one). +#[test] +fn pattern_steps_named_only_by_pattern_name_export_the_name() { + let one = Action { name: "P".into(), steps: vec![("layer.newFillLayer.pattern".into(), json!({"patternName": "Checkerboard"}))], ..Default::default() }; + let (bytes, skipped) = export("Pat", &[&one], &[], false).unwrap(); + assert!(skipped.is_empty()); + let steps = import(&bytes).unwrap().actions[0].steps.clone(); + assert_eq!(steps[0].0, "layer.newFillLayer.pattern"); + assert_eq!(steps[0].1["pattern"], json!("Checkerboard"), "{}", steps[0].1); +} + +/// CodeRabbit on batch 11: when the recorded id is installed nowhere, the recorded name is looked +/// up as a name only. A pattern whose id equals that name text doesn't beat the one named so. +#[test] +fn pattern_fill_name_fallback_matches_names_not_ids() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 4, "height": 4, "mode": "rgb", "depth": 8})).unwrap(); + let red = define_pattern(&mut s, "#ff0000", "Red"); + // Green is named like the red pattern's id. + define_pattern(&mut s, "#00ff00", &red); + let data = set_of("Pat", vec![("NameIsAnId", vec![pattern_fill_step("5e1c0000-aaaa-4bbb-8ccc-000000000000", &red)])]); + s.execute("actions.load", json!({"data": data})).unwrap(); + s.execute("file.new", json!({"width": 4, "height": 4, "mode": "rgb", "depth": 8})).unwrap(); + let r = s.execute("actions.play", json!({"action": "NameIsAnId"})).unwrap(); + assert!(r.get("failed").is_none(), "{r}"); + assert_eq!(pixel(&mut s), [0.0, 1.0, 0.0, 1.0]); +} + /// A recorded pattern installed neither by id nor by name fails with an error that names the /// pattern, from the imported step and from the Pattern Fill dialog's command alike. #[test] diff --git a/crates/engine/src/cmd/pattern_cmds.rs b/crates/engine/src/cmd/pattern_cmds.rs index c5484f4b4ab..d1a93b42d4f 100644 --- a/crates/engine/src/cmd/pattern_cmds.rs +++ b/crates/engine/src/cmd/pattern_cmds.rs @@ -197,7 +197,11 @@ pub(crate) fn resolve_or_named(s: &Session, key: &str, p: &Value) -> std::result let in_doc = |id: &str, name: &str| s.active().and_then(|d| find(&d.doc.patterns, id, name)).map(|p| (p, false)); let by_key = |k: &str| in_doc(k, k).or_else(|| library_pattern(s, k).map(|p| (p, true))); let found = match name { - Some(n) => in_doc(key, "").or_else(|| find(&s.patterns.items, key, "").map(|p| (p, true))).or_else(|| by_key(n)), + // The name is a name: another pattern whose id happens to equal it doesn't count. + Some(n) => in_doc(key, "") + .or_else(|| find(&s.patterns.items, key, "").map(|p| (p, true))) + .or_else(|| in_doc("", n)) + .or_else(|| find(&s.patterns.items, "", n).map(|p| (p, true))), None => by_key(key), }; match found { diff --git a/crates/psd/src/codepage.rs b/crates/psd/src/codepage.rs index e44cf0d7ce5..75e0f7c468a 100644 --- a/crates/psd/src/codepage.rs +++ b/crates/psd/src/codepage.rs @@ -23,7 +23,8 @@ //! Only the first [`GUESS_SAMPLE`] bytes of names are examined. use encoding_rs::{ - BIG5, DecoderResult, EUC_KR, Encoding, GBK, MACINTOSH, REPLACEMENT, SHIFT_JIS, UTF_8, UTF_16BE, UTF_16LE, WINDOWS_1251, WINDOWS_1252, X_USER_DEFINED, + BIG5, DecoderResult, EUC_KR, Encoding, GBK, ISO_2022_JP, MACINTOSH, REPLACEMENT, SHIFT_JIS, UTF_8, UTF_16BE, UTF_16LE, WINDOWS_1251, WINDOWS_1252, + X_USER_DEFINED, }; use crate::error::{PsdError, Result}; @@ -142,10 +143,11 @@ pub(crate) fn reads_as_common(name: &[u8], enc: &'static Encoding) -> bool { /// Resolves an encoding label (`shift_jis`, `gbk`, `big5`, `euc-kr`, `windows-1252`, `utf-8`…; /// case and surrounding whitespace are ignored). Labels for encodings that cannot hold an 8-bit -/// name are rejected. +/// name are rejected, and so is ISO-2022-JP: its names are 7-bit escape sequences, which would +/// pass through as ASCII. pub(crate) fn resolve_label(label: &str) -> Result<&'static Encoding> { match Encoding::for_label(label.as_bytes()) { - Some(enc) if ![REPLACEMENT, UTF_16LE, UTF_16BE, X_USER_DEFINED].contains(&enc) => Ok(enc), + Some(enc) if ![REPLACEMENT, UTF_16LE, UTF_16BE, X_USER_DEFINED, ISO_2022_JP].contains(&enc) => Ok(enc), _ => Err(PsdError::Unsupported(format!("text encoding `{label}`: use a label such as shift_jis, gbk, big5, euc-kr, windows-1252 or utf-8"))), } } @@ -540,7 +542,7 @@ mod tests { for ok in ["shift_jis", "gbk", "big5", "euc-kr", "windows-1252", "utf-8"] { assert!(resolve_label(ok).is_ok(), "{ok}"); } - for bad in ["nope", "replacement", "utf-16le", "x-user-defined", "", "iso-2022-kr"] { + for bad in ["nope", "replacement", "utf-16le", "x-user-defined", "", "iso-2022-kr", "iso-2022-jp", "csISO2022JP"] { let Err(e) = resolve_label(bad) else { panic!("{bad} should be rejected") }; assert!(e.to_string().contains("shift_jis"), "{e}"); } diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index 5f2ab0a45c6..6fa9e7877e6 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -101,9 +101,9 @@ fn playback_targets(app: &PhotocraftApp) -> Vec { /// pauses for a step dialog of its own hands the rest to that dialog, which plays them after its OK /// (Cancel stops them all, as it stops one action). A pause inside an action it calls resumes only /// the called action, so the set stops there rather than run its next action on an unfinished one. Returns the last result with `ran` counting the steps -/// of all of them, or `None` when there was nothing to play. -fn play_targets(app: &mut PhotocraftApp, targets: &[usize]) -> Result, String> { - let (mut last, mut ran) = (None, 0u64); +/// of all of them plus `before` (steps the same Play ran before a pause), or `None` when there was nothing to play. +fn play_targets(app: &mut PhotocraftApp, targets: &[usize], before: u64) -> Result, String> { + let (mut last, mut ran) = (None, before); for (n, &i) in targets.iter().enumerate() { let name = app.session.actions.list.get(i).map(|a| a.name.clone()); let mut v = app.run("actions.play", json!({"action": i}))?; @@ -115,12 +115,15 @@ fn play_targets(app: &mut PhotocraftApp, targets: &[usize]) -> Result = targets.get(n + 1..).unwrap_or_default().iter().filter_map(|i| list.get(*i).map(|a| a.name.clone())).collect(); let token = app.ui.dialog_mut(dialog).and_then(|d| d.fields.get(RESUME)).and_then(Value::as_u64); if let Some(entry) = token.and_then(|t| app.paused_playbacks.paused.get_mut(&t)) && name.as_ref() == Some(&entry.action) { entry.then = rest; + entry.ran = ran; } break; } @@ -521,7 +524,14 @@ fn save_dialog(app: &mut PhotocraftApp, set: Option) -> Result' | '|') { '_' } else { c }) .collect(); - let file = format!("{}.atn", photocraft_engine::file_cmds::portable_device_name(stem)); + // A file name holds at most 255 bytes: the stem gets what `.atn` leaves, cut at a character. + let mut stem = photocraft_engine::file_cmds::portable_device_name(stem); + let mut cut = 255 - ".atn".len(); + while !stem.is_char_boundary(cut.min(stem.len())) { + cut -= 1; + } + stem.truncate(cut); + let file = format!("{stem}.atn"); app.pick_save(&file, move |app, path| { let write = app.services.write.as_mut().ok_or("no writer configured")?; write(&path, &bytes)?; @@ -690,8 +700,11 @@ pub(crate) struct PausedPlayback { /// box, automation), which end the call through `resume`, `abandoned` or `stopped`, so the /// recording comes back exactly once. record: Option, - /// The actions still to play after this one, when Play started a whole set. - then: Vec, + /// The actions still to play after this one, by name, when Play started a whole set. + then: Vec, + /// The steps that Play ran before this pause (earlier actions of the set, and this one's + /// steps before the dialog), so the final count covers the whole Play. + ran: u64, } /// The paused playbacks, by the token their dialog carries. The dialog's fields hold only the @@ -705,7 +718,7 @@ pub(crate) struct PausedPlaybacks { impl PausedPlaybacks { fn pause(&mut self, action: String, from: usize, gate: Option) -> u64 { self.last = self.last.wrapping_add(1); - self.paused.insert(self.last, PausedPlayback { action, from, gate, record: None, then: Vec::new() }); + self.paused.insert(self.last, PausedPlayback { action, from, gate, record: None, then: Vec::new(), ran: 0 }); self.last } @@ -748,22 +761,29 @@ pub fn resume(app: &mut PhotocraftApp, fields: &serde_json::Map) && entry.action == paused.action { entry.then = paused.then.clone(); + entry.ran = paused.ran.saturating_add(1).saturating_add(v.get("ran").and_then(Value::as_u64).unwrap_or(0)); } - // The rest of a set Play started: under the same gate, and only if this action finished. + // The count covers the steps this Play ran before the pause, and the step the dialog ran. + let ran = paused.ran.saturating_add(1).saturating_add(played.as_ref().ok().and_then(|v| v.get("ran")).and_then(Value::as_u64).unwrap_or(0)); + if let Ok(Some(o)) = played.as_mut().map(Value::as_object_mut) + && o.contains_key("ran") + { + o.insert("ran".into(), json!(ran)); + } + // The rest of a set Play started: under the same gate, and only if this action finished. An + // action of it deleted or renamed meanwhile ends the set there. if let Ok(v) = &played && !paused.then.is_empty() && v.get("failed").is_none() && v.get("paused").is_none() { - let ran = v.get("ran").and_then(Value::as_u64).unwrap_or(0); - played = play_targets(app, &paused.then).map(|rest| { - let mut rest = rest.unwrap_or(Value::Null); - let total = ran.saturating_add(rest.get("ran").and_then(Value::as_u64).unwrap_or(0)); - if let Some(o) = rest.as_object_mut() { - o.insert("ran".into(), json!(total)); - } - rest - }); + let list = &app.session.actions.list; + let rest: Vec = paused.then.iter().map_while(|name| list.iter().position(|a| &a.name == name)).collect(); + match play_targets(app, &rest, ran) { + Ok(Some(r)) => played = Ok(r), + Ok(None) => {} + Err(e) => played = Err(e), + } } app.session.authorize = saved; match played { @@ -842,7 +862,7 @@ pub fn panel_menu(app: &mut PhotocraftApp, ui: &mut egui::Ui) { "stopRec" => app.run("actions.stop", json!({})), "play" => { let targets = playback_targets(app); - play_targets(app, &targets).map(|v| { + play_targets(app, &targets, 0).map(|v| { if let Some(v) = &v { report_play(app, v); } @@ -1363,7 +1383,7 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { } }); if let Some(targets) = play_idx { - match play_targets(app, &targets) { + match play_targets(app, &targets, 0) { Ok(Some(v)) => report_play(app, &v), Ok(None) => {} Err(e) => { diff --git a/crates/ui-egui/src/panels/actions/tests.rs b/crates/ui-egui/src/panels/actions/tests.rs index 7a233fcdf57..cf1758bcf8e 100644 --- a/crates/ui-egui/src/panels/actions/tests.rs +++ b/crates/ui-egui/src/panels/actions/tests.rs @@ -721,6 +721,19 @@ fn play_with_an_empty_set_selected_plays_nothing() { assert!(layer_names(h.state()).is_empty(), "{:?}", layer_names(h.state())); } +/// CodeRabbit on batch 11: with an empty set selected, Batch and Create Droplet start on the first +/// action, as `selected_action` documents. +#[test] +fn an_empty_selected_set_falls_back_to_the_first_action() { + use egui_kittest::kittest::Queryable; + let mut h = two_set_panel(); + h.state_mut().run("actions.newSet", json!({"name": "Print"})).unwrap(); + h.run_steps(2); + h.get_by_label("Print").click(); + h.run_steps(2); + assert_eq!(selected_action(h.state()).map(|a| a.name.as_str()), Some("Resize")); +} + /// #10459 fix-up: the common case is unchanged: a selected action plays alone, also after a set /// folder was selected before it, and a later Delete doesn't bring that set back. #[test] @@ -832,10 +845,41 @@ fn a_set_paused_at_a_step_dialog_plays_its_other_actions_after_ok() { let mut names = layer_names(h.state()); names.sort(); assert_eq!(names, ["a", "a2", "b"], "B played after A's dialogs"); - assert!(h.state().ui.status.starts_with("Played"), "{}", h.state().ui.status); + // CodeRabbit on batch 11: the count covers the whole Play, also the steps before each pause. + assert_eq!(h.state().ui.status, "Played 5 steps"); } } +/// CodeRabbit on batch 11: the rest of a paused set is kept by name, so an action moved into the +/// middle of the list while the dialog is open neither plays in its place nor skips one of the set. +#[test] +fn a_set_paused_at_a_dialog_plays_its_own_actions_after_a_move() { + use egui_kittest::kittest::Queryable; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + for (name, set, layer) in [("A", "S", "a"), ("B", "S", "b"), ("C", "S", "c"), ("X", "Other", "x")] { + let mut a = Action::new(name, vec![("layer.new.layer".into(), json!({"name": layer}))]); + a.set = Some(set.into()); + app.session.actions.list.push(a); + } + app.session.actions.list[0].steps.push(("filter.blur.gaussianBlur".into(), json!({"radius": 1}))); + app.session.actions.list[0].dialogs.insert(1); + let mut h = egui_kittest::Harness::builder().with_size(vec2(360.0, 400.0)).build_ui_state(|ui, app| panel(app, ui), app); + h.run_steps(2); + h.get_by_label("S").click(); + h.run_steps(2); + h.get_by_label("Play selection").click(); + h.run_steps(2); + assert_eq!(layer_names(h.state()), ["a"]); + let dialog = h.state().ui.dialogs.last().map(|d| d.id).expect("the blur's dialog"); + h.state_mut().run("actions.move", json!({"action": "X", "to": 1})).unwrap(); + crate::dialogs::confirm(h.state_mut(), dialog).unwrap(); + h.run_steps(2); + let mut names = layer_names(h.state()); + names.sort(); + assert_eq!(names, ["a", "b", "c"]); +} + /// #10459 fix-up: a set whose action pauses at a dialog inside an action it calls stops there: /// the called action resumes alone, so the next action of the set must not run on a caller that /// never finished. @@ -1200,6 +1244,23 @@ fn save_actions_suggests_a_windows_safe_name_for_device_and_control_character_se } } +/// CodeRabbit on batch 11: a set name longer than a file name may be is cut to 255 bytes with its +/// suffix, at a character boundary. +#[test] +fn save_actions_suggests_a_file_name_of_at_most_255_bytes() { + use egui_kittest::kittest::Queryable; + let set = "é".repeat(200); + let (mut h, asked) = empty_set_save_harness(&set); + h.get_by_label(set.as_str()).click(); + h.run_steps(2); + h.get_by_label("Save Actions…").click(); + h.run_steps(2); + h.state_mut().poll_file_dialog(&egui::Context::default(), None); + let asked = asked.borrow(); + let [crate::file_dialog::FileDialogRequest::Save { suggested }] = asked.as_slice() else { panic!("{asked:?}") }; + assert_eq!(*suggested, format!("{}.atn", "é".repeat(125))); +} + #[test] fn moving_an_action_next_to_another_set_joins_it() { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());