diff --git a/crates/engine/src/cmd/file_cmds.rs b/crates/engine/src/cmd/file_cmds.rs index 44c16844ca..24375502bf 100644 --- a/crates/engine/src/cmd/file_cmds.rs +++ b/crates/engine/src/cmd/file_cmds.rs @@ -448,6 +448,10 @@ mod place_job_tests; #[path = "file_cmds/open_as_smart_object_tests.rs"] mod open_as_smart_object_tests; +#[cfg(test)] +#[path = "file_cmds/open_as_error_name_tests.rs"] +mod open_as_error_name_tests; + #[cfg(test)] mod aces_exr_tests { use super::*; diff --git a/crates/engine/src/cmd/file_cmds/open.rs b/crates/engine/src/cmd/file_cmds/open.rs index 282eae0e4e..d48a41eab2 100644 --- a/crates/engine/src/cmd/file_cmds/open.rs +++ b/crates/engine/src/cmd/file_cmds/open.rs @@ -196,11 +196,14 @@ pub fn open_bytes_as_with_options( let mut opts = crate::jobs::import_options(s.prefs()); opts.psd_high_memory_approved = approve_high_memory; opts.psd_approved_estimate = None; - let raw = super::raw_open::prepare(s, &decode_name, path.as_deref(), bytes)?; + let raw = super::raw_open::prepare(s, &decode_name, &file_name(name), path.as_deref(), bytes)?; let (r, raw_settings) = if let Some((imported, settings)) = raw { (imported, Some(settings)) } else { - let r = photocraft_io::import_with_options(&decode_name, bytes, &opts).map_err(|e| crate::error::io_open_error(&decode_name, e))?; + let r = photocraft_io::import_with_options(&decode_name, bytes, &opts).map_err(|e| match as_ext { + Some(ext) => crate::error::io_open_as_error(&file_name(name), ext, e), + None => crate::error::io_open_error(&decode_name, e), + })?; (r, None) }; if (s.batch_open.is_some() || s.batch_open_notices.is_some()) && r.preview_only { @@ -235,6 +238,22 @@ pub fn open_bytes_as_with_options( Ok(json!({"document": i, "color": color, "warnings": r.warnings})) } +/// Extensions Open As reads besides the codec formats, the camera raw formats +/// (`photocraft_io::raw::EXTENSIONS`) and the Affinity ones (`photocraft_io::affinity::EXTENSIONS`): +/// the document and vector formats `photocraft_io::import` handles, and `raw`, the Open As type +/// for any camera raw. +const OPEN_AS_EXTRA: &[&str] = &["raw", "pdn", "ora", "xcf", "xcf.gz", "xcfgz", "kra", "krz", "psd", "psb", "psdt", "pcraft", "svg", "svgz", "pdf", "ai"]; + +/// Whether `ext` (the `as` value of Open As) names a format PhotoCraft reads. +fn is_open_as_format(ext: &str) -> bool { + let ext = ext.trim_start_matches('.').to_ascii_lowercase(); + let ext = ext.as_str(); + OPEN_AS_EXTRA.contains(&ext) + || photocraft_io::raw::EXTENSIONS.contains(&ext) + || photocraft_io::affinity::EXTENSIONS.contains(&ext) + || photocraft_codecs::from_extension(ext).is_some_and(|f| f.caps().read) +} + /// 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 { let path = str_param(p, "path", "file.openAs")?.to_string(); @@ -246,6 +265,11 @@ pub(super) fn open_as(s: &mut Session, p: &Value) -> Result { return Err(EngineError::BadParams { cmd: "file.openAs".into(), msg: "expected boolean for \"approveHighMemory\"".into() }); } }; + if let Some(ext) = as_ext + && !is_open_as_format(ext) + { + return Err(EngineError::BadParams { cmd: "file.openAs".into(), msg: format!("\"as\" names no format PhotoCraft reads: {ext:?}") }); + } let bytes = read_file(&path)?; let result = open_bytes_as_with_options(s, &path, &bytes, as_ext, Some(path.clone()), approve_high_memory)?; remember_batch_open(s); diff --git a/crates/engine/src/cmd/file_cmds/open_as_error_name_tests.rs b/crates/engine/src/cmd/file_cmds/open_as_error_name_tests.rs new file mode 100644 index 0000000000..78584e246e --- /dev/null +++ b/crates/engine/src/cmd/file_cmds/open_as_error_name_tests.rs @@ -0,0 +1,92 @@ +//! File › Open As… (#14049): an error names the file that was chosen and the format asked for, +//! never the stem plus the `as` extension that only picks the decoder. + +use super::*; + +fn tmp(name: &str) -> String { + static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let d = std::env::temp_dir().join(format!("photocraft-open-as-name-{}-{name}-{id}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d.to_string_lossy().into_owned() +} + +fn write_notes(dir: &str) -> String { + let path = join(dir, "notes.txt"); + std::fs::write(&path, b"just some text.\n").unwrap(); + path +} + +fn error_text(s: &mut Session, path: &str, as_ext: &str) -> String { + match s.execute("file.openAs", json!({"path": path, "as": as_ext})) { + Err(e) => e.to_string(), + Ok(v) => panic!("opening a text file as {as_ext} succeeded: {v}"), + } +} + +#[test] +fn a_text_file_opened_as_pcx_names_notes_txt_and_pcx() { + let dir = tmp("pcx"); + let path = write_notes(&dir); + let mut s = Session::new(); + let msg = error_text(&mut s, &path, "pcx"); + assert!(msg.contains("notes.txt"), "{msg}"); + assert!(msg.contains("PCX"), "{msg}"); + assert!(!msg.contains("notes.pcx"), "{msg}"); + assert!(msg.contains("unrecognized image format"), "the decoder's detail stays: {msg}"); + assert_eq!(s.documents().len(), 0); +} + +#[test] +fn a_text_file_opened_as_raw_names_notes_txt_and_raw() { + let dir = tmp("raw"); + let path = write_notes(&dir); + let mut s = Session::new(); + let msg = error_text(&mut s, &path, "raw"); + assert!(msg.contains("notes.txt"), "{msg}"); + assert!(msg.contains("RAW"), "{msg}"); + assert!(!msg.contains("notes.raw"), "{msg}"); + assert_eq!(s.documents().len(), 0); +} + +#[test] +fn an_unknown_as_value_is_a_parameter_error_naming_it() { + let dir = tmp("bogus"); + let path = write_notes(&dir); + let mut s = Session::new(); + match s.execute("file.openAs", json!({"path": path, "as": "bogus"})) { + Err(EngineError::BadParams { cmd, msg }) => { + assert_eq!(cmd, "file.openAs"); + assert!(msg.contains("bogus"), "{msg}"); + } + other => panic!("expected BadParams, got {other:?}"), + } + assert_eq!(s.documents().len(), 0); +} + +#[test] +fn every_camera_raw_and_affinity_extension_is_an_open_as_format() { + // The `as` check must take every format the importer reads, not a copy of the lists that can + // fall behind them: a text file asked to open as one fails to read, never as a parameter error. + let dir = tmp("raw-exts"); + let path = write_notes(&dir); + let mut s = Session::new(); + for ext in photocraft_io::raw::EXTENSIONS.iter().chain(photocraft_io::affinity::EXTENSIONS) { + let r = s.execute("file.openAs", json!({"path": path, "as": ext})); + assert!(!matches!(r, Err(EngineError::BadParams { .. })), "{ext}: {r:?}"); + } +} + +#[test] +fn a_png_opened_as_png_keeps_its_real_file_name() { + let dir = tmp("png"); + let img = photocraft_codecs::Image::from_u8(4, 4, photocraft_codecs::ChannelLayout::Rgb, vec![200; 48]).unwrap(); + let bytes = photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()).unwrap(); + let path = join(&dir, "photo one.png"); + std::fs::write(&path, bytes).unwrap(); + let mut s = Session::new(); + s.execute("file.openAs", json!({"path": path, "as": "png"})).unwrap(); + assert_eq!(s.documents().len(), 1); + assert_eq!(s.active().unwrap().doc.name, "photo one.png"); +} diff --git a/crates/engine/src/cmd/file_cmds/raw_open.rs b/crates/engine/src/cmd/file_cmds/raw_open.rs index c252acc1de..eb61322f35 100644 --- a/crates/engine/src/cmd/file_cmds/raw_open.rs +++ b/crates/engine/src/cmd/file_cmds/raw_open.rs @@ -61,7 +61,7 @@ fn auto_sample(surface: &photocraft_raster::Surface) -> Vec<[f32; 4]> { } /// Develop representable prior settings at the sensor stage, retaining only the remaining RGB work. -pub(super) fn prepare(s: &Session, name: &str, path: Option<&str>, bytes: &[u8]) -> Result> { +pub(super) fn prepare(s: &Session, name: &str, shown: &str, path: Option<&str>, bytes: &[u8]) -> Result> { let Some(defaults) = &s.batch_raw_open else { return Ok(None) }; if !photocraft_io::raw::is_raw(bytes) { return Ok(None); @@ -74,9 +74,9 @@ pub(super) fn prepare(s: &Session, name: &str, path: Option<&str>, bytes: &[u8]) let prior = prior.map(|(settings, _)| settings); let mut settings = prior.clone().unwrap_or_default(); let opts = crate::jobs::import_options(s.prefs()); - let mut imported = photocraft_io::import_with_options(name, bytes, &opts).map_err(|error| EngineError::Other(format!("{name}: {error}")))?; + let mut imported = photocraft_io::import_with_options(name, bytes, &opts).map_err(|error| EngineError::Other(format!("{shown}: {error}")))?; if imported.preview_only || !imported.warnings.iter().any(|warning| warning.contains(photocraft_io::raw::DEVELOPED_NOTE)) { - return Err(EngineError::Other(format!("{name}: complete RAW development is required"))); + return Err(EngineError::Other(format!("{shown}: complete RAW development is required"))); } if prior.is_none() && defaults.apply_auto_tone { let surface = imported.document.layers.iter().find_map(|layer| layer.surface()).ok_or(EngineError::NoDocument)?; @@ -97,7 +97,8 @@ pub(super) fn prepare(s: &Session, name: &str, path: Option<&str>, bytes: &[u8]) }; if tuning != (RawTuning { demosaic: opts.demosaic, ..Default::default() }) { super::open::raw_defaults(s, &imported.warnings, &mut imported.document); - let (mut developed, wb) = photocraft_io::raw::import_raw_tuned(name, bytes, &tuning).map_err(|error| EngineError::Other(format!("{name}: {error}")))?; + let (mut developed, wb) = + photocraft_io::raw::import_raw_tuned(name, bytes, &tuning).map_err(|error| EngineError::Other(format!("{shown}: {error}")))?; developed.document.resolution_dpi = imported.document.resolution_dpi; imported = developed; settings.exposure = 0.0; diff --git a/crates/engine/src/error.rs b/crates/engine/src/error.rs index 4d98747394..0cbbd3039e 100644 --- a/crates/engine/src/error.rs +++ b/crates/engine/src/error.rs @@ -144,6 +144,19 @@ pub(crate) fn io_open_error(name: &str, error: photocraft_io::IoError) -> Engine } } +/// [`io_open_error`] for Open As: `name` is the real file name and `as_ext` the format asked for, +/// so a file that cannot be read as it says so instead of naming a made-up `.` file. +pub(crate) fn io_open_as_error(name: &str, as_ext: &str, error: photocraft_io::IoError) -> EngineError { + match io_open_error(name, error) { + EngineError::Other(message) => { + let detail = message.strip_prefix(&format!("{name}: ")).unwrap_or(&message); + let format = as_ext.trim_start_matches('.').to_ascii_uppercase(); + EngineError::Other(format!("\"{name}\" could not be opened as {format}: {detail}")) + } + other => other, + } +} + impl From for EngineError { fn from(error: photocraft_raster::AllocationError) -> Self { Self::Other(format!("not enough memory for this operation ({error}); the document was not changed"))