mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
Merge pull request #15039 from hectorviov/fix/layer-export-folder
Layer › Export As: several files go into a folder as <layer name>.<ext>
This commit is contained in:
5 files changed
+410
-36
No files matched your search
@@ -935,6 +935,16 @@ fn content_options(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
|
||||
/// 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<Document> {
|
||||
let l = doc.layer(id).ok_or(EngineError::NoLayer(id))?;
|
||||
let mut alone = l.clone();
|
||||
@@ -955,7 +965,7 @@ pub fn layer_document(doc: &Document, id: LayerId) -> Result<Document> {
|
||||
}
|
||||
}
|
||||
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);
|
||||
|
||||
@@ -176,12 +176,25 @@ 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<u64, String> {
|
||||
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).
|
||||
// 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 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::<Vec<_>>()));
|
||||
let template = "Export As: {n} layers";
|
||||
@@ -190,6 +203,33 @@ 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<Vec<Document>, 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;
|
||||
#[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<Value, String> {
|
||||
let mut f = Map::new();
|
||||
@@ -213,8 +253,7 @@ 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: 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 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") {
|
||||
@@ -1130,27 +1169,37 @@ pub(crate) fn replay(app: &mut PhotocraftApp, params: &Value) -> Result<Value, S
|
||||
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 source_profile = effective_source_profile(app, &st.doc);
|
||||
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() {
|
||||
if ids.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 docs = exportable_layers(&st.doc, ids)?;
|
||||
let ext = s_fmt(f);
|
||||
let (f, settings) = (f.clone(), settings(f));
|
||||
// Several files on the desktop: a folder, then `<layer name>.<ext>` 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())]);
|
||||
@@ -1159,6 +1208,74 @@ fn confirm_layers(app: &mut PhotocraftApp, f: &Map<String, Value>, 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<String, Value>,
|
||||
settings: &ExportSettings,
|
||||
source_profile: &Profile,
|
||||
path: &str,
|
||||
) -> Result<Value, String> {
|
||||
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). 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<String> {
|
||||
// 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<String>, 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 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
|
||||
}
|
||||
|
||||
/// 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.
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
//! #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<RefCell<Vec<String>>>;
|
||||
|
||||
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) {
|
||||
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(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": 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() {
|
||||
// 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();
|
||||
assert_eq!(fields["__layer"], json!(l.red.0), "the preview shows the first layer with pixels");
|
||||
confirm(&mut app, &fields).unwrap();
|
||||
poll(&mut app);
|
||||
// Two files: a folder with one `<layer name>.<ext>` each (#14808).
|
||||
let want: Vec<String> = ["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);
|
||||
}
|
||||
|
||||
#[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::<Vec<_>>()}).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);
|
||||
}
|
||||
|
||||
/// 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}");
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
//! #14808: Layer › Export As with several files to write asks for a folder and writes one
|
||||
//! `<layer name>.<ext>` 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<RefCell<Vec<String>>>;
|
||||
type Asked = Rc<RefCell<Vec<crate::file_dialog::FileDialogRequest>>>;
|
||||
|
||||
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#"q<u>o"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"]);
|
||||
// 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"]);
|
||||
// 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"]);
|
||||
}
|
||||
|
||||
/// 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>, 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::<Vec<_>>()}).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() {
|
||||
// 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");
|
||||
let want: Vec<String> = ["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 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()));
|
||||
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");
|
||||
}
|
||||
|
||||
#[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"]);
|
||||
}
|
||||
@@ -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 `<layer name>.<ext>` 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<String> = ["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::<Vec<_>>();
|
||||
got.sort_unstable();
|
||||
assert_eq!(got, [(10, 25), (20, 15)], "each board at its own size, scaled to 50 %");
|
||||
|
||||
Reference in new issue
Block a user