Skip to content

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

Exposure: the slider keeps fractional stops (#4164) (#4165)

David Mannf60202879d73
diff --git a/crates/ui-egui/src/adjust_editors.rs b/crates/ui-egui/src/adjust_editors.rs
index 84fab70b4..cc47bb33d 100644
--- a/crates/ui-egui/src/adjust_editors.rs
+++ b/crates/ui-egui/src/adjust_editors.rs
@@ -115,18 +115,18 @@ pub fn editor(ui: &mut egui::Ui, kind: &str, v: &mut Value, cx: &EditorCx) -> Ed
ui,
v,
&[
- ("exposure", tl!("Exposure"), -20.0, 20.0, 0.0, ""),
- ("offset", tl!("Offset"), -0.5, 0.5, 0.0, ""),
- ("gamma", tl!("Gamma Correction"), 0.01, 9.99, 1.0, ""),
+ ("exposure", tl!("Exposure"), -20.0, 20.0, 0.0, "", Some(2)),
+ ("offset", tl!("Offset"), -0.5, 0.5, 0.0, "", Some(4)),
+ ("gamma", tl!("Gamma Correction"), 0.01, 9.99, 1.0, "", None),
],
),
- "vibrance" => sliders(ui, v, &[("vibrance", "Vibrance", -100.0, 100.0, 0.0, "%"), ("saturation", "Saturation", -100.0, 100.0, 0.0, "%")]),
+ "vibrance" => sliders(ui, v, &[("vibrance", "Vibrance", -100.0, 100.0, 0.0, "%", None), ("saturation", "Saturation", -100.0, 100.0, 0.0, "%", None)]),
"hueSaturation" => hue_saturation(ui, v, cx),
"colorBalance" => color_balance(ui, v, cx),
"blackWhite" => black_white(ui, v, cx),
"photoFilter" => photo_filter(ui, v, cx),
"channelMixer" => channel_mixer(ui, v, cx),
- "posterize" => sliders(ui, v, &[("levels", "Levels", 2.0, 255.0, 4.0, "")]),
+ "posterize" => sliders(ui, v, &[("levels", "Levels", 2.0, 255.0, 4.0, "", None)]),
"threshold" => threshold(ui, v, cx),
"gradientMap" => gradient_map(ui, v, cx),
_ => Edit::default(),
@@ -190,15 +190,31 @@ fn label(ui: &mut egui::Ui, text: &str) {
}
/// Labelled slider rows over top-level keys: (key, label, min, max, default, unit).
-fn sliders(ui: &mut egui::Ui, v: &mut Value, rows: &[(&str, &str, f32, f32, f32, &str)]) -> Edit {
+/// A row of [`sliders`]: params key, label, range, default, unit, and its decimal places (None:
+/// two for a range of 10 or less, else whole numbers).
+type SliderRow<'a> = (&'a str, &'a str, f32, f32, f32, &'a str, Option<u32>);
+
+/// The value a [`sliders`] row stores for `x`: rounded to `decimals` places, or by its range.
+pub(crate) fn row_value(x: f32, min: f32, max: f32, decimals: Option<u32>) -> f32 {
+ match decimals {
+ Some(d) => {
+ let scale = 10f32.powi(d.min(6) as i32);
+ (x * scale).round() / scale
+ }
+ None if max - min <= 10.0 => round(x, 0.01),
+ None => x.round(),
+ }
+}
+
+fn sliders(ui: &mut egui::Ui, v: &mut Value, rows: &[SliderRow]) -> Edit {
let mut e = Edit::default();
- for &(key, text, min, max, default, unit) in rows {
+ for &(key, text, min, max, default, unit, decimals) in rows {
let mut x = num(v, key, default).clamp(min, max);
// A double-click on the slider puts it back to its default (Photoshop).
let gestures = widgets::RowGestures { reset: Some(default), wheel_step: None };
- let r = widgets::slider_row_with(ui, text, &mut x, min..=max, unit, None, gestures);
+ let r = widgets::slider_row_prec(ui, text, &mut x, min..=max, unit, None, gestures, decimals);
if r.changed() {
- v[key] = json!(if max - min <= 10.0 { round(x, 0.01) } else { x.round() });
+ v[key] = json!(row_value(x, min, max, decimals));
}
e.add(Edit::of(&r));
}
@@ -222,7 +238,7 @@ fn track_stops<'a>(cx: &EditorCx, stops: &'a [Color32]) -> Option<&'a [Color32]>
fn brightness_contrast(ui: &mut egui::Ui, v: &mut Value) -> Edit {
let legacy = flag(v, "legacy", false);
let lo = if legacy { -100.0 } else { -50.0 };
- let mut e = sliders(ui, v, &[("brightness", tl!("Brightness"), -150.0, 150.0, 0.0, ""), ("contrast", tl!("Contrast"), lo, 100.0, 0.0, "")]);
+ let mut e = sliders(ui, v, &[("brightness", tl!("Brightness"), -150.0, 150.0, 0.0, "", None), ("contrast", tl!("Contrast"), lo, 100.0, 0.0, "", None)]);
let mut l = legacy;
if widgets::checkbox(ui, &mut l, tl!("Use Legacy")).changed() {
v["legacy"] = json!(l);
@@ -798,7 +814,7 @@ fn threshold(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Edit {
p.line_segment([pos2(x, hr.top()), pos2(x, hr.bottom())], Stroke::new(1.0, t.accent));
p.rect_stroke(hr, 0.0, Stroke::new(1.0, t.field_border), StrokeKind::Inside);
ui.add_space(4.0);
- sliders(ui, v, &[("level", tl!("Threshold Level"), 1.0, 255.0, 128.0, "")])
+ sliders(ui, v, &[("level", tl!("Threshold Level"), 1.0, 255.0, 128.0, "", None)])
}
// ---------------------------------------------------------------------------------------------
@@ -912,7 +928,11 @@ fn hue_saturation(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Edit {
o["hue"] = json!(h.round());
}
sub.add(Edit::of(&r));
- sub.add(sliders(ui, &mut o, &[("saturation", tl!("Saturation"), -100.0, 100.0, 0.0, "%"), ("lightness", tl!("Lightness"), -100.0, 100.0, 0.0, "%")]));
+ sub.add(sliders(
+ ui,
+ &mut o,
+ &[("saturation", tl!("Saturation"), -100.0, 100.0, 0.0, "%", None), ("lightness", tl!("Lightness"), -100.0, 100.0, 0.0, "%", None)],
+ ));
if sub.changed {
v[key] = o;
}
@@ -1143,7 +1163,7 @@ fn photo_filter(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Edit {
e.add(r);
});
ui.data_mut(|d| d.insert_temp(mode_id, use_color));
- e.add(sliders(ui, v, &[("density", tl!("Density"), 0.0, 100.0, 25.0, "%")]));
+ e.add(sliders(ui, v, &[("density", tl!("Density"), 0.0, 100.0, 25.0, "%", None)]));
let mut pl = flag(v, "preserveLuminosity", true);
if widgets::checkbox(ui, &mut pl, tl!("Preserve Luminosity")).changed() {
v["preserveLuminosity"] = json!(pl);
diff --git a/crates/ui-egui/src/adjust_editors_tests.rs b/crates/ui-egui/src/adjust_editors_tests.rs
index 478b2de68..805bbbdd9 100644
--- a/crates/ui-egui/src/adjust_editors_tests.rs
+++ b/crates/ui-egui/src/adjust_editors_tests.rs
@@ -664,3 +664,89 @@ fn properties_white_point_eyedropper_edits_the_layer(kind: &str) {
h.state_mut().run("edit.undo", json!({})).unwrap();
assert_eq!(layer(&h).1, before);
}
+
+/// A bare `kind` editor over `params`, as the Properties panel and the dialog host it.
+fn editor_harness(kind: &'static str, params: serde_json::Value) -> Harness<'static, serde_json::Value> {
+ use crate::adjust_editors::{EditorCx, editor};
+ let mut h = Harness::builder().with_size(vec2(300.0, 400.0)).build_ui_state(
+ move |ui, values: &mut serde_json::Value| {
+ let cx = EditorCx {
+ mem: egui::Id::new("precision"),
+ hist: None,
+ gray: false,
+ swatches: [[0.0; 3], [1.0; 3]],
+ gradients: Vec::new(),
+ dialog: true,
+ dynamic_color_sliders: true,
+ };
+ editor(ui, kind, values, &cx);
+ },
+ params,
+ );
+ PhotocraftApp::setup_context(&h.ctx, Default::default());
+ h.run_steps(4);
+ h
+}
+
+/// Types `text` into the `index`th number field and commits it with Enter.
+fn type_into_field(h: &mut Harness<'static, serde_json::Value>, index: usize, text: &str) {
+ h.query_all_by_role(egui::accesskit::Role::SpinButton).nth(index).unwrap().click();
+ h.run_steps(2);
+ h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
+ h.run_steps(1);
+ h.event(egui::Event::Text(text.into()));
+ h.run_steps(1);
+ h.key_press(egui::Key::Enter);
+ h.run_steps(3);
+}
+
+/// The text the `index`th number field shows.
+fn field_text(h: &Harness<'static, serde_json::Value>, index: usize) -> String {
+ h.query_all_by_role(egui::accesskit::Role::SpinButton).nth(index).unwrap().value().unwrap_or_default()
+}
+
+/// #4164: Exposure keeps fractional stops (Photoshop: two decimals) and Offset four decimals,
+/// instead of rounding Exposure to whole stops because its range is wider than 10.
+#[test]
+fn exposure_keeps_fractional_stops_and_offset_four_decimals() {
+ let mut h = editor_harness("exposure", json!({}));
+ type_into_field(&mut h, 0, "0.5");
+ assert_eq!(h.state()["exposure"].as_f64(), Some(0.5), "{}", h.state());
+ type_into_field(&mut h, 0, "-1.37");
+ assert!((h.state()["exposure"].as_f64().unwrap() + 1.37).abs() < 1e-4, "{}", h.state());
+ type_into_field(&mut h, 1, "0.0123");
+ assert!((h.state()["offset"].as_f64().unwrap() - 0.0123).abs() < 1e-6, "{}", h.state());
+ type_into_field(&mut h, 2, "1.234");
+ assert!((h.state()["gamma"].as_f64().unwrap() - 1.23).abs() < 1e-4, "Gamma keeps two decimals: {}", h.state());
+ h.run_steps(2);
+ assert_eq!(field_text(&h, 0), "-1.37");
+ assert_eq!(field_text(&h, 1), "0.0123");
+ assert_eq!(field_text(&h, 2), "1.23");
+}
+
+/// #4164: the integer rows that share Exposure's slider code stay whole numbers.
+#[test]
+fn integer_adjustment_rows_stay_whole_numbers() {
+ for (kind, key, typed, want) in [
+ ("posterize", "levels", "4.6", 5.0),
+ ("threshold", "level", "100.4", 100.0),
+ ("brightnessContrast", "brightness", "12.7", 13.0),
+ ("vibrance", "vibrance", "-20.4", -20.0),
+ ] {
+ let mut h = editor_harness(kind, json!({}));
+ type_into_field(&mut h, 0, typed);
+ assert_eq!(h.state()[key].as_f64(), Some(want), "{kind}: {}", h.state());
+ }
+}
+
+/// #4164: a row's own decimals win over the range rule; rows without them keep it.
+#[test]
+fn row_values_round_to_their_own_decimals() {
+ use crate::adjust_editors::row_value;
+ assert_eq!(row_value(0.5, -20.0, 20.0, Some(2)), 0.5);
+ assert_eq!(row_value(-1.374, -20.0, 20.0, Some(2)), -1.37);
+ assert!((row_value(0.012_34, -0.5, 0.5, Some(4)) - 0.0123).abs() < 1e-7);
+ assert_eq!(row_value(4.6, 2.0, 255.0, None), 5.0, "wide ranges stay whole numbers");
+ assert!((row_value(1.234, 0.01, 9.99, None) - 1.23).abs() < 1e-6, "small ranges keep two decimals");
+ assert!(row_value(f32::NAN, -20.0, 20.0, Some(u32::MAX)).is_nan(), "no panic on odd input");
+}
diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs
index 5a3def4f2..8d57c51e7 100644
--- a/crates/ui-egui/src/widgets.rs
+++ b/crates/ui-egui/src/widgets.rs
@@ -973,6 +973,22 @@ pub fn slider_row_with(
suffix: &str,
gradient: Option<&[Color32]>,
g: RowGestures,
+) -> Response {
+ slider_row_prec(ui, label, value, range, suffix, gradient, g, None)
+}
+
+/// [`slider_row_with`] whose field shows `decimals` places instead of the one (or two, for a
+/// small range) it picks itself: Exposure's ±20 stops show two, its Offset four (#4164).
+#[allow(clippy::too_many_arguments)]
+pub fn slider_row_prec(
+ ui: &mut Ui,
+ label: &str,
+ value: &mut f32,
+ range: std::ops::RangeInclusive<f32>,
+ suffix: &str,
+ gradient: Option<&[Color32]>,
+ g: RowGestures,
+ decimals: Option<u32>,
) -> Response {
let t = Tokens::get(ui.ctx());
let mut changed_resp = None;
@@ -981,7 +997,7 @@ pub fn slider_row_with(
let l = ui.label(egui::RichText::new(tl!(label)).color(t.text_dim));
scrub_label_within(ui, &l, f32::INFINITY);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
- changed_resp = Some(value_field(ui, value, range.clone(), suffix, 74.0));
+ changed_resp = Some(value_field_in(ui, value, range.clone(), suffix, 74.0, 0.0, FieldOpts { decimals, units: None }).0);
});
});
let s = slider_with(ui, value, range, gradient, g);