Layer Comps to Files: a long comment is shortened, not a failed export (#13940)

The comp comment is appended to the file name, and nothing limited the
length, so a comment of a few sentences gave a name past the 255-byte
file name limit and the save stopped the whole export at that comp.

`comp_file_name` now builds `<prefix>_<index>_<name>[_<comment>].<ext>`
within 255 bytes (which also keeps it within Windows' 255 UTF-16 units).
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, and every cut falls
between characters.

The new test exports a comp with a six-sentence comment (with umlauts)
and the comp after it, as PNG and TIFF; without the change the export
fails at the first comp. The names tests now export into a folder per
run, so the PNG tests no longer share one.
This commit is contained in:
RickiNano committed 2026-11-25 07:16:04 +01:00
1 parent b77e6333ed
commit 5bc0153391
2 files changed
+54 -5

No files matched your search

+29 -3
View File
@@ -493,8 +493,8 @@ fn comps_to_files(s: &mut Session, p: &Value) -> Result<Value> {
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<Value> {
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;
/// `<prefix>_<index>_<name>[_<comment>].<ext>`, 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<CommandSpec> {
macro_rules! spec {
($id:expr, $label:expr, $menu:expr, $params:expr, $enabled:expr, $run:expr) => {
@@ -577,7 +603,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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 "<prefix>_<index>_<comp name>[_<comment>].<ext>" 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 "<prefix>_<index>_<comp name>[_<comment>].<ext>" 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
),
@@ -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<String>) {
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);
}
}