From 82845589f562c39e37d909fc6864f21f9c39345e Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sat, 14 Nov 2026 22:31:18 -0600 Subject: [PATCH 1/6] Layer export: skip empty, adjustment and off-canvas layers instead of failing (#14806) --- crates/engine/src/cmd/layer_menu_cmds.rs | 12 +- crates/ui-egui/src/dialogs/export_dialog.rs | 43 +++++-- .../export_dialog/layer_empty_skip_tests.rs | 115 ++++++++++++++++++ 3 files changed, 161 insertions(+), 9 deletions(-) create mode 100644 crates/ui-egui/src/dialogs/export_dialog/layer_empty_skip_tests.rs diff --git a/crates/engine/src/cmd/layer_menu_cmds.rs b/crates/engine/src/cmd/layer_menu_cmds.rs index 58f253bb68..f215779ea8 100644 --- a/crates/engine/src/cmd/layer_menu_cmds.rs +++ b/crates/engine/src/cmd/layer_menu_cmds.rs @@ -932,6 +932,16 @@ fn content_options(s: &mut Session, _: &Value) -> Result { /// The layer rendered alone (visible, its blend mode ignored) and trimmed to its pixels, as a /// one-layer document — what Export As does for a layer. +/// The error [`layer_document`] gives for a layer with nothing on the canvas: an empty pixel +/// layer, an adjustment layer, a layer entirely off the canvas. +const EMPTY_LAYER: &str = "the layer is empty"; + +/// Whether `e` is [`layer_document`]'s error for a layer with nothing on the canvas, which a +/// several-layer export skips (#14806), rather than a real failure. +pub fn is_empty_layer(e: &EngineError) -> bool { + matches!(e, EngineError::Other(msg) if msg == EMPTY_LAYER) +} + pub fn layer_document(doc: &Document, id: LayerId) -> Result { let l = doc.layer(id).ok_or(EngineError::NoLayer(id))?; let mut alone = l.clone(); @@ -952,7 +962,7 @@ pub fn layer_document(doc: &Document, id: LayerId) -> Result { } } if b.is_empty() { - return Err(other("the layer is empty")); + return Err(other(EMPTY_LAYER)); } let fmt = doc.pixel_format(); let mut out = Document::new(l.name.clone(), photocraft_doc::Size::new(b.width(), b.height()), doc.mode, doc.depth); diff --git a/crates/ui-egui/src/dialogs/export_dialog.rs b/crates/ui-egui/src/dialogs/export_dialog.rs index 34ade9aedb..ed6c94aa57 100644 --- a/crates/ui-egui/src/dialogs/export_dialog.rs +++ b/crates/ui-egui/src/dialogs/export_dialog.rs @@ -176,12 +176,16 @@ pub fn open_layer(app: &mut PhotocraftApp, layer: photocraft_doc::LayerId) -> Re /// 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 { - let (first, n) = match layers { + let n = match layers { [] => return Err("no selected layers".into()), [one] => return open_layer(app, *one), - [first, ..] => (*first, layers.len()), + _ => layers.len(), }; - let id = open_layer(app, first)?; + // The dialog opens on the first layer with pixels: an empty, adjustment or off-canvas layer + // at the bottom of the selection no longer stops it (#14806). + let st = app.session.active().ok_or("no document")?; + let first = layers.iter().copied().find(|id| photocraft_engine::layer_menu_cmds::layer_document(&st.doc, *id).is_ok()); + let id = open_layer(app, first.ok_or_else(|| tl!(NO_VALID_ASSET).to_string())?)?; 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::>())); let template = "Export As: {n} layers"; @@ -190,6 +194,31 @@ pub fn open_layers(app: &mut PhotocraftApp, layers: &[photocraft_doc::LayerId]) Ok(id) } +/// What a several-layer export says when no selected layer has pixels, as in the reference +/// application. +const NO_VALID_ASSET: &str = "No valid asset to export. Please resolve any warnings and try again."; + +/// The export documents of the selected `ids` that have pixels on the canvas, in order. Empty, +/// adjustment and off-canvas layers are skipped (#14806); any other failure is still an error, +/// and so is a selection with nothing left to export. +fn exportable_layers(doc: &Document, ids: &[photocraft_doc::LayerId]) -> Result, String> { + let mut docs = Vec::new(); + for id in ids { + match photocraft_engine::layer_menu_cmds::layer_document(doc, *id) { + Ok(d) => docs.push(d), + Err(e) if photocraft_engine::layer_menu_cmds::is_empty_layer(&e) => {} + Err(e) => return Err(e.to_string()), + } + } + if docs.is_empty() { + return Err(tl!(NO_VALID_ASSET).into()); + } + Ok(docs) +} + +#[cfg(test)] +mod layer_empty_skip_tests; + /// Layer › Quick Export as PNG. pub fn quick_export_layer_png(app: &mut PhotocraftApp, layer: photocraft_doc::LayerId) -> Result { let mut f = Map::new(); @@ -213,8 +242,7 @@ pub fn quick_export_selected_layers_png(app: &mut PhotocraftApp) -> Result = - layers.into_iter().map(|id| photocraft_engine::layer_menu_cmds::layer_document(&st.doc, id).map_err(|e| e.to_string())).collect::>()?; + 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") { @@ -1113,11 +1141,10 @@ pub(crate) fn replay(app: &mut PhotocraftApp, params: &Value) -> Result, ids: &[photocraft_doc::LayerId]) -> Result { let st = app.session.active().ok_or("no document")?; let source_profile = effective_source_profile(app, &st.doc); - let docs: Vec = - ids.iter().map(|id| photocraft_engine::layer_menu_cmds::layer_document(&st.doc, *id).map_err(|e| e.to_string())).collect::>()?; - if docs.is_empty() { + if ids.is_empty() { return Err("no selected layers".into()); } + let docs = exportable_layers(&st.doc, ids)?; 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)); 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 new file mode 100644 index 0000000000..1f34fd3b9a --- /dev/null +++ b/crates/ui-egui/src/dialogs/export_dialog/layer_empty_skip_tests.rs @@ -0,0 +1,115 @@ +//! #14806: Layer › Export As and Quick Export as PNG with several layers skip empty, adjustment +//! and off-canvas layers instead of failing. The dialog opens on the first layer with pixels; +//! with nothing left to export they say why. + +use super::*; +use photocraft_doc::LayerId; +use photocraft_geom::Rect; +use std::{cell::RefCell, rc::Rc}; + +type Written = Rc>>; + +struct Layers { + empty: LayerId, + adjustment: LayerId, + gone: LayerId, + red: LayerId, + blue: LayerId, +} + +/// 100 x 80 with, bottom to top: Background, `Empty` (no pixels), an Invert adjustment layer, +/// `Gone` (pixels only past the right edge), `Red` and `Blue` (filled). +fn app(answer: &str) -> (PhotocraftApp, Layers, Written) { + let written = Written::default(); + let capture = written.clone(); + let (picker, _) = crate::file_dialog::fake(vec![Some(crate::FileDialogAnswer::SaveTo(answer.into()))]); + let services = crate::Services { + file_dialog: Some(picker), + export: Some(Box::new(|doc, path, settings| { + photocraft_io::export(doc, path, &settings.io_options()).map(|r| (r.bytes, r.warnings)).map_err(|e| e.to_string()) + })), + write: Some(Box::new(move |path, _| { + capture.borrow_mut().push(path.to_string()); + Ok(()) + })), + ..Default::default() + }; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); + app.run("file.new", json!({"width": 100, "height": 80})).unwrap(); + let active = |app: &PhotocraftApp| app.session.active().unwrap().active_layer.unwrap(); + app.run("layer.new.layer", json!({"name": "Empty"})).unwrap(); + let empty = active(&app); + app.run("layer.newAdjustmentLayer.invert", json!({})).unwrap(); + let adjustment = active(&app); + app.run("layer.new.layer", json!({"name": "Gone"})).unwrap(); + let gone = active(&app); + { + let st = app.session.active_mut().unwrap(); + let doc = Arc::make_mut(&mut st.doc); + let surface = doc.layer_mut(gone).unwrap().surface_mut().unwrap(); + let red = photocraft_raster::from_rgba(&surface.format(), [1.0, 0.0, 0.0, 1.0]); + surface.fill_rect(Rect::new(150, 0, 190, 40), &red); + } + app.run("layer.new.layer", json!({"name": "Red"})).unwrap(); + app.run("paint.bucket", json!({"x": 0, "y": 0, "color": "#ff0000"})).unwrap(); + let red = active(&app); + app.run("layer.new.layer", json!({"name": "Blue"})).unwrap(); + app.run("paint.bucket", json!({"x": 0, "y": 0, "color": "#0000ff"})).unwrap(); + let blue = active(&app); + (app, Layers { empty, adjustment, gone, red, blue }, written) +} + +fn poll(app: &mut PhotocraftApp) { + let ctx = egui::Context::default(); + for _ in 0..3 { + app.poll_file_dialog(&ctx, None); + } +} + +#[test] +fn the_dialog_opens_on_the_first_layer_with_pixels_and_exports_only_those() { + let (mut app, l, written) = app("out.png"); + let selection = [l.empty, l.adjustment, l.gone, l.red, l.blue]; + let id = open_layers(&mut app, &selection).expect("an empty lowest layer no longer stops the dialog"); + let fields = app.ui.dialog_mut(id).unwrap().fields.clone(); + assert_eq!(fields["__layer"], json!(l.red.0), "the preview shows the first layer with pixels"); + confirm(&mut app, &fields).unwrap(); + poll(&mut app); + assert_eq!(*written.borrow(), ["out.png", "out-2-Blue.png"], "Red and Blue; the empty, adjustment and off-canvas layers write nothing"); + assert!(!app.ui.status_error, "{}", app.ui.status); +} + +#[test] +fn quick_export_skips_the_same_layers() { + let (mut app, l, written) = app("quick.png"); + app.session.active_mut().unwrap().selected_layers = vec![l.empty, l.red, l.adjustment, l.blue, l.gone]; + quick_export_selected_layers_png(&mut app).unwrap(); + poll(&mut app); + assert_eq!(*written.borrow(), ["quick.png", "quick-2-Blue.png"]); +} + +#[test] +fn nothing_left_to_export_writes_nothing_and_says_why() { + let (mut app, l, written) = app("none.png"); + let empties = [l.empty, l.adjustment, l.gone]; + let no_asset = |e: String| assert!(e.contains("No valid asset to export"), "{e}"); + no_asset(open_layers(&mut app, &empties).unwrap_err()); + let f = json!({"format": "png", "scale": 100, "__layers": empties.iter().map(|l| l.0).collect::>()}).as_object().unwrap().clone(); + no_asset(confirm(&mut app, &f).unwrap_err()); + let st = app.session.active_mut().unwrap(); + st.selected_layers = empties.to_vec(); + st.active_layer = Some(l.gone); + no_asset(quick_export_selected_layers_png(&mut app).unwrap_err()); + poll(&mut app); + assert!(written.borrow().is_empty()); +} + +/// A real failure (a layer that isn't in the document) is still an error, not skipped. +#[test] +fn other_failures_are_still_errors() { + let (app, l, _) = app("x.png"); + let doc = app.session.active().unwrap().doc.clone(); + let err = exportable_layers(&doc, &[l.red, LayerId(987_654)]).unwrap_err(); + assert!(!err.contains("No valid asset"), "{err}"); + assert_eq!(exportable_layers(&doc, &[l.gone, l.red]).unwrap().len(), 1); +} From 7b7274b8538d07da7ee6b8a88535379a6e300f7c Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sat, 14 Nov 2026 22:39:46 -0600 Subject: [PATCH 2/6] =?UTF-8?q?Layer=20=E2=80=BA=20Export=20As:=20several?= =?UTF-8?q?=20files=20go=20into=20a=20folder=20as=20.?= =?UTF-8?q?=20(#14808)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/ui-egui/src/dialogs/export_dialog.rs | 97 ++++++++++++++-- .../export_dialog/layer_empty_skip_tests.rs | 12 +- .../layer_folder_export_tests.rs | 106 ++++++++++++++++++ crates/ui-egui/src/file_dialog/tests.rs | 20 +--- 4 files changed, 205 insertions(+), 30 deletions(-) create mode 100644 crates/ui-egui/src/dialogs/export_dialog/layer_folder_export_tests.rs diff --git a/crates/ui-egui/src/dialogs/export_dialog.rs b/crates/ui-egui/src/dialogs/export_dialog.rs index ed6c94aa57..1567880172 100644 --- a/crates/ui-egui/src/dialogs/export_dialog.rs +++ b/crates/ui-egui/src/dialogs/export_dialog.rs @@ -218,6 +218,8 @@ fn exportable_layers(doc: &Document, ids: &[photocraft_doc::LayerId]) -> Result< #[cfg(test)] mod layer_empty_skip_tests; +#[cfg(test)] +mod layer_folder_export_tests; /// Layer › Quick Export as PNG. pub fn quick_export_layer_png(app: &mut PhotocraftApp, layer: photocraft_doc::LayerId) -> Result { @@ -1145,22 +1147,33 @@ fn confirm_layers(app: &mut PhotocraftApp, f: &Map, ids: &[photoc return Err("no selected layers".into()); } let docs = exportable_layers(&st.doc, ids)?; - 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 ext = s_fmt(f); let (f, settings) = (f.clone(), settings(f)); + // Several files on the desktop: a folder, then `.` per layer there (#14808). + if docs.len() > 1 && !cfg!(target_arch = "wasm32") { + let names = layer_file_names(&docs, &ext); + return app.ask_folder(move |app, dir| { + let mut exported = Vec::new(); + for (doc, name) in docs.iter().zip(names) { + let path = std::path::Path::new(&dir).join(name); + replace_link(&path)?; + exported.push(write_layer_file(app, doc, &f, &settings, &source_profile, &path.to_string_lossy())?); + } + 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})) + }); + } + // One file: the save dialog, named after the layer. The web downloads each file as before. + let suggested = match docs.as_slice() { + [one] => format!("{}.{ext}", layer_file_stem(&one.name)), + _ => format!("{}.{ext}", export_name(st.doc.name.rsplit_once('.').map_or(st.doc.name.as_str(), |(a, _)| a))), + }; app.pick_export(&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, &source_profile)?; - crate::app::ensure_memory_to_save(&out, &path)?; - 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})); + exported.push(write_layer_file(app, doc, &f, &settings, &source_profile, &path)?); } let template = "Exported {n} files"; app.ui.status = crate::i18n::fmt(tl!(template), &[("n", &exported.len().to_string())]); @@ -1169,6 +1182,66 @@ fn confirm_layers(app: &mut PhotocraftApp, f: &Map, ids: &[photoc }) } +/// One layer's file of a Layer › Export As: rendered with the dialog's settings and written. +fn write_layer_file( + app: &mut PhotocraftApp, + doc: &Document, + f: &Map, + settings: &ExportSettings, + source_profile: &Profile, + path: &str, +) -> Result { + let out = export_document(doc, f, None, source_profile)?; + crate::app::ensure_memory_to_save(&out, path)?; + 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); + Ok(json!({"path": path, "bytes": bytes.len(), "warnings": warnings})) +} + +/// A layer's file name, as measured in the reference application: each character a file name +/// 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.trim().is_empty() { "layer".into() } else { stem } +} + +/// The names several layers' files get, for `docs` in document order (bottom to top). Equal +/// names are numbered in Layers panel order: the upper layer keeps the name, the next ones down +/// get `-1`, `-2`, … (skipping a name another layer already has). +fn layer_file_names(docs: &[Document], ext: &str) -> Vec { + let mut used = std::collections::HashSet::new(); + 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 n = 1u64; + while used.contains(&name) { + name = format!("{stem}-{n}.{ext}"); + n = n.saturating_add(1); + } + used.insert(name.clone()); + names[i] = name; + } + names +} + +/// Existing files are replaced without a prompt, but a link where a file goes is removed first, +/// so the write lands there and is never redirected (the writer follows links). +fn replace_link(path: &std::path::Path) -> Result<(), String> { + #[cfg(not(target_arch = "wasm32"))] + if path.symlink_metadata().is_ok_and(|m| m.file_type().is_symlink()) { + std::fs::remove_file(path).map_err(|e| format!("{}: {e}", path.display()))?; + } + #[cfg(target_arch = "wasm32")] + let _ = path; + Ok(()) +} + /// 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/dialogs/export_dialog/layer_empty_skip_tests.rs b/crates/ui-egui/src/dialogs/export_dialog/layer_empty_skip_tests.rs index 1f34fd3b9a..720ede743a 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 @@ -20,9 +20,13 @@ struct Layers { /// 100 x 80 with, bottom to top: Background, `Empty` (no pixels), an Invert adjustment layer, /// `Gone` (pixels only past the right edge), `Red` and `Blue` (filled). fn app(answer: &str) -> (PhotocraftApp, Layers, Written) { + app_answering(crate::FileDialogAnswer::SaveTo(answer.into())) +} + +fn app_answering(answer: crate::FileDialogAnswer) -> (PhotocraftApp, Layers, Written) { let written = Written::default(); let capture = written.clone(); - let (picker, _) = crate::file_dialog::fake(vec![Some(crate::FileDialogAnswer::SaveTo(answer.into()))]); + let (picker, _) = crate::file_dialog::fake(vec![Some(answer)]); let services = crate::Services { file_dialog: Some(picker), export: Some(Box::new(|doc, path, settings| { @@ -68,14 +72,16 @@ fn poll(app: &mut PhotocraftApp) { #[test] fn the_dialog_opens_on_the_first_layer_with_pixels_and_exports_only_those() { - let (mut app, l, written) = app("out.png"); + let (mut app, l, written) = app_answering(crate::FileDialogAnswer::FolderTo("/out".into())); let selection = [l.empty, l.adjustment, l.gone, l.red, l.blue]; let id = open_layers(&mut app, &selection).expect("an empty lowest layer no longer stops the dialog"); let fields = app.ui.dialog_mut(id).unwrap().fields.clone(); assert_eq!(fields["__layer"], json!(l.red.0), "the preview shows the first layer with pixels"); confirm(&mut app, &fields).unwrap(); poll(&mut app); - assert_eq!(*written.borrow(), ["out.png", "out-2-Blue.png"], "Red and Blue; the empty, adjustment and off-canvas layers write nothing"); + // Two files: a folder with one `.` each (#14808). + let want: Vec = ["Red.png", "Blue.png"].iter().map(|n| std::path::Path::new("/out").join(n).to_string_lossy().into_owned()).collect(); + assert_eq!(*written.borrow(), want, "Red and Blue; the empty, adjustment and off-canvas layers write nothing"); assert!(!app.ui.status_error, "{}", app.ui.status); } 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 new file mode 100644 index 0000000000..9c8a456f3a --- /dev/null +++ b/crates/ui-egui/src/dialogs/export_dialog/layer_folder_export_tests.rs @@ -0,0 +1,106 @@ +//! #14808: Layer › Export As with several files to write asks for a folder and writes one +//! `.` per layer there: illegal characters become `_`, equal names are numbered +//! from the upper layer down, existing files are replaced (a planted link too, never followed). +//! One file keeps the save dialog with the layer's name. + +use super::*; +use photocraft_doc::{Color, Size}; +use std::{cell::RefCell, rc::Rc}; + +type Written = Rc>>; +type Asked = Rc>>; + +fn named(name: &str) -> Document { + Document::with_background(name, Size::new(4, 4), ColorMode::Rgb, photocraft_doc::SampleType::U8, Color::WHITE) +} + +#[test] +fn names_keep_spaces_replace_illegal_characters_and_number_duplicates_downwards() { + assert_eq!(layer_file_stem("a/b:c*?"), "a_b_c__"); + assert_eq!(layer_file_stem("Artboard 1"), "Artboard 1"); + assert_eq!(layer_file_stem(r#"qo"t|e\s"#), "q_u_o_t_e_s"); + // Bottom to top: three `Dup`s under `Top`. The upper `Dup` keeps the name. + let docs = [named("Dup"), named("Dup"), named("Dup"), named("Top")]; + assert_eq!(layer_file_names(&docs, "png"), ["Dup-2.png", "Dup-1.png", "Dup.png", "Top.png"]); + // A layer already called `Dup-1` keeps its name; the numbering skips it. + let docs = [named("Dup"), named("Dup-1"), named("Dup")]; + assert_eq!(layer_file_names(&docs, "jpg"), ["Dup-2.jpg", "Dup-1.jpg", "Dup.jpg"]); +} + +/// A document with filled layers `a/b:c*?`, `Dup` and `Dup` (bottom to top), all selected, plus +/// an empty layer. +fn app(answer: crate::FileDialogAnswer) -> (PhotocraftApp, Vec, photocraft_doc::LayerId, Written, Asked) { + let written = Written::default(); + let capture = written.clone(); + let (picker, asked) = crate::file_dialog::fake(vec![Some(answer)]); + let services = crate::Services { + file_dialog: Some(picker), + export: Some(Box::new(|doc, path, settings| { + photocraft_io::export(doc, path, &settings.io_options()).map(|r| (r.bytes, r.warnings)).map_err(|e| e.to_string()) + })), + write: Some(Box::new(move |path, _| { + capture.borrow_mut().push(path.to_string()); + Ok(()) + })), + ..Default::default() + }; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); + app.run("file.new", json!({"width": 40, "height": 30})).unwrap(); + app.run("layer.new.layer", json!({"name": "Blank"})).unwrap(); + let empty = app.session.active().unwrap().active_layer.unwrap(); + let mut ids = Vec::new(); + for (name, color) in [("a/b:c*?", "#ff0000"), ("Dup", "#00ff00"), ("Dup", "#0000ff")] { + app.run("layer.new.layer", json!({"name": name})).unwrap(); + app.run("paint.bucket", json!({"x": 0, "y": 0, "color": color})).unwrap(); + ids.push(app.session.active().unwrap().active_layer.unwrap()); + } + (app, ids, empty, written, asked) +} + +fn export_layers(app: &mut PhotocraftApp, ids: &[photocraft_doc::LayerId]) { + let f = json!({"format": "png", "scale": 100, "__layers": ids.iter().map(|l| l.0).collect::>()}).as_object().unwrap().clone(); + confirm(app, &f).unwrap(); + let ctx = egui::Context::default(); + for _ in 0..3 { + app.poll_file_dialog(&ctx, None); + } +} + +#[test] +fn several_layers_go_into_a_folder_one_file_each() { + let dir = std::env::temp_dir().join(format!("pc-layer-folder-{}", std::process::id())); + let (mut app, ids, _, written, asked) = app(crate::FileDialogAnswer::FolderTo(dir.to_string_lossy().into_owned())); + export_layers(&mut app, &ids); + assert!(matches!(asked.borrow().first(), Some(crate::file_dialog::FileDialogRequest::Folder { .. })), "a folder choice"); + let want: Vec = ["a_b_c__.png", "Dup-1.png", "Dup.png"].iter().map(|n| dir.join(n).to_string_lossy().into_owned()).collect(); + assert_eq!(*written.borrow(), want, "no sub folder; the upper Dup keeps the name"); + assert!(!app.ui.status_error, "{}", app.ui.status); +} + +#[cfg(unix)] +#[test] +fn a_planted_link_is_replaced_not_followed() { + let dir = std::env::temp_dir().join(format!("pc-layer-link-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let link = dir.join("Dup.png"); + std::os::unix::fs::symlink(dir.join("victim"), &link).unwrap(); + let (mut app, ids, _, written, _) = app(crate::FileDialogAnswer::FolderTo(dir.to_string_lossy().into_owned())); + export_layers(&mut app, &ids); + assert!(link.symlink_metadata().is_err(), "the link is gone before the write"); + assert!(written.borrow().contains(&link.to_string_lossy().into_owned())); + assert!(!dir.join("victim").exists(), "nothing was written through the link"); + std::fs::remove_dir_all(&dir).unwrap(); +} + +#[test] +fn one_file_keeps_the_save_dialog_with_the_layers_name() { + let (mut app, ids, empty, written, asked) = app(crate::FileDialogAnswer::SaveTo("/out/picked.png".into())); + export_layers(&mut app, &[empty, ids[0]]); + let suggested = asked.borrow().iter().find_map(|r| match r { + crate::file_dialog::FileDialogRequest::Save { suggested } => Some(suggested.clone()), + _ => None, + }); + assert!(suggested.as_deref().is_some_and(|s| s.ends_with("a_b_c__.png")), "{suggested:?}"); + assert_eq!(*written.borrow(), ["/out/picked.png"]); +} diff --git a/crates/ui-egui/src/file_dialog/tests.rs b/crates/ui-egui/src/file_dialog/tests.rs index 3eba37f0ae..d009b116cd 100644 --- a/crates/ui-egui/src/file_dialog/tests.rs +++ b/crates/ui-egui/src/file_dialog/tests.rs @@ -1284,7 +1284,7 @@ fn an_unavailable_dialog_is_reported_and_a_cancelled_one_is_not() { } /// #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. +/// board's size and with the dialog's settings, after one destination prompt (a folder, #14808). #[test] fn export_as_with_several_artboards_selected_writes_one_file_each() { let (mut app, open, written) = app(); @@ -1311,22 +1311,12 @@ fn export_as_with_several_artboards_selected_writes_one_file_each() { 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()))); + // #14808: several files go into a chosen folder, one `.` each. + answer(&open, Some(FileDialogAnswer::FolderTo("/out".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"); - // The sibling path is built with `Path::join`, so Windows turns the separator into `\`. - let second = written.borrow()[1].replace('\\', "/"); - assert!(second.starts_with("/out/boards-2-") && second.ends_with(".jpg"), "{:?}", written.borrow()); - let written = written.borrow(); - assert_eq!(written.len(), 2); - // First file uses the exact path from the dialog (forward slashes in test) - assert_eq!(std::path::Path::new(&written[0]).file_name().and_then(|n| n.to_str()), Some("boards.jpg")); - // Second file is generated by batch_paths which uses platform path separators - let sibling = std::path::Path::new(&written[1]); - assert_eq!(sibling.parent(), std::path::Path::new(&written[0]).parent()); - assert_eq!(sibling.file_name().and_then(|name| name.to_str()), Some("boards-2-Capsule.jpg")); + let want: Vec = ["Header.jpg", "Capsule.jpg"].iter().map(|n| std::path::Path::new("/out").join(n).to_string_lossy().into_owned()).collect(); + assert_eq!(*written.borrow(), want); let mut got = sizes.borrow().iter().map(|(_, w, h)| (*w, *h)).collect::>(); got.sort_unstable(); assert_eq!(got, [(10, 25), (20, 15)], "each board at its own size, scaled to 50 %"); From dbaf4d0fd056b1ef7058a677bb7e5535c9cec06b Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sun, 15 Nov 2026 02:51:08 -0600 Subject: [PATCH 3/6] Layer export: opening the dialog skips only empty layers and reports any other error --- crates/ui-egui/src/dialogs/export_dialog.rs | 11 ++++++++++- .../export_dialog/layer_empty_skip_tests.rs | 15 +++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs/export_dialog.rs b/crates/ui-egui/src/dialogs/export_dialog.rs index 1567880172..d7d7376b95 100644 --- a/crates/ui-egui/src/dialogs/export_dialog.rs +++ b/crates/ui-egui/src/dialogs/export_dialog.rs @@ -183,8 +183,17 @@ pub fn open_layers(app: &mut PhotocraftApp, layers: &[photocraft_doc::LayerId]) }; // The dialog opens on the first layer with pixels: an empty, adjustment or off-canvas layer // at the bottom of the selection no longer stops it (#14806). + // Only an empty layer is skipped: any other failure (an unknown id, say) is the answer, whether or + // not a valid layer follows it. let st = app.session.active().ok_or("no document")?; - let first = layers.iter().copied().find(|id| photocraft_engine::layer_menu_cmds::layer_document(&st.doc, *id).is_ok()); + let mut first = None; + for id in layers { + match photocraft_engine::layer_menu_cmds::layer_document(&st.doc, *id) { + Ok(_) => first = first.or(Some(*id)), + Err(e) if photocraft_engine::layer_menu_cmds::is_empty_layer(&e) => {} + Err(e) => return Err(e.to_string()), + } + } let id = open_layer(app, first.ok_or_else(|| tl!(NO_VALID_ASSET).to_string())?)?; 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::>())); 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 720ede743a..86e34f9ad5 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 @@ -119,3 +119,18 @@ fn other_failures_are_still_errors() { assert!(!err.contains("No valid asset"), "{err}"); assert_eq!(exportable_layers(&doc, &[l.gone, l.red]).unwrap().len(), 1); } + +/// CodeRabbit on #15034: opening the dialog skips only empty layers. An unknown id is reported, before or +/// after a valid layer, and the empty-layer message is kept for a selection that is all empty. +#[test] +fn opening_with_an_unknown_layer_reports_it_instead_of_skipping_it() { + let (mut app, l, _) = app("/out/x.png"); + let unknown = LayerId(987_654); + for selection in [vec![unknown, l.empty], vec![l.empty, unknown, l.red], vec![l.red, unknown]] { + let err = open_layers(&mut app, &selection).unwrap_err(); + assert!(!err.contains("No valid asset"), "{selection:?}: the unknown id is the error, not the empty message: {err}"); + assert!(app.ui.dialogs.is_empty(), "no dialog opened"); + } + let e = open_layers(&mut app, &[l.empty, l.adjustment]).unwrap_err(); + assert!(e.contains("No valid asset to export"), "{e}"); +} From 3d8ce67dfde7c077afc8da9799916bf468238bf6 Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sun, 15 Nov 2026 02:59:10 -0600 Subject: [PATCH 4/6] Layer export to a folder: compare file names case-folded; use temporary folders in the folder tests --- crates/ui-egui/src/dialogs/export_dialog.rs | 8 +++++--- .../export_dialog/layer_empty_skip_tests.rs | 7 +++++-- .../export_dialog/layer_folder_export_tests.rs | 16 +++++++++++----- 3 files changed, 21 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/dialogs/export_dialog.rs b/crates/ui-egui/src/dialogs/export_dialog.rs index d7d7376b95..cdb19832c1 100644 --- a/crates/ui-egui/src/dialogs/export_dialog.rs +++ b/crates/ui-egui/src/dialogs/export_dialog.rs @@ -1221,7 +1221,9 @@ fn layer_file_stem(name: &str) -> String { /// The names several layers' files get, for `docs` in document order (bottom to top). Equal /// names are numbered in Layers panel order: the upper layer keeps the name, the next ones down -/// get `-1`, `-2`, … (skipping a name another layer already has). +/// get `-1`, `-2`, … (skipping a name another layer already has). Names are compared case-folded, +/// as a case-insensitive destination (a default Windows or macOS volume) treats `Logo` and `logo` +/// as one file, which a second write would silently replace. fn layer_file_names(docs: &[Document], ext: &str) -> Vec { let mut used = std::collections::HashSet::new(); let mut names = vec![String::new(); docs.len()]; @@ -1229,11 +1231,11 @@ fn layer_file_names(docs: &[Document], ext: &str) -> Vec { let stem = layer_file_stem(&doc.name); let mut name = format!("{stem}.{ext}"); let mut n = 1u64; - while used.contains(&name) { + while used.contains(&name.to_lowercase()) { name = format!("{stem}-{n}.{ext}"); n = n.saturating_add(1); } - used.insert(name.clone()); + used.insert(name.to_lowercase()); names[i] = name; } names 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 86e34f9ad5..e9abe4b0bf 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 @@ -72,7 +72,10 @@ fn poll(app: &mut PhotocraftApp) { #[test] fn the_dialog_opens_on_the_first_layer_with_pixels_and_exports_only_those() { - let (mut app, l, written) = app_answering(crate::FileDialogAnswer::FolderTo("/out".into())); + // A real folder, so the planted-link check on the targets never meets a path outside the test. + let guard = tempfile::tempdir().unwrap(); + let out = guard.path().to_path_buf(); + let (mut app, l, written) = app_answering(crate::FileDialogAnswer::FolderTo(out.to_string_lossy().into_owned())); let selection = [l.empty, l.adjustment, l.gone, l.red, l.blue]; let id = open_layers(&mut app, &selection).expect("an empty lowest layer no longer stops the dialog"); let fields = app.ui.dialog_mut(id).unwrap().fields.clone(); @@ -80,7 +83,7 @@ fn the_dialog_opens_on_the_first_layer_with_pixels_and_exports_only_those() { confirm(&mut app, &fields).unwrap(); poll(&mut app); // Two files: a folder with one `.` each (#14808). - let want: Vec = ["Red.png", "Blue.png"].iter().map(|n| std::path::Path::new("/out").join(n).to_string_lossy().into_owned()).collect(); + let want: Vec = ["Red.png", "Blue.png"].iter().map(|n| out.join(n).to_string_lossy().into_owned()).collect(); assert_eq!(*written.borrow(), want, "Red and Blue; the empty, adjustment and off-canvas layers write nothing"); assert!(!app.ui.status_error, "{}", app.ui.status); } 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 9c8a456f3a..32d279cdff 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 @@ -22,6 +22,12 @@ fn names_keep_spaces_replace_illegal_characters_and_number_duplicates_downwards( // Bottom to top: three `Dup`s under `Top`. The upper `Dup` keeps the name. let docs = [named("Dup"), named("Dup"), named("Dup"), named("Top")]; assert_eq!(layer_file_names(&docs, "png"), ["Dup-2.png", "Dup-1.png", "Dup.png", "Top.png"]); + // Names that differ only in case are one file on a case-insensitive destination: the upper layer + // keeps its name, the lower one is numbered. + let docs = [named("Logo"), named("logo")]; + assert_eq!(layer_file_names(&docs, "png"), ["Logo-1.png", "logo.png"]); + let docs = [named("logo"), named("LOGO"), named("Logo")]; + assert_eq!(layer_file_names(&docs, "png"), ["logo-2.png", "LOGO-1.png", "Logo.png"]); // A layer already called `Dup-1` keeps its name; the numbering skips it. let docs = [named("Dup"), named("Dup-1"), named("Dup")]; assert_eq!(layer_file_names(&docs, "jpg"), ["Dup-2.jpg", "Dup-1.jpg", "Dup.jpg"]); @@ -68,7 +74,9 @@ fn export_layers(app: &mut PhotocraftApp, ids: &[photocraft_doc::LayerId]) { #[test] fn several_layers_go_into_a_folder_one_file_each() { - let dir = std::env::temp_dir().join(format!("pc-layer-folder-{}", std::process::id())); + // The guard removes the folder on success and on failure. + let guard = tempfile::tempdir().unwrap(); + let dir = guard.path().to_path_buf(); let (mut app, ids, _, written, asked) = app(crate::FileDialogAnswer::FolderTo(dir.to_string_lossy().into_owned())); export_layers(&mut app, &ids); assert!(matches!(asked.borrow().first(), Some(crate::file_dialog::FileDialogRequest::Folder { .. })), "a folder choice"); @@ -80,9 +88,8 @@ fn several_layers_go_into_a_folder_one_file_each() { #[cfg(unix)] #[test] fn a_planted_link_is_replaced_not_followed() { - let dir = std::env::temp_dir().join(format!("pc-layer-link-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); + let guard = tempfile::tempdir().unwrap(); + let dir = guard.path().to_path_buf(); let link = dir.join("Dup.png"); std::os::unix::fs::symlink(dir.join("victim"), &link).unwrap(); let (mut app, ids, _, written, _) = app(crate::FileDialogAnswer::FolderTo(dir.to_string_lossy().into_owned())); @@ -90,7 +97,6 @@ fn a_planted_link_is_replaced_not_followed() { assert!(link.symlink_metadata().is_err(), "the link is gone before the write"); assert!(written.borrow().contains(&link.to_string_lossy().into_owned())); assert!(!dir.join("victim").exists(), "nothing was written through the link"); - std::fs::remove_dir_all(&dir).unwrap(); } #[test] From 57a3fd7c83060d6a5d79b1bfb1a3e8045ffb8d07 Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sun, 15 Nov 2026 04:53:27 -0600 Subject: [PATCH 5/6] Layer export to a folder: fold names by uppercase (final sigma) --- crates/ui-egui/src/dialogs/export_dialog.rs | 7 ++++--- .../src/dialogs/export_dialog/layer_folder_export_tests.rs | 3 +++ 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/dialogs/export_dialog.rs b/crates/ui-egui/src/dialogs/export_dialog.rs index cdb19832c1..e28d269966 100644 --- a/crates/ui-egui/src/dialogs/export_dialog.rs +++ b/crates/ui-egui/src/dialogs/export_dialog.rs @@ -1221,7 +1221,8 @@ fn layer_file_stem(name: &str) -> String { /// The names several layers' files get, for `docs` in document order (bottom to top). Equal /// names are numbered in Layers panel order: the upper layer keeps the name, the next ones down -/// get `-1`, `-2`, … (skipping a name another layer already has). Names are compared case-folded, +/// get `-1`, `-2`, … (skipping a name another layer already has). Names are compared upper-cased (as +/// Windows folds them, so a final sigma `ς` and `σ` are one name), /// as a case-insensitive destination (a default Windows or macOS volume) treats `Logo` and `logo` /// as one file, which a second write would silently replace. fn layer_file_names(docs: &[Document], ext: &str) -> Vec { @@ -1231,11 +1232,11 @@ fn layer_file_names(docs: &[Document], ext: &str) -> Vec { let stem = layer_file_stem(&doc.name); let mut name = format!("{stem}.{ext}"); let mut n = 1u64; - while used.contains(&name.to_lowercase()) { + while used.contains(&name.to_uppercase()) { name = format!("{stem}-{n}.{ext}"); n = n.saturating_add(1); } - used.insert(name.to_lowercase()); + used.insert(name.to_uppercase()); names[i] = name; } names 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 32d279cdff..0f0786ad58 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 @@ -28,6 +28,9 @@ fn names_keep_spaces_replace_illegal_characters_and_number_duplicates_downwards( assert_eq!(layer_file_names(&docs, "png"), ["Logo-1.png", "logo.png"]); let docs = [named("logo"), named("LOGO"), named("Logo")]; assert_eq!(layer_file_names(&docs, "png"), ["logo-2.png", "LOGO-1.png", "Logo.png"]); + // Windows folds names by upper-casing: a final sigma and a sigma are one file there. + let docs = [named("ς"), named("σ")]; + assert_eq!(layer_file_names(&docs, "png"), ["ς-1.png", "σ.png"]); // A layer already called `Dup-1` keeps its name; the numbering skips it. let docs = [named("Dup"), named("Dup-1"), named("Dup")]; assert_eq!(layer_file_names(&docs, "jpg"), ["Dup-2.jpg", "Dup-1.jpg", "Dup.jpg"]); From 2dde628389c2979a3dd7e5378ba66522d3a9f7c6 Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sun, 15 Nov 2026 06:46:13 -0600 Subject: [PATCH 6/6] Layer export to a folder: a name is taken under upper-case or lower-case folding --- crates/ui-egui/src/dialogs/export_dialog.rs | 11 ++++++++--- .../export_dialog/layer_folder_export_tests.rs | 3 +++ 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/dialogs/export_dialog.rs b/crates/ui-egui/src/dialogs/export_dialog.rs index e28d269966..722e89eee1 100644 --- a/crates/ui-egui/src/dialogs/export_dialog.rs +++ b/crates/ui-egui/src/dialogs/export_dialog.rs @@ -1221,22 +1221,27 @@ fn layer_file_stem(name: &str) -> String { /// The names several layers' files get, for `docs` in document order (bottom to top). Equal /// names are numbered in Layers panel order: the upper layer keeps the name, the next ones down -/// get `-1`, `-2`, … (skipping a name another layer already has). Names are compared upper-cased (as -/// Windows folds them, so a final sigma `ς` and `σ` are one name), +/// get `-1`, `-2`, … (skipping a name another layer already has). Names are compared upper-cased and lower-cased +/// (so a final sigma `ς` and `σ`, and `K` and the Kelvin sign, are one name), /// as a case-insensitive destination (a default Windows or macOS volume) treats `Logo` and `logo` /// as one file, which a second write would silently replace. fn layer_file_names(docs: &[Document], ext: &str) -> Vec { + // A name is taken when its upper-cased or its lower-cased form is: upper-casing joins `σ` and `ς` + // (Windows folds that way), lower-casing joins `K` and the Kelvin sign `K` (which APFS treats as + // one name). Neither folding alone catches both. + let taken = |used: &std::collections::HashSet, name: &str| used.contains(&name.to_uppercase()) || used.contains(&name.to_lowercase()); let mut used = std::collections::HashSet::new(); 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 n = 1u64; - while used.contains(&name.to_uppercase()) { + while taken(&used, &name) { name = format!("{stem}-{n}.{ext}"); n = n.saturating_add(1); } used.insert(name.to_uppercase()); + used.insert(name.to_lowercase()); names[i] = name; } names 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 0f0786ad58..8959a82cbc 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 @@ -31,6 +31,9 @@ fn names_keep_spaces_replace_illegal_characters_and_number_duplicates_downwards( // Windows folds names by upper-casing: a final sigma and a sigma are one file there. let docs = [named("ς"), named("σ")]; assert_eq!(layer_file_names(&docs, "png"), ["ς-1.png", "σ.png"]); + // `K` and the Kelvin sign are one name on a volume that normalises (APFS); upper-casing alone keeps them apart. + let docs = [named("K"), named("\u{212A}")]; + assert_eq!(layer_file_names(&docs, "png"), ["K-1.png", "\u{212A}.png"]); // A layer already called `Dup-1` keeps its name; the numbering skips it. let docs = [named("Dup"), named("Dup-1"), named("Dup")]; assert_eq!(layer_file_names(&docs, "jpg"), ["Dup-2.jpg", "Dup-1.jpg", "Dup.jpg"]);