PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Crop/marquee readout and Properties W/H/X/Y in the ruler unit (cm, mm, in…) (#2334)
llduyll1027e25c2cb484
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rsindex 338eef798..1df5b5e4d 100644--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@ -263,6 +263,20 @@ pub fn marquee_readout(r: [f64; 4]) -> [String; 2] {[format!("{} px", r[2] - r[0]), format!("{} px", r[3] - r[1])]}+/// [`marquee_readout`] in the Units & Rulers unit, as Photoshop shows it (cm when the rulers are in+/// centimeters), from the active document's resolution; pixels without a document.+pub fn size_readout(app: &PhotocraftApp, r: [f64; 4]) -> [String; 2] {+ let Some(d) = app.session.active() else { return marquee_readout(r) };+ let (dpi, size) = (f64::from(d.doc.resolution_dpi), d.doc.size);+ readout_in(&app.session.prefs().units_and_rulers, dpi, [size.width as f64, size.height as f64], r)+}++/// `r`'s width and height formatted in `ur`'s ruler unit at `dpi` (percent of `extent`).+pub fn readout_in(ur: &photocraft_engine::prefs::UnitsAndRulers, dpi: f64, extent: [f64; 2], r: [f64; 4]) -> [String; 2] {+ let s = ur.rulers.suffix();+ [format!("{} {s}", ur.format(r[2] - r[0], dpi, extent[0])), format!("{} {s}", ur.format(r[3] - r[1], dpi, extent[1]))]+}+/// Draw the marquee size readout below-right of the cursor (kept on screen), like Photoshop's:/// two rows, `W:` / `H:` labels on the left and the values right-aligned.fn draw_marquee_readout(ctx: &egui::Context, cursor: Pos2, values: [String; 2]) {@@ -3592,7 +3606,7 @@ fn draw_tool_state(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform,draw_readout(painter.ctx(), "crop-angle-readout", h, ["Angle:"], [format!("{a:.1}°")]);} else if let (Some([w, h]), Some(at)) = (crate::crop_ui::sizing(app), hover) {// Its W × H while it is drawn or resized (#1919), like the marquee's.- draw_marquee_readout(painter.ctx(), at, marquee_readout([0.0, 0.0, w, h]));+ draw_marquee_readout(painter.ctx(), at, size_readout(app, [0.0, 0.0, w, h]));}}}@@ -3679,7 +3693,7 @@ fn draw_drag_preview(app: &mut PhotocraftApp, painter: &egui::Painter, xf: &Viewlet last = d.points.last().map(|p| [p[0], p[1]]).unwrap_or(d.start);let marquee = marquee_preview_px(&app.ui.tool_options, d, app.point_zoom());if let Some(r) = marquee {- draw_marquee_readout(painter.ctx(), xf.to_screen(last[0] as f32, last[1] as f32), marquee_readout(r));+ draw_marquee_readout(painter.ctx(), xf.to_screen(last[0] as f32, last[1] as f32), size_readout(app, r));}match d.tool {// The canvas shows the live stroke itself (`LiveStroke`); a stroke that couldn't start onediff --git a/crates/ui-egui/src/doc_props_ui.rs b/crates/ui-egui/src/doc_props_ui.rsindex 544ce7cf3..2383590c7 100644--- a/crates/ui-egui/src/doc_props_ui.rs+++ b/crates/ui-egui/src/doc_props_ui.rs@@ -94,16 +94,22 @@ fn field_label(ui: &mut egui::Ui, s: &str, w: f32) {}/// A number field that only reports a committed value (drag released, Enter, focus lost).-fn committed_field(ui: &mut egui::Ui, id: &str, current: f32, suffix: &str) -> Option<f32> {+fn committed_field(ui: &mut egui::Ui, id: &str, current: f32, u: crate::layer_props_ui::LenUnit) -> Option<f32> {let key = egui::Id::new(("doc-props-field", id));- let mut v = ui.data(|d| d.get_temp::<f32>(key)).unwrap_or(current);- let r = widgets::value_field(ui, &mut v, 1.0..=300_000.0, suffix, 74.0);+ // Shown in the ruler unit (cm when the rulers are in centimeters); 100% is the current size.+ let extent = f64::from(current);+ let mut v = ui.data(|d| d.get_temp::<f32>(key)).unwrap_or_else(|| u.shown(extent, extent));+ let r = widgets::value_field(ui, &mut v, 0.01..=300_000.0, u.unit.suffix(), 74.0);if r.dragged() || r.has_focus() {ui.data_mut(|d| d.insert_temp(key, v));return None;}ui.data_mut(|d| d.remove::<f32>(key));- (r.drag_stopped() || r.lost_focus() || r.changed()).then_some(v).filter(|v| (*v - current).abs() >= 0.5)+ if !(r.drag_stopped() || r.lost_focus() || r.changed()) {+ return None;+ }+ let px = (u.px(v, extent) as f32).clamp(1.0, 300_000.0);+ ((px - current).abs() >= 0.5).then_some(px)}/// A disabled-looking field (Photoshop greys Canvas X/Y for documents without artboards).@@ -119,6 +125,7 @@ pub fn properties(app: &mut PhotocraftApp, ui: &mut egui::Ui) {let Some(st) = app.session.active() else { return };let (w, h, mode, depth, dpi) = (st.doc.size.width, st.doc.size.height, st.doc.mode, st.doc.depth, st.doc.resolution_dpi);let has_bg = st.doc.layers.first().is_some_and(|l| is_background(&st.doc, l));+ let lu = crate::layer_props_ui::LenUnit::of(app);let mut run: Vec<(String, Value)> = Vec::new();ui.horizontal(|ui| {let (r, _) = ui.allocate_exact_size(vec2(24.0, 24.0), Sense::hover());@@ -144,7 +151,7 @@ pub fn properties(app: &mut PhotocraftApp, ui: &mut egui::Ui) {ui.vertical(|ui| {ui.horizontal(|ui| {field_label(ui, "W", 18.0);- if let Some(v) = committed_field(ui, "w", w as f32, "px") {+ if let Some(v) = committed_field(ui, "w", w as f32, lu) {run.extend(canvas_resize_params((w, h), Some(v), None, linked).map(|p| ("image.canvasSize".to_string(), p)));}field_label(ui, "X", 22.0);@@ -152,7 +159,7 @@ pub fn properties(app: &mut PhotocraftApp, ui: &mut egui::Ui) {});ui.horizontal(|ui| {field_label(ui, "H", 18.0);- if let Some(v) = committed_field(ui, "h", h as f32, "px") {+ if let Some(v) = committed_field(ui, "h", h as f32, lu) {run.extend(canvas_resize_params((w, h), None, Some(v), linked).map(|p| ("image.canvasSize".to_string(), p)));}field_label(ui, "Y", 22.0);diff --git a/crates/ui-egui/src/layer_props_ui.rs b/crates/ui-egui/src/layer_props_ui.rsindex 14c6bf5c0..12554c872 100644--- a/crates/ui-egui/src/layer_props_ui.rs+++ b/crates/ui-egui/src/layer_props_ui.rs@@ -34,19 +34,48 @@ pub fn transform_params(layer: u64, b: [i32; 4], w: Option<f32>, h: Option<f32>,}/// A number field that reports a value once committed (drag released, Enter, focus lost).-fn field(ui: &mut egui::Ui, id: &str, label: &str, current: f32, width: f32) -> Option<f32> {+fn field(ui: &mut egui::Ui, id: &str, label: &str, current: f32, width: f32, u: LenUnit, extent: f64) -> Option<f32> {let t = Tokens::get(ui.ctx());let (r, _) = ui.allocate_exact_size(vec2(LABEL_W, 22.0), Sense::hover());ui.painter().text(pos2(r.right() - 2.0, r.center().y), egui::Align2::RIGHT_CENTER, tl!(label), egui::FontId::proportional(12.0), t.text_dim);let key = egui::Id::new(("layer-props-field", id));- let mut v = ui.data(|d| d.get_temp::<f32>(key)).unwrap_or(current);- let resp = widgets::value_field(ui, &mut v, -300_000.0..=300_000.0, "px", width);+ let mut v = ui.data(|d| d.get_temp::<f32>(key)).unwrap_or_else(|| u.shown(f64::from(current), extent));+ let resp = widgets::value_field(ui, &mut v, -300_000.0..=300_000.0, u.unit.suffix(), width);if resp.dragged() || resp.has_focus() {ui.data_mut(|d| d.insert_temp(key, v));return None;}ui.data_mut(|d| d.remove::<f32>(key));- (resp.drag_stopped() || resp.lost_focus() || resp.changed()).then_some(v).filter(|v| (*v - current).abs() >= 0.5)+ if !(resp.drag_stopped() || resp.lost_focus() || resp.changed()) {+ return None;+ }+ let px = u.px(v, extent) as f32;+ ((px - current).abs() >= 0.5).then_some(px)+}++/// Lengths in the Units & Rulers unit, as Photoshop's Properties panel shows them (cm when the+/// rulers are in centimeters): document px ↔ that unit at the document's resolution.+#[derive(Clone, Copy, Debug)]+pub(crate) struct LenUnit {+ pub unit: photocraft_engine::prefs::Unit,+ pub dpi: f64,+ pub ppi: f64,+}++impl LenUnit {+ pub(crate) fn of(app: &PhotocraftApp) -> Self {+ let ur = &app.session.prefs().units_and_rulers;+ let dpi = app.session.active().map_or(72.0, |s| f64::from(s.doc.resolution_dpi));+ LenUnit { unit: ur.rulers, dpi, ppi: ur.point_size.per_inch() }+ }+ /// `px` shown in the unit (`extent` is 100% for percent).+ pub(crate) fn shown(&self, px: f64, extent: f64) -> f32 {+ self.unit.from_px(px, self.dpi, extent, self.ppi) as f32+ }+ /// A value typed in the unit, in document px.+ pub(crate) fn px(&self, v: f32, extent: f64) -> f64 {+ self.unit.to_px(f64::from(v), self.dpi, extent, self.ppi)+ }}/// Align glyph: a reference line and two bars (Photoshop's align icons).@@ -99,6 +128,8 @@ pub fn properties(app: &mut PhotocraftApp, ui: &mut egui::Ui, layer: &Layer) {let mut run: Vec<(String, Value)> = Vec::new();if let Some(s) = layer.surface() {let b = app.cached_bounds(layer.id.0, s);+ let u = LenUnit::of(app);+ let (dw, dh) = app.session.active().map_or((1.0, 1.0), |s| (f64::from(s.doc.size.width), f64::from(s.doc.size.height)));if section(ui, "transform", tl!("Transform")) {let link_key = egui::Id::new("layer-props-link");let linked = ui.data(|d| d.get_temp::<bool>(link_key)).unwrap_or(true);@@ -107,24 +138,24 @@ pub fn properties(app: &mut PhotocraftApp, ui: &mut egui::Ui, layer: &Layer) {let w = ((ui.available_width() - 2.0 * (LABEL_W + LABEL_GAP) - LINK_W - 2.0 * LABEL_GAP) / 2.0).max(36.0);ui.horizontal(|ui| {ui.spacing_mut().item_spacing.x = LABEL_GAP;- if let Some(v) = field(ui, "w", "W", b.width() as f32, w) {+ if let Some(v) = field(ui, "w", "W", b.width() as f32, w, u, dw) {run.extend(transform_params(layer.id.0, bb, Some(v), None, linked).map(|p| ("edit.transform".to_string(), p)));}if crate::icons::button(ui, if linked { "link" } else { "unlink" }, LINK_W, linked, tl!("Link width and height")).clicked() {ui.data_mut(|d| d.insert_temp(link_key, !linked));}- if let Some(v) = field(ui, "h", "H", b.height() as f32, w) {+ if let Some(v) = field(ui, "h", "H", b.height() as f32, w, u, dh) {run.extend(transform_params(layer.id.0, bb, None, Some(v), linked).map(|p| ("edit.transform".to_string(), p)));}});ui.add_space(ROW_GAP);ui.horizontal(|ui| {ui.spacing_mut().item_spacing.x = LABEL_GAP;- if let Some(v) = field(ui, "x", "X", b.x0 as f32, w) {+ if let Some(v) = field(ui, "x", "X", b.x0 as f32, w, u, dw) {run.push(("layer.translate".into(), json!({"layer": layer.id.0, "dx": (v - b.x0 as f32).round() as i32, "dy": 0})));}ui.add_space(LINK_W + LABEL_GAP);- if let Some(v) = field(ui, "y", "Y", b.y0 as f32, w) {+ if let Some(v) = field(ui, "y", "Y", b.y0 as f32, w, u, dh) {run.push(("layer.translate".into(), json!({"layer": layer.id.0, "dx": 0, "dy": (v - b.y0 as f32).round() as i32})));}});@@ -194,6 +225,20 @@ pub fn properties(app: &mut PhotocraftApp, ui: &mut egui::Ui, layer: &Layer) {mod tests {use super::*;+ #[test]+ fn transform_fields_show_and_take_the_ruler_unit() {+ use photocraft_engine::prefs::Unit;+ // 72 dpi: 1644 px = 58 cm; typing 60 cm sets 1700.8 px+ let u = LenUnit { unit: Unit::Centimeters, dpi: 72.0, ppi: 72.0 };+ assert!((u.shown(1644.0, 1.0) - 58.0).abs() < 0.01);+ assert!((u.px(60.0, 1.0) - 1700.787).abs() < 0.01);+ let px = LenUnit { unit: Unit::Pixels, dpi: 150.0, ppi: 72.0 };+ assert_eq!(px.shown(170.0, 1.0), 170.0);+ assert_eq!(px.px(170.0, 1.0), 170.0);+ let pc = LenUnit { unit: Unit::Percent, dpi: 72.0, ppi: 72.0 };+ assert_eq!(pc.shown(822.0, 1644.0), 50.0);+ }+#[test]fn width_edit_scales_from_the_top_left() {let p = transform_params(7, [10, 20, 110, 70], Some(200.0), None, true).unwrap();diff --git a/crates/ui-egui/src/marquee_tests.rs b/crates/ui-egui/src/marquee_tests.rsindex e0eb785f8..42081d013 100644--- a/crates/ui-egui/src/marquee_tests.rs+++ b/crates/ui-egui/src/marquee_tests.rs@@ -677,3 +677,17 @@ fn selection_cursor_follows_the_modifiers_and_the_floating_piece() {tool_event(&mut app, ToolEvent::Move { x: 30.0, y: 20.0, pressure: 1.0 }, none);assert_eq!(selection_cursor(&app, Tool::RectMarquee, [30.0, 20.0], none), Some(SelCursor::Outline));}++#[test]+fn size_readout_follows_the_ruler_unit() {+ use photocraft_engine::prefs::{Unit, UnitsAndRulers};+ let mut ur = UnitsAndRulers::default();+ // 1644 × 2659 px at 72 dpi: 58 cm wide+ let r = [0.0, 0.0, 1644.0, 2659.0];+ ur.rulers = Unit::Pixels;+ assert_eq!(crate::canvas::readout_in(&ur, 72.0, [1644.0, 2659.0], r), ["1644 px".to_string(), "2659 px".to_string()]);+ ur.rulers = Unit::Centimeters;+ assert_eq!(crate::canvas::readout_in(&ur, 72.0, [1644.0, 2659.0], r), ["58 cm".to_string(), "93.8 cm".to_string()]);+ ur.rulers = Unit::Millimeters;+ assert_eq!(crate::canvas::readout_in(&ur, 150.0, [1644.0, 2659.0], [0.0, 0.0, 3425.0, 100.0])[0], "579.97 mm");+}