mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
Fix browser Save for Web downloads and stale export dimensions (#1857)
Save for Web gets a platform-writer entry point (web_cmds::save_for_web_with_writer) so the browser build downloads every image, spacer and HTML file side by side; the export is authorized before any picker opens, a failed write stops it, and only a complete export remembers its settings. Each document now opens the dialog at its own size instead of the last export's width, height and percent. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
c0541baf6a
commit
cd559b387a
3 files changed
+246
-8
No files matched your search
@@ -707,7 +707,20 @@ fn html_table(title: &str, w: u32, h: u32, cells: &[(Rect, String, String)], spa
|
||||
|
||||
/// File › Export › Save for Web (Legacy).
|
||||
fn save_for_web(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
save_for_web_with_writer(s, p, &mut write_file)
|
||||
}
|
||||
|
||||
/// Save for Web through a platform writer (native files or browser downloads).
|
||||
/// The writer receives every image, spacer and HTML file. A write error stops the export;
|
||||
/// only a complete export remembers its settings and fires the export event.
|
||||
pub fn save_for_web_with_writer(s: &mut Session, p: &Value, write: &mut dyn FnMut(&str, &[u8]) -> Result<()>) -> Result<Value> {
|
||||
let cmd = "file.export.saveForWebLegacy";
|
||||
if let Some(authorize) = s.authorize {
|
||||
authorize(cmd, p)?;
|
||||
}
|
||||
// Direct platform calls must export the moved selection as it appears on the canvas,
|
||||
// just as Session::execute does before dispatching the native command.
|
||||
crate::float_cmds::before_command(s, cmd)?;
|
||||
let st = WebSettings::from_params(p, cmd)?;
|
||||
let d = s.active().ok_or(EngineError::NoDocument)?;
|
||||
let doc = d.doc.clone();
|
||||
@@ -730,7 +743,6 @@ fn save_for_web(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.collect();
|
||||
let single = p.get("path").and_then(Value::as_str).filter(|v| !v.is_empty());
|
||||
let dir = p.get("dir").and_then(Value::as_str).filter(|v| !v.is_empty());
|
||||
s.file_menu.last_web = Some(p.clone());
|
||||
// Estimate only (the dialog's annotations): the whole image, or each chosen slice.
|
||||
if single.is_none() && dir.is_none() {
|
||||
let o = optimize(&buf.px, bw, wdoc.bounds(), &st, icc, xmp.as_deref(), dpi, false)?;
|
||||
@@ -738,7 +750,8 @@ fn save_for_web(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
if let Some(path) = single.filter(|_| dir.is_none() && (all.len() == 1 || p.get("slices").is_none())) {
|
||||
let o = optimize(&buf.px, bw, wdoc.bounds(), &st, icc, xmp.as_deref(), dpi, false)?;
|
||||
write_file(path, &o.bytes)?;
|
||||
write(path, &o.bytes)?;
|
||||
s.file_menu.last_web = Some(p.clone());
|
||||
crate::automate_cmds::fire_event(s, "export");
|
||||
return Ok(json!({"files": [path], "bytes": o.bytes.len(), "width": o.width, "height": o.height, "colors": o.colors}));
|
||||
}
|
||||
@@ -799,7 +812,7 @@ fn save_for_web(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let name = unique(&stem, o.ext);
|
||||
let rel = if images.is_empty() { name.clone() } else { format!("{images}/{name}") };
|
||||
let out = join(&dir, &rel);
|
||||
write_file(&out, &o.bytes)?;
|
||||
write(&out, &o.bytes)?;
|
||||
total += o.bytes.len();
|
||||
files.push(out);
|
||||
let alt = stored.map_or(String::new(), |s| html_escape(&s.alt));
|
||||
@@ -820,13 +833,14 @@ fn save_for_web(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let spacer = grid.then(|| if images.is_empty() { "spacer.gif".to_string() } else { format!("{images}/spacer.gif") });
|
||||
if let Some(sp) = &spacer {
|
||||
let gif = photocraft_codecs::web::encode_gif_indexed(1, 1, &[0], &[[0, 0, 0]], Some(0), false).map_err(other)?;
|
||||
write_file(&join(&dir, sp), &gif)?;
|
||||
write(&join(&dir, sp), &gif)?;
|
||||
}
|
||||
let page = html_table(&base, wdoc.size.width, wdoc.size.height, &cells, spacer.as_deref());
|
||||
let hp = join(&dir, &format!("{base}.html"));
|
||||
write_file(&hp, page.as_bytes())?;
|
||||
write(&hp, page.as_bytes())?;
|
||||
html_path = Some(hp);
|
||||
}
|
||||
s.file_menu.last_web = Some(p.clone());
|
||||
crate::automate_cmds::fire_event(s, "export");
|
||||
Ok(json!({"files": files, "html": html_path, "bytes": total, "slices": chosen.len(), "width": wdoc.size.width, "height": wdoc.size.height}))
|
||||
}
|
||||
|
||||
@@ -34,6 +34,122 @@ fn decode(path: &str) -> photocraft_codecs::Image {
|
||||
photocraft_codecs::decode(&std::fs::read(path).unwrap()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn estimates_preserve_last_successful_export_settings() {
|
||||
let dir = tmp("estimate_settings");
|
||||
let mut s = session(8);
|
||||
let saved = json!({"format": "png24", "path": format!("{dir}/saved.png"), "width": 32, "height": 24});
|
||||
s.execute("file.export.saveForWebLegacy", saved.clone()).unwrap();
|
||||
assert_eq!(s.file_menu.last_web.as_ref(), Some(&saved));
|
||||
|
||||
let estimate = s.execute("file.export.saveForWebLegacy", json!({"format": "jpeg", "quality": 10, "width": 16, "height": 12})).unwrap();
|
||||
assert_eq!((estimate["width"].as_u64(), estimate["height"].as_u64()), (Some(16), Some(12)));
|
||||
assert_eq!(s.file_menu.last_web.as_ref(), Some(&saved), "preview estimates must not replace the settings from the last successful export");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn platform_writer_receives_resized_image_at_every_depth() {
|
||||
for depth in [8, 16, 32] {
|
||||
let mut s = session(depth);
|
||||
let params = json!({"format": "png24", "path": "download.png", "width": 32, "height": 24});
|
||||
let mut files = Vec::new();
|
||||
let r = save_for_web_with_writer(&mut s, ¶ms, &mut |path, bytes| {
|
||||
files.push((path.to_string(), bytes.to_vec()));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(files.len(), 1);
|
||||
assert_eq!(files[0].0, "download.png");
|
||||
assert_eq!(r["files"], json!(["download.png"]));
|
||||
assert_eq!(r["bytes"].as_u64(), Some(files[0].1.len() as u64));
|
||||
let img = photocraft_codecs::decode(&files[0].1).unwrap().convert(photocraft_codecs::ChannelLayout::Rgba, photocraft_codecs::SampleType::U8);
|
||||
assert_eq!(img.dimensions(), (32, 24), "{depth}-bit document");
|
||||
let i = (8 * 32 + 8) * 4;
|
||||
assert_eq!(&img.data()[i..i + 4], &[255, 0, 0, 255]);
|
||||
assert_eq!(s.file_menu.last_web.as_ref(), Some(¶ms));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn platform_writer_checks_authorization_before_dropping_floating_pixels() {
|
||||
let mut s = session(8);
|
||||
s.execute("select.rect", json!({"x": 8, "y": 8, "width": 4, "height": 4})).unwrap();
|
||||
s.execute("select.float", json!({"dx": 32})).unwrap();
|
||||
assert!(crate::float_cmds::floating(s.active().unwrap()).is_some());
|
||||
s.authorize = Some(|cmd, params| {
|
||||
assert_eq!(cmd, "file.export.saveForWebLegacy");
|
||||
assert_eq!(params["path"], "moved.png");
|
||||
Err(other("export denied"))
|
||||
});
|
||||
let params = json!({"format": "png24", "path": "moved.png"});
|
||||
let mut output = Vec::new();
|
||||
let denied = save_for_web_with_writer(&mut s, ¶ms, &mut |_, bytes| {
|
||||
output.extend_from_slice(bytes);
|
||||
Ok(())
|
||||
});
|
||||
assert!(denied.unwrap_err().to_string().contains("export denied"));
|
||||
assert!(output.is_empty());
|
||||
assert!(s.file_menu.last_web.is_none());
|
||||
assert!(crate::float_cmds::floating(s.active().unwrap()).is_some(), "denied export must not commit a floating move");
|
||||
|
||||
s.authorize = None;
|
||||
save_for_web_with_writer(&mut s, ¶ms, &mut |_, bytes| {
|
||||
output.extend_from_slice(bytes);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert!(crate::float_cmds::floating(s.active().unwrap()).is_none());
|
||||
let img = photocraft_codecs::decode(&output).unwrap().convert(photocraft_codecs::ChannelLayout::Rgba, photocraft_codecs::SampleType::U8);
|
||||
let old = (10 * 64 + 10) * 4;
|
||||
let moved = (10 * 64 + 42) * 4;
|
||||
assert_eq!(img.data()[old + 3], 0, "the selected pixels left their original position");
|
||||
assert_eq!(&img.data()[moved..moved + 4], &[255, 0, 0, 255], "the download contains the moved pixels");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn platform_writer_receives_slices_spacer_and_html_with_sibling_references() {
|
||||
let mut s = session(8);
|
||||
s.execute("slice.new", json!({"rect": [8, 8, 24, 24], "name": "logo", "alt": "Logo"})).unwrap();
|
||||
s.execute("slice.new", json!({"rect": [40, 0, 24, 20], "kind": "noImage", "cellText": "Hello & bye"})).unwrap();
|
||||
let params = json!({"format": "png24", "dir": "downloads", "imagesFolder": "", "html": true});
|
||||
let mut files = std::collections::BTreeMap::new();
|
||||
let r = save_for_web_with_writer(&mut s, ¶ms, &mut |path, bytes| {
|
||||
assert!(files.insert(path.to_string(), bytes.to_vec()).is_none(), "each file is written once");
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let page = std::str::from_utf8(files.get(r["html"].as_str().unwrap()).unwrap()).unwrap();
|
||||
let images = r["files"].as_array().unwrap();
|
||||
assert_eq!(files.len(), images.len() + 2, "image slices, spacer and HTML all reach the writer");
|
||||
for path in images {
|
||||
let path = path.as_str().unwrap();
|
||||
let filename = path.strip_prefix("downloads/").unwrap();
|
||||
assert!(page.contains(&format!("src=\"{filename}\"")), "the HTML refers to its sibling {filename}");
|
||||
assert!(photocraft_codecs::decode(files.get(path).unwrap()).is_ok());
|
||||
}
|
||||
assert!(page.contains("src=\"spacer.gif\""));
|
||||
assert!(page.contains("Hello & bye"));
|
||||
assert_eq!(photocraft_codecs::decode(files.get("downloads/spacer.gif").unwrap()).unwrap().dimensions(), (1, 1));
|
||||
assert_eq!(photocraft_codecs::decode(files.get("downloads/logo.png").unwrap()).unwrap().dimensions(), (24, 24));
|
||||
assert_eq!(s.file_menu.last_web.as_ref(), Some(¶ms));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn platform_writer_failure_stops_export_and_preserves_saved_settings() {
|
||||
let mut s = session(8);
|
||||
let saved = json!({"format": "png24", "path": "saved.png"});
|
||||
save_for_web_with_writer(&mut s, &saved, &mut |_, _| Ok(())).unwrap();
|
||||
s.execute("slice.new", json!({"rect": [8, 8, 24, 24], "name": "logo"})).unwrap();
|
||||
let mut attempts = 0;
|
||||
let failed = save_for_web_with_writer(&mut s, &json!({"format": "gif", "dir": "downloads", "html": true}), &mut |_, _| {
|
||||
attempts += 1;
|
||||
if attempts == 2 { Err(other("download failed")) } else { Ok(()) }
|
||||
});
|
||||
assert!(failed.unwrap_err().to_string().contains("download failed"));
|
||||
assert_eq!(attempts, 2, "no later slice, spacer or HTML should be written after failure");
|
||||
assert_eq!(s.file_menu.last_web.as_ref(), Some(&saved));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn estimates_every_format_at_every_depth() {
|
||||
for depth in [8, 16, 32] {
|
||||
|
||||
@@ -177,17 +177,19 @@ fn b(f: &Map<String, Value>, k: &str, d: bool) -> bool {
|
||||
// ---------- Save for Web ----------
|
||||
|
||||
const WEB_FORMATS: [(&str, &str); 5] = [("gif", "GIF"), ("png8", "PNG-8"), ("png24", "PNG-24"), ("jpeg", "JPEG"), ("wbmp", "WBMP")];
|
||||
const WEB_COMMAND: &str = "file.export.saveForWebLegacy";
|
||||
|
||||
pub fn open_web(app: &mut PhotocraftApp) -> u64 {
|
||||
let mut f = Map::new();
|
||||
f.insert("__web".into(), json!(true));
|
||||
f.insert("__command".into(), json!(WEB_COMMAND));
|
||||
f.insert("__label".into(), json!("Save for Web (Legacy)"));
|
||||
f.insert("__view".into(), json!("2up"));
|
||||
// Start from the last settings, like Photoshop.
|
||||
// Remember encoding choices, but each document starts at its own full size.
|
||||
let last = app.session.file_menu.last_web.clone().unwrap_or_else(|| json!({"format": "jpeg", "quality": 60}));
|
||||
if let Value::Object(m) = last {
|
||||
for (k, v) in m {
|
||||
if !matches!(k.as_str(), "path" | "dir") {
|
||||
if !matches!(k.as_str(), "path" | "dir" | "width" | "height" | "percent") {
|
||||
f.insert(k, v);
|
||||
}
|
||||
}
|
||||
@@ -494,6 +496,16 @@ fn web_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<String, Valu
|
||||
|
||||
fn web_confirm(app: &mut PhotocraftApp, f: &Map<String, Value>) -> Result<Value, String> {
|
||||
let mut p = params(f);
|
||||
// Check while the control/input policy is still installed, before an asynchronous picker
|
||||
// can outlive the request. A browser download uses the interactive platform writer.
|
||||
if let Some(authorize) = app.session.authorize.or(if app.automation_input { app.services.automation_authorize } else { None }) {
|
||||
authorize(WEB_COMMAND, &p).map_err(|e| e.to_string())?;
|
||||
}
|
||||
if app.automation_input
|
||||
&& let Some(authorize) = app.services.automation_command.as_ref()
|
||||
{
|
||||
authorize(WEB_COMMAND, &p)?;
|
||||
}
|
||||
if p.get("path").is_some() || p.get("dir").is_some() {
|
||||
return save_for_web(app, p);
|
||||
}
|
||||
@@ -518,11 +530,30 @@ fn web_confirm(app: &mut PhotocraftApp, f: &Map<String, Value>) -> Result<Value,
|
||||
|
||||
/// Runs Save for Web with `p`, which says where to write.
|
||||
fn save_for_web(app: &mut PhotocraftApp, p: Value) -> Result<Value, String> {
|
||||
let r = app.run("file.export.saveForWebLegacy", p)?;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let result = download_for_web(app, p);
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let result = app.run(WEB_COMMAND, p);
|
||||
let r = result.inspect_err(|error| {
|
||||
app.ui.status = error.clone();
|
||||
app.ui.status_error = true;
|
||||
})?;
|
||||
app.sync_views();
|
||||
app.ui.status = format!("Saved for Web: {} file(s)", r["files"].as_array().map_or(0, Vec::len));
|
||||
app.ui.status_error = false;
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
#[cfg(any(test, target_arch = "wasm32"))]
|
||||
fn download_for_web(app: &mut PhotocraftApp, mut p: Value) -> Result<Value, String> {
|
||||
// Browser downloads have no directory hierarchy. Keep the HTML's image and spacer URLs
|
||||
// beside the downloaded page, matching the names handed to the platform service.
|
||||
p["imagesFolder"] = json!("");
|
||||
let write = app.services.write.as_mut().ok_or("no download service")?;
|
||||
web_cmds::save_for_web_with_writer(&mut app.session, &p, &mut |path, bytes| write(path, bytes).map_err(photocraft_engine::EngineError::Other))
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
// ---------- Print ----------
|
||||
|
||||
pub fn open_print(app: &mut PhotocraftApp) -> u64 {
|
||||
@@ -759,6 +790,83 @@ mod tests {
|
||||
assert!(!d.fields.contains_key("path"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_for_web_starts_at_the_current_document_size() {
|
||||
let (mut app, _) = app();
|
||||
let path = std::env::temp_dir().join(format!("pc-webui-size-{}.png", std::process::id())).to_string_lossy().into_owned();
|
||||
app.run("file.export.saveForWebLegacy", json!({"path": path, "format": "png24", "width": 60, "height": 40, "percent": 50})).unwrap();
|
||||
app.run("file.new", json!({"width": 240, "height": 160, "name": "next"})).unwrap();
|
||||
let id = open_web(&mut app);
|
||||
let f = &app.ui.dialog_mut(id).unwrap().fields;
|
||||
assert_eq!(f["format"], "png24");
|
||||
assert_eq!(f["percent"], 100.0);
|
||||
assert!(!f.contains_key("width"));
|
||||
assert!(!f.contains_key("height"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_for_web_downloads_images_and_html_through_the_platform_writer() {
|
||||
let (mut app, _) = app();
|
||||
let downloads = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
|
||||
let captured = downloads.clone();
|
||||
app.services.write = Some(Box::new(move |path, bytes| {
|
||||
captured.borrow_mut().push((path.to_string(), bytes.to_vec()));
|
||||
Ok(())
|
||||
}));
|
||||
download_for_web(&mut app, json!({"path": "web.png", "format": "png24"})).unwrap();
|
||||
assert_eq!(downloads.borrow()[0].0, "web.png");
|
||||
assert!(downloads.borrow()[0].1.starts_with(b"\x89PNG\r\n\x1a\n"));
|
||||
downloads.borrow_mut().clear();
|
||||
|
||||
app.run("slice.new", json!({"rect": [0, 0, 60, 80], "name": "left"})).unwrap();
|
||||
download_for_web(&mut app, json!({"dir": ".", "format": "png24", "html": true, "imagesFolder": "images"})).unwrap();
|
||||
let files = downloads.borrow();
|
||||
let html = std::str::from_utf8(&files.iter().find(|(path, _)| path.ends_with(".html")).unwrap().1).unwrap();
|
||||
assert!(!html.contains("images/"), "downloaded files are siblings, not an images directory");
|
||||
for (path, bytes) in files.iter().filter(|(path, _)| !path.ends_with(".html")) {
|
||||
let name = std::path::Path::new(path).file_name().unwrap().to_str().unwrap();
|
||||
assert!(html.contains(&format!("src=\"{name}\"")), "missing downloaded image {name}");
|
||||
assert!(!bytes.is_empty());
|
||||
}
|
||||
assert!(files.iter().any(|(path, _)| path.ends_with("spacer.gif")));
|
||||
drop(files);
|
||||
|
||||
app.services.write = Some(Box::new(|_, _| Err("download failed".into())));
|
||||
assert_eq!(download_for_web(&mut app, json!({"path": "fail.png", "format": "png24"})).unwrap_err(), "download failed");
|
||||
app.services.write = None;
|
||||
assert_eq!(download_for_web(&mut app, json!({"path": "missing.png"})).unwrap_err(), "no download service");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_for_web_authorizes_before_opening_a_picker() {
|
||||
fn deny(_: &str, _: &Value) -> photocraft_engine::Result<()> {
|
||||
Err(photocraft_engine::EngineError::Other("export denied".into()))
|
||||
}
|
||||
for explicit_path in [false, true] {
|
||||
for synthetic_input in [false, true] {
|
||||
let (mut app, ctx) = app();
|
||||
let id = open_web(&mut app);
|
||||
if explicit_path {
|
||||
app.ui.dialog_mut(id).unwrap().fields.insert("path".into(), json!("denied.png"));
|
||||
}
|
||||
app.services.automation_authorize = Some(deny);
|
||||
app.services.file_dialog = Some(Box::new(|_, _, _| panic!("denied export must not show a picker")));
|
||||
app.services.write = Some(Box::new(|_, _| panic!("denied export must not write")));
|
||||
let error = if synthetic_input {
|
||||
app.automation_input = true;
|
||||
crate::dialogs::confirm(&mut app, id).unwrap_err()
|
||||
} else {
|
||||
let (request, _) = crate::control::ControlRequest::new("ui.dialog.confirm", json!({"dialog": id}));
|
||||
let crate::control::Outcome::Done(reply) = crate::control::handle(&mut app, &ctx, &request) else { panic!("expected immediate denial") };
|
||||
assert_eq!(reply["ok"], false);
|
||||
reply["error"].as_str().unwrap().to_string()
|
||||
};
|
||||
assert_eq!(error, "export denied");
|
||||
assert!(!app.file_dialog_open());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn print_dialog_and_toggles() {
|
||||
let (mut app, ctx) = app();
|
||||
|
||||
Reference in new issue
Block a user