mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
Replay Batch Override Open with scoped input bindings
This commit is contained in:
1 parent
2d9697d4b8
commit
d656c0f6e1
12 files changed
+316
-37
No files matched your search
@@ -443,6 +443,7 @@ pub fn saves_smart_contents(s: &Session, id: &str) -> bool {
|
||||
id == "file.save" && s.is_enabled(SAVE_CONTENTS)
|
||||
}
|
||||
|
||||
/// Replay enabled steps with their effective parameters authorized before execution.
|
||||
fn run_recorded(s: &mut Session, action: &Action, from: usize) -> (u64, Option<Value>) {
|
||||
let mut ran = 0u64;
|
||||
let mut failed = None;
|
||||
@@ -451,6 +452,8 @@ fn run_recorded(s: &mut Session, action: &Action, from: usize) -> (u64, Option<V
|
||||
failed = Some(json!({"step": i, "id": id, "error": format!("action playback exceeded the {}-step limit", MAX_PLAYBACK_STEPS)}));
|
||||
break;
|
||||
}
|
||||
let effective = crate::file_cmds::batch_open_params(s, id, params);
|
||||
let params = effective.as_ref().unwrap_or(params);
|
||||
if let Some(auth) = s.authorize
|
||||
&& let Err(e) = auth(id, params)
|
||||
{
|
||||
|
||||
@@ -112,12 +112,17 @@ fn read(d: &Descriptor) -> Option<Value> {
|
||||
if !keys(d, &["null", "OvrO", "Fldr", "suppressWarnings", "suppressOpenOptions", "Usng", "T ", "SvAn", "Ovrd", "fileNamingRules"]) {
|
||||
return None;
|
||||
}
|
||||
// Enabled overrides and Alias payloads stay whole until their behavior is represented.
|
||||
for key in ["OvrO", "suppressWarnings", "suppressOpenOptions"] {
|
||||
// Dialog suppression and Alias payloads stay whole until their behavior is represented.
|
||||
for key in ["suppressWarnings", "suppressOpenOptions"] {
|
||||
if d.get(key).is_some_and(|v| v != &D::Boolean(false)) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let override_open = match d.get("OvrO") {
|
||||
None => None,
|
||||
Some(D::Boolean(value)) => Some(*value),
|
||||
_ => return None,
|
||||
};
|
||||
let save_and_close = match d.get("SvAn") {
|
||||
None | Some(D::Boolean(false)) => false,
|
||||
Some(D::Boolean(true)) => true,
|
||||
@@ -127,6 +132,9 @@ fn read(d: &Descriptor) -> Option<Value> {
|
||||
return None;
|
||||
}
|
||||
let mut p = json!({"input":path_text(d.get("null")?)?,"stopOnError":true,"includeNonImages":true});
|
||||
if let Some(value) = override_open {
|
||||
p["overrideOpen"] = json!(value);
|
||||
}
|
||||
if save_and_close {
|
||||
p["destination"] = json!("saveAndClose");
|
||||
} else {
|
||||
@@ -185,6 +193,7 @@ pub(super) fn batch_to(_: &str, p: &Value) -> Option<Descriptor> {
|
||||
"flatOutput",
|
||||
"includeSubfolders",
|
||||
"overrideSaveAs",
|
||||
"overrideOpen",
|
||||
"stopOnError",
|
||||
"includeNonImages",
|
||||
"namingComponents",
|
||||
@@ -240,6 +249,9 @@ pub(super) fn batch_to(_: &str, p: &Value) -> Option<Descriptor> {
|
||||
let d = desc("Btch").with("null", path_value(input)).with("Fldr", D::Boolean(subfolders)).with("Usng", D::Reference(reference));
|
||||
let d = if save_and_close { d.with("SvAn", D::Boolean(true)) } else { d.with("T ", path_value(jstr(p, "output").filter(|s| !s.is_empty())?)) };
|
||||
let mut d = d.with("Ovrd", D::Boolean(p.get("overrideSaveAs")?.as_bool()?));
|
||||
if let Some(value) = p.get("overrideOpen") {
|
||||
d = d.with("OvrO", D::Boolean(value.as_bool()?));
|
||||
}
|
||||
if p.get("namingComponents").is_some() {
|
||||
d = d.with("fileNamingRules", D::Descriptor(naming_to(p)?));
|
||||
} else if !save_and_close || ["startingSerial", "compatibility"].iter().any(|key| p.get(key).is_some()) {
|
||||
|
||||
@@ -27,14 +27,21 @@ pub(super) fn place_to(id: &str, p: &Value) -> Option<Descriptor> {
|
||||
|
||||
/// `open`: File › Open of a recorded path.
|
||||
pub(super) fn open_from(d: &Descriptor) -> Mapped {
|
||||
if d.items.len() != 1 || !d.class_id.is("null") || !d.name.to_string_lossy().is_empty() {
|
||||
return Mapped::Unsupported { harmless: false };
|
||||
}
|
||||
match d.get("null").and_then(path_text) {
|
||||
Some(path) => step("file.openAs", json!({"path": path})),
|
||||
None => Mapped::Unsupported { harmless: false },
|
||||
}
|
||||
}
|
||||
|
||||
/// Export the represented Open path; refuse settings without a supported wire mapping.
|
||||
pub(super) fn open_to(_: &str, p: &Value) -> Option<Descriptor> {
|
||||
Some(desc("null").with("null", path_value(jstr(p, "path")?)))
|
||||
if p.as_object()?.len() != 1 {
|
||||
return None;
|
||||
}
|
||||
Some(desc("null").with("null", path_value(jstr(p, "path").filter(|path| !path.is_empty())?)))
|
||||
}
|
||||
|
||||
fn path_extension(path: &str) -> Option<String> {
|
||||
|
||||
@@ -170,11 +170,36 @@ fn batch_all_documented_components_and_compatibility_flags_round_trip() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Batch's Open binding round-trips, but richer Open descriptors must remain whole.
|
||||
#[test]
|
||||
fn batch_override_open_and_unrepresented_open_settings_round_trip() {
|
||||
for enabled in [false, true] {
|
||||
let mut p = batch_case();
|
||||
p.as_object_mut().unwrap().remove("__atnBatch");
|
||||
p["overrideOpen"] = json!(enabled);
|
||||
let a = Action::new("Driver", vec![("file.automate.batch".into(), p)]);
|
||||
let (bytes, skipped) = export("S", &[&a], &[], false).unwrap();
|
||||
assert!(skipped.is_empty());
|
||||
let loaded = import(&bytes).unwrap();
|
||||
assert_eq!(loaded.actions[0].steps[0].1["overrideOpen"], enabled);
|
||||
let (again, skipped) = export("S", &[&loaded.actions[0]], &[], false).unwrap();
|
||||
assert!(skipped.is_empty());
|
||||
assert_eq!(atn::parse(&again).unwrap().actions[0].items[0].descriptor, atn::parse(&bytes).unwrap().actions[0].items[0].descriptor);
|
||||
}
|
||||
let rich = desc("null").with("null", path_value("/recorded.png")).with("unrepresentedOpenSetting", D::Boolean(true));
|
||||
let bytes = photocraft_paint::tile::b64_decode(&set_of("S", vec![("Driver", vec![item("Opn ", "Open", Some(rich.clone()))])])).unwrap();
|
||||
let loaded = import(&bytes).unwrap();
|
||||
assert_eq!(loaded.actions[0].steps[0].0, PHOTOSHOP_STEP);
|
||||
let (again, _) = export("S", &[&loaded.actions[0]], &[], false).unwrap();
|
||||
assert_eq!(atn::parse(&again).unwrap().actions[0].items[0].descriptor, Some(rich));
|
||||
assert!(super::steps_doc::open_to("file.openAs", &json!({"path":"/recorded.png","as":"png"})).is_none());
|
||||
}
|
||||
|
||||
/// Unsupported modes and misplaced fields must not lose data through a partial conversion.
|
||||
#[test]
|
||||
fn batch_unknown_components_wrong_start_placement_and_unsupported_modes_stay_whole() {
|
||||
let mut cases = vec![batch_descriptor("unknownComponent")];
|
||||
for (key, value) in [("Strt", D::Integer(3)), ("OvrO", D::Boolean(true)), ("SvAn", D::Boolean(true)), ("Log ", path_value("/log"))] {
|
||||
for (key, value) in [("Strt", D::Integer(3)), ("OvrO", D::Integer(1)), ("SvAn", D::Boolean(true)), ("Log ", path_value("/log"))] {
|
||||
cases.push(batch_descriptor("Nm ").with(key, value));
|
||||
}
|
||||
let mut odd = batch_descriptor("Nm ");
|
||||
|
||||
@@ -39,6 +39,7 @@ fn selected(p: &Value, prefix: &str) -> Vec<String> {
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Open the selected EXR parts and view, retaining their Batch source identity.
|
||||
fn open_exr_parts(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = crate::file_cmds::str_param(p, "path", "file.openExrParts")?.to_string();
|
||||
let view = p.get("view").and_then(Value::as_str).unwrap_or("both");
|
||||
@@ -55,6 +56,7 @@ fn open_exr_parts(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut r = photocraft_io::exr_parts::import(&stem(&path), &bytes, &sel).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
|
||||
crate::file_cmds::tag_exr_colorspace(s, &path, &mut r.document);
|
||||
let (i, color) = s.open_document(r.document, Some(path.clone()));
|
||||
crate::file_cmds::remember_batch_open(s);
|
||||
Ok(json!({"document": i, "color": color, "warnings": r.warnings}))
|
||||
}
|
||||
|
||||
|
||||
@@ -39,9 +39,9 @@ use info::file_info;
|
||||
pub use info::{CAMERA_FIELDS, camera_data, read_file_info, write_file_info};
|
||||
#[cfg(test)]
|
||||
use info::{exposure_text, find_element};
|
||||
pub(crate) use open::{BatchOpen, batch_open_params, import, remember_batch_open, tag_exr_colorspace};
|
||||
pub use open::{PLACE_EMBEDDED, open_bytes_as, place_bytes, raw_defaults};
|
||||
use open::{close_all, close_others, open_as, place, revert};
|
||||
pub(crate) use open::{import, tag_exr_colorspace};
|
||||
use paths::is_file;
|
||||
#[cfg(test)]
|
||||
use paths::openable_name;
|
||||
@@ -308,7 +308,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Batch…",
|
||||
&["File", "Automate"],
|
||||
None,
|
||||
r##"{"action":name|index? (instead of steps),"set":str?,"steps":[[commandId,params]|{"command":id,"params":{}}…] (a recorded action; a Save, Save As or Save a Copy step marks the document written to output, in this command's format and options: as the save found it if it was closed or another document is active at the end, else as the action leaves it; with no such step, the active document at the end),"input":folder|[paths],"includeNonImages":bool=false (folder inputs report unsupported files as per-file errors instead of skipping them; arrays are unchanged),"includeSubfolders":bool=false (a folder input also takes the images in its subfolders, up to 32 levels and 100000 files; each result keeps its subfolder under output),"destination":"folder|saveAndClose"="folder" (Save and Close writes the same source path/format; rejects already-open sources and changed result document identity),"output":folder? (required only for folder; omit for Save and Close),"format":"same|png|jpg|psd|tiff|…"="same" (Save and Close requires same),"quality":0..12?,"jpegFormat":"baseline|optimized|progressive"?,"namingComponents":[{"component":choice}|{"text":str}]? (up to six; the exact filename, with no automatic extension),"compatibility":{"macintosh":bool,"windows":bool,"unix":bool}?,"flatOutput":bool=false (structured naming only),"overrideSaveAs":bool? (recorded routing; requires a directly represented Save configuration),"stopOnError":bool=false (report the first failed input and stop; earlier outputs remain saved),"naming":string? (blank keeps source names; {name}, {serial} padded to 3 digits, {date} as YYYY-MM-DD UTC; extension added automatically),"startingSerial":1..4294967295=1 (input position, including failed inputs),"tiffLayers":bool? (Folder default false; Save and Close default true, with false refused when TIFF layer data would be lost),"tiffCompression":"none|lzw|zip"?,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain),"calledActions":[{"name","steps"}…]? (the actions Play Action steps call; default: the session's)} → {files, errors} (an input whose output name was already written in the run goes to errors)"##,
|
||||
r##"{"action":name|index? (instead of steps),"set":str?,"steps":[[commandId,params]|{"command":id,"params":{}}…] (a recorded action; a Save, Save As or Save a Copy step marks the document written to output, in this command's format and options: as the save found it if it was closed or another document is active at the end, else as the action leaves it; with no such step, the active document at the end),"input":folder|[paths],"overrideOpen":bool=false (execute action Open steps with the current input path, retaining other Open options; without an executed Open the input fails),"includeNonImages":bool=false (folder inputs report unsupported files as per-file errors instead of skipping them; arrays are unchanged),"includeSubfolders":bool=false (a folder input also takes the images in its subfolders, up to 32 levels and 100000 files; each result keeps its subfolder under output),"destination":"folder|saveAndClose"="folder" (Save and Close writes the same source path/format; rejects already-open sources and changed result document identity),"output":folder? (required only for folder; omit for Save and Close),"format":"same|png|jpg|psd|tiff|…"="same" (Save and Close requires same),"quality":0..12?,"jpegFormat":"baseline|optimized|progressive"?,"namingComponents":[{"component":choice}|{"text":str}]? (up to six; the exact filename, with no automatic extension),"compatibility":{"macintosh":bool,"windows":bool,"unix":bool}?,"flatOutput":bool=false (structured naming only),"overrideSaveAs":bool? (recorded routing; requires a directly represented Save configuration),"stopOnError":bool=false (report the first failed input and stop; earlier outputs remain saved),"naming":string? (blank keeps source names; {name}, {serial} padded to 3 digits, {date} as YYYY-MM-DD UTC; extension added automatically),"startingSerial":1..4294967295=1 (input position, including failed inputs),"tiffLayers":bool? (Folder default false; Save and Close default true, with false refused when TIFF layer data would be lost),"tiffCompression":"none|lzw|zip"?,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain),"calledActions":[{"name","steps"}…]? (the actions Play Action steps call; default: the session's)} → {files, errors} (an input whose output name was already written in the run goes to errors)"##,
|
||||
native,
|
||||
batch
|
||||
),
|
||||
|
||||
@@ -137,7 +137,7 @@ pub(crate) fn process_tree(
|
||||
suffix: &str,
|
||||
f: &dyn Fn(&mut Session, &str) -> Result<bool>,
|
||||
) -> Value {
|
||||
process_outputs(s, default_outputs(inputs, output, format, suffix), save, None, false, false, f)
|
||||
process_outputs(s, default_outputs(inputs, output, format, suffix), save, None, false, InputOpen::default(), f)
|
||||
}
|
||||
|
||||
/// Stream legacy destination names without collecting another path list for large batches.
|
||||
@@ -188,6 +188,13 @@ fn same_format_takes_the_file_names_extension() {
|
||||
assert_eq!(same_format("/in/.hidden"), "png");
|
||||
}
|
||||
|
||||
/// How one Batch input is opened; Image Processor keeps automatic image-only opening.
|
||||
#[derive(Clone, Copy, Default)]
|
||||
struct InputOpen {
|
||||
check_format: bool,
|
||||
from_action: bool,
|
||||
}
|
||||
|
||||
/// Check collisions before input reads and isolate each file in a scratch session.
|
||||
/// An optional content format decouples encoding from the structured destination filename.
|
||||
fn process_outputs<'a>(
|
||||
@@ -196,11 +203,11 @@ fn process_outputs<'a>(
|
||||
save: SaveOpts,
|
||||
content_format: Option<&str>,
|
||||
stop_on_error: bool,
|
||||
check_folder_format: bool,
|
||||
open: InputOpen,
|
||||
f: &dyn Fn(&mut Session, &str) -> Result<bool>,
|
||||
) -> Value {
|
||||
// The scratch sessions have default preferences; a raw opens at the user's Raw Defaults.
|
||||
let raw_ppi = s.prefs().raw_defaults.resolution;
|
||||
let raw_ppi = super::open::raw_open_resolution(s);
|
||||
let mut files = Vec::new();
|
||||
let mut errors = Vec::new();
|
||||
let mut written = OutputClaims::default();
|
||||
@@ -209,15 +216,19 @@ fn process_outputs<'a>(
|
||||
written.check(&out).map_err(EngineError::Other)?;
|
||||
// A folder must not silently use the embedded preview of an unsupported raw format.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if check_folder_format && !super::paths::openable_name(path) {
|
||||
if open.check_format && !super::paths::openable_name(path) {
|
||||
return Err(EngineError::Other(format!("unsupported Batch folder input: {path}")));
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let _ = check_folder_format;
|
||||
let bytes = read_file(path)?;
|
||||
let _ = open.check_format;
|
||||
let mut scratch = Session::new();
|
||||
let doc = import_at_raw_ppi(raw_ppi, &file_name(path), &bytes)?;
|
||||
scratch.add_document(doc, Some(path.to_string()));
|
||||
if open.from_action {
|
||||
scratch.batch_open = Some(super::open::BatchOpen { path: path.to_string(), sources: Vec::new(), raw_ppi });
|
||||
} else {
|
||||
let bytes = read_file(path)?;
|
||||
let doc = import_at_raw_ppi(raw_ppi, &file_name(path), &bytes)?;
|
||||
scratch.add_document(doc, Some(path.to_string()));
|
||||
}
|
||||
if !f(&mut scratch, &out)? {
|
||||
let d = scratch.active().ok_or(EngineError::NoDocument)?;
|
||||
let ext = content_format.map(|format| if format == "same" { same_format(path) } else { format.trim_start_matches('.').to_ascii_lowercase() });
|
||||
@@ -302,6 +313,11 @@ pub(crate) fn batch_action(list: &[crate::actions_cmds::Action], p: &Value) -> R
|
||||
/// Apply the selected file-error policy while retaining per-file results for direct callers.
|
||||
pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "file.automate.batch";
|
||||
let override_open = match p.get("overrideOpen") {
|
||||
None | Some(Value::Null) => false,
|
||||
Some(Value::Bool(value)) => *value,
|
||||
_ => return Err(EngineError::BadParams { cmd: cmd.into(), msg: "overrideOpen must be a boolean".into() }),
|
||||
};
|
||||
// Save and Close destination adapted from #10026 (@edaldridgePersonal, b96be5300cfa).
|
||||
let save_and_close = match p.get("destination") {
|
||||
None | Some(Value::Null) => false,
|
||||
@@ -422,7 +438,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let structured = !save_and_close && p.get("namingComponents").is_some_and(|v| !v.is_null());
|
||||
let run_format = structured.then(|| format.clone());
|
||||
let run = move |scratch: &mut Session, out: &str| {
|
||||
let source_id = scratch.active().ok_or(EngineError::NoDocument)?.doc.id;
|
||||
let source_id = scratch.active().map(|st| st.doc.id);
|
||||
if save_and_close {
|
||||
let encodable = extension(out).is_some_and(|ext| {
|
||||
matches!(ext.as_str(), "psd" | "psb" | "pcraft" | "ora") || photocraft_codecs::from_extension(&ext).is_some_and(|format| format.caps().write)
|
||||
@@ -433,17 +449,28 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let content_ext = run_format.as_deref().map(|format| {
|
||||
if format == "same" {
|
||||
same_format(scratch.active().and_then(|d| d.path.as_deref()).unwrap_or("input.png"))
|
||||
same_format(
|
||||
scratch
|
||||
.batch_open
|
||||
.as_ref()
|
||||
.map(|binding| binding.path.as_str())
|
||||
.or_else(|| scratch.active().and_then(|d| d.path.as_deref()))
|
||||
.unwrap_or("input.png"),
|
||||
)
|
||||
} else {
|
||||
format.trim_start_matches('.').to_ascii_lowercase()
|
||||
}
|
||||
});
|
||||
// Check the actual result, including a saved snapshot after Close, before either write path.
|
||||
let validate_result = |doc: &Document| -> Result<()> {
|
||||
let validate_result = |scratch: &Session, doc: &Document| -> Result<()> {
|
||||
if scratch.batch_open.as_ref().is_some_and(|binding| binding.sources.is_empty()) {
|
||||
return Err(EngineError::Other("Override Open requires an executed Open step for this input".into()));
|
||||
}
|
||||
if !save_and_close {
|
||||
return Ok(());
|
||||
}
|
||||
if doc.id != source_id {
|
||||
let from_source = scratch.batch_open.as_ref().map_or(source_id == Some(doc.id), |binding| binding.sources.contains(&doc.id));
|
||||
if !from_source {
|
||||
return Err(EngineError::Other("Save and Close needs the original source document or its recorded Save snapshot".into()));
|
||||
}
|
||||
let tiff = extension(out).and_then(|ext| photocraft_codecs::from_extension(&ext)) == Some(photocraft_codecs::Format::Tiff);
|
||||
@@ -484,14 +511,12 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// document left active, it is written as the save found it.
|
||||
match saved {
|
||||
Some(doc) if scratch.active().is_none_or(|d| d.doc.id != doc.id) => {
|
||||
validate_result(&doc)?;
|
||||
validate_result(scratch, &doc)?;
|
||||
save_output(&doc, out, save, content_ext.as_deref())?;
|
||||
Ok(true)
|
||||
}
|
||||
_ => {
|
||||
if save_and_close {
|
||||
validate_result(&scratch.active().ok_or(EngineError::NoDocument)?.doc)?;
|
||||
}
|
||||
validate_result(scratch, &scratch.active().ok_or(EngineError::NoDocument)?.doc)?;
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
@@ -499,20 +524,13 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
carried.set(scratch.actions.playback_steps);
|
||||
result
|
||||
};
|
||||
let open = InputOpen { check_format: check_folder_format, from_action: override_open };
|
||||
let r = match names {
|
||||
_ if save_and_close => {
|
||||
process_outputs(s, inputs.iter().map(|input| (input.path.as_str(), input.path.clone())), save, None, stop_on_error, check_folder_format, &run)
|
||||
_ if save_and_close => process_outputs(s, inputs.iter().map(|input| (input.path.as_str(), input.path.clone())), save, None, stop_on_error, open, &run),
|
||||
Some(names) => {
|
||||
process_outputs(s, inputs.iter().map(|i| i.path.as_str()).zip(names), save, structured.then_some(format.as_str()), stop_on_error, open, &run)
|
||||
}
|
||||
Some(names) => process_outputs(
|
||||
s,
|
||||
inputs.iter().map(|i| i.path.as_str()).zip(names),
|
||||
save,
|
||||
structured.then_some(format.as_str()),
|
||||
stop_on_error,
|
||||
check_folder_format,
|
||||
&run,
|
||||
),
|
||||
None => process_outputs(s, default_outputs(&inputs, &output, &format, ""), save, None, stop_on_error, check_folder_format, &run),
|
||||
None => process_outputs(s, default_outputs(&inputs, &output, &format, ""), save, None, stop_on_error, open, &run),
|
||||
};
|
||||
if s.actions.playing > 0 {
|
||||
s.actions.playback_steps = carried.get();
|
||||
|
||||
@@ -4,6 +4,32 @@ use super::{
|
||||
resize_surface, str_param, translate_surface,
|
||||
};
|
||||
|
||||
/// Input and successfully opened document identities of one Override Open scratch session.
|
||||
pub(crate) struct BatchOpen {
|
||||
pub path: String,
|
||||
pub sources: Vec<photocraft_doc::DocId>,
|
||||
pub raw_ppi: f64,
|
||||
}
|
||||
|
||||
/// Replace only the file choice before either authorization gate; malformed params stay invalid.
|
||||
pub(crate) fn batch_open_params(s: &Session, id: &str, params: &Value) -> Option<Value> {
|
||||
let binding = s.batch_open.as_ref()?;
|
||||
if !matches!(id, "file.openAs" | "file.openExrParts") || !(params.is_object() || params.is_null()) {
|
||||
return None;
|
||||
}
|
||||
let mut effective = if params.is_null() { super::json!({}) } else { params.clone() };
|
||||
effective.as_object_mut()?.insert("path".into(), Value::String(binding.path.clone()));
|
||||
Some(effective)
|
||||
}
|
||||
|
||||
/// Record provenance after a redirected native Open succeeds, including repeated Opens.
|
||||
pub(crate) fn remember_batch_open(s: &mut Session) {
|
||||
let id = s.active().map(|st| st.doc.id);
|
||||
if let (Some(binding), Some(id)) = (&mut s.batch_open, id) {
|
||||
binding.sources.push(id);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn import(name: &str, bytes: &[u8]) -> Result<Document> {
|
||||
import_result(name, bytes).map(|r| r.document)
|
||||
}
|
||||
@@ -99,7 +125,12 @@ pub(crate) fn tag_exr_colorspace(s: &Session, name: &str, doc: &mut Document) {
|
||||
/// Camera Raw's workflow options set it (the raw itself states none). `warnings` are the
|
||||
/// import's notes, which say whether the raw was developed or only its preview opened.
|
||||
pub fn raw_defaults(s: &Session, warnings: &[String], doc: &mut Document) {
|
||||
raw_resolution(s.prefs().raw_defaults.resolution, warnings, doc);
|
||||
raw_resolution(raw_open_resolution(s), warnings, doc);
|
||||
}
|
||||
|
||||
/// RAW resolution inherited by nested Batch inputs, or the session preference outside a binding.
|
||||
pub(crate) fn raw_open_resolution(s: &Session) -> f64 {
|
||||
s.batch_open.as_ref().map_or_else(|| s.prefs().raw_defaults.resolution, |binding| binding.raw_ppi)
|
||||
}
|
||||
|
||||
fn raw_resolution(ppi: f64, warnings: &[String], doc: &mut Document) {
|
||||
@@ -115,6 +146,9 @@ pub fn open_bytes_as(s: &mut Session, name: &str, bytes: &[u8], as_ext: Option<&
|
||||
None => name.to_string(),
|
||||
};
|
||||
let r = photocraft_io::import(&decode_name, bytes).map_err(|e| EngineError::Other(format!("{decode_name}: {e}")))?;
|
||||
if s.batch_open.is_some() && r.preview_only {
|
||||
return Err(EngineError::Other(format!("{name}: only an embedded preview could be read; Batch cannot process it as the source")));
|
||||
}
|
||||
let mut doc = r.document;
|
||||
tag_exr_colorspace(s, &decode_name, &mut doc);
|
||||
raw_defaults(s, &r.warnings, &mut doc);
|
||||
@@ -137,11 +171,14 @@ pub fn open_bytes_as(s: &mut Session, name: &str, bytes: &[u8], as_ext: Option<&
|
||||
Ok(json!({"document": i, "color": color, "warnings": r.warnings}))
|
||||
}
|
||||
|
||||
/// Open the selected file with its decoder options and record its Batch source identity.
|
||||
pub(super) fn open_as(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = str_param(p, "path", "file.openAs")?.to_string();
|
||||
let bytes = read_file(&path)?;
|
||||
let as_ext = p.get("as").or_else(|| p.get("format")).and_then(Value::as_str);
|
||||
open_bytes_as(s, &path, &bytes, as_ext, Some(path.clone()))
|
||||
let result = open_bytes_as(s, &path, &bytes, as_ext, Some(path.clone()))?;
|
||||
remember_batch_open(s);
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
// ---------- place ----------
|
||||
|
||||
@@ -308,6 +308,151 @@ fn batch_save_and_close_keeps_tiff_layers() {
|
||||
assert_eq!(result["files"], json!([flat]));
|
||||
}
|
||||
|
||||
/// Read a small saved Batch result with the same import/compositor oracle as the existing fixtures.
|
||||
fn batch_open_pixel(path: &str) -> [f32; 4] {
|
||||
let loaded = photocraft_io::import("result.png", &std::fs::read(path).unwrap()).unwrap().document;
|
||||
photocraft_compose::render(&loaded, Rect::new(0, 0, 1, 1)).px[0]
|
||||
}
|
||||
|
||||
/// Called and conditional actions and scripts retain Open settings and use each selected input.
|
||||
#[test]
|
||||
fn batch_override_open_follows_called_conditional_and_script_steps() {
|
||||
let dir = tmp("batch-override-open");
|
||||
let first = png(&dir, "a.png", 3, 2, "#ff0000");
|
||||
let second = png(&dir, "b.png", 3, 2, "#0000ff");
|
||||
let recorded = png(&dir, "recorded.png", 3, 2, "#00ff00");
|
||||
let mut s = session(7, 9, 8);
|
||||
let caller = photocraft_format::save_to_bytes(doc(&s), &Default::default()).unwrap();
|
||||
let prefs = serde_json::to_value(s.prefs()).unwrap();
|
||||
s.actions.list.push(crate::actions_cmds::Action::new("Open", vec![("file.openAs".into(), json!({"path":recorded,"as":"png"}))]));
|
||||
let actions = serde_json::to_value(&s.actions.list).unwrap();
|
||||
let steps = json!([["actions.conditional",{"if":"always","then":"Open"}],
|
||||
["file.scripts.browse",{"steps":[["file.closeAll",{}],["file.openAs",{"path":recorded,"as":"png"}]]}],
|
||||
["image.adjustments.invert",{}]]);
|
||||
for enabled in [false, true] {
|
||||
let output = join(&dir, if enabled { "redirected" } else { "legacy" });
|
||||
let result = s
|
||||
.execute(
|
||||
"file.automate.batch",
|
||||
json!({"input":[first,second],"output":output,"steps":steps,
|
||||
"calledActions":s.actions.list,"overrideOpen":enabled}),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(result["errors"].as_array().unwrap().is_empty(), "{result}");
|
||||
assert_eq!(batch_open_pixel(&join(&output, "a.png")), if enabled { [0.0, 1.0, 1.0, 1.0] } else { [1.0, 0.0, 1.0, 1.0] });
|
||||
assert_eq!(batch_open_pixel(&join(&output, "b.png")), if enabled { [1.0, 1.0, 0.0, 1.0] } else { [1.0, 0.0, 1.0, 1.0] });
|
||||
}
|
||||
let failed = s
|
||||
.execute(
|
||||
"file.automate.batch",
|
||||
json!({"input":[first],"output":join(&dir,"forced-format"),"overrideOpen":true,
|
||||
"steps":[["file.openAs",{"path":recorded,"as":"pdn"}]]}),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(failed["errors"].as_array().unwrap().len(), 1, "nondefault Open settings must still affect decoding: {failed}");
|
||||
assert!(!std::path::Path::new(&join(&dir, "forced-format/a.png")).exists());
|
||||
let invalid = join(&dir, "invalid-override");
|
||||
assert!(s.execute("file.automate.batch", json!({"input":[first],"output":invalid,"steps":[],"overrideOpen":"true"})).is_err());
|
||||
assert!(!std::path::Path::new(&invalid).exists());
|
||||
assert_eq!(serde_json::to_value(&s.actions.list).unwrap(), actions);
|
||||
assert_eq!(serde_json::to_value(s.prefs()).unwrap(), prefs);
|
||||
assert_eq!(photocraft_format::save_to_bytes(doc(&s), &Default::default()).unwrap(), caller);
|
||||
assert!(s.batch_open.is_none());
|
||||
}
|
||||
|
||||
/// Both authorization gates see the actual input; a denied file keeps its source and output intact.
|
||||
#[test]
|
||||
fn batch_override_open_authorizes_effective_path_and_carries_failure_budget() {
|
||||
static OPENS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
|
||||
fn gate(id: &str, p: &Value) -> Result<()> {
|
||||
if id == "file.openAs" {
|
||||
OPENS.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
|
||||
if p["as"] != "png" || p["path"].as_str().is_none_or(|path| file_name(path) != "a.png") {
|
||||
return Err(EngineError::Other("effective Open denied".into()));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
let dir = tmp("batch-open-authorization");
|
||||
let first = png(&dir, "a.png", 3, 2, "#ff0000");
|
||||
let second = png(&dir, "b.png", 3, 2, "#0000ff");
|
||||
let original = std::fs::read(&second).unwrap();
|
||||
let output = join(&dir, "out");
|
||||
std::fs::create_dir_all(&output).unwrap();
|
||||
let existing = png(&output, "b.png", 3, 2, "#4488aa");
|
||||
let intact = std::fs::read(&existing).unwrap();
|
||||
let mut s = Session::new();
|
||||
s.actions.list.push(crate::actions_cmds::Action::new("Open", vec![("file.openAs".into(), json!({"path":"/recorded.png","as":"png"}))]));
|
||||
s.batch_open = Some(BatchOpen { path: first.clone(), sources: Vec::new(), raw_ppi: 300.0 });
|
||||
assert!(matches!(s.execute("file.openAs", json!([1])), Err(EngineError::BadParams { .. })));
|
||||
assert!(s.documents().is_empty());
|
||||
s.batch_open = None;
|
||||
s.authorize = Some(gate);
|
||||
s.actions.playing = 1;
|
||||
OPENS.store(0, std::sync::atomic::Ordering::SeqCst);
|
||||
let result = s
|
||||
.execute(
|
||||
"file.automate.batch",
|
||||
json!({"input":[first,second],"output":output,"overrideOpen":true,"stopOnError":true,
|
||||
"steps":[["actions.play",{"action":"Open"}]]}),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(result["files"], json!([join(&output, "a.png")]), "{result}");
|
||||
assert_eq!(result["errors"].as_array().unwrap().len(), 1, "{result}");
|
||||
assert!(result["errors"][0]["error"].as_str().unwrap().contains("effective Open denied"));
|
||||
assert_eq!(OPENS.load(std::sync::atomic::Ordering::SeqCst), 3, "two gates for the first Open, preauthorization denies the second");
|
||||
assert_eq!(s.actions.playback_steps, 4);
|
||||
assert_eq!(std::fs::read(&second).unwrap(), original);
|
||||
assert_eq!(std::fs::read(&existing).unwrap(), intact);
|
||||
assert!(s.documents().is_empty());
|
||||
assert!(s.batch_open.is_none());
|
||||
}
|
||||
|
||||
/// Inner Batch bindings do not replace outer input provenance or the shared logical-step budget.
|
||||
#[test]
|
||||
fn batch_override_open_nested_binding_and_save_close_preserve_sources() {
|
||||
let dir = tmp("batch-open-nested");
|
||||
let first = png(&dir, "a.png", 3, 2, "#ff0000");
|
||||
let second = png(&dir, "b.png", 3, 2, "#0000ff");
|
||||
let output = join(&dir, "outer");
|
||||
let inner = join(&dir, "inner");
|
||||
let open = json!({"path":"/recorded.png","as":"png"});
|
||||
let mut s = Session::new();
|
||||
s.actions.list.push(crate::actions_cmds::Action::new("Open", vec![("file.openAs".into(), open.clone())]));
|
||||
let steps = json!([["actions.play",{"action":"Open"}],
|
||||
["file.automate.batch",{"input":[second],"output":inner,"overrideOpen":true,"steps":[["file.openAs",open],["image.adjustments.invert",{}]]}],
|
||||
["file.closeAll",{}],["file.openAs",open],["image.adjustments.invert",{}]]);
|
||||
s.actions.playing = 1;
|
||||
s.actions.playback_steps = crate::actions_cmds::MAX_PLAYBACK_STEPS - 8;
|
||||
let result = s.execute("file.automate.batch", json!({"input":[first],"output":output,"overrideOpen":true,"steps":steps})).unwrap();
|
||||
assert!(result["errors"].as_array().unwrap().is_empty(), "{result}");
|
||||
assert_eq!(batch_open_pixel(&join(&output, "a.png")), [0.0, 1.0, 1.0, 1.0]);
|
||||
assert_eq!(batch_open_pixel(&join(&inner, "b.png")), [1.0, 1.0, 0.0, 1.0]);
|
||||
assert_eq!(s.actions.playback_steps, crate::actions_cmds::MAX_PLAYBACK_STEPS);
|
||||
s.actions.playing = 0;
|
||||
let original = std::fs::read(&first).unwrap();
|
||||
for steps in [
|
||||
json!([["image.adjustments.invert", {}]]),
|
||||
json!([["file.new",{"width":2,"height":2}],["file.saveAs",{}]]),
|
||||
json!([["file.openAs",open],["file.new",{"width":2,"height":2}],["file.saveAs",{}]]),
|
||||
] {
|
||||
let result = s.execute("file.automate.batch", json!({"input":[first],"destination":"saveAndClose","overrideOpen":true,"steps":steps})).unwrap();
|
||||
assert_eq!(result["errors"].as_array().unwrap().len(), 1, "{result}");
|
||||
assert_eq!(std::fs::read(&first).unwrap(), original);
|
||||
}
|
||||
let result = s
|
||||
.execute(
|
||||
"file.automate.batch",
|
||||
json!({"input":[first],"destination":"saveAndClose","overrideOpen":true,
|
||||
"steps":[["file.openAs",open],["image.adjustments.invert",{}],["file.saveAs",{}],["file.close",{}]]}),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(result["errors"].as_array().unwrap().is_empty(), "{result}");
|
||||
assert_eq!(batch_open_pixel(&first), [0.0, 1.0, 1.0, 1.0]);
|
||||
assert!(s.documents().is_empty());
|
||||
assert!(s.batch_open.is_none());
|
||||
}
|
||||
|
||||
fn tmp(name: &str) -> String {
|
||||
let d = std::env::temp_dir().join(format!("photocraft-file-cmds-{}-{name}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
@@ -451,6 +596,20 @@ fn revert_batch_and_stack_open_a_raw_at_the_raw_defaults_resolution() {
|
||||
assert_eq!(files.len(), 1, "{r}");
|
||||
let psd = photocraft_io::import("IMG_0003.psd", &std::fs::read(files[0].as_str().unwrap()).unwrap()).unwrap().document;
|
||||
assert_eq!(psd.resolution_dpi, 240.0, "Batch");
|
||||
// A nested Override Open inherits the outer input's resolution, not scratch defaults.
|
||||
let nested = join(&dir, "nested");
|
||||
let r = s
|
||||
.execute(
|
||||
"file.automate.batch",
|
||||
json!({"input":[path],"output":join(&dir,"outer"),"format":"psd","overrideOpen":true,
|
||||
"steps":[["file.openAs",{"path":"/recorded.dng"}],
|
||||
["file.automate.batch",{"input":[path],"output":nested,"format":"psd","overrideOpen":true,
|
||||
"steps":[["file.openAs",{"path":"/recorded.dng"}]]}]]}),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(r["errors"].as_array().unwrap().is_empty(), "{r}");
|
||||
let nested = photocraft_io::import("IMG_0003.psd", &std::fs::read(join(&nested, "IMG_0003.psd")).unwrap()).unwrap().document;
|
||||
assert_eq!(nested.resolution_dpi, 240.0, "nested Override Open keeps the caller's RAW resolution");
|
||||
s.execute("file.scripts.loadFilesIntoStack", json!({"paths": [path]})).unwrap();
|
||||
assert_eq!(doc(&s).resolution_dpi, 240.0, "Load Files into Stack");
|
||||
}
|
||||
|
||||
@@ -787,6 +787,7 @@ impl Session {
|
||||
if !(params.is_object() || params.is_null()) {
|
||||
return Err(EngineError::BadParams { cmd: id.to_string(), msg: "params must be a JSON object".into() });
|
||||
}
|
||||
let params = crate::file_cmds::batch_open_params(self, id, ¶ms).unwrap_or(params);
|
||||
// Untrusted sessions gate every command, including the ones a command runs on its own
|
||||
// behalf (`file.automate.conditionalModeChange` runs `image.mode.*`), before any side
|
||||
// effect.
|
||||
|
||||
@@ -186,6 +186,8 @@ pub(crate) fn active_layer_of(s: &Session) -> std::result::Result<&photocraft_do
|
||||
#[derive(Default)]
|
||||
pub struct Session {
|
||||
docs: Vec<DocState>,
|
||||
/// Override Open belongs only to one Batch scratch session, never to caller preferences.
|
||||
pub(crate) batch_open: Option<file_cmds::BatchOpen>,
|
||||
/// Admitted document identities in opening order, independent of visual-tab reordering.
|
||||
open_document_order: Vec<photocraft_doc::DocId>,
|
||||
active: Option<usize>,
|
||||
|
||||
+14
-1
@@ -281,8 +281,21 @@ exact extension; import-only/unknown/extensionless inputs require Save As and
|
||||
fail instead of producing guessed sibling files. Caller documents and editing
|
||||
state stay unchanged.
|
||||
|
||||
Override Open starts each input without a document and redirects executed Open
|
||||
steps to that input, preserving their represented native options. Called actions,
|
||||
conditionals and scripts share that input binding; nested Batch runs keep their
|
||||
own binding. Authorization sees the redirected path before opening. No executed
|
||||
Open is a per-file failure. Save and Close accepts only a document opened from
|
||||
that input or its recorded Save snapshot, including after Close.
|
||||
|
||||
The Open ATN converter admits only its represented path field. Richer recorded
|
||||
Open settings remain complete steps; native format/decoder options execute but
|
||||
are refused on ATN export until their wire representation is supported. This does
|
||||
not claim parity for unrepresented Open options. Native Batch keeps automatic
|
||||
opening when overrideOpen is false or omitted.
|
||||
|
||||
This maps supported text-path folder forms. Alias bytes, open-document sources,
|
||||
error logs and enabled Open/dialog overrides remain preserved steps. Save and
|
||||
error logs and enabled dialog overrides remain preserved steps. Save and
|
||||
Close with unrepresented override combinations also remains preserved. For an
|
||||
admitted recorded Save As configuration, native preflight refuses unrepresented
|
||||
save routing: override requires a directly represented Save step,
|
||||
|
||||
Reference in new issue
Block a user