Merge pull request #15290

This commit is contained in:
autocraft-bot[bot] committed 2026-12-01 15:26:27 +00:00
commit e13bf04166
9 files changed
+182 -52

No files matched your search

+3 -2
View File
@@ -101,8 +101,8 @@ fn recovery_dir() -> Option<PathBuf> {
}
/// Write `bytes` crash-safely (temp file beside the target, fsync, rename, directory fsync; see
/// [`photocraft_format::atomic`]). Every document write (Save, Save As, Export, Save for Web) and
/// the preferences go through here, so a failed or interrupted save never destroys the old file.
/// [`photocraft_format::atomic`]). Save, Save As, overwriting exports and preferences use this so
/// a failed or interrupted write never destroys the old file.
fn write_atomic(path: &Path, bytes: &[u8]) -> Result<(), String> {
photocraft_format::atomic_write(path, bytes).map_err(|e| e.to_string())
}
@@ -602,6 +602,7 @@ pub fn native(automation: Option<photocraft_automation::AuthorizedWorkspace>, wa
file_panels: Some(file_panels),
settings: Some(settings_store()),
write: Some(Box::new(|path: &str, bytes: &[u8]| write_atomic(Path::new(path), bytes))),
write_new: Some(Box::new(|path, bytes| photocraft_format::write_noreplace(Path::new(path), bytes).map_err(|e| format!("{path}: {e}")))),
file_stamp: Some(Box::new(|path: &str| {
// Follows a symlink, as Save writes through it to the file it points at.
let meta = std::fs::metadata(path).ok()?;
+96 -40
View File
@@ -379,8 +379,7 @@ pub fn quick_export_layer_png(app: &mut PhotocraftApp, layer: LayerId) -> Result
pick_and_export(app, f)
}
/// Export each selected layer separately, with one destination prompt for the batch.
/// The chosen path names the first file; subsequent files have numbered sibling names.
/// Export each selected layer or group to its own PNG, named after the source.
pub fn quick_export_selected_layers_png(app: &mut PhotocraftApp) -> Result<Value, String> {
let st = app.session.active().ok_or("no document")?;
let layers = st.selected_layers();
@@ -393,28 +392,56 @@ pub fn quick_export_selected_layers_png(app: &mut PhotocraftApp) -> Result<Value
// Capture all sources before showing the dialog: changing selection or document while it
// is open cannot change which layers get exported.
let docs = exportable_layers(&st.doc, layers)?;
let suggested = format!("{}.png", export_name(&st.doc.name));
app.pick_export(&suggested, move |app, path| {
if !path.to_ascii_lowercase().ends_with(".png") {
return Err("Quick Export as PNG writes .png files".into());
}
let paths = batch_paths(&path, &docs);
let mut exported = Vec::new();
for (doc, path) in docs.iter().zip(paths) {
crate::app::ensure_memory_to_save(doc, &path)?;
let export = app.services.export.as_ref().ok_or("no exporter configured")?;
let (bytes, warnings) = export(doc, &path, &ExportSettings { xmp_all: false, ..Default::default() })?;
let write = app.services.write.as_mut().ok_or("no writer configured")?;
write(&path, &bytes)?;
crate::notices::io_warnings(app, &format!("Exported {}", crate::file_open::display_name(&path)), &warnings);
exported.push(json!({"path": path, "bytes": bytes.len(), "warnings": warnings}));
}
app.ui.status = format!("Exported {} PNG files", exported.len());
app.ui.status_error = false;
Ok(json!({"files": exported}))
if let [only] = docs.as_slice() {
let suggested = layer_export_suggestion(&only.name, "png");
return app.pick_export(&suggested, move |app, path| {
if !path.to_ascii_lowercase().ends_with(".png") {
return Err("Quick Export as PNG writes .png files".into());
}
write_quick_pngs(app, &docs, [path], false)
});
}
let names = layer_file_names(&docs, "png");
#[cfg(target_arch = "wasm32")]
return write_quick_pngs(app, &docs, names, false);
#[cfg(not(target_arch = "wasm32"))]
app.pick_export_folder(move |app, dir| {
let dir = std::path::Path::new(&dir);
// When a file already exists, a numbered alternative must also leave every other
// selected layer's name available. Resolve each path just before writing it so names
// the file system treats as aliases also get distinct destinations.
let reserved: std::collections::HashSet<_> = names.iter().flat_map(|name| [name.to_uppercase(), name.to_lowercase()]).collect();
let paths = names.iter().map(|name| {
let stem = name.strip_suffix(".png").unwrap_or(name);
unused_export_path(dir, stem, "png", |candidate| reserved.contains(&candidate.to_uppercase()) || reserved.contains(&candidate.to_lowercase()))
.to_string_lossy()
.into_owned()
});
write_quick_pngs(app, &docs, paths, true)
})
}
fn write_quick_pngs(app: &mut PhotocraftApp, docs: &[Document], paths: impl IntoIterator<Item = String>, new_files_only: bool) -> Result<Value, String> {
let mut exported = Vec::new();
for (doc, path) in docs.iter().zip(paths) {
crate::app::ensure_memory_to_save(doc, &path)?;
let export = app.services.export.as_ref().ok_or("no exporter configured")?;
let (bytes, warnings) = export(doc, &path, &ExportSettings { xmp_all: false, ..Default::default() })?;
// A file may have appeared at a generated path while the encoder was running.
let write = if new_files_only {
app.services.write_new.as_mut().ok_or("no exclusive export writer configured")?
} else {
app.services.write.as_mut().ok_or("no writer configured")?
};
write(&path, &bytes)?;
crate::notices::io_warnings(app, &format!("Exported {}", crate::file_open::display_name(&path)), &warnings);
exported.push(json!({"path": path, "bytes": bytes.len(), "warnings": warnings}));
}
app.ui.status = format!("Exported {} PNG files", exported.len());
app.ui.status_error = false;
Ok(json!({"files": exported}))
}
/// The first 80 characters of `name`, each control character and each character a file name
/// can't hold (`< > : " / \ | ? *`) turned into `_`.
fn file_name_chars(name: &str) -> String {
@@ -435,6 +462,26 @@ fn layer_export_name(name: &str) -> String {
if name.chars().all(|c| c.is_whitespace() || c == '.') { "layer".into() } else { name }
}
fn layer_export_suggestion(name: &str, ext: &str) -> String {
generated_export_name(&layer_export_name(&stem_of(name)), ext, None)
}
/// Leave room within a 255-byte filename component for the atomic writer's temporary suffix.
const MAX_GENERATED_EXPORT_NAME_BYTES: usize = 200;
fn generated_export_name(stem: &str, ext: &str, number: Option<u64>) -> String {
let suffix = number.map_or_else(String::new, |number| format!("-{number}"));
let limit = MAX_GENERATED_EXPORT_NAME_BYTES.saturating_sub(ext.len()).saturating_sub(1 + suffix.len());
let name_at = |limit| {
let stem = stem.get(..stem.floor_char_boundary(limit)).unwrap_or_default();
let stem = if stem.chars().all(|c| c.is_whitespace() || c == '.') { "layer" } else { stem };
photocraft_engine::file_cmds::portable_device_name(format!("{stem}{suffix}.{ext}"))
};
let name = name_at(limit);
// Truncation can expose a Windows device name. Its escape adds one byte.
if name.len() > MAX_GENERATED_EXPORT_NAME_BYTES { name_at(limit.saturating_sub(1)) } else { name }
}
/// The files a multi-layer export writes: the chosen path, then numbered siblings named after
/// each layer, in the chosen path's format.
fn batch_paths(path: &str, docs: &[Document]) -> Vec<String> {
@@ -448,27 +495,36 @@ fn batch_paths(path: &str, docs: &[Document]) -> Vec<String> {
if i == 0 {
return path.to_string();
}
let name = export_name(&doc.name);
let candidate = parent.join(format!("{stem}-{}-{name}.{ext}", i + 1));
let numbered = format!("{stem}-{}-{}", i + 1, export_name(&doc.name));
// The first file's overwrite is handled by the Save dialog; never overwrite sibling
// files silently on desktop. Downloads on the web are named by the browser.
#[cfg(not(target_arch = "wasm32"))]
let candidate = {
let mut candidate = candidate;
let mut suffix = 1u64;
// A name any entry occupies is taken, a symlink (even a dangling one) included: the writer
// follows links, so one planted here would redirect the export.
while candidate.symlink_metadata().is_ok() {
candidate = parent.join(format!("{stem}-{}-{name}-{suffix}.{ext}", i + 1));
suffix = suffix.saturating_add(1);
}
candidate
};
let candidate = unused_export_path(parent, &numbered, ext, |_| false);
#[cfg(target_arch = "wasm32")]
let candidate = parent.join(format!("{numbered}.{ext}"));
candidate.to_string_lossy().into_owned()
})
.collect()
}
/// Keep existing entries, including links (even dangling ones), when choosing an output path.
#[cfg(not(target_arch = "wasm32"))]
fn unused_export_path(dir: &std::path::Path, stem: &str, ext: &str, reserved: impl Fn(&str) -> bool) -> std::path::PathBuf {
let candidate = dir.join(generated_export_name(stem, ext, None));
if candidate.symlink_metadata().is_err() {
return candidate;
}
let mut suffix = 1u64;
loop {
let name = generated_export_name(stem, ext, Some(suffix));
let candidate = dir.join(&name);
if !reserved(&name) && candidate.symlink_metadata().is_err() {
return candidate;
}
suffix = suffix.saturating_add(1);
}
}
/// The document a dialog exports: the whole image, or one layer (`__layer`).
fn source_document_from(doc: Arc<Document>, f: &Map<String, Value>) -> Result<Arc<Document>, String> {
match f.get("__layer").and_then(Value::as_u64) {
@@ -1073,8 +1129,8 @@ fn export_to(app: &mut PhotocraftApp, f: &Map<String, Value>, path: &str) -> Res
/// A layer's name may hold characters a file name can't (#14810): `a/b:c*?` suggests `a_b_c__`.
fn pick_and_export(app: &mut PhotocraftApp, f: Map<String, Value>) -> Result<Value, String> {
let doc = source_document(app, &f)?;
let stem = if f.contains_key("__layer") { layer_export_name(&stem_of(&doc.name)) } else { stem_of(&doc.name) };
let suggested = format!("{stem}.{}", s_fmt(&f));
let ext = s_fmt(&f);
let suggested = if f.contains_key("__layer") { layer_export_suggestion(&doc.name, &ext) } else { format!("{}.{ext}", stem_of(&doc.name)) };
app.pick_export(&suggested, move |app, path| export_to(app, &f, &path))
}
@@ -1185,7 +1241,7 @@ pub(crate) fn replay(app: &mut PhotocraftApp, params: &Value) -> Result<Value, S
/// layers are skipped (#14806). With several files on the desktop `path` is the folder the dialog
/// asked for, and each layer is written there as `<layer name>.<ext>`, replacing a file of that
/// name (#14808). One file is written at `path`; the web downloads each file, the first under
/// `path` and the others named as Quick Export names a selection's files.
/// `path` and the others under numbered names derived from that filename and their layer names.
fn export_layers(app: &mut PhotocraftApp, f: &Map<String, Value>, ids: &[LayerId], path: &str) -> Result<Value, String> {
let st = app.session.active().ok_or("no document")?;
let source_profile = effective_source_profile(app, &st.doc);
@@ -1239,7 +1295,7 @@ fn write_layer_file(
/// can't hold becomes `_` (`a/b:c*?` → `a_b_c__`), spaces are kept.
fn layer_file_stem(name: &str) -> String {
let stem: String = name.chars().map(|c| if c.is_control() || "<>:\"/\\|?*".contains(c) { '_' } else { c }).collect();
if stem.chars().all(|c| c.is_whitespace() || c == '.') { "layer".into() } else { stem }
if stem.chars().all(|c| c.is_whitespace() || c == '.') { "layer".into() } else { photocraft_engine::file_cmds::portable_device_name(stem) }
}
/// The names several layers' files get, for `docs` in document order (bottom to top). Equal
@@ -1257,10 +1313,10 @@ fn layer_file_names(docs: &[Document], ext: &str) -> Vec<String> {
let mut names = vec![String::new(); docs.len()];
for (i, doc) in docs.iter().enumerate().rev() {
let stem = layer_file_stem(&doc.name);
let mut name = format!("{stem}.{ext}");
let mut name = generated_export_name(&stem, ext, None);
let mut n = 1u64;
while taken(&used, &name) {
name = format!("{stem}-{n}.{ext}");
name = generated_export_name(&stem, ext, Some(n));
n = n.saturating_add(1);
}
used.insert(name.to_uppercase());
@@ -70,9 +70,11 @@ fn answer(app: &mut PhotocraftApp, files: &ScriptedFiles, path: &std::path::Path
fn quick_export_skips_the_same_layers() {
let (mut app, l, written, files) = app();
*app.session.active_mut().unwrap().selection_mut() = vec![l.empty, l.red, l.adjustment, l.blue, l.gone];
app.services.write_new = app.services.write.take();
let out = tempfile::tempdir().unwrap();
quick_export_selected_layers_png(&mut app).unwrap();
answer(&mut app, &files, std::path::Path::new("quick.png"));
assert_eq!(*written.borrow(), ["quick.png", "quick-2-Blue.png"]);
answer(&mut app, &files, out.path());
assert_eq!(*written.borrow(), [out.path().join("Red.png").to_string_lossy(), out.path().join("Blue.png").to_string_lossy()]);
}
#[test]
@@ -89,6 +89,21 @@ mod planted_link {
request
}
#[test]
fn quick_export_uses_one_folder_and_names_each_file_after_its_layer() {
let out = tempfile::tempdir().unwrap();
let (mut app, ids, _, written, files) = app();
app.services.write_new = app.services.write.take();
app.session.restore_layer_selection(Some(ids[0]), &ids, None).unwrap();
quick_export_selected_layers_png(&mut app).unwrap();
assert_eq!(files.requests().last().unwrap().kind, craft::host::PickKind::Folder);
files.answer(Picked::Paths(vec![out.path().to_path_buf()])).unwrap();
app.poll_file_dialog();
let written = written.borrow();
let actual: Vec<_> = written.iter().map(|p| std::path::Path::new(p).file_name().unwrap().to_str().unwrap()).collect();
assert_eq!(actual, ["a_b_c__.png", "Dup-1.png", "Dup.png"]);
}
#[test]
fn a_planted_link_is_replaced_not_followed() {
let guard = tempfile::tempdir().unwrap();
@@ -5,25 +5,45 @@
//! export's `export_name`.
use super::*;
use craft::host::ScriptedFiles;
use craft::host::{PickKind, ScriptedFiles};
/// The file name Layer › Quick Export as PNG suggests for a layer named `name` (the Save dialog
/// stays open), and the whole save request as text.
fn suggested_for(name: &str) -> (String, String) {
suggested_for_selection(name, false)
}
fn suggested_for_selection(name: &str, include_empty: bool) -> (String, String) {
let files = Arc::new(ScriptedFiles::held());
let services = crate::Services { files: Some(files.clone()), ..Default::default() };
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services);
app.run("file.new", json!({"width": 20, "height": 20})).unwrap();
app.run("layer.new.layer", json!({"name": "Empty"})).unwrap();
let empty = app.session.active().unwrap().active_layer.unwrap();
app.run("layer.new.layer", json!({"name": name})).unwrap();
app.run("select.rect", json!({"x": 2, "y": 2, "width": 6, "height": 6})).unwrap();
app.run("edit.fill", json!({"color": "#ff0000"})).unwrap();
let layer = app.session.active().unwrap().active_layer.unwrap();
quick_export_layer_png(&mut app, layer).unwrap();
if include_empty {
app.session.restore_layer_selection(Some(layer), &[empty, layer], None).unwrap();
}
crate::menus::invoke(&mut app, &egui::Context::default(), "layer.quickExportAsPng", Value::Null).unwrap();
let asked = files.requests();
let [request] = asked.as_slice() else { panic!("one Save dialog: {asked:?}") };
assert_eq!(request.kind, PickKind::Save);
(request.file_name.clone().unwrap_or_default(), format!("{request:?}"))
}
#[test]
fn quick_export_suggests_the_same_name_when_an_empty_layer_is_selected() {
for name in ["Hero.v2", "a/b:c*?", "CON", &"界".repeat(100)] {
let (single, _) = suggested_for(name);
let (with_empty, _) = suggested_for_selection(name, true);
assert_eq!(with_empty, single, "{name:?}");
assert!(single.len() <= MAX_GENERATED_EXPORT_NAME_BYTES);
}
}
#[test]
fn a_layer_named_with_illegal_characters_suggests_underscores() {
let (file, path) = suggested_for("a/b:c*?");
+28
View File
@@ -241,6 +241,34 @@ impl PhotocraftApp {
self.pick_save_in(suggested, true, None, then)
}
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn pick_export_folder(&mut self, then: impl FnOnce(&mut Self, String) -> Result<Value, String> + 'static) -> Result<Value, String> {
let doc = self.session.active();
let document_dir = doc.and_then(|st| {
self.save_dirs
.get(&st.doc.id)
.filter(|dir| folder_exists(dir))
.cloned()
.or_else(|| st.path.as_deref().and_then(|p| Path::new(p).parent()).map(Path::to_path_buf))
});
let doc = doc.map(|st| st.doc.id);
let mut request = PickRequest::folder("export");
if let Some(dir) = export_start_dir(Some(&self.session.prefs().export.last_folder), document_dir, folder_exists) {
request = request.directory(dir);
}
self.ask_file(request, move |app, picked| {
let path = path_strings(&picked).into_iter().next().ok_or(UNEXPECTED)?;
let exported = then(app, path.clone())?;
if let Some(doc) = doc
&& app.session.documents().iter().any(|st| st.doc.id == doc)
{
app.save_dirs.insert(doc, PathBuf::from(&path));
}
app.session.prefs.edit(|prefs| prefs.export.last_folder = path);
Ok(exported)
})
}
fn pick_save_in(
&mut self,
suggested: &str,
+6 -3
View File
@@ -910,6 +910,8 @@ fn convert_to_linked_asks_where_to_write_the_contents() {
#[test]
fn quick_export_selected_layers_writes_separate_pngs_with_one_prompt() {
let (mut app, files, written) = app();
app.services.write_new = app.services.write.take();
let out = tempfile::tempdir().unwrap();
app.run("layer.new.layer", json!({"name": "Same/name"})).unwrap();
app.run("paint.bucket", json!({"x": 0, "y": 0, "color": "#ff0000"})).unwrap();
app.run("layer.new.layer", json!({"name": "Same/name"})).unwrap();
@@ -932,12 +934,13 @@ fn quick_export_selected_layers_writes_separate_pngs_with_one_prompt() {
assert_eq!(files.requests().len(), 1, "one destination for the entire selection");
// Selection changes while choosing a destination must not change the captured sources.
app.run("layer.select", json!({"layer": selected[0].0})).unwrap();
answer(&files, chose("selected.png"));
assert_eq!(files.requests()[0].kind, craft::host::PickKind::Folder);
answer(&files, Picked::Paths(vec![out.path().to_path_buf()]));
app.poll_file_dialog();
assert_eq!(written.borrow().len(), selected.len());
assert_eq!(sources.borrow().len(), selected.len());
assert_eq!(written.borrow()[0], "selected.png");
assert_eq!(written.borrow()[1], "selected-2-Same_name.png");
assert_eq!(written.borrow()[0], out.path().join("Same_name-1.png").to_string_lossy());
assert_eq!(written.borrow()[1], out.path().join("Same_name.png").to_string_lossy());
assert_eq!(selected.len(), 2, "Select All Layers leaves the locked Background out");
assert_eq!(app.session.active().unwrap().doc, before);
assert!(!app.ui.status_error, "{}", app.ui.status);
+2
View File
@@ -540,6 +540,8 @@ pub struct Services {
pub file_dialog: Option<FileDialogFn>,
/// Write bytes to a path (native) or trigger a download (web).
pub write: Option<WriteFn>,
/// Publish a new file on the desktop, leaving any occupied destination intact.
pub write_new: Option<WriteFn>,
/// Size and modification time of a file (native); `None` on the web, where Save never
/// writes back to a file.
pub file_stamp: Option<FileStampFn>,
+6 -3
View File
@@ -813,9 +813,12 @@ else}` is Photoshop's Insert Conditional as a step: it tests the document or act
(`always`, `landscape`, `modeIsRGB`, `hasLayers`, `isBackground`, `hasPixelMask`… see its params)
and plays the matching action by name, failing the caller when that action fails.
Layer-panel **Quick Export as PNG** exports every selected layer as a separate PNG. A single
Save dialog chooses the first filename; remaining files are numbered siblings with sanitized
layer names. Selection is captured before opening the dialog; an unselected layer is excluded.
Layer-panel **Quick Export as PNG** exports each selected layer or group with exportable pixels
as a separate PNG. Each PNG uses its source name with unsafe filename characters replaced.
For several outputs, desktop asks for one folder and the web downloads each file. Duplicate
names get numbered alternatives, as do occupied filenames on desktop. A single output uses
a Save dialog that lets you confirm replacing an existing file.
Multiple selected sources are captured before opening the picker.
## Shared panel docking