diff --git a/crates/engine/src/cmd/web_cmds.rs b/crates/engine/src/cmd/web_cmds.rs index 3bd4f5a6c3f..624250e5096 100644 --- a/crates/engine/src/cmd/web_cmds.rs +++ b/crates/engine/src/cmd/web_cmds.rs @@ -80,7 +80,7 @@ pub fn specs() -> Vec { "Save for Web (Legacy)…", &["File", "Export"], Some("Cmd+Alt+Shift+S"), - r##"{"preset":"GIF 128 Dithered|JPEG High|PNG-24|…"?,"format":"gif|png8|png24|jpeg|wbmp|webp"="png24","palette":"perceptual|selective|adaptive|restrictive|exact|systemMac|systemWindows|uniform"="selective","colors":2..256=256,"colorTable":["#rrggbb",…]? (fixed opaque source palette, 1–256 entries; 255 with transparency),"colorTableEdits":{"0":"#rrggbb",…}? (replace entries after indexing; requires colorTable),"dither":"none|diffusion|pattern|noise"="diffusion","ditherAmount":0..100=88,"transparency":bool=true,"matte":"#rrggbb|none"="none" (a preset's own: white; formats without transparency go over white),"interlaced":bool=false,"webSnap":0..100=0,"quality":0..100=60 (JPEG, lossy WebP),"lossless":bool=false (WebP),"progressive":bool=false,"optimized":bool=true,"embedIcc":bool=false,"metadata":"none|copyright|copyrightAndContact|allExceptCameraInfo|all"="copyright" (EXIF only with all),"convertToSrgb":bool=true,"width"|"height"|"percent"? (image size),"resample":"bicubic|bilinear|nearest"?,"path":file? (whole image),"folder":folder? (whole image, named after the document; ignored with "path" or "dir"),"dir":folder? (one file per slice in images/),"imagesFolder":relative-folder?="images","html":bool=false,"trustedSliceHtml":bool=false (only for trusted documents; emit raw no-image cell HTML),"slices":"all|user"="all","numbers":[n]?} → no path/dir: {bytes,width,height,colors,colorTable,transparentIndex} estimate; else {files, html, bytes, warnings}"##, + r##"{"preset":"GIF 128 Dithered|JPEG High|PNG-24|…"?,"format":"gif|png8|png24|jpeg|wbmp|webp"="png24","palette":"perceptual|selective|adaptive|restrictive|exact|systemMac|systemWindows|uniform"="selective","colors":2..256=256,"colorTable":["#rrggbb",…]? (fixed opaque source palette, 1–256 entries; 255 with transparency),"colorTableEdits":{"0":"#rrggbb",…}? (replace entries after indexing; requires colorTable),"dither":"none|diffusion|pattern|noise"="diffusion","ditherAmount":0..100=88,"transparency":bool=true,"matte":"#rrggbb|none"="none" (a preset's own: white; formats without transparency go over white),"interlaced":bool=false,"webSnap":0..100=0,"quality":0..100=60 (JPEG, lossy WebP),"lossless":bool=false (WebP),"progressive":bool=false,"optimized":bool=true,"embedIcc":bool=false,"metadata":"none|copyright|copyrightAndContact|allExceptCameraInfo|all"="copyright" (EXIF only with all),"convertToSrgb":bool=true,"width"|"height"|"percent"? (image size),"resample":"bicubic|bilinear|nearest"?,"path":file? (whole image),"folder":folder? (whole image, named after the document; ignored with "path" or "dir"),"dir":folder? (one file per slice in images/),"imagesFolder":relative-folder?="images","html":bool=false,"trustedSliceHtml":bool=false (only for trusted documents; emit raw no-image cell HTML),"slices":"all|user|selected"="all" (selected requires numbers when the document has slices),"numbers":[n]? (slice numbers, each an existing slice; chooses the slices whatever the mode; with `path` or `folder` alone on a document with slices, refused: use `dir`)} → no path/dir: {bytes,width,height,colors,colorTable,transparentIndex} estimate; else {files, html, bytes, warnings}"##, has_doc, save_for_web ), diff --git a/crates/engine/src/cmd/web_cmds/save_web.rs b/crates/engine/src/cmd/web_cmds/save_web.rs index cac6a15e5c0..af655df8d70 100644 --- a/crates/engine/src/cmd/web_cmds/save_web.rs +++ b/crates/engine/src/cmd/web_cmds/save_web.rs @@ -167,6 +167,57 @@ fn remember_web_settings(s: &mut Session, cmd: &str, settings: &Value) { }); } +/// Which slices an export writes. +enum SlicePick { + All, + User, + Numbers(Vec), +} + +/// The slices chosen by `slices` (`all|user|selected`) and `numbers`. Photoshop's dialog can +/// only select slices it shows, so a script naming one that doesn't exist, an unknown mode, or +/// Selected Slices with nothing selected is refused rather than exporting too few or too many +/// files. A document without slices is one image whatever the mode, as in the dialog. +fn slice_pick(p: &Value, cmd: &str, doc: &photocraft_doc::Document) -> Result { + let mode = match p.get("slices") { + None | Some(Value::Null) => "all", + Some(Value::String(m)) if matches!(m.as_str(), "all" | "user" | "selected") => m.as_str(), + Some(v) => return Err(bad(cmd, format!("unknown slices `{}` (all|user|selected)", v.as_str().map_or_else(|| v.to_string(), str::to_string)))), + }; + let Some(numbers) = p.get("numbers").filter(|v| !v.is_null()) else { + return match mode { + "selected" if !doc.slices.is_empty() => Err(bad(cmd, "no slices are selected: Selected Slices needs `numbers`")), + "user" => Ok(SlicePick::User), + _ => Ok(SlicePick::All), + }; + }; + let numbers: Vec = numbers + .as_array() + .filter(|a| !a.is_empty()) + .and_then(|a| a.iter().map(Value::as_u64).collect()) + .ok_or_else(|| bad(cmd, "numbers must be a list of slice numbers"))?; + let count = slices::resolve(doc).len(); + let mut missing: Vec = numbers.iter().copied().filter(|n| !(1..=count as u64).contains(n)).collect(); + missing.sort_unstable(); + missing.dedup(); + if !missing.is_empty() { + let list = missing.iter().map(u64::to_string).collect::>().join(", "); + let what = if missing.len() == 1 { "slice" } else { "slices" }; + return Err(bad(cmd, format!("no {what} numbered {list} (the document's slices are 1–{count})"))); + } + // `path` alone is the whole image in one file (with `slices` too, the slices go next to it): + // the chosen slices would be ignored, so a document with slices refuses it. + let given = |k: &str| p.get(k).and_then(Value::as_str).is_some_and(|v| !v.is_empty()); + if given("path") && !given("dir") && matches!(p.get("slices"), None | Some(Value::Null)) && count > 1 { + return Err(bad(cmd, "`path` writes the whole image as one file: to export the slices in `numbers`, use `dir`")); + } + // `folder` alone (#5305) is the whole image too, under the document's name. + if given("folder") && !given("path") && !given("dir") && count > 1 { + return Err(bad(cmd, "`folder` writes the whole image as one file: to export the slices in `numbers`, use `dir`")); + } + Ok(SlicePick::Numbers(numbers)) +} + fn save_for_web_impl(s: &mut Session, p: &Value, write: &mut dyn FnMut(&str, &[u8]) -> Result<()>, native_paths: bool) -> Result { let cmd = "file.export.saveForWebLegacy"; if let Some(authorize) = s.authorize { @@ -174,6 +225,8 @@ fn save_for_web_impl(s: &mut Session, p: &Value, write: &mut dyn FnMut(&str, &[u } // Settings are checked first, so a refused export leaves a floating selection where it is. let st = WebSettings::from_params(p, cmd)?; + // So are the slices: committing a floating move doesn't change them. + let pick = slice_pick(p, cmd, &s.active().ok_or(EngineError::NoDocument)?.doc)?; // 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)?; @@ -191,16 +244,12 @@ fn save_for_web_impl(s: &mut Session, p: &Value, write: &mut dyn FnMut(&str, &[u let dpi = wdoc.resolution_dpi; let warnings = web_warnings(&st, exif, dpi); let all = slices::resolve(&doc); - let pick = p.get("slices").and_then(Value::as_str).unwrap_or("all"); - let numbers: Option> = p.get("numbers").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_u64).collect()); - let chosen: Vec<&ResolvedSlice> = all - .iter() - .filter(|r| match (&numbers, pick) { - (Some(n), _) => n.contains(&(r.number as u64)), - (None, "user") => r.origin != photocraft_doc::SliceOrigin::Auto, - _ => true, - }) - .collect(); + let picked = |r: &ResolvedSlice| match &pick { + SlicePick::Numbers(n) => n.contains(&(r.number as u64)), + SlicePick::User => r.origin != photocraft_doc::SliceOrigin::Auto, + SlicePick::All => true, + }; + let chosen: Vec<&ResolvedSlice> = all.iter().filter(|r| picked(r)).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()); // `folder` (with no `path` or `dir`): the whole image into that folder under the document's @@ -265,13 +314,20 @@ fn save_for_web_impl(s: &mut Session, p: &Value, write: &mut dyn FnMut(&str, &[u }; // Slices never overlap here: one covered by later slices comes as its visible pieces (see // `slices::resolve`), each its own image and cell, as Photoshop's subslices. A no-image cell's - // text goes into its first piece only. + // text goes into its first piece only. In the HTML, a slice that isn't exported stays as an + // empty cell, so the exported ones keep their place in the table. let mut texted = std::collections::HashSet::new(); - for r in &chosen { + for r in &all { let piece = scale_rect(r.rect, sx, sy).intersect(&wdoc.bounds()); if piece.is_empty() { continue; } + if !picked(r) { + if html { + cells.push((piece, String::new(), String::new())); + } + continue; + } let stored = r.id.and_then(|id| doc.slices.get(id)); if r.kind == SliceKind::NoImage { let text = stored diff --git a/crates/engine/src/cmd/web_cmds/tests.rs b/crates/engine/src/cmd/web_cmds/tests.rs index e887b929300..82c2a6c5a98 100644 --- a/crates/engine/src/cmd/web_cmds/tests.rs +++ b/crates/engine/src/cmd/web_cmds/tests.rs @@ -1417,3 +1417,169 @@ fn folder_saves_under_the_documents_own_name() { assert_eq!(r["files"], json!([format!("{dir}/named.png")])); let _ = std::fs::remove_dir_all(&dir); } + +#[test] +fn selected_slices_keep_their_place_in_the_html_table() { + // CodeRabbit review on PR #10557: exporting only the right of two slices put its image in + // the table's first column, on the left. Unexported slices stay as empty cells. + let dir = tmp("selected-html"); + let mut s = session(8); + s.execute("slice.new", json!({"rect": [0, 0, 32, 48], "name": "left"})).unwrap(); + s.execute("slice.new", json!({"rect": [32, 0, 32, 48], "name": "right"})).unwrap(); + let right = photocraft_doc::slices::resolve(&s.active().unwrap().doc).iter().find(|r| r.name == "right").unwrap().number; + let r = s.execute("file.export.saveForWebLegacy", json!({"format": "png24", "dir": dir, "html": true, "numbers": [right]})).unwrap(); + let files: Vec<&str> = r["files"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().rsplit('/').next().unwrap()).collect(); + assert_eq!(files, ["right.png"]); + let page = std::fs::read_to_string(r["html"].as_str().unwrap()).unwrap(); + let row = &page[page.find("").unwrap()..page.find("").unwrap()]; + let cells: Vec<&str> = row.split("= 2, "{row}"); + assert!(!cells[0].contains("images/right.png"), "the right slice is in column 0:\n{row}"); + assert!(cells[1].contains("images/right.png"), "column 1:\n{row}"); +} + +/// Two side-by-side user slices, `left` and `right`, and their numbers. +fn two_slices() -> (Session, u64, u64) { + let mut s = session(8); + s.execute("slice.new", json!({"rect": [0, 0, 32, 48], "name": "left"})).unwrap(); + s.execute("slice.new", json!({"rect": [32, 0, 32, 48], "name": "right"})).unwrap(); + let all = photocraft_doc::slices::resolve(&s.active().unwrap().doc); + let number = |name: &str| all.iter().find(|r| r.name == name).unwrap().number as u64; + (s, number("left"), number("right")) +} + +/// A refused slice export writes and remembers nothing, and (called directly, as the platform +/// writer is) leaves a floating move in place. +fn assert_refused(s: &mut Session, dir: &str, p: Value, expect: &str) { + s.execute("select.rect", json!({"x": 8, "y": 8, "width": 4, "height": 4})).unwrap(); + s.execute("select.float", json!({"dx": 32})).unwrap(); + let mut written = Vec::new(); + let err = save_for_web_with_writer(s, &p, &mut |path, _| { + written.push(path.to_string()); + Ok(()) + }) + .unwrap_err() + .to_string(); + assert!(err.contains(expect), "{p}: {err}"); + assert_eq!(written, Vec::::new(), "{p}: nothing written"); + assert!(s.file_menu.last_web.is_none(), "{p}: nothing remembered"); + assert!(crate::float_cmds::floating(s.active().unwrap()).is_some(), "{p}: the floating move is not committed"); + let err = s.execute("file.export.saveForWebLegacy", p.clone()).unwrap_err().to_string(); + assert!(err.contains(expect), "{p}: {err}"); + assert_eq!(std::fs::read_dir(dir).unwrap().count(), 0, "{p}: nothing written"); +} + +#[test] +fn slice_numbers_that_do_not_exist_are_refused() { + // FredApps review on PR #10557: a number naming no slice was dropped, so an export of only + // missing numbers "succeeded" with no files and a page of empty cells. Photoshop's dialog + // can only select existing slices; a script naming others is refused. + let dir = tmp("missing-numbers"); + let (mut s, left, right) = two_slices(); + let count = photocraft_doc::slices::resolve(&s.active().unwrap().doc).len() as u64; + let (gone, also_gone) = (count + 1, count + 7); + assert_refused(&mut s, &dir, json!({"format": "png24", "dir": dir, "html": true, "numbers": [gone]}), &format!("no slice numbered {gone}")); + // Partly missing: the dialog builds `numbers` from slices it shows, so every number it sends + // exists; one that doesn't is a stale or mistyped script and the export is refused whole. + let err = s + .execute("file.export.saveForWebLegacy", json!({"format": "png24", "dir": dir, "html": true, "numbers": [left, also_gone, right, gone]})) + .unwrap_err() + .to_string(); + assert!(err.contains(&format!("no slices numbered {gone}, {also_gone}")), "{err}"); + assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0, "nothing written"); + // Slice numbers start at 1. + let err = s.execute("file.export.saveForWebLegacy", json!({"format": "png24", "dir": dir, "numbers": [0]})).unwrap_err().to_string(); + assert!(err.contains("no slice numbered 0"), "{err}"); + // Existing numbers still export exactly those slices. + let r = s.execute("file.export.saveForWebLegacy", json!({"format": "png24", "dir": dir, "numbers": [right, left]})).unwrap(); + let mut files: Vec<&str> = r["files"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().rsplit('/').next().unwrap()).collect(); + files.sort_unstable(); + assert_eq!(files, ["left.png", "right.png"]); +} + +#[test] +fn slice_modes_are_validated() { + // FredApps review on PR #10557: any `slices` value but "user" exported every slice, + // including the dialog's "selected" without `numbers`. + let dir = tmp("slice-modes"); + let (mut s, left, right) = two_slices(); + for (p, expect) in [ + (json!({"slices": "selcted"}), "unknown slices `selcted` (all|user|selected)"), + (json!({"slices": 2}), "unknown slices `2` (all|user|selected)"), + (json!({"slices": "selected"}), "no slices are selected"), + (json!({"slices": "selected", "numbers": []}), "numbers must be a list of slice numbers"), + (json!({"numbers": ["1"]}), "numbers must be a list of slice numbers"), + (json!({"numbers": 1}), "numbers must be a list of slice numbers"), + ] { + let mut p = p; + p["format"] = json!("png24"); + p["dir"] = json!(dir); + assert_refused(&mut s, &dir, p, expect); + } + // Every valid call still works. + let count = photocraft_doc::slices::resolve(&s.active().unwrap().doc).len(); + let names = |r: &Value| r["files"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().rsplit('/').next().unwrap().to_string()).collect::>(); + for (mode, expect) in [(json!(null), count), (json!("all"), count), (json!("user"), 2)] { + let out = tmp("slice-modes-ok"); + let mut p = json!({"format": "png24", "dir": out}); + if !mode.is_null() { + p["slices"] = mode.clone(); + } + assert_eq!(names(&s.execute("file.export.saveForWebLegacy", p).unwrap()).len(), expect, "{mode}"); + } + let out = tmp("slice-modes-selected"); + let r = s.execute("file.export.saveForWebLegacy", json!({"format": "png24", "dir": out, "slices": "selected", "numbers": [right]})).unwrap(); + assert_eq!(names(&r), ["right.png"]); + let r = s.execute("file.export.saveForWebLegacy", json!({"format": "png24", "dir": out, "slices": "user", "numbers": [left]})).unwrap(); + assert_eq!(names(&r), ["left.png"], "numbers choose the slices whatever the mode"); + // A document without slices exports the whole image as one, whatever the dialog's Slices + // choice: the dialog sends "selected" without numbers then (`web_params`). + let mut s = session(8); + for mode in ["all", "user", "selected"] { + let out = tmp("slice-modes-none"); + if mode != "user" { + let r = s.execute("file.export.saveForWebLegacy", json!({"format": "png24", "dir": out, "slices": mode})).unwrap(); + assert_eq!(names(&r), ["web.png"], "{mode}"); + assert_eq!(decode(r["files"][0].as_str().unwrap()).dimensions(), (64, 48), "{mode}"); + } + let path = format!("{out}/whole.png"); + s.execute("file.export.saveForWebLegacy", json!({"format": "png24", "path": path, "slices": mode})).unwrap(); + assert_eq!(decode(&path).dimensions(), (64, 48), "{mode}"); + } +} + +#[test] +fn a_whole_image_path_with_slice_numbers_is_refused() { + // CodeRabbit review on PR #10557: `path` alone writes the whole image as one file, so slice + // `numbers` with it were ignored and every slice came out in that file. It is refused; `dir` + // exports the chosen slices. + let dir = tmp("path-numbers"); + let (mut s, left, right) = two_slices(); + let path = format!("{dir}/web.png"); + assert_refused(&mut s, &dir, json!({"format": "png24", "path": path, "numbers": [right]}), "use `dir`"); + assert_refused(&mut s, &dir, json!({"format": "png24", "path": path, "dir": "", "numbers": [left, right]}), "use `dir`"); + // `folder` alone is the whole image under the document's name (#5305): refused the same way. + assert_refused(&mut s, &dir, json!({"format": "png24", "folder": dir, "numbers": [right]}), "use `dir`"); + // An explicit null `slices` is the default mode, as if absent. + assert_refused(&mut s, &dir, json!({"format": "png24", "path": path, "slices": null, "numbers": [right]}), "use `dir`"); + // Valid calls still work: `path` alone is the whole image; with `slices`, the chosen slices + // go next to it; `dir` with `numbers` writes those slices. + let r = s.execute("file.export.saveForWebLegacy", json!({"format": "png24", "path": path})).unwrap(); + assert_eq!(r["files"], json!([path])); + assert_eq!(decode(&path).dimensions(), (64, 48)); + let names = |r: &Value| r["files"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().rsplit('/').next().unwrap().to_string()).collect::>(); + let out = tmp("path-numbers-selected"); + let r = s + .execute("file.export.saveForWebLegacy", json!({"format": "png24", "path": format!("{out}/web.png"), "slices": "selected", "numbers": [right]})) + .unwrap(); + assert_eq!(names(&r), ["right.png"]); + let out = tmp("path-numbers-dir"); + let r = s.execute("file.export.saveForWebLegacy", json!({"format": "png24", "path": format!("{out}/web.png"), "dir": out, "numbers": [left]})).unwrap(); + assert_eq!(names(&r), ["left.png"]); + // A document without slices is one image: its only slice number is the whole image. + let mut s = session(8); + let out = tmp("path-numbers-none"); + let whole = format!("{out}/whole.png"); + s.execute("file.export.saveForWebLegacy", json!({"format": "png24", "path": whole, "numbers": [1]})).unwrap(); + assert_eq!(decode(&whole).dimensions(), (64, 48)); +} diff --git a/crates/ui-egui/src/dialogs/file_ui.rs b/crates/ui-egui/src/dialogs/file_ui.rs index c29299fd26f..f9d0af7258b 100644 --- a/crates/ui-egui/src/dialogs/file_ui.rs +++ b/crates/ui-egui/src/dialogs/file_ui.rs @@ -24,6 +24,8 @@ use print::{drag_print_position, driver_paper_is_wide, print_params, print_previ use print::{print_body, print_confirm}; pub use web::open_web; #[cfg(test)] +use web::web_params; +#[cfg(test)] use web::{WEB_COMMAND, WebCache, WebProxy, advance_preview, download_for_web, variants, web_frame_document}; use web::{web_body, web_confirm}; diff --git a/crates/ui-egui/src/dialogs/file_ui/tests.rs b/crates/ui-egui/src/dialogs/file_ui/tests.rs index 050e730bf58..8ddd093f4f4 100644 --- a/crates/ui-egui/src/dialogs/file_ui/tests.rs +++ b/crates/ui-egui/src/dialogs/file_ui/tests.rs @@ -1157,3 +1157,75 @@ fn a_turn_takes_the_printable_area_with_the_paper() { assert!(f.get("printable").is_none(), "{area}"); } } + +#[test] +fn the_web_preview_selects_slices_and_saves_only_the_selected_ones() { + // A 120 × 80 document with a user slice on its left half; the right half is auto slice 02. + let (mut app, _) = app(); + app.run("slice.new", json!({"rect": [0, 0, 60, 80], "name": "left"})).unwrap(); + let id = open_web(&mut app); + let fields = &mut app.ui.dialog_mut(id).unwrap().fields; + fields.insert("__view".into(), json!("optimized")); + fields.insert("format".into(), json!("png24")); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1600.0, 1100.0)).build_ui_state( + |ui, app| { + crate::color_picker_ui::widget_tick(app, ui.ctx()); + if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("semibold".into()))) { + crate::dialogs::show(app, ui.ctx()); + } + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, Default::default()); + h.run_steps(5); + let r = &h.state().ui.dialogs[0].fields["__previewRects"][0]; + let pane = egui::Rect::from_min_max( + egui::pos2(r[0].as_f64().unwrap() as f32, r[1].as_f64().unwrap() as f32), + egui::pos2(r[2].as_f64().unwrap() as f32, r[3].as_f64().unwrap() as f32), + ); + // The preview fits the document in the pane, centred. + let scale = (pane.width() / 120.0).min(pane.height() / 80.0); + let at = |x: f32, y: f32| pane.center() + egui::vec2(x - 60.0, y - 40.0) * scale; + let click = |h: &mut egui_kittest::Harness<'_, PhotocraftApp>, pos: egui::Pos2, modifiers: egui::Modifiers| { + // The window reports held modifiers as their own event as well as on the button events. + h.event(egui::Event::ModifiersChanged(modifiers)); + h.event(egui::Event::PointerMoved(pos)); + h.step(); + h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, modifiers }); + h.step(); + h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, modifiers }); + h.run_steps(2); + }; + let selected = |h: &egui_kittest::Harness<'_, PhotocraftApp>| h.state().ui.dialogs[0].fields.get("__selectedSlices").cloned(); + click(&mut h, at(30.0, 40.0), egui::Modifiers::NONE); + assert_eq!(selected(&h), Some(json!([1])), "a click selects the slice under the pointer"); + click(&mut h, at(90.0, 40.0), egui::Modifiers::SHIFT); + assert_eq!(selected(&h), Some(json!([1, 2])), "Shift-click adds a slice"); + click(&mut h, at(30.0, 40.0), egui::Modifiers::SHIFT); + assert_eq!(selected(&h), Some(json!([2])), "Shift-click on a selected slice removes it"); + // The view's own drag still pans rather than selecting. + assert_eq!(h.state().ui.dialogs[0].fields["__zoom"], json!(null)); + + let mut fields = h.state().ui.dialogs[0].fields.clone(); + fields.insert("slices".into(), json!("selected")); + let p = web_params(&fields, true).unwrap(); + assert_eq!(p["numbers"], json!([2])); + fields.insert("__selectedSlices".into(), json!([])); + assert!(web_params(&fields, true).is_err(), "Selected Slices with nothing selected is an error, not every slice"); + assert!(web_params(&fields, false).unwrap().get("numbers").is_none(), "a document without slices ignores the choice"); + + let mut app = h.into_state(); + let downloads = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); + let captured = downloads.clone(); + app.services.write = Some(Box::new(move |path, _| { + captured.borrow_mut().push(path.to_string()); + Ok(()) + })); + let mut p = p; + p["dir"] = json!("."); + p["html"] = json!(false); + download_for_web(&mut app, p).unwrap(); + let files = downloads.borrow(); + assert_eq!(files.len(), 1, "only the selected slice is saved: {files:?}"); + assert!(!files[0].contains("left"), "{files:?}"); +} diff --git a/crates/ui-egui/src/dialogs/file_ui/web.rs b/crates/ui-egui/src/dialogs/file_ui/web.rs index 12fc335b4ea..d8db1fee042 100644 --- a/crates/ui-egui/src/dialogs/file_ui/web.rs +++ b/crates/ui-egui/src/dialogs/file_ui/web.rs @@ -27,7 +27,7 @@ pub fn open_web(app: &mut PhotocraftApp) -> u64 { .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" | "folder" | "width" | "height" | "percent" | "colorTable" | "colorTableEdits") { + if !matches!(k.as_str(), "path" | "dir" | "folder" | "width" | "height" | "percent" | "colorTable" | "colorTableEdits" | "numbers") { f.insert(k, v); } } @@ -152,13 +152,14 @@ fn web_pane(app: &PhotocraftApp, ui: &mut egui::Ui, size: egui::Vec2, p: Option< }; ui.vertical(|ui| { ui.set_width(size.x); - let (r, response) = ui.allocate_exact_size((size - egui::vec2(0.0, 42.0)).max(egui::vec2(1.0, 1.0)), egui::Sense::drag()); + let (r, response) = ui.allocate_exact_size((size - egui::vec2(0.0, 42.0)).max(egui::vec2(1.0, 1.0)), egui::Sense::click_and_drag()); let response = response.on_hover_cursor(egui::CursorIcon::Grab); if let Some(rects) = f.get_mut("__previewRects").and_then(Value::as_array_mut) { rects.push(json!([r.left(), r.top(), r.right(), r.bottom()])); } crate::widgets::checker(ui.painter(), r, 8.0); - web_preview::paint(ui, r, &response, &tex, source_size, f); + let image = web_preview::paint(ui, r, &response, &tex, source_size, f); + web_preview::slices(ui, r, image, &response, &doc, crate::tools::slice_ui::slice_color(app), f); ui.painter().rect_stroke(r, 0.0, egui::Stroke::new(1.0, t.separator), egui::StrokeKind::Inside); let (l1, l2) = match (p, info) { (None, _) => ("Original".to_string(), format!("{} · {} × {} px", doc.name, doc.size.width, doc.size.height)), @@ -412,7 +413,15 @@ pub(super) fn web_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map) -> Re } Ok(()) }; - let mut p = params(f); + let has_slices = app.session.active().is_some_and(|st| !st.doc.slices.is_empty()); + let mut p = web_params(f, has_slices)?; authorize(&p)?; // Confirmation may follow a field edit without an intervening frame (Enter or automation). let mut fields = f.clone(); web_preview::prepare_table(app, &mut fields)?; - let prepared = params(&fields); + let prepared = web_params(&fields, has_slices)?; if prepared != p { // The policy must also approve the actual palette-bearing export parameters. authorize(&prepared)?; @@ -570,7 +580,6 @@ pub(super) fn web_confirm(app: &mut PhotocraftApp, f: &Map) -> Re return save_for_web(app, p); } let doc = app.session.active().ok_or("no document")?.doc.clone(); - let has_slices = !doc.slices.is_empty(); let html = b(f, "html", true); let st = WebSettings::from_params(&p, "file.export.saveForWebLegacy").map_err(|e| e.to_string())?; let base = photocraft_doc::slices::base_name(&doc); @@ -605,6 +614,20 @@ fn kept_name_folder(path: &str, base: &str, ext: &str) -> Option { kept.then(|| file.parent().map(|d| d.to_string_lossy().into_owned()).unwrap_or_default()) } +/// The export parameters: the fields, plus the numbers of the slices selected in the preview +/// when the document's slices are exported as Selected Slices. +pub(super) fn web_params(f: &Map, has_slices: bool) -> Result { + let mut p = params(f); + if has_slices && s(f, "slices", "all") == "selected" { + let numbers = web_preview::selected_slices(f); + if numbers.is_empty() { + return Err(tl!("No slices are selected. Click a slice in the preview to select it.").to_string()); + } + p["numbers"] = json!(numbers); + } + Ok(p) +} + /// Runs Save for Web with `p`, which says where to write. fn save_for_web(app: &mut PhotocraftApp, p: Value) -> Result { #[cfg(target_arch = "wasm32")] diff --git a/crates/ui-egui/src/dialogs/file_ui/web_preview.rs b/crates/ui-egui/src/dialogs/file_ui/web_preview.rs index c2bdd4ad110..41bcd77b0e9 100644 --- a/crates/ui-egui/src/dialogs/file_ui/web_preview.rs +++ b/crates/ui-egui/src/dialogs/file_ui/web_preview.rs @@ -230,7 +230,16 @@ pub fn controls(ui: &mut egui::Ui, f: &mut Map) { nav.write(f); } -pub fn paint(ui: &mut egui::Ui, rect: egui::Rect, response: &egui::Response, tex: &egui::TextureHandle, source: egui::Vec2, f: &mut Map) { +/// Paints the preview image in `rect` and returns where the whole image lies (it may extend +/// past `rect` when zoomed in). +pub fn paint( + ui: &mut egui::Ui, + rect: egui::Rect, + response: &egui::Response, + tex: &egui::TextureHandle, + source: egui::Vec2, + f: &mut Map, +) -> egui::Rect { let mut nav = Navigation::read(f); let ppp = ui.ctx().pixels_per_point(); if response.double_clicked() { @@ -267,6 +276,99 @@ pub fn paint(ui: &mut egui::Ui, rect: egui::Rect, response: &egui::Response, tex f.insert("__effectiveZoom".into(), json!(scale * ppp)); } nav.write(f); + image +} + +/// The numbers of the slices selected in the preview, in ascending order. +pub fn selected_slices(f: &Map) -> Vec { + let mut numbers: Vec = f.get("__selectedSlices").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_u64).collect()).unwrap_or_default(); + numbers.sort_unstable(); + numbers.dedup(); + numbers +} + +/// Draws the document's slices over a preview pane, as Photoshop's Save for Web does: user and +/// layer slices outlined in the slice colour, auto slices dashed, each with its number, and the +/// selected ones highlighted (#10548). A click selects the slice under the pointer and +/// Shift-click adds or removes one, like the dialog's Slice Select tool; the selection is the +/// `__selectedSlices` field, which Selected Slices exports. +pub fn slices( + ui: &egui::Ui, + rect: egui::Rect, + image: egui::Rect, + response: &egui::Response, + doc: &photocraft_doc::Document, + color: egui::Color32, + f: &mut Map, +) { + use photocraft_doc::SliceOrigin; + if doc.slices.is_empty() { + return; + } + let (dw, dh) = (doc.size.width.max(1) as f32, doc.size.height.max(1) as f32); + let to_screen = |r: photocraft_geom::Rect| { + let at = |x: i32, y: i32| image.min + egui::vec2(x as f32 / dw * image.width(), y as f32 / dh * image.height()); + egui::Rect::from_two_pos(at(r.x0, r.y0), at(r.x1, r.y1)) + }; + let all = photocraft_doc::slices::resolve(doc); + if response.clicked() + && let Some(pos) = response.interact_pointer_pos() + { + let hit = all.iter().find(|r| to_screen(r.rect).contains(pos)).map(|r| r.number as u64); + let mut selected = selected_slices(f); + match hit { + Some(n) if ui.input(|i| i.modifiers.shift) => { + if let Some(i) = selected.iter().position(|v| *v == n) { + selected.remove(i); + } else { + selected.push(n); + } + } + Some(n) => selected = vec![n], + None => {} + } + f.insert("__selectedSlices".into(), json!(selected)); + } + let selected = selected_slices(f); + let highlight = egui::Color32::from_rgb(0xff, 0xb0, 0x00); + let painter = ui.painter().with_clip_rect(rect.intersect(ui.clip_rect())); + // Auto slices first (dashed, underneath), then user and layer slices, then the selection. + for pass in 0..3 { + for r in &all { + let auto = r.origin == SliceOrigin::Auto; + let chosen = selected.contains(&(r.number as u64)); + if (pass == 0 && !auto) || (pass == 1 && auto) || (pass == 2 && !chosen) { + continue; + } + let sr = to_screen(r.rect); + match pass { + 0 => { + let pts = [sr.left_top(), sr.right_top(), sr.right_bottom(), sr.left_bottom(), sr.left_top()]; + painter.add(egui::Shape::dashed_line(&pts, egui::Stroke::new(1.0, color.gamma_multiply(0.7)), 3.0, 3.0)); + } + 1 => { + painter.rect_stroke(sr, 0.0, egui::Stroke::new(1.0, color), egui::StrokeKind::Inside); + } + _ => { + painter.rect_filled(sr, 0.0, highlight.gamma_multiply(0.12)); + painter.rect_stroke(sr, 0.0, egui::Stroke::new(2.0, highlight), egui::StrokeKind::Inside); + } + } + if pass < 2 && sr.width() > 18.0 && sr.height() > 12.0 { + let galley = painter.layout_no_wrap(format!("{:02}", r.number), egui::FontId::proportional(10.0), egui::Color32::WHITE); + let badge = egui::Rect::from_min_size(sr.left_top() + egui::vec2(2.0, 2.0), galley.size() + egui::vec2(6.0, 2.0)); + let bg = if chosen { + highlight + } else if auto { + egui::Color32::from_gray(110) + } else { + color + }; + painter.rect_filled(badge, 2.0, bg); + painter.galley(badge.min + egui::vec2(3.0, 1.0), galley, egui::Color32::WHITE); + } + } + } } #[cfg(test)] diff --git a/crates/ui-egui/src/tools/slice_ui.rs b/crates/ui-egui/src/tools/slice_ui.rs index f56e330f0ab..3be02a6d81d 100644 --- a/crates/ui-egui/src/tools/slice_ui.rs +++ b/crates/ui-egui/src/tools/slice_ui.rs @@ -229,6 +229,11 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, _mods: egui::Modifiers) - true } +/// The slice colour from Preferences › Guides, Grid & Slices. +pub fn slice_color(app: &PhotocraftApp) -> Color32 { + hex(&app.session.prefs().guides_grid_and_slices.slice_color, Color32::from_rgb(0x38, 0xb5, 0xff)) +} + fn hex(s: &str, fallback: Color32) -> Color32 { let s = s.trim_start_matches('#'); let b = |i: usize| s.get(i..i + 2).and_then(|h| u8::from_str_radix(h, 16).ok()); @@ -246,7 +251,7 @@ pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform return; } let prefs = &app.session.prefs().guides_grid_and_slices; - let color = hex(&prefs.slice_color, Color32::from_rgb(0x38, 0xb5, 0xff)); + let color = slice_color(app); let numbers = prefs.show_slice_numbers; let selected_color = Color32::from_rgb(0xff, 0xb0, 0x00); let to_screen = |r: photocraft_geom::Rect| Rect::from_two_pos(xf.to_screen(r.x0 as f32, r.y0 as f32), xf.to_screen(r.x1 as f32, r.y1 as f32));