Skip to content

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

Layer › Export As exports every selected layer or artboard (#3629) (#3909)

Fabian Ghenof83f4452bf2dc
diff --git a/crates/ui-egui/src/export_dialog.rs b/crates/ui-egui/src/export_dialog.rs
index b16fbc31a..cd520d5c3 100644
--- a/crates/ui-egui/src/export_dialog.rs
+++ b/crates/ui-egui/src/export_dialog.rs
@@ -44,6 +44,23 @@ pub fn open_layer(app: &mut PhotocraftApp, layer: photocraft_doc::LayerId) -> Re
Ok(id)
}
+/// Layer › Export As… with several layers (artboards, say) selected: the same dialog, then one
+/// file per layer with its settings (#3629). The preview shows the first layer.
+pub fn open_layers(app: &mut PhotocraftApp, layers: &[photocraft_doc::LayerId]) -> Result<u64, String> {
+ let (first, n) = match layers {
+ [] => return Err("no selected layers".into()),
+ [one] => return open_layer(app, *one),
+ [first, ..] => (*first, layers.len()),
+ };
+ let id = open_layer(app, first)?;
+ if let Some(d) = app.ui.dialogs.iter_mut().find(|d| d.id == id) {
+ d.fields.insert("__layers".into(), json!(layers.iter().map(|l| l.0).collect::<Vec<_>>()));
+ let template = "Export As: {n} layers";
+ d.fields.insert("__label".into(), json!(crate::i18n::fmt(tl!(template), &[("n", &n.to_string())])));
+ }
+ Ok(id)
+}
+
/// Layer › Quick Export as PNG.
pub fn quick_export_layer_png(app: &mut PhotocraftApp, layer: photocraft_doc::LayerId) -> Result<Value, String> {
let mut f = Map::new();
@@ -96,10 +113,13 @@ fn export_name(name: &str) -> String {
if name.is_empty() { "layer".into() } else { name.into() }
}
+/// 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> {
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");
+ let ext = first.extension().and_then(|e| e.to_str()).unwrap_or("png");
docs.iter()
.enumerate()
.map(|(i, doc)| {
@@ -107,7 +127,7 @@ fn batch_paths(path: &str, docs: &[Document]) -> Vec<String> {
return path.to_string();
}
let name = export_name(&doc.name);
- let candidate = parent.join(format!("{stem}-{}-{name}.png", i + 1));
+ let candidate = parent.join(format!("{stem}-{}-{name}.{ext}", 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"))]
@@ -115,7 +135,7 @@ fn batch_paths(path: &str, docs: &[Document]) -> Vec<String> {
let mut candidate = candidate;
let mut suffix = 1u64;
while candidate.exists() {
- candidate = parent.join(format!("{stem}-{}-{name}-{suffix}.png", i + 1));
+ candidate = parent.join(format!("{stem}-{}-{name}-{suffix}.{ext}", i + 1));
suffix = suffix.saturating_add(1);
}
candidate
@@ -335,6 +355,10 @@ pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<String, Valu
/// Export with the dialog's settings: choose a path, render, encode, write.
pub fn confirm(app: &mut PhotocraftApp, f: &Map<String, Value>) -> Result<Value, String> {
+ if let Some(layers) = f.get("__layers").and_then(Value::as_array) {
+ let ids: Vec<_> = layers.iter().filter_map(Value::as_u64).map(photocraft_doc::LayerId).collect();
+ return confirm_layers(app, f, &ids);
+ }
let doc = source_document(app, f)?;
let stem = doc.name.rsplit_once('.').map_or(doc.name.as_str(), |(a, _)| a).to_string();
let ext = s_fmt(f);
@@ -356,6 +380,39 @@ pub fn confirm(app: &mut PhotocraftApp, f: &Map<String, Value>) -> Result<Value,
})
}
+/// [`confirm`] for several layers: one destination prompt, then each layer exported with the
+/// dialog's settings and named as Quick Export names a selection's files. The layers are captured
+/// when asked, so changing the selection or document meanwhile can't change what is exported.
+fn confirm_layers(app: &mut PhotocraftApp, f: &Map<String, Value>, ids: &[photocraft_doc::LayerId]) -> Result<Value, String> {
+ let st = app.session.active().ok_or("no document")?;
+ let docs: Vec<Document> =
+ ids.iter().map(|id| photocraft_engine::layer_menu_cmds::layer_document(&st.doc, *id).map_err(|e| e.to_string())).collect::<Result<_, _>>()?;
+ if docs.is_empty() {
+ return Err("no selected layers".into());
+ }
+ let stem = st.doc.name.rsplit_once('.').map_or(st.doc.name.as_str(), |(a, _)| a);
+ let suggested = format!("{}.{}", export_name(stem), s_fmt(f));
+ let (f, settings) = (f.clone(), settings(f));
+ app.pick_save(&suggested, move |app, path| {
+ let mut exported = Vec::new();
+ for (doc, path) in docs.iter().zip(batch_paths(&path, &docs)) {
+ let out = export_document(doc, &f, None)?;
+ let export = app.services.export.as_ref().ok_or("no exporter configured")?;
+ let (bytes, warnings) = export(&out, &path, &settings)?;
+ let write = app.services.write.as_mut().ok_or("no writer configured")?;
+ write(&path, &bytes)?;
+ let template = "Exported {path}";
+ let what = crate::i18n::fmt(tl!(template), &[("path", &crate::file_open::display_name(&path))]);
+ crate::notices::io_warnings(app, &what, &warnings);
+ exported.push(json!({"path": path, "bytes": bytes.len(), "warnings": warnings}));
+ }
+ let template = "Exported {n} files";
+ app.ui.status = crate::i18n::fmt(tl!(template), &[("n", &exported.len().to_string())]);
+ app.ui.status_error = false;
+ Ok(json!({"files": exported}))
+ })
+}
+
/// File › Export › Quick Export as PNG: the format, quality, metadata, colour space and location
/// from File › Export › Export Preferences (engine `file.export.quickExport`). On the web (no
/// file system) it falls back to a PNG download through the export service.
diff --git a/crates/ui-egui/src/file_dialog/tests.rs b/crates/ui-egui/src/file_dialog/tests.rs
index e985a486c..3081de03f 100644
--- a/crates/ui-egui/src/file_dialog/tests.rs
+++ b/crates/ui-egui/src/file_dialog/tests.rs
@@ -685,3 +685,42 @@ fn an_unavailable_dialog_is_reported_and_a_cancelled_one_is_not() {
assert_eq!(app.ui.status, "No file dialog can open");
assert!(!app.file_dialog_open(), "the pending dialog is over");
}
+
+/// #3629: Layer › Export As with several artboards selected exports one file per board, at each
+/// board's size and with the dialog's settings, after one destination prompt.
+#[test]
+fn export_as_with_several_artboards_selected_writes_one_file_each() {
+ let (mut app, open, written) = app();
+ let a = app.run("layer.new.artboard", json!({"rect": [0, 0, 40, 30], "name": "Header"})).unwrap()["layer"].as_u64().unwrap();
+ let b = app.run("layer.new.artboard", json!({"rect": [60, 0, 20, 50], "name": "Capsule"})).unwrap()["layer"].as_u64().unwrap();
+ app.run("layer.select", json!({"layer": a})).unwrap();
+ app.run("layer.select", json!({"layer": b, "mode": "add"})).unwrap();
+ assert_eq!(app.session.active().unwrap().selected_layers().len(), 2);
+ let sizes = Rc::new(RefCell::new(Vec::new()));
+ let capture = sizes.clone();
+ app.services.export = Some(Box::new(move |doc: &photocraft_doc::Document, _: &str, _: &crate::ExportSettings| {
+ capture.borrow_mut().push((doc.name.clone(), doc.size.width, doc.size.height));
+ Ok((b"out".to_vec(), Vec::new()))
+ }));
+ assert!(!crate::layer_menu_ui::single_layer_only("layer.exportAs"), "the menu offers it for a selection");
+ let ctx = egui::Context::default();
+ let r = menus::invoke(&mut app, &ctx, "layer.exportAs", Value::Null).unwrap();
+ let id = r["dialog"].as_u64().unwrap();
+ let mut fields = app.ui.dialogs.iter().find(|d| d.id == id).unwrap().fields.clone();
+ assert_eq!(fields["__label"], "Export As: 2 layers");
+ // The dialog's settings apply to every file: JPG at 50 %.
+ fields.insert("format".into(), json!("jpg"));
+ fields.insert("scale".into(), json!(50));
+ crate::export_dialog::confirm(&mut app, &fields).unwrap();
+ app.poll_file_dialog(&ctx, None);
+ assert_eq!(open.borrow().len(), 1, "one destination for every board");
+ answer(&open, Some(FileDialogAnswer::SaveTo("/out/boards.jpg".into())));
+ app.poll_file_dialog(&ctx, None);
+ assert!(!app.ui.status_error, "{}", app.ui.status);
+ assert_eq!(written.borrow().len(), 2);
+ assert_eq!(written.borrow()[0], "/out/boards.jpg");
+ assert!(written.borrow()[1].starts_with("/out/boards-2-") && written.borrow()[1].ends_with(".jpg"), "{:?}", written.borrow());
+ let mut got = sizes.borrow().iter().map(|(_, w, h)| (*w, *h)).collect::<Vec<_>>();
+ got.sort_unstable();
+ assert_eq!(got, [(10, 25), (20, 15)], "each board at its own size, scaled to 50 %");
+}
diff --git a/crates/ui-egui/src/layer_menu_ui.rs b/crates/ui-egui/src/layer_menu_ui.rs
index 10629f254..fa70e436b 100644
--- a/crates/ui-egui/src/layer_menu_ui.rs
+++ b/crates/ui-egui/src/layer_menu_ui.rs
@@ -40,14 +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?), 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.
+/// Options (one dialog), Copy Layer Style (copy from which layer?) 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, Rasterize and
+/// Export As (one file per layer, #3629) 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.exportAs")
- || (id.starts_with("layer.layerMask.") && !adds_mask)
+ matches!(id, "layer.layerStyle.blendingOptions" | "layer.layerStyle.copyLayerStyle") || (id.starts_with("layer.layerMask.") && !adds_mask)
}
/// The context menu entries for a layer (Photoshop 2026 order, trimmed to the layer kind).
@@ -567,11 +566,12 @@ 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", "Export As…"] {
+ for label in ["Blending Options…", "Copy Layer Style"] {
assert!(h.get_by_label(label).accesskit_node().is_disabled(), "{label} works on one layer only");
}
for label in [
"Quick Export As PNG",
+ "Export As…",
"Add Layer Mask",
"Duplicate Layers…",
"Delete Layers",
@@ -602,12 +602,12 @@ mod tests {
"layer.layerMask.enabled",
"layer.layerMask.apply",
"layer.layerMask.delete",
- "layer.exportAs",
] {
assert!(single_layer_only(id), "{id}");
}
for id in [
"layer.quickExportAsPng",
+ "layer.exportAs",
"layer.duplicate",
"layer.delete",
"layer.rasterize.layer",
diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs
index b5b72e93a..4e6c9ba18 100644
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@ -396,6 +396,11 @@ pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id:
l if matches!(l, "layer.exportAs" | "layer.quickExportAsPng") && params.as_object().is_none_or(|o| o.is_empty()) => {
let layer = app.session.active().and_then(|d| d.active_layer).ok_or("no active layer")?;
if l == "layer.exportAs" {
+ // Several layers (artboards, say) selected: one file each (#3629).
+ let layers = app.session.active().map(|d| d.selected_layers()).unwrap_or_default();
+ if layers.len() > 1 {
+ return Ok(json!({"dialog": crate::export_dialog::open_layers(app, &layers)?}));
+ }
Ok(json!({"dialog": crate::export_dialog::open_layer(app, layer)?}))
} else {
crate::export_dialog::quick_export_selected_layers_png(app)