diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rs index 045c31def3..12817dcb2d 100644 --- a/apps/photocraft/src/services.rs +++ b/apps/photocraft/src/services.rs @@ -101,8 +101,8 @@ fn recovery_dir() -> Option { } /// 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, 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()?; diff --git a/crates/ui-egui/src/dialogs/export_dialog.rs b/crates/ui-egui/src/dialogs/export_dialog.rs index 9aac59ac13..8ce51d3d4d 100644 --- a/crates/ui-egui/src/dialogs/export_dialog.rs +++ b/crates/ui-egui/src/dialogs/export_dialog.rs @@ -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 { 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 = 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, new_files_only: bool) -> Result { + 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) -> 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 { @@ -448,27 +495,36 @@ fn batch_paths(path: &str, docs: &[Document]) -> Vec { 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, f: &Map) -> Result, String> { match f.get("__layer").and_then(Value::as_u64) { @@ -1073,8 +1129,8 @@ fn export_to(app: &mut PhotocraftApp, f: &Map, 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) -> Result { 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.`, 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, ids: &[LayerId], path: &str) -> Result { 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 { 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()); diff --git a/crates/ui-egui/src/dialogs/export_dialog/layer_empty_skip_tests.rs b/crates/ui-egui/src/dialogs/export_dialog/layer_empty_skip_tests.rs index 4eaea2e4c3..89e2e91690 100644 --- a/crates/ui-egui/src/dialogs/export_dialog/layer_empty_skip_tests.rs +++ b/crates/ui-egui/src/dialogs/export_dialog/layer_empty_skip_tests.rs @@ -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] diff --git a/crates/ui-egui/src/dialogs/export_dialog/layer_folder_export_tests.rs b/crates/ui-egui/src/dialogs/export_dialog/layer_folder_export_tests.rs index 652adf18c6..96ed42d2c5 100644 --- a/crates/ui-egui/src/dialogs/export_dialog/layer_folder_export_tests.rs +++ b/crates/ui-egui/src/dialogs/export_dialog/layer_folder_export_tests.rs @@ -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(); diff --git a/crates/ui-egui/src/dialogs/export_dialog/layer_name_sanitise_tests.rs b/crates/ui-egui/src/dialogs/export_dialog/layer_name_sanitise_tests.rs index d7006361fc..f4ceaad0c2 100644 --- a/crates/ui-egui/src/dialogs/export_dialog/layer_name_sanitise_tests.rs +++ b/crates/ui-egui/src/dialogs/export_dialog/layer_name_sanitise_tests.rs @@ -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*?"); diff --git a/crates/ui-egui/src/file_dialog.rs b/crates/ui-egui/src/file_dialog.rs index f418ef3923..3caea64f8e 100644 --- a/crates/ui-egui/src/file_dialog.rs +++ b/crates/ui-egui/src/file_dialog.rs @@ -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 + 'static) -> Result { + 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, diff --git a/crates/ui-egui/src/file_dialog/tests.rs b/crates/ui-egui/src/file_dialog/tests.rs index 11edd5f050..3e854efbd2 100644 --- a/crates/ui-egui/src/file_dialog/tests.rs +++ b/crates/ui-egui/src/file_dialog/tests.rs @@ -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); diff --git a/crates/ui-egui/src/services.rs b/crates/ui-egui/src/services.rs index 90fbd74f2a..9e621dd6f5 100644 --- a/crates/ui-egui/src/services.rs +++ b/crates/ui-egui/src/services.rs @@ -540,6 +540,8 @@ pub struct Services { pub file_dialog: Option, /// Write bytes to a path (native) or trigger a download (web). pub write: Option, + /// Publish a new file on the desktop, leaving any occupied destination intact. + pub write_new: Option, /// Size and modification time of a file (native); `None` on the web, where Save never /// writes back to a file. pub file_stamp: Option, diff --git a/docs/control-protocol.md b/docs/control-protocol.md index a3a766a182..b815713606 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -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