Skip to content

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

Export Preferences: WebP quality and lossless settings for Quick Export (#1260) (#1279)

Nigel Ihza Firdausy7d78e1dd2c1e
diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs
index 0aa3adf19..ecf10a6c5 100644
--- a/crates/engine/src/prefs.rs
+++ b/crates/engine/src/prefs.rs
@@ -364,6 +364,9 @@ pub struct Export {
pub quick_export_format: QuickExportFormat,
pub quick_export_location: ExportLocation,
pub jpeg_quality: u32,
+ /// Keep the existing lossless Quick Export default until the user opts into lossy WebP.
+ pub webp_lossless: bool,
+ pub webp_quality: u32,
pub metadata: ExportMetadata,
pub convert_to_srgb: bool,
}
@@ -374,6 +377,8 @@ impl Default for Export {
quick_export_format: QuickExportFormat::Png,
quick_export_location: ExportLocation::Ask,
jpeg_quality: 85,
+ webp_lossless: true,
+ webp_quality: 85,
metadata: ExportMetadata::Copyright,
convert_to_srgb: true,
}
@@ -905,7 +910,7 @@ pub fn range(path: &str) -> Option<(f64, f64)> {
Some(match path {
"fileHandling.autosaveMinutes" => (1.0, 240.0),
"fileHandling.recentFileCount" => (0.0, 100.0),
- "export.jpegQuality" => (1.0, 100.0),
+ "export.jpegQuality" | "export.webpQuality" => (1.0, 100.0),
"performance.memoryUsageMb" => (256.0, 1_048_576.0),
"performance.historyStates" => (1.0, 1000.0),
"performance.cacheLevels" => (1.0, 8.0),
diff --git a/crates/engine/src/web_cmds.rs b/crates/engine/src/web_cmds.rs
index 19e2997aa..346fe9230 100644
--- a/crates/engine/src/web_cmds.rs
+++ b/crates/engine/src/web_cmds.rs
@@ -840,6 +840,8 @@ fn export_preferences(s: &mut Session, p: &Value) -> Result<Value> {
("quickExportFormat", "export.quickExportFormat"),
("quickExportLocation", "export.quickExportLocation"),
("jpegQuality", "export.jpegQuality"),
+ ("webpLossless", "export.webpLossless"),
+ ("webpQuality", "export.webpQuality"),
("metadata", "export.metadata"),
("convertToSrgb", "export.convertToSrgb"),
] {
@@ -897,9 +899,12 @@ fn quick_export(s: &mut Session, p: &Value) -> Result<Value> {
o.insert("format".into(), json!("gif"));
}
"webp" => {
- // WebP has no legacy Save for Web optimiser: write it through the regular exporter.
+ // WebP uses the regular exporter. Its optional quality is in the Photoshop-style
+ // 0–12 save scale: invert that mapping so the codec receives the chosen 1–100.
+ // Keeping quality absent preserves the historical lossless Quick Export behavior.
let (wdoc, _, _) = web_document(&doc, &json!({}), &WebSettings { convert_to_srgb: prefs.convert_to_srgb, ..Default::default() })?;
- let warnings = crate::file_cmds::save_doc(&wdoc, &path, None)?;
+ let quality = if prefs.webp_lossless { None } else { Some((f64::from(prefs.webp_quality.clamp(1, 100)) - 1.0) * 12.0 / 99.0) };
+ let warnings = crate::file_cmds::save_doc(&wdoc, &path, quality)?;
crate::automate_cmds::fire_event(s, "export");
return Ok(json!({"path": path, "format": fmt, "warnings": warnings}));
}
@@ -1211,7 +1216,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export Preferences…",
&["File", "Export"],
None,
- r##"{"quickExportFormat":"png|jpg|gif|webp"?,"quickExportLocation":"ask|sameFolder"?,"jpegQuality":1..100?,"metadata":"none|copyright|all"?,"convertToSrgb":bool?} → {values}"##,
+ r##"{"quickExportFormat":"png|jpg|gif|webp"?,"quickExportLocation":"ask|sameFolder"?,"jpegQuality":1..100?,"webpLossless":bool?,"webpQuality":1..100?,"metadata":"none|copyright|all"?,"convertToSrgb":bool?} → {values}"##,
|_| Ok(()),
export_preferences
),
diff --git a/crates/engine/src/web_cmds/tests.rs b/crates/engine/src/web_cmds/tests.rs
index 7dcc92af0..9392bbdfb 100644
--- a/crates/engine/src/web_cmds/tests.rs
+++ b/crates/engine/src/web_cmds/tests.rs
@@ -153,6 +153,54 @@ fn export_preferences_drive_quick_export() {
s.execute("prefs.reset", json!({"path": "export"})).unwrap();
}
+#[test]
+fn webp_export_preferences_select_lossless_or_lossy_output() {
+ let dir = tmp("quick_webp_quality");
+ let mut s = session(8);
+ let defaults = s.prefs().export.clone();
+ assert!(defaults.webp_lossless, "existing Quick Export defaults to lossless WebP");
+ assert_eq!(defaults.webp_quality, 85);
+
+ // Simulate an older stored preference section without the newly added WebP keys.
+ let mut old = s.prefs().to_json();
+ old["export"].as_object_mut().unwrap().remove("webpLossless");
+ old["export"].as_object_mut().unwrap().remove("webpQuality");
+ let restored: crate::prefs::Preferences = serde_json::from_value(old).unwrap();
+ assert!(restored.export.webp_lossless);
+ assert_eq!(restored.export.webp_quality, 85);
+
+ let r = s.execute("file.export.exportPreferences", json!({"quickExportFormat": "webp", "webpLossless": true, "webpQuality": 40})).unwrap();
+ assert_eq!(r["values"]["webpLossless"], true);
+ assert_eq!(r["values"]["webpQuality"], 40);
+ let lossless_path = format!("{dir}/lossless.webp");
+ s.execute("file.export.quickExport", json!({"path": lossless_path})).unwrap();
+ let lossless = std::fs::read(&lossless_path).unwrap();
+ assert!(lossless.starts_with(b"RIFF") && &lossless[8..12] == b"WEBP");
+ assert!(lossless.windows(4).any(|w| w == b"VP8L"), "lossless WebP should use VP8L");
+ assert_eq!(decode(&lossless_path).dimensions(), (64, 48));
+
+ s.execute("file.export.exportPreferences", json!({"webpLossless": false})).unwrap();
+ let low_path = format!("{dir}/lossy40.webp");
+ s.execute("file.export.quickExport", json!({"path": low_path})).unwrap();
+ let low = std::fs::read(&low_path).unwrap();
+ assert!(low.windows(4).any(|w| w == b"VP8 "), "lossy WebP should contain a VP8 frame");
+ assert_eq!(decode(&low_path).dimensions(), (64, 48));
+
+ s.execute("file.export.exportPreferences", json!({"webpQuality": 90})).unwrap();
+ let high_path = format!("{dir}/lossy90.webp");
+ s.execute("file.export.quickExport", json!({"path": high_path})).unwrap();
+ let high = std::fs::read(&high_path).unwrap();
+ assert!(high.windows(4).any(|w| w == b"VP8 "));
+ assert_eq!(decode(&high_path).dimensions(), (64, 48));
+ assert_ne!(low, high, "changing WebP quality should change the encoded image");
+
+ let before = s.prefs().export.webp_quality;
+ for quality in [0, 101] {
+ assert!(s.execute("file.export.exportPreferences", json!({"webpQuality": quality})).is_err());
+ assert_eq!(s.prefs().export.webp_quality, before);
+ }
+}
+
#[test]
fn generator_naming_grammar() {
let a = parse_asset_name("200% [email protected], 48x48 icons/bar.png8 + photo.jpg8", 72.0);
diff --git a/crates/ui-egui/src/export_dialog.rs b/crates/ui-egui/src/export_dialog.rs
index c44aa0b68..e88d6c3a8 100644
--- a/crates/ui-egui/src/export_dialog.rs
+++ b/crates/ui-egui/src/export_dialog.rs
@@ -19,8 +19,8 @@ pub fn open(app: &mut PhotocraftApp) -> Result<u64, String> {
f.insert("__export".into(), json!(true));
f.insert("__label".into(), json!("Export As"));
f.insert("format".into(), json!("png"));
- f.insert("quality".into(), json!(85));
- f.insert("lossless".into(), json!(false));
+ f.insert("quality".into(), json!(app.session.prefs().export.jpeg_quality));
+ f.insert("lossless".into(), json!(app.session.prefs().export.webp_lossless));
f.insert("transparency".into(), json!(true));
f.insert("scale".into(), json!(100));
f.insert("metadata".into(), json!("none"));
@@ -92,6 +92,22 @@ fn export_document(doc: &Document, f: &Map<String, Value>, max_side: Option<u32>
s.active().map(|d| (*d.doc).clone()).ok_or_else(|| "export failed".into())
}
+/// Export As already supports lossy WebP; reuse the Quick Export defaults when
+/// choosing that format so both flows expose the same quality and lossless options.
+fn set_format_defaults(f: &mut Map<String, Value>, fmt: &str, prefs: &photocraft_engine::prefs::Export) {
+ f.insert("format".into(), json!(fmt));
+ match fmt {
+ "jpg" => {
+ f.insert("quality".into(), json!(prefs.jpeg_quality));
+ }
+ "webp" => {
+ f.insert("quality".into(), json!(prefs.webp_quality));
+ f.insert("lossless".into(), json!(prefs.webp_lossless));
+ }
+ _ => {}
+ }
+}
+
fn s_fmt(f: &Map<String, Value>) -> String {
let v = s(f, "format");
if v.is_empty() { "png".into() } else { v }
@@ -137,7 +153,7 @@ pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<String, Valu
let mut fmt = s_fmt(f);
let opts: Vec<(String, &str)> = FORMATS.iter().map(|(k, l)| (k.to_string(), *l)).collect();
if crate::widgets::dropdown(ui, "export-format", &mut fmt, &opts, 130.0) {
- f.insert("format".into(), json!(fmt));
+ set_format_defaults(f, &fmt, &app.session.prefs().export);
}
});
let fmt = s_fmt(f);
@@ -287,6 +303,28 @@ mod tests {
assert_eq!(settings(&f).jpeg_quality, Some(85));
}
+ #[test]
+ fn switching_export_formats_uses_independent_quality_preferences() {
+ let prefs = photocraft_engine::prefs::Export { jpeg_quality: 43, webp_quality: 72, webp_lossless: false, ..Default::default() };
+ let mut fields = Map::new();
+ set_format_defaults(&mut fields, "webp", &prefs);
+ assert_eq!(fields["quality"], 72);
+ assert_eq!(fields["lossless"], false);
+ let s = settings(&fields);
+ assert!(!s.webp_lossless);
+ assert_eq!(s.webp_quality, Some(72));
+ assert_eq!(s.jpeg_quality, None);
+
+ set_format_defaults(&mut fields, "jpg", &prefs);
+ assert_eq!(fields["quality"], 43);
+ assert_eq!(settings(&fields).jpeg_quality, Some(43));
+ assert_eq!(settings(&fields).webp_quality, None);
+
+ set_format_defaults(&mut fields, "webp", &photocraft_engine::prefs::Export::default());
+ assert!(settings(&fields).webp_lossless, "default WebP Quick Export mode is lossless");
+ assert_eq!(settings(&fields).webp_quality, None);
+ }
+
#[test]
fn webp_settings_follow_the_lossless_switch() {
let mut f = Map::new();
diff --git a/crates/ui-egui/src/prefs_ui.rs b/crates/ui-egui/src/prefs_ui.rs
index 42c8726c5..bb690bd15 100644
--- a/crates/ui-egui/src/prefs_ui.rs
+++ b/crates/ui-egui/src/prefs_ui.rs
@@ -756,6 +756,13 @@ pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<String, Valu
}
fn humanize(key: &str) -> String {
+ // These controls appear only for WebP, so reuse the existing translated labels.
+ if key == "webpLossless" {
+ return "Lossless".into();
+ }
+ if key == "webpQuality" {
+ return "Quality".into();
+ }
let mut s = String::new();
for (i, ch) in key.chars().enumerate() {
if i == 0 {
@@ -940,6 +947,17 @@ fn has_visible_fields(values: &Value, section: &str) -> bool {
values.get(section).and_then(Value::as_object).is_some_and(|o| o.keys().any(|k| !prefs::is_hidden(&format!("{section}.{k}"))))
}
+/// JPEG and WebP have independent settings; unrelated format controls stay out of view.
+fn export_field_visible(obj: &Map<String, Value>, key: &str) -> bool {
+ let format = obj.get("quickExportFormat").and_then(Value::as_str).unwrap_or("png");
+ match key {
+ "jpegQuality" => format == "jpg",
+ "webpLossless" => format == "webp",
+ "webpQuality" => format == "webp" && obj.get("webpLossless").and_then(Value::as_bool) != Some(true),
+ _ => true,
+ }
+}
+
/// Generic editor for a section's fields: checkboxes, dropdowns for choices, colour swatches,
/// number fields with the preference's range, text fields.
fn section_fields(ui: &mut egui::Ui, section: &str, obj: &mut Map<String, Value>, order: &[String], lang: crate::i18n::Lang) {
@@ -954,7 +972,10 @@ fn section_fields(ui: &mut egui::Ui, section: &str, obj: &mut Map<String, Value>
let path = format!("{section}.{k}");
// Settings nothing reads yet stay out of the dialog (issue #204); their stored values
// pass through untouched.
- if prefs::is_hidden(&path) || (section == "performance" && matches!(k.as_str(), "useGpu" | "gpuBackend" | "renderingMode")) {
+ if prefs::is_hidden(&path)
+ || (section == "performance" && matches!(k.as_str(), "useGpu" | "gpuBackend" | "renderingMode"))
+ || (section == "export" && !export_field_visible(obj, &k))
+ {
continue;
}
let v = obj.get(&k).cloned().unwrap_or(Value::Null);
@@ -1431,6 +1452,29 @@ mod tests {
assert_eq!(*h.state(), [0x80, 0x80, 0x80]);
}
+ #[test]
+ fn quick_export_controls_match_selected_format() {
+ let mut obj = serde_json::to_value(photocraft_engine::prefs::Export::default()).unwrap().as_object().unwrap().clone();
+ assert!(!export_field_visible(&obj, "jpegQuality"));
+ assert!(!export_field_visible(&obj, "webpLossless"));
+ assert!(!export_field_visible(&obj, "webpQuality"));
+
+ obj.insert("quickExportFormat".into(), json!("jpg"));
+ assert!(export_field_visible(&obj, "jpegQuality"));
+ assert!(!export_field_visible(&obj, "webpLossless"));
+ assert!(!export_field_visible(&obj, "webpQuality"));
+
+ obj.insert("quickExportFormat".into(), json!("webp"));
+ assert!(!export_field_visible(&obj, "jpegQuality"));
+ assert!(export_field_visible(&obj, "webpLossless"));
+ assert!(!export_field_visible(&obj, "webpQuality"), "lossless WebP does not have a quality setting");
+
+ obj.insert("webpLossless".into(), json!(false));
+ assert!(export_field_visible(&obj, "webpQuality"));
+ assert_eq!(humanize("webpLossless"), "Lossless");
+ assert_eq!(humanize("webpQuality"), "Quality");
+ }
+
#[test]
fn rendering_mode_display_respects_explicit_mode_and_legacy_disable() {
let legacy = serde_json::json!({"useGpu": false, "gpuBackend": "auto"});
diff --git a/docs/scorecard.md b/docs/scorecard.md
index f903a5108..770946f8f 100644
--- a/docs/scorecard.md
+++ b/docs/scorecard.md
@@ -9,7 +9,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js
| [Performance](#performance) | 3 | 22 | 13 | 47 scenarios: 3 within budget, 22 over budget or failing, 15 tracked only, 6 not run, 7 not measurable yet (baseline 2026-10-05) |
| [File compatibility](#file-compatibility) | 3 | 9 | 15 | io corpus: oracle ≥ 146/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 229/309, round trip ≥ 307/309; photoshop oracles: oracle ≥ 133/256, round trip ≥ 258/256 |
| [Tools](#tools) | 6 | 15 | 9 | |
-| [Workspace and UI](#workspace-and-ui) | 0 | 5 | 18 | settings that do nothing: 57 of 135 (target 0) |
+| [Workspace and UI](#workspace-and-ui) | 0 | 5 | 18 | settings that do nothing: 57 of 137 (target 0) |
| [Type](#type) | 0 | 3 | 6 | |
| [Automation](#automation) | 3 | 2 | 6 | 627 of 627 menu items live (100.0%) |
| [Reliability](#reliability) | 4 | 1 | 2 | never-crash lints on 27 of 27 crates; panic_hunt present |
@@ -154,7 +154,7 @@ Corpus floors (`crates/io/tests/corpus.rs`): the enforced minimums; the corpus t
## Workspace and UI
-**Settings that do nothing: 57 of 135** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't.
+**Settings that do nothing: 57 of 137** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't.
Unread: `general.color_picker`, `general.beep_when_done`, `general.export_clipboard`, `general.resize_image_during_place`, `general.always_create_smart_objects_when_placing`, `general.animated_zoom`, `general.zoom_resizes_windows`, `interface.show_channels_in_color`, `interface.dynamic_color_sliders`, `workspace.auto_collapse_icon_panels`, `workspace.auto_show_hidden_panels`, `workspace.open_documents_as_tabs`, `workspace.enable_floating_document_window_docking`, `workspace.large_tabs`, `workspace.enable_narrow_options_bar`, `tools.zoom_clicked_point_to_center`, `tools.enable_flick_panning`, `tools.vary_round_brush_hardness_on_hud`, `tools.show_transformation_values`, `tools.double_click_layer_mask_launches_select_and_mask`, `file_handling.image_previews`, `file_handling.lowercase_extension`, `file_handling.save_in_background`, `file_handling.ignore_exif_profile_tag`, `file_handling.maximize_psd_compatibility`, `performance.cache_levels`, `performance.legacy_compositing`, `scratch_disks.disks`, `cursors.brush_preview_color`, `units_and_rulers.type_units`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `units_and_rulers.print_resolution`, `units_and_rulers.screen_resolution`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `plug_ins.generator_enabled`, `type_.smart_quotes`, `type_.missing_glyph_protection`, `type_.show_font_names_in_english`, `type_.use_esc_to_commit`, `type_.text_engine`, `type_.font_preview`, `type_.fill_new_type_layers_with_placeholder`, `type_.recent_fonts`, `enhanced_controls.scrubby_slider_acceleration`, `enhanced_controls.touch_gestures`, `enhanced_controls.zoom_with_trackpad_pinch`, `enhanced_controls.rotate_view_with_trackpad`, `raw_defaults.color_space`, `raw_defaults.bit_depth`, `raw_defaults.resolution`, `raw_defaults.sharpen_for`, `raw_defaults.open_as_smart_object`, `raw_defaults.apply_auto_tone`, `integrations.allow_agent_control`, `integrations.control_port`.