Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Commands check an explicit "layer" instead of whichever layer is active (#3466)

Fabian Ghenof17855ab3d1f2
diff --git a/crates/engine/src/jobs.rs b/crates/engine/src/jobs.rs
index 15e7387b0..f678a6c7d 100644
--- a/crates/engine/src/jobs.rs
+++ b/crates/engine/src/jobs.rs
@@ -634,7 +634,7 @@ impl Session {
}
// Pixel commands follow the Channels panel target unless the caller names one.
let run_params = crate::channel_cmds::inject_target(self, id, crate::commands::inject_kind(id, params.clone()));
- if let Err(why) = crate::smart_cmds::target_enabled(self, spec, &params).unwrap_or_else(|| self.precondition(spec, &run_params)) {
+ if let Err(why) = self.explicit_layer_enabled(spec, &params).unwrap_or_else(|| self.precondition(spec, &run_params)) {
return Err(EngineError::Disabled(id.to_string(), why));
}
if let Some(why) = self.job_conflict(id, spec.journal) {
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 17539ab30..035cfabef 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -578,6 +578,26 @@ impl Session {
&& params.get("layer").and_then(Value::as_u64).is_some_and(|l| self.active().is_some_and(|st| st.doc.layer(LayerId(l)).is_some()))
}
+ /// The precondition of a command whose params document `"layer":id` (it acts on that layer),
+ /// when `params` name an existing layer of the active document: checked on that layer rather
+ /// than on the active one, which stays active (#466). A script, action or agent can then
+ /// Replace Contents, Rasterize or Merge Down a layer without selecting it first. `None` for
+ /// other commands, or without such a layer.
+ pub(crate) fn explicit_layer_enabled(&mut self, spec: &commands::CommandSpec, params: &Value) -> Option<std::result::Result<(), String>> {
+ if !spec.params.contains("\"layer\":id") {
+ return None;
+ }
+ let target = LayerId(params.get("layer")?.as_u64()?);
+ let d = self.active_mut()?;
+ d.doc.layer(target)?;
+ let active = d.active_layer.replace(target);
+ let r = (spec.enabled)(self);
+ if let Some(d) = self.active_mut() {
+ d.active_layer = active;
+ }
+ Some(r)
+ }
+
/// Apply an undoable edit to the active document.
pub fn edit<R>(&mut self, label: &str, f: impl FnOnce(&mut Document, &mut Option<LayerId>) -> Result<R>) -> Result<R> {
let restrict = self.color_restrict;
diff --git a/crates/engine/src/smart_cmds.rs b/crates/engine/src/smart_cmds.rs
index aa617ccc4..5678a8b7d 100644
--- a/crates/engine/src/smart_cmds.rs
+++ b/crates/engine/src/smart_cmds.rs
@@ -1057,24 +1057,6 @@ fn move_filter(s: &mut Session, p: &Value) -> Result<Value> {
// ---------- enablement ----------
-/// Whether smart-filter or contents command `spec` can run with `p`: its precondition is checked on an
-/// explicit `"layer"` of the active document (the layer it then edits) rather than on the
-/// active layer, which stays active (#466). `None` for other commands or without that target.
-pub(crate) fn target_enabled(s: &mut Session, spec: &CommandSpec, p: &Value) -> Option<std::result::Result<(), String>> {
- if !spec.id.starts_with("layer.smartFilter.") && !matches!(spec.id, "layer.smartObjects.editContents" | "layer.smartObjects.convertToLayers") {
- return None;
- }
- let target = LayerId(p.get("layer")?.as_u64()?);
- let d = s.active_mut()?;
- d.doc.layer(target)?;
- let active = d.active_layer.replace(target);
- let r = (spec.enabled)(s);
- if let Some(d) = s.active_mut() {
- d.active_layer = active;
- }
- Some(r)
-}
-
fn active_smart(s: &Session) -> std::result::Result<&SmartObject, String> {
let d = s.active().ok_or("no document open")?;
let id = d.active_layer.ok_or("no active layer")?;
diff --git a/crates/engine/tests/explicit_layer_target.rs b/crates/engine/tests/explicit_layer_target.rs
new file mode 100644
index 000000000..6479b9c6d
--- /dev/null
+++ b/crates/engine/tests/explicit_layer_target.rs
@@ -0,0 +1,74 @@
+//! A command that documents `"layer":id` checks its precondition on that layer, not on whichever
+//! layer happens to be active (#466 for smart filters, generalised): a script, action or agent can
+//! Replace Contents or Rasterize a smart object while another layer is selected.
+
+use photocraft_doc::{LayerContent, LayerId};
+use photocraft_engine::{EngineError, Session};
+use photocraft_geom::Rect;
+use serde_json::json;
+
+/// A smart object (blue) under a plain pixel layer, which is active.
+fn session() -> (Session, u64, u64) {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 8, "height": 6})).unwrap();
+ s.execute("layer.new.layer", json!({})).unwrap();
+ s.edit("paint", |doc, active| {
+ doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(0, 0, 8, 6), &[0.0, 0.0, 1.0, 1.0]);
+ Ok(())
+ })
+ .unwrap();
+ let so = s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap()["layer"].as_u64().unwrap();
+ let pixels = s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap();
+ (s, so, pixels)
+}
+
+fn active(s: &Session) -> u64 {
+ s.active().unwrap().active_layer.unwrap().0
+}
+
+fn kind(s: &Session, id: u64) -> &'static str {
+ s.active().unwrap().doc.layer(LayerId(id)).unwrap().content.kind_name()
+}
+
+#[test]
+fn smart_object_commands_act_on_a_named_layer_while_another_is_active() {
+ let (mut s, so, pixels) = session();
+ assert_eq!(active(&s), pixels);
+ // Without "layer" the active pixel layer decides, as the menus show.
+ assert!(!s.is_enabled("layer.smartObjects.replaceContents"));
+ // Replace Contents on the named smart object.
+ let dir = std::env::temp_dir().join(format!("pcraft-explicit-layer-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let png = dir.join("red.png");
+ let red = photocraft_doc::Document::with_background(
+ "r",
+ photocraft_geom::Size::new(8, 6),
+ photocraft_color::ColorMode::Rgb,
+ photocraft_color::SampleType::U8,
+ photocraft_color::Color::rgba(1.0, 0.0, 0.0, 1.0),
+ );
+ std::fs::write(&png, photocraft_io::export(&red, "png", &Default::default()).unwrap().bytes).unwrap();
+ s.execute("layer.smartObjects.replaceContents", json!({"layer": so, "path": png.to_str().unwrap()})).unwrap();
+ std::fs::remove_dir_all(&dir).ok();
+ let LayerContent::Smart(sm) = &s.active().unwrap().doc.layer(LayerId(so)).unwrap().content else { panic!("smart object") };
+ assert_eq!(sm.cache.as_ref().unwrap().rgba(2, 2), [1.0, 0.0, 0.0, 1.0], "the named smart object was replaced");
+ assert_eq!(active(&s), pixels, "the active layer stays");
+ // Rasterize it, still without selecting it.
+ s.execute("layer.rasterize.smartObject", json!({"layer": so})).unwrap();
+ assert_eq!(kind(&s, so), "Pixel");
+ assert_eq!(active(&s), pixels);
+}
+
+#[test]
+fn a_named_layer_of_the_wrong_kind_or_that_does_not_exist_is_refused() {
+ let (mut s, _so, pixels) = session();
+ let before = s.active().unwrap().doc.clone();
+ // The named layer is checked: a pixel layer is not a smart object.
+ let r = s.execute("layer.smartObjects.rasterize", json!({"layer": pixels}));
+ assert!(matches!(r, Err(EngineError::Disabled(..))), "{r:?}");
+ // A layer that doesn't exist falls back to the active layer's check, and still fails.
+ assert!(s.execute("layer.smartObjects.rasterize", json!({"layer": 999_999})).is_err());
+ assert!(s.execute("layer.smartObjects.rasterize", json!({"layer": "nope"})).is_err());
+ assert_eq!(s.active().unwrap().doc, before);
+ assert_eq!(active(&s), pixels);
+}