Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

fix(export): quick-export every selected layer as a separate PNG (#3462)

kotulskycc772a03c1a6
diff --git a/crates/ui-egui/src/export_dialog.rs b/crates/ui-egui/src/export_dialog.rs
index 67d21b6f5..b16fbc31a 100644
--- a/crates/ui-egui/src/export_dialog.rs
+++ b/crates/ui-egui/src/export_dialog.rs
@@ -54,6 +54,77 @@ pub fn quick_export_layer_png(app: &mut PhotocraftApp, layer: photocraft_doc::La
confirm(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.
+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();
+ if layers.len() == 1 {
+ return quick_export_layer_png(app, layers[0]);
+ }
+ if layers.is_empty() {
+ return Err("no selected layers".into());
+ }
+ // Capture all sources before showing the dialog: changing selection or document while it
+ // is open cannot change which layers get exported.
+ let docs: Vec<_> =
+ layers.into_iter().map(|id| photocraft_engine::layer_menu_cmds::layer_document(&st.doc, id).map_err(|e| e.to_string())).collect::<Result<_, _>>()?;
+ let suggested = format!("{}.png", export_name(&st.doc.name));
+ app.pick_save(&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) {
+ 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}))
+ })
+}
+
+fn export_name(name: &str) -> String {
+ let name: String = name.chars().take(80).map(|c| if c.is_control() || "<>:\"/\\|?*".contains(c) { '_' } else { c }).collect();
+ let name = name.trim().trim_matches('.');
+ if name.is_empty() { "layer".into() } else { name.into() }
+}
+
+fn batch_paths(path: &str, docs: &[Document]) -> Vec<String> {
+ let first = std::path::Path::new(path);
+ let parent = first.parent().unwrap_or_else(|| std::path::Path::new(""));
+ let stem = first.file_stem().and_then(|s| s.to_str()).unwrap_or("layers");
+ docs.iter()
+ .enumerate()
+ .map(|(i, doc)| {
+ if i == 0 {
+ return path.to_string();
+ }
+ let name = export_name(&doc.name);
+ let candidate = parent.join(format!("{stem}-{}-{name}.png", i + 1));
+ // 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;
+ while candidate.exists() {
+ candidate = parent.join(format!("{stem}-{}-{name}-{suffix}.png", i + 1));
+ suffix = suffix.saturating_add(1);
+ }
+ candidate
+ };
+ candidate.to_string_lossy().into_owned()
+ })
+ .collect()
+}
+
/// The document a dialog exports: the whole image, or one layer (`__layer`).
fn source_document(app: &PhotocraftApp, f: &Map<String, Value>) -> Result<Arc<Document>, String> {
let st = app.session.active().ok_or("no document")?;
diff --git a/crates/ui-egui/src/file_dialog/tests.rs b/crates/ui-egui/src/file_dialog/tests.rs
index d166d89a8..59c8c4973 100644
--- a/crates/ui-egui/src/file_dialog/tests.rs
+++ b/crates/ui-egui/src/file_dialog/tests.rs
@@ -587,6 +587,59 @@ 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, open, written) = app();
+ 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();
+ app.run("paint.bucket", json!({"x": 0, "y": 0, "color": "#00ff00"})).unwrap();
+ app.run("select.allLayers", json!({})).unwrap();
+ let selected = app.session.active().unwrap().selected_layers();
+ let before = app.session.active().unwrap().doc.clone();
+ let sources = Rc::new(RefCell::new(Vec::new()));
+ let capture = sources.clone();
+ app.services.export = Some(Box::new(move |doc, path, _| {
+ assert_eq!(doc.layers.len(), 1, "each PNG must contain just its source layer");
+ let png = photocraft_io::export(doc, path, &Default::default()).unwrap();
+ assert!(png.bytes.starts_with(b"\x89PNG\r\n\x1a\n"));
+ capture.borrow_mut().push(doc.name.clone());
+ Ok((png.bytes, Vec::new()))
+ }));
+ let ctx = egui::Context::default();
+ assert!(!crate::layer_menu_ui::single_layer_only("layer.quickExportAsPng"));
+ menus::invoke(&mut app, &ctx, "layer.quickExportAsPng", Value::Null).unwrap();
+ app.poll_file_dialog(&ctx, None);
+ assert_eq!(open.borrow().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(&open, Some(FileDialogAnswer::SaveTo("selected.png".into())));
+ app.poll_file_dialog(&ctx, None);
+ 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!(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);
+}
+
+#[test]
+fn cancelling_multi_layer_quick_export_writes_nothing() {
+ let (mut app, open, written) = app();
+ for color in ["#ff0000", "#00ff00"] {
+ app.run("layer.new.layer", json!({})).unwrap();
+ app.run("paint.bucket", json!({"x": 0, "y": 0, "color": color})).unwrap();
+ }
+ app.run("select.allLayers", json!({})).unwrap();
+ let ctx = egui::Context::default();
+ menus::invoke(&mut app, &ctx, "layer.quickExportAsPng", Value::Null).unwrap();
+ app.poll_file_dialog(&ctx, None);
+ answer(&open, None);
+ app.poll_file_dialog(&ctx, None);
+ assert!(written.borrow().is_empty());
+}
+
/// #3354: a system with no dialog backend answers `Unavailable`; the message reaches the status
/// bar as an error, where a cancelled dialog stays silent.
#[test]
diff --git a/crates/ui-egui/src/layer_menu_ui.rs b/crates/ui-egui/src/layer_menu_ui.rs
index 12e220930..da0e1608d 100644
--- a/crates/ui-egui/src/layer_menu_ui.rs
+++ b/crates/ui-egui/src/layer_menu_ui.rs
@@ -40,13 +40,13 @@ pub fn mask_button_command(layer: Option<&Layer>, has_selection: bool, alt: bool
}
/// Commands that act on the active layer only and have no sensible meaning for a selection: Blending
-/// Options (one dialog), Copy Layer Style (copy from which layer?), the exports, and the per-layer
+/// Options (one dialog), Copy Layer Style (copy from which layer?), Export As, and the per-layer
/// mask items. With several layers selected they would hit whichever layer is active, not the one
/// that was right-clicked, so the menu greys them. Adding a mask, Paste/Clear Layer Style and
/// Rasterize run on every selected layer instead.
pub fn single_layer_only(id: &str) -> bool {
let adds_mask = matches!(id, "layer.layerMask.revealAll" | "layer.layerMask.hideAll" | "layer.layerMask.revealSelection" | "layer.layerMask.hideSelection");
- matches!(id, "layer.layerStyle.blendingOptions" | "layer.layerStyle.copyLayerStyle" | "layer.quickExportAsPng" | "layer.exportAs")
+ matches!(id, "layer.layerStyle.blendingOptions" | "layer.layerStyle.copyLayerStyle" | "layer.exportAs")
|| (id.starts_with("layer.layerMask.") && !adds_mask)
}
@@ -567,10 +567,19 @@ mod tests {
fn multi_selection_menu_greys_what_acts_on_one_layer() {
use egui_kittest::kittest::{NodeT, Queryable};
let (h, _) = open_multi_selection_menu();
- for label in ["Blending Options…", "Copy Layer Style", "Quick Export As PNG", "Export As…"] {
+ for label in ["Blending Options…", "Copy Layer Style", "Export As…"] {
assert!(h.get_by_label(label).accesskit_node().is_disabled(), "{label} works on one layer only");
}
- for label in ["Add Layer Mask", "Duplicate Layers…", "Delete Layers", "Convert to Smart Object", "Rasterize Layers", "Link Layers", "Merge Layers"] {
+ for label in [
+ "Quick Export As PNG",
+ "Add Layer Mask",
+ "Duplicate Layers…",
+ "Delete Layers",
+ "Convert to Smart Object",
+ "Rasterize Layers",
+ "Link Layers",
+ "Merge Layers",
+ ] {
assert!(!h.get_by_label(label).accesskit_node().is_disabled(), "{label} acts on the selection");
}
// Greyed here only for lack of something to act on: no style on the clipboard, no style to clear.
@@ -593,12 +602,12 @@ mod tests {
"layer.layerMask.enabled",
"layer.layerMask.apply",
"layer.layerMask.delete",
- "layer.quickExportAsPng",
"layer.exportAs",
] {
assert!(single_layer_only(id), "{id}");
}
for id in [
+ "layer.quickExportAsPng",
"layer.duplicate",
"layer.delete",
"layer.rasterize.layer",
diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs
index 690069daa..509284dd8 100644
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@ -394,7 +394,7 @@ pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id:
if l == "layer.exportAs" {
Ok(json!({"dialog": crate::export_dialog::open_layer(app, layer)?}))
} else {
- crate::export_dialog::quick_export_layer_png(app, layer)
+ crate::export_dialog::quick_export_selected_layers_png(app)
}
}
"layer.layerStyle.blendingOptions" if params.as_object().is_none_or(|o| o.is_empty()) => {
diff --git a/docs/control-protocol.md b/docs/control-protocol.md
index 4ee966801..429c67cea 100644
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@ -511,6 +511,10 @@ the parent before its next step. Every nested command retains the normal automat
Existing recordings containing expanded commands remain unchanged; remove those steps and record
the named call again if desired.
+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.
+
## Shared panel docking
Panel arrangements support tab grouping and reordering, horizontal and vertical splits,