From b1b44595b7baac4149cb89f7f79b31d6edbf3004 Mon Sep 17 00:00:00 2001 From: Dan Hiorns Date: Mon, 12 Oct 2026 19:56:29 -0600 Subject: [PATCH 01/15] Toolbar: no tooltips over an open tool flyout (#4450) (#4469) Holding a tool button to open its flyout showed that button's tooltip on top of the flyout, and other toolbar buttons kept showing theirs while it was open. The flyout is our own Area, so egui's rule that hides tooltips while a popup is open didn't apply. The toolbar's buttons (the tools, Quick Mask, Change Screen Mode) now skip their tooltips while a tool flyout is open or the mouse button is held. icons::button_with_icon_size_tip keeps the tooltip text as the button's label when the tooltip is hidden. Co-authored-by: Claude Opus 5.5 Co-authored-by: Brandon Thomas --- crates/ui-egui/src/icons.rs | 8 +++- crates/ui-egui/src/panels.rs | 81 ++++++++++++++++++++++++++++++++++-- 2 files changed, 85 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index 390b378716..215e5994e8 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -177,6 +177,12 @@ pub fn button(ui: &mut egui::Ui, name: &str, box_size: f32, selected: bool, tool /// Square icon button with an explicit glyph size, independent of its hit area. pub fn button_with_icon_size(ui: &mut egui::Ui, name: &str, box_size: f32, icon_size: f32, selected: bool, tooltip: &str) -> Response { + button_with_icon_size_tip(ui, name, box_size, icon_size, selected, tooltip, true) +} + +/// [`button_with_icon_size`] whose tooltip shows only when `show_tip`; the tooltip text still +/// names the button (for screen readers and tests) when it is hidden. +pub fn button_with_icon_size_tip(ui: &mut egui::Ui, name: &str, box_size: f32, icon_size: f32, selected: bool, tooltip: &str, show_tip: bool) -> Response { let t = Tokens::get(ui.ctx()); let style = IconButtonStyle { normal: ButtonVisuals { fill: Color32::TRANSPARENT, stroke: egui::Stroke::NONE, icon: t.icon }, @@ -190,7 +196,7 @@ pub fn button_with_icon_size(ui: &mut egui::Ui, name: &str, box_size: f32, icon_ let resp = IconButton::new(label, Vec2::splat(box_size), &style).selected(selected).show(ui, |ui, rect, tint| { paint(ui, rect, name, icon_size, tint); }); - if tooltip.is_empty() { resp } else { resp.on_hover_text(label) } + if tooltip.is_empty() || !show_tip { resp } else { resp.on_hover_text(label) } } /// Rail toggle: "on" gets a quiet filled background and full-strength icon (no accent). diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 585841042f..95bf65068f 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -123,6 +123,10 @@ pub fn toolbar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { if ui.input(|i| i.pointer.any_pressed()) { ui.data_mut(|d| d.remove::(held_id)); } + // No tool tooltips over an open flyout, or while a button is held to open one (#4450): + // Photoshop shows none there. (The flyout is our own Area, so egui's rule for popups + // doesn't hide them.) + let tool_tips = ui.data(|d| d.get_temp::<(egui::Id, Rect)>(flyout_id)).is_none() && !ui.input(|i| i.pointer.primary_down()); let ctx = ui.ctx().clone(); let footer = (if t.pro { 8.0 } else { 14.0 }) + chips_height(t.pro, t.round_chips, t.round_chips && double) @@ -155,7 +159,8 @@ pub fn toolbar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let sel = slot.contains(&app.ui.tool); let tip = if tool.key() == '\0' { tl!(tool.label()).to_string() } else { format!("{} ({})", tl!(tool.label()), tool.key()) }; - let resp = icons::button_with_icon_size(ui, icons::tool_icon(tool), bx, toolbar_icon_size(bx, t.pro), sel, &tip); + let resp = + icons::button_with_icon_size_tip(ui, icons::tool_icon(tool), bx, toolbar_icon_size(bx, t.pro), sel, &tip, tool_tips); if slot.len() > 1 { paint_toolbar_flyout_indicator(ui, &t, &resp); } @@ -284,18 +289,20 @@ pub fn toolbar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { ui.with_layout(layout, |ui| { let quick_mask = app.session.active().is_some_and(|s| s.doc.quick_mask.is_some()); - if icons::button( + if icons::button_with_icon_size_tip( ui, "square-dashed", bx, + (bx * 0.52).round(), quick_mask, if quick_mask { tl!("Edit in Standard Mode (Q)") } else { tl!("Edit in Quick Mask Mode (Q)") }, + tool_tips, ) .clicked() { let _ = crate::menus::invoke(app, &ctx, "select.editInQuickMaskMode", json!({})); } - let sm = icons::button(ui, "app-window", bx, false, tl!("Change Screen Mode (F)")); + let sm = icons::button_with_icon_size_tip(ui, "app-window", bx, (bx * 0.52).round(), false, tl!("Change Screen Mode (F)"), tool_tips); paint_toolbar_flyout_indicator(ui, &t, &sm); // Right-click, or click and hold like the tool flyouts (#4444), lists the modes, @@ -4752,6 +4759,74 @@ mod type_flyout_tests { assert!(menu_open(&ctx)); } + /// Every text drawn in one toolbar frame. + fn frame_texts(app: &mut PhotocraftApp, ctx: &egui::Context, time: f64, events: Vec) -> Vec { + fn collect(shape: &egui::Shape, out: &mut Vec) { + match shape { + egui::Shape::Text(t) => out.push(t.galley.text().to_string()), + egui::Shape::Vec(v) => v.iter().for_each(|s| collect(s, out)), + _ => {} + } + } + let mut out = ctx.run_ui( + egui::RawInput { time: Some(time), events, screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(1200.0, 1800.0))), ..Default::default() }, + |ui| toolbar(app, ui), + ); + out.textures_delta.clear(); + let mut texts = Vec::new(); + out.shapes.iter().for_each(|c| collect(&c.shape, &mut texts)); + texts + } + + /// #4450: no tool tooltip while a flyout is open or a tool button is held to open one, for the + /// held tool or any other; a plain hover still shows its tooltip. + #[test] + fn no_tooltips_over_an_open_tool_flyout() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ALL[0]); + frame(&mut app, &ctx, 0.0, vec![]); + frame(&mut app, &ctx, 0.1, vec![]); + let bx = if Tokens::get(&ctx).pro { 30.0 } else { 36.0 }; + let mut buttons: Vec = ctx.viewport(|v| { + v.prev_pass + .widgets + .layers() + .flat_map(|(_, w)| w.iter()) + .filter(|w| w.rect.size() == egui::Vec2::splat(bx) && w.sense.senses_click()) + .map(|w| w.rect) + .collect() + }); + buttons.sort_by(|a, b| a.top().total_cmp(&b.top())); + let slot_of = |tool: Tool| TOOL_SECTIONS.iter().flat_map(|section| section.iter()).position(|slot| slot.contains(&tool)).unwrap(); + let (eyedropper, brush) = (buttons[slot_of(Tool::Eyedropper)].center(), buttons[slot_of(Tool::Brush)].center()); + let tip = |tool: Tool| format!("{} ({})", tl!(tool.label()), tool.key()); + let pointer = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + // A plain hover shows the tooltip. + frame(&mut app, &ctx, 1.0, vec![egui::Event::PointerMoved(brush)]); + let mut texts = Vec::new(); + for k in 1..=10 { + texts = frame_texts(&mut app, &ctx, 1.0 + 0.1 * f64::from(k), vec![]); + } + assert!(texts.contains(&tip(Tool::Brush)), "hovered long enough: {texts:?}"); + // Held on the Eyedropper: no tooltip before or after its flyout opens. + frame(&mut app, &ctx, 3.0, vec![egui::Event::PointerMoved(eyedropper), pointer(eyedropper, true)]); + for k in 1..=10 { + let texts = frame_texts(&mut app, &ctx, 3.0 + 0.1 * f64::from(k), vec![]); + assert!(!texts.contains(&tip(Tool::Eyedropper)), "held {k}: {texts:?}"); + } + assert!(ctx.data(|d| d.get_temp::<(egui::Id, Rect)>(egui::Id::new("tool-flyout"))).is_some(), "the flyout is open"); + // Released, with the flyout still open: none for the held tool or another one. + frame(&mut app, &ctx, 4.1, vec![pointer(eyedropper, false)]); + for (start, at, tool) in [(4.5, eyedropper, Tool::Eyedropper), (6.0, brush, Tool::Brush)] { + frame(&mut app, &ctx, start, vec![egui::Event::PointerMoved(at)]); + for k in 1..=10 { + let texts = frame_texts(&mut app, &ctx, start + 0.1 * f64::from(k), vec![]); + assert!(!texts.contains(&tip(tool)), "{tool:?} under the flyout: {texts:?}"); + } + } + } + #[test] fn red_eye_is_in_the_j_flyout() { let j = TOOL_SECTIONS.iter().flat_map(|section| section.iter()).find(|slot| slot.contains(&Tool::SpotHealing)).expect("J group"); From 1cb3eaa5d240cafce4cbf110dc0febff385574d0 Mon Sep 17 00:00:00 2001 From: Ian Swope Date: Mon, 12 Oct 2026 20:57:47 -0500 Subject: [PATCH 02/15] Free Transform: apply a large layer's warp in the background, with progress and Esc to cancel (#1015) (#4218) Committing Free Transform on a 300-550 MP layer ran the bicubic warp on the UI thread: several seconds of a frozen window with no feedback. On a 20000x16000 layer the warp alone took about 6.6 s. edit.transform is now a background job (edit_job): the warp reports progress per tile and stops when cancelled. The transform session stays open while it runs, showing the moving pixels without the box, so the layer doesn't jump back to its old place until the result lands. The modal progress dialog shows after the usual delay, and Esc or Cancel cancels the job. A copy or placed layer the session made is folded into the step, or taken back, in its own document. Undo and Redo are refused while the commit runs. Tests and scripts run inline as before. Co-authored-by: Brandon Thomas Co-authored-by: Claude Opus 5.5 --- crates/algo/src/transform.rs | 59 +++++++++++- crates/engine/src/jobs_tests.rs | 16 ++++ crates/engine/src/transform_cmds.rs | 138 +++++++++++++++++---------- crates/ui-egui/src/jobs_ui.rs | 2 + crates/ui-egui/src/jobs_ui_tests.rs | 62 ++++++++++++ crates/ui-egui/src/transform_tool.rs | 99 +++++++++++++++++-- 6 files changed, 317 insertions(+), 59 deletions(-) diff --git a/crates/algo/src/transform.rs b/crates/algo/src/transform.rs index 2584a877df..ba75a65336 100644 --- a/crates/algo/src/transform.rs +++ b/crates/algo/src/transform.rs @@ -9,7 +9,7 @@ use photocraft_color::PixelFormat; use photocraft_geom::Rect; -use photocraft_raster::Surface; +use photocraft_raster::{Interrupt, Surface}; use serde::{Deserialize, Serialize}; use crate::resample::{Resample, resize_surface}; @@ -143,14 +143,26 @@ fn catmull_rom(t: f64) -> [f64; 4] { /// The result has the same format as `src`, with alpha added if `src` had none; pixels outside /// the warped quad are transparent. pub fn warp_surface(src: &Surface, src_rect: Rect, h: &Homography, interp: Interp) -> Result { - warp(src, src_rect, h, interp, None) + warp(src, src_rect, h, interp, None, &Interrupt::NONE) +} + +/// [`warp_surface`] reporting progress per destination tile; `Ok(None)` once `ctl` is cancelled. +pub fn warp_surface_with( + src: &Surface, + src_rect: Rect, + h: &Homography, + interp: Interp, + ctl: &Interrupt, +) -> Result, photocraft_raster::AllocationError> { + let out = warp(src, src_rect, h, interp, None, ctl)?; + Ok((!ctl.cancelled()).then_some(out)) } /// [`warp_surface`] keeping only the destination pixels inside `clip`. The work is bounded by /// `clip` even when part of the source lies at or beyond the map's horizon (a Perspective Crop of a /// layer that reaches far past the crop quad), which would make the full warped extent unbounded. pub fn warp_surface_clipped(src: &Surface, src_rect: Rect, h: &Homography, interp: Interp, clip: Rect) -> Result { - warp(src, src_rect, h, interp, Some(clip)) + warp(src, src_rect, h, interp, Some(clip), &Interrupt::NONE) } /// Is `q` (TL, TR, BR, BL) a usable Perspective Crop quad: finite, strictly convex with every @@ -216,7 +228,15 @@ fn corner_bounds(corners: &[(f64, f64); 4]) -> Option { Some(Rect::new(bx0, by0, bx1, by1)) } -fn warp(src: &Surface, src_rect: Rect, h: &Homography, interp: Interp, clip: Option) -> Result { +/// A cancelled `ctl` skips the remaining tiles; the caller discards the result. +fn warp( + src: &Surface, + src_rect: Rect, + h: &Homography, + interp: Interp, + clip: Option, + ctl: &Interrupt, +) -> Result { let mut fmt = src.format(); let converted; let mut src = if fmt.alpha { @@ -277,7 +297,16 @@ fn warp(src: &Surface, src_rect: Rect, h: &Homography, interp: Interp, clip: Opt tiles.try_reserve_exact(tile_count).map_err(|_| photocraft_raster::AllocationError::NotEnoughMemory { bytes: tile_bytes })?; tiles.extend(dst.tiles().map(|tc| tc.rect().intersect(&dst)).filter(|r| !r.is_empty())); let src_ref: &Surface = src; + // Tiles finished so far, for progress reported per tile (from any worker thread). + let finished = std::sync::atomic::AtomicUsize::new(0); + let total = tiles.len().max(1); let work = |t: &Rect| -> Result)>, photocraft_raster::AllocationError> { + if ctl.cancelled() { + return Ok(None); + } + let k = finished.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; + // The last few percent are the writes. + ctl.progress(0.98 * k as f32 / total as f32); // Source footprint of this tile (inverse-mapped corners of its sampled part), padded for the filter. let tc = [(t.x0, t.y0), (t.x1, t.y0), (t.x1, t.y1), (t.x0, t.y1)].map(|(x, y)| (x as f64, y as f64)); let wc = tc.map(|(x, y)| inv.0[6] * x + inv.0[7] * y + inv.0[8]); @@ -413,6 +442,9 @@ fn warp(src: &Surface, src_rect: Rect, h: &Homography, interp: Interp, clip: Opt } } let done = done.into_inner().unwrap_or_else(std::sync::PoisonError::into_inner); + if ctl.cancelled() { + return Ok(out); + } for (r, v) in done { out.try_write_region(r, &v)?; } @@ -424,6 +456,25 @@ fn warp(src: &Surface, src_rect: Rect, h: &Homography, interp: Interp, clip: Opt mod tests { use super::*; + #[test] + fn the_interruptible_warp_reports_progress_and_stops_when_cancelled() { + let mut s = Surface::new(PixelFormat::RGBA8); + s.fill_rect(Rect::new(0, 0, 600, 400), &[0.2, 0.4, 0.6, 1.0]); + let r = s.content_bounds(); + let h = Homography::rect_to_quad([0.0, 0.0, 600.0, 400.0], [[10.0, 0.0], [590.0, 20.0], [600.0, 400.0], [0.0, 380.0]]).unwrap(); + let reported = std::sync::Mutex::new(0.0f32); + let progress = |p: f32| { + let mut m = reported.lock().unwrap(); + *m = m.max(p); + }; + let never = || false; + let out = warp_surface_with(&s, r, &h, Interp::Bicubic, &Interrupt::new(&never, &progress)).unwrap().expect("not cancelled"); + assert_eq!(out.read_region(r), warp_surface(&s, r, &h, Interp::Bicubic).unwrap().read_region(r)); + assert!(*reported.lock().unwrap() > 0.9); + let always = || true; + assert!(warp_surface_with(&s, r, &h, Interp::Bicubic, &Interrupt::cancel_only(&always)).unwrap().is_none()); + } + /// Perspective Crop's map lands each quad corner exactly on its rectangle corner; degenerate, /// self-crossing, counter-clockwise and non-finite quads have none. #[test] diff --git a/crates/engine/src/jobs_tests.rs b/crates/engine/src/jobs_tests.rs index 4f631e82ef..a40b712c81 100644 --- a/crates/engine/src/jobs_tests.rs +++ b/crates/engine/src/jobs_tests.rs @@ -78,6 +78,22 @@ fn a_job_applies_as_one_undo_step_and_matches_the_inline_result() { assert!(s.jobs().is_empty()); } +#[test] +fn free_transform_runs_as_a_job_with_the_inline_result() { + let quad = json!({"quad": [[20, 10], [280, 30], [260, 190], [40, 170]]}); + let mut inline = session(300, 200); + inline.execute("edit.transform", quad.clone()).unwrap(); + + let mut s = session(300, 200); + let steps = s.active().unwrap().history.past_len(); + let id = job(s.start("edit.transform", quad).unwrap()); + let e = wait_event(&mut s, id); + assert!(matches!(e.outcome, JobOutcome::Done(_)), "{e:?}"); + assert_eq!(e.label, "Free Transform"); + assert_eq!(s.active().unwrap().history.past_len(), steps + 1, "one undo step"); + assert_eq!(pixels(&s), pixels(&inline), "same pixels as the synchronous command"); +} + #[test] fn cancel_leaves_the_document_byte_identical() { let mut s = session(1600, 1200); diff --git a/crates/engine/src/transform_cmds.rs b/crates/engine/src/transform_cmds.rs index a09366e6fd..bcf97126cc 100644 --- a/crates/engine/src/transform_cmds.rs +++ b/crates/engine/src/transform_cmds.rs @@ -1,10 +1,10 @@ //! Edit › Free Transform / Transform: projective transforms of layers (and the selection). -use photocraft_algo::transform::{Homography, Interp, warp_output_bounds, warp_surface}; +use photocraft_algo::transform::{Homography, Interp, warp_output_bounds, warp_surface, warp_surface_with}; use photocraft_color::PixelFormat; use photocraft_doc::{Document, Layer, LayerContent, LayerId, Locks}; use photocraft_geom::{Affine, Rect}; -use photocraft_raster::Surface; +use photocraft_raster::{Interrupt, Surface}; use serde_json::{Value, json}; use crate::commands::CommandSpec; @@ -304,11 +304,33 @@ fn check_layer_budget(doc_sel: Option<&Surface>, l: &Layer, h: &Homography) -> R /// is turned into a normal layer by the caller first ([`crate::extra_cmds::background_to_layer`]). /// Refused, with `l` untouched, when a result would exceed [`MAX_TRANSFORM_PIXELS`]. pub(crate) fn transform_layer(doc_sel: Option<&Surface>, group: Locks, l: &mut Layer, h: &Homography, affine: Option, interp: Interp) -> Result<()> { - check_layer_budget(doc_sel, l, h)?; - apply_transform(doc_sel, group, l, h, affine, interp) + transform_layer_with(doc_sel, group, l, h, affine, interp, &Interrupt::NONE) } -fn apply_transform(doc_sel: Option<&Surface>, group: Locks, l: &mut Layer, h: &Homography, affine: Option, interp: Interp) -> Result<()> { +/// [`transform_layer`] with progress and cancellation for the pixel warp (the slow part on a +/// large layer, #1015). +fn transform_layer_with( + doc_sel: Option<&Surface>, + group: Locks, + l: &mut Layer, + h: &Homography, + affine: Option, + interp: Interp, + ctl: &Interrupt, +) -> Result<()> { + check_layer_budget(doc_sel, l, h)?; + apply_transform(doc_sel, group, l, h, affine, interp, ctl) +} + +fn apply_transform( + doc_sel: Option<&Surface>, + group: Locks, + l: &mut Layer, + h: &Homography, + affine: Option, + interp: Interp, + ctl: &Interrupt, +) -> Result<()> { crate::allocation::checkpoint("transforming pixels")?; let locks = transform_locks(l, group, false); if locks.position || locks.all { @@ -317,7 +339,7 @@ fn apply_transform(doc_sel: Option<&Surface>, group: Locks, l: &mut Layer, h: &H if h.is_identity() { if let LayerContent::Group(g) = &mut l.content { for c in g.children.iter_mut() { - apply_transform(None, locks, c, h, affine, interp)?; + apply_transform(None, locks, c, h, affine, interp, ctl)?; } } return Ok(()); @@ -328,7 +350,7 @@ fn apply_transform(doc_sel: Option<&Surface>, group: Locks, l: &mut Layer, h: &H match &mut l.content { LayerContent::Group(g) => { for c in g.children.iter_mut() { - apply_transform(None, locks, c, h, affine, interp)?; + apply_transform(None, locks, c, h, affine, interp, ctl)?; } } LayerContent::Text(t) => { @@ -366,12 +388,12 @@ fn apply_transform(doc_sel: Option<&Surface>, group: Locks, l: &mut Layer, h: &H // Only the selected pixels move: lift them, clear them, warp and paste back. Some(sel) => { let (lifted, mut rest) = split_selected(surf, sel)?; - let moved = warp_surface(&lifted, src, h, interp)?; + let moved = warp_surface_with(&lifted, src, h, interp, ctl)?.ok_or(EngineError::Cancelled)?; composite_over(&mut rest, &moved); rest.prune(); rest } - None => warp_surface(surf, src, h, interp)?, + None => warp_surface_with(surf, src, h, interp, ctl)?.ok_or(EngineError::Cancelled)?, }; } } @@ -571,49 +593,69 @@ fn transform(s: &mut Session, p: &Value) -> Result { (m[6].abs() < 1e-12 && m[7].abs() < 1e-12).then(|| Affine { m: [m[0] / m[8], m[3] / m[8], m[1] / m[8], m[4] / m[8], m[2] / m[8], m[5] / m[8]] }); let interp = Interp::parse(p.get("interpolation").and_then(Value::as_str).unwrap_or("bicubic")); let lone = lone.is_some(); - s.edit("Free Transform", |doc, _| { - let sel = doc.selection.clone(); - // The selection outline moves too: price it before anything is built. - if let Some(sel) = sel.as_ref().filter(|_| !h.is_identity()) { - check_budget(sel.content_bounds(), &h, "selection")?; - } - if lone { - // A targeted unlinked mask, alpha channel or Quick Mask transforms by itself. - if !h.is_identity() { - let (surf, _) = crate::channel_cmds::target_surface(doc, id, p)?; - let src = sel.as_ref().map_or_else(|| surf.content_bounds(), Surface::content_bounds); - check_budget(src, &h, "mask or channel")?; - *surf = match &sel { - Some(sel) => warp_gray_selected(surf, sel, &h, interp)?, - None => warp_gray(surf, &h, interp)?, - }; - if let Some(sel) = &doc.selection { - doc.selection = Some(warp_gray(sel, &h, Interp::Bilinear)?).filter(|s| !s.content_bounds().is_empty()); - } - } - return Ok(()); - } - let id = id.ok_or_else(|| EngineError::Other("no active layer".into()))?; - let is_group = doc.layer(id).is_some_and(Layer::is_group); - let group = group_locks(doc, id); - // Photoshop turns the Background into a normal layer before transforming it. - crate::extra_cmds::background_to_layer(doc, id); - let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; - transform_layer(if is_group { None } else { sel.as_ref() }, group, l, &h, affine, interp)?; + let p = p.clone(); + // A background job when started with `Session::start` (#1015): the warp of a large layer runs + // on a worker with progress, and can be cancelled. + crate::jobs::edit_job( + s, + "Free Transform", + move |doc, _, ctx| ctx.stage(0.0, 1.0, "Transforming", |ctl| transform_doc(doc, id, &p, lone, &h, affine, interp, ctl)), + move |()| json!({"rect": rect}), + ) +} + +/// The edit of [`transform`]: the layer (or a lone mask or channel) and the selection outline. +#[allow(clippy::too_many_arguments)] +fn transform_doc( + doc: &mut Document, + id: Option, + p: &Value, + lone: bool, + h: &Homography, + affine: Option, + interp: Interp, + ctl: &Interrupt, +) -> Result<()> { + let sel = doc.selection.clone(); + // The selection outline moves too: price it before anything is built. + if let Some(sel) = sel.as_ref().filter(|_| !h.is_identity()) { + check_budget(sel.content_bounds(), h, "selection")?; + } + if lone { + // A targeted unlinked mask, alpha channel or Quick Mask transforms by itself. if !h.is_identity() { - // Type layers re-render from their new transform. - let snapshot = doc.clone(); - if let Some(l) = doc.layer_mut(id) { - refresh_text(&snapshot, l); - } - // The selection outline moves with the pixels. + let (surf, _) = crate::channel_cmds::target_surface(doc, id, p)?; + let src = sel.as_ref().map_or_else(|| surf.content_bounds(), Surface::content_bounds); + check_budget(src, h, "mask or channel")?; + *surf = match &sel { + Some(sel) => warp_gray_selected(surf, sel, h, interp)?, + None => warp_gray(surf, h, interp)?, + }; if let Some(sel) = &doc.selection { - doc.selection = Some(warp_gray(sel, &h, Interp::Bilinear)?).filter(|s| !s.content_bounds().is_empty()); + doc.selection = Some(warp_gray(sel, h, Interp::Bilinear)?).filter(|s| !s.content_bounds().is_empty()); } } - Ok(()) - })?; - Ok(json!({"rect": rect})) + return Ok(()); + } + let id = id.ok_or_else(|| EngineError::Other("no active layer".into()))?; + let is_group = doc.layer(id).is_some_and(Layer::is_group); + let group = group_locks(doc, id); + // Photoshop turns the Background into a normal layer before transforming it. + crate::extra_cmds::background_to_layer(doc, id); + let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; + transform_layer_with(if is_group { None } else { sel.as_ref() }, group, l, h, affine, interp, ctl)?; + if !h.is_identity() { + // Type layers re-render from their new transform. + let snapshot = doc.clone(); + if let Some(l) = doc.layer_mut(id) { + refresh_text(&snapshot, l); + } + // The selection outline moves with the pixels. + if let Some(sel) = &doc.selection { + doc.selection = Some(warp_gray(sel, h, Interp::Bilinear)?).filter(|s| !s.content_bounds().is_empty()); + } + } + Ok(()) } pub fn specs() -> Vec { diff --git a/crates/ui-egui/src/jobs_ui.rs b/crates/ui-egui/src/jobs_ui.rs index 5dc1cba41d..83218402d6 100644 --- a/crates/ui-egui/src/jobs_ui.rs +++ b/crates/ui-egui/src/jobs_ui.rs @@ -449,6 +449,8 @@ fn on_event(app: &mut PhotocraftApp, ctx: &egui::Context, e: JobEvent) { true } }); + // A Free Transform commit's session ends with its job (then reported like any job). + crate::transform_tool::on_job_event(app, &e); if crate::prefs_ui::on_recovery_event(app, &e) { return; } diff --git a/crates/ui-egui/src/jobs_ui_tests.rs b/crates/ui-egui/src/jobs_ui_tests.rs index bc29064512..3e2750f481 100644 --- a/crates/ui-egui/src/jobs_ui_tests.rs +++ b/crates/ui-egui/src/jobs_ui_tests.rs @@ -704,3 +704,65 @@ fn printing_keeps_drawing_and_reports_only_the_final_spooler_result() { } } } + +fn layer_count(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().doc.layers.len() +} + +/// Free Transform the active layer to the right half of the canvas, then ↩. +fn transform_and_commit(h: &mut Harness<'static, PhotocraftApp>, copy: bool) { + let ctx = h.ctx.clone(); + let app = h.state_mut(); + if copy { crate::transform_tool::begin_copy(app, &ctx) } else { crate::transform_tool::begin(app, &ctx) }.unwrap(); + app.ui.transform.as_mut().unwrap().quad = [[160.0, 0.0], [320.0, 0.0], [320.0, 120.0], [160.0, 120.0]]; + crate::transform_tool::commit(app); +} + +#[test] +fn a_free_transform_commit_runs_in_the_background_and_keeps_its_preview() { + let mut h = app_harness(); + let (layers, steps) = (layer_count(h.state()), h.state().session.active().unwrap().history.past_len()); + transform_and_commit(&mut h, true); + let app = h.state(); + // The warp runs as a job; the moving pixels stay on screen until it lands, and the box's + // history is closed meanwhile. + let job = crate::transform_tool::committing(app).expect("the commit runs as a job"); + assert!(app.session.job(job).is_some_and(|j| j.label == "Free Transform")); + assert!(app.ui.transform.is_some() && app.transform_preview.is_some()); + assert_eq!(crate::transform_tool::is_enabled(app, "edit.undo"), Some(false)); + assert!(h.state_mut().run("edit.undo", json!({})).is_err()); + crate::transform_tool::commit(h.state_mut()); + let t = Instant::now(); + while h.state().session.has_jobs() && t.elapsed() < Duration::from_secs(10) { + h.step(); + } + h.run_steps(2); + let app = h.state(); + assert!(app.ui.transform.is_none() && app.transform_preview.is_none(), "the session ends with the job"); + // The copy and its transform are one step, as when the commit ran inline. + let st = app.session.active().unwrap(); + assert_eq!((layer_count(app), st.history.past_len()), (layers + 1, steps + 1)); + assert_eq!(st.history.undo_label(), Some("Free Transform")); + let moved = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().content_bounds(); + assert_eq!((moved.x0, moved.y0, moved.x1, moved.y1), (160, 0, 320, 120)); +} + +#[test] +fn esc_cancels_a_background_free_transform_commit() { + let mut h = app_harness(); + let (layers, steps) = (layer_count(h.state()), h.state().session.active().unwrap().history.past_len()); + let before = h.state().session.active().unwrap().doc.clone(); + transform_and_commit(&mut h, true); + let job = crate::transform_tool::committing(h.state()).expect("the commit runs as a job"); + // Esc reaches the transform tool first (shortcuts), which cancels the job. + crate::transform_tool::cancel(h.state_mut()); + h.run_steps(3); + let app = h.state(); + assert!(app.session.job(job).is_none()); + assert!(app.ui.transform.is_none() && app.transform_preview.is_none()); + // The copy is taken back with the transform, leaving nothing to redo. + let st = app.session.active().unwrap(); + assert_eq!((layer_count(app), st.history.past_len()), (layers, steps)); + assert!(!st.history.can_redo()); + assert_eq!(st.doc.layers.len(), before.layers.len()); +} diff --git a/crates/ui-egui/src/transform_tool.rs b/crates/ui-egui/src/transform_tool.rs index 0af28a81c5..b2ff21d531 100644 --- a/crates/ui-egui/src/transform_tool.rs +++ b/crates/ui-egui/src/transform_tool.rs @@ -14,6 +14,7 @@ use std::sync::Arc; use egui::{Color32, CursorIcon, Pos2, Stroke, pos2, vec2}; use photocraft_algo::transform::Homography; use photocraft_doc::{DocId, Document, LayerContent, LayerId}; +use photocraft_engine::jobs::{JobEvent, JobId, JobOutcome}; use photocraft_geom::warp::{BezierMesh, Warp, WarpStyle}; use serde_json::json; @@ -85,6 +86,9 @@ 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, + /// The commit running as a background job (#1015): the moving pixels stay on screen, without + /// the box, until it lands; Esc cancels it. The session ends with the job. + committing: Option, /// Content-Aware Scale's live preview (cas_transform.rs). pub(crate) content_aware: Option, } @@ -229,6 +233,7 @@ pub fn begin(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String> above: Some(above), styled: styled.then(|| crate::transform_fx::StyledPreview::new(format!("transform-{session}-styled"))), follow: Some(Follow { revision, hidden: lifted.is_none() }), + committing: None, gesture: None, warp_drag: None, split_tool: None, @@ -327,6 +332,7 @@ pub(crate) fn begin_content_aware( opacity: layer.opacity * layer.fill_opacity, above: Some(above), follow: Some(Follow { revision, hidden: false }), + committing: None, gesture: None, warp_drag: None, split_tool: None, @@ -385,13 +391,20 @@ fn take_back_made(app: &mut PhotocraftApp, document: DocId, layer: LayerId) { /// After the transform: the step that made the layer and the transform become one history step, /// the transform's for a copy and Place Embedded for a placed file. -fn fold_made(app: &mut PhotocraftApp, made: MadeLayer) { +fn fold_made(app: &mut PhotocraftApp, document: DocId, made: MadeLayer) { + // A background commit lands in its own document, which need not be the active one by then. + let Some(index) = app.session.documents().iter().position(|st| st.doc.id == document) else { return }; + let active = app.session.active_index(); + app.session.set_active(index); if let Some(st) = app.session.active_mut() { st.history.purge_last(); if made == MadeLayer::Place { st.history.set_current_label(photocraft_engine::file_cmds::PLACE_EMBEDDED); } } + if let Some(active) = active { + app.session.set_active(active); + } } /// Free Transform of a targeted unlinked layer mask, alpha channel or Quick Mask by itself: the @@ -440,6 +453,7 @@ fn begin_lone( above: None, styled: None, follow: None, + committing: None, gesture: None, warp_drag: None, split_tool: None, @@ -501,6 +515,7 @@ fn begin_path(app: &mut PhotocraftApp, ctx: &egui::Context, params: serde_json:: content_aware: None, above: None, follow: None, + committing: None, }); app.ui.transform = Some(TransformSession { session, @@ -574,6 +589,7 @@ pub fn begin_selection(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<( above: None, styled: None, follow: None, + committing: None, gesture: None, warp_drag: None, split_tool: None, @@ -949,7 +965,13 @@ fn contains(l: &photocraft_doc::Layer, id: LayerId) -> bool { l.id == id || matches!(&l.content, LayerContent::Group(g) if g.children.iter().any(|c| contains(c, id))) } +/// Undo and Redo while the commit runs in the background. +const STILL_APPLYING: &str = "Free Transform is still being applied"; + pub fn commit(app: &mut PhotocraftApp) { + if committing(app).is_some() { + return; + } let document = app.transform_preview.as_ref().map(|pv| pv.doc.id); if document.is_some_and(|id| app.session.active().is_none_or(|st| st.doc.id != id)) { cancel(app); @@ -957,7 +979,7 @@ pub fn commit(app: &mut PhotocraftApp) { } let type_layer = warps_type(app); let Some(t) = app.ui.transform.take() else { return }; - let preview = app.transform_preview.take(); + let mut preview = app.transform_preview.take(); if let Some(options) = &t.content_aware { crate::cas_transform::commit(app, &t, options); return; @@ -1012,16 +1034,54 @@ pub fn commit(app: &mut PhotocraftApp) { } app.run("edit.transform", p) }; + // A large layer's warp runs in the background: the session stays until the job ends. + if let Ok(v) = &r + && let Some(job) = v.get("pending").and_then(serde_json::Value::as_bool).filter(|p| *p).and(v.get("job")).and_then(serde_json::Value::as_u64) + && let Some(pv) = preview.as_mut() + { + pv.committing = Some(JobId(job)); + app.ui.transform = Some(t); + app.transform_preview = preview; + return; + } match r { - Ok(_) => { - if let Some(made) = made { - fold_made(app, made); - } - } + Ok(_) => finish(app, document, LayerId(t.layer), made, true), Err(e) => keep_open(app, t, preview, e), } } +/// After the transform landed or not: fold the layer the session made into its step, or take it +/// back. +fn finish(app: &mut PhotocraftApp, document: Option, layer: LayerId, made: Option, landed: bool) { + let (Some(made), Some(document)) = (made, document) else { return }; + if landed { + fold_made(app, document, made); + } else { + take_back_made(app, document, layer); + } +} + +/// The job applying the transform, while it runs. +pub(crate) fn committing(app: &PhotocraftApp) -> Option { + app.transform_preview.as_ref().and_then(|pv| pv.committing) +} + +/// A job ended (see [`crate::jobs_ui`]): when it was the commit, the session ends with it. Its +/// status and errors are reported like any job's. +pub fn on_job_event(app: &mut PhotocraftApp, e: &JobEvent) { + if committing(app) != Some(e.id) { + return; + } + let (Some(t), Some(mut pv)) = (app.ui.transform.take(), app.transform_preview.take()) else { return }; + // A refused commit (a result over the pixel budget, #3773) keeps the box open, as inline. + if let JobOutcome::Failed(msg) = &e.outcome { + pv.committing = None; + keep_open(app, t, Some(pv), msg.clone()); + return; + } + finish(app, Some(pv.doc.id), LayerId(t.layer), t.made, matches!(e.outcome, JobOutcome::Done(_))); +} + /// A commit the engine refused (a result over the pixel budget, #3773): the box stays open as it /// was, with the reason in the status bar, so the transform can be changed or cancelled. A copy or /// a placed layer it made goes only when it is cancelled. @@ -1038,6 +1098,9 @@ fn keep_open(app: &mut PhotocraftApp, t: TransformSession, preview: Option Option { let t = app.ui.transform.as_ref()?; + if committing(app).is_some() { + return box_command(id).then_some(false); + } 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. @@ -1168,8 +1239,16 @@ fn box_preset(id: &str) -> Option<(f64, f64, f64)> { /// document under the box, is refused. Edit › Transform's Rotate and Flip turn the box itself, as /// in Photoshop, instead of the layer under it; committing stays with ↩ and the options bar. /// `None` for other commands or when not transforming. +/// The commands the open box answers itself ([`is_enabled`], [`intercept`]). +fn box_command(id: &str) -> bool { + matches!(id, "edit.undo" | "edit.redo" | "edit.toggleLastState" | "edit.contentAwareScale" | "edit.puppetWarp") || box_preset(id).is_some() +} + pub fn intercept(app: &mut PhotocraftApp, id: &str) -> Option> { let warping = app.ui.transform.as_ref()?.warp.is_some(); + if committing(app).is_some() { + return box_command(id).then(|| Err(STILL_APPLYING.into())); + } match id { "edit.undo" => Some(Ok(step(app, false))), "edit.redo" => Some(Ok(step(app, true))), @@ -1259,6 +1338,9 @@ fn accepts_outside_click(g: Gesture, end: [f64; 2], tol: f64) -> bool { /// Pointer input while transforming. Returns false when no transform is active. pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> bool { let Some(t) = app.ui.transform.clone() else { return false }; + if committing(app).is_some() { + return true; + } let tol = handle_tolerance(app); if t.warp.is_some() { warp_pointer(app, ev, tol, mods); @@ -1991,6 +2073,9 @@ pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform if let Some(a) = &pv.above { a.draw(painter, xf); } + if pv.committing.is_some() { + return; + } let accent = crate::theme::Tokens::get(painter.ctx()).accent; if let (Some(path), Some(h)) = (&pv.path, Homography::rect_to_quad(t.rect, t.quad)) { crate::vector_ui::draw_outline( From 4d4103460f2f606ebd10dc17cd9c6ce77d452164 Mon Sep 17 00:00:00 2001 From: Dan Hiorns Date: Mon, 12 Oct 2026 20:01:17 -0600 Subject: [PATCH 03/15] Toolbar: a press outside a tool flyout closes it (#4460) (#4480) An open tool flyout closed only on a click outside it. Dragging on the canvas (cropping, painting) isn't a click, so the flyout stayed open over the work. Any press that starts outside the flyout and its button now closes it, as in Photoshop. A press on the flyout itself still keeps it open for the row it picks on release, and Escape still closes it. Co-authored-by: Claude Opus 5.5 Co-authored-by: Brandon Thomas --- crates/ui-egui/src/panels.rs | 58 +++++++++++++++++++++++++++++++++--- 1 file changed, 54 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 95bf65068f..6134274d4a 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -264,10 +264,13 @@ pub fn toolbar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { }); }, ); - let held_release = resp.clicked() && ui.data(|d| d.get_temp::(held_id)) == Some(key); - let clicked_outside = - ui.input(|i| i.pointer.any_click()) && !held_release && !area.response.hovered() && !resp.hovered(); - if clicked_outside || ui.input(|i| i.key_pressed(egui::Key::Escape)) { + // Any press outside the flyout and its button closes it, as in Photoshop: a + // drag on the canvas (cropping, painting) isn't a click (#4460). + let pressed_outside = ui.input(|i| { + i.pointer.any_pressed() + && i.pointer.press_origin().is_some_and(|p| !area.response.rect.contains(p) && !resp.rect.contains(p)) + }); + if pressed_outside || ui.input(|i| i.key_pressed(egui::Key::Escape)) { ui.data_mut(|d| d.remove::<(egui::Id, Rect)>(flyout_id)); } } @@ -4827,6 +4830,53 @@ mod type_flyout_tests { } } + /// #4460: a press outside an open flyout closes it, even when it becomes a drag (cropping or + /// painting on the canvas) rather than a click; a press on the flyout keeps it for its pick. + #[test] + fn a_drag_outside_closes_the_tool_flyout() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ALL[0]); + frame(&mut app, &ctx, 0.0, vec![]); + frame(&mut app, &ctx, 0.1, vec![]); + let index = TOOL_SECTIONS.iter().flat_map(|section| section.iter()).position(|slot| slot.contains(&Tool::Brush)).unwrap(); + let bx = if Tokens::get(&ctx).pro { 30.0 } else { 36.0 }; + let mut buttons: Vec = ctx.viewport(|v| { + v.prev_pass + .widgets + .layers() + .flat_map(|(_, w)| w.iter()) + .filter(|w| w.rect.size() == egui::Vec2::splat(bx) && w.sense.senses_click()) + .map(|w| w.rect) + .collect() + }); + buttons.sort_by(|a, b| a.top().total_cmp(&b.top())); + let at = buttons[index].center(); + let flyout = |ctx: &egui::Context| ctx.data(|d| d.get_temp::<(egui::Id, Rect)>(egui::Id::new("tool-flyout"))).is_some(); + let secondary = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Secondary, pressed, modifiers: Default::default() }; + let primary = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + let open = |app: &mut PhotocraftApp, t: f64| { + frame(app, &ctx, t, vec![egui::Event::PointerMoved(at), secondary(true)]); + frame(app, &ctx, t + 0.05, vec![secondary(false)]); + frame(app, &ctx, t + 0.1, vec![]); + assert!(flyout(&ctx), "right-click opens it"); + }; + // A press on the flyout itself keeps it open (the row picks on release). + open(&mut app, 1.0); + let menu = ctx.memory(|m| m.area_rect(egui::Id::new(("tool-slot", index)).with("flyout"))).unwrap(); + frame(&mut app, &ctx, 1.5, vec![egui::Event::PointerMoved(menu.center()), primary(menu.center(), true)]); + assert!(flyout(&ctx), "a press on the flyout keeps it"); + frame(&mut app, &ctx, 1.55, vec![primary(menu.center(), false)]); + // A drag far from the toolbar (the canvas) closes it as soon as it starts. + open(&mut app, 2.0); + let canvas = egui::pos2(900.0, 900.0); + frame(&mut app, &ctx, 2.5, vec![egui::Event::PointerMoved(canvas), primary(canvas, true)]); + frame(&mut app, &ctx, 2.55, vec![egui::Event::PointerMoved(canvas + vec2(80.0, 60.0))]); + assert!(!flyout(&ctx), "a press outside closes it, even one that becomes a drag"); + frame(&mut app, &ctx, 2.6, vec![primary(canvas + vec2(80.0, 60.0), false)]); + assert!(!flyout(&ctx)); + } + #[test] fn red_eye_is_in_the_j_flyout() { let j = TOOL_SECTIONS.iter().flat_map(|section| section.iter()).find(|slot| slot.contains(&Tool::SpotHealing)).expect("J group"); From cee010ef5a60e392dddc611e7312c35871b36df5 Mon Sep 17 00:00:00 2001 From: mroxso <24775431+mroxso@users.noreply.github.com> Date: Tue, 13 Oct 2026 04:03:15 +0200 Subject: [PATCH 04/15] Replace Color: a canvas eyedropper picks the From colour (#4143) (#4247) The dialog had no colour control at all: the engine defaulted the From colour to the foreground and the spec's `color` param rendered nothing. It now shows a Color row (swatch opens the Color Picker, seeded from the foreground) plus a pipette that arms a canvas eyedropper: the next click on the image samples the merged composite into the field, like the Curves picker and Photoshop's Replace Color. Co-authored-by: highperfocused Co-authored-by: Brandon Thomas Co-authored-by: Claude Opus 5.5 --- crates/engine/src/adjust_cmds.rs | 2 +- crates/ui-egui/src/canvas.rs | 9 ++- crates/ui-egui/src/filter_dialog.rs | 90 +++++++++++++++++++++++++++++ crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + 6 files changed, 100 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/adjust_cmds.rs b/crates/engine/src/adjust_cmds.rs index 15c3af2060..738ef921f4 100644 --- a/crates/engine/src/adjust_cmds.rs +++ b/crates/engine/src/adjust_cmds.rs @@ -454,7 +454,7 @@ pub fn specs() -> Vec { "image.adjustments.replaceColor", "Replace Color…", ["Image", "Adjustments"], - r##"{"color":json,"fuzziness":0..200=40,"hue":-180..180=0,"saturation":-100..100=0,"lightness":-100..100=0} (color: "#rrggbb", default the foreground colour)"##, + r##"{"color":color,"fuzziness":0..200=40,"hue":-180..180=0,"saturation":-100..100=0,"lightness":-100..100=0} (color: "#rrggbb", default the foreground colour)"##, has_pixels, replace_color ), diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index d4a1cbb58b..4f78b853f2 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -3022,10 +3022,11 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: if under_dialog { // With a colour dialog picker armed the image is its eyedropper, whatever the tool; Space - // and the middle button still pan. Curves uses the same merged-composite sampler as the - // Color Picker, never the reduced adjustment preview. + // and the middle button still pan. Curves and Replace Color use the same merged-composite + // sampler as the Color Picker, never the reduced adjustment preview. let curves_picking = crate::adjust_dialog::picker_armed(app); - let picking = primary && (crate::color_picker_ui::top(app).is_some() || curves_picking); + let replace_picking = crate::filter_dialog::color_eyedropper_armed(app); + let picking = primary && (crate::color_picker_ui::top(app).is_some() || curves_picking || replace_picking); let range_picking = primary && app.ui.dialogs.last().is_some_and(|d| crate::color_range_ui::owns(&d.fields) && crate::color_range_ui::controls(&d.fields).sampling); // Select and Mask's Refine Edge Brush paints on the image. @@ -3049,6 +3050,8 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: let d = xf.to_doc(p); if curves_picking { crate::adjust_dialog::sample_at(app, d[0], d[1]); + } else if replace_picking { + crate::filter_dialog::color_eyedropper_sample(app, d[0], d[1]); } else { crate::color_picker_ui::sample_at(app, d[0], d[1]); } diff --git a/crates/ui-egui/src/filter_dialog.rs b/crates/ui-egui/src/filter_dialog.rs index 8f588fbc99..31ef157110 100644 --- a/crates/ui-egui/src/filter_dialog.rs +++ b/crates/ui-egui/src/filter_dialog.rs @@ -343,6 +343,11 @@ fn default_value(app: &PhotocraftApp, command: &str, p: &Param) -> Option // Identity kernel: 1 in the centre. Kind::Grid(n) => json!((0..*n).map(|i| i64::from(i == *n / 2)).collect::>()), Kind::Color(Some(rgb)) => json!(crate::color_picker_ui::hex(*rgb)), + // Replace Color starts from the foreground colour and can sample a new one off the canvas. + Kind::Color(None) if command == REPLACE_COLOR => { + let fg = app.session.tools.foreground; + json!(crate::color_picker_ui::hex([fg[0], fg[1], fg[2]])) + } Kind::Color(None) => return None, // Colour inputs come from the current swatches, so the proxy preview matches the result. Kind::Json if p.key == "foreground" => json!(app.session.tools.foreground), @@ -542,6 +547,38 @@ fn uses_angle_dial(command: &str, key: &str) -> bool { key == "angle" && ANGLE_DIAL.contains(&command) } +/// Replace Color (#4143): the dialog's "From" colour, sampled from the image with a canvas +/// eyedropper like Photoshop's. While armed, the next click on the image writes the merged +/// composite colour into the `color` field (the same sampler the Color Picker uses). +const REPLACE_COLOR: &str = "image.adjustments.replaceColor"; +const COLOR_EYEDROPPER: &str = "__colorEyedropper"; + +fn color_eyedropper_owns(f: &Map) -> bool { + f.get("__filter").and_then(Value::as_bool) == Some(true) + && f.get("__command").and_then(Value::as_str) == Some(REPLACE_COLOR) + && f.get(COLOR_EYEDROPPER).and_then(Value::as_bool) == Some(true) +} + +/// Whether the top dialog is a Replace Color with its canvas eyedropper armed. +pub(crate) fn color_eyedropper_armed(app: &PhotocraftApp) -> bool { + app.ui.dialogs.last().is_some_and(|d| color_eyedropper_owns(&d.fields)) +} + +/// Sample the merged image at document point (x, y) into the armed dialog's "From" colour. +/// Returns true when the click was consumed, even off-image or over transparency, where nothing +/// changes and the eyedropper stays armed (like the Curves picker). +pub(crate) fn color_eyedropper_sample(app: &mut PhotocraftApp, x: f64, y: f64) -> bool { + let Some(id) = app.ui.dialogs.last().filter(|d| color_eyedropper_owns(&d.fields)).map(|d| d.id) else { + return false; + }; + if let Some(rgb) = crate::canvas::composite_color(app, x, y) + && let Some(d) = app.ui.dialog_mut(id) + { + d.fields.insert("color".into(), json!(crate::color_picker_ui::hex(rgb))); + } + true +} + /// Dialog body for filter commands. pub fn body(ui: &mut egui::Ui, f: &mut Map) { let t = Tokens::get(ui.ctx()); @@ -684,11 +721,18 @@ pub fn body(ui: &mut egui::Ui, f: &mut Map) { let bytes = rgb.map(q); let name = label(&p.key); let mut clicked = false; + let eyedropper = cmd == REPLACE_COLOR && p.key == "color"; ui.horizontal(|ui| { ui.label(egui::RichText::new(&name).color(t.text_dim)); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { // PhotoCraft's Color Picker, as everywhere else (#2144). clicked = crate::widgets::color_swatch_button(ui, egui::Color32::from_rgb(bytes[0], bytes[1], bytes[2]), &name).clicked(); + if eyedropper { + let armed = f.get(COLOR_EYEDROPPER).and_then(Value::as_bool).unwrap_or(false); + if crate::icons::button(ui, "pipette", 24.0, armed, "Pick Color From Image").clicked() { + f.insert(COLOR_EYEDROPPER.into(), json!(!armed)); + } + } ui.label(egui::RichText::new(crate::color_picker_ui::hex(rgb)).color(t.text_dim).monospace()); }); }); @@ -1911,4 +1955,50 @@ mod tests { let fields = &app.ui.dialogs.last().unwrap().fields; assert_eq!(fields["direction"], json!("cw"), "Explicit default matching first option is preserved"); } + + /// #4143: Replace Color shows the From colour (defaulting to the foreground) and its canvas + /// eyedropper samples the merged image into the dialog. + #[test] + fn replace_color_eyedropper_samples_the_image() { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16, "background": "#00ff00"})).unwrap(); + let mut app = PhotocraftApp::new(s, crate::Services::default()); + app.run("tools.setColors", json!({"foreground": "#ff0000"})).unwrap(); + let id = open(&mut app, REPLACE_COLOR).unwrap(); + assert_eq!(app.ui.dialogs.last().unwrap().fields["color"], json!("#ff0000"), "the dialog starts from the foreground colour"); + assert!(!color_eyedropper_armed(&app)); + app.ui.dialog_mut(id).unwrap().fields.insert(COLOR_EYEDROPPER.into(), json!(true)); + assert!(color_eyedropper_armed(&app)); + assert!(color_eyedropper_sample(&mut app, 4.0, 4.0)); + assert_eq!(app.ui.dialogs.last().unwrap().fields["color"], json!("#00ff00")); + // Off-image: the click is consumed, nothing changes and the eyedropper stays armed. + assert!(color_eyedropper_sample(&mut app, -1.0, 4.0)); + assert_eq!(app.ui.dialogs.last().unwrap().fields["color"], json!("#00ff00")); + assert!(color_eyedropper_armed(&app)); + // Disarmed, the dialog never claims the click. + app.ui.dialog_mut(id).unwrap().fields.insert(COLOR_EYEDROPPER.into(), json!(false)); + assert!(!color_eyedropper_armed(&app)); + assert!(!color_eyedropper_sample(&mut app, 4.0, 4.0)); + } + + /// #4143: the eyedropper button arms and disarms the canvas picker. + #[test] + fn replace_color_dialog_arms_the_eyedropper_button() { + use egui_kittest::Harness; + use egui_kittest::kittest::Queryable; + + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16})).unwrap(); + let mut app = PhotocraftApp::new(s, crate::Services::default()); + let mut h = Harness::builder().with_size(egui::vec2(900.0, 700.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), &mut app); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + open(h.state_mut(), REPLACE_COLOR).unwrap(); + h.run_steps(3); + h.get_by_label("Pick Color From Image").click(); + h.run_steps(2); + assert!(color_eyedropper_armed(h.state())); + h.get_by_label("Pick Color From Image").click(); + h.run_steps(2); + assert!(!color_eyedropper_armed(h.state())); + } } diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 0775780a4f..9476ed77a2 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -3396,6 +3396,7 @@ cameraRaw Yellow Sárga Photomerge Fotóegyesítés Pick a screen pixel or press Esc to cancel Válassz egy pixelt a képernyőn, vagy nyomd meg az Esc billentyűt a megszakításhoz Pick screen color Szín kiválasztása a képernyőről + Pick Color From Image Szín felvétele a képről Pins Tűk Pixel Layer Pixelréteg Place Scale Marker Méretarány-jelölő elhelyezése diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index c67ccd0138..c34e673367 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -2316,6 +2316,7 @@ Color Picker (Stroke Color) Renk Seçici (Kontur Rengi) Stroke color Kontur rengi Pick screen color Ekran rengini seç + Pick Color From Image Görüntüden Renk Seç Sample a pixel anywhere on the screen Ekranın herhangi bir yerinde bir pikseli örnekleyin Click to pick · Esc to cancel Seçmek için tıklayın · İptal etmek için Esc Pick a screen pixel or press Esc to cancel Bir ekran pikseli seçin veya iptal etmek için Esc tuşuna basın diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 5157c3d46d..9fc122a766 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -2033,6 +2033,7 @@ layers Fill: Độ tô: Option-click to define a source point to clone from Option+nhấp để chỉ định điểm nguồn nhân bản Out of gamut for printing: click for the nearest printable colour Ngoài gamut in: nhấp để lấy màu in được gần nhất Pick screen color Lấy màu màn hình + Pick Color From Image Lấy màu từ hình ảnh Point Sample Mẫu điểm Pupil Size Kích thước đồng tử Quick Selection found nothing there Chọn nhanh không tìm thấy gì From 575f8eb2bc54eeeeba27c4c5349f2b7002deb68b Mon Sep 17 00:00:00 2001 From: Jannik Wappler <167129173+RavoxX@users.noreply.github.com> Date: Tue, 13 Oct 2026 05:16:06 +0300 Subject: [PATCH 05/15] Allow toolbar tool shortcuts to be remapped (#4194) Co-authored-by: Brandon Thomas Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/menus.rs | 8 ++ crates/ui-egui/src/panels.rs | 10 +- crates/ui-egui/src/prefs_ui.rs | 8 ++ crates/ui-egui/src/shortcut_capture_tests.rs | 88 ++++++++++++++++++ crates/ui-egui/src/shortcut_dispatch.rs | 1 + crates/ui-egui/src/shortcuts.rs | 8 +- crates/ui-egui/src/tool_shortcuts.rs | 96 ++++++++++++++++++++ docs/gaps.md | 5 +- docs/ui-parity.md | 4 +- 10 files changed, 221 insertions(+), 8 deletions(-) create mode 100644 crates/ui-egui/src/tool_shortcuts.rs diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 4a05a57282..873437b260 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -199,6 +199,7 @@ mod tool_cursor; pub mod tool_feedback; pub(crate) mod tool_memory; mod tool_reset; +mod tool_shortcuts; pub mod transform_fx; pub mod transform_tex; pub mod transform_tool; diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 161c64c0c2..71fab42239 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -161,6 +161,10 @@ pub fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: Va /// [`invoke`] without the unsaved-changes prompt, for once the user has already answered it. pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: Value) -> Result { + if let Some(tool) = crate::tool_shortcuts::tool(id) { + app.ui.tool = tool; + return Ok(json!({"tool": tool})); + } if id == "ui.symmetryTransform" { return crate::symmetry_ui::begin(app).map(|_| Value::Null); } @@ -660,6 +664,9 @@ fn open_path(app: &mut PhotocraftApp, path: &str) -> Result { } pub fn is_enabled(app: &PhotocraftApp, id: &str) -> bool { + if crate::tool_shortcuts::tool(id).is_some() { + return true; + } if id == "ui.symmetryTransform" { return crate::symmetry_ui::can_transform(app); } @@ -890,6 +897,7 @@ pub struct MenuItem { pub fn is_live(id: &str) -> bool { static UI_IDS: std::sync::OnceLock> = std::sync::OnceLock::new(); photocraft_engine::commands::find(id).is_some() + || crate::tool_shortcuts::tool(id).is_some() || UI_IDS.get_or_init(|| UI_COMMANDS.iter().map(|c| c.0).collect()).contains(id) || panel_alias(id).is_some() || workspace_name(id).is_some() diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 6134274d4a..78f1715c98 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -157,8 +157,10 @@ pub fn toolbar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let key = egui::Id::new(("tool-slot", *slot_index)); let tool = slot_tool(ui, app.ui.tool, slot, key); let sel = slot.contains(&app.ui.tool); - let tip = - if tool.key() == '\0' { tl!(tool.label()).to_string() } else { format!("{} ({})", tl!(tool.label()), tool.key()) }; + let tip = match crate::tool_shortcuts::shortcut(app, tool) { + Some(sc) => format!("{} ({})", tl!(tool.label()), crate::shortcuts::pretty(&sc)), + None => tl!(tool.label()).to_string(), + }; let resp = icons::button_with_icon_size_tip(ui, icons::tool_icon(tool), bx, toolbar_icon_size(bx, t.pro), sel, &tip, tool_tips); if slot.len() > 1 { @@ -247,11 +249,11 @@ pub fn toolbar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { egui::FontId::proportional(12.5), t.text, ); - if item.key() != '\0' { + if let Some(sc) = crate::tool_shortcuts::shortcut(app, item) { ui.painter().text( pos2(r.right() - 8.0, r.center().y), Align2::RIGHT_CENTER, - item.key().to_string(), + crate::shortcuts::pretty(&sc), egui::FontId::proportional(12.0), t.text_dim, ); diff --git a/crates/ui-egui/src/prefs_ui.rs b/crates/ui-egui/src/prefs_ui.rs index 202944b58a..8260fed722 100644 --- a/crates/ui-egui/src/prefs_ui.rs +++ b/crates/ui-egui/src/prefs_ui.rs @@ -765,6 +765,11 @@ pub fn shortcut_items(app: &PhotocraftApp) -> Vec<(String, String, Vec, let at = out.iter().rposition(|i| i.2.first().map(String::as_str) == Some("Layer")).map_or(out.len(), |i| i + 1); out.splice(at..at, layer); out.extend(tools); + out.extend( + crate::state::Tool::ALL + .into_iter() + .map(|tool| (crate::tool_shortcuts::id(tool), tool.label().to_string(), vec!["Tools".into()], crate::tool_shortcuts::default(tool))), + ); for (id, label, def) in prefs::TEMPORARY_TOOLS { if seen.insert(id.to_string()) { out.push((id.to_string(), label.to_string(), vec!["Tools".into(), "Temporary".into()], Some(def.to_string()))); @@ -1670,6 +1675,9 @@ fn shortcuts_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map, id: u64, name: &str) -> Value { h.state().ui.dialogs.iter().find(|d| d.id == id).unwrap().fields.get(name).cloned().unwrap_or(Value::Null) } +#[test] +fn toolbar_shortcut_can_be_captured_and_restored_on_restart() { + let (mut h, id) = dialog(1.0, "tools.select.pencil", "Pencil Tool"); + h.get_by_role_and_label(egui::accesskit::Role::Button, "B").click(); + h.run_steps(2); + h.key_press(Key::F6); + h.run_steps(2); + assert_eq!(field(&h, id, "overrides")["tools.select.pencil"], json!("F6")); + crate::dialogs::confirm(h.state_mut(), id).unwrap(); + h.run_steps(2); + h.key_press(Key::F6); + h.run_steps(2); + assert_eq!(h.state().ui.tool, crate::state::Tool::Pencil); + + let saved = h.state().session.prefs_to_json(); + let mut session = photocraft_engine::Session::new(); + session.load_prefs_json(&saved).unwrap(); + let mut restarted = PhotocraftApp::new(session, crate::Services::default()); + let ctx = egui::Context::default(); + ctx.begin_pass(egui::RawInput { + events: vec![Event::Key { key: Key::F6, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }], + ..Default::default() + }); + crate::shortcuts::handle(&mut restarted, &ctx); + ctx.end_pass().textures_delta.clear(); + assert_eq!(restarted.ui.tool, crate::state::Tool::Pencil); +} + +#[test] +fn toolbar_shortcut_overrides_remove_old_keys_and_skip_removed_group_members() { + use crate::state::Tool; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + let press = |app: &mut PhotocraftApp, key, modifiers| { + ctx.begin_pass(egui::RawInput { + // A tap: press and release, so the next press isn't a held key's repeat. + events: vec![ + Event::ModifiersChanged(modifiers), + Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }, + Event::Key { key, physical_key: None, pressed: false, repeat: false, modifiers }, + ], + ..Default::default() + }); + crate::shortcuts::handle(app, &ctx); + ctx.end_pass().textures_delta.clear(); + }; + app.run("edit.keyboardShortcuts", json!({"set": {"tools.select.move": "F6", "tools.select.pencil": ""}, "allowUnknown": true})).unwrap(); + app.ui.tool = Tool::Zoom; + press(&mut app, Key::V, Modifiers::NONE); + assert_eq!(app.ui.tool, Tool::Artboard, "the old key only selects unchanged tools"); + press(&mut app, Key::F6, Modifiers::NONE); + assert_eq!(app.ui.tool, Tool::Move); + + app.ui.tool = Tool::Pencil; + press(&mut app, Key::V, Modifiers::NONE); + press(&mut app, Key::B, Modifiers::NONE); + assert_eq!(app.ui.tool, Tool::Brush, "a removed tool cannot return through group memory"); + press(&mut app, Key::B, Modifiers::SHIFT); + assert_eq!(app.ui.tool, Tool::MixerBrush, "Shift cycling skips a removed tool"); + + app.run("edit.keyboardShortcuts", json!({"reset": true})).unwrap(); + app.ui.tool = Tool::Brush; + press(&mut app, Key::B, Modifiers::SHIFT); + assert_eq!(app.ui.tool, Tool::Pencil, "reset restores the default group"); + app.session.edit_prefs(|p| p.tools.use_shift_key_for_tool_switch = false); + press(&mut app, Key::B, Modifiers::NONE); + assert_eq!(app.ui.tool, Tool::MixerBrush, "plain-key cycling still follows the preference"); +} + +#[test] +fn toolbar_shortcuts_participate_in_conflict_resolution() { + let (mut h, id) = dialog(1.0, "edit.search", "search…"); + capture(&mut h, &crate::shortcuts::pretty("Cmd+F"), Key::ControlLeft, Modifiers::COMMAND, Key::B); + // Remove Ctrl from the captured binding: a plain B belongs to the Brush group by default. + h.state_mut().ui.dialog_mut(id).unwrap().fields["overrides"]["edit.search"] = json!("B"); + crate::dialogs::confirm(h.state_mut(), id).unwrap(); + for tool in ["brush", "pencil", "mixerBrush", "colorReplacement"] { + assert_eq!(h.state().session.prefs().shortcuts.get(&format!("tools.select.{tool}")).map(String::as_str), Some("")); + } + let ctx = h.ctx.clone(); + h.state_mut().ui.tool = crate::state::Tool::Move; + key(&mut h, Key::B, true, Modifiers::NONE); + h.run_steps(2); + assert!(h.state().ui.palette_open, "B now runs Search"); + assert_eq!(h.state().ui.tool, crate::state::Tool::Move); + assert_eq!(crate::shortcut_dispatch::take_log(&ctx).last().map(|i| i.0.as_str()), Some("edit.search")); +} + /// Click the selected command's shortcut button, then press `modifier` and `k` like a keyboard: /// the modifier key goes down first (its own key event), then the key with the modifier held. fn capture(h: &mut Harness<'_, PhotocraftApp>, button: &str, modifier: Key, held: Modifiers, k: Key) { diff --git a/crates/ui-egui/src/shortcut_dispatch.rs b/crates/ui-egui/src/shortcut_dispatch.rs index 17607c479f..1a6980077d 100644 --- a/crates/ui-egui/src/shortcut_dispatch.rs +++ b/crates/ui-egui/src/shortcut_dispatch.rs @@ -302,6 +302,7 @@ fn label(id: &str) -> String { .map(|c| c.1) .or_else(|| crate::menus::UI_COMMANDS.iter().find(|c| c.0 == id).map(|c| c.1)) .or_else(|| photocraft_engine::commands::find(id).map(|c| c.label)) + .or_else(|| crate::tool_shortcuts::tool(id).map(|tool| tool.label())) .unwrap_or(id) .trim_end_matches('…') .to_string() diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index 6e592385a1..c8528e1aa5 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -108,6 +108,7 @@ pub fn default_shortcut(id: &str) -> Option { .or_else(|| crate::menu_catalog::CATALOG.iter().find(|c| c.3 == id).and_then(|c| c.2)) .or_else(|| photocraft_engine::prefs::TEMPORARY_TOOLS.iter().find(|t| t.0 == id).map(|t| t.2)) .map(str::to_string) + .or_else(|| crate::tool_shortcuts::tool(id).and_then(crate::tool_shortcuts::default)) } /// With ⇧ held the OS reports the shifted character as the logical key (US layout): ⇧; is `:`. @@ -580,15 +581,18 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context) { ctx.input_mut(|i| i.events.retain(|e| !matches!(e, egui::Event::Key { key, pressed: true, repeat: true, .. } if crate::spring_tools::is_tool_key(*key)))); let shift_switch = app.session.prefs().tools.use_shift_key_for_tool_switch; for t in Tool::ALL { + if !crate::tool_shortcuts::uses_default(app, t) { + continue; + } let Some(k) = crate::spring_tools::key_of(t.key()) else { continue }; let cycle_shift = shift_switch && ctx.input_mut(|i| i.consume_key(Modifiers::SHIFT, k)); if cycle_shift || pressed(k) { let before = app.ui.tool; - let group: Vec = Tool::ALL.iter().copied().filter(|x| x.key() == t.key()).collect(); + let group: Vec = Tool::ALL.iter().copied().filter(|x| x.key() == t.key() && crate::tool_shortcuts::uses_default(app, *x)).collect(); app.ui.tool = match group.iter().position(|x| *x == app.ui.tool) { Some(i) if shift_switch && !cycle_shift => group[i], Some(i) => group[(i + 1) % group.len()], - None => app.ui.group_tool(t.key()).unwrap_or(group[0]), + None => app.ui.group_tool(t.key()).filter(|last| group.contains(last)).unwrap_or(group[0]), }; // `consume_key` ignores extra ⇧ and ⌥: a ⇧/⌥ switch is never spring-loaded. let (plain, now) = ctx.input(|i| (!cycle_shift && !i.modifiers.shift && !i.modifiers.alt, i.time)); diff --git a/crates/ui-egui/src/tool_shortcuts.rs b/crates/ui-egui/src/tool_shortcuts.rs new file mode 100644 index 0000000000..345b7f57b3 --- /dev/null +++ b/crates/ui-egui/src/tool_shortcuts.rs @@ -0,0 +1,96 @@ +//! Toolbar tools in Edit › Keyboard Shortcuts (#4086). Explicit assignments select an +//! individual tool; unchanged tools keep Photoshop's shared keys and Shift cycling. + +use crate::{PhotocraftApp, state::Tool}; + +pub(crate) fn id(tool: Tool) -> String { + let mut name = format!("{tool:?}"); + if let Some(first) = name.get_mut(..1) { + first.make_ascii_lowercase(); + } + format!("tools.select.{name}") +} + +pub(crate) fn tool(id: &str) -> Option { + let name = id.strip_prefix("tools.select.")?; + let tool = Tool::from_name(name)?; + (id == self::id(tool)).then_some(tool) +} + +pub(crate) fn default(tool: Tool) -> Option { + (tool.key() != '\0').then(|| tool.key().to_string()) +} + +pub(crate) fn shortcut(app: &PhotocraftApp, tool: Tool) -> Option { + crate::shortcuts::effective_shortcut(app, &id(tool), default(tool).as_deref()) +} + +pub(crate) fn uses_default(app: &PhotocraftApp, tool: Tool) -> bool { + !app.session.prefs().shortcuts.contains_key(&id(tool)) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn every_toolbar_tool_has_a_unique_live_shortcut_row() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + let items = crate::prefs_ui::shortcut_items(&app); + let mut ids = std::collections::HashSet::new(); + for t in Tool::ALL { + let id = id(t); + assert!(ids.insert(id.clone())); + assert_eq!(tool(&id), Some(t)); + assert!(crate::menus::is_live(&id)); + assert!(crate::menus::is_enabled(&app, &id)); + let rows: Vec<_> = items.iter().filter(|i| i.0 == id).collect(); + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].1, t.label()); + assert_eq!(rows[0].2, ["Tools"]); + assert_eq!(rows[0].3, default(t)); + assert_eq!(crate::shortcuts::default_shortcut(&id), default(t)); + crate::menus::invoke(&mut app, &ctx, &id, json!({})).unwrap(); + assert_eq!(app.ui.tool, t); + } + for id in ["tools.select.", "tools.select.missing", "tools.select.Brush"] { + assert!(!crate::menus::is_live(id)); + assert!(crate::menus::invoke(&mut app, &ctx, id, json!({})).is_err()); + } + } + + #[test] + fn toolbar_hints_follow_assignments_removal_and_reset() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + assert_eq!(shortcut(&app, Tool::Pencil).as_deref(), Some("B")); + assert_eq!(shortcut(&app, Tool::SingleRowMarquee), None); + app.run("prefs.set", json!({"path": "shortcuts.tools.select.pencil", "value": "F6"})).unwrap(); + assert_eq!(shortcut(&app, Tool::Pencil).as_deref(), Some("F6")); + app.run("prefs.set", json!({"path": "shortcuts.tools.select.pencil", "value": ""})).unwrap(); + assert_eq!(shortcut(&app, Tool::Pencil), None); + app.run("prefs.reset", json!({"path": "shortcuts.tools.select.pencil"})).unwrap(); + assert_eq!(shortcut(&app, Tool::Pencil).as_deref(), Some("B")); + } + + #[test] + fn a_remapped_tool_letter_does_not_steal_text_input() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("prefs.set", json!({"path": "shortcuts.tools.select.pencil", "value": "Q"})).unwrap(); + let mut h = egui_kittest::Harness::builder().build_ui_state( + |ui, app: &mut PhotocraftApp| { + ui.text_edit_singleline(&mut app.ui.status).request_focus(); + crate::shortcuts::handle(app, ui.ctx()); + }, + app, + ); + h.run_steps(3); + assert!(h.ctx.text_edit_focused()); + h.key_press(egui::Key::Q); + h.event(egui::Event::Text("q".into())); + h.run_steps(2); + assert_eq!(h.state().ui.tool, Tool::Brush); + assert_eq!(h.state().ui.status, "q"); + } +} diff --git a/docs/gaps.md b/docs/gaps.md index 8e75167810..70b2dde405 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where PhotoCraft falls short of Photoshop -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed) · **Target:** Adobe Photoshop 2026 Every known shortfall against Photoshop 2026 (27.11.0), one entry each, ranked by user impact on the way to beta. This is the work list agents pick from: take the highest-ranked entry that @@ -170,6 +170,8 @@ what an agent can't finish alone. - **Estimate:** 60–110 h. ### G9. Panels, preferences and workspace +- **Progress (2026-10-12):** toolbar tool shortcuts can be reassigned, removed and reset (#4086), + with saved bindings, matching toolbar hints and regression coverage (`ui-egui/src/tool_shortcuts.rs`). - **Missing:** 27 of 156 preferences do nothing (scorecard prefs audit); panel groups can't float or tear off into OS windows (UI-217-5, #1828, #1213, #2305); Color panel lacks wheel and slider modes (UI-217-17, #2569); more themes (UI-217-11, #2661); layer clipboard @@ -240,6 +242,7 @@ what an agent can't finish alone. | Date | Change | Summary | |---|---|---| +| 2026-10-12 | minor | G9: toolbar tool shortcut editing (#4086); the remaining workspace gaps stay open | | 2026-10-12 | minor | G1: #2465 (CS2 `PlLd`-only smart objects) marked fixed | | 2026-10-12 | minor | G5: spring-loaded tool letters done (#2672) | | 2026-10-12 | minor | G10: DPX read and write (#1049); Cineon remains open | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index d48af3bfcd..8c0e0d2580 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity: tools, handles, modifiers and feel -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (⇧-dragged guides land on ruler ticks; layer and selection keys; tool keys; spring-loaded tool letters; type formatting keys; Pen Auto Add/Delete, #4144) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (toolbar tool shortcuts can be reassigned; ⇧-dragged guides land on ruler ticks; layer and selection keys; tool keys; spring-loaded tool letters; type formatting keys; Pen Auto Add/Delete, #4144) · **Target:** Adobe Photoshop 2026 How PhotoCraft's direct manipulation compares with Photoshop 2026 (27.11.0): the toolbox, the handles and modifier keys of each gesture, nudging, snapping, numeric precision, navigation, @@ -183,6 +183,7 @@ Triangle and Curvature Pen (minus legacy Rounded Rectangle and Targeted Adjustme | Shortcut audit | 214 → 0 failures (2026-10-07) | measured then; not re-run here | | `.kys` import | done (`engine/src/kys.rs`) | | | Shortcut glyphs per platform | done (UI-217-19) | | +| Toolbar tool shortcut editing | done (#4086): each tool has a row under Tools; assignments persist, removed tools leave the default key group, and unchanged tools keep Shift cycling. Toolbar and flyout hints follow the binding | `tool_shortcuts.rs`, `shortcut_capture_tests.rs` | | Brush size/hardness keys on non-US layouts | done (#3109): `[` `]` need AltGr on many layouts, so Photoshop uses other keys there (German: Ö / #, ⇧ for hardness). `layout_keys.rs` has a data table of such layouts (`LAYOUTS`, add rows to support one more) and a fallback for all others: the keys at the US `[` / `]` positions act as `[` / `]` when they don't type brackets. Off once a real bracket is typed; Edit › Keyboard Shortcuts overrides still apply | | | Layer and selection keys: ⌘, toggles visibility, ⌘\ targets the mask, / locks transparency, ⌘⌥2 loads luminosity, ⌘⌥⌫ fills from history, Tab / ⇧Tab rename the next layer, ⌥-click a thumbnail fits the layer | done (2026-10-11) | | | Tool keys: ← / → turn the brush tip (1°, ⇧ 15°), ⇧-click with Type starts new text over old, Space+F / ⇧Space+F cycle the pasteboard colour | done (2026-10-11) | | @@ -224,3 +225,4 @@ Paragraph; the rest open as in-app floating windows. | 2026-10-11 | minor | Spring-loaded tool letters done (#2672): holding any tool letter (Z included) past 300 ms, or using the canvas while it is down, makes the tool temporary until release | | 2026-10-11 | minor | Type formatting keys done: ⇧⌘K, U, B, I and /, ⌥↑/↓, ⇧⌥↑/↓, ⌥←/→ over a selection and ⌥⇧⌘H format the selected type while editing, and no longer reach Color Settings, Desaturate, Auto Color or Inverse | | 2026-10-12 | minor | Pen Auto Add/Delete on the active path, with its options-bar checkbox, hover feedback and + / − cursor badge (#4144) | +| 2026-10-12 | minor | Toolbar tool shortcuts can be reassigned, removed and reset in Keyboard Shortcuts (#4086); capture, restart, group cycling, conflict and text-focus regressions | From f80e57fb8a2e0c24b7a65f4b3787399701d999fc Mon Sep 17 00:00:00 2001 From: Minischatten <61423557+Minischatten@users.noreply.github.com> Date: Tue, 13 Oct 2026 04:16:46 +0200 Subject: [PATCH 06/15] Fix macOS system dialog localization (#4261) * Fix macOS system dialog localization * Info.plist: declare the Hungarian and Turkish localizations too Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Brandon Thomas Co-authored-by: Claude Opus 5.5 --- packaging/macos/Info.plist.in | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/packaging/macos/Info.plist.in b/packaging/macos/Info.plist.in index 5dec67ee2e..3a190a4b17 100644 --- a/packaging/macos/Info.plist.in +++ b/packaging/macos/Info.plist.in @@ -6,6 +6,31 @@ CFBundleDevelopmentRegion en + + CFBundleLocalizations + + en + ja + zh-Hans + zh-Hant + es + ru + uk + cs + fr + id + ko + pl + de + pt-BR + el + nl + it + hu + tr + vi + CFBundleDisplayName PhotoCraft CFBundleName From ee8aca562b4bd4af7afd42d19c5c48c7e1f71573 Mon Sep 17 00:00:00 2001 From: Valentin Klein Date: Tue, 13 Oct 2026 04:23:46 +0200 Subject: [PATCH 07/15] Engine: reject unknown params for layer.hideLayers/showLayers via an opt-in registry check (#4336) (#4364) Co-authored-by: Claude Opus 5.5 --- crates/engine/src/jobs.rs | 1 + crates/engine/src/lib.rs | 1 + crates/engine/src/param_check.rs | 138 +++++++++++++++++++++++++++++++ docs/control-protocol.md | 1 + 4 files changed, 141 insertions(+) create mode 100644 crates/engine/src/param_check.rs diff --git a/crates/engine/src/jobs.rs b/crates/engine/src/jobs.rs index 42c7fa4862..9c8cb9cdd0 100644 --- a/crates/engine/src/jobs.rs +++ b/crates/engine/src/jobs.rs @@ -632,6 +632,7 @@ impl Session { if id == "file.new" { crate::document_preset_cmds::validate_new_params(self, ¶ms)?; } + crate::param_check::check(spec, ¶ms)?; crate::filters::validate_params(id, ¶ms)?; // A floating selection drops before any other command (Undo puts it back instead). if let Some(v) = crate::float_cmds::before_command(self, id)? { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 1cc8eb692b..f1bd9bd16e 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -76,6 +76,7 @@ pub mod multichannel_cmds; pub mod new_layer; pub mod notes_cmds; pub mod paint_cmds; +mod param_check; mod path_edit_cmds; pub mod pattern_cmds; pub mod pattern_fill_cmds; diff --git a/crates/engine/src/param_check.rs b/crates/engine/src/param_check.rs new file mode 100644 index 0000000000..a59236d1d1 --- /dev/null +++ b/crates/engine/src/param_check.rs @@ -0,0 +1,138 @@ +//! Reject params a command does not document (#4336). +//! +//! Commands read the keys they know from a JSON object and used to ignore the rest, so a +//! misspelled key (`{"ids":[4]}` for `{"layer":4}`) ran the command on its defaults and reported +//! success. For the commands in [`STRICT`] the dispatcher now checks the keys against the +//! command's `params` doc once, for every transport (CLI, MCP, control channel, UI, actions). +//! +//! This is opt-in because `params` docs are free-form text and many are not complete yet (the +//! engine's own tests pass undocumented keys to `paint.pencil`, `timeline.create`, +//! `layer.new.artboard`, the Selective Color and Color Lookup adjustments and more). To opt a +//! command in: make sure its `params` doc names every key the command reads as `"key":...`, and +//! add its id to [`STRICT`]; `strict_commands_have_closed_docs` checks the doc is parseable. +//! A doc with a top-level `…` is open-ended and is never checked. + +use serde_json::Value; + +use crate::commands::CommandSpec; +use crate::{EngineError, Result}; + +/// Keys any command accepts: the history-coalescing key every command honours (see +/// `Session::execute`) and the Channels-panel `"target"` that pixel commands follow. +const UNIVERSAL: &[&str] = &["coalesce", "target"]; + +/// The commands whose unknown params are rejected: their `params` doc is complete. +const STRICT: &[&str] = &["layer.hideLayers", "layer.showLayers"]; + +/// The keys a `params` doc names, or `None` when the doc is open-ended. +fn documented_keys(doc: &str) -> Option> { + let bytes = doc.as_bytes(); + let (mut depth, mut in_str, mut start) = (0usize, false, 0usize); + let mut quoted: Vec<(usize, usize)> = Vec::new(); + for (i, &b) in bytes.iter().enumerate() { + if in_str { + if b == b'"' { + in_str = false; + quoted.push((start, i)); + } + continue; + } + match b { + b'"' => { + in_str = true; + start = i + 1; + } + b'{' | b'[' => depth += 1, + b'}' | b']' => depth = depth.saturating_sub(1), + _ => {} + } + // `…` / `...` straight inside the top-level braces: the list is not complete. + if depth == 1 + && (doc.get(i..).is_some_and(|r| r.starts_with('…') || r.starts_with("..."))) + && doc.get(..i).is_some_and(|l| l.trim_start().starts_with('{')) + { + return None; + } + } + let mut keys = Vec::new(); + for (n, &(a, b)) in quoted.iter().enumerate() { + let Some(word) = doc.get(a..b) else { continue }; + if word.is_empty() || !word.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'_') { + continue; + } + // A key is followed by `:`, or by `,"other"` pairs that end in one (`"all","pixels":bool`). + let mut end = b + 1; + let mut k = n; + loop { + let rest = doc.get(end..).unwrap_or(""); + if rest.starts_with(':') { + keys.push(word); + break; + } + let Some(after) = rest.strip_prefix(',') else { break }; + let Some(&(na, nb)) = quoted.get(k + 1) else { break }; + if na != end + 2 || after.as_bytes().first() != Some(&b'"') { + break; + } + end = nb + 1; + k += 1; + } + } + Some(keys) +} + +/// Err when `params` has a key the command does not document (only for commands in [`STRICT`]). +pub(crate) fn check(spec: &CommandSpec, params: &Value) -> Result<()> { + if !STRICT.contains(&spec.id) { + return Ok(()); + } + let Some(map) = params.as_object() else { return Ok(()) }; + let Some(keys) = documented_keys(spec.params) else { return Ok(()) }; + for key in map.keys() { + if UNIVERSAL.contains(&key.as_str()) || keys.contains(&key.as_str()) { + continue; + } + let expected = if keys.is_empty() { "no parameters".to_string() } else { format!("expected: {}", keys.join(", ")) }; + return Err(EngineError::BadParams { cmd: spec.id.to_string(), msg: format!("unknown parameter `{key}` ({expected})") }); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use serde_json::json; + + use super::*; + use crate::Session; + + #[test] + fn documented_keys_reads_keys_and_stops_at_open_docs() { + assert_eq!(documented_keys(r##"{"layer":id?} (shows them instead)"##), Some(vec!["layer"])); + assert_eq!(documented_keys(r##"{"locks":{"all","pixels":bool}?,"name":str?}"##), Some(vec!["locks", "all", "pixels", "name"])); + assert_eq!(documented_keys("{}"), Some(vec![])); + assert_eq!(documented_keys(r##"{"layer":id?, …params of that kind}"##), None); + } + + #[test] + fn strict_commands_have_closed_docs() { + for id in STRICT { + let spec = crate::commands::find(id).expect("strict command exists"); + assert!(documented_keys(spec.params).is_some_and(|k| !k.is_empty()), "{id}: params doc must list its keys"); + } + } + + #[test] + fn unknown_param_is_an_error_naming_the_key_and_the_accepted_ones() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + let a = s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap(); + let visible = |s: &Session| s.active().unwrap().doc.layer(photocraft_doc::LayerId(a)).unwrap().visible; + for cmd in ["layer.hideLayers", "layer.showLayers"] { + let err = s.execute(cmd, json!({"ids": [a]})).unwrap_err().to_string(); + assert!(err.contains("unknown parameter `ids`") && err.contains("expected: layer"), "{err}"); + assert!(visible(&s), "{cmd}: nothing ran"); + } + s.execute("layer.hideLayers", json!({"layer": a, "coalesce": "k"})).unwrap(); + assert!(!visible(&s)); + } +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 166a61210c..e571e94f8b 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -75,6 +75,7 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i - `ui.click {x, y, button?, count?}` / `ui.move {x, y}`: synthetic pointer input in screen points (`button`: `left` (default), `right` (or `secondary`) or `middle`). `count` (default 1, `2` for a double-click) is at most 256; a larger one is an error and queues nothing - `ui.key {key, command?, shift?, alt?, ctrl?}` (flags may also be grouped under `modifiers`): press and release a key, e.g. `{"key": "ArrowLeft", "shift": true}` - `ui.pointer`, `ui.click`, `ui.move`, `ui.key` and `ui.screenshot` validate every parameter before acting, as `ui.set` does: an unknown field (top-level, under `modifiers` or in an event), a value of the wrong JSON type (`"x": "abc"`, `"ctrl": "yes"`), a `button`, `kind`, `tool` or `key` outside the accepted set, or a number outside its range (`pressure`, tilt, `rotation`, `count`) is an error naming the parameter, and nothing is queued or applied. A `null` field counts as omitted and takes its default +- Engine commands (`engine.execute`, `photocraft-cli run`, MCP `command_run`) reject a param key their `params` doc does not name for the commands listed in `STRICT` (`crates/engine/src/param_check.rs`, today `layer.hideLayers` and `layer.showLayers`): `{"ids":[4]}` is the error `unknown parameter \`ids\` (expected: layer)`, and nothing runs. Other commands still ignore unknown keys until their `params` doc is complete and they are added to that list (`coalesce` and `target` are always accepted). - `ui.type {text}`: type text (goes to the focused widget, or to the canvas while the Type tool is editing) - `ui.resize {width, height}`: resize the main window - `ui.gpu.simulateLoss {error?}`: act as if the wgpu device was lost (or reported an error with `error: true`). The app switches to the CPU image compositor for the rest of the session and shows the same recovery warning as on a real loss. `gpuFallbackNotice` in `ui.inspect` contains the reason while the warning is open. Keep Using CPU saves CPU compatibility for the next launch; Retry GPU saves GPU mode and asks the user to save and restart. The window renderer still requires a working graphics or software adapter. Returns `wasActive` and `gpuInfo`. For testing the fallback From 4543ef35b975b2c177ff55b3acd5d92fea12387c Mon Sep 17 00:00:00 2001 From: jonathanwxh-cell Date: Tue, 13 Oct 2026 10:23:50 +0800 Subject: [PATCH 08/15] Preserve signed HDR colors in float text rasterization (#4379) Co-authored-by: jonathnwxh <258340642+jonathanwxh-cell@users.noreply.github.com> --- crates/text/src/render.rs | 7 +++++-- crates/text/src/tests.rs | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 2 deletions(-) diff --git a/crates/text/src/render.rs b/crates/text/src/render.rs index 44165461aa..b50a63fe0a 100644 --- a/crates/text/src/render.rs +++ b/crates/text/src/render.rs @@ -1,6 +1,6 @@ //! Rasterizes a [`TextLayout`] into a document-space [`Surface`] of any pixel format. -use photocraft_color::{Color, PixelFormat}; +use photocraft_color::{Color, PixelFormat, SampleType}; use photocraft_doc::text::AntiAlias; use photocraft_geom::{Affine, Rect}; use photocraft_raster::Surface; @@ -267,7 +267,10 @@ pub fn rasterize_warped(layout: &TextLayout, transform: &Affine, format: PixelFo let a = px[n]; if a > 0.0 { for v in &mut px[..n] { - *v = (*v / a).clamp(0.0, 1.0); + let straight = *v / a; + // Float text can carry HDR and signed colours. Keep integer output bounded + // and retain the old handling of non-finite intermediate values. + *v = if format.sample == SampleType::F32 && straight.is_finite() { straight } else { straight.clamp(0.0, 1.0) }; } } } diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index c21d5c2682..148a84c5e8 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -13,6 +13,44 @@ fn styled(text: &str, style: CharStyle) -> TextLayer { TextLayer { text: text.into(), runs: vec![TextRun { len: text.len(), style }], ..Default::default() } } +#[test] +fn raster_preserves_hdr_and_signed_float_text_colors() { + let mut e = TextEngine::new(); + for alpha in [1.0, 0.4] { + let color = Color::rgba(2.5, -0.25, 0.5, alpha); + let style = CharStyle { size_pt: 48.0, color, ..Default::default() }; + let (_, rendered) = e.render(&styled("HDR", style), 72.0, PixelFormat::RGBA32F); + let pixels = rendered.surface.read_region(rendered.rect); + let mut covered = 0; + for pixel in pixels.as_chunks::<4>().0.iter().filter(|p| p[3] > 0.01) { + covered += 1; + for channel in 0..3 { + assert!((pixel[channel] - color.c[channel]).abs() < 1e-5, "alpha={alpha}, pixel={pixel:?}"); + } + assert!(pixel[3] <= alpha + 1e-6); + } + assert!(covered > 100); + } +} + +#[test] +fn raster_integer_text_colors_stay_bounded() { + let mut e = TextEngine::new(); + for format in [PixelFormat::RGBA8, PixelFormat::RGBA16] { + let style = CharStyle { size_pt: 48.0, color: Color::rgba(2.5, -0.25, 0.5, 0.4), ..Default::default() }; + let (_, rendered) = e.render(&styled("HDR", style), 72.0, format); + let pixels = rendered.surface.read_region(rendered.rect); + let mut covered = 0; + for pixel in pixels.as_chunks::<4>().0.iter().filter(|p| p[3] > 0.01) { + covered += 1; + assert_eq!(&pixel[..2], &[1.0, 0.0]); + assert!((pixel[2] - 0.5).abs() < 1.0 / 255.0); + assert!(pixel[3] <= 0.4 + 1.0 / 255.0); + } + assert!(covered > 100); + } +} + fn with_para(mut t: TextLayer, p: ParagraphStyle) -> TextLayer { t.paragraphs = vec![ParagraphRun { len: t.text.len(), style: p }]; t From 20e8f949f9cb9bf0445721c26319f56872b44fdc Mon Sep 17 00:00:00 2001 From: Valentin Klein Date: Tue, 13 Oct 2026 04:23:55 +0200 Subject: [PATCH 09/15] Type: fall back to installed Indic fonts for document text (#4383) (#4386) * Type: fall back to installed Indic fonts for document text (#4383) Co-Authored-By: Claude Opus 5.5 * docs: regenerate scorecard after merging main Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/text/src/fonts.rs | 42 ++++++++++++++++++++++++++++++- crates/text/src/tests.rs | 53 ++++++++++++++++++++++++++++++++++++++++ docs/scorecard.md | 2 +- scorecard/type.toml | 2 +- 4 files changed, 96 insertions(+), 3 deletions(-) diff --git a/crates/text/src/fonts.rs b/crates/text/src/fonts.rs index 433baee074..54cfeb471b 100644 --- a/crates/text/src/fonts.rs +++ b/crates/text/src/fonts.rs @@ -59,7 +59,7 @@ fn inflate_font(deflated: &[u8]) -> Vec { /// Families tried (if installed) after the requested one, for missing glyphs. The Southeast Asian /// and CJK families ([`THAI_FAMILIES`], [`KHMER_FAMILIES`], [`LAO_FAMILIES`], [`MYANMAR_FAMILIES`], -/// [`crate::cjk::families`]) go between these two lists, in the UI locale's script order. +/// [`INDIC_FAMILIES`], [`crate::cjk::families`]) go between these two lists, in the UI locale's script order. const FALLBACK_CANDIDATES: &[&str] = &["Noto Sans", "Segoe UI", "DejaVu Sans", "Geeza Pro", "Arial Hebrew", "Noto Sans Arabic", "Noto Sans Hebrew"]; /// Thai-capable families: Windows (Leelawadee UI since Windows 8; Tahoma and Leelawadee on /// older systems), macOS (Thonburi, Sukhumvit Set) and Linux (Noto). Text in a font without Thai @@ -76,6 +76,38 @@ pub const LAO_FAMILIES: &[&str] = &["Lao Sangam MN", "Lao MN", "Lao UI", "Noto S /// Myanmar/Burmese-capable families: macOS (Myanmar Sangam MN, Myanmar MN), Windows (Myanmar Text) /// and Linux (Noto). pub const MYANMAR_FAMILIES: &[&str] = &["Myanmar Sangam MN", "Myanmar MN", "Myanmar Text", "Noto Sans Myanmar"]; +/// Indic-script families for document text. Windows has `Nirmala UI` for all nine scripts (from +/// Windows 8); macOS has the Kohinoor and Sangam MN families; Linux has Noto Sans. Indic text in a +/// font without these glyphs had no candidate to fall back to and drew .notdef boxes (#218). +pub const DEVANAGARI_FAMILIES: &[&str] = &["Nirmala UI", "Kohinoor Devanagari", "Devanagari Sangam MN", "Noto Sans Devanagari", "Noto Sans Devanagari UI"]; +/// Bengali-capable families (see [`DEVANAGARI_FAMILIES`]). +pub const BENGALI_FAMILIES: &[&str] = &["Nirmala UI", "Kohinoor Bangla", "Bangla Sangam MN", "Noto Sans Bengali", "Noto Sans Bengali UI"]; +/// Gurmukhi-capable families (see [`DEVANAGARI_FAMILIES`]). +pub const GURMUKHI_FAMILIES: &[&str] = &["Nirmala UI", "Gurmukhi Sangam MN", "Noto Sans Gurmukhi", "Noto Sans Gurmukhi UI"]; +/// Gujarati-capable families (see [`DEVANAGARI_FAMILIES`]). +pub const GUJARATI_FAMILIES: &[&str] = &["Nirmala UI", "Kohinoor Gujarati", "Gujarati Sangam MN", "Noto Sans Gujarati", "Noto Sans Gujarati UI"]; +/// Tamil-capable families (see [`DEVANAGARI_FAMILIES`]). +pub const TAMIL_FAMILIES: &[&str] = &["Nirmala UI", "Tamil Sangam MN", "Noto Sans Tamil", "Noto Sans Tamil UI"]; +/// Telugu-capable families (see [`DEVANAGARI_FAMILIES`]). +pub const TELUGU_FAMILIES: &[&str] = &["Nirmala UI", "Kohinoor Telugu", "Telugu Sangam MN", "Noto Sans Telugu", "Noto Sans Telugu UI"]; +/// Kannada-capable families (see [`DEVANAGARI_FAMILIES`]). +pub const KANNADA_FAMILIES: &[&str] = &["Nirmala UI", "Kannada Sangam MN", "Noto Sans Kannada", "Noto Sans Kannada UI"]; +/// Malayalam-capable families (see [`DEVANAGARI_FAMILIES`]). +pub const MALAYALAM_FAMILIES: &[&str] = &["Nirmala UI", "Malayalam Sangam MN", "Noto Sans Malayalam", "Noto Sans Malayalam UI"]; +/// Sinhala-capable families (see [`DEVANAGARI_FAMILIES`]). +pub const SINHALA_FAMILIES: &[&str] = &["Nirmala UI", "Sinhala Sangam MN", "Noto Sans Sinhala", "Noto Sans Sinhala UI"]; +/// All Indic-script families, in the order they join the fallback candidates. +pub const INDIC_FAMILIES: &[&[&str]] = &[ + DEVANAGARI_FAMILIES, + BENGALI_FAMILIES, + GURMUKHI_FAMILIES, + GUJARATI_FAMILIES, + TAMIL_FAMILIES, + TELUGU_FAMILIES, + KANNADA_FAMILIES, + MALAYALAM_FAMILIES, + SINHALA_FAMILIES, +]; /// Broad-coverage and emoji fonts, tried after the CJK script fonts so shared Han characters get /// the locale's forms instead of Arial Unicode's. const FALLBACK_LAST: &[&str] = &["Arial Unicode MS", "Apple Color Emoji", "Segoe UI Emoji", "Noto Color Emoji"]; @@ -87,6 +119,14 @@ pub fn fallback_candidates(order: &[crate::cjk::CjkScript; 4]) -> Vec<&'static s v.extend_from_slice(KHMER_FAMILIES); v.extend_from_slice(LAO_FAMILIES); v.extend_from_slice(MYANMAR_FAMILIES); + for fams in INDIC_FAMILIES { + for f in *fams { + // Nirmala UI covers all nine scripts and is listed by each; probe it once. + if !v.contains(f) { + v.push(f); + } + } + } for s in order { // craft-fonts' Japanese fonts (if built in) go ahead of the installed Japanese fonts, in // the Japanese slot of the locale order, so shared Han keeps the locale's forms. diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index 148a84c5e8..832f0f0d85 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -1655,6 +1655,59 @@ fn southeast_asian_fallback_candidates_cover_every_platform() { } } +/// The Indic scripts of document text, with conjuncts, matras and viramas (#218). +const INDIC: &[(&str, &str, &[&str])] = &[ + ("Devanagari", "हिन्दी भाषा क्षत्रिय श्री", fonts::DEVANAGARI_FAMILIES), + ("Bengali", "বাংলা ভাষা ক্ষত্রিয় শ্রী", fonts::BENGALI_FAMILIES), + ("Gurmukhi", "ਪੰਜਾਬੀ ਭਾਸ਼ਾ ਸਤਿ ਸ੍ਰੀ", fonts::GURMUKHI_FAMILIES), + ("Gujarati", "ગુજરાતી ભાષા ક્ષત્રિય શ્રી", fonts::GUJARATI_FAMILIES), + ("Tamil", "தமிழ் மொழி ஸ்ரீ கொடை", fonts::TAMIL_FAMILIES), + ("Telugu", "తెలుగు భాష క్షత్రియ శ్రీ", fonts::TELUGU_FAMILIES), + ("Kannada", "ಕನ್ನಡ ಭಾಷೆ ಕ್ಷತ್ರಿಯ ಶ್ರೀ", fonts::KANNADA_FAMILIES), + ("Malayalam", "മലയാളം ഭാഷ ക്ഷത്രിയ ശ്രീ", fonts::MALAYALAM_FAMILIES), + ("Sinhala", "සිංහල භාෂාව ක්‍ෂත්‍රිය ශ්‍රී", fonts::SINHALA_FAMILIES), +]; + +#[test] +fn indic_scripts_fall_back_to_installed_fonts() { + for (name, sample, families) in INDIC { + let mut e = TextEngine::with_system_fonts(); + let Some(hit) = families.iter().find(|f| e.fonts.has_family(f)) else { + eprintln!("skipped: no {name}-capable font installed"); + continue; + }; + let direct = TextLayer { text: (*sample).into(), font_family: hit.to_string(), size_pt: 24.0, ..Default::default() }; + let l = e.layout(&direct, 72.0); + assert!(!l.glyphs.is_empty() && l.glyphs.iter().all(|g| g.id != 0), "{hit} is installed but shapes .notdef for {name}"); + let mixed = format!("Latin {sample}"); + let l = e.layout(&point(&mixed, 24.0), 72.0); + assert!(l.glyphs.iter().all(|g| g.id != 0), "{name} in a Latin font drawn with .notdef although {hit} is installed"); + let latin = l.glyphs.first().map(|g| g.face); + assert!(l.glyphs.iter().any(|g| Some(g.face) != latin), "Latin and {name} drawn with the same face"); + } +} + +#[test] +fn indic_fallback_candidates_cover_every_platform() { + // Logic-level half (runs without these fonts): every script has a Windows, macOS and Linux + // family in the candidates, ahead of the broad last-resort fonts; the shared Nirmala UI is + // probed once. + for order in [crate::cjk::script_order(None), crate::cjk::script_order(Some("ja"))] { + let fb = fonts::fallback_candidates(&order); + let last = fb.iter().position(|f| *f == "Arial Unicode MS").unwrap(); + assert_eq!(fb.iter().filter(|f| **f == "Nirmala UI").count(), 1, "{fb:?}"); + for (name, _, families) in INDIC { + assert!(families.contains(&"Nirmala UI"), "{name}"); + assert!(families.iter().any(|f| f.ends_with("Sangam MN") || f.starts_with("Kohinoor")), "{name}: no macOS family"); + assert!(families.iter().any(|f| f.starts_with("Noto Sans ")), "{name}: no Linux family"); + for fam in *families { + let i = fb.iter().position(|f| f == fam).unwrap_or_else(|| panic!("{fam} missing from {fb:?}")); + assert!(i < last, "{fam} after the last-resort fonts"); + } + } + } +} + #[test] fn a_served_script_fallback_joins_the_fallback_stack_once_it_arrives() { let Some(cairo) = crate::CRAFT_FONTS.iter().find(|f| f.family == "Cairo") else { diff --git a/docs/scorecard.md b/docs/scorecard.md index 712a17b611..db11f4050b 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -212,7 +212,7 @@ Unread: `general.color_picker`, `general.animated_zoom`, `general.zoom_resizes_w |---|---|---|---|---| | TYPE-218-1 | Type on a path: path shape, glyphs along the curve, caret follows, PSD round trip | missing | [#218](https://github.com/storytold/photocraft/issues/218) | doc text.rs:209 TextShape has Point and Box only | | TYPE-218-2 | Paragraph direction (Auto/LTR/RTL) in the panel and options bar; visual RTL caret | missing | [#218](https://github.com/storytold/photocraft/issues/218) | Engine has TextDirection (text.rs:155); no UI | -| TYPE-218-3 | Thai/Khmer/Indic fallback fonts; golden shaping tests for complex scripts and RTL | partial | [#218](https://github.com/storytold/photocraft/issues/218) | Thai is covered: THAI_FAMILIES (fonts.rs) lists the Windows, macOS and Linux families and thai_in_latin_font_falls_back_to_installed_thai_font checks a sample with above and below marks (#1909); Arabic and Hebrew fall back too. Khmer and Indic have no fallback list, and there are no per-script golden shaping tests (only a bidi test) | +| TYPE-218-3 | Thai/Khmer/Indic fallback fonts; golden shaping tests for complex scripts and RTL | partial | [#218](https://github.com/storytold/photocraft/issues/218) | Fallback fonts are covered for Thai, Khmer, Lao, Myanmar (THAI_FAMILIES, KHMER_FAMILIES, LAO_FAMILIES, MYANMAR_FAMILIES in fonts.rs; #1909, #3259), the nine Indic scripts (INDIC_FAMILIES: Nirmala UI, Kohinoor and Sangam MN, Noto Sans) and Arabic and Hebrew. Still missing: per-script golden shaping tests against reference output (only smoke tests that an installed font shapes without .notdef, plus a bidi test) | | TYPE-218-4 | Variable font axis sliders from the font's axes; opsz follows the point size | done | [#218](https://github.com/storytold/photocraft/issues/218) | One slider per axis of the style's font in the Character section (Properties and Window > Character), setting type.setStyle variations; opsz follows the type size unless set (layout.rs variation_list); a style or weight resets the wght axis (#2985). PSD does not round-trip axis values yet | | TYPE-218-5 | OpenType UI: Character panel buttons, Numerals and Stylistic Sets submenus | partial | [#218](https://github.com/storytold/photocraft/issues/218) | Type > OpenType toggles (type_extra_cmds.rs:512). Character panel (and the Properties Character section) has Photoshop's eight OpenType buttons: Standard Ligatures, Contextual Alternates, Discretionary Ligatures, Swash, Stylistic Alternates, Titling Alternates, Ordinals, Fractions, pressed while the feature is on at the selection and dispatching the type.openType.* commands (type_tool.rs opentype_row; character_panel_opentype_buttons_toggle_and_show_the_feature, #3752). Still missing: the Numerals and Stylistic Sets submenus, and greying out features the font lacks | | TYPE-218-6 | Manual pair kerning (Alt+arrows), optical kerning rendered, both round-trip PSD (#206) | done | [#218](https://github.com/storytold/photocraft/issues/218) | Alt+Left/Right at a collapsed caret kerns the pair (type_tool.rs kern_pair, 20 per step and 100 with Cmd; type_tool_alt_arrows_kern_the_pair). Optical kerning is computed from the glyph outlines in text/src/optical.rs and applied by layout.rs when the run's mode is Optical (optical_matches_photoshop, optical_kerning_tightens_open_pairs). Both modes and manual values round-trip through PSD (io/tests/psd_kerning.rs; the optical mode travels in Txt2, txt2_carries_optical_kerning) | diff --git a/scorecard/type.toml b/scorecard/type.toml index 81064ce8d3..078c956a3f 100644 --- a/scorecard/type.toml +++ b/scorecard/type.toml @@ -23,7 +23,7 @@ id = "TYPE-218-3" target = "Thai/Khmer/Indic fallback fonts; golden shaping tests for complex scripts and RTL" status = "partial" issue = 218 -note = "Thai is covered: THAI_FAMILIES (fonts.rs) lists the Windows, macOS and Linux families and thai_in_latin_font_falls_back_to_installed_thai_font checks a sample with above and below marks (#1909); Arabic and Hebrew fall back too. Khmer and Indic have no fallback list, and there are no per-script golden shaping tests (only a bidi test)" +note = "Fallback fonts are covered for Thai, Khmer, Lao, Myanmar (THAI_FAMILIES, KHMER_FAMILIES, LAO_FAMILIES, MYANMAR_FAMILIES in fonts.rs; #1909, #3259), the nine Indic scripts (INDIC_FAMILIES: Nirmala UI, Kohinoor and Sangam MN, Noto Sans) and Arabic and Hebrew. Still missing: per-script golden shaping tests against reference output (only smoke tests that an installed font shapes without .notdef, plus a bidi test)" [[item]] id = "TYPE-218-4" From 88f84aab59b2bf4b2acd959129600bedddbb1a77 Mon Sep 17 00:00:00 2001 From: Marco Arnulfo <103679419+marcoarnulfo@users.noreply.github.com> Date: Tue, 13 Oct 2026 04:23:59 +0200 Subject: [PATCH 10/15] Raw: treat DNG samples piled up below the stated white level as clipped (fixes #4348) (#4389) Some DNG writers state a white level the sensor never reaches (an iPhone 15 Pro Max Bayer DNG states 4095 and clips at 3567). Development clips each channel at 1 after white balance, so red and blue reached 1 while green stayed at 0.85 and blown highlights turned magenta. On decode, a per-colour pile-up clearly below the white level is now raised to it, as in storytold/lightcraft#586. --- crates/raw/src/lib.rs | 10 +- crates/raw/src/saturation.rs | 265 +++++++++++++++++++++++++++++++++++ crates/raw/tests/dng.rs | 25 ++++ 3 files changed, 299 insertions(+), 1 deletion(-) create mode 100644 crates/raw/src/saturation.rs diff --git a/crates/raw/src/lib.rs b/crates/raw/src/lib.rs index dc1805d478..d5a3e987c7 100644 --- a/crates/raw/src/lib.rs +++ b/crates/raw/src/lib.rs @@ -60,6 +60,7 @@ mod par; mod preview; mod raf; mod rw2; +mod saturation; mod sensor; mod sony; mod tiff; @@ -230,7 +231,7 @@ pub fn decode(bytes: &[u8], limits: &Limits) -> Result { _ => { let t = Tiff::new(bytes).ok_or(RawError::NotRaw)?; match format { - RawFormat::Dng => dng::decode(&t, limits), + RawFormat::Dng => dng::decode(&t, limits).map(lift_clipped), RawFormat::Cr2 => cr2::decode(&t, limits), RawFormat::Rw2 => rw2::decode(&t, limits), RawFormat::Orf => orf::decode(&t, limits), @@ -240,6 +241,13 @@ pub fn decode(bytes: &[u8], limits: &Limits) -> Result { } } +/// DNG writers can state a white level the sensor never reaches; samples stuck at the real saturation +/// point are raised to it so they clip together (see `saturation.rs`). +fn lift_clipped(mut s: Sensor) -> Sensor { + s.lift_clipped_samples(); + s +} + /// Decodes a lossless JPEG (T.81 process 14) stream into `(width, height, /// components, samples)`; at most `max_samples` samples are allocated. /// Exposed for fuzzing and tools. diff --git a/crates/raw/src/saturation.rs b/crates/raw/src/saturation.rs new file mode 100644 index 0000000000..a36692a3f6 --- /dev/null +++ b/crates/raw/src/saturation.rs @@ -0,0 +1,265 @@ +//! Sensors that clip below the stated white level. +//! +//! A DNG's `WhiteLevel` is what the writer says the samples top out at, not always where the sensor +//! really saturates: a camera app can state 4095 for 12-bit data that piles up at 3567 (85 % of the +//! range above black, storytold/photocraft#4348, as storytold/lightcraft#548). Development clips each +//! channel at 1 after white balance, so samples stuck 15 % below the white level are not clipped +//! together: red and blue (multiplied by more than green) reach 1, green stays at 0.85, and blown +//! highlights turn magenta. +//! +//! [`Sensor::lift_clipped_samples`] finds the real saturation point of each colour from the samples +//! (a pile-up of identical values near the top of the range) and raises the samples at or above it to +//! the stated white level. Unclipped samples keep their values, and a file whose data reaches its white +//! level, or has no pile-up, is left alone. Same detector as storytold/lightcraft#586. + +use crate::sensor::Sensor; + +/// A saturation plateau must hold at least this share of its colour's samples (and 100 of them), as +/// many must lie below it (a scene, not a flat field)... +const MIN_SHARE: f64 = 1e-4; +/// ...be at least this many times as populated as the average value just below it... +const MIN_SPIKE: f64 = 16.0; +/// ...and have next to nothing above it (a real clip point is the top of the data; a popular value in +/// the middle of sparse or curve-coded data has plenty of samples above): at most this share of the +/// plateau lies more than `ABOVE_MARGIN` of the range over it (noise spilling past the plateau). +const MAX_ABOVE: f64 = 0.02; +const ABOVE_MARGIN: f32 = 0.01; +/// Plateaus within this share of the range from the white level are the white level (no lift needed). +const NEAR_WHITE: f32 = 0.03; +/// How far below the plateau the "average value just below it" reaches. +const NEIGHBOURHOOD: usize = 64; + +impl Sensor { + /// The value each colour's samples saturate at, when that is clearly below the stated white level + /// (see the module docs). Only CFA data without a linearization table is examined: with a table the + /// stored values are not on the white level's scale. + pub(crate) fn saturation_points(&self) -> [Option; 3] { + let none = [None; 3]; + let Some(cfa) = &self.cfa else { return none }; + if self.samples != 1 || self.linearization.is_some() || self.width.checked_mul(self.height) != Some(self.data.len()) { + return none; + } + let white = self.white[0]; + let black = if self.black.values.is_empty() { 0.0 } else { self.black.values.iter().sum::() / self.black.values.len() as f32 }; + // a hostile file can state any levels: NaN, negative or inverted ones are left alone + if !(black.is_finite() && white.is_finite() && black >= 0.0 && white > black && white <= 65535.0) { + return none; + } + let a = self.active; + let fits = |start: usize, len: usize, max: usize| start.checked_add(len).is_some_and(|end| end <= max); + if !fits(a.x, a.width, self.width) || !fits(a.y, a.height, self.height) { + return none; + } + let lo = (black + 0.5 * (white - black)).ceil() as usize; + let hi = white as usize; + if lo + NEIGHBOURHOOD >= hi { + return none; + } + let mut hist = vec![[0u32; 3]; 65536]; + let mut total = [0u64; 3]; + for y in a.y..a.y + a.height { + let row = &self.data[y * self.width + a.x..][..a.width]; + for (x, &v) in (a.x..).zip(row) { + let c = usize::from(cfa.color(x, y)).min(2); + total[c] += 1; + hist[usize::from(v)][c] += 1; + } + } + let mut out = none; + for c in 0..3 { + // the most populated value of the upper half of the range + let Some((v, n)) = (lo..hi).map(|v| (v, hist[v][c])).max_by_key(|&(v, n)| (n, v)) else { continue }; + let min_n = (total[c] as f64 * MIN_SHARE).max(100.0); + if f64::from(n) < min_n || v as f32 >= white - NEAR_WHITE * (white - black) { + continue; + } + // a colour whose samples all sit on one value is a flat field, not a scene that clipped + let darker: u64 = hist[..v].iter().map(|h| u64::from(h[c])).sum(); + if (darker as f64) < min_n { + continue; + } + let below: u64 = (v.saturating_sub(NEIGHBOURHOOD)..v).map(|u| u64::from(hist[u][c])).sum(); + let from = (v + ((ABOVE_MARGIN * (white - black)) as usize).max(1) + 1).min(hist.len()); + let above: u64 = hist[from..].iter().map(|h| u64::from(h[c])).sum(); + if f64::from(n) >= MIN_SPIKE * (below as f64 / NEIGHBOURHOOD as f64).max(1.0) && above as f64 <= MAX_ABOVE * f64::from(n) { + out[c] = u16::try_from(v).ok(); + } + } + out + } + + /// Raises samples at or above their colour's real saturation point ([`Self::saturation_points`]) to + /// the stated white level, so development clips them together. Returns how many samples changed + /// (0: the data is untouched). + pub(crate) fn lift_clipped_samples(&mut self) -> usize { + let points = self.saturation_points(); + if points.iter().all(Option::is_none) { + return 0; + } + let Some(cfa) = self.cfa.clone() else { return 0 }; + let (a, w) = (self.active, self.width); + // the white level itself, rounded up: (white - black) / (white - black) is exactly 1 + let white = self.white[0].ceil() as u16; + let mut changed = 0; + for y in a.y..a.y + a.height { + let row = &mut self.data[y * w + a.x..][..a.width]; + for (x, v) in (a.x..).zip(row.iter_mut()) { + if let Some(p) = points[usize::from(cfa.color(x, y)).min(2)] + && *v >= p + && *v < white + { + *v = white; + changed += 1; + } + } + } + changed + } +} + +#[cfg(test)] +mod tests { + use crate::*; + + /// A 64 x 64 RGGB mosaic with a gradient, black 528, white `white`, whose samples above `clip` (when + /// given) are stuck at `clip` like a sensor that saturates early. + fn sensor_with(clip: Option, white: f32) -> Sensor { + let data = (0..64 * 64) + .map(|i| { + let v = 528 + ((i % 64) * 60 + (i / 64) * 7) as u16 % 4000; + clip.map_or(v, |c| v.min(c)) + }) + .collect(); + Sensor { + format: RawFormat::Dng, + make: None, + model: None, + width: 64, + height: 64, + samples: 1, + data, + cfa: Cfa::bayer("RGGB"), + linearization: None, + black: BlackLevels::uniform(528.0), + white: [white; 3], + active: Rect::new(0, 0, 64, 64), + crop: Rect::new(0, 0, 64, 64), + color: ColorInfo::default(), + camera_wb: None, + orientation: 1, + baseline_exposure: 0.0, + gain_maps: Vec::new(), + tone_curve: Vec::new(), + black_point: 0.0, + warnings: Vec::new(), + } + } + + /// The gradient of `sensor_with`, wrapped so it never gets near the top of the range. + fn without_top(s: &mut Sensor) { + for v in s.data.iter_mut() { + *v = 528 + (*v - 528) % 3000; + } + } + + #[test] + fn a_pile_up_below_the_white_level_is_found_and_lifted() { + let mut s = sensor_with(Some(3567), 4095.0); + assert_eq!(s.saturation_points(), [Some(3567); 3]); + let before = s.data.clone(); + assert!(s.lift_clipped_samples() > 100); + for (x, y) in before.iter().zip(&s.data) { + // plateau samples go to the white level, everything else is untouched + assert_eq!(*y, if *x >= 3567 { 4095 } else { *x }); + } + assert_eq!(s.lift_clipped_samples(), 0, "idempotent"); + } + + #[test] + fn data_that_reaches_its_white_level_is_left_alone() { + let mut s = sensor_with(Some(4095), 4095.0); + let before = s.data.clone(); + assert_eq!(s.saturation_points(), [None; 3]); + assert_eq!(s.lift_clipped_samples(), 0); + assert_eq!(s.data, before); + } + + #[test] + fn data_without_a_pile_up_is_left_alone() { + let mut s = sensor_with(None, 4095.0); + without_top(&mut s); + let before = s.data.clone(); + assert_eq!(s.saturation_points(), [None; 3]); + assert_eq!(s.lift_clipped_samples(), 0); + assert_eq!(s.data, before); + } + + /// Sparse or curve-coded data has popular values with plenty of samples above them: not a clip point. + #[test] + fn a_popular_value_with_data_above_it_is_not_a_clip_point() { + let mut s = sensor_with(None, 4095.0); + without_top(&mut s); + for (i, v) in s.data.iter_mut().enumerate() { + // a third of the samples sit on one code in the upper half, a few hundred are brighter + if i % 3 == 0 { + *v = 3000; + } else if i % 11 == 0 { + *v = 3000 + (i % 700) as u16 + 1; + } + } + assert_eq!(s.saturation_points(), [None; 3]); + assert_eq!(s.lift_clipped_samples(), 0); + } + + /// A uniform patch (a flat-field test frame) has nothing darker: not a scene that clipped. + #[test] + fn a_flat_field_is_not_a_clip_point() { + let mut s = sensor_with(None, 4095.0); + s.data.fill(3000); + assert_eq!(s.saturation_points(), [None; 3]); + assert_eq!(s.lift_clipped_samples(), 0); + } + + #[test] + fn a_few_stuck_samples_are_not_a_plateau() { + let mut s = sensor_with(None, 4095.0); + without_top(&mut s); + for v in s.data.iter_mut().take(20) { + *v = 3800; + } + assert_eq!(s.saturation_points(), [None; 3]); + } + + /// With a linearization table the stored codes are not on the white level's scale. + #[test] + fn linearized_data_is_left_alone() { + let mut s = sensor_with(Some(3567), 4095.0); + s.linearization = Some((0..4096).collect()); + assert_eq!(s.saturation_points(), [None; 3]); + assert_eq!(s.lift_clipped_samples(), 0); + } + + #[test] + fn hostile_levels_are_left_alone() { + for black in [-5000.0, f32::NAN] { + let mut s = sensor_with(Some(40), 4095.0); + s.black = BlackLevels::uniform(black); + assert_eq!(s.saturation_points(), [None; 3]); + assert_eq!(s.lift_clipped_samples(), 0); + } + for white in [f32::NAN, f32::INFINITY, 1e9, 100.0] { + let mut s = sensor_with(Some(3567), 4095.0); + s.white = [white; 3]; + assert_eq!(s.saturation_points(), [None; 3], "{white}"); + } + // an active area that runs past the data (or overflows when added up) is refused + let mut s = sensor_with(Some(3567), 4095.0); + s.active = Rect::new(usize::MAX, 0, 2, 64); + assert_eq!(s.saturation_points(), [None; 3]); + s.active = Rect::new(0, 0, 64, 65); + assert_eq!(s.lift_clipped_samples(), 0); + let mut s = sensor_with(Some(3567), 4095.0); + s.data.pop(); + assert_eq!(s.lift_clipped_samples(), 0); + } +} diff --git a/crates/raw/tests/dng.rs b/crates/raw/tests/dng.rs index 9dfab5dfd7..e13fb920dd 100644 --- a/crates/raw/tests/dng.rs +++ b/crates/raw/tests/dng.rs @@ -425,6 +425,31 @@ fn highlights_clip_to_white_and_exposure_applies() { assert!((lin(up) / lin(base) - 2.0).abs() < 0.02, "{} vs {}", lin(up), lin(base)); } +/// storytold/photocraft#4348 (as storytold/lightcraft#548): a 12-bit DNG that states WhiteLevel 4095 +/// but whose sensor saturates at 3567 in every colour. Under the camera's white balance (red x2.46, +/// blue x1.59) the stuck red and blue samples clip at 1 while green stays at 0.85, so a blown wall +/// rendered magenta. The wall must come out neutral, and the unclipped ramp beside it unchanged. +#[test] +fn highlights_that_clip_below_the_stated_white_level_stay_neutral() { + let (w, h) = (64, 32); + let data: Vec = (0..w * h).map(|i| if i % w < w / 2 { 528 + ((i % w) * 90 + (i / w) * 3) as u16 } else { 3567 }).collect(); + let mut spec = DngSpec::cfa(w, h, data.clone()); + spec.bits = 12; + spec.black = vec![528]; + spec.white = 4095; + spec.as_shot_neutral = Some([1.0 / 2.46, 1.0, 1.0 / 1.59]); + let b = spec.build(); + let d = develop(&b, &DevelopOptions::default()).unwrap(); + let px = &d.rgb[(16 * w + 48) * 3..(16 * w + 48) * 3 + 3]; + let lin = |v: u16| (f64::from(v) / 65535.0).powf(1.8); + let tint = (lin(px[0]) / lin(px[1]) - 1.0).abs().max((lin(px[2]) / lin(px[1]) - 1.0).abs()); + assert!(tint < 0.01, "the clipped wall is tinted: {px:?}"); + let s = sensor(&b); + for (i, (&got, &was)) in s.data.iter().zip(&data).enumerate() { + assert_eq!(got, if was == 3567 { 4095 } else { was }, "sample {i}"); + } +} + #[test] fn gain_map_opcode_is_applied() { // Uniform 0.25 grey; a gain map that doubles everything over the whole image. From 5aa6e33adf03b42620341178aa16b18679d5f633 Mon Sep 17 00:00:00 2001 From: Valentin Klein Date: Tue, 13 Oct 2026 04:24:03 +0200 Subject: [PATCH 11/15] Content-Aware Move: live preview of the result (#4385) (#4393) * Content-Aware Move: live preview of the result while the pointer rests (#4385) A cancellable, debounced background job shows the move/extend result during the drag and in the Transform On Drop box. Co-Authored-By: Claude Opus 5.5 * docs: regenerate scorecard after merging main Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/engine/src/retouch_cmds.rs | 1 + .../src/retouch_cmds/content_aware_move.rs | 58 +++- crates/engine/src/retouch_cmds/tests.rs | 25 ++ crates/ui-egui/src/cam_preview.rs | 285 ++++++++++++++++++ crates/ui-egui/src/cam_transform.rs | 18 +- crates/ui-egui/src/canvas.rs | 7 +- crates/ui-egui/src/lib.rs | 4 + docs/scorecard.md | 2 +- scorecard/tools.toml | 2 +- 9 files changed, 386 insertions(+), 16 deletions(-) create mode 100644 crates/ui-egui/src/cam_preview.rs diff --git a/crates/engine/src/retouch_cmds.rs b/crates/engine/src/retouch_cmds.rs index cba7a22976..315a8d3929 100644 --- a/crates/engine/src/retouch_cmds.rs +++ b/crates/engine/src/retouch_cmds.rs @@ -27,6 +27,7 @@ mod content_aware_move; mod patch; mod pattern_stamp; mod remove; +pub use content_aware_move::{ContentAwarePreview, preview as content_aware_move_preview}; pub use patch::preview as patch_preview; fn bad(cmd: &str, msg: impl Into) -> EngineError { diff --git a/crates/engine/src/retouch_cmds/content_aware_move.rs b/crates/engine/src/retouch_cmds/content_aware_move.rs index 120c8b7c02..ddca9c6e0f 100644 --- a/crates/engine/src/retouch_cmds/content_aware_move.rs +++ b/crates/engine/src/retouch_cmds/content_aware_move.rs @@ -96,6 +96,8 @@ struct Plan { mode: Mode, structure: u8, color: u8, + /// Most pixels the fills may sample around the content ([`MAX_MARGIN`], less for a preview). + margin: i32, } /// Transform On Drop's `scaleX` / `scaleY` (%) and `rotate` (degrees): the map from a source point @@ -193,7 +195,7 @@ fn landed_mask(cov: &[f32], area: Rect, inv: &Homography, rect: Rect) -> Vec Result { +fn plan(s: &Session, p: &Value, margin: i32) -> Result { let mode = match string(p, "mode", "move") { "move" => Mode::Move, "extend" => Mode::Extend, @@ -242,7 +244,7 @@ fn plan(s: &Session, p: &Value) -> Result { } }; let all_layers = flag(p, "sampleAllLayers", false) && targets_pixels(p); - Ok(Plan { target: Target { id, all_layers }, canvas, area, offset: (dx, dy), map, dest, mode, structure, color }) + Ok(Plan { target: Target { id, all_layers }, canvas, area, offset: (dx, dy), map, dest, mode, structure, color, margin }) } /// Width in pixels of the edge band re-synthesised at the new place, for Structure 1..7 and content @@ -293,7 +295,12 @@ fn erode(w: usize, h: usize, m: &[bool], r: usize) -> Vec { /// Where a fill samples from around `r`: Photoshop's Content-Aware window /// ([`crate::fill_cmds::sampling_window`]), at most [`MAX_MARGIN`] pixels around `r`. pub(super) fn window(r: Rect, canvas: Rect) -> Rect { - crate::fill_cmds::sampling_window(r, canvas).intersect(&r.inflate(MAX_MARGIN)) + window_within(r, canvas, MAX_MARGIN) +} + +/// [`window`] with at most `margin` pixels around `r`. +fn window_within(r: Rect, canvas: Rect, margin: i32) -> Rect { + crate::fill_cmds::sampling_window(r, canvas).intersect(&r.inflate(margin)) } /// The pixels a step works on: the targeted surface, or with Sample All Layers the visible @@ -433,7 +440,7 @@ fn run_move(doc: &mut Document, sel: &Surface, plan: &Plan, p: &Value, ctx: &cra // 1. The content at its new place: the content with its original surroundings laid over the // window there; never sampling the content's old place. - let win = window(plan.dest, plan.canvas); + let win = window_within(plan.dest, plan.canvas, plan.margin); let (content, moved) = match &inv { None => { let mut content = read(doc, plan.target, p, win.translate(-dx, -dy))?; @@ -443,7 +450,7 @@ fn run_move(doc: &mut Document, sel: &Surface, plan: &Plan, p: &Value, ctx: &cra Some(inv) => { // Only the content and a ring around it (the colour fit's reference) matter: read // the source behind that, a few pixels past the area, and resample it. - let src = mapped_bounds(inv, plan.dest.inflate(8)).intersect(&plan.area.inflate(MAX_MARGIN)).intersect(&plan.canvas); + let src = mapped_bounds(inv, plan.dest.inflate(8)).intersect(&plan.area.inflate(plan.margin)).intersect(&plan.canvas); let src = if src.is_empty() { plan.area } else { src }; (resample(&read(doc, plan.target, p, src)?, inv, win), landed_mask(&cov, plan.area, inv, win)) } @@ -454,7 +461,7 @@ fn run_move(doc: &mut Document, sel: &Surface, plan: &Plan, p: &Value, ctx: &cra // 2. Move: fill the place the content left (where the content didn't land on it). if plan.mode == Mode::Move { ctx.check()?; - let win = window(plan.area, plan.canvas); + let win = window_within(plan.area, plan.canvas, plan.margin); let (w, h) = (win.width() as usize, win.height() as usize); let img = read(doc, plan.target, p, win)?; let landed = match &inv { @@ -478,7 +485,7 @@ fn run_move(doc: &mut Document, sel: &Surface, plan: &Plan, p: &Value, ctx: &cra } pub(super) fn content_aware_move(s: &mut Session, p: &Value) -> Result { - let plan = plan(s, p)?; + let plan = plan(s, p, MAX_MARGIN)?; let label = if plan.mode == Mode::Move { "Content-Aware Move" } else { "Content-Aware Extend" }; let d = s.active().ok_or(EngineError::NoDocument)?; let doc = d.doc.clone(); @@ -520,3 +527,40 @@ pub(super) fn content_aware_move(s: &mut Session, p: &Value) -> Result { }, ) } + +/// Largest selection (bounding box, in pixels) the live preview computes. +const PREVIEW_MAX_PIXELS: u64 = 256 * 256; +/// Sampling margin of a preview: a fraction of the command's, so a preview is a small solve. +const PREVIEW_MARGIN: i32 = 48; + +/// A live preview of `paint.contentAwareMove` that can run on any thread: the document as of +/// [`preview`], with the move's params. Cheaper than the command (a small sampling margin, and +/// only small selections), so the result is close to, not the same as, what the command makes. +pub struct ContentAwarePreview { + doc: std::sync::Arc, + plan: Plan, + params: Value, +} + +impl ContentAwarePreview { + /// The active document with the move applied (nothing is recorded, the session is not + /// touched) and the rectangle it changed. Stops with `Cancelled` once `ctx` is cancelled. + pub fn run(&self, ctx: &crate::jobs::JobCtx) -> Result<(Document, Rect)> { + let mut work = (*self.doc).clone(); + let sel = self.doc.selection.as_ref().ok_or_else(|| bad(CMD, "select the area to move first"))?; + let (_, damage, _) = run_move(&mut work, sel, &self.plan, &self.params, ctx, "Content-Aware Move preview")?; + Ok((work, damage)) + } +} + +/// Prepare the preview of `paint.contentAwareMove` with params `p` on the active document. Errors +/// like the command does, and for a selection larger than a preview takes. +pub fn preview(s: &Session, p: &Value) -> Result { + let plan = plan(s, p, PREVIEW_MARGIN)?; + let pixels = u64::from(plan.area.width()) * u64::from(plan.area.height()); + if pixels > PREVIEW_MAX_PIXELS { + return Err(bad(CMD, format!("the selection is too large to preview ({pixels} pixels, at most {PREVIEW_MAX_PIXELS})"))); + } + let d = s.active().ok_or(EngineError::NoDocument)?; + Ok(ContentAwarePreview { doc: d.doc.clone(), plan, params: p.clone() }) +} diff --git a/crates/engine/src/retouch_cmds/tests.rs b/crates/engine/src/retouch_cmds/tests.rs index b566196738..625e702989 100644 --- a/crates/engine/src/retouch_cmds/tests.rs +++ b/crates/engine/src/retouch_cmds/tests.rs @@ -917,6 +917,31 @@ fn content_aware_move_moves_the_object_and_fills_its_place_at_all_depths() { } } +#[test] +fn content_aware_move_preview_shows_the_result_without_touching_the_session() { + use crate::jobs::JobCtx; + let mut s = session(128, 64, 8, "rgb"); + paint_layer(&mut s, with_object(20, 26)); + s.execute("select.rect", json!({"x": 16, "y": 22, "width": 20, "height": 20})).unwrap(); + let before = s.active().unwrap().revision; + let p = json!({"offset": [70, 0]}); + let (doc, damage) = content_aware_move_preview(&s, &p).unwrap().run(&JobCtx::new()).unwrap(); + let px = |d: &Document, x, y| d.layers[0].surface().unwrap().rgba(x, y); + assert!(is_object(px(&doc, 95, 31)) && !is_object(px(&doc, 25, 31)), "the preview shows the move"); + assert!(damage.contains(95, 31) && damage.contains(25, 31), "{damage:?}"); + // The session is untouched. + assert!(is_object(rgba(&s, 25, 31)) && !is_object(rgba(&s, 95, 31))); + assert_eq!(s.active().unwrap().revision, before); + // A cancelled preview stops; a selection past the preview's size and bad params are errors. + let ctx = JobCtx::new(); + ctx.cancel(); + assert!(matches!(content_aware_move_preview(&s, &p).unwrap().run(&ctx), Err(EngineError::Cancelled))); + assert!(content_aware_move_preview(&s, &json!({"offset": [0, 0]})).is_err()); + assert!(content_aware_move_preview(&s, &json!({"offset": [70, 0], "rotate": "x"})).is_err()); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 300, "height": 300})).unwrap(); + assert!(content_aware_move_preview(&s, &json!({"offset": [1, 0]})).is_err()); +} + #[test] fn content_aware_move_transform_on_drop_scales_and_rotates_the_content() { // A horizontal 16×6 bar in a 36×36 selection, dropped 80 px right and turned 90° with 125% diff --git a/crates/ui-egui/src/cam_preview.rs b/crates/ui-egui/src/cam_preview.rs new file mode 100644 index 0000000000..4065e3353c --- /dev/null +++ b/crates/ui-egui/src/cam_preview.rs @@ -0,0 +1,285 @@ +//! Content-Aware Move drags and its Transform On Drop box shown with the result: once the pointer +//! (or the box) rests for a moment, the move is computed as a background job +//! ([`photocraft_engine::retouch_cmds::content_aware_move_preview`]: a smaller sampling window than +//! the command and only small selections) and the canvas shows the document with it. Any change of +//! the offset, scale or rotation cancels the job and starts the wait again, so the UI never waits +//! for the blend. Releasing (or Enter) runs the exact `paint.contentAwareMove`; the document is +//! untouched until then. Not available on wasm (no threads). + +use std::sync::Arc; +use std::sync::mpsc::{Receiver, TryRecvError}; + +use photocraft_doc::{DocId, Document}; +use photocraft_engine::jobs::JobCtx; +use serde_json::Value; + +use crate::PhotocraftApp; +use crate::state::Tool; + +/// Preview keys: `BASE + n`, one per result shown (see `canvas::display_doc`). +const BASE: u64 = 1 << 45; +/// How long the move must stay unchanged before a preview is computed. +const DEBOUNCE_MS: f64 = 150.0; +/// How often a running job is polled for its result. +const POLL_MS: u64 = 40; + +struct Running { + key: String, + ctx: JobCtx, + rx: Receiver>, +} + +pub(crate) struct CamPreview { + doc: DocId, + revision: u64, + /// The params the move has now, and when they last changed (ms). + key: String, + since: f64, + /// Params whose preview failed (too large a selection, say): not tried again. + failed: Option, + running: Option, + /// The latest finished preview, with the params it shows. + shown: Option<(String, Arc)>, + serial: u64, +} + +impl CamPreview { + fn stop(&mut self) { + if let Some(r) = self.running.take() { + r.ctx.cancel(); + } + } +} + +impl Drop for CamPreview { + fn drop(&mut self) { + self.stop(); + } +} + +/// `paint.contentAwareMove`'s params for what the pointer or the box has now; `None` without a +/// move to preview. +fn wanted(app: &mut PhotocraftApp) -> Option { + if app.ui.tool != Tool::ContentAwareMove || cfg!(target_arch = "wasm32") { + return None; + } + if let Some(t) = &app.ui.cam_transform { + let place = crate::cam_transform::placement(t)?; + if place.offset == [0, 0] && place.is_plain_move() { + return None; + } + return Some(crate::cam_transform::params(app, &place)); + } + let d = app.drag.as_ref().filter(|d| d.tool == Tool::ContentAwareMove)?; + let (start, mods) = (d.start, d.modifiers); + let end = d.points.last().map_or(start, |p| [p[0], p[1]]); + if !crate::retouch_ui::patch_drags_selection(app, start, mods) { + return None; + } + let off = crate::retouch_ui::patch_offset(app, start, end); + (off != [0, 0]).then(|| crate::retouch_ui::content_aware_move_params(app, off.map(i64::from))) +} + +/// The document to show for the move on document `idx`: with the move applied, once its preview +/// has been computed for the current offset and transform. +pub(crate) fn display_doc(app: &mut PhotocraftApp, idx: usize) -> Option<(Arc, u64)> { + if app.session.active_index() != Some(idx) { + return None; + } + step(app, crate::gpu_canvas::now_ms()) +} + +fn step(app: &mut PhotocraftApp, now: f64) -> Option<(Arc, u64)> { + let Some(params) = wanted(app) else { + app.cam_preview = None; + return None; + }; + let st = app.session.active()?; + let (doc, revision) = (st.doc.id, st.revision); + let key = params.to_string(); + if app.cam_preview.as_ref().is_some_and(|p| p.doc != doc || p.revision != revision) { + app.cam_preview = None; + } + let p = app.cam_preview.get_or_insert_with(|| CamPreview { + doc, + revision, + key: String::new(), + since: now, + failed: None, + running: None, + shown: None, + serial: 0, + }); + if p.key != key { + p.key = key.clone(); + p.since = now; + // What is computing is already out of date. + if p.running.as_ref().is_some_and(|r| r.key != key) { + p.stop(); + } + } + if let Some(r) = &p.running { + match r.rx.try_recv() { + Ok(result) => { + let r = p.running.take(); + match (result, r) { + (Ok(d), Some(r)) => { + // Duotone documents display through their inks. + let d = photocraft_engine::mode_cmds::display_document(&d).unwrap_or(d); + p.shown = Some((r.key, Arc::new(d))); + p.serial += 1; + } + (_, Some(r)) => p.failed = Some(r.key), + _ => {} + } + } + Err(TryRecvError::Disconnected) => { + if let Some(r) = p.running.take() { + p.failed = Some(r.key); + } + } + Err(TryRecvError::Empty) => {} + } + } + let settled = now - p.since >= DEBOUNCE_MS; + let done = p.shown.as_ref().is_some_and(|s| s.0 == key); + if settled && !done && p.running.is_none() && p.failed.as_deref() != Some(&key) { + match start(app, ¶ms, key.clone()) { + Some(r) => app.cam_preview.as_mut()?.running = Some(r), + None => app.cam_preview.as_mut()?.failed = Some(key.clone()), + } + } + let p = app.cam_preview.as_ref()?; + // Only a preview of the move as it is now: an older one would show a wrong place. + let (_, d) = p.shown.as_ref().filter(|s| s.0 == key)?; + Some((d.clone(), BASE + p.serial)) +} + +/// Compute the preview of `params` on a worker thread. +fn start(app: &PhotocraftApp, params: &Value, key: String) -> Option { + let job = photocraft_engine::retouch_cmds::content_aware_move_preview(&app.session, params).ok()?; + let ctx = JobCtx::new(); + let (tx, rx) = std::sync::mpsc::channel(); + let worker = ctx.clone(); + std::thread::Builder::new() + .name("cam-preview".into()) + .spawn(move || { + let _ = tx.send(job.run(&worker).map(|(d, _)| d)); + }) + .ok()?; + Some(Running { key, ctx, rx }) +} + +/// Keep frames coming while a preview waits out its debounce or computes. +pub(crate) fn wake(app: &PhotocraftApp, ctx: &egui::Context) { + let Some(p) = &app.cam_preview else { return }; + if p.running.is_some() { + ctx.request_repaint_after(std::time::Duration::from_millis(POLL_MS)); + } else if p.shown.as_ref().is_none_or(|s| s.0 != p.key) && p.failed.as_deref() != Some(&p.key) { + let left = (DEBOUNCE_MS - (crate::gpu_canvas::now_ms() - p.since)).max(1.0); + ctx.request_repaint_after(std::time::Duration::from_millis(left as u64)); + } +} + +/// Whether the canvas shows a preview. +pub(crate) fn showing(app: &PhotocraftApp) -> bool { + app.cam_preview.as_ref().is_some_and(|p| p.shown.as_ref().is_some_and(|s| s.0 == p.key)) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::canvas::{ToolEvent, tool_event}; + use serde_json::json; + + fn blue(d: &Document, x: i32, y: i32) -> bool { + d.layers[0].surface().unwrap().rgba(x, y)[0] < 0.5 + } + + #[test] + fn the_drag_previews_the_move_after_it_rests_and_never_touches_the_document() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 100, "height": 60})).unwrap(); + app.run("paint.pencil", json!({"points": [[16, 30], [28, 30]], "size": 4, "color": "#0000ff"})).unwrap(); + app.run("select.lasso", json!({"points": [[6, 14], [38, 14], [38, 46], [6, 46]]})).unwrap(); + app.ui.tool = Tool::ContentAwareMove; + let m = egui::Modifiers::NONE; + let steps = app.session.active().unwrap().history.past_len(); + + // Nothing to preview before the patch moves. + tool_event(&mut app, ToolEvent::Down { x: 22.0, y: 30.0, pressure: 1.0 }, m); + assert!(step(&mut app, 0.0).is_none() && app.cam_preview.is_none()); + tool_event(&mut app, ToolEvent::Move { x: 72.0, y: 30.0, pressure: 1.0 }, m); + // Still moving: the wait starts and nothing is computed or shown yet. + assert!(step(&mut app, 1000.0).is_none()); + assert!(step(&mut app, 1000.0 + DEBOUNCE_MS / 2.0).is_none() && app.cam_preview.as_ref().unwrap().running.is_none()); + // At rest: the job runs, off this thread, and its result shows once it arrives. + let mut now = 1000.0 + DEBOUNCE_MS; + let mut shown = step(&mut app, now); + for _ in 0..600 { + if shown.is_some() { + break; + } + std::thread::sleep(std::time::Duration::from_millis(10)); + now += 10.0; + shown = step(&mut app, now); + } + let (preview, key) = shown.expect("a preview once the pointer rested"); + assert!(key > BASE && showing(&app)); + assert!(blue(&preview, 72, 30) && !blue(&preview, 22, 30), "the preview shows the move"); + let doc = app.session.active().unwrap().doc.clone(); + assert!(blue(&doc, 22, 30) && !blue(&doc, 72, 30), "the document is untouched"); + assert_eq!(app.session.active().unwrap().history.past_len(), steps); + + // Moving on drops the stale preview at once and cancels what is not shown yet. + tool_event(&mut app, ToolEvent::Move { x: 60.0, y: 30.0, pressure: 1.0 }, m); + assert!(step(&mut app, now + 5.0).is_none() && !showing(&app)); + // Release commits the exact move; the preview is gone. + tool_event(&mut app, ToolEvent::Up { x: 60.0, y: 30.0 }, m); + assert!(step(&mut app, now + 10.0).is_none() && app.cam_preview.is_none()); + } + + #[test] + fn the_transform_on_drop_box_previews_the_dropped_patch() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 100, "height": 60})).unwrap(); + app.run("paint.pencil", json!({"points": [[16, 30], [28, 30]], "size": 4, "color": "#0000ff"})).unwrap(); + app.run("select.lasso", json!({"points": [[6, 14], [38, 14], [38, 46], [6, 46]]})).unwrap(); + app.ui.tool = Tool::ContentAwareMove; + app.ui.tool_options.cam_transform_on_drop = true; + let m = egui::Modifiers::NONE; + tool_event(&mut app, ToolEvent::Down { x: 22.0, y: 30.0, pressure: 1.0 }, m); + tool_event(&mut app, ToolEvent::Move { x: 72.0, y: 30.0, pressure: 1.0 }, m); + tool_event(&mut app, ToolEvent::Up { x: 72.0, y: 30.0 }, m); + assert!(crate::cam_transform::active(&app)); + let (mut now, mut shown) = (0.0, step(&mut app, 0.0)); + for _ in 0..800 { + if shown.is_some() { + break; + } + std::thread::sleep(std::time::Duration::from_millis(10)); + now += 10.0; + shown = step(&mut app, now); + } + let (preview, _) = shown.expect("the box shows the result"); + assert!(blue(&preview, 72, 30) && !blue(&preview, 22, 30)); + // Cancelling the box drops the preview. + crate::cam_transform::cancel(&mut app); + assert!(step(&mut app, now + 1.0).is_none() && app.cam_preview.is_none()); + } + + #[test] + fn a_selection_too_large_to_preview_is_not_retried() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 600, "height": 400})).unwrap(); + app.run("select.rect", json!({"x": 10, "y": 10, "width": 300, "height": 300})).unwrap(); + app.ui.tool = Tool::ContentAwareMove; + let m = egui::Modifiers::NONE; + tool_event(&mut app, ToolEvent::Down { x: 100.0, y: 100.0, pressure: 1.0 }, m); + tool_event(&mut app, ToolEvent::Move { x: 140.0, y: 100.0, pressure: 1.0 }, m); + assert!(step(&mut app, 0.0).is_none()); + assert!(step(&mut app, DEBOUNCE_MS + 1.0).is_none()); + let p = app.cam_preview.as_ref().unwrap(); + assert!(p.running.is_none() && p.failed.as_deref() == Some(p.key.as_str())); + } +} diff --git a/crates/ui-egui/src/cam_transform.rs b/crates/ui-egui/src/cam_transform.rs index 33912a28e8..27b0943a0f 100644 --- a/crates/ui-egui/src/cam_transform.rs +++ b/crates/ui-egui/src/cam_transform.rs @@ -112,6 +112,17 @@ pub(crate) fn cancel_stale(app: &mut PhotocraftApp) { } } +/// `paint.contentAwareMove`'s params for the box's placement and the options bar. +pub(crate) fn params(app: &PhotocraftApp, place: &Placement) -> serde_json::Value { + let mut p = crate::retouch_ui::content_aware_move_params(app, place.offset); + if !place.is_plain_move() { + p["scaleX"] = place.scale[0].into(); + p["scaleY"] = place.scale[1].into(); + p["rotate"] = place.rotate.into(); + } + p +} + /// ↩ / ✓: the move with the transformed patch, as one background job and History step. pub(crate) fn commit(app: &mut PhotocraftApp) { cancel_stale(app); @@ -122,12 +133,7 @@ pub(crate) fn commit(app: &mut PhotocraftApp) { crate::retouch_ui::patch_hint(app); return; } - let mut p = crate::retouch_ui::content_aware_move_params(app, place.offset); - if !place.is_plain_move() { - p["scaleX"] = place.scale[0].into(); - p["scaleY"] = place.scale[1].into(); - p["rotate"] = place.rotate.into(); - } + let p = params(app, &place); if let Err(e) = app.run("paint.contentAwareMove", p) { app.ui.status = e; app.ui.status_error = true; diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 4f78b853f2..051714aeba 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1076,6 +1076,10 @@ pub(crate) fn display_doc(app: &mut PhotocraftApp, idx: usize) -> (std::sync::Ar if let Some(shown) = crate::patch_preview::display_doc(app, idx) { return shown; } + // Content-Aware Move drag or box: the result, once computed in the background. + if let Some(shown) = crate::cam_preview::display_doc(app, idx) { + return shown; + } // A blend mode hovered in the Layers panel. if let Some(shown) = crate::blend_preview::display_doc(app, idx) { return shown; @@ -1146,7 +1150,7 @@ const NAVIGATOR_SETTLE_MS: f64 = 200.0; /// of document `idx` and catches up on release: each step of the drag is a new preview, and a /// thumbnail composite of the whole document per step makes painting lag on large images. fn navigator_waits_for_drag(app: &PhotocraftApp, idx: usize) -> bool { - crate::move_ui::showing(app) || crate::patch_preview::showing(app) || live_stroke(app, idx).is_some() + crate::move_ui::showing(app) || crate::patch_preview::showing(app) || crate::cam_preview::showing(app) || live_stroke(app, idx).is_some() } /// The Navigator panel's image of document `idx`. With the CPU canvas that is the canvas texture @@ -3485,6 +3489,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: crate::type_tool::draw_overlay(app, &painter, &xf); crate::transform_tool::draw_overlay(app, &painter, &xf); crate::cam_transform::draw(app, &painter, &xf); + crate::cam_preview::wake(app, painter.ctx()); crate::distort_ui::draw_overlay(app, &painter, &xf); crate::perspective_crop_ui::draw_overlay(app, &painter, &xf); crate::retouch_ui::draw_source_marker(app, &painter, &xf); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 873437b260..e599845669 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -34,6 +34,7 @@ pub mod brush_preview; pub mod brush_resize; pub mod brush_sections; pub mod brushes_tab; +pub(crate) mod cam_preview; mod cam_transform; mod camera_raw_detail_ui; mod camera_raw_preview_ui; @@ -520,6 +521,8 @@ pub struct PhotocraftApp { pub(crate) blend_preview: Option, /// Patch Tool drag: the healed document at the pointer (`patch_preview`). pub(crate) patch_preview: Option, + /// Content-Aware Move drag or box shown with its result (`cam_preview`). + pub(crate) cam_preview: Option, /// The pixels a Magnetic Lasso border follows (`magnetic_lasso_ui`). pub(crate) magnetic: magnetic_lasso_ui::Runtime, /// The next tool `Down` is a right-button drag that erases (see `paint_mouse`). @@ -747,6 +750,7 @@ impl PhotocraftApp { object_finder: None, blend_preview: None, patch_preview: None, + cam_preview: None, magnetic: Default::default(), secondary_erase: false, held_erase: false, diff --git a/docs/scorecard.md b/docs/scorecard.md index db11f4050b..465b7bc7a9 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -133,7 +133,7 @@ Corpus floors (`crates/io/tests/corpus.rs`): the enforced minimums; the corpus t | TOOL-213-1 | Pencil tool: aliased 1 px painting, square pixel-aligned cursor | done | [#213](https://github.com/storytold/photocraft/issues/213) | Tool::Pencil (B group): live aliased strokes on the pixel grid, square cursor, Auto Erase; pencil_tests.rs | | TOOL-213-2 | Mixer Brush tool on the toolbar | done | [#213](https://github.com/storytold/photocraft/issues/213) | Tool::MixerBrush in the Brush (B) flyout; Wet/Load/Mix/Flow/Sample All Layers options, command/control dispatch and selection-clipping tests | | TOOL-213-3 | Patch tool with a live preview of the patched area | done | [#213](https://github.com/storytold/photocraft/issues/213) | paint.patch (retouch_cmds/patch.rs, source/destination) + Tool::Patch (J group: lasso, then drag the selection); the drag shows the heal live (patch_preview.rs, coarse colour fit: 1000x1000 in 52 ms) | -| TOOL-213-4 | Content-Aware Move tool reusing inpaint completion | partial | [#213](https://github.com/storytold/photocraft/issues/213) | paint.contentAwareMove (retouch_cmds/content_aware_move.rs: move/extend, Structure 1-7, Color 0-10, Sample All Layers, Transform On Drop's scaleX/scaleY/rotate; background job) + Tool::ContentAwareMove (J group: lasso, then drag; Transform On Drop puts a scale/rotate box on the dropped patch, cam_transform.rs: Enter commits as one step, Esc cancels). Missing: a live preview of the result (the drag and the box show the outline only) | +| TOOL-213-4 | Content-Aware Move tool reusing inpaint completion | partial | [#213](https://github.com/storytold/photocraft/issues/213) | paint.contentAwareMove (retouch_cmds/content_aware_move.rs: move/extend, Structure 1-7, Color 0-10, Sample All Layers, Transform On Drop's scaleX/scaleY/rotate; background job) + Tool::ContentAwareMove (J group: lasso, then drag; Transform On Drop puts a scale/rotate box on the dropped patch, cam_transform.rs: Enter commits as one step, Esc cancels). cam_preview.rs: once the pointer or the box rests, the result shows (a cancellable background job on a smaller sampling window, small selections only, #4385). Missing: a progressive preview for big selections | | TOOL-213-5 | Painting a type/shape/smart/fill layer offers to rasterize, then continues the stroke | done | [#213](https://github.com/storytold/photocraft/issues/213) | rasterize_prompt.rs: OK rasterizes then paints (two history states), Cancel does nothing; drivable via ui.dialog.confirm | | TOOL-213-6 | Fill dialog: contents, blend, opacity, preserve transparency; remembered; Shift+Backspace | done | [#213](https://github.com/storytold/photocraft/issues/213) | fill_ui.rs dialog over edit.fill (fill_cmds.rs): all contents, mode, opacity, preserve; remembered in prefs; Shift+F5 / Shift+Backspace | | TOOL-213-7 | Live stroke preview for every brush-based retouch tool | partial | [#213](https://github.com/storytold/photocraft/issues/213) | Live (canvas.rs strokes_live): Brush, Pencil, Eraser, Blur, Sharpen, Smudge, Dodge, Burn, Sponge, Clone Stamp, Healing Brush, History Brush (#1026, #1040); the release commits the live stroke's pixels (P32). Not yet live: Spot Healing Brush, Mixer Brush, Background Eraser, Pattern Stamp | diff --git a/scorecard/tools.toml b/scorecard/tools.toml index c090d4f897..cbff50e333 100644 --- a/scorecard/tools.toml +++ b/scorecard/tools.toml @@ -31,7 +31,7 @@ id = "TOOL-213-4" target = "Content-Aware Move tool reusing inpaint completion" status = "partial" issue = 213 -note = "paint.contentAwareMove (retouch_cmds/content_aware_move.rs: move/extend, Structure 1-7, Color 0-10, Sample All Layers, Transform On Drop's scaleX/scaleY/rotate; background job) + Tool::ContentAwareMove (J group: lasso, then drag; Transform On Drop puts a scale/rotate box on the dropped patch, cam_transform.rs: Enter commits as one step, Esc cancels). Missing: a live preview of the result (the drag and the box show the outline only)" +note = "paint.contentAwareMove (retouch_cmds/content_aware_move.rs: move/extend, Structure 1-7, Color 0-10, Sample All Layers, Transform On Drop's scaleX/scaleY/rotate; background job) + Tool::ContentAwareMove (J group: lasso, then drag; Transform On Drop puts a scale/rotate box on the dropped patch, cam_transform.rs: Enter commits as one step, Esc cancels). cam_preview.rs: once the pointer or the box rests, the result shows (a cancellable background job on a smaller sampling window, small selections only, #4385). Missing: a progressive preview for big selections" [[item]] id = "TOOL-213-5" From 78c61e6df5aee4ef726044154e2234cc335fbd3e Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Tue, 13 Oct 2026 04:24:07 +0200 Subject: [PATCH 12/15] Swatches: an RGB group with the exact primaries and secondaries (#4302) (#4409) The built-in "Pure" group's hues are vivid but not pure (its green is #28C850), so picking it for text looked dull next to Photoshop's #00FF00. Add a Photoshop-style "RGB" group (#FF0000, #FFFF00, #00FF00, #00FFFF, #0000FF, #FF00FF) right after Grays. Pure is kept unchanged so existing documents, actions and saved swatches that use it keep their colours. --- crates/engine/src/presets/swatches.rs | 35 ++++++++++++++++++++++---- crates/engine/src/swatch_cmds/tests.rs | 21 ++++++++-------- 2 files changed, 41 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/presets/swatches.rs b/crates/engine/src/presets/swatches.rs index eec8c2d0d8..eb666e1ec5 100644 --- a/crates/engine/src/presets/swatches.rs +++ b/crates/engine/src/presets/swatches.rs @@ -288,7 +288,9 @@ pub fn hex(c: [f32; 3]) -> String { // ------------------------------------------------------------------ defaults -/// The default library: 40 colours in four groups (our own palette). +/// The default library: 46 colours in five groups. "RGB" holds the exact primaries and +/// secondaries (#FF0000, #00FF00, ...) as Photoshop's RGB group does; the other four are our own +/// palette, whose "Pure" hues are vivid but not the pure channel values (#4302). pub fn builtin() -> Vec> { let rgb = |n: &str, c: [u8; 3]| Swatch::new(n, SwatchColor::Rgb(c.map(|v| f32::from(v) / 255.0))); let grays = [ @@ -333,8 +335,19 @@ pub fn builtin() -> Vec> { let row = |prefix: &str, cs: [[u8; 3]; 10]| -> Vec { hues.iter().zip(cs).map(|(h, c)| rgb(&if prefix.is_empty() { (*h).to_string() } else { format!("{prefix} {h}") }, c)).collect() }; + // Right after Grays, near the top of the panel (Grays stays first: new swatches land there). + // Photoshop's order: red, yellow, green, cyan, blue, magenta. + let exact: [(&str, [u8; 3]); 6] = [ + ("RGB Red", [255, 0, 0]), + ("RGB Yellow", [255, 255, 0]), + ("RGB Green", [0, 255, 0]), + ("RGB Cyan", [0, 255, 255]), + ("RGB Blue", [0, 0, 255]), + ("RGB Magenta", [255, 0, 255]), + ]; vec![ Group::new("Grays", grays.iter().map(|(n, v)| rgb(n, [*v; 3])).collect()), + Group::new("RGB", exact.iter().map(|(n, c)| rgb(n, *c)).collect()), Group::new("Pastel", row("Pastel", pastel)), Group::new("Pure", row("", pure)), Group::new("Dark", row("Dark", dark)), @@ -346,15 +359,27 @@ mod tests { use super::*; #[test] - fn default_library_has_the_forty_colours() { + fn default_library_has_the_forty_six_colours() { let b = builtin(); - assert_eq!(b.iter().map(|g| g.items.len()).sum::(), 40); + assert_eq!(b.iter().map(|g| g.items.len()).sum::(), 46); let names: Vec<&str> = b.iter().flat_map(|g| g.items.iter().map(|s| s.name.as_str())).collect(); let mut uniq = names.clone(); uniq.sort_unstable(); uniq.dedup(); - assert_eq!(uniq.len(), 40, "names are unique: {names:?}"); - assert_eq!(b[2].items[0].color, SwatchColor::Rgb([230.0 / 255.0, 40.0 / 255.0, 40.0 / 255.0])); + assert_eq!(uniq.len(), 46, "names are unique: {names:?}"); + assert_eq!(b[3].name, "Pure"); + assert_eq!(b[3].items[0].color, SwatchColor::Rgb([230.0 / 255.0, 40.0 / 255.0, 40.0 / 255.0])); + } + + #[test] + fn the_rgb_group_holds_exact_primaries_and_secondaries() { + // #4302: picking green should give #00FF00, as in Photoshop's RGB group. + let b = builtin(); + let g = &b[1]; + assert_eq!(g.name, "RGB"); + let conv = SwatchConv::builtin(); + let hexes: Vec = g.items.iter().map(|s| hex(conv.rgb(&s.color))).collect(); + assert_eq!(hexes, ["#ff0000", "#ffff00", "#00ff00", "#00ffff", "#0000ff", "#ff00ff"]); } #[test] diff --git a/crates/engine/src/swatch_cmds/tests.rs b/crates/engine/src/swatch_cmds/tests.rs index cb121a1832..836b843971 100644 --- a/crates/engine/src/swatch_cmds/tests.rs +++ b/crates/engine/src/swatch_cmds/tests.rs @@ -14,10 +14,11 @@ fn export_bytes(s: &mut Session, p: Value) -> Vec { fn defaults_and_listing() { let mut s = Session::new(); let r = s.execute("swatches.list", json!({})).unwrap(); - assert_eq!(r["count"], 40); + assert_eq!(r["count"], 46); assert_eq!(r["groups"][0]["name"], "Grays"); assert_eq!(r["groups"][0]["swatches"][0], json!({"name": "Black", "model": "rgb", "values": [0.0, 0.0, 0.0], "hex": "#000000"})); - assert_eq!(r["groups"][2]["swatches"][0]["hex"], "#e62828"); + assert_eq!(r["groups"][1]["swatches"][2]["hex"], "#00ff00", "RGB Green is exact (#4302)"); + assert_eq!(r["groups"][3]["swatches"][0]["hex"], "#e62828"); } #[test] @@ -67,7 +68,7 @@ fn rename_delete_move_and_groups() { assert_eq!(s.presets.swatches[0].items[0].name, "White"); let r = s.execute("swatches.move", json!({"swatch": "White", "to": "Dark", "position": 1})).unwrap(); assert_eq!(r, json!({"group": "Dark", "position": 1})); - assert_eq!(s.presets.swatches[3].items[1].name, "White"); + assert_eq!(s.presets.swatches[4].items[1].name, "White"); // Out-of-range positions clamp. let r = s.execute("swatches.move", json!({"swatch": "White", "position": 999_999})).unwrap(); assert_eq!(r["position"], 10); @@ -80,21 +81,21 @@ fn rename_delete_move_and_groups() { assert!(s.execute("swatches.renameGroup", json!({"group": "Favourites", "name": "Dark"})).is_err()); let r = s.execute("swatches.deleteGroup", json!({"group": "Favourites", "keepSwatches": true})).unwrap(); assert_eq!(r["kept"], 2); - assert!(s.presets.swatches[3].items.iter().any(|i| i.name == "Red"), "kept in the group above"); + assert!(s.presets.swatches[4].items.iter().any(|i| i.name == "Red"), "kept in the group above"); s.execute("swatches.deleteGroup", json!({"group": "Mine 1"})).unwrap(); // Delete several by name, and one by index. let r = s.execute("swatches.delete", json!({"swatch": ["Red", "Blue", "Red"]})).unwrap(); assert_eq!(r["deleted"].as_array().unwrap().len(), 2); let r = s.execute("swatches.delete", json!({"index": 0})).unwrap(); assert_eq!(r["deleted"], json!(["Ink Black"])); - assert_eq!(names(&s).len(), 37); + assert_eq!(names(&s).len(), 43); // Reset restores the defaults; append adds them again with unique names. s.execute("swatches.reset", json!({})).unwrap(); - assert_eq!(names(&s).len(), 40); + assert_eq!(names(&s).len(), 46); s.execute("swatches.reset", json!({"append": true})).unwrap(); - assert_eq!(names(&s).len(), 80); + assert_eq!(names(&s).len(), 92); assert!(names(&s).contains(&"Black 2".to_string())); - assert_eq!(s.presets.swatches[4].name, "Grays 1"); + assert_eq!(s.presets.swatches[5].name, "Grays 1"); } #[test] @@ -220,7 +221,7 @@ fn bad_params_fail_gracefully() { ("swatches.delete", json!({"swatch": "Nope"})), ("swatches.delete", json!({"swatch": ["Red", 5]})), ("swatches.delete", json!({"swatch": ["Red", "Nope"]})), - ("swatches.delete", json!({"index": 40})), + ("swatches.delete", json!({"index": 46})), ("swatches.delete", json!({"index": "0"})), ("swatches.delete", json!({"swatch": "Red", "group": "Grays"})), ("swatches.rename", json!({"swatch": "Red"})), @@ -264,7 +265,7 @@ fn bad_params_fail_gracefully() { assert_eq!(s.presets.swatches, before, "failed commands change nothing"); // Empty library: the swatch commands are disabled, not crashing. s.execute("swatches.delete", json!({"swatch": names(&s)})).unwrap(); - for g in ["Grays", "Pastel", "Pure", "Dark"] { + for g in ["Grays", "RGB", "Pastel", "Pure", "Dark"] { s.execute("swatches.deleteGroup", json!({"group": g})).unwrap(); } for id in ["swatches.delete", "swatches.rename", "swatches.move", "swatches.use", "swatches.export", "swatches.renameGroup", "swatches.deleteGroup"] { From 1f76d839e3825fc3f1bf121c76e8bf252b4a8365 Mon Sep 17 00:00:00 2001 From: F4LCON <107556180+itsF4LCON@users.noreply.github.com> Date: Tue, 13 Oct 2026 04:24:11 +0200 Subject: [PATCH 13/15] SVG: a group clipped by one path opens as editable shapes with a vector mask (#4266) (#4425) --- crates/io/src/svg.rs | 90 +++++++++++++++++++++++++++++++++++++++--- crates/io/tests/svg.rs | 3 +- 2 files changed, 87 insertions(+), 6 deletions(-) diff --git a/crates/io/src/svg.rs b/crates/io/src/svg.rs index b6a7741d6e..04fc4bee3a 100644 --- a/crates/io/src/svg.rs +++ b/crates/io/src/svg.rs @@ -15,7 +15,7 @@ use std::sync::{Arc, OnceLock}; use photocraft_color::blend::BlendMode; use photocraft_color::{Color, ColorMode, PixelFormat, SampleType}; use photocraft_doc::effects::GradientStyle; -use photocraft_doc::vector::{FillRule, Knot, LineCap, LineJoin, Path, PathOp, ShapeLayer, ShapeStroke, StrokeAlign, Subpath}; +use photocraft_doc::vector::{FillRule, Knot, LineCap, LineJoin, Path, PathOp, ShapeLayer, ShapeStroke, StrokeAlign, Subpath, VectorMask}; use photocraft_doc::{Document, Fill, Group, Layer, LayerContent, MAX_GROUP_DEPTH}; use photocraft_geom::{Point, Rect, Size}; use photocraft_raster::Surface; @@ -348,8 +348,11 @@ impl Conv { fn convert_node(&mut self, node: &usvg::Node, out: &mut Vec, depth: usize, rec: usize, parent: tiny_skia::Transform) { match node { usvg::Node::Group(g) => { + // A clip-path of one plain path becomes the group's vector mask (#4266); others + // are rasterised with the group. + let clip = g.clip_path().and_then(|cp| self.clip_mask(g, cp)); let dropped: [(bool, &'static str); 3] = - [(!g.filters().is_empty(), "filter"), (g.clip_path().is_some(), "clip-path"), (g.mask().is_some(), "mask")]; + [(!g.filters().is_empty(), "filter"), (g.clip_path().is_some() && clip.is_none(), "clip-path"), (g.mask().is_some(), "mask")]; let too_deep = self.max_group_depth.is_some_and(|limit| depth >= limit) || depth >= MAX_GROUP_DEPTH || rec >= MAX_RECURSION; if dropped.iter().any(|d| d.0) || too_deep { for (yes, what) in dropped { @@ -366,7 +369,7 @@ impl Conv { } // A group that only carries a transform (baked into its paths by usvg) or that // usvg inserted for its own bookkeeping adds nothing to the layer tree. - let plain = g.id().is_empty() && g.opacity().get() >= 1.0 && g.blend_mode() == usvg::BlendMode::Normal; + let plain = clip.is_none() && g.id().is_empty() && g.opacity().get() >= 1.0 && g.blend_mode() == usvg::BlendMode::Normal; let children = self.convert_children(g.children(), if plain { depth } else { depth + 1 }, rec + 1, g.abs_transform()); if children.is_empty() { return; @@ -376,9 +379,14 @@ impl Conv { return; } let only_id = g.opacity().get() >= 1.0 && g.blend_mode() == usvg::BlendMode::Normal; - if only_id && children.len() == 1 { + // A lone child takes the group's name (and its clip, when it has no vector mask of + // its own). + if only_id && children.len() == 1 && (clip.is_none() || children.iter().all(|c| c.vector_mask.is_none())) { if let Some(mut child) = children.into_iter().next() { - child.name = g.id().to_string(); + if !g.id().is_empty() { + child.name = g.id().to_string(); + } + child.vector_mask = clip.or(child.vector_mask); out.push(child); } return; @@ -386,6 +394,7 @@ impl Conv { let mut l = Layer::new(self.name(g.id(), 1), LayerContent::Group(Group { children, expanded: false, artboard: None })); l.opacity = g.opacity().get(); l.blend = blend(g.blend_mode()); + l.vector_mask = clip; out.push(l); } usvg::Node::Path(p) => out.extend(self.shape_layer(node, p, parent)), @@ -412,6 +421,29 @@ impl Conv { } } + /// The vector mask for group `g` clipped by `cp`, when the clip is one visible path with no + /// clip of its own: what resvg draws for the clip (the group's transform, then the clip's, + /// then the path), in canvas pixels, with the clip rule as its fill rule. + fn clip_mask(&self, g: &usvg::Group, cp: &usvg::ClipPath) -> Option { + if cp.clip_path().is_some() { + return None; + } + let [usvg::Node::Path(p)] = cp.root().children() else { return None }; + if !p.is_visible() { + return None; + } + let ts = g.abs_transform().pre_concat(cp.transform()).post_concat(self.global); + let subpaths = knots(&(*p.data()).clone().transform(ts)?); + if subpaths.is_empty() { + return None; + } + let fill_rule = match p.fill().map(|f| f.rule()) { + Some(usvg::FillRule::EvenOdd) => FillRule::EvenOdd, + _ => FillRule::NonZero, + }; + Some(VectorMask::new(Path { subpaths, fill_rule, inverted: false })) + } + /// A path as a shape layer, or a pixel layer when its paint is a pattern. fn shape_layer(&mut self, node: &usvg::Node, p: &usvg::Path, parent: tiny_skia::Transform) -> Option { if !p.is_visible() { @@ -688,6 +720,54 @@ mod tests { assert!(r.warnings.iter().all(|w| !w.contains("font")), "{:?}", r.warnings); } + /// #4266: a group clipped by one path (the PhotoCraft icon's rounded square) stays editable + /// shapes with the clip as its vector mask, and looks as resvg draws the drawing; a clip of + /// two shapes is still rasterised, with the warning. + #[test] + fn a_single_path_clip_becomes_the_groups_vector_mask() { + let svg = br##" + + + + + "##; + let r = import_svg("t", svg).unwrap(); + assert!(r.warnings.iter().all(|w| !w.contains("clip-path")), "{:?}", r.warnings); + let [group] = r.document.layers.as_slice() else { panic!("one group: {:?}", r.document.layers.len()) }; + let LayerContent::Group(g) = &group.content else { panic!("a group") }; + assert_eq!(g.children.len(), 2); + assert!(g.children.iter().all(|c| matches!(c.content, LayerContent::Shape(_))), "editable shapes"); + let mask = group.vector_mask.as_ref().expect("the clip as a vector mask"); + let xs: Vec = mask.path.subpaths.iter().flat_map(|s| s.knots.iter().map(|k| k.anchor.x)).collect(); + let (lo, hi) = (xs.iter().copied().fold(f64::MAX, f64::min), xs.iter().copied().fold(f64::MIN, f64::max)); + assert!((lo - 12.0).abs() < 1e-3 && (hi - 52.0).abs() < 1e-3, "in the group's space: {lo}..{hi}"); + // Pixel for pixel what resvg draws, but for anti-aliasing along the edges. + let ours = photocraft_compose::flatten(&r.document).to_rgba8().pixels; + let tree = parse(svg).unwrap().tree; + let mut pm = tiny_skia::Pixmap::new(64, 64).unwrap(); + resvg::render(&tree, tiny_skia::Transform::default(), &mut pm.as_mut()); + let theirs: Vec = pm + .pixels() + .iter() + .flat_map(|p| { + let c = p.demultiply(); + [c.red(), c.green(), c.blue(), c.alpha()] + }) + .collect(); + let off = ours.chunks(4).zip(theirs.chunks(4)).filter(|(a, b)| a.iter().zip(*b).any(|(x, y)| x.abs_diff(*y) > 48)).count(); + assert!(off < 64, "{off} pixels differ"); + // The report's file: PhotoCraft's own icon opens without the clip-path warning. + let icon = import_svg("photocraft.svg", include_bytes!("../../../assets/app-icon/photocraft.svg")).unwrap(); + assert!(icon.warnings.iter().all(|w| !w.contains("clip-path")), "{:?}", icon.warnings); + assert!(icon.document.layers.iter().any(|l| l.vector_mask.is_some()), "its rounded square is a vector mask"); + // Two shapes in the clip: rasterised, and said so. + let two = br##" + + "##; + let r = import_svg("t", two).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("clip-path")), "{:?}", r.warnings); + } + #[test] fn huge_drawings_scale_to_the_side_limit() { let tree = parse(b"").unwrap().tree; diff --git a/crates/io/tests/svg.rs b/crates/io/tests/svg.rs index adbdf08a03..d1baf418fa 100644 --- a/crates/io/tests/svg.rs +++ b/crates/io/tests/svg.rs @@ -148,10 +148,11 @@ fn gradients_are_approximated_with_a_warning() { #[test] fn clip_paths_masks_filters_patterns_and_images_are_rasterised() { + // A clip of one path becomes a vector mask (#4266); one of two shapes is still rasterised. let r = open(&format!( "\ \ - \ + \ \ \ \ From f586e7133ef302d241b42c3eaabe1881d38d55cc Mon Sep 17 00:00:00 2001 From: Valentin Klein Date: Tue, 13 Oct 2026 04:24:15 +0200 Subject: [PATCH 14/15] Compose: key the vector-mask cache by mask content, not a temporary's address (#4426) (#4428) RenderVectorMasks keyed compiled masks by the address of the VectorMask it was given. hiding_mask/effects_source pass temporary clones, whose addresses get reused, so a later layer received an earlier layer's compiled mask. Co-authored-by: Claude Opus 5.5 --- crates/compose/src/advanced_tests.rs | 20 ++++++++++++++++++++ crates/compose/src/lib.rs | 17 +++++++++++++---- 2 files changed, 33 insertions(+), 4 deletions(-) diff --git a/crates/compose/src/advanced_tests.rs b/crates/compose/src/advanced_tests.rs index 9a8723c41d..c19b0dc92f 100644 --- a/crates/compose/src/advanced_tests.rs +++ b/crates/compose/src/advanced_tests.rs @@ -426,6 +426,26 @@ fn vector_mask_hides_effects() { } } +/// The per-render vector-mask cache must key masks by content: `hiding_mask` and +/// `effects_source` hand it temporary clones whose addresses get reused (#4426). +#[test] +fn vector_mask_cache_does_not_mix_up_layers() { + use photocraft_doc::{Path, Subpath, VectorMask}; + for depth in DEPTHS { + let mut d = doc(depth, true); + for (name, color, x0, x1) in [("a", BLUE, -4.0, 6.0), ("b", GREEN, 6.0, 16.0)] { + let mut l = solid(&d, name, full(&d), color); + l.effects.items = vec![inside_stroke()]; + l.advanced.vector_mask_hides_effects = true; + let path = Path::new(vec![Subpath::polygon(&[(x0, -4.0), (x1, -4.0), (x1, 12.0), (x0, 12.0)])]); + l.vector_mask = Some(VectorMask::new(path)); + d.layers.push(l); + } + check(&d, 2, 4, BLUE, "layer A inside its own mask"); + check(&d, 9, 4, GREEN, "layer B inside its own mask"); + } +} + #[test] fn defaults_take_the_plain_paths() { let d = doc(SampleType::U8, true); diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index ae9e53e39c..5931bea018 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -451,18 +451,27 @@ fn render_reduced_in_bands(doc: &Document, b: Rect, w: u32, h: u32, damage: Opti Buffer { rect: out, px: acc } } +type VectorMaskSlot = std::sync::Arc>; + #[derive(Default)] struct RenderVectorMasks { - masks: std::sync::Mutex>>>, + /// Compiled masks by content. Callers pass temporary clones (see `advanced.rs`), so an + /// address cannot identify a mask: a dropped clone's address is reused by the next one. + masks: std::sync::Mutex>, } impl RenderVectorMasks { fn values(&self, mask: &photocraft_doc::VectorMask, rect: Rect) -> Vec { - // Addresses identify immutable mask instances only for this render's lifetime. - let key = std::ptr::from_ref(mask) as usize; let slot = { let mut masks = self.masks.lock().unwrap_or_else(|e| e.into_inner()); - masks.entry(key).or_default().clone() + match masks.iter().find(|(m, _)| m == mask) { + Some((_, slot)) => slot.clone(), + None => { + let slot = VectorMaskSlot::default(); + masks.push((mask.clone(), slot.clone())); + slot + } + } }; // Compilation is sequential. Rendering can enter Rayon and must happen after // initialization, so waiting tiles cannot re-enter a slot still being built. From b4aea45e1960346dc897bb82de21082eaf3d9b60 Mon Sep 17 00:00:00 2001 From: F4LCON <107556180+itsF4LCON@users.noreply.github.com> Date: Tue, 13 Oct 2026 04:24:18 +0200 Subject: [PATCH 15/15] =?UTF-8?q?Actions:=20record=20File=20=E2=80=BA=20Sa?= =?UTF-8?q?ve=20a=20Copy=20and=20play=20it=20back=20as=20a=20copy=20(#4373?= =?UTF-8?q?)=20(#4390)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/engine/src/actions_cmds.rs | 7 ++-- crates/ui-egui/src/actions.rs | 4 +- .../src/discard_ui/tests/targa_tests.rs | 20 +++++++--- crates/ui-egui/src/file_open/tests.rs | 24 +++++++++++ crates/ui-egui/src/lib.rs | 9 ++++- crates/ui-egui/src/targa_options_ui.rs | 15 +++---- crates/ui-egui/src/view_cmds.rs | 40 +++++++++++++------ 7 files changed, 88 insertions(+), 31 deletions(-) diff --git a/crates/engine/src/actions_cmds.rs b/crates/engine/src/actions_cmds.rs index 3ee242d7d6..3b3ffd1f01 100644 --- a/crates/engine/src/actions_cmds.rs +++ b/crates/engine/src/actions_cmds.rs @@ -115,10 +115,11 @@ pub fn replayable(id: &str) -> bool { && (shell_view_command(id) || shell_save_command(id) || crate::commands::find(id).is_some_and(|c| c.journal))) } -/// File › Save and Save As, recorded by the desktop shell once the save has a path (#2032). -/// The shell replays them; batch and droplets write to their destination folder instead. +/// File › Save, Save As and Save a Copy, recorded by the desktop shell once the save has a path +/// (#2032, #4373). The shell replays them; batch and droplets write to their destination folder +/// instead. pub fn shell_save_command(id: &str) -> bool { - matches!(id, "file.save" | "file.saveAs") + matches!(id, "file.save" | "file.saveAs" | "file.saveACopy") } /// View-only menu commands recorded by the desktop shell. Headless playback reports diff --git a/crates/ui-egui/src/actions.rs b/crates/ui-egui/src/actions.rs index 7902a39bba..e0f3713f2e 100644 --- a/crates/ui-egui/src/actions.rs +++ b/crates/ui-egui/src/actions.rs @@ -37,10 +37,12 @@ struct RenameAction { focused: bool, } -fn label_of(id: &str) -> String { +pub(crate) fn label_of(id: &str) -> String { photocraft_engine::commands::find(id) .map(|c| c.label) .or_else(|| crate::menus::UI_COMMANDS.iter().find(|c| c.0 == id).map(|c| c.1)) + // Shell menu items recorded as steps, like Save a Copy (#4373). + .or_else(|| crate::menu_catalog::CATALOG.iter().find(|c| c.3 == id).map(|c| c.1)) .map(|label| label.trim_end_matches('…').to_string()) .unwrap_or_else(|| id.to_string()) } diff --git a/crates/ui-egui/src/discard_ui/tests/targa_tests.rs b/crates/ui-egui/src/discard_ui/tests/targa_tests.rs index e4c83bda64..565fe01037 100644 --- a/crates/ui-egui/src/discard_ui/tests/targa_tests.rs +++ b/crates/ui-egui/src/discard_ui/tests/targa_tests.rs @@ -113,7 +113,7 @@ fn save_a_copy_to_a_targa_asks_and_keeps_the_document_unsaved() { crate::menus::invoke(h.state_mut(), &ctx, "file.saveACopy", json!({})).unwrap(); h.run_steps(3); assert_eq!(h.state().targa_options.as_ref().map(|p| (p.bits, p.copy)), Some((TgaBits::Bits32, true))); - assert!(targa_options_ui::park(h.state_mut(), "other.tga".into(), false, true).is_err(), "the waiting prompt is kept"); + assert!(targa_options_ui::park(h.state_mut(), "other.tga".into(), false, "file.saveAs").is_err(), "the waiting prompt is kept"); assert_eq!(h.state().targa_options.as_ref().map(|p| p.path.as_str()), Some("copy.tga")); h.key_press(Key::Enter); h.run_steps(3); @@ -140,8 +140,8 @@ fn targa_options_keeps_a_layered_save_as_a_copy() { assert_eq!(st.path, None); } -/// An action being recorded keeps a Targa Save As with its bits, answered in Targa Options or -/// scripted (#2032), and plays it back without asking; the dialog's Save a Copy isn't recorded. +/// An action being recorded keeps a Targa Save As or Save a Copy with its bits, answered in Targa +/// Options or scripted (#2032, #4373), and plays them back without asking. #[test] fn recorded_targa_save_as_keeps_its_bits_and_replays_without_asking() { let (mut h, writes) = targa_app(true, "copy.tga"); @@ -164,12 +164,22 @@ fn recorded_targa_save_as_keeps_its_bits_and_replays_without_asking() { &[("t.tga".to_string(), asked(Some(24))), ("copy.tga".to_string(), asked(Some(32))), ("s.tga".to_string(), asked(Some(32)))] ); let steps = &h.state().session.actions.list[0].steps; - assert_eq!(steps, &[("file.saveAs".into(), json!({"path": "t.tga", "tgaBits": 24})), ("file.saveAs".into(), json!({"path": "s.tga", "tgaBits": 32}))]); + assert_eq!( + steps, + &[ + ("file.saveAs".into(), json!({"path": "t.tga", "tgaBits": 24})), + ("file.saveACopy".into(), json!({"path": "copy.tga", "tgaBits": 32})), + ("file.saveAs".into(), json!({"path": "s.tga", "tgaBits": 32})) + ] + ); writes.borrow_mut().clear(); let played = h.state_mut().run("actions.play", json!({"action": 0})).unwrap(); assert!(played.get("failed").is_none(), "{played}"); assert!(h.state().targa_options.is_none(), "playback doesn't ask"); - assert_eq!(writes.borrow().as_slice(), &[("t.tga".to_string(), asked(Some(24))), ("s.tga".to_string(), asked(Some(32)))]); + assert_eq!( + writes.borrow().as_slice(), + &[("t.tga".to_string(), asked(Some(24))), ("copy.tga".to_string(), asked(Some(32))), ("s.tga".to_string(), asked(Some(32)))] + ); } /// Closing an unsaved document whose save goes to a Targa waits behind Targa Options, then closes. diff --git a/crates/ui-egui/src/file_open/tests.rs b/crates/ui-egui/src/file_open/tests.rs index 9a833b7ba1..67887877e1 100644 --- a/crates/ui-egui/src/file_open/tests.rs +++ b/crates/ui-egui/src/file_open/tests.rs @@ -777,6 +777,30 @@ fn a_set_of_background_opens_keeps_its_order_however_they_finish() { assert_eq!(doc_names(&app), ["dropped.psd", "existing.psd", "f0.psd", "f1.psd", "f2.psd", "f3.psd", "late.psd"]); } +/// #4373: Save a Copy is recorded in an action, like Save and Save As, and played back as a copy: +/// the document keeps its own file and unsaved changes. +#[test] +fn save_a_copy_is_recorded_and_replayed_as_a_copy() { + let (mut app, written) = app_with(vec![Some(FileDialogAnswer::SaveTo("/pics/copy.png".into()))]); + let ctx = egui::Context::default(); + app.open_file("/pics/work.pcraft", b"x").unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("actions.record", json!({})).unwrap(); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + menus::invoke(&mut app, &ctx, "file.saveACopy", json!({})).unwrap(); + answer(&mut app); + app.run("actions.stop", json!({})).unwrap(); + assert_eq!(app.session.actions.list[0].steps.last(), Some(&("file.saveACopy".to_string(), json!({"path": "/pics/copy.png"})))); + assert_eq!(crate::actions::label_of("file.saveACopy"), "Save a Copy"); + written.borrow_mut().clear(); + let played = app.run("actions.play", json!({"action": 0})).unwrap(); + assert!(played.get("failed").is_none(), "{played}"); + assert_eq!(written.borrow().iter().map(|(p, _)| p.as_str()).collect::>(), ["/pics/copy.png"]); + let st = app.session.active().unwrap(); + assert_eq!(st.path.as_deref(), Some("/pics/work.pcraft"), "the document keeps its file"); + assert!(st.is_dirty(), "and its unsaved changes"); +} + /// #4400: a new document saved under a name is listed in Open Recent (and on the Home screen), /// as opening it is; a Save a Copy isn't, since the document doesn't live there. #[test] diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index e599845669..96158c024e 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1288,7 +1288,7 @@ impl PhotocraftApp { // which records the step once answered. if tga_bits.is_none() && targa_options_ui::wants_prompt(self, &path) { let copy = self.saves_copy(&path, None)?; - targa_options_ui::park(self, path.clone(), copy, true)?; + targa_options_ui::park(self, path.clone(), copy, "file.saveAs")?; return Ok(serde_json::json!({"path": path, "warnings": []})); } // A layered TIFF asks about its layers first (Preferences › File Handling); the save @@ -1325,7 +1325,7 @@ impl PhotocraftApp { Ok(r) } - /// Replays a recorded `file.save` / `file.saveAs` step: no dialog or prompt, and the + /// Replays a recorded `file.save` / `file.saveAs` / `file.saveACopy` step: no dialog or prompt, and the /// recorded TIFF or Targa answer (if any) stands in for the TIFF or Targa Options prompt. pub(crate) fn replay_save(&mut self, id: &str, params: &Value) -> Result { if self.save_options_open() { @@ -1344,6 +1344,11 @@ impl PhotocraftApp { } let path = params.get("path").and_then(Value::as_str).filter(|p| !p.is_empty()).ok_or("Save As needs a `path`")?; let tga_bits = targa_options_ui::bits_param(params, id)?; + if id == "file.saveACopy" { + // A copy: the document keeps its own file and unsaved state, as when recorded (#4373). + let doc = self.session.active().ok_or("no document")?.doc.clone(); + return crate::view_cmds::write_copy(self, &doc, path, tga_bits); + } self.save_as_step(path.to_string(), params.get("tiffLayers").and_then(Value::as_bool), tga_bits) } diff --git a/crates/ui-egui/src/targa_options_ui.rs b/crates/ui-egui/src/targa_options_ui.rs index afc7f60ba2..c2161a0c9b 100644 --- a/crates/ui-egui/src/targa_options_ui.rs +++ b/crates/ui-egui/src/targa_options_ui.rs @@ -20,9 +20,10 @@ pub struct Prompt { pub bits: TgaBits, /// Save a Copy: the document keeps its path and unsaved changes. pub copy: bool, - /// File › Save As: the answered save is recorded as a `file.saveAs` step, so an action being - /// recorded keeps it (#2032). The dialog's Save a Copy isn't recorded. - pub record: bool, + /// The step the answered save is recorded as, so an action being recorded keeps it: + /// `file.saveAs` for Save As (#2032, even when a flat Targa is written as a copy) and + /// `file.saveACopy` for Save a Copy (#4373). + pub record: &'static str, } /// `true` when `path` names a Targa (`.tga`, and the rarer `.icb`, `.vda`, `.vst`). @@ -43,7 +44,7 @@ pub fn bits_param(params: &serde_json::Value, cmd: &str) -> Result Result<(), String> { +pub fn park(app: &mut PhotocraftApp, path: String, copy: bool, record: &'static str) -> Result<(), String> { if app.save_options_open() { return Err("Answer TIFF or Targa Options before starting another save".into()); } @@ -80,9 +81,9 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { let settings = ExportSettings { tga_bits: Some(p.bits), ..app.save_settings() }; let step = serde_json::json!({"path": p.path, "tgaBits": p.bits.bits()}); let written = app.with_document(p.doc, |app| app.write_document(p.path, &settings, p.copy)); - if written.is_ok() && p.record { - // An action being recorded keeps the Save As with this answer (#2032). - app.session.journal.push(("file.saveAs".into(), step)); + if written.is_ok() { + // An action being recorded keeps the Save As or Save a Copy with this answer (#2032). + app.session.journal.push((p.record.into(), step)); } match written { Err(e) => { diff --git a/crates/ui-egui/src/view_cmds.rs b/crates/ui-egui/src/view_cmds.rs index 585e5dd074..09d759ed45 100644 --- a/crates/ui-egui/src/view_cmds.rs +++ b/crates/ui-egui/src/view_cmds.rs @@ -1387,7 +1387,8 @@ fn front(app: &mut PhotocraftApp, id: &str, params: &Value) -> Option Result { let doc = app.session.active().ok_or("no document")?.doc.clone(); let stem = doc.name.rsplit_once('.').map_or(doc.name.as_str(), |(a, _)| a); @@ -1398,27 +1399,40 @@ fn save_a_copy(app: &mut PhotocraftApp) -> Result { let parked = app.with_document(doc.id, |app| { let ask = crate::targa_options_ui::wants_prompt(app, &path); if ask { - crate::targa_options_ui::park(app, path.clone(), true, false)?; + crate::targa_options_ui::park(app, path.clone(), true, "file.saveACopy")?; } Ok(ask) })?; if parked { return Ok(json!({"path": path, "warnings": []})); } - let settings = app.save_settings(); - let export = app.services.export.as_ref().ok_or("no exporter configured")?; - let (bytes, warnings) = export(&doc, &path, &settings)?; - let write = app.services.write.as_mut().ok_or("no writer configured")?; - write(&path, &bytes)?; - let template = "Saved a copy as {path}"; - app.ui.status = crate::i18n::fmt(tl!(template), &[("path", &path)]); - app.ui.status_error = false; - let what = crate::i18n::fmt(tl!(template), &[("path", &crate::file_open::display_name(&path))]); - crate::notices::io_warnings(app, &what, &warnings); - Ok(json!({"path": path, "warnings": warnings})) + let r = write_copy(app, &doc, &path, None)?; + app.session.journal.push(("file.saveACopy".into(), json!({"path": path}))); + Ok(r) }) } +/// Writes `doc` to `path` as a copy (Save a Copy, and its replayed action step): the document's +/// path and saved state are untouched. `tga_bits` is the Targa answer, when there is one. +pub(crate) fn write_copy( + app: &mut PhotocraftApp, + doc: &photocraft_doc::Document, + path: &str, + tga_bits: Option, +) -> Result { + let settings = crate::ExportSettings { tga_bits, ..app.save_settings() }; + let export = app.services.export.as_ref().ok_or("no exporter configured")?; + let (bytes, warnings) = export(doc, path, &settings)?; + let write = app.services.write.as_mut().ok_or("no writer configured")?; + write(path, &bytes)?; + let template = "Saved a copy as {path}"; + app.ui.status = crate::i18n::fmt(tl!(template), &[("path", path)]); + app.ui.status_error = false; + let what = crate::i18n::fmt(tl!(template), &[("path", &crate::file_open::display_name(path))]); + crate::notices::io_warnings(app, &what, &warnings); + Ok(json!({"path": path, "warnings": warnings})) +} + /// Layer › Smart Objects › Export Contents: saves the contents file under its own name by default. fn export_contents(app: &mut PhotocraftApp) -> Result { let st = app.session.active().ok_or("no document")?;