diff --git a/crates/engine-vector/src/cmd/comps_cmds.rs b/crates/engine-vector/src/cmd/comps_cmds.rs index 8c4154772e0..577f584c4b5 100644 --- a/crates/engine-vector/src/cmd/comps_cmds.rs +++ b/crates/engine-vector/src/cmd/comps_cmds.rs @@ -493,8 +493,8 @@ fn comps_to_files(s: &mut Session, p: &Value) -> Result { let mut one = (*doc).clone(); apply_comp(&mut one, c, false); one.last_applied_comp = Some(c.id); - let comment = if c.comment.trim().is_empty() { String::new() } else { format!("_{}", part(&c.comment)) }; - let path = join(&dir, &format!("{}_{:04}_{}{comment}.{ext}", sanitize(&prefix), i, part(&c.name))); + let comment = if c.comment.trim().is_empty() { String::new() } else { part(&c.comment) }; + let path = join(&dir, &comp_file_name(&sanitize(&prefix), i, &part(&c.name), &comment, ext)); save_doc(&one, &path, save)?; files.push(path); } @@ -507,6 +507,32 @@ fn comps_to_files(s: &mut Session, p: &Value) -> Result { Ok(json!({"files": files})) } +/// The longest file name most file systems take: 255 bytes (and a name of at most 255 UTF-8 bytes +/// is at most 255 UTF-16 units, Windows' limit). +const MAX_FILE_NAME_BYTES: usize = 255; + +/// `__[_].`, at most [`MAX_FILE_NAME_BYTES`] long. A name that +/// doesn't fit loses the end of its comment first (the whole comment, with its `_`, when none of it +/// fits), then of the comp name, then of the prefix; the index and extension always stay. Each +/// cut falls between characters. +fn comp_file_name(prefix: &str, index: usize, name: &str, comment: &str, ext: &str) -> String { + let index = format!("_{index:04}_"); + let room = MAX_FILE_NAME_BYTES.saturating_sub(index.len() + 1 + ext.len()); + let prefix = clip_bytes(prefix, room); + let room = room - prefix.len(); + let name = clip_bytes(name, room); + let comment = clip_bytes(comment, (room - name.len()).saturating_sub(1)); + let comment = if comment.is_empty() { String::new() } else { format!("_{comment}") }; + format!("{prefix}{index}{name}{comment}.{ext}") +} + +/// The longest start of `text` that fits in `max` bytes without splitting a character, with any +/// spaces the cut leaves at its end trimmed. +fn clip_bytes(text: &str, max: usize) -> &str { + let end = text.char_indices().map(|(i, c)| i + c.len_utf8()).take_while(|&end| end <= max).last().unwrap_or(0); + text.get(..end).unwrap_or_default().trim_end() +} + pub fn specs() -> Vec { macro_rules! spec { ($id:expr, $label:expr, $menu:expr, $params:expr, $enabled:expr, $run:expr) => { @@ -577,7 +603,7 @@ pub fn specs() -> Vec { "file.export.layerCompsToFiles", "Layer Comps to Files…", &["File", "Export"], - r##"{"dir":folder,"format":"png|jpg|psd|tiff|…"="png","prefix":str=document name,"selectedOnly":bool=false (only the last applied comp),"comps":[id]?,"quality":0..12?} → {files} (one "__[_]." per comp, the index 4 digits from 0000 in panel order and the comment only when not blank: spaces in the name and comment become "-" in PNG and stay in other formats, characters a file name can't hold become "_", and TIFF and JPEG are written as .tif and .jpg)"##, + r##"{"dir":folder,"format":"png|jpg|psd|tiff|…"="png","prefix":str=document name,"selectedOnly":bool=false (only the last applied comp),"comps":[id]?,"quality":0..12?} → {files} (one "__[_]." per comp, the index 4 digits from 0000 in panel order and the comment only when not blank: spaces in the name and comment become "-" in PNG and stay in other formats, characters a file name can't hold become "_", and TIFF and JPEG are written as .tif and .jpg; a name past 255 bytes is cut from the end of the comment first, then of the comp name, then of the prefix, keeping the index and extension)"##, export_comps, comps_to_files ), diff --git a/crates/engine-vector/src/cmd/comps_cmds/layer_comps_to_files_names_tests.rs b/crates/engine-vector/src/cmd/comps_cmds/layer_comps_to_files_names_tests.rs index dc4aba130dc..60df647c9ce 100644 --- a/crates/engine-vector/src/cmd/comps_cmds/layer_comps_to_files_names_tests.rs +++ b/crates/engine-vector/src/cmd/comps_cmds/layer_comps_to_files_names_tests.rs @@ -13,9 +13,11 @@ fn session(comps: &[(&str, &str)]) -> Session { s } -/// Runs Layer Comps to Files with `format` into a fresh folder named after it; the folder and the file names. +/// Runs Layer Comps to Files with `format` into a fresh folder of its own; the folder and the file names. fn export(s: &mut Session, format: &str) -> (std::path::PathBuf, Vec) { - let dir = std::env::temp_dir().join(format!("photocraft-comp-names-{format}-{}", std::process::id())); + static RUN: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + let run = RUN.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let dir = std::env::temp_dir().join(format!("photocraft-comp-names-{format}-{}-{run}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); let params = json!({"dir": dir.to_string_lossy(), "prefix": "lcomps-test", "format": format}); @@ -55,3 +57,24 @@ fn other_formats_keep_spaces_and_write_tif_and_jpg() { let _ = std::fs::remove_dir_all(&dir); } } + +/// A comment of several sentences no longer stops the export at its comp (#13940 review): the +/// comment is cut to fit, between characters, and that comp and the next keep their indices and +/// extension. +#[test] +fn a_long_comment_is_shortened_and_the_export_goes_on() { + let long = "Hintergrund für die Nachtszene, mit gedämpftem Licht über dem Fluss. ".repeat(6); + for (format, ext) in [("png", "png"), ("tiff", "tif")] { + let mut s = session(&[("Comp A", &long), ("Comp B", "")]); + let (dir, names) = export(&mut s, format); + assert_eq!(names.len(), 2, "{format}: {names:?}"); + let full = if ext == "png" { sanitize(&long).replace(' ', "-") } else { sanitize(&long) }; + let first = names[0].strip_prefix("lcomps-test_0000_Comp").and_then(|n| n.strip_suffix(&format!(".{ext}"))).unwrap_or_default(); + let kept = first.get(3..).unwrap_or_default(); + assert!(!kept.is_empty() && full.starts_with(kept) && kept.len() < full.len(), "{format}: the comment is shortened, not dropped: {}", names[0]); + assert!(names[0].len() <= 255, "{format}: {} bytes", names[0].len()); + assert_eq!(names[1], format!("lcomps-test_0001_Comp{}B.{ext}", if ext == "png" { "-" } else { " " }), "{format}"); + assert!(names.iter().all(|n| dir.join(n).is_file()), "{format}: both files are written"); + let _ = std::fs::remove_dir_all(&dir); + } +}