Skip to content

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

Save for Web and Export As remember their settings across restarts (FILE-215-18) (#4184)

Reynold Hu1412ac26e2d0
diff --git a/crates/engine/src/web_cmds.rs b/crates/engine/src/web_cmds.rs
index cccddbf9f..727e35590 100644
--- a/crates/engine/src/web_cmds.rs
+++ b/crates/engine/src/web_cmds.rs
@@ -837,6 +837,21 @@ pub fn save_for_web_with_writer(s: &mut Session, p: &Value, write: &mut dyn FnMu
save_for_web_impl(s, p, write, false)
}
+/// Settings to seed the Save for Web dialog from on the next launch: `file_menu` is session
+/// state, so a complete export also writes the preferences' remembered dialog settings (like
+/// Fill, Liquify and the filter dialogs). The destination is per export, never remembered.
+fn remember_web_settings(s: &mut Session, cmd: &str, settings: &Value) {
+ let mut m = settings.clone();
+ if let Some(o) = m.as_object_mut() {
+ for k in ["path", "dir", "trustedSliceHtml"] {
+ o.remove(k);
+ }
+ }
+ s.prefs.edit(|p| {
+ p.dialogs.insert(cmd.to_string(), m);
+ });
+}
+
fn save_for_web_impl(s: &mut Session, p: &Value, write: &mut dyn FnMut(&str, &[u8]) -> Result<()>, native_paths: bool) -> Result<Value> {
let cmd = "file.export.saveForWebLegacy";
if let Some(authorize) = s.authorize {
@@ -883,6 +898,7 @@ fn save_for_web_impl(s: &mut Session, p: &Value, write: &mut dyn FnMut(&str, &[u
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(path, &o.bytes)?;
+ remember_web_settings(s, cmd, &last_web);
s.file_menu.last_web = Some(last_web);
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}));
@@ -973,6 +989,7 @@ fn save_for_web_impl(s: &mut Session, p: &Value, write: &mut dyn FnMut(&str, &[u
write(&web_derived_path(&dir, &format!("{base}.html"), native_paths)?, page.as_bytes())?;
html_path = Some(hp);
}
+ remember_web_settings(s, cmd, &last_web);
s.file_menu.last_web = Some(last_web);
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}))
diff --git a/crates/engine/src/web_cmds/tests.rs b/crates/engine/src/web_cmds/tests.rs
index 787560f42..9550cd849 100644
--- a/crates/engine/src/web_cmds/tests.rs
+++ b/crates/engine/src/web_cmds/tests.rs
@@ -47,6 +47,23 @@ fn estimates_preserve_last_successful_export_settings() {
assert_eq!(s.file_menu.last_web.as_ref(), Some(&saved), "preview estimates must not replace the settings from the last successful export");
}
+/// The next launch's dialog seeds from the preferences: `file_menu` is not saved, so a complete
+/// export remembers its settings in `prefs.dialogs` too, as Fill and the filter dialogs do.
+#[test]
+fn a_complete_export_remembers_its_settings_in_the_preferences() {
+ let dir = tmp("remember_settings");
+ let mut s = session(8);
+ s.execute("file.export.saveForWebLegacy", json!({"format": "jpeg", "quality": 42, "path": format!("{dir}/out.jpg")})).unwrap();
+ let saved = s.prefs().dialogs.get("file.export.saveForWebLegacy").cloned().expect("remembered");
+ assert_eq!(saved["format"], "jpeg");
+ assert_eq!(saved["quality"], 42);
+ assert!(saved.get("path").is_none(), "the destination is per export, not remembered");
+
+ // Preview estimates remember nothing, like they don't replace `file_menu`.
+ s.execute("file.export.saveForWebLegacy", json!({"format": "png24", "width": 16, "height": 12})).unwrap();
+ assert_eq!(s.prefs().dialogs.get("file.export.saveForWebLegacy").unwrap()["format"], "jpeg");
+}
+
#[test]
fn platform_writer_receives_resized_image_at_every_depth() {
for depth in [8, 16, 32] {
diff --git a/crates/ui-egui/src/export_dialog.rs b/crates/ui-egui/src/export_dialog.rs
index cd520d5c3..79abeaadb 100644
--- a/crates/ui-egui/src/export_dialog.rs
+++ b/crates/ui-egui/src/export_dialog.rs
@@ -13,6 +13,46 @@ use crate::{ExportSettings, PhotocraftApp};
const FORMATS: [(&str, &str); 5] = [("png", "PNG"), ("jpg", "JPG"), ("webp", "WebP"), ("tif", "TIFF"), ("tga", "TGA")];
+/// Preferences ▸ remembered dialog settings: Export As writes the settings it was used with
+/// last under its command id and seeds the next dialog from them, as Fill, Liquify and the
+/// filter dialogs do.
+pub(crate) const COMMAND: &str = "file.export.exportAs";
+
+/// The dialog is seeded from the settings it was used with last (see [`COMMAND`]); a value that
+/// no longer matches a control (a hand-edited preferences file) is left at its default.
+fn seed_remembered(app: &PhotocraftApp, f: &mut Map<String, Value>) {
+ let Some(Value::Object(saved)) = app.session.prefs().dialogs.get(COMMAND) else { return };
+ if let Some(v) = saved.get("format").and_then(Value::as_str).filter(|v| FORMATS.iter().any(|(k, _)| k == v)) {
+ f.insert("format".into(), json!(v));
+ }
+ if let Some(v) = saved.get("quality").and_then(Value::as_f64).filter(|v| (1.0..=100.0).contains(v)) {
+ f.insert("quality".into(), json!(v));
+ }
+ if let Some(v) = saved.get("scale").and_then(Value::as_f64).filter(|v| (1.0..=1000.0).contains(v)) {
+ f.insert("scale".into(), json!(v));
+ }
+ for key in ["lossless", "transparency"] {
+ if let Some(v) = saved.get(key).and_then(Value::as_bool) {
+ f.insert(key.into(), json!(v));
+ }
+ }
+ if let Some(v) = saved.get("metadata").and_then(Value::as_str).filter(|v| ["none", "all"].contains(v)) {
+ f.insert("metadata".into(), json!(v));
+ }
+ if let Some(v) = saved.get("tgaBits").and_then(Value::as_str).filter(|v| ["auto", "24", "32"].contains(v)) {
+ f.insert("tgaBits".into(), json!(v));
+ }
+}
+
+/// Record the settings for the next Export As (see [`seed_remembered`]).
+fn remember(app: &mut PhotocraftApp, f: &Map<String, Value>) {
+ const KEYS: [&str; 7] = ["format", "quality", "lossless", "transparency", "scale", "metadata", "tgaBits"];
+ let saved: Map<String, Value> = KEYS.iter().filter_map(|k| f.get(*k).map(|v| ((*k).to_string(), v.clone()))).collect();
+ app.session.prefs.edit(|p| {
+ p.dialogs.insert(COMMAND.into(), Value::Object(saved));
+ });
+}
+
pub fn open(app: &mut PhotocraftApp) -> Result<u64, String> {
let st = app.session.active().ok_or("no document")?;
let mut f = Map::new();
@@ -27,6 +67,7 @@ pub fn open(app: &mut PhotocraftApp) -> Result<u64, String> {
f.insert("tgaBits".into(), json!("auto"));
f.insert("__w".into(), json!(st.doc.size.width));
f.insert("__h".into(), json!(st.doc.size.height));
+ seed_remembered(app, &mut f);
Ok(app.ui.open_dialog(DialogKind::Command, f))
}
@@ -355,6 +396,7 @@ pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<String, Valu
/// Export with the dialog's settings: choose a path, render, encode, write.
pub fn confirm(app: &mut PhotocraftApp, f: &Map<String, Value>) -> Result<Value, String> {
+ remember(app, f);
if let Some(layers) = f.get("__layers").and_then(Value::as_array) {
let ids: Vec<_> = layers.iter().filter_map(Value::as_u64).map(photocraft_doc::LayerId).collect();
return confirm_layers(app, f, &ids);
@@ -452,6 +494,55 @@ fn quick_export(app: &mut PhotocraftApp, p: Value) -> Result<Value, String> {
mod tests {
use super::*;
+ /// Export As reopens with the settings it was used with last (Preferences ▸ remembered
+ /// dialog settings), and a value no control accepts keeps its default.
+ #[test]
+ fn export_as_opens_with_the_settings_used_last() {
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({"width": 20, "height": 10})).unwrap();
+ app.session.prefs.edit(|p| {
+ p.dialogs.insert(
+ COMMAND.into(),
+ json!({"format": "jpg", "quality": 88, "scale": 37, "transparency": false, "metadata": "all", "tgaBits": "24", "lossless": true}),
+ );
+ });
+ let id = open(&mut app).unwrap();
+ let f = &app.ui.dialog_mut(id).unwrap().fields;
+ assert_eq!(f["format"], "jpg");
+ assert_eq!(f["quality"], json!(88.0));
+ assert_eq!(f["scale"], json!(37.0));
+ assert_eq!(f["transparency"], false);
+ assert_eq!(f["metadata"], "all");
+ assert_eq!(f["tgaBits"], "24");
+
+ app.session.prefs.edit(|p| {
+ p.dialogs.insert(COMMAND.into(), json!({"format": "nope", "scale": 0, "metadata": "sometimes"}));
+ });
+ let id = open(&mut app).unwrap();
+ let f = &app.ui.dialog_mut(id).unwrap().fields;
+ assert_eq!(f["format"], "png");
+ assert_eq!(f["scale"], 100);
+ assert_eq!(f["metadata"], "none");
+ }
+
+ /// Only the dialog's own settings are remembered: not the destination, the document size or
+ /// the layer the dialog was opened with.
+ #[test]
+ fn remembering_keeps_only_the_dialog_settings() {
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
+ let mut f = Map::new();
+ f.insert("format".into(), json!("webp"));
+ f.insert("scale".into(), json!(50));
+ f.insert("path".into(), json!("/tmp/x.webp"));
+ f.insert("__w".into(), json!(1200));
+ f.insert("__layer".into(), json!(3));
+ remember(&mut app, &f);
+ let saved = app.session.prefs().dialogs.get(COMMAND).cloned().unwrap();
+ assert_eq!(saved["format"], "webp");
+ assert_eq!(saved["scale"], 50);
+ assert!(saved.get("path").is_none() && saved.get("__w").is_none() && saved.get("__layer").is_none());
+ }
+
#[test]
fn export_document_scales_height_when_rounded_width_is_unchanged() {
use photocraft_doc::{Color, ColorMode, SampleType, Size};
diff --git a/crates/ui-egui/src/file_ui.rs b/crates/ui-egui/src/file_ui.rs
index e3884796f..d7e2252e7 100644
--- a/crates/ui-egui/src/file_ui.rs
+++ b/crates/ui-egui/src/file_ui.rs
@@ -192,8 +192,16 @@ pub fn open_web(app: &mut PhotocraftApp) -> u64 {
f.insert("__command".into(), json!(WEB_COMMAND));
f.insert("__label".into(), json!("Save for Web (Legacy)"));
f.insert("__view".into(), json!("2up"));
- // 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}));
+ // Remember encoding choices, but each document starts at its own full size. This session's
+ // last export lives in `file_menu`; the last one before a restart comes from the
+ // preferences' remembered dialog settings (`web_cmds::remember_web_settings`).
+ let last = app
+ .session
+ .file_menu
+ .last_web
+ .clone()
+ .or_else(|| app.session.prefs().dialogs.get(WEB_COMMAND).cloned())
+ .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" | "width" | "height" | "percent" | "colorTable" | "colorTableEdits") {
@@ -937,6 +945,20 @@ mod tests {
assert!(!d.fields.contains_key("path"));
}
+ /// A fresh session's dialog seeds from the preferences: the last export before a restart is
+ /// remembered there (`web_cmds::remember_web_settings`), as `file_menu` is not saved.
+ #[test]
+ fn the_save_for_web_dialog_seeds_from_the_remembered_preferences() {
+ let (mut app, _) = app();
+ app.session.prefs.edit(|p| {
+ p.dialogs.insert(WEB_COMMAND.into(), json!({"format": "png8", "colors": 64}));
+ });
+ let id = open_web(&mut app);
+ let f = &app.ui.dialog_mut(id).unwrap().fields;
+ assert_eq!(f["format"], "png8");
+ assert_eq!(f["colors"], 64);
+ }
+
#[test]
fn save_for_web_starts_at_the_current_document_size() {
let (mut app, _) = app();
diff --git a/docs/scorecard.md b/docs/scorecard.md
index d2ee641b1..651d68309 100644
--- a/docs/scorecard.md
+++ b/docs/scorecard.md
@@ -115,7 +115,7 @@ Corpus floors (`crates/io/tests/corpus.rs`): the enforced minimums; the corpus t
| FILE-215-15 | Layer Style contour picker, curve editor, presets, .shc import/export | partial | [#2912](https://github.com/storytold/photocraft/issues/2912) | Layer Style dialog: contour thumbnail + preset picker (12 standard shapes, own control points) and Anti-aliased on Drop/Inner Shadow, Outer/Inner Glow, Satin, Bevel Gloss Contour and Contour element; Contour Editor (add/drag/delete, Corner, Input/Output, Preset, Load…/Save… .shc per Adobe's public spec, psd shc.rs); corner points render (compose contour_curve_lut) and map to PSD Cnty. Missing: a user contour library (New…, picker Load/Save/Replace Contours), Anti-aliased doesn't change the render yet, .shc not yet checked against a Photoshop-written file |
| FILE-215-16 | Advanced Blending (knockout, blend as group, mask hides effects) end to end | partial | [#215](https://github.com/storytold/photocraft/issues/215) | doc advanced.rs + .pcraft + PSD/layered TIFF (knko infx clbl tsly lmgm vmgm), CPU compose advanced.rs (GPU falls back), blendingOptions command + dialog; 7 psd-tools knockout oracles now pass; knockout-isolated-groups (0.45 % AA edges), advanced-blending, blend-and-clipping still differ |
| FILE-215-17 | CMYK/RGB documents preview spot inks; spot plates export (TIFF extra samples, PDF) | missing | [#215](https://github.com/storytold/photocraft/issues/215) | compose multichannel.rs:1 spot preview for Multichannel only |
-| FILE-215-18 | Save for Web per-slice settings remembered; Export As remembers and offers nearest scaling | partial | [#215](https://github.com/storytold/photocraft/issues/215) | file_ui.rs:188 last_web in-session only; export_dialog.rs:16 fixed defaults |
+| FILE-215-18 | Save for Web per-slice settings remembered; Export As remembers and offers nearest scaling | partial | [#215](https://github.com/storytold/photocraft/issues/215) | Save for Web settings survive a restart through the remembered dialog settings in prefs.dialogs (web_cmds::remember_web_settings stores them on a complete export, never the destination; file_ui.rs open_web seeds from the session's last export, else the preferences). export_dialog seeds Export As the same way (seed_remembered: format, quality, transparency, scale, metadata, TGA bits) and confirm remembers them as used. Missing: Export As nearest-neighbour scaling |
| FILE-215-19 | Save As JPEG opens a JPEG Options dialog (quality 0-12, format options) | missing | [#215](https://github.com/storytold/photocraft/issues/215) | ExportSettings has jpeg_quality 1-100 only (lib.rs:118) |
| FILE-215-20 | Artboard tool with handles and + buttons, Duplicate Artboard beside, vector PDF pages | partial | [#215](https://github.com/storytold/photocraft/issues/215) | artboard_tool.rs: Artboard tool draws, selects, moves and resizes boards by their handles (⇧ keeps proportions), its + buttons add a board or (⌥) a copy beside the selected one (#3033); Duplicate Artboard places the copy beside (#1584); raster PDF pages only |
| FILE-215-21 | Local libraries of colours, patterns, images and layers, as linked items or copies | missing | [#215](https://github.com/storytold/photocraft/issues/215) | Only preset libraries (preset_store.rs) |
diff --git a/scorecard/file_compat.toml b/scorecard/file_compat.toml
index 3c93a9d5b..780bee4f1 100644
--- a/scorecard/file_compat.toml
+++ b/scorecard/file_compat.toml
@@ -129,7 +129,7 @@ id = "FILE-215-18"
target = "Save for Web per-slice settings remembered; Export As remembers and offers nearest scaling"
status = "partial"
issue = 215
-note = "file_ui.rs:188 last_web in-session only; export_dialog.rs:16 fixed defaults"
+note = "Save for Web settings survive a restart through the remembered dialog settings in prefs.dialogs (web_cmds::remember_web_settings stores them on a complete export, never the destination; file_ui.rs open_web seeds from the session's last export, else the preferences). export_dialog seeds Export As the same way (seed_remembered: format, quality, transparency, scale, metadata, TGA bits) and confirm remembers them as used. Missing: Export As nearest-neighbour scaling"
[[item]]
id = "FILE-215-19"