From 42ee0d967561fed2ebb1a4dff501559cc34153d2 Mon Sep 17 00:00:00 2001 From: Valentin Klein Date: Mon, 12 Oct 2026 01:33:15 +0200 Subject: [PATCH] Content-Aware Scale: transform box with live preview (#3096) (#3103) * Content-Aware Scale: transform box with live preview (#3096) Edit > Content-Aware Scale opened a parameter dialog. Photoshop has no dialog: it puts a scale-only transform box on the layer (or the selection's bounds). The menu now opens that box. - The box reuses Free Transform. Corner and edge drags scale and an inside drag moves; dragging outside does not rotate, Cmd does not skew or distort, and the Warp switch and the Transform modes are off. - The options bar shows X/Y and W/H, then Amount, Protect (an alpha channel) and Protect skin tones. - The live preview runs the command's own carving (ContentAwareScalePreview) on a 384 px copy on a worker thread. A run for a box that has changed since is cancelled after 150 ms, and the latest result is drawn through the box. - Enter runs edit.contentAwareScale with the box's size and its new x/y params as one history step; Esc cancels. - With params the command still runs directly. Scorecard TOOL-214-7: done. Co-Authored-By: Claude Opus 5.5 * Content-Aware Move's transform box: set the new content_aware field #3095 (Transform On Drop) builds a TransformSession by hand; this PR adds content_aware to it. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: Brandon Thomas --- crates/engine/src/edit_menu_cmds.rs | 174 +++++++++++--- crates/engine/src/edit_menu_cmds/tests.rs | 28 +++ crates/ui-egui/src/cam_transform.rs | 1 + crates/ui-egui/src/canvas.rs | 1 + crates/ui-egui/src/cas_transform.rs | 276 ++++++++++++++++++++++ crates/ui-egui/src/i18n/cs.tsv | 3 + crates/ui-egui/src/i18n/de.tsv | 3 + crates/ui-egui/src/i18n/el.tsv | 3 + crates/ui-egui/src/i18n/es.tsv | 3 + crates/ui-egui/src/i18n/fr.tsv | 3 + crates/ui-egui/src/i18n/id.tsv | 3 + crates/ui-egui/src/i18n/it.tsv | 3 + crates/ui-egui/src/i18n/ja.tsv | 3 + crates/ui-egui/src/i18n/ko.tsv | 3 + crates/ui-egui/src/i18n/nl.tsv | 3 + crates/ui-egui/src/i18n/pl.tsv | 3 + crates/ui-egui/src/i18n/pt-br.tsv | 3 + crates/ui-egui/src/i18n/ru.tsv | 3 + crates/ui-egui/src/i18n/uk.tsv | 3 + crates/ui-egui/src/i18n/zh-hans.tsv | 3 + crates/ui-egui/src/i18n/zh-hant.tsv | 3 + crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/menus.rs | 3 + crates/ui-egui/src/prefs_ui.rs | 25 +- crates/ui-egui/src/state.rs | 23 ++ crates/ui-egui/src/transform_tool.rs | 171 ++++++++++++-- crates/ui-egui/src/type_transform.rs | 1 + docs/scorecard.md | 4 +- scorecard/tools.toml | 4 +- 29 files changed, 682 insertions(+), 78 deletions(-) create mode 100644 crates/ui-egui/src/cas_transform.rs diff --git a/crates/engine/src/edit_menu_cmds.rs b/crates/engine/src/edit_menu_cmds.rs index 93ecd479c4..e289e43d60 100644 --- a/crates/engine/src/edit_menu_cmds.rs +++ b/crates/engine/src/edit_menu_cmds.rs @@ -507,8 +507,24 @@ fn apply_content_aware_fill( // ------------------------------------------------------------------ Content-Aware Scale -fn content_aware_scale(s: &mut Session, p: &Value) -> Result { - use photocraft_algo::seam::{carve_with, resize_bilinear, skin_mask}; +/// Reach of Content-Aware Scale's `x`/`y`: the largest document side. +const CAS_POSITION_LIMIT: f64 = 300_000.0; + +/// What Content-Aware Scale does, read from its params against the active document: the +/// command and the transform box's live preview ([`ContentAwareScalePreview`]) share it. +struct CasPlan { + doc: std::sync::Arc, + layer: LayerId, + /// The area scaled: the selection's bounds, else the layer's content. + region: Rect, + /// Where the result goes: `x`, `y` (default: the region's corner), `width`, `height`. + dst: Rect, + amount: f32, + protect: Option, + skin_tones: bool, +} + +fn cas_plan(s: &Session, p: &Value) -> Result { let cmd = "edit.contentAwareScale"; let id = pixel_layer(s).map_err(EngineError::Other)?; let st = s.active().ok_or(EngineError::NoDocument)?; @@ -522,7 +538,7 @@ fn content_aware_scale(s: &mut Session, p: &Value) -> Result { return Err(EngineError::Other("nothing to scale: the layer is empty".into())); } let (w, h) = (region.width() as usize, region.height() as usize); - let dim = |k: &str, pct: &str, cur: usize| -> Result { + let dim = |k: &str, pct: &str, cur: usize| -> Result { let v = match (p.get(k).and_then(Value::as_f64), p.get(pct).and_then(Value::as_f64)) { (Some(px), _) => px, (None, Some(pc)) => cur as f64 * pc / 100.0, @@ -531,19 +547,72 @@ fn content_aware_scale(s: &mut Session, p: &Value) -> Result { if !(1.0..=60_000.0).contains(&v) { return Err(bad(cmd, format!("`{k}` must be 1..60000 px"))); } - Ok(v.round() as usize) + Ok(v.round() as u32) }; let (nw, nh) = (dim("width", "scaleX", w)?, dim("height", "scaleY", h)?); + let at = |k: &str, cur: i32| -> Result { + match p.get(k).filter(|v| !v.is_null()) { + None => Ok(cur), + Some(v) => match v.as_f64() { + Some(x) if (-CAS_POSITION_LIMIT..=CAS_POSITION_LIMIT).contains(&x) => Ok(x.round() as i32), + _ => Err(bad(cmd, format!("`{k}` must be a number of px within ±300000"))), + }, + } + }; + let dst = Rect::from_xywh(at("x", region.x0)?, at("y", region.y0)?, nw, nh); let amount = f32_or(p, "amount", 100.0).clamp(0.0, 100.0) / 100.0; - let fmt = surf.format(); - let n = fmt.channels(); // Protection: an alpha channel and/or skin tones. - let protect_mask: Option = match p.get("protect").filter(|v| !v.is_null() && v.as_str() != Some("none")) { + let protect = match p.get("protect").filter(|v| !v.is_null() && v.as_str() != Some("none")) { Some(v) => Some(channel_mask(&doc, v).cloned().ok_or_else(|| bad(cmd, "`protect` must name an alpha channel (index or name) or \"none\""))?), None => None, }; let skin_tones = bool_or(p, "protectSkinTones", false); - let dst = Rect::from_xywh(region.x0, region.y0, nw as u32, nh as u32); + Ok(CasPlan { doc, layer: id, region, dst, amount: if amount.is_finite() { amount } else { 1.0 }, protect, skin_tones }) +} + +/// The scaled pixels: `img` (`w`×`h`, `fmt`) seam-carved to `nw`×`nh` where the protection +/// (`protect`, one value per pixel, and the skin tones when asked) steers the seams, blended with +/// a plain resample by `amount` (0..1). Checks `ctx` for cancellation before every seam. +#[allow(clippy::too_many_arguments)] +fn cas_pixels( + ctx: &crate::jobs::JobCtx, + label: &str, + img: &[f32], + (w, h): (usize, usize), + fmt: PixelFormat, + mut protect: Option>, + skin_tones: bool, + (nw, nh): (usize, usize), + amount: f32, +) -> Result> { + use photocraft_algo::seam::{carve_with, resize_bilinear, skin_mask}; + let n = fmt.channels(); + if skin_tones { + let rgba: Vec = img.chunks_exact(n).flat_map(|px| to_rgba(&fmt, px)).collect(); + let skin = skin_mask(w, h, 4, &rgba); + protect = Some(match protect { + Some(pm) => pm.iter().zip(&skin).map(|(a, b)| a.max(*b)).collect(), + None => skin, + }); + } + ctx.check()?; + let carved = if amount > 0.0 { + ctx.stage(0.05, 0.95, label, |ctl| carve_with(w, h, n, img, protect.as_deref(), nw, nh, ctl)).map_err(|_| EngineError::Cancelled)? + } else { + Vec::new() + }; + let plain = if amount < 1.0 { resize_bilinear(w, h, n, img, nw, nh) } else { Vec::new() }; + Ok(match (carved.is_empty(), plain.is_empty()) { + (false, true) => carved, + (true, false) => plain, + _ => carved.iter().zip(&plain).map(|(c, l)| l + (c - l) * amount).collect::>(), + }) +} + +fn content_aware_scale(s: &mut Session, p: &Value) -> Result { + let CasPlan { doc, layer: id, region, dst, amount, protect: protect_mask, skin_tones } = cas_plan(s, p)?; + let (w, h) = (region.width() as usize, region.height() as usize); + let (nw, nh) = (dst.width() as usize, dst.height() as usize); let label = "Content-Aware Scale"; // A background job when started with `Session::start` (#210): seam carving runs on a worker // against the document snapshot and checks for cancellation before every seam. @@ -555,28 +624,9 @@ fn content_aware_scale(s: &mut Session, p: &Value) -> Result { ctx.progress(0.0, label); let surf = doc.layer(id).and_then(|l| l.surface()).ok_or(EngineError::NoLayer(id))?; let img = surf.read_region(region); - let mut protect: Option> = + let protect: Option> = protect_mask.map(|m| (0..w * h).map(|i| m.sample_channel(region.x0 + (i % w) as i32, region.y0 + (i / w) as i32, 0)).collect()); - if skin_tones { - let rgba: Vec = img.chunks_exact(n).flat_map(|px| to_rgba(&fmt, px)).collect(); - let skin = skin_mask(w, h, 4, &rgba); - protect = Some(match protect { - Some(pm) => pm.iter().zip(&skin).map(|(a, b)| a.max(*b)).collect(), - None => skin, - }); - } - ctx.check()?; - let carved = if amount > 0.0 { - ctx.stage(0.05, 0.95, label, |ctl| carve_with(w, h, n, &img, protect.as_deref(), nw, nh, ctl)).map_err(|_| EngineError::Cancelled)? - } else { - Vec::new() - }; - let plain = if amount < 1.0 { resize_bilinear(w, h, n, &img, nw, nh) } else { Vec::new() }; - Ok(match (carved.is_empty(), plain.is_empty()) { - (false, true) => carved, - (true, false) => plain, - _ => carved.iter().zip(&plain).map(|(c, l)| l + (c - l) * amount).collect::>(), - }) + cas_pixels(ctx, label, &img, (w, h), surf.format(), protect, skin_tones, (nw, nh), amount) }, move |s, out| { s.edit(label, |doc, _| { @@ -591,6 +641,70 @@ fn content_aware_scale(s: &mut Session, p: &Value) -> Result { ) } +/// Content-Aware Scale on a reduced copy, for the transform box's live preview (#3096): the +/// command's own carving, on the area scaled down so the longer of its sides before and after +/// is at most `max_side` px. Prepared from the session ([`ContentAwareScalePreview::new`]) and +/// [`run`](ContentAwareScalePreview::run) on any thread. +pub struct ContentAwareScalePreview { + plan: CasPlan, + max_side: u32, +} + +impl ContentAwareScalePreview { + /// `p` takes `edit.contentAwareScale`'s params; the same ones fail the same way. + pub fn new(s: &Session, p: &Value, max_side: u32) -> Result { + Ok(Self { plan: cas_plan(s, p)?, max_side: max_side.max(1) }) + } + + /// The area scaled, in document px. + pub fn region(&self) -> Rect { + self.plan.region + } + + /// The reduced sizes of the area before and after: `[w, h, new w, new h]`. + fn reduced(&self) -> [usize; 4] { + let (region, dst) = (self.plan.region, self.plan.dst); + let (w, h, nw, nh) = (region.width(), region.height(), dst.width(), dst.height()); + let k = (f64::from(w.max(h).max(nw).max(nh)) / f64::from(self.max_side)).max(1.0); + let side = |v: u32| ((f64::from(v) / k).round() as usize).max(1); + [side(w), side(h), side(nw), side(nh)] + } + + /// The size of [`run`](Self::run)'s result, px. + pub fn size(&self) -> [u32; 2] { + let [_, _, w, h] = self.reduced(); + [w as u32, h as u32] + } + + /// The scaled pixels at the reduced size ([`size`](Self::size)), in the layer's format, as a + /// surface with its corner at the origin. Checks `ctx` for cancellation before every seam. + pub fn run(&self, ctx: &crate::jobs::JobCtx) -> Result { + let CasPlan { doc, layer, region, dst: _, amount, protect, skin_tones } = &self.plan; + let surf = doc.layer(*layer).and_then(|l| l.surface()).ok_or(EngineError::NoLayer(*layer))?; + let fmt = surf.format(); + let n = fmt.channels(); + let (w, h) = (region.width(), region.height()); + let [pw, ph, pnw, pnh] = self.reduced(); + // Nearest samples of the area (and of the protecting channel) at the reduced size. + let src_x: Vec = (0..pw).map(|i| region.x0 + (((i as f64 + 0.5) * f64::from(w) / pw as f64) as i32).min(w as i32 - 1)).collect(); + let src_y = |j: usize| region.y0 + (((j as f64 + 0.5) * f64::from(h) / ph as f64) as i32).min(h as i32 - 1); + let mut img = Vec::with_capacity(pw * ph * n); + for j in 0..ph { + ctx.check()?; + let row = surf.read_region(Rect::from_xywh(region.x0, src_y(j), w, 1)); + for &x in &src_x { + let at = (x - region.x0) as usize * n; + img.extend_from_slice(row.get(at..at + n).ok_or_else(|| EngineError::Other("preview read out of bounds".into()))?); + } + } + let protect = protect.as_ref().map(|m| (0..pw * ph).map(|i| m.sample_channel(src_x[i % pw], src_y(i / pw), 0)).collect()); + let out = cas_pixels(ctx, "Content-Aware Scale", &img, (pw, ph), fmt, protect, *skin_tones, (pnw, pnh), *amount)?; + let mut s = Surface::new(fmt); + s.write_region(Rect::from_xywh(0, 0, pnw as u32, pnh as u32), &out); + Ok(s) + } +} + // ------------------------------------------------------------------ Define Brush / Custom Shape fn define_brush_preset(s: &mut Session, p: &Value) -> Result { @@ -1006,7 +1120,7 @@ pub fn specs() -> Vec { "Content-Aware Scale", ["Edit"], Some("Cmd+Alt+Shift+C"), - r##"{"width":px?,"height":px?,"scaleX":1..400=100,"scaleY":1..400=100,"amount":0..100=100,"protect":"none"|channel index|name,"protectSkinTones":bool=false}"##, + r##"{"width":px?,"height":px?,"scaleX":1..400=100,"scaleY":1..400=100,"x":px?,"y":px?,"amount":0..100=100,"protect":"none"|channel index|name,"protectSkinTones":bool=false}"##, |s| pixel_layer(s).map(|_| ()), content_aware_scale ), diff --git a/crates/engine/src/edit_menu_cmds/tests.rs b/crates/engine/src/edit_menu_cmds/tests.rs index a94a054103..7b58891a82 100644 --- a/crates/engine/src/edit_menu_cmds/tests.rs +++ b/crates/engine/src/edit_menu_cmds/tests.rs @@ -298,6 +298,34 @@ fn content_aware_scale_params() { assert!(s.execute("edit.contentAwareScale", json!({"protect": "no such channel"})).is_err()); } +#[test] +fn content_aware_scale_places_the_result_and_previews_it_reduced() { + // The transform box (#3096) moves the result with `x`/`y` and previews it on a reduced copy. + for depth in [8, 16, 32] { + let mut s = session(depth); + 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(4, 4, 36, 28), &[0.2, 0.4, 0.6, 1.0]); + Ok(()) + }) + .unwrap(); + let p = json!({"width": 16, "height": 40, "x": 10, "y": 2}); + let preview = super::ContentAwareScalePreview::new(&s, &p, 10).unwrap(); + assert_eq!(preview.region(), Rect::new(4, 4, 36, 28)); + let small = preview.run(&crate::jobs::JobCtx::new()).unwrap(); + assert_eq!(small.content_bounds(), Rect::new(0, 0, 4, 10), "depth {depth}: the longest side, 40 px, previews at 10"); + let past = s.active().unwrap().history.past_len(); + let r = s.execute("edit.contentAwareScale", p).unwrap(); + assert_eq!(r["bounds"], json!([10, 2, 16, 40])); + assert_eq!(active(&s).surface().unwrap().content_bounds(), Rect::from_xywh(10, 2, 16, 40), "depth {depth}"); + assert_eq!(s.active().unwrap().history.past_len(), past + 1, "depth {depth}: one step"); + for bad in [json!({"x": "left"}), json!({"y": 1e9})] { + assert!(s.execute("edit.contentAwareScale", bad.clone()).is_err(), "{bad}"); + assert!(super::ContentAwareScalePreview::new(&s, &bad, 64).is_err(), "{bad}"); + } + } +} + #[test] fn content_aware_scale_enlarges_a_one_pixel_line() { // A 1 px wide (or tall) layer has no seam to spare, so enlarging it used to return the line diff --git a/crates/ui-egui/src/cam_transform.rs b/crates/ui-egui/src/cam_transform.rs index 181519c03d..33912a28e8 100644 --- a/crates/ui-egui/src/cam_transform.rs +++ b/crates/ui-egui/src/cam_transform.rs @@ -58,6 +58,7 @@ pub(crate) fn begin(app: &mut PhotocraftApp, offset: [i32; 2]) -> bool { path: None, made: None, mode: Default::default(), + content_aware: None, }; app.ui.cam_transform = Some(CamTransform { document, revision, offset, frame, gesture: None }); app.ui.status = crate::i18n::fmt(tl!("Scale or rotate the moved area, then press {key}"), &[("key", &crate::shortcuts::pretty("Enter"))]); diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 277035727c..d20f46e4e1 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1676,6 +1676,7 @@ fn documents(app: &mut PhotocraftApp, ui: &mut egui::Ui) { app.tab_strip = None; retain_gpu_documents(app); crate::transform_tool::track_steps(app, ui.ctx()); + crate::cas_transform::tick(app, ui.ctx()); crate::symmetry_ui::track(app, ui.ctx()); let n = app.session.documents().len(); // Files opening in the background (#210) have tabs before they have documents. diff --git a/crates/ui-egui/src/cas_transform.rs b/crates/ui-egui/src/cas_transform.rs new file mode 100644 index 0000000000..d5b263d6e8 --- /dev/null +++ b/crates/ui-egui/src/cas_transform.rs @@ -0,0 +1,276 @@ +//! Edit › Content-Aware Scale as Photoshop has it (#3096): no dialog, a transform box on the layer +//! (or the selection) that only scales and moves. The options bar has the reference point X/Y, +//! W/H, Amount, Protect (an alpha channel) and Protect Skin Tones. While the box changes, the +//! command's own seam carving runs on a reduced copy in the background and its latest result is +//! drawn through the box; ↩ runs `edit.contentAwareScale` with the box's size and position (one +//! history step) and Esc cancels. +//! +//! With params (actions, the CLI, MCP, the control channel) the command runs directly. + +use std::sync::mpsc::{Receiver, TryRecvError}; + +use egui::ColorImage; +use photocraft_engine::edit_menu_cmds::ContentAwareScalePreview; +use photocraft_engine::jobs::JobCtx; +use serde_json::{Value, json}; + +use crate::PhotocraftApp; +use crate::state::{ContentAwareOptions, TransformSession}; +use crate::transform_tex::PreviewTextures; + +pub const COMMAND: &str = "edit.contentAwareScale"; + +/// Long side of the live preview's reduced copy, px: carving it takes milliseconds, so the +/// preview follows a drag. +const PROXY_SIDE: u32 = 384; + +/// How long a preview may run for a box that has changed since before it is cancelled. Shorter +/// would cancel every preview during a drag, so none would show until the drag stops (the filter +/// previews' settle time). +const STALE_MS: f64 = 150.0; + +/// The preview being computed: what for, its result channel and its cancellation. +struct Running { + key: Value, + rx: Receiver>, + job: JobCtx, + started_ms: f64, +} + +/// The live preview of an open Content-Aware Scale box (kept with the Free Transform preview). +#[derive(Default)] +pub(crate) struct Live { + running: Option, + /// The latest finished preview and what it was computed for. + shown: Option<(Value, PreviewTextures)>, + /// Texture names must differ from one result to the next. + serial: u64, +} + +impl Drop for Live { + fn drop(&mut self) { + // A closed box stops its preview at the next seam. + if let Some(r) = &self.running { + r.job.cancel(); + } + } +} + +impl Live { + /// The latest result to draw through the box `t`, with how many document px one of its + /// texels covers there (so the texture picks the right level). `None` until a preview has + /// finished, and for an unscaled box (the full-resolution pixels show then). + pub(crate) fn shown(&self, t: &TransformSession) -> Option<(&PreviewTextures, f32)> { + let (_, tex) = self.shown.as_ref()?; + let [w, h] = box_size(t); + if [w, h] == source_size(t) { + return None; + } + let [tw, th] = tex.size(); + let texel = (w / tw.max(1) as f64).max(h / th.max(1) as f64); + Some((tex, if texel.is_finite() { texel as f32 } else { 1.0 })) + } +} + +/// Edit › Content-Aware Scale from the menu: open the box (`Err` says why it can't). +pub fn begin(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result { + if app.ui.transform.is_some() { + return Err("Commit or cancel the transform first".into()); + } + if let Some(Err(why)) = photocraft_engine::commands::find(COMMAND).map(|c| (c.enabled)(&app.session)) { + return Err(why); + } + // The command's own checks and area (the selection's bounds, else the layer's content). + let region = ContentAwareScalePreview::new(&app.session, &json!({}), PROXY_SIDE).map_err(|e| e.to_string())?.region(); + crate::transform_tool::begin_content_aware(app, ctx, region, Live::default())?; + Ok(json!({"transform": app.ui.transform})) +} + +/// The box's size, document px (its bounding box: the box only scales and moves). +fn box_size(t: &TransformSession) -> [f64; 2] { + let (x0, y0, x1, y1) = bounds(t); + [(x1 - x0).round().max(1.0), (y1 - y0).round().max(1.0)] +} + +fn source_size(t: &TransformSession) -> [f64; 2] { + [(t.rect[2] - t.rect[0]).round().max(1.0), (t.rect[3] - t.rect[1]).round().max(1.0)] +} + +fn bounds(t: &TransformSession) -> (f64, f64, f64, f64) { + t.quad.iter().fold((f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY), |(x0, y0, x1, y1), q| { + (x0.min(q[0]), y0.min(q[1]), x1.max(q[0]), y1.max(q[1])) + }) +} + +/// `edit.contentAwareScale`'s params for the box: its size and options, and with `place` its +/// position. +pub(crate) fn params(t: &TransformSession, o: &ContentAwareOptions, place: bool) -> Value { + let [w, h] = box_size(t); + let mut p = json!({ + "width": w, + "height": h, + "amount": o.amount.clamp(0.0, 100.0), + "protect": o.protect.as_deref().unwrap_or("none"), + "protectSkinTones": o.protect_skin_tones, + }); + if place { + let (x0, y0, _, _) = bounds(t); + p["x"] = json!(x0.round()); + p["y"] = json!(y0.round()); + } + p +} + +/// ↩: run the command for the box. An untouched box changes nothing and adds no step. +pub(crate) fn commit(app: &mut PhotocraftApp, t: &TransformSession, o: &ContentAwareOptions) { + if t.quad == [[t.rect[0], t.rect[1]], [t.rect[2], t.rect[1]], [t.rect[2], t.rect[3]], [t.rect[0], t.rect[3]]] { + return; + } + if let Err(e) = app.run(COMMAND, params(t, o, true)) { + app.ui.status = e; + app.ui.status_error = true; + } +} + +/// Once per frame while the box is open: take a finished preview, cancel one gone stale and start +/// one for the box as it is now. +pub fn tick(app: &mut PhotocraftApp, ctx: &egui::Context) { + let Some(t) = app.ui.transform.as_ref() else { return }; + let Some(o) = t.content_aware.as_ref() else { return }; + let unscaled = box_size(t) == source_size(t); + let want = params(t, o, false); + let now = crate::gpu_canvas::now_ms(); + let Some(live) = app.transform_preview.as_mut().and_then(|pv| pv.content_aware.as_mut()) else { return }; + if let Some(r) = &live.running { + let finished = match r.rx.try_recv() { + Ok(result) => Some(result), + Err(TryRecvError::Empty) => None, + Err(TryRecvError::Disconnected) => Some(Err("Content-Aware Scale preview stopped".into())), + }; + if let Some(result) = finished { + let key = live.running.take().map(|r| r.key).unwrap_or_default(); + // A failed or cancelled preview keeps the last one; the commit reports real errors. + if let Ok(image) = result { + live.serial += 1; + live.shown = Some((key, PreviewTextures::new(ctx, format!("content-aware-scale-{}", live.serial), image, [1.0, 1.0]))); + } + } else { + if r.key != want && now - r.started_ms >= STALE_MS { + r.job.cancel(); + } + ctx.request_repaint(); + return; + } + } + if unscaled || live.shown.as_ref().is_some_and(|(k, _)| *k == want) { + return; + } + let preview = match ContentAwareScalePreview::new(&app.session, &want, PROXY_SIDE) { + Ok(p) => p, + Err(e) => { + app.ui.status = e.to_string(); + return; + } + }; + let Some(live) = app.transform_preview.as_mut().and_then(|pv| pv.content_aware.as_mut()) else { return }; + let (tx, rx) = std::sync::mpsc::sync_channel(1); + let job = JobCtx::new(); + let work = job.clone(); + let repaint = ctx.clone(); + let compute = move || { + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let surf = preview.run(&work).map_err(|e| e.to_string())?; + let [w, h] = preview.size(); + Ok(crate::transform_tex::read_surface(&surf, None, photocraft_geom::Rect::from_xywh(0, 0, w, h), usize::MAX).0) + })) + .unwrap_or_else(|_| Err("Content-Aware Scale preview failed".into())); + let _ = tx.send(result); + repaint.request_repaint(); + }; + // No threads (the browser): the reduced copy is small enough to carve inline. + #[cfg(not(target_arch = "wasm32"))] + { + let spawned = std::thread::Builder::new().name("content-aware-scale-preview".into()).spawn(compute); + if spawned.is_err() { + return; + } + } + #[cfg(target_arch = "wasm32")] + compute(); + live.running = Some(Running { key: want, rx, job, started_ms: now }); + ctx.request_repaint(); +} + +/// The options bar while the box is open: X/Y, W/H, Amount, Protect and Protect Skin Tones. +pub fn fields(app: &mut PhotocraftApp, ui: &mut egui::Ui, t: &TransformSession) { + let Some(o) = t.content_aware.clone() else { return }; + let tk = crate::theme::Tokens::get(ui.ctx()); + let lbl = |ui: &mut egui::Ui, s: &str| { + ui.label(egui::RichText::new(s).color(tk.text_dim).size(12.0)); + }; + crate::transform_tool::position_size_fields(app, ui, t); + crate::widgets::vline(ui, 22.0); + let mut next = o.clone(); + lbl(ui, tl!("Amount:")); + crate::widgets::value_field(ui, &mut next.amount, 0.0..=100.0, "%", 60.0); + crate::widgets::vline(ui, 22.0); + lbl(ui, tl!("Protect:")); + let channels: Vec = app.session.active().map(|st| st.doc.channels.iter().map(|c| c.name.clone()).collect()).unwrap_or_default(); + let mut options: Vec<(Option, &str)> = vec![(None, tl!("None"))]; + options.extend(channels.iter().map(|n| (Some(n.clone()), n.as_str()))); + crate::widgets::dropdown(ui, "content-aware-scale-protect", &mut next.protect, &options, 120.0); + crate::widgets::checkbox(ui, &mut next.protect_skin_tones, tl!("Protect skin tones")); + if next != o + && let Some(s) = app.ui.transform.as_mut() + { + s.content_aware = Some(next); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::canvas::ToolEvent; + + #[test] + fn menu_opens_a_scale_box_and_enter_commits_one_step() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("select.rect", json!({"x": 8, "y": 8, "width": 40, "height": 24})).unwrap(); + app.run("edit.fill", json!({"color": "#c03020"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + app.sync_views(); + let past = app.session.active().unwrap().history.past_len(); + // The menu opens the box, not a dialog. + let r = crate::menus::invoke(&mut app, &ctx, COMMAND, json!({})).unwrap(); + assert!(r.get("dialog").is_none() && app.ui.dialogs.is_empty(), "{r}"); + let t = app.ui.transform.clone().unwrap(); + assert_eq!(t.rect, [8.0, 8.0, 48.0, 32.0]); + assert!(t.content_aware.is_some()); + // Dragging outside the box doesn't rotate it; the right edge narrows it (⇧: that axis only). + let shift = egui::Modifiers { shift: true, ..Default::default() }; + for (from, to) in [([60.0, 40.0], [62.0, 10.0]), ([48.0, 20.0], [32.0, 20.0])] { + assert!(crate::transform_tool::pointer(&mut app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, shift)); + crate::transform_tool::pointer(&mut app, ToolEvent::Move { x: to[0], y: to[1], pressure: 1.0 }, shift); + crate::transform_tool::pointer(&mut app, ToolEvent::Up { x: to[0], y: to[1] }, shift); + } + assert_eq!(app.ui.transform.as_ref().unwrap().quad, [[8.0, 8.0], [32.0, 8.0], [32.0, 32.0], [8.0, 32.0]]); + // The live preview carves a reduced copy in the background. + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20); + while app.transform_preview.as_ref().and_then(|pv| pv.content_aware.as_ref()).is_none_or(|l| l.shown.is_none()) { + assert!(std::time::Instant::now() < deadline, "no live preview"); + tick(&mut app, &ctx); + std::thread::sleep(std::time::Duration::from_millis(2)); + } + // ↩ (the options bar's commit) runs the command: one step, the new size, in place. + crate::transform_tool::commit(&mut app); + assert!(app.ui.transform.is_none()); + let st = app.session.active().unwrap(); + assert_eq!(st.history.past_len(), past + 1); + assert_eq!(st.history.undo_label(), Some("Content-Aware Scale")); + let b = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().content_bounds(); + assert_eq!([b.x0, b.y0, b.width() as i32, b.height() as i32], [8, 8, 24, 24]); + } +} diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 0cf3e558f1..c66ffad53d 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -3441,6 +3441,9 @@ layerLabel No Color Žádná barva Dodge Zesvětlení Burn Ztmavení Sponge Houba + Amount: Míra: + Protect: Chránit: + Protect skin tones Chránit tóny pleti # Select and Mask view modes (#1754) Onion Skin Cibulová slupka Marching Ants Pochodující mravenci diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index b9864db8e3..f7818e1c54 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -2617,6 +2617,9 @@ cameraData Lens Objektiv Spot Healing Brush Punktkorrektur-Pinsel Smudge Wischfinger Sponge Schwamm + Amount: Stärke: + Protect: Schützen: + Protect skin tones Hauttöne schützen # Select and Mask view modes (#1754) Onion Skin Zwiebelschicht Marching Ants Laufende Ameisen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index f134be8a4e..0f2f3fbc3a 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -3678,6 +3678,9 @@ cameraData Lens Φακός Dodge Φωτισμός Burn Σκοτείνιασμα Sponge Σφουγγάρι + Amount: Ποσότητα: + Protect: Προστασία: + Protect skin tones Προστασία τόνων δέρματος # Select and Mask view modes (#1754) Onion Skin Φλούδα κρεμμυδιού Marching Ants Κινούμενο περίγραμμα diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index eeb2c03be3..054ccaf185 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -2658,6 +2658,9 @@ cameraData Lens Objetivo Spot Healing Brush Pincel corrector puntual Smudge Dedo Sponge Esponja + Amount: Cantidad: + Protect: Proteger: + Protect skin tones Proteger tonos de piel # Select and Mask view modes (#1754) Onion Skin Papel cebolla Marching Ants Hormigas en marcha diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index c72b688190..599a4195c6 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -2995,6 +2995,9 @@ cameraData Lens Objectif Spot Healing Brush Correcteur localisé Smudge Doigt Sponge Éponge + Amount: Quantité : + Protect: Protéger : + Protect skin tones Protéger les tons chair # Select and Mask view modes (#1754) Onion Skin Pelure d'oignon Marching Ants Fourmis en marche diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 25b9fdeb58..a791e224a2 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -2982,6 +2982,9 @@ cameraData Lens Lensa Spot Healing Brush Spot Healing Brush Smudge Smudge Sponge Sponge + Amount: Jumlah: + Protect: Lindungi: + Protect skin tones Lindungi warna kulit # Select and Mask view modes (#1754) Onion Skin Kulit Bawang Marching Ants Semut Berbaris diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index b13ff561d5..188468b8df 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -2649,6 +2649,9 @@ cameraData Lens Obiettivo Spot Healing Brush Pennello correttivo al volo Smudge Sfumino Sponge Spugna + Amount: Quantità: + Protect: Proteggi: + Protect skin tones Proteggi toni pelle # Select and Mask view modes (#1754) Onion Skin Velina Marching Ants Formiche in marcia diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index dd299a064a..10b305913a 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3589,6 +3589,9 @@ cameraData Lens レンズ Healing Brush 修復ブラシ Spot Healing Brush スポット修復ブラシ Smudge 指先 + Amount: 量: + Protect: 保護: + Protect skin tones 肌色を保護 # Select and Mask view modes (#1754) Onion Skin オニオンスキン Marching Ants 点線の境界 diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index cd927f38b1..da54b74eef 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3162,6 +3162,9 @@ cameraData Lens 렌즈 Smudge 손가락 Dodge 닷지 Burn 번 + Amount: 양: + Protect: 보호: + Protect skin tones 피부톤 보호 # Select and Mask view modes (#1754) Onion Skin 어니언 스킨 Marching Ants 점선 윤곽 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index e8531ac057..ee6c251604 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -3734,6 +3734,9 @@ cameraData Lens Lens Healing Brush Herstelpenseel Spot Healing Brush Snel herstelpenseel Smudge Uitsmeren + Amount: Hoeveelheid: + Protect: Beschermen: + Protect skin tones Huidtinten beschermen # Select and Mask view modes (#1754) Onion Skin Uienschil Marching Ants Mierenmars diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 2e1506f841..dbe2d1cff0 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -3591,6 +3591,9 @@ cameraData Lens Obiektyw Healing Brush Pędzel korygujący Spot Healing Brush Punktowy pędzel korygujący Smudge Palec + Amount: Wartość: + Protect: Chroń: + Protect skin tones Chroń odcienie skóry # Select and Mask view modes (#1754) Onion Skin Skórka cebuli Marching Ants Maszerujące mrówki diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 6df8697dc4..0c331dbd7d 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -3000,6 +3000,9 @@ cameraData Lens Lente Spot Healing Brush Pincel de recuperação para manchas Smudge Borrar Sponge Esponja + Amount: Quantidade: + Protect: Proteger: + Protect skin tones Proteger tons de pele # Select and Mask view modes (#1754) Onion Skin Papel vegetal Marching Ants Formigas marchando diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 8449dc879a..868682fefa 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -2918,6 +2918,9 @@ cameraData Lens Объектив Spot Healing Brush Точечная восстанавливающая кисть Smudge Палец Sponge Губка + Amount: Эффект: + Protect: Защитить: + Protect skin tones Защищать тона кожи # Select and Mask view modes (#1754) Onion Skin Калька Marching Ants Бегущие муравьи diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index c04c5d62b1..6637561b9e 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -3665,6 +3665,9 @@ cameraData Lens Об'єктив Healing Brush Відновлювальний пензель Spot Healing Brush Точковий відновлювальний пензель Smudge Розмазування + Amount: Величина: + Protect: Захистити: + Protect skin tones Захистити тони шкіри # Select and Mask view modes (#1754) Onion Skin Калька Marching Ants Мурашки diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index f1c45f6bd0..94ec1a7e6f 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -2591,6 +2591,9 @@ cameraData Lens 镜头 Dodge 减淡 Burn 加深 Sponge 海绵 + Amount: 数量: + Protect: 保护: + Protect skin tones 保护肤色 # Select and Mask view modes (#1754) Onion Skin 洋葱皮 Marching Ants 蚂蚁线 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 0a1869387e..13b4fe87f1 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2561,6 +2561,9 @@ cameraData Lens 鏡頭 Dodge 加亮 Burn 加深 Sponge 海綿 + Amount: 總量: + Protect: 保護: + Protect skin tones 保護膚色 # Select and Mask view modes (#1754) Onion Skin 洋蔥皮 Marching Ants 螞蟻線 diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index cd9d7df316..efffc00f35 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -40,6 +40,7 @@ pub mod camera_raw_ui; pub mod canvas; mod canvas_popup; pub mod canvas_tool_menu; +pub mod cas_transform; pub mod channel_view; pub mod channels_panel; pub mod chrome_ui; diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index a34ec7c2b9..541586c98f 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -534,6 +534,9 @@ pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id: | "edit.transform.perspective" => { // While a box is up, Scale / Rotate / Skew / Distort / Perspective (and Free Transform) // switch its mode; otherwise they start one in that mode. + if app.ui.transform.as_ref().is_some_and(|t| t.content_aware.is_some()) { + return Err(crate::transform_tool::CAS_ONLY_SCALES.into()); + } if app.ui.transform.is_none() { crate::transform_tool::begin(app, ctx)?; } diff --git a/crates/ui-egui/src/prefs_ui.rs b/crates/ui-egui/src/prefs_ui.rs index ba218c0cac..4cf7e0cefd 100644 --- a/crates/ui-egui/src/prefs_ui.rs +++ b/crates/ui-egui/src/prefs_ui.rs @@ -800,7 +800,7 @@ pub fn is_modifier_key(key: egui::Key) -> bool { /// Shell front ends for Edit-menu commands invoked without parameters (dialogs, pickers). /// `None` when `id` isn't handled here. -pub fn invoke(app: &mut PhotocraftApp, _ctx: &egui::Context, id: &str, params: &Value) -> Option> { +pub fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &Value) -> Option> { let empty = params.as_object().is_none_or(|o| o.is_empty()); if !empty { return None; @@ -857,22 +857,8 @@ pub fn invoke(app: &mut PhotocraftApp, _ctx: &egui::Context, id: &str, params: & } dialog(d) } - "edit.contentAwareScale" => { - let st = app.session.active()?; - let b = match &st.doc.selection { - Some(s) => s.content_bounds(), - None => st.active_layer.and_then(|l| st.doc.layer(l)).and_then(|l| l.surface()).map(|s| s.content_bounds()).unwrap_or_default(), - }; - let d = crate::filter_dialog::open(app, id); - if let Some(dm) = d.and_then(|d| app.ui.dialog_mut(d)) { - dm.fields.insert("width".into(), json!(b.width())); - dm.fields.insert("height".into(), json!(b.height())); - dm.fields.remove("scaleX"); - dm.fields.remove("scaleY"); - dm.fields.insert("__preview".into(), json!(true)); - } - dialog(d) - } + // Photoshop has no dialog: the menu opens the scale box (with params: the engine). + crate::cas_transform::COMMAND => Some(crate::cas_transform::begin(app, ctx)), "edit.presets.presetManager" => { Some(Ok(json!({"dialog": open_kind(app, "presets", "Preset Manager", json!({"kind": "brushes", "selected": 0, "newName": ""}))}))) } @@ -3124,8 +3110,9 @@ mod tests { let d = crate::menus::invoke(&mut app, &ctx, "edit.contentAwareFill", json!({})).unwrap()["dialog"].as_u64().unwrap(); assert_eq!(app.ui.dialogs.iter().find(|x| x.id == d).unwrap().fields["__preview"], true); crate::dialogs::confirm(&mut app, d).unwrap(); - let d = crate::menus::invoke(&mut app, &ctx, "edit.contentAwareScale", json!({})).unwrap()["dialog"].as_u64().unwrap(); - assert_eq!(app.ui.dialogs.iter().find(|x| x.id == d).unwrap().fields["width"], 8); + let r = crate::menus::invoke(&mut app, &ctx, "edit.contentAwareScale", json!({})).unwrap(); + assert_eq!(r["transform"]["rect"], json!([4.0, 4.0, 12.0, 12.0])); + crate::transform_tool::cancel(&mut app); let d = crate::menus::invoke(&mut app, &ctx, "edit.presets.presetManager", json!({})).unwrap()["dialog"].as_u64().unwrap(); assert!(crate::dialogs::confirm(&mut app, d).is_ok()); } diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 10bc9ec107..c0a8ae4a07 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -883,6 +883,29 @@ pub struct TransformSession { /// Edit › Transform › Skew / Distort / Perspective (`Free` for Free Transform). #[serde(default)] pub mode: TransformMode, + /// Edit › Content-Aware Scale (#3096): the box only scales and moves, and OK runs + /// `edit.contentAwareScale` with these options instead of `edit.transform`. + #[serde(default)] + pub content_aware: Option, +} + +/// Content-Aware Scale's options bar: Amount, Protect and Protect Skin Tones. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ContentAwareOptions { + /// How much is content-aware, 0..100 % (the rest is a plain resample). + pub amount: f32, + /// The alpha channel whose white areas keep their shape (`None`: no protection). + #[serde(default)] + pub protect: Option, + #[serde(default)] + pub protect_skin_tones: bool, +} + +impl Default for ContentAwareOptions { + fn default() -> Self { + Self { amount: 100.0, protect: None, protect_skin_tones: false } + } } /// Why a Free Transform session's layer was made for it. diff --git a/crates/ui-egui/src/transform_tool.rs b/crates/ui-egui/src/transform_tool.rs index ccde6b6a39..062cdbdcce 100644 --- a/crates/ui-egui/src/transform_tool.rs +++ b/crates/ui-egui/src/transform_tool.rs @@ -82,6 +82,8 @@ pub struct TransformPreview { /// A layer's session keeps `doc` and `opacity` up to date with edits made while the box is /// open ([`follow_edits`]); `None` for a lone mask or channel and Transform Selection. follow: Option, + /// Content-Aware Scale's live preview (cas_transform.rs). + pub(crate) content_aware: Option, } /// What [`follow_edits`] needs to rebuild the preview document. @@ -97,6 +99,9 @@ struct Follow { /// starts on a layer locked in place, by its own lock or a group's. pub const LOCKED: &str = "Could not complete the Free Transform command because the layer is locked."; +/// Why Edit › Transform's modes and Warp refuse while Content-Aware Scale's box is open. +pub const CAS_ONLY_SCALES: &str = "Content-Aware Scale only scales: commit or cancel it first"; + /// Grab radius of the box's handles, in screen points. Generous, so a corner is easy to catch; /// just beyond it, outside the box, a drag rotates. pub const HANDLE_PX: f64 = 12.0; @@ -226,6 +231,7 @@ pub fn begin(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String> steps: Steps::default(), tool: app.ui.tool, path: None, + content_aware: None, }); app.ui.transform = Some(TransformSession { session, @@ -240,6 +246,7 @@ pub fn begin(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String> path: None, made: None, mode: Default::default(), + content_aware: None, }); start_steps(app); Ok(()) @@ -274,6 +281,75 @@ pub fn begin_placed(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), Ok(()) } +/// Edit › Content-Aware Scale (#3096): a scale-only box over `region` of the active pixel layer +/// (the selection's bounds, else the layer's content), cleared under the box as the command +/// clears it. OK runs `edit.contentAwareScale` (cas_transform.rs) instead of `edit.transform`. +pub(crate) fn begin_content_aware( + app: &mut PhotocraftApp, + ctx: &egui::Context, + region: photocraft_geom::Rect, + live: crate::cas_transform::Live, +) -> Result<(), String> { + let st = app.session.active().ok_or("no document")?; + let (doc, revision) = (st.doc.clone(), st.revision); + let id = st.active_layer.ok_or("no active layer")?; + let layer = doc.layer(id).ok_or("no layer")?; + let surf = layer.surface().ok_or("Content-Aware Scale needs a pixel layer")?; + if region.is_empty() { + return Err("Could not scale: the layer is empty".into()); + } + crate::type_tool::commit(app); + let rect = [region.x0 as f64, region.y0 as f64, region.x1 as f64, region.y1 as f64]; + let session = app.ui.alloc_id(); + // The command clears the area before writing the result (a layer without transparency keeps it). + let mut pd = (*doc).clone(); + if let Some(s) = pd.layer_mut(id).and_then(|l| l.surface_mut()).filter(|s| s.format().alpha) { + let clear = vec![0.0; s.format().channels()]; + s.fill_rect(region, &clear); + s.prune(); + } + let max_side = ctx.input(|i| i.max_texture_side).max(app.gpu.as_ref().map_or(1, |g| g.max_texture_side())); + let above = Above::new(ctx, format!("transform-{session}-above"), &doc, id, max_side); + above.hide_in(&mut pd.layers); + let (image, uv) = crate::transform_tex::read_surface(surf, None, region, max_side); + let texture = crate::transform_tex::PreviewTextures::new(ctx, format!("transform-{session}"), image, uv); + app.transform_preview = Some(TransformPreview { + session, + doc: Arc::new(pd), + texture, + opacity: layer.opacity * layer.fill_opacity, + above: Some(above), + follow: Some(Follow { revision, hidden: false }), + gesture: None, + warp_drag: None, + split_tool: None, + split_pointer: None, + split_placing: false, + split_quick: false, + steps: Steps::default(), + tool: app.ui.tool, + path: None, + content_aware: Some(live), + }); + app.ui.transform = Some(TransformSession { + session, + layer: id.0, + rect, + quad: corners(rect), + pivot: [(rect[0] + rect[2]) / 2.0, (rect[1] + rect[3]) / 2.0], + interpolation: "bicubic".into(), + warp: None, + selection: false, + target: None, + path: None, + made: None, + mode: Default::default(), + content_aware: Some(Default::default()), + }); + start_steps(app); + Ok(()) +} + /// Undoes the layer a cancelled or failed session made (⌥⌘T's copy, a placed file), leaving /// nothing to redo. fn take_back_made(app: &mut PhotocraftApp, document: DocId, layer: LayerId) { @@ -364,6 +440,7 @@ fn begin_lone( steps: Steps::default(), tool: app.ui.tool, path: None, + content_aware: None, }); app.ui.transform = Some(TransformSession { session, @@ -378,6 +455,7 @@ fn begin_lone( path: None, made: None, mode: Default::default(), + content_aware: None, }); start_steps(app); Ok(()) @@ -410,6 +488,7 @@ fn begin_path(app: &mut PhotocraftApp, ctx: &egui::Context, params: serde_json:: steps: Steps::default(), tool: app.ui.tool, path: Some(path), + content_aware: None, above: None, follow: None, }); @@ -426,6 +505,7 @@ fn begin_path(app: &mut PhotocraftApp, ctx: &egui::Context, params: serde_json:: path: Some(params), made: None, mode: Default::default(), + content_aware: None, }); start_steps(app); Ok(()) @@ -492,6 +572,7 @@ pub fn begin_selection(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<( steps: Steps::default(), tool: app.ui.tool, path: None, + content_aware: None, }); app.ui.transform = Some(TransformSession { session, @@ -506,6 +587,7 @@ pub fn begin_selection(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<( path: None, made: None, mode: Default::default(), + content_aware: None, }); start_steps(app); Ok(()) @@ -513,6 +595,9 @@ pub fn begin_selection(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<( /// Start (or switch an active Free Transform into) Warp mode. pub fn begin_warp(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String> { + if app.ui.transform.as_ref().is_some_and(|t| t.content_aware.is_some()) { + return Err(CAS_ONLY_SCALES.into()); + } let fresh = app.ui.transform.is_none(); if fresh { begin(app, ctx)?; @@ -851,6 +936,10 @@ pub fn commit(app: &mut PhotocraftApp) { let type_layer = warps_type(app); let Some(t) = app.ui.transform.take() else { return }; app.transform_preview = None; + if let Some(options) = &t.content_aware { + crate::cas_transform::commit(app, &t, options); + return; + } if t.selection { let mut p = json!({"rect": t.rect, "interpolation": t.interpolation}); match &t.warp { @@ -1008,8 +1097,12 @@ pub fn is_enabled(app: &PhotocraftApp, id: &str) -> Option { let t = app.ui.transform.as_ref()?; let steps = app.transform_preview.as_ref().map(|pv| &pv.steps); match id { + // Content-Aware Scale's box only scales: no switching it to another transform or Warp. + "edit.freeTransform" | "edit.freeTransformCopy" if t.content_aware.is_some() => Some(false), + i if i.starts_with("edit.transform.") && t.content_aware.is_some() => Some(false), "edit.undo" => Some(steps.is_some_and(|s| s.can_undo(&Step::of(t)))), "edit.redo" => Some(steps.is_some_and(|s| !s.redo.is_empty())), + // No Toggle Last State under the box, and one box at a time. "edit.toggleLastState" | "edit.contentAwareScale" | "edit.puppetWarp" => Some(false), // Rotate and Flip turn the box (not while warping, where the mesh is the box). _ if box_preset(id).is_some() => Some(t.warp.is_none()), @@ -1158,7 +1251,8 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> } // Distort only moves corners (and the whole box from inside): no rotating, no edges. // Even in Distort mode, remember an outside press so a plain click can - // accept the transform. A drag outside remains inert in that mode. + // accept the transform. A drag outside remains inert in that mode, and in + // Content-Aware Scale, which only scales and moves. pv.gesture = (distort_allows(t.mode, h) || h == Hit::Outside).then_some(Gesture { hit: h, start: [x, y], quad0: t.quad, pivot0: t.pivot }); } ToolEvent::Move { x, y, .. } | ToolEvent::Up { x, y } => { @@ -1176,9 +1270,13 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> let legacy = app.session.prefs().general.use_legacy_free_transform; if let (Some(g), Some(s)) = (g, app.ui.transform.as_mut()) && distort_allows(t.mode, g.hit) + && (t.content_aware.is_none() || g.hit != Hit::Outside) { let (mode, mods) = if no_distort { scale_not_distort(t.mode, g.hit, mods) } else { (t.mode, mods) }; - apply_drag(s, g, [x, y], mode_mods(mode, g.hit, legacy_mods(legacy, g.hit, mods))); + let mut mods = mode_mods(mode, g.hit, legacy_mods(legacy, g.hit, mods)); + // Content-Aware Scale: ⌘ neither skews nor distorts. + mods.command &= t.content_aware.is_none(); + apply_drag(s, g, [x, y], mods); } } } @@ -1672,7 +1770,8 @@ pub(crate) fn rotate_cursor_dir(app: &PhotocraftApp, p: [f64; 2]) -> Option<[f64 } fn rotate_dir(t: &TransformSession, pv: Option<&TransformPreview>, p: [f64; 2], tol: f64) -> Option<[f64; 2]> { - if !(p[0].is_finite() && p[1].is_finite()) || t.warp.is_some() || t.mode == TransformMode::Distort { + // Content-Aware Scale's box only scales: no rotate arrow. + if !(p[0].is_finite() && p[1].is_finite()) || t.warp.is_some() || t.content_aware.is_some() || t.mode == TransformMode::Distort { return None; } let rotating = pv.is_some_and(|pv| pv.gesture.is_some_and(|g| g.hit == Hit::Outside)); @@ -1713,7 +1812,7 @@ pub fn cursor(app: &PhotocraftApp, p: [f64; 2], quick_split: bool) -> Option texture.pick(painter.ctx(), zoom, texel, false), + None => pv.texture.pick(painter.ctx(), zoom, quad_scale(t), t.interpolation == "nearest"), + }; let mut mesh = egui::Mesh::with_texture(tex); let tint = Color32::from_white_alpha((pv.opacity.clamp(0.0, 1.0) * 255.0) as u8); for j in 0..=n { @@ -2155,6 +2259,8 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { row.set_clip_rect(fields); if let Some(w) = t.warp.clone() { warp_fields(app, &mut row, &w); + } else if t.content_aware.is_some() { + crate::cas_transform::fields(app, &mut row, &t); } else { transform_fields(app, &mut row, &t); } @@ -2162,12 +2268,39 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let start = row.min_rect().right().min(split); let actions = egui::Rect::from_min_max(egui::pos2(start, bar.top()), egui::pos2(start + buttons_w, bar.bottom())); let mut btns = ui.new_child(egui::UiBuilder::new().id_salt("transform-actions").max_rect(actions).layout(egui::Layout::right_to_left(egui::Align::Center))); - transform_actions(app, &mut btns, warping); + transform_actions(app, &mut btns, warping, t.content_aware.is_none()); } fn transform_fields(app: &mut PhotocraftApp, ui: &mut egui::Ui, t: &TransformSession) { let tk = crate::theme::Tokens::get(ui.ctx()); - let (sx, sy, angle, _) = readout(t); + let (_, _, angle, _) = readout(t); + let lbl = |ui: &mut egui::Ui, s: &str| { + ui.label(egui::RichText::new(s).color(tk.text_dim).size(12.0)); + }; + position_size_fields(app, ui, t); + crate::widgets::vline(ui, 22.0); + let mut a = angle as f32; + let (r, resp) = ui.allocate_exact_size(vec2(18.0, 22.0), egui::Sense::hover()); + crate::icons::paint(ui, r, "rotate-cw", 13.0, tk.text_dim); + resp.on_hover_text(tl!("Rotate")); + if crate::widgets::value_field(ui, &mut a, -180.0..=180.0, "°", 60.0).changed() { + rotate_about_pivot(app, (a as f64 - angle).to_radians()); + } + crate::widgets::vline(ui, 22.0); + lbl(ui, tl!("Interpolation:")); + let mut interp = t.interpolation.clone(); + let opts = [("bicubic".to_string(), tl!("Bicubic")), ("bilinear".to_string(), tl!("Bilinear")), ("nearest".to_string(), tl!("Nearest Neighbor"))]; + if crate::widgets::dropdown(ui, "transform-interp", &mut interp, &opts, 130.0) + && let Some(s) = app.ui.transform.as_mut() + { + s.interpolation = interp; + } +} + +/// The reference point's X/Y and the W/H scale fields (with the aspect link) of the options bar. +pub(crate) fn position_size_fields(app: &mut PhotocraftApp, ui: &mut egui::Ui, t: &TransformSession) { + let tk = crate::theme::Tokens::get(ui.ctx()); + let (sx, sy, _, _) = readout(t); let lbl = |ui: &mut egui::Ui, s: &str| { ui.label(egui::RichText::new(s).color(tk.text_dim).size(12.0)); }; @@ -2224,23 +2357,6 @@ fn transform_fields(app: &mut PhotocraftApp, ui: &mut egui::Ui, t: &TransformSes }; scale_about_pivot(app, kx, ky); } - crate::widgets::vline(ui, 22.0); - let mut a = angle as f32; - let (r, resp) = ui.allocate_exact_size(vec2(18.0, 22.0), egui::Sense::hover()); - crate::icons::paint(ui, r, "rotate-cw", 13.0, tk.text_dim); - resp.on_hover_text(tl!("Rotate")); - if crate::widgets::value_field(ui, &mut a, -180.0..=180.0, "°", 60.0).changed() { - rotate_about_pivot(app, (a as f64 - angle).to_radians()); - } - crate::widgets::vline(ui, 22.0); - lbl(ui, tl!("Interpolation:")); - let mut interp = t.interpolation.clone(); - let opts = [("bicubic".to_string(), tl!("Bicubic")), ("bilinear".to_string(), tl!("Bilinear")), ("nearest".to_string(), tl!("Nearest Neighbor"))]; - if crate::widgets::dropdown(ui, "transform-interp", &mut interp, &opts, 130.0) - && let Some(s) = app.ui.transform.as_mut() - { - s.interpolation = interp; - } } /// Options bar fields in Warp mode: style, bend, the split icons and the grid menu. @@ -2417,7 +2533,8 @@ fn split_icon(ui: &mut egui::Ui, kind: &str, tip: &str, on: bool) -> egui::Respo } /// Warp switch, cancel and commit, kept on the right of the options bar. -fn transform_actions(app: &mut PhotocraftApp, ui: &mut egui::Ui, warping: bool) { +/// `mode_switch`: the Free Transform / Warp switch (not for Content-Aware Scale, which only scales). +fn transform_actions(app: &mut PhotocraftApp, ui: &mut egui::Ui, warping: bool, mode_switch: bool) { ui.add_space(8.0); let commit_tip = if warping { crate::i18n::fmt(tl!("Commit warp ({key})"), &[("key", &crate::shortcuts::pretty("Enter"))]) @@ -2444,6 +2561,9 @@ fn transform_actions(app: &mut PhotocraftApp, ui: &mut egui::Ui, warping: bool) reset_warp(app); } } + if !mode_switch { + return; + } crate::widgets::vline(ui, 22.0); let mode = crate::icons::button(ui, "grid-3x3", 26.0, warping, tl!("Switch between free transform and warp modes")); mode.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, "Switch between free transform and warp modes")); @@ -2497,6 +2617,7 @@ mod tests { path: None, made: None, mode: Default::default(), + content_aware: None, } } diff --git a/crates/ui-egui/src/type_transform.rs b/crates/ui-egui/src/type_transform.rs index 42c9cc8eec..d99334cba9 100644 --- a/crates/ui-egui/src/type_transform.rs +++ b/crates/ui-egui/src/type_transform.rs @@ -125,6 +125,7 @@ pub(crate) fn frame(app: &mut PhotocraftApp) -> Option { path: None, made: None, mode: Default::default(), + content_aware: None, }) } diff --git a/docs/scorecard.md b/docs/scorecard.md index d598f0b84f..46d522983d 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -8,7 +8,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js |---|---:|---:|---:|---| | [Performance](#performance) | 3 | 22 | 22 | 56 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 17 not run, 5 not measurable yet (baseline 2026-10-05) | | [File compatibility](#file-compatibility) | 6 | 13 | 8 | io corpus: oracle ≥ 146/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 236/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 133/256, round trip ≥ 258/256 | -| [Tools](#tools) | 26 | 15 | 2 | | +| [Tools](#tools) | 27 | 14 | 2 | | | [Workspace and UI](#workspace-and-ui) | 10 | 7 | 6 | settings that do nothing: 30 of 154 (target 0) | | [Type](#type) | 4 | 2 | 3 | | | [Automation](#automation) | 3 | 2 | 6 | 631 of 631 menu items live (100.0%) | @@ -151,7 +151,7 @@ Corpus floors (`crates/io/tests/corpus.rs`): the enforced minimums; the corpus t | TOOL-214-4 | Move tool: box-select layers, Auto-Select hover outline, double-click fit, drag to a tab | partial | [#214](https://github.com/storytold/photocraft/issues/214) | Auto-Select hover outline (Preferences › Tools › Show Highlight on Rollover, #2834) and box-select layers from an empty spot (move_box.rs, layer.selectInRect, #2844) done; double-click fit and drag to a tab open | | TOOL-214-5 | Right-click menu during Free Transform (scale, rotate, skew, warp, flip, rotate 90/180) | done | [#214](https://github.com/storytold/photocraft/issues/214) | canvas_tool_menu.rs TRANSFORM_MENU: modes, Content-Aware Scale / Puppet Warp greyed, Rotate 180 / 90 CW / 90 CCW and Flip turn the open box (transform_tool::intercept, #2832) | | 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-7 | Content-Aware Scale through the Free Transform box with a live proxy preview | done | [#214](https://github.com/storytold/photocraft/issues/214) | Edit > Content-Aware Scale opens a scale-only Free Transform box (cas_transform.rs) with Amount, Protect and Protect Skin Tones in the options bar; edit.contentAwareScale carves a 384 px copy in the background for the live preview, and Enter runs it with the box's size and x/y as one step (#3096) | | TOOL-214-8 | A measured ruler angle prefills Image Rotation > Arbitrary (0.01 deg) | done | [#214](https://github.com/storytold/photocraft/issues/214) | analysis_ui.rs: image.rotation.arbitrary opens seeded with the ruler angle and the direction that straightens it; arbitrary_rotation_starts_at_the_ruler_angle checks 5.7106 deg within 1e-3 and cw/ccw for three measured lines | | TOOL-214-9 | Crop: W x H x Resolution with units, saved crop presets, Straighten in the options bar | done | [#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); New / Delete Crop Preset save and delete crop tool presets (crop_presets.rs, tool.presets.* with tool crop, persisted with the preferences) | | 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); Backspace/Delete retracts the last point while drawing (#1466); Alt during a drag breaks the handle pair, Alt-drag turns the last anchor's outgoing handle alone, and dragging on the first anchor closes with that anchor's handles (vector_ui.rs, #3306); no Shift 45 deg | diff --git a/scorecard/tools.toml b/scorecard/tools.toml index 6d5e67aed6..21330bdc0c 100644 --- a/scorecard/tools.toml +++ b/scorecard/tools.toml @@ -155,9 +155,9 @@ note = "algo/puppet.rs:136 builds a block-grid mesh" [[item]] id = "TOOL-214-7" target = "Content-Aware Scale through the Free Transform box with a live proxy preview" -status = "partial" +status = "done" issue = 214 -note = "edit.contentAwareScale (edit_menu_cmds.rs:899) behind a parameter dialog" +note = "Edit > Content-Aware Scale opens a scale-only Free Transform box (cas_transform.rs) with Amount, Protect and Protect Skin Tones in the options bar; edit.contentAwareScale carves a 384 px copy in the background for the live preview, and Enter runs it with the box's size and x/y as one step (#3096)" [[item]] id = "TOOL-214-8"