PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Free Transform: W and H take a typed length in percent view (#6284) (#6293)
David Mann3cafc636564f
diff --git a/crates/ui-egui/src/numeric_expression.rs b/crates/ui-egui/src/numeric_expression.rsindex a3232dd96..6c7f96393 100644--- a/crates/ui-egui/src/numeric_expression.rs+++ b/crates/ui-egui/src/numeric_expression.rs@@ -19,6 +19,10 @@ pub struct Units<'s> {pub dpi: f64,/// Points per inch (72 PostScript, 72.27 traditional).pub ppi: f64,+ /// The length in pixels that 100 % stands for, in a field that is both (Free Transform's W+ /// and H, #6284): a length then converts into its percent and a percentage into its length.+ /// `None` (most fields) keeps lengths and percentages apart.+ pub extent: Option<f64>,}/// Unit names a number may carry, longest first so `pica` wins over `pc`.@@ -34,8 +38,9 @@ const UNIT_NAMES: [(&str, Unit); 8] = [];/// [`parse`] where a number may carry a unit (`2in`, `5 mm`, `50%`), converted into the field's-/// unit. A unit that can't convert (a length in a percent field, any unit in a unitless one) makes-/// the whole text invalid; without `units`, unit names are invalid as before.+/// unit. A unit that can't convert (a length in a percent field without an [`Units::extent`], any+/// unit in a unitless one) makes the whole text invalid; without `units`, unit names are invalid+/// as before.pub(crate) fn parse_with_units(text: &str, units: Option<Units>) -> Option<f64> {if text.len() > 1024 {return None;@@ -168,7 +173,13 @@ impl Parser<'_> {Some(field) if field == typed => Some(value),// Lengths convert through pixels; a percentage has no length to convert against.Some(field) if field != Unit::Percent && typed != Unit::Percent => Some(field.from_px(typed.to_px(value, dpi, 1.0, ppi), dpi, 1.0, ppi)),- _ => None,+ // A field whose 100 % is a length: convert through that length's pixels.+ Some(field) => {+ let extent = units.extent.map(f64::abs).filter(|e| e.is_finite() && *e > 1e-9)?;+ let v = field.from_px(typed.to_px(value, dpi, extent, ppi), dpi, extent, ppi);+ v.is_finite().then_some(v)+ }+ None => None,}}}@@ -206,10 +217,10 @@ mod tests {#[test]fn units_convert_into_the_field_unit_and_bad_input_is_rejected() {use super::{Unit, Units, parse_with_units};- let px = Units { unit: Some(Unit::Pixels), suffix: "px", dpi: 300.0, ppi: 72.0 };- let pt = Units { unit: Some(Unit::Points), suffix: "pt", dpi: 144.0, ppi: 72.0 };- let pct = Units { unit: Some(Unit::Percent), suffix: "%", dpi: 72.0, ppi: 72.0 };- let deg = Units { unit: None, suffix: "°", dpi: 72.0, ppi: 72.0 };+ let px = Units { unit: Some(Unit::Pixels), suffix: "px", dpi: 300.0, ppi: 72.0, extent: None };+ let pt = Units { unit: Some(Unit::Points), suffix: "pt", dpi: 144.0, ppi: 72.0, extent: None };+ let pct = Units { unit: Some(Unit::Percent), suffix: "%", dpi: 72.0, ppi: 72.0, extent: None };+ let deg = Units { unit: None, suffix: "°", dpi: 72.0, ppi: 72.0, extent: None };for (text, units, want) in [("1in", px, 300.0),("2.54cm", px, 300.0),@@ -255,6 +266,40 @@ mod tests {}assert_eq!(parse("1in"), None, "without a field unit, unit names stay invalid");}+ #[test]+ fn a_field_with_an_extent_converts_between_lengths_and_percent() {+ use super::{Unit, Units, parse_with_units};+ // Free Transform's W at 300 ppi for a 600 px side (#6284): 100 % is 600 px, 2 in.+ let pct = Units { unit: Some(Unit::Percent), suffix: "%", dpi: 300.0, ppi: 72.0, extent: Some(600.0) };+ let px = Units { unit: Some(Unit::Pixels), suffix: "px", ..pct };+ let inches = Units { unit: Some(Unit::Inches), suffix: "in", ..pct };+ for (text, units, want) in [+ ("300px", pct, 50.0),+ ("1in", pct, 50.0),+ ("2in*2", pct, 200.0),+ ("2.54cm", pct, 50.0),+ ("-1in", pct, -50.0),+ ("50%", pct, 50.0),+ ("50", pct, 50.0),+ ("50%", px, 300.0),+ ("50%+10", px, 310.0),+ ("150%", inches, 3.0),+ ("10%3", px, 1.0),+ ] {+ let got = parse_with_units(text, Some(units));+ assert!(got.is_some_and(|v| (v - want).abs() < 1e-9), "{text}: {got:?}, want {want}");+ }+ // A degenerate or hostile extent can't convert, and never divides by zero.+ for extent in [Some(0.0), Some(f64::NAN), Some(f64::INFINITY), None] {+ assert_eq!(parse_with_units("1in", Some(Units { extent, ..pct })), None, "{extent:?}");+ assert_eq!(parse_with_units("50%", Some(Units { extent, ..px })), None, "{extent:?}");+ }+ assert_eq!(parse_with_units("1e308in", Some(Units { extent: Some(1e-6), ..pct })), None, "an overflow is invalid");+ // Other percent fields (opacity, fill …) still reject a length.+ let opacity = Units { extent: None, ..pct };+ assert_eq!(parse_with_units("40px", Some(opacity)), None);+ assert_eq!(parse_with_units("2in", Some(opacity)), None);+ }}#[cfg(test)]diff --git a/crates/ui-egui/src/transform_tool.rs b/crates/ui-egui/src/transform_tool.rsindex 7f4238ae8..7ae223029 100644--- a/crates/ui-egui/src/transform_tool.rs+++ b/crates/ui-egui/src/transform_tool.rs@@ -2880,14 +2880,17 @@ pub(crate) fn position_size_fields(app: &mut PhotocraftApp, ui: &mut egui::Ui, tlet (suffix, places) = (u.unit.suffix(), u.unit.decimals() as u32);// Lengths need more room than a percentage ("2116.67 mm").let size_w = if u.unit == photocraft_engine::prefs::Unit::Percent { 66.0 } else { 84.0 };+ // Whatever their unit, W and H take any other typed in (`500 px` or `2 in` in percent, `50%`+ // in a length), converted at the document's resolution against the box's original side (#6284).+ let units = crate::widgets::FieldUnits { unit: u.unit, dpi: u.dpi, ppi: u.ppi };lbl(ui, "W:");- let rw = crate::widgets::value_field_prec(ui, &mut w, -wlim_u..=wlim_u, suffix, size_w, places);+ let rw = crate::widgets::value_field_extent(ui, &mut w, -wlim_u..=wlim_u, suffix, size_w, places, units, side_w);let link = !app.ui.transform_unlinked;if crate::icons::button(ui, if link { "link" } else { "unlink" }, 22.0, link, tl!("Maintain aspect ratio")).clicked() {app.ui.transform_unlinked = link;}lbl(ui, "H:");- let rh = crate::widgets::value_field_prec(ui, &mut h, -hlim_u..=hlim_u, suffix, size_w, places);+ let rh = crate::widgets::value_field_extent(ui, &mut h, -hlim_u..=hlim_u, suffix, size_w, places, units, side_h);for r in [&rw, &rh] {r.context_menu(|ui| {if let Some(name) = crate::rulers::unit_menu(ui, u.unit) {@@ -3514,6 +3517,93 @@ mod tests {assert_eq!(shown_size(&bar_harness(|_| {})), ["100", "100"]);}+ /// Opens a document at `dpi` so the W/H fields convert typed lengths at its resolution.+ fn at_dpi(app: &mut PhotocraftApp, dpi: f32) {+ app.session.execute("file.new", json!({"width": 400, "height": 400})).unwrap();+ app.session+ .edit("resolution", |doc, _| {+ doc.resolution_dpi = dpi;+ Ok(())+ })+ .unwrap();+ }++ /// The box's width and height in px after a W/H edit.+ fn box_size(t: &TransformSession) -> (f64, f64) {+ (t.quad[1][0] - t.quad[0][0], t.quad[3][1] - t.quad[0][1])+ }++ #[test]+ fn w_and_h_in_percent_take_a_typed_length() {+ use photocraft_engine::prefs::Unit;+ let near = |a: f64, b: f64| (a - b).abs() < 0.01;+ // The 100 × 50 px box with W/H showing percent (#6284): a typed length is the box's new side.+ for (text, px) in+ [("40px", 40.0), ("40 px", 40.0), ("2in", 600.0), ("2 in", 600.0), ("5cm", 5.0 / 2.54 * 300.0), ("25.4mm", 300.0), ("72pt", 300.0), ("1pica", 50.0)]+ {+ // Linked: the height follows the width.+ let t = type_into_bar_field_with(|app| at_dpi(app, 300.0), 2, text);+ let (w, h) = box_size(&t);+ assert!(near(w, px) && near(h, px / 2.0), "{text} linked: {w} × {h}");+ // Unlinked: only the width changes.+ let t = type_into_bar_field_with(+ |app| {+ at_dpi(app, 300.0);+ app.ui.transform_unlinked = true;+ },+ 2,+ text,+ );+ let (w, h) = box_size(&t);+ assert!(near(w, px) && near(h, 50.0), "{text} unlinked: {w} × {h}");+ }+ // H takes a length too; linked, the width follows.+ let t = type_into_bar_field_with(|app| at_dpi(app, 300.0), 3, "1in");+ let (w, h) = box_size(&t);+ assert!(near(w, 600.0) && near(h, 300.0), "H 1in: {w} × {h}");+ // A plain number is still the percentage.+ let (w, _) = box_size(&type_into_bar_field_with(|app| at_dpi(app, 300.0), 2, "40"));+ assert!(near(w, 40.0), "40 is 40 % of 100 px: {w}");+ // A percentage typed into a length field is that share of the box's original side.+ let px = |app: &mut PhotocraftApp| {+ at_dpi(app, 300.0);+ set_size_unit(app, Unit::Pixels.name());+ };+ let (w, h) = box_size(&type_into_bar_field_with(px, 2, "50%"));+ assert!(near(w, 50.0) && near(h, 25.0), "50% in px: {w} × {h}");+ let inches = |app: &mut PhotocraftApp| {+ at_dpi(app, 300.0);+ set_size_unit(app, Unit::Inches.name());+ };+ let (w, h) = box_size(&type_into_bar_field_with(inches, 3, "300%"));+ assert!(near(w, 300.0) && near(h, 150.0), "300% in inches: {w} × {h}");+ }++ #[test]+ fn w_and_h_reject_or_clamp_hostile_typed_lengths() {+ let near = |a: f64, b: f64| (a - b).abs() < 0.01;+ // Text that is no number leaves the box alone.+ for text in ["px", "in", "NaN", "%"] {+ let (w, h) = box_size(&type_into_bar_field_with(|app| at_dpi(app, 300.0), 2, text));+ assert!(near(w, 100.0) && near(h, 50.0), "{text}: {w} × {h}");+ }+ // Invalid text after a number keeps only what applied while typing (a plain number applies+ // per keystroke), never a NaN or a box past the largest document.+ for text in ["1in/0", "1e400px", "2 inches", "1e308in"] {+ let (w, h) = box_size(&type_into_bar_field_with(|app| at_dpi(app, 300.0), 2, text));+ assert!(w.is_finite() && h.is_finite() && w.abs() <= f64::from(POSITION_LIMIT_PX) + 0.01, "{text}: {w} × {h}");+ }+ // A huge length stops at the field's limit: the box stays within the largest document.+ let (w, h) = box_size(&type_into_bar_field_with(|app| at_dpi(app, 300.0), 2, "1e9in"));+ assert!(w.is_finite() && w <= f64::from(POSITION_LIMIT_PX) + 0.01 && h <= f64::from(POSITION_LIMIT_PX), "{w} × {h}");+ // A negative length flips, as a negative percentage does.+ let (w, _) = box_size(&type_into_bar_field_with(|app| at_dpi(app, 300.0), 2, "-40px"));+ assert!(near(w, -40.0), "{w}");+ // Zero collapses the side without dividing by zero.+ let (w, h) = box_size(&type_into_bar_field_with(|app| at_dpi(app, 300.0), 2, "0px"));+ assert!(w.is_finite() && h.is_finite(), "{w} × {h}");+ }+#[test]fn right_clicking_w_or_h_picks_their_unit_and_remembers_it() {use egui_kittest::kittest::Queryable;diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rsindex 19f47830d..0a9105838 100644--- a/crates/ui-egui/src/widgets.rs+++ b/crates/ui-egui/src/widgets.rs@@ -350,6 +350,25 @@ pub fn value_field_units(ui: &mut Ui, value: &mut f32, range: std::ops::RangeIncvalue_field_in(ui, value, range, "", width, 0.0, FieldOpts { decimals: Some(decimals), units: Some(units), ..Default::default() }).0}+/// A [`value_field_prec`] in `units` whose 100 % is a length of `extent` px (Free Transform's W+/// and H): a length typed while it shows percent becomes that share of `extent` (`40px`, `2in`),+/// and a percentage typed while it shows a length becomes that share of `extent` (`50%`), at+/// `units`' resolution (#6284). The field keeps its own unit.+#[allow(clippy::too_many_arguments)]+pub fn value_field_extent(+ ui: &mut Ui,+ value: &mut f32,+ range: std::ops::RangeInclusive<f32>,+ suffix: &str,+ width: f32,+ decimals: u32,+ units: FieldUnits,+ extent: f64,+) -> Response {+ let opts = FieldOpts { decimals: Some(decimals), units: Some(units), extent: Some(extent), ..Default::default() };+ value_field_in(ui, value, range, suffix, width, 0.0, opts).0+}+fn field_resolution_id() -> egui::Id {egui::Id::new("pc-field-resolution")}@@ -499,6 +518,8 @@ struct FieldOpts {decimals: Option<u32>,/// The unit typed units convert into (default: the suffix's, at [`set_field_resolution`]).units: Option<FieldUnits>,+ /// The length (px) 100 % stands for, so lengths and percentages convert into each other.+ extent: Option<f64>,wrap_drag: bool,}@@ -526,7 +547,7 @@ fn value_field_box(trailing: f32,opts: FieldOpts,) -> (Response, Rect) {- let FieldOpts { decimals, units, wrap_drag } = opts;+ let FieldOpts { decimals, units, extent, wrap_drag } = opts;let t = Tokens::get(ui.ctx());let (rect, slot) = ui.allocate_exact_size(size, Sense::hover());let scrub = take_label_scrub(ui, rect).map(|s| {@@ -544,8 +565,8 @@ fn value_field_box(// Typed text loses its spaces before parsing, so a " pt" suffix reads as "pt".let typed_suffix = suffix.trim();let units = match units {- Some(u) => crate::numeric_expression::Units { unit: Some(u.unit), suffix: typed_suffix, dpi: u.dpi, ppi: u.ppi },- None => crate::numeric_expression::Units { unit: unit_of_suffix(typed_suffix), suffix: typed_suffix, dpi, ppi },+ Some(u) => crate::numeric_expression::Units { unit: Some(u.unit), suffix: typed_suffix, dpi: u.dpi, ppi: u.ppi, extent },+ None => crate::numeric_expression::Units { unit: unit_of_suffix(typed_suffix), suffix: typed_suffix, dpi, ppi, extent },};surface(ui, rect, t.field, false);if !t.bevel {