PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Play .atn steps that switch to another open document
jonathanwxh-cell2cca4faba0ae
diff --git a/crates/engine/src/atn_cmds.rs b/crates/engine/src/atn_cmds.rsindex d5c688f0a..195cef1fa 100644--- a/crates/engine/src/atn_cmds.rs+++ b/crates/engine/src/atn_cmds.rs@@ -13,7 +13,9 @@//! work; tool selections and other steps with no document effect are imported switched off.//!//! Layer references by name (`select` of layer "Shadow") become `{"layer": "Shadow"}`, which-//! `commands::layer_param` resolves in whatever document the action plays on (#219).+//! `commands::layer_param` resolves in whatever document the action plays on (#219). A switch+//! to another open document (`select` of `Dcmn` by offset) becomes `document.activate+//! {"offset"}`, the tab that many places from the active one (#7103).use photocraft_psd::atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem};use photocraft_psd::descriptor::{Class, Descriptor, Id, ReferenceItem, UnicodeString, Value as D};@@ -1442,6 +1444,9 @@ fn select_from(d: &Descriptor) -> Mapped {}}(Some(c), Target::Class) if is_tool_class(c) => Mapped::Unsupported { harmless: true },+ // Switching to another open document: its offset from the active one, -1 for the previous+ // tab and 1 for the next (a template action copies from one and pastes into the other, #7103).+ (Some("Dcmn"), Target::Offset(o)) => step("document.activate", json!({"offset": o})),_ => Mapped::Unsupported { harmless: false },}}@@ -1476,6 +1481,11 @@ fn select_to(id: &str, p: &Value) -> Option<Descriptor> {"layer.addBelowToSelection" => desc("null").with("null", ord("Bckw")).with("selectionModifier", enm("selectionModifierType", "addToSelection")),"layer.selectTop" => desc("null").with("null", ord("Frnt")),"layer.selectBottom" => desc("null").with("null", ord("Back")),+ // An absolute tab index has no Photoshop equivalent; an offset is what Photoshop records.+ "document.activate" if p.get("document").is_none_or(Value::is_null) => {+ let offset = i32::try_from(p.get("offset")?.as_i64()?).ok()?;+ desc("null").with("null", D::Reference(vec![ReferenceItem::Offset { class: class("Dcmn"), offset }]))+ }_ => return None,})}@@ -2854,6 +2864,7 @@ const EVENTS: &[Event] = &["channel.target","edit.undo","edit.redo",+ "document.activate",],from: select_from,to: select_to,diff --git a/crates/engine/src/atn_cmds/tests.rs b/crates/engine/src/atn_cmds/tests.rsindex c4fe00eb9..c50936133 100644--- a/crates/engine/src/atn_cmds/tests.rs+++ b/crates/engine/src/atn_cmds/tests.rs@@ -301,6 +301,7 @@ fn every_mapped_command_exports_and_imports_back() {("actions.conditional", json!({"if": "landscape", "then": "Wide", "else": null, "set": "S"})),("actions.play", json!({"action": "Other", "set": "S"})),(STOP_MESSAGE, json!({"message": "Hi", "allowContinue": false})),+ ("document.activate", json!({"offset": -1})),// The TrueGrit Texture Supply sets (Debaser, Distress Press, Halftone Zine Machine).("filter.distort.ripple", json!({"amount": 50, "size": "medium"})),("filter.pixelate.crystallize", json!({"cellSize": 5})),@@ -865,6 +866,74 @@ fn fsel(t: D) -> Descriptor {desc("null").with("null", D::Reference(vec![ReferenceItem::Property { class: class("Chnl"), key: Id::new("fsel") }])).with("T ", t)}+/// #7103: Photoshop records switching to another open document as a `select` of `Dcmn` by+/// offset (previous -1, next +1). The template action of the report, which copies from the+/// source image and pastes into the template opened after it, imports with no Photoshop steps,+/// plays across the two documents and saves back the same shape. With no previous document+/// open, playback stops at the switch instead of pasting into the wrong document.+#[test]+fn select_document_by_offset_imports_plays_and_saves_back() {+ let doc = |offset: i32| desc("null").with("null", D::Reference(vec![ReferenceItem::Offset { class: class("Dcmn"), offset }]));+ // A recorded document id (`DocI`) means nothing in another session: ignored, not written back.+ let copy_in = vec![+ item("slct", "Select", Some(doc(-1).with("DocI", long(35.0)))),+ item("setd", "Set", Some(fsel(enm("Ordn", "Al ")))),+ item("copy", "Copy", None),+ item("slct", "Select", Some(doc(1))),+ item("past", "Paste", None),+ ];+ let data = set_of("Template", vec![("Copy In", copy_in)]);++ let mut s = Session::new();+ s.execute("file.new", json!({"width": 8, "height": 8, "name": "source"})).unwrap();+ s.execute("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap();+ s.execute("file.new", json!({"width": 8, "height": 8, "name": "template", "background": "transparent"})).unwrap();+ let r = s.execute("actions.load", json!({"data": data})).unwrap();+ assert_eq!(r["unsupported"], json!([]), "{r}");+ let steps = &s.actions.list[0].steps;+ assert_eq!(steps[0], ("document.activate".to_string(), json!({"offset": -1})));+ assert_eq!(steps[3], ("document.activate".to_string(), json!({"offset": 1})));++ let pixel = |s: &mut Session| -> Vec<f32> { serde_json::from_value(s.execute("document.pixel", json!({"x": 4, "y": 4})).unwrap()).unwrap() };+ assert_eq!(pixel(&mut s), [0.0; 4]);+ let r = s.execute("actions.play", json!({"action": "Copy In"})).unwrap();+ assert!(r.get("failed").is_none(), "{r}");+ assert_eq!(s.active().unwrap().doc.name, "template");+ assert_eq!(s.active().unwrap().doc.layers.len(), 2, "the source's pixels are pasted on a new layer");+ assert_eq!(pixel(&mut s), [1.0, 0.0, 0.0, 1.0]);+ assert_eq!(s.documents()[0].doc.layers.len(), 1, "the source is only copied from");++ let first = s.actions.list.clone();+ let r = s.execute("actions.save", json!({"set": "Template"})).unwrap();+ assert_eq!(r["skipped"], json!([]));+ let saved = photocraft_paint::tile::b64_decode(r["data"].as_str().unwrap()).unwrap();+ let file = atn::parse(&saved).unwrap();+ let offsets: Vec<i32> = file.actions[0]+ .items+ .iter()+ .filter_map(|i| match get_ref(i.descriptor.as_ref()?, "null")? {+ [ReferenceItem::Offset { class, offset }] if trimmed(&class.class_id) == "Dcmn" => Some(*offset),+ _ => None,+ })+ .collect();+ assert_eq!(offsets, [-1, 1]);+ assert!(file.actions[0].items[0].descriptor.as_ref().unwrap().get("DocI").is_none());+ let mut t = Session::new();+ t.execute("actions.load", json!({"data": b64(&saved)})).unwrap();+ assert_eq!(t.actions.list, first);+ // An absolute tab index has no Photoshop equivalent: it stays out of a strict save.+ assert!(export_item("document.activate", &json!({"document": 0}), "S").is_none());+ assert!(export_item("document.activate", &json!({"document": 0, "offset": 1}), "S").is_none());++ let mut one = Session::new();+ one.execute("file.new", json!({"width": 8, "height": 8, "name": "template"})).unwrap();+ one.execute("actions.load", json!({"data": data})).unwrap();+ let r = one.execute("actions.play", json!({"action": "Copy In"})).unwrap();+ assert_eq!(r["failed"]["step"], 0, "{r}");+ assert_eq!(r["failed"]["error"], "no document 1 before the active one, which is 1 of 1", "{r}");+ assert_eq!(one.active().unwrap().doc.layers.len(), 1);+}+fn set_of(name: &str, actions: Vec<(&str, Vec<AtnItem>)>) -> String {let file = AtnFile {name: UnicodeString::new_nul(name),diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rsindex cd7f5d606..9cb069ffb 100644--- a/crates/engine/src/commands.rs+++ b/crates/engine/src/commands.rs@@ -1248,12 +1248,33 @@ fn build() -> Vec<CommandSpec> {label: "Activate Document",menu: &[],shortcut: None,- params: r##"{"document":index}"##,+ params: r##"{"document":index} or {"offset":int} (the open document that many tabs after the active one, before it when negative: a Photoshop action's switch to another document) → {document}"##,enabled: has_doc,run: |s, p| {- let i = p.get("document").and_then(Value::as_u64).ok_or_else(|| bad("document.activate", "missing `document`"))?;- let idx = usize::try_from(i).map_err(|_| bad("document.activate", "`document` out of range"))?;- if s.set_active(idx) { Ok(Value::Null) } else { Err(EngineError::Other(format!("no document at index {idx}"))) }+ // A null key counts as omitted.+ let given = |k: &str| p.get(k).filter(|v| !v.is_null());+ let idx = match (given("document"), given("offset")) {+ (Some(_), Some(_)) => return Err(bad("document.activate", "give `document` or `offset`, not both")),+ (None, None) => return Err(bad("document.activate", "needs `document` (a tab index) or `offset`")),+ // Past the first or last tab is refused rather than wrapped, so an action that+ // copies from one document never silently pastes into the wrong one (#7103).+ (None, Some(o)) => {+ let o = o.as_i64().ok_or_else(|| bad("document.activate", "`offset` must be an integer"))?;+ let (active, len) = (s.active_index().ok_or(EngineError::NoDocument)?, s.documents().len());+ let target = i64::try_from(active).ok().and_then(|a| a.checked_add(o)).and_then(|i| usize::try_from(i).ok());+ let Some(i) = target.filter(|&i| i < len) else {+ let side = if o < 0 { "before" } else { "after" };+ let msg = format!("no document {} {side} the active one, which is {} of {len}", o.unsigned_abs(), active + 1);+ return Err(EngineError::Other(msg));+ };+ i+ }+ (Some(d), None) => {+ let i = d.as_u64().ok_or_else(|| bad("document.activate", "`document` must be a tab index"))?;+ usize::try_from(i).map_err(|_| bad("document.activate", "`document` out of range"))?+ }+ };+ if s.set_active(idx) { Ok(json!({"document": idx})) } else { Err(EngineError::Other(format!("no document at index {idx}"))) }},journal: false,},diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rsindex 0849cd941..2acd70fcc 100644--- a/crates/engine/src/tests.rs+++ b/crates/engine/src/tests.rs@@ -1470,6 +1470,53 @@ fn document_inspect_and_activate_invalid_index() {assert_eq!(err_act.to_string(), "no document at index 9");}+/// #7103: Photoshop's Select Document by offset (previous is -1, next +1) walks the open+/// documents in tab order from the active one. Past either end it is refused, not wrapped onto+/// another document, and bad params leave the active document as it was.+#[test]+fn document_activate_by_offset_walks_the_tabs() {+ let mut s = Session::new();+ for name in ["a", "b", "c"] {+ s.execute("file.new", json!({"width": 2, "height": 2, "name": name})).unwrap();+ }+ let active = |s: &Session| s.active().unwrap().doc.name.clone();+ assert_eq!(active(&s), "c");+ assert_eq!(s.execute("document.activate", json!({"offset": -2})).unwrap(), json!({"document": 0}));+ assert_eq!(active(&s), "a");+ assert_eq!(s.execute("document.activate", json!({"offset": 1})).unwrap(), json!({"document": 1}));+ assert_eq!(active(&s), "b");+ s.execute("document.activate", json!({"offset": 0})).unwrap();+ assert_eq!(active(&s), "b");+ assert_eq!(s.execute("document.activate", json!({"document": 2})).unwrap(), json!({"document": 2}));+ // A null key counts as omitted.+ s.execute("document.activate", json!({"document": null, "offset": -1})).unwrap();+ assert_eq!(active(&s), "b");++ let err = s.execute("document.activate", json!({"offset": 2})).unwrap_err().to_string();+ assert_eq!(err, "no document 2 after the active one, which is 2 of 3");+ let err = s.execute("document.activate", json!({"offset": -2})).unwrap_err().to_string();+ assert_eq!(err, "no document 2 before the active one, which is 2 of 3");+ for bad in [+ json!({}),+ json!({"offset": null}),+ json!({"offset": 1.5}),+ json!({"offset": "1"}),+ json!({"offset": i64::MAX}),+ json!({"offset": i64::MIN}),+ json!({"offset": u64::MAX}),+ json!({"document": 0, "offset": 1}),+ json!({"document": -1}),+ ] {+ assert!(s.execute("document.activate", bad.clone()).is_err(), "{bad}");+ assert_eq!(active(&s), "b", "{bad}");+ }+ // Tabs, not the order the documents were opened in: with "c" dragged to the front, two tabs+ // before "b" is "c".+ s.execute("document.move", json!({"document": 2, "to": 0})).unwrap();+ s.execute("document.activate", json!({"offset": -2})).unwrap();+ assert_eq!(active(&s), "c");+}+/// #2166, measured in Photoshop 25.1: a layer mask and the layer pixels keep separate/// foreground/background pairs, swapped when the edit target changes.#[test]diff --git a/docs/gaps.md b/docs/gaps.mdindex 4457a87dd..81828282f 100644--- a/docs/gaps.md+++ b/docs/gaps.md@@ -1,6 +1,6 @@# Where PhotoCraft falls short of Photoshop-> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-18 · **Change:** minor (G9: fill and adjustment layers copy and paste whole, #2344; G1: smart filter masks show on PSD open, Photoshop-oracle floor 188/258; G10: DPX read and write, #1049, Cineon read; G1: CMYK Hue/Saturation and Color Balance keep the black ink; G1: CMYK Posterize on the stored values, psd-tools oracle floor 242/309; G1: CMYK adjustment layers composite on the document's inks, Photoshop-oracle floor 165/258; G1: CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; G1: modern Brightness/Contrast's brightness curve matches Photoshop, Photoshop-oracle floor 151/258; G1: Lab documents composite on their stored L, a, b, Photoshop-oracle floor 152/258; G1: Levels on whole levels at every step, Photoshop-oracle floor 146/258, psd-tools 238/309; G1: 32-bit Brightness/Contrast legacy, Channel Mixer, Photo Filter and Black & White tint unclipped as in Photoshop, Photoshop-oracle floor 149/258; G1: mask feathers blur with their exact variance, psd-tools oracle floor 240/309; G1: Threshold splits on Photoshop's luminosity, psd-tools oracle floor 241/309; G1: pass-through clipping base with an adjustment renders isolated, psd-tools oracle floor 240/309; G1: 16-bit Posterize as Photoshop bins it, psd-tools oracle floor 241/309; G1: Gradient Map driven by the W3C luminosity, Photoshop-oracle floor 147/258; G7: Field Blur's on-canvas pins, #3373; G4: Hue Jitter amount track, #3825 partial; G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed; stale missing-tool rows corrected: Color Replacement, Red Eye and Add/Delete Anchor Point are live tools, so only Art History Brush is missing; no estimate changed) · **Target:** Adobe Photoshop 2026+> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-19 · **Change:** minor (G11: `.atn` steps that switch to another open document import, play and save back, #7103; G9: fill and adjustment layers copy and paste whole, #2344; G1: smart filter masks show on PSD open, Photoshop-oracle floor 188/258; G10: DPX read and write, #1049, Cineon read; G1: CMYK Hue/Saturation and Color Balance keep the black ink; G1: CMYK Posterize on the stored values, psd-tools oracle floor 242/309; G1: CMYK adjustment layers composite on the document's inks, Photoshop-oracle floor 165/258; G1: CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; G1: modern Brightness/Contrast's brightness curve matches Photoshop, Photoshop-oracle floor 151/258; G1: Lab documents composite on their stored L, a, b, Photoshop-oracle floor 152/258; G1: Levels on whole levels at every step, Photoshop-oracle floor 146/258, psd-tools 238/309; G1: 32-bit Brightness/Contrast legacy, Channel Mixer, Photo Filter and Black & White tint unclipped as in Photoshop, Photoshop-oracle floor 149/258; G1: mask feathers blur with their exact variance, psd-tools oracle floor 240/309; G1: Threshold splits on Photoshop's luminosity, psd-tools oracle floor 241/309; G1: pass-through clipping base with an adjustment renders isolated, psd-tools oracle floor 240/309; G1: 16-bit Posterize as Photoshop bins it, psd-tools oracle floor 241/309; G1: Gradient Map driven by the W3C luminosity, Photoshop-oracle floor 147/258; G7: Field Blur's on-canvas pins, #3373; G4: Hue Jitter amount track, #3825 partial; G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed; stale missing-tool rows corrected: Color Replacement, Red Eye and Add/Delete Anchor Point are live tools, so only Art History Brush is missing; no estimate changed) · **Target:** Adobe Photoshop 2026Every known shortfall against Photoshop 2026 (27.11.0), one entry each, ranked by user impacton the way to beta. This is the work list agents pick from: take the highest-ranked entry that@@ -98,6 +98,11 @@ what an agent can't finish alone.mapped events (paths, scripts, Generative Fill, Filter Gallery effects other than Spatter,Duplicate Layers into a new document, Bitmap halftone screens…) load as kept Photoshop stepsthat fail at playback by name.+- **Done 2026-10-19:** `.atn` steps that switch to another open document (a `select` of `Dcmn` by+ offset: the previous, next or Nth tab from the active one) import as `document.activate {"offset"}`,+ play and save back in the same shape, so actions that copy from one open document and paste into+ another no longer stop at the switch (#7103). An offset past the first or last open document is+ refused, not wrapped.- **Done 2026-10-12:** Load/Save Actions `.atn` in the panel menu, `batch --actions set.atn`and `actions.load`/`actions.save`; 112 Photoshop events map to commands both ways (Transform,Apply Image, Save for Web, smart-object edits, Gradient Map, Quick Mask, polygon selections,@@ -270,6 +275,7 @@ what an agent can't finish alone.| Date | Change | Summary ||---|---|---|+| 2026-10-19 | minor | G11: `.atn` steps that select another open document by offset import as `document.activate {"offset"}`, play and save back (#7103); estimate unchanged || 2026-10-18 | minor | G9: with no selection, Copy takes fill and adjustment layers whole and Paste recreates them (#2344); UI-217-23 stays partial (a single pixel layer copies its pixels only); estimate unchanged || 2026-10-14 | minor | G1: a PSD smart object's filter mask shows when the file opens (Photoshop stores the filtered pixels unmasked); export stores them that way too; Photoshop-oracle floor 185 → 188 of 258 || 2026-10-13 | minor | G14: D90 image area measured (4288 × 2848 at (10, 10)); gap remains open |