Skip to content

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

Crop tool: W x H x Resolution mode resamples the crop to a size and resolution (#2443) (#2483)

David Mann7c18c68e24af
diff --git a/crates/engine/src/image_cmds.rs b/crates/engine/src/image_cmds.rs
index b2ee29d8c..5cd3cd7c3 100644
--- a/crates/engine/src/image_cmds.rs
+++ b/crates/engine/src/image_cmds.rs
@@ -156,17 +156,8 @@ fn image_size(s: &mut Session, p: &Value) -> Result<Value> {
let (nw, nh) = (nw.round().clamp(1.0, 300_000.0) as u32, nh.round().clamp(1.0, 300_000.0) as u32);
// Each side may reach 300000 px, but resampling writes real pixels: refuse a canvas whose
// raster alone would pass the budget, before allocating any of it (#1544).
- let bytes = u64::from(nw).saturating_mul(u64::from(nh)).saturating_mul(d.doc.pixel_format().bytes_per_pixel() as u64);
- if resample.is_some() && (nw, nh) != (ow, oh) && bytes > MAX_RESAMPLE_BYTES {
- let mp = |w: u32, h: u32| u64::from(w) * u64::from(h) / 1_000_000;
- let max_mp = MAX_RESAMPLE_BYTES / d.doc.pixel_format().bytes_per_pixel().max(1) as u64 / 1_000_000;
- return Err(bad(
- "image.imageSize",
- format!(
- "{nw} x {nh} px is {} megapixels; resampling at this bit depth is limited to {max_mp} megapixels. Choose a smaller size, or turn Resample off to change only the resolution",
- mp(nw, nh)
- ),
- ));
+ if resample.is_some() && (nw, nh) != (ow, oh) {
+ check_resample_budget("image.imageSize", &d.doc, nw, nh, ", or turn Resample off to change only the resolution")?;
}
let dpi = p.get("resolution").and_then(Value::as_f64).map(|v| v as f32);
s.edit("Image Size", |doc, _| {
@@ -174,27 +165,7 @@ fn image_size(s: &mut Session, p: &Value) -> Result<Value> {
doc.resolution_dpi = r.clamp(1.0, 10_000.0);
}
let Some(filter) = resample else { return Ok(()) };
- let (sx, sy) = (nw as f64 / ow.max(1) as f64, nh as f64 / oh.max(1) as f64);
- if (sx - 1.0).abs() < 1e-12 && (sy - 1.0).abs() < 1e-12 {
- return Ok(());
- }
- // Content that reaches the canvas edge keeps it: a Background stays opaque to the border.
- let canvas = Rect::new(0, 0, ow as i32, oh as i32);
- for_each_surface(&mut doc.layers, true, &mut |surf, is_mask| {
- *surf = resize_surface_in_canvas(surf, sx, sy, if is_mask { Resample::Bilinear } else { filter }, canvas);
- });
- let k = ((sx + sy) / 2.0) as f32;
- for_each_layer(&mut doc.layers, &mut |l| scale_effects(&mut l.effects, k));
- for ch in doc.channels.iter_mut().chain(doc.quick_mask.as_mut()) {
- ch.surface = resize_surface_in_canvas(&ch.surface, sx, sy, Resample::Bilinear, canvas);
- }
- if let Some(sel) = &doc.selection {
- doc.selection = Some(resize_surface_in_canvas(sel, sx, sy, Resample::Bilinear, canvas));
- }
- // Vector geometry, guides and marks scale with the pixels; vectors re-render sharp.
- crate::canvas_geom::transform_geometry(doc, &photocraft_geom::Affine { m: [sx, 0.0, 0.0, sy, 0.0, 0.0] });
- doc.size = Size::new(nw, nh);
- crate::canvas_geom::refresh(doc, crate::canvas_geom::Refresh::All);
+ resample_doc(doc, nw, nh, filter);
Ok(())
})?;
// The size the document has now: without resampling `width`/`height` are ignored (#1815).
@@ -202,6 +173,47 @@ fn image_size(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "width": size.width, "height": size.height }))
}
+/// Refuses to resample `doc` to `nw` x `nh` px when the raster alone would pass the budget, before
+/// allocating any of it (#1544). `hint` ends the message with what the caller can do instead.
+fn check_resample_budget(cmd: &str, doc: &Document, nw: u32, nh: u32, hint: &str) -> Result<()> {
+ let bpp = doc.pixel_format().bytes_per_pixel().max(1) as u64;
+ let bytes = u64::from(nw).saturating_mul(u64::from(nh)).saturating_mul(bpp);
+ if bytes <= MAX_RESAMPLE_BYTES {
+ return Ok(());
+ }
+ let mp = u64::from(nw).saturating_mul(u64::from(nh)) / 1_000_000;
+ let max_mp = MAX_RESAMPLE_BYTES / bpp / 1_000_000;
+ Err(bad(cmd, format!("{nw} x {nh} px is {mp} megapixels; resampling at this bit depth is limited to {max_mp} megapixels. Choose a smaller size{hint}")))
+}
+
+/// Resamples the whole document (pixels, masks, channels, selection, effects, vectors, guides) to
+/// `nw` x `nh` px with `filter`: the body of Image Size, shared by the Crop tool's W x H x Resolution
+/// mode. Callers check [`check_resample_budget`] first.
+fn resample_doc(doc: &mut Document, nw: u32, nh: u32, filter: Resample) {
+ let (ow, oh) = (doc.size.width, doc.size.height);
+ let (sx, sy) = (nw as f64 / ow.max(1) as f64, nh as f64 / oh.max(1) as f64);
+ if (sx - 1.0).abs() < 1e-12 && (sy - 1.0).abs() < 1e-12 {
+ return;
+ }
+ // Content that reaches the canvas edge keeps it: a Background stays opaque to the border.
+ let canvas = Rect::from_xywh(0, 0, ow, oh);
+ for_each_surface(&mut doc.layers, true, &mut |surf, is_mask| {
+ *surf = resize_surface_in_canvas(surf, sx, sy, if is_mask { Resample::Bilinear } else { filter }, canvas);
+ });
+ let k = ((sx + sy) / 2.0) as f32;
+ for_each_layer(&mut doc.layers, &mut |l| scale_effects(&mut l.effects, k));
+ for ch in doc.channels.iter_mut().chain(doc.quick_mask.as_mut()) {
+ ch.surface = resize_surface_in_canvas(&ch.surface, sx, sy, Resample::Bilinear, canvas);
+ }
+ if let Some(sel) = &doc.selection {
+ doc.selection = Some(resize_surface_in_canvas(sel, sx, sy, Resample::Bilinear, canvas));
+ }
+ // Vector geometry, guides and marks scale with the pixels; vectors re-render sharp.
+ crate::canvas_geom::transform_geometry(doc, &photocraft_geom::Affine { m: [sx, 0.0, 0.0, sy, 0.0, 0.0] });
+ doc.size = Size::new(nw, nh);
+ crate::canvas_geom::refresh(doc, crate::canvas_geom::Refresh::All);
+}
+
fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }
}
@@ -367,9 +379,14 @@ fn crop(s: &mut Session, p: &Value) -> Result<Value> {
}
_ => None,
};
+ let target = crop_target(p)?;
+ if let Some((tw, th)) = target.size {
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ check_resample_budget("image.crop", &d.doc, tw, th, "")?;
+ }
if let Some(a) = crop_angle(p)? {
let rect = explicit.ok_or_else(|| bad("image.crop", "an `angle` needs an explicit `x`, `y`, `width` and `height`"))?;
- return rotated_crop(s, rect, a, delete);
+ return rotated_crop(s, rect, a, delete, &target);
}
// An explicit rectangle (the Crop tool) may extend past the canvas; a selection crop is clamped.
let r = explicit
@@ -381,9 +398,82 @@ fn crop(s: &mut Session, p: &Value) -> Result<Value> {
s.edit("Crop", |doc, _| {
crop_doc(doc, "image.crop", r, delete)?;
doc.selection = None;
+ target.apply(doc);
Ok(())
})?;
- Ok(json!({ "x": r.x0, "y": r.y0, "width": r.width(), "height": r.height() }))
+ Ok(crop_result(s, json!({ "x": r.x0, "y": r.y0, "width": r.width(), "height": r.height() })))
+}
+
+/// The Crop tool's W x H x Resolution: the size (px) the cropped area is resampled to and the
+/// resolution the document gets, both optional.
+struct CropTarget {
+ size: Option<(u32, u32)>,
+ resolution: Option<f32>,
+ filter: Resample,
+}
+
+impl CropTarget {
+ /// Applies the target to a document that has just been cropped (inside the crop's history step).
+ fn apply(&self, doc: &mut Document) {
+ if let Some((w, h)) = self.size {
+ resample_doc(doc, w, h, self.filter);
+ }
+ if let Some(r) = self.resolution {
+ doc.resolution_dpi = r;
+ }
+ }
+}
+
+/// The highest resolution (ppi) a crop may set, as for Image Size.
+const MAX_CROP_RESOLUTION: f64 = 10_000.0;
+
+/// `image.crop`'s optional `targetWidth`/`targetHeight` (whole px, both or neither), `resolution`
+/// (ppi) and `resample` (as for `image.imageSize`; "none" is refused with a target size).
+fn crop_target(p: &Value) -> Result<CropTarget> {
+ const CMD: &str = "image.crop";
+ let side = |key: &str| -> Result<Option<u32>> {
+ match p.get(key) {
+ None | Some(Value::Null) => Ok(None),
+ Some(v) => v
+ .as_u64()
+ .and_then(|n| u32::try_from(n).ok())
+ .filter(|n| (1..=MAX_CROP_SIDE as u32).contains(n))
+ .map(Some)
+ .ok_or_else(|| bad(CMD, format!("`{key}` = {v} must be a whole number of pixels from 1 to {MAX_CROP_SIDE}"))),
+ }
+ };
+ let size = match (side("targetWidth")?, side("targetHeight")?) {
+ (Some(w), Some(h)) => Some((w, h)),
+ (None, None) => None,
+ _ => return Err(bad(CMD, "`targetWidth` and `targetHeight` go together")),
+ };
+ let resolution = match p.get("resolution") {
+ None | Some(Value::Null) => None,
+ Some(v) => {
+ let r = v.as_f64().filter(|r| r.is_finite() && (1.0..=MAX_CROP_RESOLUTION).contains(r));
+ Some(r.ok_or_else(|| bad(CMD, format!("`resolution` = {v} must be a number of pixels per inch from 1 to {MAX_CROP_RESOLUTION}")))? as f32)
+ }
+ };
+ let filter = match p.get("resample") {
+ None | Some(Value::Null) => Some(Resample::Bicubic),
+ Some(v) => parse_resample(v.as_str().ok_or_else(|| bad(CMD, "`resample` must be a string"))?),
+ };
+ let filter = match (filter, size) {
+ (Some(f), _) => f,
+ (None, None) => Resample::Bicubic,
+ (None, Some(_)) => return Err(bad(CMD, "a `targetWidth` x `targetHeight` crop needs resampling: `resample` can't be \"none\"")),
+ };
+ Ok(CropTarget { size, resolution, filter })
+}
+
+/// A crop's result: the frame it cropped to, plus the document's size and resolution afterwards.
+fn crop_result(s: &Session, mut frame: Value) -> Value {
+ if let (Some(d), Some(o)) = (s.active(), frame.as_object_mut()) {
+ o.insert("documentWidth".into(), json!(d.doc.size.width));
+ o.insert("documentHeight".into(), json!(d.doc.size.height));
+ o.insert("resolution".into(), json!(d.doc.resolution_dpi));
+ }
+ frame
}
/// The largest crop angle accepted (degrees), as for Image Rotation › Arbitrary.
@@ -410,7 +500,7 @@ fn crop_angle(p: &Value) -> Result<Option<f64>> {
/// background colour, other layers keep transparency there and every pixel of theirs), which makes
/// the frame upright, then cropped to it (`deleteCroppedPixels` as for an unrotated crop), all in
/// one undo step.
-fn rotated_crop(s: &mut Session, r: Rect, angle: f64, delete: bool) -> Result<Value> {
+fn rotated_crop(s: &mut Session, r: Rect, angle: f64, delete: bool, crop_target: &CropTarget) -> Result<Value> {
const CMD: &str = "image.crop";
let size = s.active().ok_or(EngineError::NoDocument)?.doc.size;
let (w, h) = (f64::from(r.width()), f64::from(r.height()));
@@ -436,10 +526,11 @@ fn rotated_crop(s: &mut Session, r: Rect, angle: f64, delete: bool) -> Result<Va
s.edit("Crop", |doc, _| {
crop_doc(doc, CMD, target, delete)?;
doc.selection = None;
+ crop_target.apply(doc);
Ok(())
})
})?;
- Ok(json!({ "x": r.x0, "y": r.y0, "width": r.width(), "height": r.height(), "angle": angle }))
+ Ok(crop_result(s, json!({ "x": r.x0, "y": r.y0, "width": r.width(), "height": r.height(), "angle": angle })))
}
/// Image → Trim.
@@ -558,7 +649,7 @@ pub fn specs() -> Vec<CommandSpec> {
"image.crop",
"Crop",
["Image"],
- r##"{"x":px,"y":px,"width":px,"height":px,"angle":-3600..3600=0,"deleteCroppedPixels":bool=true}"##,
+ r##"{"x":px,"y":px,"width":px,"height":px,"angle":-3600..3600=0,"deleteCroppedPixels":bool=true,"targetWidth":px,"targetHeight":px,"resolution":ppi,"resample":"bicubic|bilinear|nearest|lanczos|preserveDetails"="bicubic"} → {x,y,width,height,documentWidth,documentHeight,resolution} (targetWidth/targetHeight, both or neither: the cropped area is resampled to exactly that size, as Image Size, in the same undo step; resolution: the document's new ppi)"##,
has_doc,
crop
),
@@ -1004,6 +1095,86 @@ mod tests {
assert_eq!(doc(&s).size, Size::new(300_000, 2));
}
+ /// #2443: the Crop tool's W x H x Resolution crops, resamples the cropped area to exactly the
+ /// target size and sets the resolution, in one undo step, at 8 and 16 bits.
+ #[test]
+ fn crop_to_a_target_size_and_resolution_is_one_step() {
+ for depth in [8, 16] {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 400, "height": 300, "resolution": 72, "depth": depth})).unwrap();
+ s.execute("layer.new.layer", json!({})).unwrap();
+ s.edit("paint", |doc, active| {
+ doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(100, 100, 200, 225), &[1.0, 0.0, 0.0, 1.0]);
+ Ok(())
+ })
+ .unwrap();
+ let past = s.active().unwrap().history.past_len();
+ // 4 x 5 in at 300 ppi from a 100 x 125 px frame.
+ let r = s
+ .execute("image.crop", json!({"x": 100, "y": 100, "width": 100, "height": 125, "targetWidth": 1200, "targetHeight": 1500, "resolution": 300}))
+ .unwrap();
+ assert_eq!((r["documentWidth"].as_u64(), r["documentHeight"].as_u64()), (Some(1200), Some(1500)), "{depth}: {r}");
+ assert_eq!(r["resolution"].as_f64(), Some(300.0), "{depth}");
+ let d = doc(&s);
+ assert_eq!(d.size, Size::new(1200, 1500), "{depth}");
+ assert_eq!(d.resolution_dpi, 300.0, "{depth}");
+ assert_eq!(d.layers[0].surface().unwrap().format().sample, if depth == 8 { SampleType::U8 } else { SampleType::U16 });
+ // The red frame filled the crop; it fills the result.
+ let red = d.layers[1].surface().unwrap();
+ for (x, y) in [(0, 0), (600, 750), (1199, 1499)] {
+ assert_eq!(red.pixel(x, y), vec![1.0, 0.0, 0.0, 1.0], "{depth}: ({x}, {y})");
+ }
+ assert_eq!(s.active().unwrap().history.past_len(), past + 1, "{depth}: one history step");
+ s.execute("edit.undo", json!({})).unwrap();
+ assert_eq!((doc(&s).size, doc(&s).resolution_dpi), (Size::new(400, 300), 72.0), "{depth}: undo restores the original");
+ }
+ }
+
+ #[test]
+ fn crop_target_resamples_after_a_turned_crop_and_resolution_alone_keeps_the_pixels() {
+ let mut s = session();
+ let past = s.active().unwrap().history.past_len();
+ s.execute("image.crop", json!({"x": 10, "y": 0, "width": 10, "height": 20, "angle": 90, "targetWidth": 30, "targetHeight": 60, "resample": "nearest"}))
+ .unwrap();
+ assert_eq!(doc(&s).size, Size::new(30, 60));
+ assert_eq!(s.active().unwrap().history.past_len(), past + 1, "rotate, crop and resample: one step");
+ let mut s = session();
+ s.execute("image.crop", json!({"x": 2, "y": 3, "width": 30, "height": 10, "resolution": 150})).unwrap();
+ assert_eq!((doc(&s).size, doc(&s).resolution_dpi), (Size::new(30, 10), 150.0));
+ }
+
+ #[test]
+ fn crop_target_rejects_bad_params_without_changing_the_document() {
+ let rect = json!({"x": 0, "y": 0, "width": 10, "height": 10});
+ let bad_params = [
+ json!({"targetWidth": 100}),
+ json!({"targetHeight": 100}),
+ json!({"targetWidth": 0, "targetHeight": 10}),
+ json!({"targetWidth": -5, "targetHeight": 10}),
+ json!({"targetWidth": 10.5, "targetHeight": 10}),
+ json!({"targetWidth": "10", "targetHeight": 10}),
+ json!({"targetWidth": 300_001, "targetHeight": 10}),
+ json!({"targetWidth": 4_294_967_306_u64, "targetHeight": 10}),
+ json!({"targetWidth": 300_000, "targetHeight": 300_000}),
+ json!({"targetWidth": 10, "targetHeight": 10, "resample": "none"}),
+ json!({"targetWidth": 10, "targetHeight": 10, "resample": 3}),
+ json!({"resolution": 0}),
+ json!({"resolution": -72}),
+ json!({"resolution": 1e9}),
+ json!({"resolution": "300"}),
+ ];
+ for extra in bad_params {
+ let mut s = session();
+ let (size, dpi, past) = (doc(&s).size, doc(&s).resolution_dpi, s.active().unwrap().history.past_len());
+ let mut p = rect.clone();
+ if let (Some(o), Some(e)) = (p.as_object_mut(), extra.as_object()) {
+ o.extend(e.clone());
+ }
+ assert!(s.execute("image.crop", p.clone()).is_err(), "{p}");
+ assert_eq!((doc(&s).size, doc(&s).resolution_dpi, s.active().unwrap().history.past_len()), (size, dpi, past), "{p}: nothing changed");
+ }
+ }
+
#[test]
fn trim_based_on_top_left_colour() {
let mut s = session();
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs
index 86e01ecfa..2a2a068bb 100644
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@ -4365,6 +4365,8 @@ pub fn commit_crop(app: &mut PhotocraftApp) {
if angle != 0.0 {
p["angle"] = json!(angle);
}
+ // W x H x Resolution (#2443): resample to that size and set the resolution.
+ crate::crop_size::commit_params(app, &mut p);
if app.run("image.crop", p).is_ok()
&& let Some(i) = app.session.active_index()
{
diff --git a/crates/ui-egui/src/crop_size.rs b/crates/ui-egui/src/crop_size.rs
new file mode 100644
index 000000000..d6203bad7
--- /dev/null
+++ b/crates/ui-egui/src/crop_size.rs
@@ -0,0 +1,450 @@
+//! The Crop tool's W x H x Resolution mode (#2443), as in Photoshop's options bar.
+//!
+//! The preset dropdown's "W x H x Resolution" (`crop_ratio` = [`WHR`]) shows a width and a height
+//! field, each a length with its unit ("4 in", "10 cm", "25 mm", "1024 px"; a bare number keeps the
+//! field's unit, pixels for an empty field), and a resolution with its unit (px/in or px/cm).
+//!
+//! - While the frame is drawn or resized it holds W : H ([`ratio`]).
+//! - Committing (`canvas::commit_crop`) passes `targetWidth`/`targetHeight` (px) and `resolution`
+//! (ppi) to `image.crop` ([`commit_params`]): the cropped area is resampled to exactly W x H px and
+//! the document takes the resolution, in one undo step. Physical lengths convert at the typed
+//! resolution, or at the document's own when the resolution field is empty (which then leaves
+//! the resolution alone). With W or H empty the crop is not resampled (a free crop); a
+//! resolution alone still sets the document's resolution.
+//! - The dropdown's built-in presets (4 x 5 in 300 ppi, …) fill the fields; Front Image (or `I`
+//! with the Crop tool, [`keys`]) fills them with the active document's size in px and its
+//! resolution; Clear empties them; ⇄ and X swap W and H.
+
+use egui::{Modifiers, Stroke, StrokeKind, vec2};
+use photocraft_engine::prefs::Unit;
+use serde_json::{Value, json};
+
+use crate::PhotocraftApp;
+use crate::state::{Tool, ToolOptions};
+use crate::theme::Tokens;
+
+/// `crop_ratio` key of the W x H x Resolution mode.
+pub const WHR: &str = "whr";
+/// Dropdown key of Front Image (applied at once, never kept in `crop_ratio`).
+pub const FRONT: &str = "front";
+/// Resolution units of the resolution field.
+pub const PX_PER_IN: &str = "px/in";
+pub const PX_PER_CM: &str = "px/cm";
+/// Points per inch for pt / pica lengths (PostScript, Photoshop's default).
+const POINTS_PER_INCH: f64 = 72.0;
+/// The largest number a length or resolution field keeps (well past any canvas or ppi limit,
+/// which `image.crop` enforces with its own message).
+const MAX_FIELD: f64 = 1e9;
+
+/// Photoshop's built-in crop presets: (dropdown key, label, width, height, resolution in px/in).
+pub const PRESETS: &[(&str, &str, &str, &str, &str)] = &[
+ ("preset:4x5in", "4 x 5 in 300 ppi", "4 in", "5 in", "300"),
+ ("preset:8.5x11in", "8.5 x 11 in 300 ppi", "8.5 in", "11 in", "300"),
+ ("preset:1024x768px", "1024 x 768 px 92 ppi", "1024 px", "768 px", "92"),
+ ("preset:1280x800px", "1280 x 800 px 113 ppi", "1280 px", "800 px", "113"),
+ ("preset:1366x768px", "1366 x 768 px 135 ppi", "1366 px", "768 px", "135"),
+ ("preset:4x6in", "4 x 6 in 300 ppi", "4 in", "6 in", "300"),
+ ("preset:5x7in", "5 x 7 in 300 ppi", "5 in", "7 in", "300"),
+ ("preset:8x10in", "8 x 10 in 300 ppi", "8 in", "10 in", "300"),
+];
+
+/// The preset dropdown: Ratio, W x H x Resolution, the ratio presets, the size presets, Front Image.
+pub fn dropdown_options() -> Vec<(String, &'static str)> {
+ let ratios = crate::chrome_ui::CROP_RATIOS;
+ let mut v: Vec<(String, &'static str)> = Vec::with_capacity(ratios.len() + PRESETS.len() + 2);
+ let mut rest = ratios.iter();
+ if let Some((k, l)) = rest.next() {
+ v.push((k.to_string(), l));
+ }
+ v.push((WHR.to_string(), tl!("W x H x Resolution")));
+ v.extend(rest.map(|(k, l)| (k.to_string(), *l)));
+ v.extend(PRESETS.iter().map(|(k, l, ..)| (k.to_string(), *l)));
+ v.push((FRONT.to_string(), tl!("Front Image")));
+ v
+}
+
+/// The unit a suffix names (`in`, `cm`, `mm`, `px`, `pt`, `pica`, and their long forms).
+fn unit_of(suffix: &str) -> Option<Unit> {
+ Some(match suffix.to_ascii_lowercase().as_str() {
+ "px" | "pixel" | "pixels" => Unit::Pixels,
+ "in" | "inch" | "inches" | "\"" => Unit::Inches,
+ "cm" | "centimeter" | "centimeters" | "centimetre" | "centimetres" => Unit::Centimeters,
+ "mm" | "millimeter" | "millimeters" | "millimetre" | "millimetres" => Unit::Millimeters,
+ "pt" | "point" | "points" => Unit::Points,
+ "pica" | "picas" => Unit::Picas,
+ _ => return None,
+ })
+}
+
+/// A typed length: a positive number and an optional unit ("4 in", "4in", "10,5 cm", "1024").
+/// A bare number takes `fallback`. `None` for anything else (empty, zero, negative, unknown unit).
+pub fn parse_length(text: &str, fallback: Unit) -> Option<(f64, Unit)> {
+ let text = text.trim();
+ if text.is_empty() || text.len() > 64 {
+ return None;
+ }
+ let split = text.find(|c: char| c.is_alphabetic() || c == '"').unwrap_or(text.len());
+ let (num, suffix) = (text.get(..split)?.trim(), text.get(split..)?.trim());
+ let v = crate::widgets::parse_num(&num.replace(',', "."))?;
+ let unit = if suffix.is_empty() { fallback } else { unit_of(suffix)? };
+ (v.is_finite() && v > 0.0 && v <= MAX_FIELD).then_some((v, unit))
+}
+
+/// "4 in", "1024 px", "8.5 in", "2.54 cm": the number (up to its unit's decimals) and the unit.
+pub fn format_length(v: f64, unit: Unit) -> String {
+ let n = format!("{v:.*}", unit.decimals().max(2));
+ let n = if n.contains('.') { n.trim_end_matches('0').trim_end_matches('.') } else { &n };
+ format!("{n} {}", unit.suffix())
+}
+
+/// The unit a stored field value is in (pixels when it has none).
+fn field_unit(stored: &str) -> Unit {
+ parse_length(stored, Unit::Pixels).map_or(Unit::Pixels, |(_, u)| u)
+}
+
+/// What a length field keeps once typed: the normalised length, empty for an empty field, and the
+/// previous value for something that isn't a length.
+pub fn normalize_length(typed: &str, previous: &str) -> String {
+ if typed.trim().is_empty() {
+ return String::new();
+ }
+ match parse_length(typed, field_unit(previous)) {
+ Some((v, u)) => format_length(v, u),
+ None => previous.to_string(),
+ }
+}
+
+/// What the resolution field keeps once typed: a positive number, empty, or the previous value.
+pub fn normalize_resolution(typed: &str, previous: &str) -> String {
+ if typed.trim().is_empty() {
+ return String::new();
+ }
+ match crate::widgets::parse_num(&typed.trim().replace(',', ".")).filter(|v| v.is_finite() && *v > 0.0 && *v <= MAX_FIELD) {
+ Some(v) => crate::widgets::fmt_num2(v),
+ None => previous.to_string(),
+ }
+}
+
+/// The resolution field in pixels per inch, `None` when empty or not a positive number.
+pub fn resolution_ppi(o: &ToolOptions) -> Option<f64> {
+ let v = crate::widgets::parse_num(&o.crop_resolution.trim().replace(',', ".")).filter(|v| v.is_finite() && *v > 0.0)?;
+ Some(if o.crop_resolution_unit == PX_PER_CM { v * 2.54 } else { v })
+}
+
+/// W x H x Resolution's target: the size in pixels the crop is resampled to (unrounded) and the
+/// resolution it sets, when the mode is on and both W and H hold lengths. Physical lengths convert
+/// at the typed resolution, or at `doc_dpi` when there is none.
+pub fn target(o: &ToolOptions, doc_dpi: f64) -> Option<(f64, f64, Option<f64>)> {
+ if o.crop_ratio != WHR {
+ return None;
+ }
+ let res = resolution_ppi(o);
+ let dpi = res.unwrap_or(doc_dpi);
+ let px = |text: &str| {
+ let (v, u) = parse_length(text, Unit::Pixels)?;
+ let px = u.to_px(v, dpi, 0.0, POINTS_PER_INCH);
+ (px.is_finite() && px > 0.0).then_some(px)
+ };
+ Some((px(&o.crop_width)?, px(&o.crop_height)?, res))
+}
+
+/// The ratio W x H x Resolution holds while the frame is drawn or resized (width / height).
+pub fn ratio(o: &ToolOptions, doc_dpi: f64) -> Option<f64> {
+ let (w, h, _) = target(o, doc_dpi)?;
+ Some(w / h).filter(|k| k.is_finite() && *k > 0.0)
+}
+
+/// `image.crop`'s target params for the pending crop: `targetWidth`/`targetHeight` (whole px) when
+/// W and H are set, and `resolution` (ppi) when the resolution is; the Image Interpolation
+/// preference resamples.
+pub fn commit_params(app: &PhotocraftApp, p: &mut Value) {
+ let o = &app.ui.tool_options;
+ if o.crop_ratio != WHR {
+ return;
+ }
+ let doc_dpi = app.session.active().map_or(72.0, |st| f64::from(st.doc.resolution_dpi));
+ let px = |v: f64| v.round().clamp(1.0, MAX_FIELD) as u64;
+ if let Some((w, h, _)) = target(o, doc_dpi) {
+ p["targetWidth"] = json!(px(w));
+ p["targetHeight"] = json!(px(h));
+ p["resample"] = json!(crate::sizing::pref_resample(app.session.prefs().general.image_interpolation));
+ }
+ if let Some(r) = resolution_ppi(o) {
+ p["resolution"] = json!(r);
+ }
+}
+
+/// Fills W, H (px) and the resolution from the active document, in W x H x Resolution mode.
+pub fn front_image(app: &mut PhotocraftApp) {
+ let Some(d) = app.session.active().map(|st| (st.doc.size, f64::from(st.doc.resolution_dpi))) else { return };
+ let (size, dpi) = d;
+ let o = &mut app.ui.tool_options;
+ o.crop_ratio = WHR.into();
+ o.crop_width = format_length(f64::from(size.width), Unit::Pixels);
+ o.crop_height = format_length(f64::from(size.height), Unit::Pixels);
+ let res = if o.crop_resolution_unit == PX_PER_CM { dpi / 2.54 } else { dpi };
+ o.crop_resolution = crate::widgets::fmt_num2(res);
+}
+
+/// Clear in W x H x Resolution mode: empties W, H and the resolution (the mode stays).
+pub fn clear(o: &mut ToolOptions) {
+ o.crop_width.clear();
+ o.crop_height.clear();
+ o.crop_resolution.clear();
+}
+
+/// Swaps W and H (the ⇄ button, X). False outside W x H x Resolution mode.
+pub fn swap(o: &mut ToolOptions) -> bool {
+ if o.crop_ratio != WHR {
+ return false;
+ }
+ std::mem::swap(&mut o.crop_width, &mut o.crop_height);
+ true
+}
+
+/// After the preset dropdown chose `crop_ratio`: a size preset fills the fields and Front Image
+/// reads the document, both leaving W x H x Resolution mode on.
+pub fn chosen(app: &mut PhotocraftApp) {
+ let key = app.ui.tool_options.crop_ratio.clone();
+ if key == FRONT {
+ app.ui.tool_options.crop_ratio = WHR.into();
+ front_image(app);
+ } else if let Some((_, _, w, h, r)) = PRESETS.iter().find(|p| p.0 == key) {
+ let o = &mut app.ui.tool_options;
+ o.crop_ratio = WHR.into();
+ o.crop_width = (*w).into();
+ o.crop_height = (*h).into();
+ o.crop_resolution = (*r).into();
+ o.crop_resolution_unit = PX_PER_IN.into();
+ }
+}
+
+/// I with the Crop tool (no text field focused, which the caller checks): Front Image. Returns
+/// true when the key was used; otherwise I stays the Eyedropper tool key.
+pub fn keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool {
+ if app.ui.tool != Tool::Crop || app.crop.drag.is_some() || app.session.active().is_none() {
+ return false;
+ }
+ if ctx.input_mut(|i| i.consume_key(Modifiers::NONE, egui::Key::I)) {
+ front_image(app);
+ return true;
+ }
+ false
+}
+
+/// A text field for a length or the resolution: what is typed is kept while it has focus and
+/// normalised into `value` (by `normalize(typed, previous)`) when it loses it. Returns true then.
+fn text_field(ui: &mut egui::Ui, id: &str, value: &mut String, hint: &str, width: f32, normalize: fn(&str, &str) -> String) -> bool {
+ let t = Tokens::get(ui.ctx());
+ let id = ui.id().with(id);
+ let mut buf = ui.data(|d| d.get_temp::<String>(id)).unwrap_or_else(|| value.clone());
+ let (rect, _) = ui.allocate_exact_size(vec2(width, 24.0), egui::Sense::hover());
+ crate::widgets::surface(ui, rect, t.field, false);
+ if !t.bevel {
+ ui.painter().rect_stroke(rect, t.radius_sm, Stroke::new(1.0, t.field_border), StrokeKind::Inside);
+ }
+ let inner = rect.shrink2(vec2(4.0, 2.0));
+ let r = ui.put(inner, egui::TextEdit::singleline(&mut buf).id(id).char_limit(32).hint_text(hint).frame(egui::Frame::NONE).font(crate::theme::mono(12.0)));
+ if r.has_focus() {
+ ui.data_mut(|d| d.insert_temp(id, buf));
+ return false;
+ }
+ ui.data_mut(|d| d.remove::<String>(id));
+ if r.lost_focus() {
+ let new = normalize(&buf, value);
+ let changed = new != *value;
+ *value = new;
+ return changed;
+ }
+ false
+}
+
+/// The W x H x Resolution fields of the options bar: W, ⇄, H, the resolution and its unit.
+pub fn fields(o: &mut ToolOptions, ui: &mut egui::Ui) {
+ text_field(ui, "crop-width", &mut o.crop_width, tl!("Width"), 64.0, normalize_length);
+ if crate::icons::button(ui, "arrow-left-right", 22.0, false, tl!("Swaps height and width")).clicked() {
+ swap(o);
+ }
+ text_field(ui, "crop-height", &mut o.crop_height, tl!("Height"), 64.0, normalize_length);
+ text_field(ui, "crop-resolution", &mut o.crop_resolution, tl!("Resolution"), 64.0, normalize_resolution);
+ let units = [(PX_PER_IN.to_string(), "px/in"), (PX_PER_CM.to_string(), "px/cm")];
+ let before = o.crop_resolution_unit.clone();
+ if crate::widgets::dropdown(ui, "crop-resolution-unit", &mut o.crop_resolution_unit, &units, 64.0) && before != o.crop_resolution_unit {
+ // The same resolution in the other unit, as in Photoshop.
+ if let Some(v) = crate::widgets::parse_num(&o.crop_resolution.trim().replace(',', ".")).filter(|v| v.is_finite() && *v > 0.0) {
+ let v = if o.crop_resolution_unit == PX_PER_CM { v / 2.54 } else { v * 2.54 };
+ o.crop_resolution = crate::widgets::fmt_num2(v);
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use photocraft_doc::{Color, ColorMode, Document, SampleType, Size};
+
+ fn app(depth: SampleType) -> PhotocraftApp {
+ let mut doc = Document::with_background("crop", Size::new(400, 300), ColorMode::Rgb, depth, Color::WHITE);
+ doc.resolution_dpi = 72.0;
+ let mut s = photocraft_engine::Session::new();
+ s.add_document(doc, None);
+ let mut app = PhotocraftApp::new(s, crate::Services::default());
+ app.ui.tool = Tool::Crop;
+ app.ui.extras.snap = false;
+ app.ui.view.show.smart_guides = false;
+ app
+ }
+
+ fn whr(w: &str, h: &str, res: &str, unit: &str) -> ToolOptions {
+ ToolOptions {
+ crop_ratio: WHR.into(),
+ crop_width: w.into(),
+ crop_height: h.into(),
+ crop_resolution: res.into(),
+ crop_resolution_unit: unit.into(),
+ ..ToolOptions::default()
+ }
+ }
+
+ #[test]
+ fn lengths_parse_with_their_units() {
+ assert_eq!(parse_length("4 in", Unit::Pixels), Some((4.0, Unit::Inches)));
+ assert_eq!(parse_length("4in", Unit::Pixels), Some((4.0, Unit::Inches)));
+ assert_eq!(parse_length(" 10 cm ", Unit::Pixels), Some((10.0, Unit::Centimeters)));
+ assert_eq!(parse_length("25 MM", Unit::Pixels), Some((25.0, Unit::Millimeters)));
+ assert_eq!(parse_length("1024 px", Unit::Inches), Some((1024.0, Unit::Pixels)));
+ assert_eq!(parse_length("8,5 in", Unit::Pixels), Some((8.5, Unit::Inches)));
+ assert_eq!(parse_length("12", Unit::Centimeters), Some((12.0, Unit::Centimeters)), "a bare number keeps the field's unit");
+ for bad in ["", "in", "0 in", "-4 in", "4 furlongs", "NaN", "1e400 px", "4 in 5"] {
+ assert_eq!(parse_length(bad, Unit::Pixels), None, "{bad}");
+ }
+ assert_eq!(normalize_length("4in", ""), "4 in");
+ assert_eq!(normalize_length("8.50 in", ""), "8.5 in");
+ assert_eq!(normalize_length("7", "5 cm"), "7 cm", "bare numbers keep the unit typed before");
+ assert_eq!(normalize_length("7", ""), "7 px");
+ assert_eq!(normalize_length("nonsense", "5 cm"), "5 cm", "something else keeps the previous value");
+ assert_eq!(normalize_length(" ", "5 cm"), "");
+ assert_eq!(normalize_resolution("300", ""), "300");
+ assert_eq!(normalize_resolution("-3", "72"), "72");
+ assert_eq!(normalize_resolution("", "72"), "");
+ }
+
+ #[test]
+ fn target_converts_physical_units_at_the_resolution_or_the_documents() {
+ let close = |a: f64, b: f64| (a - b).abs() < 1e-6;
+ let (w, h, r) = target(&whr("4 in", "5 in", "300", PX_PER_IN), 72.0).unwrap();
+ assert!(close(w, 1200.0) && close(h, 1500.0) && r == Some(300.0));
+ let (w, h, r) = target(&whr("10 cm", "25 mm", "100", PX_PER_CM), 72.0).unwrap();
+ assert!(close(w, 1000.0) && close(h, 250.0), "{w} {h}");
+ assert!(close(r.unwrap(), 254.0), "100 px/cm is 254 ppi");
+ // No resolution: inches convert at the document's, and none is set.
+ let (w, h, r) = target(&whr("2 in", "100 px", "", PX_PER_IN), 72.0).unwrap();
+ assert!(close(w, 144.0) && close(h, 100.0) && r.is_none());
+ // W or H missing, or another mode: no target (a free crop).
+ assert_eq!(target(&whr("2 in", "", "300", PX_PER_IN), 72.0), None);
+ assert_eq!(target(&ToolOptions { crop_ratio: "1:1".into(), ..whr("2 in", "3 in", "", PX_PER_IN) }, 72.0), None);
+ }
+
+ #[test]
+ fn the_frame_holds_w_by_h() {
+ let mut app = app(SampleType::U8);
+ app.ui.tool_options = whr("4 in", "5 in", "300", PX_PER_IN);
+ assert!((ratio(&app.ui.tool_options, 72.0).unwrap() - 0.8).abs() < 1e-9);
+ let mods = Modifiers::NONE;
+ use crate::canvas::{ToolEvent, tool_event};
+ tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 10.0, pressure: 1.0 }, mods);
+ tool_event(&mut app, ToolEvent::Move { x: 110.0, y: 300.0, pressure: 1.0 }, mods);
+ tool_event(&mut app, ToolEvent::Up { x: 110.0, y: 300.0 }, mods);
+ let r = app.ui.crop_rect.unwrap();
+ assert!(((r[2] - r[0]) / (r[3] - r[1]) - 0.8).abs() < 1e-9, "{r:?}");
+ }
+
+ #[test]
+ fn presets_front_image_clear_and_swap_fill_the_fields() {
+ let mut app = app(SampleType::U8);
+ app.ui.tool_options.crop_ratio = "preset:8.5x11in".into();
+ chosen(&mut app);
+ let o = &app.ui.tool_options;
+ assert_eq!((o.crop_ratio.as_str(), o.crop_width.as_str(), o.crop_height.as_str(), o.crop_resolution.as_str()), (WHR, "8.5 in", "11 in", "300"));
+ assert!(swap(&mut app.ui.tool_options));
+ assert_eq!((app.ui.tool_options.crop_width.as_str(), app.ui.tool_options.crop_height.as_str()), ("11 in", "8.5 in"));
+ app.ui.tool_options.crop_ratio = FRONT.into();
+ chosen(&mut app);
+ let o = &app.ui.tool_options;
+ assert_eq!((o.crop_ratio.as_str(), o.crop_width.as_str(), o.crop_height.as_str(), o.crop_resolution.as_str()), (WHR, "400 px", "300 px", "72"));
+ clear(&mut app.ui.tool_options);
+ let o = &app.ui.tool_options;
+ assert_eq!((o.crop_ratio.as_str(), o.crop_width.as_str(), o.crop_height.as_str(), o.crop_resolution.as_str()), (WHR, "", "", ""));
+ // px/cm shows the document's resolution per centimetre.
+ app.ui.tool_options.crop_resolution_unit = PX_PER_CM.into();
+ front_image(&mut app);
+ assert_eq!(app.ui.tool_options.crop_resolution, "28.35");
+ // Outside the mode ⇄ is the ratio's.
+ app.ui.tool_options.crop_ratio = "16:9".into();
+ assert!(!swap(&mut app.ui.tool_options));
+ assert!(dropdown_options().iter().any(|(k, _)| k == WHR) && dropdown_options().iter().any(|(k, _)| k == FRONT));
+ }
+
+ #[test]
+ fn x_swaps_w_and_h_with_the_frame() {
+ let mut app = app(SampleType::U8);
+ app.ui.tool_options = whr("4 in", "6 in", "300", PX_PER_IN);
+ app.ui.crop_rect = Some([0.0, 0.0, 40.0, 60.0]);
+ assert!(crate::crop_ui::swap_orientation(&mut app));
+ let o = &app.ui.tool_options;
+ assert_eq!((o.crop_ratio.as_str(), o.crop_width.as_str(), o.crop_height.as_str()), (WHR, "6 in", "4 in"));
+ }
+
+ #[test]
+ fn i_with_the_crop_tool_is_front_image() {
+ let mut app = app(SampleType::U8);
+ let ctx = egui::Context::default();
+ ctx.input_mut(|i| i.events.push(egui::Event::Key { key: egui::Key::I, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }));
+ assert!(keys(&mut app, &ctx));
+ assert_eq!((app.ui.tool_options.crop_ratio.as_str(), app.ui.tool_options.crop_width.as_str()), (WHR, "400 px"));
+ // Another tool keeps I.
+ let mut app2 = self::app(SampleType::U8);
+ app2.ui.tool = Tool::Brush;
+ ctx.input_mut(|i| i.events.push(egui::Event::Key { key: egui::Key::I, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }));
+ assert!(!keys(&mut app2, &ctx));
+ }
+
+ /// Committing a W x H x Resolution crop resamples the frame's area to exactly W x H px and sets
+ /// the resolution, in one undo step, at 8 and 16 bits.
+ #[test]
+ fn commit_resamples_to_the_target_size_and_resolution() {
+ for depth in [SampleType::U8, SampleType::U16] {
+ let mut app = app(depth);
+ app.ui.tool_options = whr("4 in", "5 in", "300", PX_PER_IN);
+ app.ui.crop_rect = Some([10.0, 10.0, 110.0, 135.0]);
+ let mut p = json!({});
+ commit_params(&app, &mut p);
+ assert_eq!((p["targetWidth"].as_u64(), p["targetHeight"].as_u64(), p["resolution"].as_f64()), (Some(1200), Some(1500), Some(300.0)), "{p}");
+ let past = app.session.active().unwrap().history.past_len();
+ crate::canvas::commit_crop(&mut app);
+ let st = app.session.active().unwrap();
+ assert_eq!((st.doc.size, st.doc.resolution_dpi), (Size::new(1200, 1500), 300.0), "{depth:?}");
+ assert_eq!(st.doc.pixel_format().sample, depth);
+ assert_eq!(st.history.past_len(), past + 1, "{depth:?}: one undo step");
+ }
+ // Empty resolution: inches at the document's 72 ppi, which stays.
+ let mut app = app(SampleType::U8);
+ app.ui.tool_options = whr("2 in", "1 in", "", PX_PER_IN);
+ app.ui.crop_rect = Some([0.0, 0.0, 100.0, 50.0]);
+ crate::canvas::commit_crop(&mut app);
+ let d = &app.session.active().unwrap().doc;
+ assert_eq!((d.size, d.resolution_dpi), (Size::new(144, 72), 72.0));
+ // W empty: a plain crop.
+ let mut app = self::app(SampleType::U8);
+ app.ui.tool_options = whr("", "1 in", "", PX_PER_IN);
+ app.ui.crop_rect = Some([0.0, 0.0, 100.0, 50.0]);
+ crate::canvas::commit_crop(&mut app);
+ assert_eq!(app.session.active().unwrap().doc.size, Size::new(100, 50));
+ }
+
+ #[test]
+ fn older_tool_options_load_without_the_new_fields() {
+ let o: ToolOptions = serde_json::from_str(r#"{"crop_ratio": "1:1"}"#).unwrap();
+ assert_eq!((o.crop_width.as_str(), o.crop_resolution_unit.as_str()), ("", PX_PER_IN));
+ }
+}
diff --git a/crates/ui-egui/src/crop_ui.rs b/crates/ui-egui/src/crop_ui.rs
index 38b144145..9440b291c 100644
--- a/crates/ui-egui/src/crop_ui.rs
+++ b/crates/ui-egui/src/crop_ui.rs
@@ -190,8 +190,12 @@ fn size_ok(r: [f64; 4]) -> bool {
r[2] - r[0] >= MIN_FRAME && r[3] - r[1] >= MIN_FRAME
}
-/// The options-bar ratio preset as width / height.
+/// The options-bar ratio preset as width / height (W : H in W x H x Resolution mode).
fn preset_ratio(app: &PhotocraftApp) -> Option<f64> {
+ if app.ui.tool_options.crop_ratio == crate::crop_size::WHR {
+ let dpi = app.session.active().map_or(72.0, |s| f64::from(s.doc.resolution_dpi));
+ return crate::crop_size::ratio(&app.ui.tool_options, dpi);
+ }
let size = app.session.active().map_or((1.0, 1.0), |s| (s.doc.size.width as f64, s.doc.size.height as f64));
crate::chrome_ui::crop_ratio(&app.ui.tool_options.crop_ratio, size.0, size.1).map(|(w, h)| w / h).filter(|k| k.is_finite() && *k > 0.0)
}
@@ -480,7 +484,10 @@ pub fn swapped_ratio(key: &str, doc_w: f64, doc_h: f64) -> Option<String> {
pub fn swap_orientation(app: &mut PhotocraftApp) -> bool {
let Some(r) = app.ui.crop_rect.filter(|_| takes_keys(app)) else { return false };
let size = app.session.active().map_or((0.0, 0.0), |s| (f64::from(s.doc.size.width), f64::from(s.doc.size.height)));
- if let Some(k) = swapped_ratio(&app.ui.tool_options.crop_ratio, size.0, size.1) {
+ // W x H x Resolution swaps W and H instead of a ratio.
+ if !crate::crop_size::swap(&mut app.ui.tool_options)
+ && let Some(k) = swapped_ratio(&app.ui.tool_options.crop_ratio, size.0, size.1)
+ {
app.ui.tool_options.crop_ratio = k;
}
keyed(app, swapped(r));
diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv
index f8420af05..be44f4468 100644
--- a/crates/ui-egui/src/i18n/cs.tsv
+++ b/crates/ui-egui/src/i18n/cs.tsv
@@ -2408,3 +2408,5 @@ fontWeight Italic Kurzíva
Quick Selection found nothing there Rychlý výběr zde nic nenašel
Object Selection found nothing there — try a tighter rectangle Výběr objektu zde nic nenašel — zkuste těsnější obdélník
No subject found — try a rectangle around the object Nebyl nalezen žádný objekt — zkuste obdélník kolem objektu
+ W x H x Resolution Š x V x Rozlišení
+ Front Image Přední obraz
diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv
index 28c2209f4..9af7a8326 100644
--- a/crates/ui-egui/src/i18n/de.tsv
+++ b/crates/ui-egui/src/i18n/de.tsv
@@ -2447,3 +2447,5 @@ fontWeight Italic Kursiv
Quick Selection found nothing there Die Schnellauswahl hat dort nichts gefunden
Object Selection found nothing there — try a tighter rectangle Die Objektauswahl hat dort nichts gefunden — versuchen Sie ein engeres Rechteck
No subject found — try a rectangle around the object Kein Motiv gefunden — versuchen Sie ein Rechteck um das Objekt
+ W x H x Resolution B x H x Auflösung
+ Front Image Vorderes Bild
diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv
index 40b5a282e..59d769047 100644
--- a/crates/ui-egui/src/i18n/el.tsv
+++ b/crates/ui-egui/src/i18n/el.tsv
@@ -3516,3 +3516,5 @@ fontWeight Thin Πολύ λεπτά
Quick Selection found nothing there Η Γρήγορη επιλογή δεν βρήκε τίποτα εκεί
Object Selection found nothing there — try a tighter rectangle Η Επιλογή αντικειμένου δεν βρήκε τίποτα εκεί — δοκιμάστε ένα πιο στενό ορθογώνιο
No subject found — try a rectangle around the object Δεν βρέθηκε θέμα — δοκιμάστε ένα ορθογώνιο γύρω από το αντικείμενο
+ W x H x Resolution Π x Υ x Ανάλυση
+ Front Image Μπροστινή εικόνα
diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv
index 921b63cf4..9ebb9b945 100644
--- a/crates/ui-egui/src/i18n/es.tsv
+++ b/crates/ui-egui/src/i18n/es.tsv
@@ -2476,3 +2476,5 @@ fontWeight Italic Cursiva
Quick Selection found nothing there Selección rápida no encontró nada ahí
Object Selection found nothing there — try a tighter rectangle Selección de objeto no encontró nada ahí — pruebe un rectángulo más ajustado
No subject found — try a rectangle around the object No se encontró ningún sujeto — pruebe un rectángulo alrededor del objeto
+ W x H x Resolution An. x Al. x Resolución
+ Front Image Imagen frontal
diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv
index 1270bbe74..23d730a46 100644
--- a/crates/ui-egui/src/i18n/fr.tsv
+++ b/crates/ui-egui/src/i18n/fr.tsv
@@ -2827,3 +2827,5 @@ fontWeight Italic Italique
Quick Selection found nothing there La Sélection rapide n'a rien trouvé à cet endroit
Object Selection found nothing there — try a tighter rectangle La Sélection d'objet n'a rien trouvé à cet endroit — essayez un rectangle plus serré
No subject found — try a rectangle around the object Aucun sujet trouvé — essayez un rectangle autour de l'objet
+ W x H x Resolution L x H x Résolution
+ Front Image Image de premier plan
diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv
index 7dfbc1bb7..8ee55aa62 100644
--- a/crates/ui-egui/src/i18n/id.tsv
+++ b/crates/ui-egui/src/i18n/id.tsv
@@ -2814,3 +2814,5 @@ fontWeight Italic Miring
Quick Selection found nothing there Seleksi Cepat tidak menemukan apa pun di sana
Object Selection found nothing there — try a tighter rectangle Seleksi Objek tidak menemukan apa pun di sana — coba persegi panjang yang lebih rapat
No subject found — try a rectangle around the object Subjek tidak ditemukan — coba persegi panjang di sekitar objek
+ W x H x Resolution L x T x Resolusi
+ Front Image Gambar Depan
diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv
index fc805b687..24697c273 100644
--- a/crates/ui-egui/src/i18n/it.tsv
+++ b/crates/ui-egui/src/i18n/it.tsv
@@ -2478,3 +2478,5 @@ fontWeight Italic Corsivo
Quick Selection found nothing there Selezione rapida non ha trovato nulla lì
Object Selection found nothing there — try a tighter rectangle Selezione oggetto non ha trovato nulla lì — prova un rettangolo più stretto
No subject found — try a rectangle around the object Nessun soggetto trovato — prova un rettangolo attorno all'oggetto
+ W x H x Resolution L x A x Risoluzione
+ Front Image Immagine in primo piano
diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv
index a4ed47458..06da72f98 100644
--- a/crates/ui-egui/src/i18n/ja.tsv
+++ b/crates/ui-egui/src/i18n/ja.tsv
@@ -3428,3 +3428,5 @@ fontWeight Italic 斜体
Quick Selection found nothing there クイック選択ではそこに何も見つかりませんでした
Object Selection found nothing there — try a tighter rectangle オブジェクト選択ではそこに何も見つかりませんでした — より狭い長方形で試してください
No subject found — try a rectangle around the object 被写体が見つかりません — オブジェクトを囲む長方形を試してください
+ W x H x Resolution 幅 x 高さ x 解像度
+ Front Image 前面の画像
diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv
index 06ae1973b..c990751b0 100644
--- a/crates/ui-egui/src/i18n/ko.tsv
+++ b/crates/ui-egui/src/i18n/ko.tsv
@@ -2986,3 +2986,5 @@ fontWeight Italic 기울임
Quick Selection found nothing there 빠른 선택으로 해당 위치에서 아무것도 찾지 못했습니다
Object Selection found nothing there — try a tighter rectangle 개체 선택으로 해당 위치에서 아무것도 찾지 못했습니다 — 더 좁은 사각형을 사용해 보세요
No subject found — try a rectangle around the object 피사체를 찾을 수 없습니다 — 개체 주위에 사각형을 그려 보세요
+ W x H x Resolution 폭 x 높이 x 해상도
+ Front Image 전면 이미지
diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv
index 849131ae6..39e25894e 100644
--- a/crates/ui-egui/src/i18n/nl.tsv
+++ b/crates/ui-egui/src/i18n/nl.tsv
@@ -3587,3 +3587,5 @@ cameraRaw Whites Witten
Quick Selection found nothing there Snelle selectie heeft daar niets gevonden
Object Selection found nothing there — try a tighter rectangle Objectselectie heeft daar niets gevonden — probeer een krappere rechthoek
No subject found — try a rectangle around the object Geen onderwerp gevonden — probeer een rechthoek rond het object
+ W x H x Resolution B x H x Resolutie
+ Front Image Voorste afbeelding
diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv
index c8e750904..70d16f46b 100644
--- a/crates/ui-egui/src/i18n/pl.tsv
+++ b/crates/ui-egui/src/i18n/pl.tsv
@@ -3428,3 +3428,5 @@ cameraRaw Roughness Chropowatość
Quick Selection found nothing there Szybkie zaznaczanie nic tam nie znalazło
Object Selection found nothing there — try a tighter rectangle Zaznaczanie obiektu nic tam nie znalazło — spróbuj ciaśniejszego prostokąta
No subject found — try a rectangle around the object Nie znaleziono obiektu — spróbuj prostokąta wokół obiektu
+ W x H x Resolution Szer. x Wys. x Rozdzielczość
+ Front Image Obraz na wierzchu
diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv
index a177562c3..1248becb8 100644
--- a/crates/ui-egui/src/i18n/pt-br.tsv
+++ b/crates/ui-egui/src/i18n/pt-br.tsv
@@ -2835,3 +2835,5 @@ fontWeight Italic Itálico
Quick Selection found nothing there A Seleção rápida não encontrou nada ali
Object Selection found nothing there — try a tighter rectangle A Seleção de objeto não encontrou nada ali — tente um retângulo mais justo
No subject found — try a rectangle around the object Nenhum assunto encontrado — tente um retângulo ao redor do objeto
+ W x H x Resolution L x A x Resolução
+ Front Image Imagem frontal
diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv
index 8a6e681d3..64229d004 100644
--- a/crates/ui-egui/src/i18n/ru.tsv
+++ b/crates/ui-egui/src/i18n/ru.tsv
@@ -2692,3 +2692,6 @@ fontWeight Italic Курсив
Missing delete command Отсутствует команда удаления
Invalid delete command Недопустимая команда удаления
Layer deleted, but confirmation preference could not be saved: {error} Слой удалён, но не удалось сохранить настройку подтверждения: {error}
+ W x H x Resolution Ш x В x Разрешение
+ Front Image Изображение переднего плана
+ Swaps height and width Меняет местами высоту и ширину
diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv
index 3fa95a151..36ba34902 100644
--- a/crates/ui-egui/src/i18n/uk.tsv
+++ b/crates/ui-egui/src/i18n/uk.tsv
@@ -3515,3 +3515,5 @@ cameraRaw Masking Маскування
Quick Selection found nothing there Швидке виділення нічого тут не знайшло
Object Selection found nothing there — try a tighter rectangle Виділення об'єктів нічого тут не знайшло — спробуйте вужчий прямокутник
No subject found — try a rectangle around the object Об'єкт не знайдено — спробуйте прямокутник навколо об'єкта
+ W x H x Resolution Ш x В x Роздільна здатність
+ Front Image Зображення переднього плану
diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv
index d73aad7dd..0e437e9ba 100644
--- a/crates/ui-egui/src/i18n/zh-hans.tsv
+++ b/crates/ui-egui/src/i18n/zh-hans.tsv
@@ -2416,3 +2416,5 @@ fontWeight Italic 斜体
Quick Selection found nothing there 快速选择在该处未找到任何内容
Object Selection found nothing there — try a tighter rectangle 对象选择在该处未找到任何内容 — 请尝试更紧凑的矩形
No subject found — try a rectangle around the object 未找到主体 — 请尝试在对象周围绘制矩形
+ W x H x Resolution 宽 x 高 x 分辨率
+ Front Image 前面的图像
diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv
index f3d5bbdec..8239f5d85 100644
--- a/crates/ui-egui/src/i18n/zh-hant.tsv
+++ b/crates/ui-egui/src/i18n/zh-hant.tsv
@@ -2385,3 +2385,5 @@ fontWeight Italic 斜體
Quick Selection found nothing there 快速選取在該處找不到任何內容
Object Selection found nothing there — try a tighter rectangle 物件選取在該處找不到任何內容 — 請嘗試更緊密的矩形
No subject found — try a rectangle around the object 找不到主體 — 請嘗試在物件周圍繪製矩形
+ W x H x Resolution 寬 x 高 x 解析度
+ Front Image 前面的影像
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index b5ad66cc8..2b98aada7 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -48,6 +48,7 @@ pub mod control;
pub mod credits;
pub mod crop_overlay;
pub mod crop_shield;
+pub mod crop_size;
pub mod crop_straighten;
pub mod crop_ui;
pub mod delete_layer_prompt;
diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs
index caab8b001..5c3b200d0 100644
--- a/crates/ui-egui/src/panels.rs
+++ b/crates/ui-egui/src/panels.rs
@@ -1082,23 +1082,34 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
crate::gradient_ui::options_changed(app, &before);
}
Tool::Crop if t.pro => {
- let o = &mut app.ui.tool_options;
- let ratios: Vec<(String, &str)> = crate::chrome_ui::CROP_RATIOS.iter().map(|(k, l)| (k.to_string(), *l)).collect();
- widgets::dropdown(ui, "crop-ratio", &mut o.crop_ratio, &ratios, 120.0);
- // Custom ratio fields (Photoshop shows the preset's numbers here).
- let (mut rw, mut rh) = crate::chrome_ui::crop_ratio(&o.crop_ratio, 0.0, 0.0).map_or((0.0, 0.0), |(w, h)| (w as f32, h as f32));
- let cw = widgets::value_field(ui, &mut rw, 0.0..=99_999.0, "", 54.0).changed();
- let swap = icons::button(ui, "arrow-left-right", 22.0, false, tl!("Swaps height and width")).clicked();
- let ch = widgets::value_field(ui, &mut rh, 0.0..=99_999.0, "", 54.0).changed();
- if swap {
- std::mem::swap(&mut rw, &mut rh);
+ let presets = crate::crop_size::dropdown_options();
+ if widgets::dropdown(ui, "crop-ratio", &mut app.ui.tool_options.crop_ratio, &presets, 140.0) {
+ // A size preset or Front Image fills W x H x Resolution (#2443).
+ crate::crop_size::chosen(app);
}
- if (cw || ch || swap) && rw > 0.0 && rh > 0.0 {
- o.crop_ratio = format!("{}:{}", widgets::fmt_num(rw as f64), widgets::fmt_num(rh as f64));
+ let o = &mut app.ui.tool_options;
+ if o.crop_ratio == crate::crop_size::WHR {
+ crate::crop_size::fields(o, ui);
+ } else {
+ // Custom ratio fields (Photoshop shows the preset's numbers here).
+ let (mut rw, mut rh) = crate::chrome_ui::crop_ratio(&o.crop_ratio, 0.0, 0.0).map_or((0.0, 0.0), |(w, h)| (w as f32, h as f32));
+ let cw = widgets::value_field(ui, &mut rw, 0.0..=99_999.0, "", 54.0).changed();
+ let swap = icons::button(ui, "arrow-left-right", 22.0, false, tl!("Swaps height and width")).clicked();
+ let ch = widgets::value_field(ui, &mut rh, 0.0..=99_999.0, "", 54.0).changed();
+ if swap {
+ std::mem::swap(&mut rw, &mut rh);
+ }
+ if (cw || ch || swap) && rw > 0.0 && rh > 0.0 {
+ o.crop_ratio = format!("{}:{}", widgets::fmt_num(rw as f64), widgets::fmt_num(rh as f64));
+ }
}
widgets::vline(ui, 22.0);
if widgets::secondary_button(ui, tl!("Clear"), 0.0).clicked() {
- o.crop_ratio.clear();
+ if o.crop_ratio == crate::crop_size::WHR {
+ crate::crop_size::clear(o);
+ } else {
+ o.crop_ratio.clear();
+ }
}
crate::crop_straighten::options_button(&mut app.crop.straighten, ui);
crate::crop_overlay::options_button(o, ui);
diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs
index 8b44b05bc..6ff4f2850 100644
--- a/crates/ui-egui/src/shortcuts.rs
+++ b/crates/ui-egui/src/shortcuts.rs
@@ -415,6 +415,10 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context) {
if crate::crop_shield::keys(app, ctx) {
return;
}
+ // ... and I fills W x H x Resolution from the document (Front Image, #2443).
+ if crate::crop_size::keys(app, ctx) {
+ return;
+ }
// Single-key tools (no modifiers). D and X (`tools.defaultColors` / `tools.swapColors`) and the
// brush keys [ ] ⇧[ ⇧] (`tools.decreaseBrushSize`…) are commands, dispatched above with any
// Keyboard Shortcuts override.
diff --git a/crates/ui-egui/src/sizing.rs b/crates/ui-egui/src/sizing.rs
index 61cebf7f9..6fdc916fe 100644
--- a/crates/ui-egui/src/sizing.rs
+++ b/crates/ui-egui/src/sizing.rs
@@ -28,7 +28,7 @@ fn pref_unit(u: photocraft_engine::prefs::Unit) -> &'static str {
}
/// Image Size resampling for Preferences › General › Image Interpolation.
-fn pref_resample(i: photocraft_engine::prefs::Interpolation) -> &'static str {
+pub(crate) fn pref_resample(i: photocraft_engine::prefs::Interpolation) -> &'static str {
use photocraft_engine::prefs::Interpolation;
match i {
Interpolation::Nearest => "nearest",
diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs
index 34db56b13..38abfb4bd 100644
--- a/crates/ui-egui/src/state.rs
+++ b/crates/ui-egui/src/state.rs
@@ -532,6 +532,17 @@ pub struct ToolOptions {
pub crop_ratio: String,
#[serde(default = "yes")]
pub crop_delete: bool,
+ /// Crop W x H x Resolution (`crop_ratio` = "whr", #2443): width and height as typed lengths
+ /// with their unit ("4 in", "1024 px"; empty = unset), the resolution ("" = the document's)
+ /// and its unit ("px/in" or "px/cm"). See `crop_size`.
+ #[serde(default)]
+ pub crop_width: String,
+ #[serde(default)]
+ pub crop_height: String,
+ #[serde(default)]
+ pub crop_resolution: String,
+ #[serde(default = "default_crop_resolution_unit")]
+ pub crop_resolution_unit: String,
/// Crop overlay (#1919): the guide in the crop box, when it shows and its orientation
/// (Photoshop's defaults: Rule of Thirds, Auto Show Overlay). See `crop_overlay`.
#[serde(default)]
@@ -587,6 +598,10 @@ fn yes() -> bool {
true
}
+fn default_crop_resolution_unit() -> String {
+ crate::crop_size::PX_PER_IN.into()
+}
+
fn default_move_target() -> String {
"layer".into()
}
@@ -674,6 +689,10 @@ impl Default for ToolOptions {
move_show_transform: false,
crop_ratio: String::new(),
crop_delete: true,
+ crop_width: String::new(),
+ crop_height: String::new(),
+ crop_resolution: String::new(),
+ crop_resolution_unit: default_crop_resolution_unit(),
crop_overlay: Default::default(),
crop_overlay_show: Default::default(),
crop_overlay_orientation: 0,
diff --git a/docs/scorecard.md b/docs/scorecard.md
index 8e0c423e1..5acc89435 100644
--- a/docs/scorecard.md
+++ b/docs/scorecard.md
@@ -153,7 +153,7 @@ Corpus floors (`crates/io/tests/corpus.rs`): the enforced minimums; the corpus t
| TOOL-214-6 | Puppet Warp mesh follows the object outline (constrained triangulation) | missing | [#214](https://github.com/storytold/photocraft/issues/214) | algo/puppet.rs:136 builds a block-grid mesh |
| TOOL-214-7 | Content-Aware Scale through the Free Transform box with a live proxy preview | partial | [#214](https://github.com/storytold/photocraft/issues/214) | edit.contentAwareScale (edit_menu_cmds.rs:899) behind a parameter dialog |
| TOOL-214-8 | A measured ruler angle prefills Image Rotation > Arbitrary (0.01 deg) | missing | [#214](https://github.com/storytold/photocraft/issues/214) | Arbitrary rotation is a generic dialog; ruler only feeds straighten |
-| TOOL-214-9 | Crop: W x H x Resolution with units, saved crop presets, Straighten in the options bar | partial | [#214](https://github.com/storytold/photocraft/issues/214) | Ratio dropdown and fields, Straighten (TOOL-214-21); no W x H x Resolution with units or saved presets |
+| TOOL-214-9 | Crop: W x H x Resolution with units, saved crop presets, Straighten in the options bar | partial | [#214](https://github.com/storytold/photocraft/issues/214) | Ratio dropdown and fields, Straighten (TOOL-214-21); W x H x Resolution with units, built-in size presets and Front Image (crop_size.rs, image.crop targetWidth/targetHeight/resolution, #2443); no New/Delete Crop Preset |
| TOOL-214-10 | Pen: Alt breaks a handle, Shift 45 deg, Ctrl direct-selects, Backspace, close-drag handle | partial | [#214](https://github.com/storytold/photocraft/issues/214) | Ctrl/Cmd = Direct Selection and Alt = Convert Point on existing paths (direct_select.rs, #790); no Shift 45 deg, Backspace or Alt while drawing |
| TOOL-214-11 | Stroke Path dialog: pick any brush-based tool, Simulate Pressure | partial | [#214](https://github.com/storytold/photocraft/issues/214) | path.stroke brush, pencil, eraser (vector_cmds.rs:1170); brush-only button, no dialog |
| TOOL-214-12 | Shapes: on-canvas corner radius handles, shape feather, selection to shape with tolerance | partial | [#214](https://github.com/storytold/photocraft/issues/214) | select.convertToShape with tolerance (vector_cmds.rs:1256); radius as a field only |
diff --git a/scorecard/tools.toml b/scorecard/tools.toml
index 27648245e..ea6cee3af 100644
--- a/scorecard/tools.toml
+++ b/scorecard/tools.toml
@@ -171,7 +171,7 @@ id = "TOOL-214-9"
target = "Crop: W x H x Resolution with units, saved crop presets, Straighten in the options bar"
status = "partial"
issue = 214
-note = "Ratio dropdown and fields, Straighten (TOOL-214-21); no W x H x Resolution with units or saved presets"
+note = "Ratio dropdown and fields, Straighten (TOOL-214-21); W x H x Resolution with units, built-in size presets and Front Image (crop_size.rs, image.crop targetWidth/targetHeight/resolution, #2443); no New/Delete Crop Preset"
[[item]]
id = "TOOL-214-10"