Skip to content

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

Save for Web: Width, Height, Percent and Resample in Image Size, linked in proportion (#6388)

Marco Arnulfo562601eb476f
diff --git a/crates/ui-egui/src/export_dialog.rs b/crates/ui-egui/src/export_dialog.rs
index 275221e05..ba9fec469 100644
--- a/crates/ui-egui/src/export_dialog.rs
+++ b/crates/ui-egui/src/export_dialog.rs
@@ -271,14 +271,14 @@ fn scaled_size(w: f64, h: f64, scale: f64) -> (f64, f64) {
}
/// Largest side Export As will ask Image Size for. The same cap `image.imageSize` enforces.
-const MAX_PX: f64 = 300_000.0;
+pub(crate) const MAX_PX: f64 = 300_000.0;
/// Pixel size, percent scale and whether the two sides stay linked.
#[derive(Clone, Copy, Debug, PartialEq)]
-struct ExportSize {
- width: f64,
- height: f64,
- scale: f64,
+pub(crate) struct ExportSize {
+ pub(crate) width: f64,
+ pub(crate) height: f64,
+ pub(crate) scale: f64,
}
fn finite_px(v: f64) -> Result<f64, String> {
@@ -289,7 +289,7 @@ fn finite_px(v: f64) -> Result<f64, String> {
}
/// Percent scale applied to both sides. `scale` is a percent in 1..=1000.
-fn resize_from_scale(src_w: f64, src_h: f64, scale: f64) -> Result<ExportSize, String> {
+pub(crate) fn resize_from_scale(src_w: f64, src_h: f64, scale: f64) -> Result<ExportSize, String> {
if !scale.is_finite() || !(1.0..=1000.0).contains(&scale) {
return Err("scale must be within 1..=1000 percent".into());
}
@@ -301,7 +301,7 @@ fn resize_from_scale(src_w: f64, src_h: f64, scale: f64) -> Result<ExportSize, S
}
/// An edited side. With `lock`, the other side keeps the source aspect; otherwise it stays.
-fn resize_from_side(src_w: f64, src_h: f64, width: f64, height: f64, lock: bool, edited_width: bool) -> Result<ExportSize, String> {
+pub(crate) fn resize_from_side(src_w: f64, src_h: f64, width: f64, height: f64, lock: bool, edited_width: bool) -> Result<ExportSize, String> {
let src_w = src_w.max(1.0);
let src_h = src_h.max(1.0);
let (width, height) = if edited_width {
diff --git a/crates/ui-egui/src/file_ui.rs b/crates/ui-egui/src/file_ui.rs
index 32f97bc4e..d22c936cc 100644
--- a/crates/ui-egui/src/file_ui.rs
+++ b/crates/ui-egui/src/file_ui.rs
@@ -242,6 +242,7 @@ pub fn open_web(app: &mut PhotocraftApp) -> u64 {
("convertToSrgb", json!(true)),
("metadata", json!("copyright")),
("percent", json!(100.0)),
+ ("resample", json!("bicubic")),
("webSnap", json!(0)),
] {
f.entry(k.to_string()).or_insert(v);
@@ -284,7 +285,7 @@ fn web_pane(app: &PhotocraftApp, ui: &mut egui::Ui, size: egui::Vec2, p: Option<
let rev = st.revision;
// A bounded proxy; navigation never recomposites or re-encodes it.
let base = p.cloned().unwrap_or_else(|| json!({}));
- let size_sig = format!("{}|{}|{}|{}", base["percent"], base["width"], base["height"], base["convertToSrgb"]);
+ let size_sig = format!("{}|{}|{}|{}|{}", base["percent"], base["width"], base["height"], base["resample"], base["convertToSrgb"]);
let wkey = egui::Id::new(("web-proxy", doc.id.0, pane));
let proxy_sig = format!("{rev}|{frame:?}|{size_sig}");
let cached_proxy: Option<(String, WebProxy)> = ui.data(|d| d.get_temp(wkey));
@@ -302,8 +303,9 @@ fn web_pane(app: &PhotocraftApp, ui: &mut egui::Ui, size: egui::Vec2, p: Option<
let k = (2048.0 / fw.max(fh)).min(1.0);
let st = WebSettings::from_params(&base, "preview").unwrap_or_default();
let Ok(doc) = web_frame_document(&doc, frame) else { return };
+ let resample = web_preview::proxy_resample(&base, k);
let Ok((wd, _, _)) =
- web_cmds::web_document(&doc, &json!({"width": (fw * k).round().max(1.0), "height": (fh * k).round().max(1.0), "resample": "bilinear"}), &st)
+ web_cmds::web_document(&doc, &json!({"width": (fw * k).round().max(1.0), "height": (fh * k).round().max(1.0), "resample": resample}), &st)
else {
return;
};
@@ -628,13 +630,7 @@ fn web_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<String, Valu
}
ui.add_space(8.0);
ui.label(egui::RichText::new(tl!("Image Size")).font(crate::theme::semibold(12.0)).color(t.text));
- number(ui, f, "percent", tl!("Percent"), 1.0..=1000.0, "%", 100.0);
- let pct = n(f, "percent", 100.0) / 100.0;
- ui.label(
- egui::RichText::new(format!("W: {} px H: {} px", (f64::from(doc.size.width) * pct).round(), (f64::from(doc.size.height) * pct).round()))
- .color(t.text_dim)
- .size(11.5),
- );
+ web_size(ui, f, &doc);
let nslices = photocraft_doc::slices::resolve(&doc).len();
if !doc.slices.is_empty() {
ui.add_space(6.0);
@@ -647,6 +643,86 @@ fn web_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<String, Valu
});
}
+/// A size row in a two-column grid: the label, then a field showing `shown`. Returns the typed
+/// value when it changed, compared with the value the widget was given so a field that only
+/// clamps does not count as an edit.
+fn size_field(ui: &mut egui::Ui, label: &str, shown: f64, range: std::ops::RangeInclusive<f32>, unit: &str, decimals: u32) -> Option<f64> {
+ let t = Tokens::get(ui.ctx());
+ let passed = (shown as f32).clamp(*range.start(), *range.end());
+ let mut v = passed;
+ ui.label(egui::RichText::new(label).color(t.text_dim));
+ crate::widgets::value_field_prec(ui, &mut v, range, unit, 90.0, decimals);
+ ui.end_row();
+ (v != passed).then_some(f64::from(v))
+}
+
+/// Image Size, as in Photoshop's Save for Web: Width and Height linked in proportion (on at
+/// each opening), Percent and the resampling method. A side edit sets exact pixels and drops
+/// `percent`, which the engine would otherwise apply first; a Percent edit sets both sides.
+fn web_size(ui: &mut egui::Ui, f: &mut Map<String, Value>, doc: &photocraft_doc::Document) {
+ use crate::export_dialog::{MAX_PX, resize_from_scale, resize_from_side};
+ let (w0, h0) = (f64::from(doc.size.width).max(1.0), f64::from(doc.size.height).max(1.0));
+ let (w, h) = web_preview::dimensions(doc, &params(f)).unwrap_or((w0, h0));
+ let lock = b(f, "__constrain", true);
+ let pct = n(f, "percent", w / w0 * 100.0);
+ let write = |f: &mut Map<String, Value>, width: f64, height: f64| {
+ f.insert("width".into(), json!(width));
+ f.insert("height".into(), json!(height));
+ };
+ let max = MAX_PX as f32;
+ let (width, height, percent) = egui::Grid::new("web-size")
+ .num_columns(2)
+ .show(ui, |ui| {
+ (
+ size_field(ui, tl!("Width"), w, 1.0..=max, "px", 0),
+ size_field(ui, tl!("Height"), h, 1.0..=max, "px", 0),
+ size_field(ui, tl!("Percent"), pct, 1.0..=1000.0, "%", 2),
+ )
+ })
+ .inner;
+ let side = match (width, height) {
+ (Some(v), _) => resize_from_side(w0, h0, v.round(), h, lock, true).ok(),
+ (_, Some(v)) => resize_from_side(w0, h0, w, v.round(), lock, false).ok(),
+ _ => None,
+ };
+ if let Some(size) = side {
+ f.remove("percent");
+ write(f, size.width, size.height);
+ } else if let Some(v) = percent
+ && let Ok(size) = resize_from_scale(w0, h0, v)
+ {
+ f.insert("percent".into(), json!(size.scale));
+ write(f, size.width, size.height);
+ }
+ let mut linked = lock;
+ if crate::widgets::checkbox(ui, &mut linked, tl!("Constrain proportions")).changed() {
+ f.insert("__constrain".into(), json!(linked));
+ // Linked again, the height follows the width in the document's proportions.
+ if linked && let Ok(size) = resize_from_side(w0, h0, w, h, true, true) {
+ f.remove("percent");
+ write(f, size.width, size.height);
+ }
+ }
+ ui.horizontal(|ui| {
+ ui.label(egui::RichText::new(tl!("Resample")).color(Tokens::get(ui.ctx()).text_dim));
+ // Photoshop's Save for Web list, in its order.
+ dropdown_str(
+ ui,
+ "web-resample",
+ f,
+ "resample",
+ &[
+ ("nearest", tl!("Nearest Neighbor (hard edges)")),
+ ("bilinear", tl!("Bilinear")),
+ ("bicubic", tl!("Bicubic (smooth gradients)")),
+ ("bicubicSmoother", tl!("Bicubic Smoother (enlargement)")),
+ ("bicubicSharper", tl!("Bicubic Sharper (reduction)")),
+ ],
+ 170.0,
+ );
+ });
+}
+
fn web_confirm(app: &mut PhotocraftApp, f: &Map<String, Value>) -> Result<Value, String> {
// 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.
@@ -1309,6 +1385,98 @@ mod tests {
assert!(!f.contains_key("height"));
}
+ /// Save for Web's Image Size on a 120 x 80 document, as a PNG-24 (no other number fields).
+ fn web_size_dialog(app: PhotocraftApp) -> (egui_kittest::Harness<'static, PhotocraftApp>, u64) {
+ let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1600.0, 1100.0)).build_ui_state(
+ |ui, app: &mut PhotocraftApp| {
+ 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());
+ let id = open_web(h.state_mut());
+ h.state_mut().ui.dialog_mut(id).unwrap().fields.insert("format".into(), json!("png24"));
+ h.run_steps(5);
+ (h, id)
+ }
+
+ /// Types `text` into the number field now showing `value`, and leaves it with Tab.
+ fn type_into_field(h: &mut egui_kittest::Harness<'static, PhotocraftApp>, value: f64, text: &str) {
+ use egui_kittest::kittest::{NodeT, Queryable};
+ let field = h
+ .query_all_by_role(egui::accesskit::Role::SpinButton)
+ .find(|n| n.accesskit_node().numeric_value() == Some(value))
+ .map(|n| n.rect())
+ .expect("a field showing the value");
+ h.hover_at(field.center());
+ h.run_steps(1);
+ h.drag_at(field.center());
+ h.run_steps(1);
+ h.drop_at(field.center());
+ h.run_steps(2);
+ h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
+ h.event(egui::Event::Text(text.into()));
+ h.run_steps(1);
+ h.key_press(egui::Key::Tab);
+ h.run_steps(3);
+ }
+
+ /// #6388: Save for Web's Image Size has Width and Height linked in proportion, as in
+ /// Photoshop. A typed width sets the height, the file comes out at that size, and the
+ /// document itself is never resized.
+ #[test]
+ fn save_for_web_width_keeps_proportions_and_sizes_the_file() {
+ let (app, _) = app();
+ let (mut h, id) = web_size_dialog(app);
+ let revision = h.state().session.active().unwrap().revision;
+ type_into_field(&mut h, 120.0, "60");
+ let f = h.state().ui.dialogs[0].fields.clone();
+ assert_eq!((f["width"].as_f64(), f["height"].as_f64()), (Some(60.0), Some(40.0)), "{f:?}");
+ // Unlinked, the height changes alone; linked again, it follows the width.
+ {
+ use egui_kittest::kittest::Queryable;
+ h.get_by_label("Constrain proportions").click();
+ h.run_steps(3);
+ type_into_field(&mut h, 40.0, "50");
+ let f = h.state().ui.dialogs[0].fields.clone();
+ assert_eq!((f["width"].as_f64(), f["height"].as_f64()), (Some(60.0), Some(50.0)), "{f:?}");
+ h.get_by_label("Constrain proportions").click();
+ h.run_steps(3);
+ }
+ let f = h.state().ui.dialogs[0].fields.clone();
+ assert_eq!((f["width"].as_f64(), f["height"].as_f64(), f.get("__constrain")), (Some(60.0), Some(40.0), Some(&json!(true))), "{f:?}");
+ let path = std::env::temp_dir().join(format!("pc-webui-wh-{}.png", std::process::id())).to_string_lossy().into_owned();
+ h.state_mut().ui.dialog_mut(id).unwrap().fields.insert("path".into(), json!(path));
+ let r = crate::dialogs::confirm(h.state_mut(), id).unwrap();
+ assert_eq!((r["width"].as_u64(), r["height"].as_u64()), (Some(60), Some(40)), "{r}");
+ let st = h.state().session.active().unwrap();
+ assert_eq!((st.revision, st.doc.size), (revision, photocraft_doc::Size::new(120, 80)));
+ }
+
+ /// Reopened on another document, Save for Web starts at that document's full size again
+ /// (#1857) but keeps the resampling method, like the other encoding choices.
+ #[test]
+ fn save_for_web_reopens_at_full_size_with_the_resample_method() {
+ let (app, _) = app();
+ let (mut h, id) = web_size_dialog(app);
+ type_into_field(&mut h, 120.0, "60");
+ let path = std::env::temp_dir().join(format!("pc-webui-reopen-{}.png", std::process::id())).to_string_lossy().into_owned();
+ let d = h.state_mut().ui.dialog_mut(id).unwrap();
+ d.fields.insert("resample".into(), json!("nearest"));
+ d.fields.insert("path".into(), json!(path));
+ crate::dialogs::confirm(h.state_mut(), id).unwrap();
+ h.state_mut().run("file.new", json!({"width": 240, "height": 160, "name": "next"})).unwrap();
+ let id = open_web(h.state_mut());
+ h.run_steps(3);
+ let f = h.state().ui.dialogs.iter().find(|d| d.id == id).unwrap().fields.clone();
+ assert_eq!(f["resample"], "nearest");
+ assert!(!f.contains_key("width") && !f.contains_key("height"), "{f:?}");
+ let p = web_preview::dimensions(&h.state().session.active().unwrap().doc, &params(&f)).unwrap();
+ assert_eq!(p, (240.0, 160.0));
+ }
+
#[test]
fn save_for_web_downloads_images_and_html_through_the_platform_writer() {
let (mut app, _) = app();
diff --git a/crates/ui-egui/src/file_ui/web_preview.rs b/crates/ui-egui/src/file_ui/web_preview.rs
index b60358457..02cf44cb6 100644
--- a/crates/ui-egui/src/file_ui/web_preview.rs
+++ b/crates/ui-egui/src/file_ui/web_preview.rs
@@ -18,6 +18,12 @@ pub fn dimensions(doc: &photocraft_doc::Document, p: &Value) -> Result<(f64, f64
Ok((w.round().max(1.0), h.round().max(1.0)))
}
+/// The method a preview proxy is resampled with: the export's own when the proxy is at full
+/// size, so the preview, palette and size estimate show it; bilinear for a reduced proxy.
+pub fn proxy_resample(p: &Value, scale: f64) -> &str {
+ if scale >= 1.0 { p.get("resample").and_then(Value::as_str).unwrap_or("bicubic") } else { "bilinear" }
+}
+
pub fn prepare_table(app: &PhotocraftApp, f: &mut Map<String, Value>) -> Result<(), String> {
if !matches!(s(f, "format", "jpeg").as_str(), "gif" | "png8") {
return Ok(());
@@ -55,7 +61,7 @@ pub fn prepare_table(app: &PhotocraftApp, f: &mut Map<String, Value>) -> Result<
m.remove("percent");
m.insert("width".into(), json!((w * scale).round().max(1.0)));
m.insert("height".into(), json!((h * scale).round().max(1.0)));
- m.insert("resample".into(), json!("bilinear"));
+ m.insert("resample".into(), json!(proxy_resample(&source, scale)));
}
let (doc, _, _) = web_cmds::web_document(&st.doc, &proxy, &settings).map_err(|e| e.to_string())?;
f.insert("__paletteApproximate".into(), json!(scale < 1.0));
diff --git a/docs/control-protocol.md b/docs/control-protocol.md
index 918a9f811..88b1a6596 100644
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@ -69,7 +69,7 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i
- Layer Style (`layerStyle {effect?}` opens on that effect kind): the fields hold the dialog's whole state, so agents read and drive it like a user. `effects` lists every effect instance in the layer's order as `{id, kind, on, params, fx}` (`fx` is the effect snapshot the dialog loaded; OK edits that snapshot with `params`, so anything the dialog doesn't model survives). `selected` picks the page (`blendingOptions` or an instance id), `preview` (default on) gates the live canvas preview, `p:blendingOptions` edits blend mode/opacity/fill opacity, and `patternList` names the usable patterns. OK replaces the layer's effects in one step (`layer.layerStyle.replace`); Cancel discards. "New Style…" saves the pending state via `style.presets.new {effects}`, a swatch click applies a style preset, and Make/Reset Default use `layer.layerStyle.makeDefault` / `layer.layerStyle.defaultFor`
- Preferences (`ui.menu.invoke {id: "edit.preferences.interface"}`) exposes the sections in its `values` field. Apply (`ui.dialog.apply`) and OK (`ui.dialog.confirm`) on Preferences are refused over control because automation denies whole-preferences updates and filesystem-bearing preference sections. A refused `ui.dialog.apply` returns an error and keeps the dialog open; a refused `ui.dialog.confirm` returns an error but closes and removes the dialog. `ui.dialog.cancel` closes the dialog without saving. Individual safe preferences can instead be changed with `engine.execute` using `prefs.set` (e.g. `{"command": "prefs.set", "params": {"path": "interface.showTooltips", "value": false}}`). Settings marked for the next launch still require a restart.
- Edit › Fill… (`ui.menu.invoke {id: "edit.fill"}`, Shift+F5, Shift+Backspace) opens the Fill dialog; its fields are `edit.fill`'s params (`contents`, `color`, `pattern`, `colorAdaptation`, `mode`, `opacity`, `preserveTransparency`), and OK remembers them in the preferences (`dialogs["edit.fill"]`).
- - Save for Web (`ui.menu.invoke {id: "file.export.saveForWebLegacy"}`) is resizable with independently scrolling settings. Dialog fields `__view` (`original|optimized|2up|4up`), `__zoom` (`null` = Fit, otherwise a factor; 1 = 100% in physical display pixels), and `__center: [u,v]` control the shared preview navigation. `__previewRects` reports pane rectangles in screen points. Drag a preview to pan, scroll/pinch to zoom at the pointer, or double-click to fit. GIF/PNG-8 expose `colorTable: ["#rrggbb", …]` (opaque source entries) and `colorTableEdits: {"0":"#rrggbb", …}` (zero-based replacements after quantization). A swatch opens a color picker; edits update the preview and saved file without remapping pixel indices or changing the document. Reset clears replacements. Changing palette/size/matte/transparency settings regenerates the table and clears index-based edits. Previews and generated tables use a bounded 2048-pixel proxy; full-size export uses that explicit table unchanged. `__paletteApproximate` reports proxy-derived palette generation, and enlarged proxy previews are labelled. The engine export command accepts the same table/edit parameters; its no-path estimate returns the source `colorTable` and `transparentIndex` as well as size statistics. Opening a new dialog does not carry a previous image's table across.
+ - Save for Web (`ui.menu.invoke {id: "file.export.saveForWebLegacy"}`) is resizable with independently scrolling settings. Dialog fields `__view` (`original|optimized|2up|4up`), `__zoom` (`null` = Fit, otherwise a factor; 1 = 100% in physical display pixels), and `__center: [u,v]` control the shared preview navigation. `__previewRects` reports pane rectangles in screen points. Drag a preview to pan, scroll/pinch to zoom at the pointer, or double-click to fit. GIF/PNG-8 expose `colorTable: ["#rrggbb", …]` (opaque source entries) and `colorTableEdits: {"0":"#rrggbb", …}` (zero-based replacements after quantization). A swatch opens a color picker; edits update the preview and saved file without remapping pixel indices or changing the document. Reset clears replacements. Changing palette/size/matte/transparency settings regenerates the table and clears index-based edits. Previews and generated tables use a bounded 2048-pixel proxy; full-size export uses that explicit table unchanged. `__paletteApproximate` reports proxy-derived palette generation, and enlarged proxy previews are labelled. The engine export command accepts the same table/edit parameters; its no-path estimate returns the source `colorTable` and `transparentIndex` as well as size statistics. Opening a new dialog does not carry a previous image's table across. Image Size has `width` and `height` (px), `percent` and `resample` (`nearest|bilinear|bicubic|bicubicSmoother|bicubicSharper`, default `bicubic`); `__constrain` (default true at each opening) links the two sides in proportion. A side edit sets both sides and removes `percent`, which the export command otherwise applies first; a Percent edit sets both sides from it. Each opening starts at the document's full size, while `resample` is remembered with the encoding choices. The document is never resized.
- A pixel tool pressed on a type, shape, Smart Object or fill layer (e.g. through `ui.pointer`) opens the "Rasterize?" prompt instead of painting: a dialog with `__rasterize` (`type|shape|smartObject|fill`), `message`, `layer`, `tool` and `at`. `ui.dialog.confirm` runs the `layer.rasterize.*` command and then paints at `at` (two history states, `{"rasterized", "painted"}`); `ui.dialog.cancel` does nothing.
- Edit › Transform › Warp on editable type (`ui.menu.invoke {"id":"edit.transform.warp"}`, or the warp toggle of an open transform box) opens Warp mode with no prompt, as in Photoshop: the mesh can't be dragged or split, only the options bar's warp style, Bend, H and V apply, and the commit sets the layer's Warp Text in one step, so the type stays editable. Directly: `engine.execute {"command":"edit.transform.warp","params":{"style":"flag","bend":40}}` on a type layer. Distort and Perspective stay greyed for type.
- `ui.window.open {document?}` / `ui.window.close {window}`: extra document windows