mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
Open As: an error names the file that was chosen and the format asked for (#14049)
Open As built `<stem>.<as>` to pick the decoder and also put that made-up name into the error, so notes.txt opened as pcx failed as "notes.pcx: ...". The decoder name is unchanged; the error now names the real file and the format asked for, keeping the decoder's detail: `"notes.txt" could not be opened as PCX: codec: unrecognized image format`. The batch RAW path names the real file too. An `as` value that names no format PhotoCraft reads is a BadParams error naming the value, before any decode. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Model-Effort: Opus 5.5 drove; Opus 5.5 briefed; Sonnet 5.5 wrote at medium
This commit is contained in:
1 parent
dc0f56b22e
commit
f41a952236
5 files changed
+124
-6
No files matched your search
@@ -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::*;
|
||||
|
||||
@@ -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,19 @@ 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 document, vector and camera raw
|
||||
/// 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", "af", "afdesign", "afphoto",
|
||||
"afpub", "dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "raf", "rw2", "srf", "sr2",
|
||||
];
|
||||
|
||||
/// 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();
|
||||
OPEN_AS_EXTRA.contains(&ext.as_str()) || 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<Value> {
|
||||
let path = str_param(p, "path", "file.openAs")?.to_string();
|
||||
@@ -246,6 +262,11 @@ pub(super) fn open_as(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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);
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
//! 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 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");
|
||||
}
|
||||
@@ -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<Option<(ImportResult, CameraRaw)>> {
|
||||
pub(super) fn prepare(s: &Session, name: &str, shown: &str, path: Option<&str>, bytes: &[u8]) -> Result<Option<(ImportResult, CameraRaw)>> {
|
||||
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;
|
||||
|
||||
@@ -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 `<stem>.<as>` 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<photocraft_raster::AllocationError> for EngineError {
|
||||
fn from(error: photocraft_raster::AllocationError) -> Self {
|
||||
Self::Other(format!("not enough memory for this operation ({error}); the document was not changed"))
|
||||
|
||||
Reference in new issue
Block a user