From 42e4af641634b57fd4c7f3a001d340a0a1063f9f Mon Sep 17 00:00:00 2001 From: Valentin Klein Date: Sun, 11 Oct 2026 14:20:15 +0200 Subject: [PATCH 1/4] Tools: Frame tool (#2914) (#2915) The Frame tool (K, its own toolbar slot after the Crop group) draws a rectangular or elliptical frame; the options bar picks the shape, Shift constrains to a square or circle and Alt draws from the centre. A frame drawn over the selected pixel layer's content takes that layer in; otherwise it is an empty frame. Frames are built as Frame from Layers builds them: a group clipped by a layer mask (rectangular or anti-aliased elliptical). The new engine command layer.new.frame does it in one Session::edit, so one undo step. Co-authored-by: Claude Opus 5.5 --- ATTRIBUTION.md | 3 +- README.md | 4 +- assets/icons/frame-placeholder.svg | 15 +++ crates/engine/src/frame_cmds.rs | 144 +++++++++++++++++++-- crates/ui-egui/src/canvas.rs | 5 + crates/ui-egui/src/frame_tool.rs | 187 ++++++++++++++++++++++++++++ crates/ui-egui/src/i18n/cs.tsv | 3 + crates/ui-egui/src/i18n/de.tsv | 3 + crates/ui-egui/src/i18n/el.tsv | 3 + crates/ui-egui/src/i18n/es.tsv | 3 + crates/ui-egui/src/i18n/fr.tsv | 3 + crates/ui-egui/src/i18n/id.tsv | 3 + crates/ui-egui/src/i18n/it.tsv | 3 + crates/ui-egui/src/i18n/ja.tsv | 3 + crates/ui-egui/src/i18n/ko.tsv | 3 + crates/ui-egui/src/i18n/nl.tsv | 3 + crates/ui-egui/src/i18n/pl.tsv | 3 + crates/ui-egui/src/i18n/pt-br.tsv | 3 + crates/ui-egui/src/i18n/ru.tsv | 3 + crates/ui-egui/src/i18n/uk.tsv | 3 + crates/ui-egui/src/i18n/zh-hans.tsv | 3 + crates/ui-egui/src/i18n/zh-hant.tsv | 3 + crates/ui-egui/src/icon_data.rs | 1 + crates/ui-egui/src/icons.rs | 1 + crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/panels.rs | 2 + crates/ui-egui/src/state.rs | 13 +- crates/ui-egui/src/tool_reset.rs | 3 +- docs/gaps.md | 9 +- docs/target-app-parity.md | 2 +- docs/ui-parity.md | 2 +- 31 files changed, 415 insertions(+), 25 deletions(-) create mode 100644 assets/icons/frame-placeholder.svg create mode 100644 crates/ui-egui/src/frame_tool.rs diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 8f3803e76a..004d056393 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -20,7 +20,7 @@ next to them. | `crates/ui-egui/src/i18n/uk.tsv` | Ukrainian UI translations | PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) | | `assets/fonts/Inter-Regular.ttf`, `Inter-Medium.ttf`, `Inter-SemiBold.ttf` | Inter 4.001 (UI font) | The Inter Project Authors (Rasmus Andersson) | | SIL OFL 1.1, [`assets/fonts/OFL-Inter.txt`](assets/fonts/OFL-Inter.txt) | | `assets/fonts/JetBrainsMono-Regular.ttf` | JetBrains Mono 2.305 (numeric font) | The JetBrains Mono Project Authors | | SIL OFL 1.1, [`assets/fonts/OFL-JetBrainsMono.txt`](assets/fonts/OFL-JetBrainsMono.txt) | -| `assets/icons/*.svg` except `slice-knife.svg`, `artboard.svg`, `perspective-crop.svg`, `type-mask.svg`, `type-mask-vertical.svg`, `clip-below.svg`, `clip-release.svg`, `layer-mask.svg`, `adjustment-layer.svg`, `brush-replace.svg`, `eraser-background.svg`, `eraser-magic.svg`, `lasso-magnetic.svg`, `direct-select.svg`, `pen-add-anchor.svg`, `pen-delete-anchor.svg`, `pen-freeform.svg`, `pen-curvature.svg`, `bandage-sparkle.svg`, `painting-symmetry.svg`, `symmetry-*.svg` and `marquee-{row,column}.svg` (112 files; `star-filled.svg` is `star.svg` with a solid fill) | Lucide icons | Lucide Icons and Contributors | (`icons/.svg`; `align-*` are now named `text-align-*` upstream) | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) | +| `assets/icons/*.svg` except `slice-knife.svg`, `artboard.svg`, `perspective-crop.svg`, `frame-placeholder.svg`, `type-mask.svg`, `type-mask-vertical.svg`, `clip-below.svg`, `clip-release.svg`, `layer-mask.svg`, `adjustment-layer.svg`, `brush-replace.svg`, `eraser-background.svg`, `eraser-magic.svg`, `lasso-magnetic.svg`, `direct-select.svg`, `pen-add-anchor.svg`, `pen-delete-anchor.svg`, `pen-freeform.svg`, `pen-curvature.svg`, `bandage-sparkle.svg`, `painting-symmetry.svg`, `symmetry-*.svg` and `marquee-{row,column}.svg` (112 files; `star-filled.svg` is `star.svg` with a solid fill) | Lucide icons | Lucide Icons and Contributors | (`icons/.svg`; `align-*` are now named `text-align-*` upstream) | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) | | `assets/icons/{check,chevron-down,chevron-right,chevron-up,chevrons-left,chevrons-right,circle,clock,compass,info,link,link-2,lock,minus,monitor,moon,move,navigation,plus,search,square,trash,triangle,type,x,zoom-in}.svg` | Lucide icons derived from Feather (subset of the row above) | Cole Bemis (Feather), Lucide Contributors | via Lucide | MIT (Feather) and ISC (Lucide), [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) | | `assets/icons/slice-knife.svg` | Slice tool glyph | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | | `assets/icons/artboard.svg` | Artboard tool glyph: a board with a tick at each end of its edges | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | @@ -29,6 +29,7 @@ next to them. | `assets/icons/marquee-row.svg`, `assets/icons/marquee-column.svg` | Single Row and Single Column Marquee tool glyphs: a dashed row (column) between two edge bars, drawn on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | | `assets/icons/clip-below.svg`, `assets/icons/clip-release.svg` | Clipping-mask cursors (⌥ over the line between two layers): a hooked arrow onto the layer below; the same with a small "no" badge to release | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | | `assets/icons/layer-mask.svg`, `assets/icons/adjustment-layer.svg` | Layers panel footer glyphs: Add a mask (a frame around a solid disc) and New Fill or Adjustment Layer (a circle, one half solid), drawn on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | +| `assets/icons/frame-placeholder.svg` | Frame tool glyph: an empty placeholder frame, crossed corner to corner | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | | `assets/icons/eraser-background.svg`, `assets/icons/eraser-magic.svg` | Background Eraser and Magic Eraser tool glyphs: Lucide `eraser` plus added marks | Lucide Icons and Contributors; marks by PhotoCraft contributors | Derived from `icons/eraser.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) | | `assets/icons/brush-replace.svg` | Color Replacement tool glyph: Lucide `brush` plus two swap arrows | Lucide Icons and Contributors; arrows by PhotoCraft contributors | Derived from `icons/brush.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) | | `assets/icons/bandage-sparkle.svg` | Remove tool glyph: Lucide `bandage` moved down, plus a sparkle mark | Lucide Icons and Contributors; mark by PhotoCraft contributors | Derived from `icons/bandage.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) | diff --git a/README.md b/README.md index a9a67182a5..249d165cc9 100644 --- a/README.md +++ b/README.md @@ -178,8 +178,8 @@ Every screenshot here is the real app at work on public-domain art, rendered off
-

🧰 64 tools

- Move · Artboard · Rectangular and Elliptical Marquee · Single Row Marquee · Single Column Marquee · Lasso · Polygonal Lasso · Magnetic Lasso · Object Selection · Quick Selection · Magic Wand · Crop · Perspective Crop · Slice · Slice Select · Eyedropper · Ruler · Note · Count · Remove · Spot Healing Brush · Healing Brush · Patch · Content-Aware Move · Red Eye · Brush · Pencil · Mixer Brush · Color Replacement · Clone Stamp · Pattern Stamp · History Brush · Eraser · Background Eraser · Magic Eraser · Gradient · Paint Bucket · Blur · Sharpen · Smudge · Dodge · Burn · Sponge · Pen · Freeform Pen · Curvature Pen · Add Anchor Point · Delete Anchor Point · Horizontal and Vertical Type · Horizontal and Vertical Type Mask · Path Selection · Direct Selection · Rectangle · Ellipse · Triangle · Polygon · Line · Custom Shape · Hand · Rotate View · Zoom +

🧰 65 tools

+ Move · Artboard · Rectangular and Elliptical Marquee · Single Row Marquee · Single Column Marquee · Lasso · Polygonal Lasso · Magnetic Lasso · Object Selection · Quick Selection · Magic Wand · Crop · Perspective Crop · Slice · Slice Select · Frame · Eyedropper · Ruler · Note · Count · Remove · Spot Healing Brush · Healing Brush · Patch · Content-Aware Move · Red Eye · Brush · Pencil · Mixer Brush · Color Replacement · Clone Stamp · Pattern Stamp · History Brush · Eraser · Background Eraser · Magic Eraser · Gradient · Paint Bucket · Blur · Sharpen · Smudge · Dodge · Burn · Sponge · Pen · Freeform Pen · Curvature Pen · Add Anchor Point · Delete Anchor Point · Horizontal and Vertical Type · Horizontal and Vertical Type Mask · Path Selection · Direct Selection · Rectangle · Ellipse · Triangle · Polygon · Line · Custom Shape · Hand · Rotate View · Zoom

🖌️ A real brush engine

diff --git a/assets/icons/frame-placeholder.svg b/assets/icons/frame-placeholder.svg new file mode 100644 index 0000000000..d765639bfd --- /dev/null +++ b/assets/icons/frame-placeholder.svg @@ -0,0 +1,15 @@ + + + + + diff --git a/crates/engine/src/frame_cmds.rs b/crates/engine/src/frame_cmds.rs index 739715e57a..75c24df7c1 100644 --- a/crates/engine/src/frame_cmds.rs +++ b/crates/engine/src/frame_cmds.rs @@ -2,9 +2,11 @@ //! hold an image (or placeholder) that is cropped to the frame. We build it from existing //! primitives: group the selected layers, then clip the group with a rectangular layer mask the //! size of their bounds — the same visual result Photoshop's Frame tool produces for this command. -//! Headless and scriptable like every other command. +//! `layer.new.frame` is the Frame tool's (K) command: a rectangular or elliptical frame drawn on +//! the canvas, empty or holding the pixel layer it was drawn over. Headless and scriptable like +//! every other command. -use photocraft_doc::{LayerId, LayerMask, PixelFormat}; +use photocraft_doc::{Layer, LayerContent, LayerId, LayerMask, PixelFormat}; use photocraft_geom::Rect; use serde_json::{Value, json}; @@ -74,17 +76,106 @@ fn frame_group(s: &mut Session, grouped: &Value) -> Result { Ok(json!({"layer": gid.0, "frame": [rect.x0, rect.y0, rect.width(), rect.height()]})) } +/// The largest frame side (px) `layer.new.frame` accepts, as Photoshop's canvas limit. +const MAX_FRAME_SIDE: i32 = 300_000; + +/// A reveal mask that is on inside the ellipse inscribed in `rect` and off everywhere else, with +/// 4x4-supersampled edges (as the Elliptical Marquee). Only pixels inside `area` are written. +fn ellipse_mask(rect: Rect, area: Rect) -> LayerMask { + let mut mask = LayerMask::hide_all(); + let (cx, cy) = ((f64::from(rect.x0) + f64::from(rect.x1)) / 2.0, (f64::from(rect.y0) + f64::from(rect.y1)) / 2.0); + let (rx, ry) = (f64::from(rect.width().max(1)) / 2.0, f64::from(rect.height().max(1)) / 2.0); + let inside = |x: f64, y: f64| { + let (dx, dy) = ((x - cx) / rx, (y - cy) / ry); + dx * dx + dy * dy <= 1.0 + }; + let cut = rect.intersect(&area); + for y in cut.y0..cut.y1 { + for x in cut.x0..cut.x1 { + let (fx, fy) = (f64::from(x), f64::from(y)); + let n = (0..16).filter(|i| inside(fx + (f64::from(i % 4) + 0.5) / 4.0, fy + (f64::from(i / 4) + 0.5) / 4.0)).count(); + if n > 0 { + mask.surface.write_pixel(x, y, &[n as f32 / 16.0]); + } + } + } + mask.surface.prune(); + mask +} + +/// Frame tool (K): a new frame — a group clipped to the drawn rectangle or ellipse — as one +/// history step. With `layer` (a pixel layer, not the Background), that layer becomes the frame's +/// content, as when a frame is drawn over a selected pixel layer in Photoshop; else it is empty. +fn new_frame(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "layer.new.frame"; + let bad = |msg: String| EngineError::BadParams { cmd: CMD.into(), msg }; + let get = |k: &str| crate::commands::int_i32(CMD, p, k)?.ok_or_else(|| bad(format!("missing `{k}`"))); + let (x, y, w, h) = (get("x")?, get("y")?, get("width")?, get("height")?); + if !(1..=MAX_FRAME_SIDE).contains(&w) || !(1..=MAX_FRAME_SIDE).contains(&h) { + return Err(bad(format!("`width` and `height` must be 1..={MAX_FRAME_SIDE}"))); + } + let (Some(x1), Some(y1)) = (x.checked_add(w), y.checked_add(h)) else { + return Err(bad("the frame is outside the 32-bit coordinate range".into())); + }; + let rect = Rect::new(x, y, x1, y1); + let ellipse = match p.get("shape").map(|v| v.as_str()) { + None | Some(Some("rectangle")) => false, + Some(Some("ellipse")) => true, + Some(_) => return Err(bad("`shape` must be \"rectangle\" or \"ellipse\"".into())), + }; + let content = match p.get("layer") { + None | Some(Value::Null) => None, + Some(v) => Some(LayerId(v.as_u64().ok_or_else(|| bad(format!("`layer` = {v} is not a layer id")))?)), + }; + let name = p.get("name").and_then(Value::as_str).map(str::to_string); + let gid = s.edit("New Frame", |doc, active| { + let mask = if ellipse { ellipse_mask(rect, doc.bounds()) } else { clip_mask(rect.intersect(&doc.bounds())) }; + let name = name.unwrap_or_else(|| doc.next_layer_name("Frame")); + let gid = match content { + Some(id) => { + let l = doc.layer(id).ok_or(EngineError::NoLayer(id))?; + if !matches!(l.content, LayerContent::Raster(_)) || crate::extra_cmds::is_background(l) { + return Err(bad("only a pixel layer (not the Background) can go in a frame".into())); + } + let gid = doc.insert_above(Some(id), Layer::group(name, vec![])); + let child = doc.remove(id).ok_or(EngineError::NoLayer(id))?; + doc.layer_mut(gid).and_then(Layer::children_mut).ok_or(EngineError::NoLayer(gid))?.push(child); + crate::layer_multi_cmds::check_group_depth(doc, "New Frame")?; + gid + } + None => doc.insert_above(*active, Layer::group(name, vec![])), + }; + doc.layer_mut(gid).ok_or(EngineError::NoLayer(gid))?.mask = Some(mask); + *active = Some(gid); + Ok(gid) + })?; + crate::layer_multi_cmds::reselect(s, vec![gid], Some(gid)); + Ok(json!({"layer": gid.0, "frame": [x, y, w, h], "shape": if ellipse { "ellipse" } else { "rectangle" }})) +} + pub fn specs() -> Vec { - vec![CommandSpec { - id: "layer.new.frameFromLayers", - label: "Frame from Layers", - menu: &["Layer", "New"], - shortcut: None, - params: r#"{"name":str?} → {layer, frame:[x,y,w,h]}: groups the selected layers and clips them to a frame rect"#, - enabled: has_layer, - journal: true, - run: |s, p| frame_from_layers(s, p), - }] + vec![ + CommandSpec { + id: "layer.new.frame", + label: "New Frame", + menu: &[], + shortcut: None, + params: r#"{"x":i32,"y":i32,"width":u32,"height":u32,"shape":"rectangle|ellipse"="rectangle","layer":id?,"name":str?} → {layer, frame:[x,y,w,h], shape}: Frame tool; a group clipped to the shape, holding pixel layer `layer` if given"#, + enabled: |s| s.active().map(|_| ()).ok_or_else(|| "no document open".into()), + journal: true, + run: new_frame, + }, + CommandSpec { + id: "layer.new.frameFromLayers", + label: "Frame from Layers", + menu: &["Layer", "New"], + shortcut: None, + params: r#"{"name":str?} → {layer, frame:[x,y,w,h]}: groups the selected layers and clips them to a frame rect"#, + enabled: has_layer, + journal: true, + run: |s, p| frame_from_layers(s, p), + }, + ] } #[cfg(test)] @@ -151,6 +242,35 @@ mod tests { assert!(s.active().unwrap().doc.layer(gid).is_some_and(|g| g.mask.is_some()), "redo brings back the framed group"); } + /// Frame tool: a rectangular frame is an empty group clipped to the drawn rect, undone in one + /// step; an elliptical one hides the corners; drawn over a pixel layer, it holds that layer. + #[test] + fn new_frame_clips_a_group_to_the_drawn_shape() { + let (mut s, a, _) = session(); + let count = |s: &Session| s.active().unwrap().doc.layers.len(); + let before = count(&s); + let r = s.execute("layer.new.frame", json!({"x": 10, "y": 10, "width": 40, "height": 30})).unwrap(); + let gid = LayerId(r["layer"].as_u64().unwrap()); + let st = s.active().unwrap(); + let g = st.doc.layer(gid).unwrap(); + assert!(matches!(&g.content, LayerContent::Group(c) if c.children.is_empty()), "an empty frame"); + let m = g.mask.as_ref().unwrap(); + assert_eq!((m.value(10, 10), m.value(49, 39), m.value(9, 10), m.value(50, 39)), (1.0, 1.0, 0.0, 0.0)); + assert_eq!((g.name.as_str(), st.active_layer), ("Frame 1", Some(gid))); + assert!(s.undo()); + assert_eq!(count(&s), before, "one undo removes the frame"); + + let r = s.execute("layer.new.frame", json!({"x": 10, "y": 10, "width": 40, "height": 30, "shape": "ellipse", "layer": a.0})).unwrap(); + let gid = LayerId(r["layer"].as_u64().unwrap()); + let g = s.active().unwrap().doc.layer(gid).unwrap(); + assert!(matches!(&g.content, LayerContent::Group(c) if c.children.iter().map(|l| l.id).eq([a])), "the frame holds layer A"); + let m = g.mask.as_ref().unwrap(); + assert_eq!((m.value(30, 25), m.value(10, 10)), (1.0, 0.0), "centre shown, corner hidden"); + for bad in [json!({"x": 0, "y": 0, "width": 0, "height": 5}), json!({"x": 0, "y": 0, "width": 5, "height": 5, "shape": "star"}), json!({"x": 0})] { + assert!(s.execute("layer.new.frame", bad).is_err()); + } + } + #[test] fn needs_a_selected_layer() { let mut s = Session::new(); diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 7d5ac68c94..b99b8780e6 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -3147,6 +3147,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: crate::analysis_ui::draw_overlay(app, &painter, &xf); crate::gradient_ui::draw_overlay(app, &painter, &xf); crate::slice_ui::draw_overlay(app, &painter, &xf); + crate::frame_tool::draw_overlay(app, &painter, &xf); crate::artboard_tool::draw_overlay(app, &painter, &xf); // Tool cursors (Photoshop-style). let guide_hover = response.hover_pos().and_then(|p| { @@ -4194,6 +4195,10 @@ pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) if crate::slice_ui::pointer(app, ev, mods) { return; } + // Frame tool: draw rectangular and elliptical frames. + if crate::frame_tool::pointer(app, ev, mods) { + return; + } // Artboard tool: draw, select, move and resize boards. if crate::artboard_tool::pointer(app, ev, mods) { return; diff --git a/crates/ui-egui/src/frame_tool.rs b/crates/ui-egui/src/frame_tool.rs new file mode 100644 index 0000000000..28eb556282 --- /dev/null +++ b/crates/ui-egui/src/frame_tool.rs @@ -0,0 +1,187 @@ +//! Frame tool (K): drag on the canvas to draw a rectangular or elliptical frame (the options bar +//! picks the shape). ⇧ makes it a square or circle, ⌥ draws it from the centre. Drawn over the +//! selected pixel layer's content, the frame takes that layer in, as in Photoshop; else it is an +//! empty placeholder. Each frame is one engine command (`layer.new.frame`), so one undo step; this +//! module only turns the drag into it. + +use egui::{Pos2, Stroke}; +use photocraft_doc::LayerContent; +use serde::{Deserialize, Serialize}; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, ViewXform}; +use crate::state::Tool; +use crate::theme::Tokens; + +/// A press that moves less than this (screen points) is a click, not a drawn frame. +const CLICK_PX: f64 = 3.0; + +/// Frame tool state (serde: readable and settable through the control channel). +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct FrameToolUi { + /// Options bar: draw elliptical frames (else rectangular). + pub ellipse: bool, + /// The drag in progress: press and current point (document pixels), ⇧ and ⌥ at the last event. + #[serde(skip)] + pub drag: Option, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct FrameDrag { + pub start: [f64; 2], + pub cur: [f64; 2], + pub square: bool, + pub centred: bool, +} + +/// The frame a drag leaves, `[x0, y0, x1, y1]` on whole pixels. +fn drawn(d: &FrameDrag) -> [i64; 4] { + let (mut dx, mut dy) = (d.cur[0] - d.start[0], d.cur[1] - d.start[1]); + if d.square { + let side = dx.abs().max(dy.abs()); + (dx, dy) = (side.copysign(dx), side.copysign(dy)); + } + let (a, b) = + if d.centred { ([d.start[0] - dx, d.start[1] - dy], [d.start[0] + dx, d.start[1] + dy]) } else { (d.start, [d.start[0] + dx, d.start[1] + dy]) }; + [a[0].min(b[0]), a[1].min(b[1]), a[0].max(b[0]), a[1].max(b[1])].map(|v| v.round() as i64) +} + +/// The selected pixel layer the frame `r` takes in: one whose content it overlaps and that can +/// move (not the Background or a position-locked layer). +fn content_layer(app: &PhotocraftApp, r: [i64; 4]) -> Option { + let st = app.session.active()?; + let l = st.doc.layer(st.active_layer?)?; + if !matches!(l.content, LayerContent::Raster(_)) || l.locks.position || l.locks.all { + return None; + } + let b = l.surface()?.content_bounds(); + let overlaps = i64::from(b.x0) < r[2] && r[0] < i64::from(b.x1) && i64::from(b.y0) < r[3] && r[1] < i64::from(b.y1); + (!b.is_empty() && overlaps).then_some(l.id.0) +} + +/// Pointer input for the Frame tool. Returns true when the event was its own. +pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> bool { + if app.ui.tool != Tool::Frame { + return false; + } + let (square, centred) = (mods.shift, mods.alt); + match ev { + ToolEvent::Down { x, y, .. } => { + if app.session.active().is_some() { + app.ui.frame_tool.drag = Some(FrameDrag { start: [x, y], cur: [x, y], square, centred }); + } + } + ToolEvent::Move { x, y, .. } => { + if let Some(d) = &mut app.ui.frame_tool.drag { + *d = FrameDrag { cur: [x, y], square, centred, ..*d }; + } + } + ToolEvent::Up { x, y } => { + let Some(mut d) = app.ui.frame_tool.drag.take() else { return true }; + d.cur = [x, y]; + let screen = (d.cur[0] - d.start[0]).hypot(d.cur[1] - d.start[1]) * f64::from(app.point_zoom()); + let r = drawn(&d); + if screen < CLICK_PX || r[2] <= r[0] || r[3] <= r[1] { + return true; + } + let mut p = json!({ + "x": r[0], "y": r[1], "width": r[2] - r[0], "height": r[3] - r[1], + "shape": if app.ui.frame_tool.ellipse { "ellipse" } else { "rectangle" }, + }); + if let Some(id) = content_layer(app, r) { + p["layer"] = json!(id); + } + if let Err(e) = app.run("layer.new.frame", p) { + app.ui.status = e; + app.ui.status_error = true; + } + } + } + true +} + +/// The frame a drag in progress would leave. +pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform) { + let Some(d) = app.ui.frame_tool.drag.filter(|_| app.ui.tool == Tool::Frame) else { return }; + let t = Tokens::get(painter.ctx()); + let r = drawn(&d).map(|v| v as f32); + let stroke = Stroke::new(1.5, t.accent); + let points: Vec = if app.ui.frame_tool.ellipse { + let (cx, cy, rx, ry) = ((r[0] + r[2]) / 2.0, (r[1] + r[3]) / 2.0, (r[2] - r[0]) / 2.0, (r[3] - r[1]) / 2.0); + (0..=64).map(|i| i as f32 * std::f32::consts::TAU / 64.0).map(|a| xf.to_screen(cx + rx * a.cos(), cy + ry * a.sin())).collect() + } else { + [(r[0], r[1]), (r[2], r[1]), (r[2], r[3]), (r[0], r[3]), (r[0], r[1])].into_iter().map(|(x, y)| xf.to_screen(x, y)).collect() + }; + painter.add(egui::Shape::line(points, stroke)); +} + +/// The Frame tool's options bar: Create a new rectangular frame / elliptical frame. +pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bool { + if tool != Tool::Frame { + return false; + } + let ellipse = app.ui.frame_tool.ellipse; + if crate::icons::button(ui, "square", 24.0, !ellipse, tl!("Create a new rectangular frame")).clicked() { + app.ui.frame_tool.ellipse = false; + } + if crate::icons::button(ui, "circle", 24.0, ellipse, tl!("Create a new elliptical frame")).clicked() { + app.ui.frame_tool.ellipse = true; + } + true +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::canvas::tool_event; + use photocraft_doc::LayerId; + + fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2]) { + let m = egui::Modifiers::NONE; + tool_event(app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, m); + tool_event(app, ToolEvent::Move { x: to[0], y: to[1], pressure: 1.0 }, m); + tool_event(app, ToolEvent::Up { x: to[0], y: to[1] }, m); + } + + /// K picks the Frame tool; a rectangular drag makes one frame (one undo step) clipped to the + /// drawn rect; with the elliptical button the frame's corners are hidden. + #[test] + fn frame_tool_draws_rectangular_and_elliptical_frames() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.sync_views(); + app.ui.extras.snap = false; + let ctx = egui::Context::default(); + let raw = egui::RawInput { + events: vec![egui::Event::Key { key: egui::Key::K, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }], + ..Default::default() + }; + ctx.begin_pass(raw); + crate::shortcuts::handle(&mut app, &ctx); + ctx.end_pass().textures_delta.clear(); + assert_eq!(app.ui.tool, Tool::Frame); + + let frame = |app: &PhotocraftApp| { + let st = app.session.active().unwrap(); + let l = st.doc.layer(st.active_layer.unwrap()).unwrap(); + assert!(matches!(l.content, LayerContent::Group(_)) && l.name.starts_with("Frame"), "the new frame is selected"); + (l.id, l.mask.clone().unwrap()) + }; + let layers = app.session.active().unwrap().doc.layers.len(); + drag(&mut app, [20.0, 30.0], [120.0, 110.0]); + let (_, m) = frame(&app); + assert_eq!((m.value(20, 30), m.value(119, 109), m.value(19, 30), m.value(120, 109)), (1.0, 1.0, 0.0, 0.0)); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().doc.layers.len(), layers, "one undo takes the frame back"); + + app.ui.frame_tool.ellipse = true; + drag(&mut app, [20.0, 30.0], [120.0, 110.0]); + let (id, m): (LayerId, _) = frame(&app); + assert_eq!((m.value(70, 70), m.value(20, 30)), (1.0, 0.0), "centre shown, corner hidden"); + // A click draws nothing. + drag(&mut app, [300.0, 250.0], [300.0, 250.0]); + assert_eq!(frame(&app).0, id); + } +} diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index ddb81bd480..02e36d68ab 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -2496,6 +2496,9 @@ cameraData Lens Objektiv Previous Document Předchozí dokument W x H x Resolution Š x V x Rozlišení Front Image Přední obraz + Frame Tool Nástroj rámeček + Create a new rectangular frame Vytvořit nový obdélníkový rámeček + Create a new elliptical frame Vytvořit nový eliptický rámeček Include in playback Zahrnout do přehrávání Perspective Crop Tool Nástroj perspektivní oříznutí Show Grid Zobrazit mřížku diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 3f5e126f5a..d5fe68f514 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -2529,6 +2529,9 @@ cameraData Lens Objektiv Previous Document Vorheriges Dokument W x H x Resolution B x H x Auflösung Front Image Vorderes Bild + Frame Tool Rahmenwerkzeug + Create a new rectangular frame Neuen rechteckigen Rahmen erstellen + Create a new elliptical frame Neuen elliptischen Rahmen erstellen Include in playback In Wiedergabe einbeziehen Perspective Crop Tool Perspektivisches Freistellungswerkzeug Show Grid Raster einblenden diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index f9e9fbd626..3b0c12a11b 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -3593,6 +3593,9 @@ cameraData Lens Φακός Previous Document Προηγούμενο έγγραφο W x H x Resolution Π x Υ x Ανάλυση Front Image Μπροστινή εικόνα + Frame Tool Εργαλείο πλαισίου + Create a new rectangular frame Δημιουργία νέου ορθογώνιου πλαισίου + Create a new elliptical frame Δημιουργία νέου ελλειπτικού πλαισίου Include in playback Συμπερίληψη στην αναπαραγωγή Perspective Crop Tool Περικοπή προοπτικής (Perspective Crop Tool) Drag a box or click four corners · drag the corners onto the edges of a skewed shape · {commit} commits · Esc cancels Σύρετε ένα πλαίσιο ή κάντε κλικ σε τέσσερις γωνίες · σύρετε τις γωνίες στις άκρες ενός λοξού σχήματος · {commit} για εφαρμογή · Esc για ακύρωση diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index d03df25877..df6dfd2aa0 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -2570,6 +2570,9 @@ cameraData Lens Objetivo Previous Document Documento anterior W x H x Resolution An. x Al. x Resolución Front Image Imagen frontal + Frame Tool Herramienta Marco + Create a new rectangular frame Crear un marco rectangular nuevo + Create a new elliptical frame Crear un marco elíptico nuevo Include in playback Incluir en la reproducción Perspective Crop Tool Herramienta Recortar con perspectiva Show Grid Mostrar cuadrícula diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index b1180f6c47..3dbc15e6cf 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -2907,6 +2907,9 @@ cameraData Lens Objectif Previous Document Document précédent W x H x Resolution L x H x Résolution Front Image Image de premier plan + Frame Tool Outil Cadre + Create a new rectangular frame Créer un cadre rectangulaire + Create a new elliptical frame Créer un cadre elliptique Include in playback Inclure dans la lecture Perspective Crop Tool Outil Recadrage perspective Show Grid Afficher la grille diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 2e0804bc0a..6083c94dcc 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -2894,6 +2894,9 @@ cameraData Lens Lensa Previous Document Dokumen Sebelumnya W x H x Resolution L x T x Resolusi Front Image Gambar Depan + Frame Tool Alat Bingkai + Create a new rectangular frame Buat bingkai persegi panjang baru + Create a new elliptical frame Buat bingkai elips baru Include in playback Sertakan dalam pemutaran Perspective Crop Tool Alat Crop Perspektif Show Grid Tampilkan Grid diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 3386fa0aa9..4eeda8a3e0 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -2560,6 +2560,9 @@ cameraData Lens Obiettivo Previous Document Documento precedente W x H x Resolution L x A x Risoluzione Front Image Immagine in primo piano + Frame Tool Strumento Cornice + Create a new rectangular frame Crea una nuova cornice rettangolare + Create a new elliptical frame Crea una nuova cornice ellittica Include in playback Includi nella riproduzione Perspective Crop Tool Strumento Taglierina prospettica Show Grid Mostra griglia diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index e25db1caca..c7777e64a2 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3508,6 +3508,9 @@ cameraData Lens レンズ Previous Document 前のドキュメント W x H x Resolution 幅 x 高さ x 解像度 Front Image 前面の画像 + Frame Tool フレームツール + Create a new rectangular frame 新しい長方形フレームを作成 + Create a new elliptical frame 新しい楕円形フレームを作成 Include in playback 再生に含める Perspective Crop Tool 遠近法の切り抜きツール Show Grid グリッドを表示 diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index ce7b9ea863..f6b1bee14e 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3074,6 +3074,9 @@ cameraData Lens 렌즈 Previous Document 이전 문서 W x H x Resolution 폭 x 높이 x 해상도 Front Image 전면 이미지 + Frame Tool 프레임 도구 + Create a new rectangular frame 새 사각형 프레임 만들기 + Create a new elliptical frame 새 타원형 프레임 만들기 Include in playback 재생에 포함 Perspective Crop Tool 원근 자르기 도구 Show Grid 격자 표시 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index ef4e6759c8..8d1e1f6c6c 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -3681,4 +3681,7 @@ cameraData Lens Lens Search settings… Instellingen zoeken… No matching settings Geen overeenkomende instellingen PhotoCraft — Screen Color Picker PhotoCraft — Schermkleurkiezer + Frame Tool Kadergereedschap + Create a new rectangular frame Nieuw rechthoekig kader maken + Create a new elliptical frame Nieuw ovaal kader maken Include in playback Opnemen in afspelen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 279baf77cc..4e87d5b537 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -3509,6 +3509,9 @@ cameraData Lens Obiektyw Previous Document Poprzedni dokument W x H x Resolution Szer. x Wys. x Rozdzielczość Front Image Obraz na wierzchu + Frame Tool Narzędzie Ramka + Create a new rectangular frame Utwórz nową ramkę prostokątną + Create a new elliptical frame Utwórz nową ramkę eliptyczną Include in playback Uwzględnij w odtwarzaniu Perspective Crop Tool Narzędzie Kadrowanie perspektywiczne Show Grid Pokaż siatkę diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 36197a61d2..587069bd5d 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -2915,6 +2915,9 @@ cameraData Lens Lente Previous Document Documento anterior W x H x Resolution L x A x Resolução Front Image Imagem frontal + Frame Tool Ferramenta Quadro + Create a new rectangular frame Criar um quadro retangular + Create a new elliptical frame Criar um quadro elíptico Include in playback Incluir na reprodução Perspective Crop Tool Ferramenta Corte demarcado em perspectiva Show Grid Mostrar grade diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 71d865f092..0b950a69d9 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -2834,6 +2834,9 @@ cameraData Lens Объектив Previous Document Предыдущий документ W x H x Resolution Ш x В x Разрешение Front Image Изображение переднего плана + Frame Tool Рамка + Create a new rectangular frame Создать прямоугольную рамку + Create a new elliptical frame Создать эллиптическую рамку Include in playback Включить в воспроизведение Perspective Crop Tool Кадрирование перспективы Show Grid Показать сетку diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index b119ff19b1..66ea4366cb 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -3609,6 +3609,9 @@ cameraData Lens Об'єктив Search settings… Пошук налаштувань… No matching settings Немає відповідних налаштувань PhotoCraft — Screen Color Picker PhotoCraft — Піпетка кольору екрана + Frame Tool Інструмент «Рамка» + Create a new rectangular frame Створити прямокутну рамку + Create a new elliptical frame Створити еліптичну рамку Include in playback Включити у відтворення New Crop Preset… Новий набір параметрів кадрування… Delete Crop Preset… Видалити набір параметрів кадрування… diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 409809c506..1c36a77ac6 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -2503,6 +2503,9 @@ cameraData Lens 镜头 Previous Document 上一个文档 W x H x Resolution 宽 x 高 x 分辨率 Front Image 前面的图像 + Frame Tool 图框工具 + Create a new rectangular frame 新建矩形图框 + Create a new elliptical frame 新建椭圆图框 Include in playback 包含在播放中 Perspective Crop Tool 透视裁剪工具 Show Grid 显示网格 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index acd9026ab6..cba84fda39 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2473,6 +2473,9 @@ cameraData Lens 鏡頭 Previous Document 上一個文件 W x H x Resolution 寬 x 高 x 解析度 Front Image 前面的影像 + Frame Tool 影格工具 + Create a new rectangular frame 建立新的矩形影格 + Create a new elliptical frame 建立新的橢圓形影格 Include in playback 包含在播放中 Perspective Crop Tool 透視裁切工具 Show Grid 顯示格點 diff --git a/crates/ui-egui/src/icon_data.rs b/crates/ui-egui/src/icon_data.rs index dc64bc5ad9..ab280d585e 100644 --- a/crates/ui-egui/src/icon_data.rs +++ b/crates/ui-egui/src/icon_data.rs @@ -49,6 +49,7 @@ pub static ICONS: &[(&str, &[u8])] = &[ ("folder", include_bytes!("../../../assets/icons/folder.svg")), ("folder-open", include_bytes!("../../../assets/icons/folder-open.svg")), ("folder-plus", include_bytes!("../../../assets/icons/folder-plus.svg")), + ("frame-placeholder", include_bytes!("../../../assets/icons/frame-placeholder.svg")), ("gauge", include_bytes!("../../../assets/icons/gauge.svg")), ("grid-2x2", include_bytes!("../../../assets/icons/grid-2x2.svg")), ("grid-3x3", include_bytes!("../../../assets/icons/grid-3x3.svg")), diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index 5df343c8ca..0675b2e648 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -109,6 +109,7 @@ pub fn tool_icon(t: Tool) -> &'static str { Tool::PerspectiveCrop => "perspective-crop", Tool::Slice => "slice-knife", Tool::SliceSelect => "square-dashed-mouse-pointer", + Tool::Frame => "frame-placeholder", Tool::Gradient => "blend", Tool::PaintBucket => "paint-bucket", Tool::Type | Tool::VerticalType => "type", diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 378b4d7687..406b9b1225 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -76,6 +76,7 @@ pub mod filter_dialog; #[cfg(not(target_arch = "wasm32"))] mod filter_preview_worker; mod font_preview; +pub mod frame_tool; pub mod gallery_ui; pub mod gpu_canvas; pub mod gpu_status; diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 87a1d58e97..6fc11515fe 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -21,6 +21,7 @@ const TOOL_SECTIONS: &[&[&[Tool]]] = &[ &[Tool::Lasso, Tool::PolygonLasso, Tool::MagneticLasso], &[Tool::ObjectSelection, Tool::QuickSelection, Tool::MagicWand], &[Tool::Crop, Tool::PerspectiveCrop, Tool::Slice, Tool::SliceSelect], + &[Tool::Frame], &[Tool::Eyedropper, Tool::Ruler, Tool::Note, Tool::Count], ], &[ @@ -888,6 +889,7 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { || crate::vector_ui::options_bar(app, ui, tool) || crate::analysis_ui::options_bar(app, ui, tool) || crate::slice_ui::options_bar(app, ui, tool) + || crate::frame_tool::options_bar(app, ui, tool) || crate::artboard_tool::options_bar(app, ui, tool) { return; diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index d3a75d37e5..9e31124198 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -130,10 +130,11 @@ pub enum Tool { CustomShape, Slice, SliceSelect, + Frame, } impl Tool { - pub const ALL: [Tool; 64] = [ + pub const ALL: [Tool; 65] = [ Tool::Move, Tool::Artboard, Tool::RectMarquee, @@ -198,6 +199,7 @@ impl Tool { Tool::CustomShape, Tool::Slice, Tool::SliceSelect, + Tool::Frame, ]; pub fn label(self) -> &'static str { @@ -227,6 +229,7 @@ impl Tool { Tool::PerspectiveCrop => "Perspective Crop Tool", Tool::Slice => "Slice Tool", Tool::SliceSelect => "Slice Select Tool", + Tool::Frame => "Frame Tool", Tool::Gradient => "Gradient Tool", Tool::PaintBucket => "Paint Bucket Tool", Tool::Type => "Horizontal Type Tool", @@ -315,6 +318,7 @@ impl Tool { Tool::Lasso | Tool::PolygonLasso | Tool::MagneticLasso => 'L', Tool::MagicWand => 'W', Tool::Crop | Tool::PerspectiveCrop | Tool::Slice | Tool::SliceSelect => 'C', + Tool::Frame => 'K', Tool::Gradient | Tool::PaintBucket => 'G', Tool::Type | Tool::VerticalType | Tool::HorizontalTypeMask | Tool::VerticalTypeMask => 'T', Tool::Hand => 'H', @@ -1051,8 +1055,10 @@ pub struct UiState { /// Slice and Slice Select tools (see `slice_ui`). #[serde(default)] pub slices: crate::slice_ui::SliceUi, - /// Artboard tool (see `artboard_tool`). + /// Frame tool (see `frame_tool`). #[serde(default)] + pub frame_tool: crate::frame_tool::FrameToolUi, + /// Artboard tool (see `artboard_tool`). pub artboard_tool: crate::artboard_tool::ArtboardToolUi, /// Modifier Keys panel, custom pixel aspect ratios, workspace dialogs (see `workspace_ui`). #[serde(default)] @@ -1184,6 +1190,7 @@ impl Default for UiState { analysis: Default::default(), timeline: Default::default(), slices: Default::default(), + frame_tool: Default::default(), artboard_tool: Default::default(), shell: Default::default(), layer_filter: Vec::new(), @@ -1293,7 +1300,7 @@ mod tests { assert!(!Tool::RedEye.is_brushlike()); assert_eq!(Tool::from_name("patternStamp"), Some(Tool::PatternStamp)); assert_eq!(Tool::from_name("Pattern Stamp Tool"), Some(Tool::PatternStamp)); - assert_eq!(Tool::ALL.len(), 64); + assert_eq!(Tool::ALL.len(), 65); assert_eq!(Tool::from_name("Vertical Type Mask Tool"), Some(Tool::VerticalTypeMask)); assert_eq!(Tool::from_name("addAnchorPoint"), Some(Tool::AddAnchorPoint)); assert_eq!(Tool::from_name("Delete Anchor Point Tool"), Some(Tool::DeleteAnchorPoint)); diff --git a/crates/ui-egui/src/tool_reset.rs b/crates/ui-egui/src/tool_reset.rs index 89a1c0dc2e..17bfdad1b5 100644 --- a/crates/ui-egui/src/tool_reset.rs +++ b/crates/ui-egui/src/tool_reset.rs @@ -181,7 +181,8 @@ pub fn reset_options(o: &mut ToolOptions, tool: Tool) { | Tool::SliceSelect | Tool::AddAnchorPoint | Tool::DeleteAnchorPoint - | Tool::Artboard => {} + | Tool::Artboard + | Tool::Frame => {} } } diff --git a/docs/gaps.md b/docs/gaps.md index d0419643d7..a2ec3dddc4 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -54,10 +54,11 @@ what an agent can't finish alone. scripted check there) is the only real oracle. ### G6. Missing tools -- **Missing (7 of 68):** Frame, Color Sampler (#1046), Color Replacement (engine command exists), - Art History Brush, Add Anchor Point, Delete Anchor Point, Convert Point (only as Pen + ⌥). - Freeform Pen and Curvature Pen landed (#1054); Horizontal and Vertical Type Mask landed (#1055, - `type.createSelection`); Perspective Crop landed (#1043, `image.perspectiveCrop`). +- **Missing (6 of 68):** Color Sampler (#1046), Color Replacement (engine command exists), Art + History Brush, Add Anchor Point, Delete Anchor Point, Convert Point (only as Pen + ⌥). Freeform + Pen and Curvature Pen landed (#1054); Horizontal and Vertical Type Mask landed (#1055, + `type.createSelection`); Perspective Crop landed (#1043, `image.perspectiveCrop`); Frame landed + (#2914). - **Evidence:** `Tool` enum (`crates/ui-egui/src/state.rs`) against the 67 `` entries of Photoshop's `Default Keyboard Shortcuts.kys` plus Remove, Triangle and Curvature Pen. - **Impact:** users look for them by name and shortcut; several are daily tools for designers. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ecf7f99f83..7a4f238cc8 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -61,7 +61,7 @@ architecture and the PSD writer are the serial parts. | Component | Weight | Ours / Photoshop | % | Kind | |---|---:|---|---:|---| | Menu commands | 30% | 628 / 628 catalog items dispatch a live command | 100% | measured (`cargo xtask parity`) | -| Toolbox tools | 15% | 57 / 68 (Photoshop's 67 `.kys` tools plus Remove, Triangle, Curvature Pen; minus legacy Rounded Rectangle and Targeted Adjustment) | 84% | measured (`Tool` enum in `ui-egui/src/state.rs`, `TOOL_SECTIONS` in `panels.rs`) | +| Toolbox tools | 15% | 58 / 68 (Photoshop's 67 `.kys` tools plus Remove, Triangle, Curvature Pen; minus legacy Rounded Rectangle and Targeted Adjustment) | 85% | measured (`Tool` enum in `ui-egui/src/state.rs`, `TOOL_SECTIONS` in `panels.rs`) | | Panels | 10% | 30 / 35 Window-menu panels | 86% | measured (`view_cmds.rs`, panel modules) | | Filters and adjustments | 10% | every Filter and Image › Adjustments item live; Filter Gallery 47 looks | 100% | measured (menu catalog) | | File formats (usage-weighted) | 15% | 13 of 31 Photoshop formats supported in Photoshop's directions, 4 partial; the common ones (PSD/PSB, TIFF, JPEG, PNG, WebP) all present | ~80% (48% by count) | measured list, estimated weights ([file-format-parity.md](file-format-parity.md)) | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 38c3a58f20..df23d9f61d 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -31,7 +31,7 @@ Triangle and Curvature Pen (minus legacy Rounded Rectangle and Targeted Adjustme | Lasso | Lasso, Polygonal, Magnetic | | | Selection | Object Selection, Quick Selection, Magic Wand | | | Crop and slice | Crop, Perspective Crop, Slice, Slice Select | | -| Frame | | Frame (`layer.new.frameFromLayers` exists) | +| Frame | Frame (frames are groups clipped by a rectangular or elliptical mask) | | | Eyedropper | Eyedropper, Ruler, Note, Count | Color Sampler (#1046) | | Retouch | Remove, Spot Healing, Healing, Patch, Content-Aware Move, Red Eye | | | Brush | Brush, Pencil, Mixer Brush | Color Replacement (`paint.colorReplacement` exists) | From ec28fdd03d944504add59f17d687038083a6945a Mon Sep 17 00:00:00 2001 From: Skyfuller <58360545+Skyfuller1303@users.noreply.github.com> Date: Sun, 11 Oct 2026 14:23:03 +0200 Subject: [PATCH 2/4] Add Photoshop-style guide layout dialog and live preview (#2930) * feat(ui): add guide layout dialog with live preview * test(ui): restore path helper used by save dialog assertions * chore(i18n): avoid conflicts with appended catalog entries * chore: avoid append conflict for contributor credit * Merge main: one people.toml entry for Skyfuller1303, drop the duplicate joined helper Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Brandon Thomas Co-authored-by: Claude Opus 5.5 --- contributors/people.toml | 6 +- crates/engine/src/file_cmds.rs | 73 +--- crates/engine/src/guide_layout.rs | 184 ++++++++++ crates/engine/src/lib.rs | 1 + crates/engine/tests/guide_layout_preview.rs | 73 ++++ crates/ui-egui/src/canvas.rs | 2 +- crates/ui-egui/src/dialogs.rs | 20 +- crates/ui-egui/src/guide_layout_ui.rs | 359 ++++++++++++++++++++ crates/ui-egui/src/guide_layout_ui/tests.rs | 222 ++++++++++++ crates/ui-egui/src/i18n/cs.tsv | 19 ++ crates/ui-egui/src/i18n/de.tsv | 19 ++ crates/ui-egui/src/i18n/el.tsv | 18 + crates/ui-egui/src/i18n/es.tsv | 20 ++ crates/ui-egui/src/i18n/fr.tsv | 19 ++ crates/ui-egui/src/i18n/id.tsv | 19 ++ crates/ui-egui/src/i18n/it.tsv | 20 ++ crates/ui-egui/src/i18n/ja.tsv | 17 + crates/ui-egui/src/i18n/ko.tsv | 18 + crates/ui-egui/src/i18n/nl.tsv | 17 + crates/ui-egui/src/i18n/pl.tsv | 17 + crates/ui-egui/src/i18n/pt-br.tsv | 18 + crates/ui-egui/src/i18n/ru.tsv | 19 ++ crates/ui-egui/src/i18n/uk.tsv | 18 + crates/ui-egui/src/i18n/zh-hans.tsv | 19 ++ crates/ui-egui/src/i18n/zh-hant.tsv | 19 ++ crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/rulers.rs | 20 +- crates/ui-egui/src/view_cmds.rs | 5 +- crates/ui-egui/src/widgets.rs | 4 +- 29 files changed, 1182 insertions(+), 84 deletions(-) create mode 100644 crates/engine/src/guide_layout.rs create mode 100644 crates/engine/tests/guide_layout_preview.rs create mode 100644 crates/ui-egui/src/guide_layout_ui.rs create mode 100644 crates/ui-egui/src/guide_layout_ui/tests.rs diff --git a/contributors/people.toml b/contributors/people.toml index 25d60599e7..b7107559a3 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -17,6 +17,10 @@ # To remove your names, delete your entry (or set fields empty) in a PR. The next # contributors.py run, and the next build, drop them. +[people.Skyfuller1303] +display_name = "Skyfuller" +sync_github_name = true + [people.AlanRockefeller] sync_github_name = true @@ -97,5 +101,3 @@ sync_github_name = true [people.TheTeslak] sync_github_name = true -[people.Skyfuller1303] -sync_github_name = true diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 0ccf1d10ea..a6096ac96e 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -1267,77 +1267,8 @@ fn push_unique(v: &mut Vec, x: f64) { } } -/// Guide positions for `count` columns (or rows) across `[start, end]`, Photoshop-style: both -/// edges of every column; a fixed `width` packs columns from `start` (or centres them). -fn layout_lines(start: f64, end: f64, count: u32, width: Option, gutter: f64, center: bool, out: &mut Vec) { - let avail = (end - start).max(0.0); - if count == 0 { - return; - } - let n = count as f64; - let w = width.unwrap_or(((avail - (n - 1.0) * gutter) / n).max(0.0)); - let total = n * w + (n - 1.0) * gutter; - let x0 = if center && width.is_some() { start + (avail - total) / 2.0 } else { start }; - for i in 0..count { - let a = x0 + i as f64 * (w + gutter); - push_unique(out, a); - push_unique(out, a + w); - } -} - fn new_guide_layout(s: &mut Session, p: &Value) -> Result { - let d = s.active().ok_or(EngineError::NoDocument)?; - let (cw, ch) = (d.doc.size.width as f64, d.doc.size.height as f64); - let m = match p.get("margin") { - Some(Value::Array(a)) if a.len() == 4 => [0, 1, 2, 3].map(|i| a[i].as_f64().unwrap_or(0.0)), - Some(v) if v.is_number() => [v.as_f64().unwrap_or(0.0); 4], - _ => [0.0; 4], - }; - let [top, left, bottom, right] = m; - let cols = p.get("columns").and_then(Value::as_u64).unwrap_or(0); - let rows = p.get("rows").and_then(Value::as_u64).unwrap_or(0); - // Each column/row costs a loop iteration plus a duplicate scan, so an - // absurd count from the caller would block the app for minutes (#704). - // Photoshop's own dialog caps at 32; 1000 is a generous ceiling that - // still finishes instantly. - const MAX_GUIDE_LINES: u64 = 1000; - for (n, what) in [(cols, "columns"), (rows, "rows")] { - if n > MAX_GUIDE_LINES { - return Err(EngineError::BadParams { cmd: "view.newGuideLayout".into(), msg: format!("{what} must be {MAX_GUIDE_LINES} or fewer (got {n})") }); - } - } - let (cols, rows) = (cols as u32, rows as u32); - let mut v: Vec = Vec::new(); - let mut h: Vec = Vec::new(); - let has_margin = m.iter().any(|x| *x != 0.0); - if has_margin { - push_unique(&mut v, left); - push_unique(&mut v, cw - right); - push_unique(&mut h, top); - push_unique(&mut h, ch - bottom); - } - let center = p.get("centerColumns").and_then(Value::as_bool).unwrap_or(false); - layout_lines(left, cw - right, cols, size_param(p, "width"), f64_param(p, "gutter").unwrap_or(0.0), center, &mut v); - layout_lines(top, ch - bottom, rows, size_param(p, "height"), f64_param(p, "rowGutter").or_else(|| f64_param(p, "gutter")).unwrap_or(0.0), center, &mut h); - if v.is_empty() && h.is_empty() { - return Err(EngineError::BadParams { cmd: "view.newGuideLayout".into(), msg: "give \"columns\", \"rows\" or a \"margin\"".into() }); - } - let clear = p.get("clearExisting").and_then(Value::as_bool).unwrap_or(false); - let (nv, nh) = (v.len(), h.len()); - s.edit("New Guide Layout", |doc, _| { - if clear { - doc.guides.vertical.clear(); - doc.guides.horizontal.clear(); - } - for x in v { - push_unique(&mut doc.guides.vertical, x as f64); - } - for y in h { - push_unique(&mut doc.guides.horizontal, y as f64); - } - Ok(()) - })?; - Ok(json!({"vertical": nv, "horizontal": nh})) + crate::guide_layout::apply(s, p) } fn guides_from_shape(s: &mut Session, p: &Value) -> Result { @@ -1538,7 +1469,7 @@ pub fn specs() -> Vec { "New Guide Layout…", &["View"], None, - r##"{"columns":n=0,"width":px?,"gutter":px=0,"rows":n=0,"height":px?,"rowGutter":px=gutter,"margin":px|[top,left,bottom,right]=0,"centerColumns":bool=false,"clearExisting":bool=false}"##, + r##"{"columns":n=0,"width":px?,"gutter":px=0,"rows":n=0,"height":px?,"rowGutter":px=gutter,"margin":px|[top,left,bottom,right]=0,"centerColumns":bool=false,"clearExisting":bool=false,"target":"document|selectedArtboards"="document"}"##, has_doc, new_guide_layout ), diff --git a/crates/engine/src/guide_layout.rs b/crates/engine/src/guide_layout.rs new file mode 100644 index 0000000000..7708430478 --- /dev/null +++ b/crates/engine/src/guide_layout.rs @@ -0,0 +1,184 @@ +//! Pure guide-layout calculation shared by the command and its non-destructive UI preview. + +use photocraft_doc::Guides; +use photocraft_geom::Rect; +use serde_json::Value; + +use crate::{EngineError, Result, Session}; + +const COMMAND: &str = "view.newGuideLayout"; +const MAX_COUNT: u64 = 1000; +const MAX_EDGES: u64 = 16_000; + +fn bad(message: impl Into) -> EngineError { + EngineError::BadParams { cmd: COMMAND.into(), msg: message.into() } +} + +fn number(p: &Value, key: &str, default: f64) -> Result { + match p.get(key) { + None | Some(Value::Null) => Ok(default), + Some(v) => v.as_f64().filter(|n| n.is_finite() && *n >= 0.0).ok_or_else(|| bad(format!("{key} must be a finite non-negative number"))), + } +} + +fn count(p: &Value, key: &str) -> Result { + let n = match p.get(key) { + None => 0, + Some(v) => v.as_u64().ok_or_else(|| bad(format!("{key} must be a whole number")))?, + }; + // Each column/row costs a loop iteration plus a duplicate scan, so an + // absurd count from the caller would block the app for minutes (#704). + // Photoshop's own dialog caps at 32; 1000 is a generous ceiling that + // still finishes instantly. + if n > MAX_COUNT { + return Err(bad(format!("{key} must be {MAX_COUNT} or fewer (got {n})"))); + } + Ok(n) +} + +fn flag(p: &Value, key: &str) -> Result { + match p.get(key) { + None => Ok(false), + Some(v) => v.as_bool().ok_or_else(|| bad(format!("{key} must be a boolean"))), + } +} + +/// Document coordinates of every selected artboard, including boards containing selected layers. +pub fn selected_artboards(s: &Session) -> Vec { + let Some(st) = s.active() else { return Vec::new() }; + let selected = st.selected_layers(); + let ids: std::collections::HashSet<_> = selected.iter().filter_map(|id| st.doc.artboard_of(*id)).collect(); + st.doc.artboards().into_iter().filter(|(id, _, _)| ids.contains(id)).map(|(_, _, board)| board.rect).collect() +} + +fn targets(s: &Session, p: &Value) -> Result> { + let st = s.active().ok_or(EngineError::NoDocument)?; + let target = match p.get("target") { + None => "document", + Some(v) => v.as_str().ok_or_else(|| bad("target must be a string"))?, + }; + match target { + "document" => Ok(vec![st.doc.bounds()]), + "selectedArtboards" => { + let boards = selected_artboards(s); + if boards.is_empty() { Err(bad("select an artboard or a layer inside one")) } else { Ok(boards) } + } + _ => Err(bad("target must be document or selectedArtboards")), + } +} + +fn push_unique(out: &mut Vec, value: f64) -> Result<()> { + let value = value as f32; + if !value.is_finite() { + return Err(bad("guide coordinates exceed the supported range")); + } + if !out.iter().any(|x| (*x - value).abs() < 0.01) { + out.push(value); + } + Ok(()) +} + +/// Guide positions for `count` columns (or rows) across `[start, end]`, Photoshop-style: both +/// edges of every column; a fixed `width` packs columns from `start` (or centres them). +fn axis(start: f64, end: f64, count: u64, fixed: f64, gap: f64, center: bool, out: &mut Vec) -> Result<()> { + if count == 0 { + return Ok(()); + } + let available = end - start; + let n = count as f64; + let width = if fixed > 0.0 { fixed } else { (available - (n - 1.0) * gap) / n }; + let total = n * width + (n - 1.0) * gap; + if width <= 0.0 || !total.is_finite() || total > available + 0.001 { + return Err(bad("count, size and gutter must fit inside the target margins")); + } + let origin = if center && fixed > 0.0 { start + (available - total) / 2.0 } else { start }; + for i in 0..count { + let a = origin + i as f64 * (width + gap); + push_unique(out, a)?; + push_unique(out, a + width)?; + } + Ok(()) +} + +/// New lines and the exact guide set that OK will commit. This never edits the session. +#[derive(Clone, Debug)] +pub struct Layout { + pub added: Guides, + pub guides: Guides, +} + +pub fn calculate(s: &Session, p: &Value) -> Result { + let st = s.active().ok_or(EngineError::NoDocument)?; + let cols = count(p, "columns")?; + let rows = count(p, "rows")?; + let width = number(p, "width", 0.0)?; + let height = number(p, "height", 0.0)?; + let gap = number(p, "gutter", 0.0)?; + let row_gap = number(p, "rowGutter", gap)?; + let center = flag(p, "centerColumns")?; + let clear = flag(p, "clearExisting")?; + let margins = match p.get("margin") { + Some(Value::Array(a)) => { + if a.len() != 4 { + return Err(bad("margin must contain top, left, bottom and right")); + } + let mut m = [0.0; 4]; + for (out, value) in m.iter_mut().zip(a) { + *out = value.as_f64().filter(|v| v.is_finite() && *v >= 0.0).ok_or_else(|| bad("margins must be finite non-negative numbers"))?; + } + m + } + _ => [number(p, "margin", 0.0)?; 4], + }; + let [top, left, bottom, right] = margins; + let bounds = targets(s, p)?; + // Bound the aggregate work as well as each count, including multi-artboard requests. + if (cols + rows + 4).saturating_mul(2).saturating_mul(bounds.len() as u64) > MAX_EDGES { + return Err(bad("the selected targets would create too many guide lines")); + } + let mut added = Guides::default(); + for rect in &bounds { + let (x0, y0, x1, y1) = (f64::from(rect.x0) + left, f64::from(rect.y0) + top, f64::from(rect.x1) - right, f64::from(rect.y1) - bottom); + if x0 >= x1 || y0 >= y1 { + return Err(bad("margins must leave space inside the target")); + } + if margins.iter().any(|x| *x != 0.0) { + push_unique(&mut added.vertical, x0)?; + push_unique(&mut added.vertical, x1)?; + push_unique(&mut added.horizontal, y0)?; + push_unique(&mut added.horizontal, y1)?; + } + axis(x0, x1, cols, width, gap, center, &mut added.vertical)?; + axis(y0, y1, rows, height, row_gap, center, &mut added.horizontal)?; + } + if added.vertical.is_empty() && added.horizontal.is_empty() { + return Err(bad("give \"columns\", \"rows\" or a \"margin\"")); + } + let mut guides = st.doc.guides.clone(); + if clear { + if p.get("target").and_then(Value::as_str) == Some("selectedArtboards") { + // Guides are stored as document-wide axes, matching Clear Selected Artboard Guides. + guides.vertical.retain(|v| !bounds.iter().any(|r| f64::from(*v) >= f64::from(r.x0) && f64::from(*v) <= f64::from(r.x1))); + guides.horizontal.retain(|v| !bounds.iter().any(|r| f64::from(*v) >= f64::from(r.y0) && f64::from(*v) <= f64::from(r.y1))); + } else { + guides = Guides::default(); + } + } + for x in &added.vertical { + push_unique(&mut guides.vertical, f64::from(*x))?; + } + for y in &added.horizontal { + push_unique(&mut guides.horizontal, f64::from(*y))?; + } + Ok(Layout { added, guides }) +} + +pub(crate) fn apply(s: &mut Session, p: &Value) -> Result { + let layout = calculate(s, p)?; + let result = serde_json::json!({"vertical":layout.added.vertical.len(),"horizontal":layout.added.horizontal.len()}); + s.edit("New Guide Layout", |doc, _| { + doc.guides = layout.guides; + Ok(()) + })?; + Ok(result) +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index a20d02bf8c..749c04475d 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -48,6 +48,7 @@ pub mod fx_visibility_cmds; pub mod gallery_cmds; pub mod gradient_fill_cmds; pub mod group_view_cmds; +pub mod guide_layout; pub mod hidden_target; pub mod history_cmds; pub mod image_cmds; diff --git a/crates/engine/tests/guide_layout_preview.rs b/crates/engine/tests/guide_layout_preview.rs new file mode 100644 index 0000000000..c49aa2a604 --- /dev/null +++ b/crates/engine/tests/guide_layout_preview.rs @@ -0,0 +1,73 @@ +use photocraft_engine::{Session, guide_layout}; +use serde_json::json; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width":100,"height":60})).unwrap(); + s +} + +#[test] +fn pure_preview_matches_commit_and_one_undo_restores_existing_guides() { + let mut s = session(); + s.execute("view.newGuideLayout", json!({"columns":2})).unwrap(); + let before = s.active().unwrap().doc.guides.clone(); + let revision = s.active().unwrap().revision; + let p = json!({"columns":3,"rows":2,"gutter":4,"rowGutter":6,"margin":[3,7,5,11],"clearExisting":true}); + let preview = guide_layout::calculate(&s, &p).unwrap(); + assert_eq!(s.active().unwrap().revision, revision); + assert_eq!(s.active().unwrap().doc.guides, before); + s.execute("view.newGuideLayout", p).unwrap(); + assert_eq!(s.active().unwrap().doc.guides, preview.guides); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc.guides, before); + s.execute("edit.redo", json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc.guides, preview.guides); +} + +#[test] +fn fixed_sizes_center_and_keep_existing_lines() { + let mut s = session(); + s.execute("view.newGuideLayout", json!({"margin":5})).unwrap(); + let before = s.active().unwrap().doc.guides.clone(); + let p = json!({"columns":2,"width":20,"gutter":10,"rows":2,"height":10,"rowGutter":4,"centerColumns":true}); + let result = guide_layout::calculate(&s, &p).unwrap(); + assert_eq!(result.added.vertical, vec![25.0, 45.0, 55.0, 75.0]); + assert_eq!(result.added.horizontal, vec![18.0, 28.0, 32.0, 42.0]); + assert!(before.vertical.iter().all(|g| result.guides.vertical.contains(g))); + assert!(before.horizontal.iter().all(|g| result.guides.horizontal.contains(g))); +} + +#[test] +fn invalid_geometry_is_atomic() { + let mut s = session(); + let revision = s.active().unwrap().revision; + for params in [ + json!({"columns":-1}), + json!({"rows":1.5}), + json!({"columns":2,"width":60}), + json!({"columns":3,"gutter":50}), + json!({"margin":[1,2,3]}), + json!({"margin":[0,100,0,0]}), + json!({"columns":2,"gutter":"bad"}), + json!({"columns":2,"clearExisting":1}), + json!({"columns":1,"target":"selectedArtboards"}), + ] { + assert!(s.execute("view.newGuideLayout", params.clone()).is_err(), "accepted {params}"); + assert_eq!(s.active().unwrap().revision, revision); + } +} + +#[test] +fn selected_artboards_use_offsets_and_clear_only_the_target_ranges() { + let mut s = session(); + s.execute("view.newGuideLayout", json!({"margin":5})).unwrap(); + s.execute("layer.new.artboard", json!({"rect":[200,100,100,60]})).unwrap(); + let p = json!({"columns":2,"margin":[5,10,5,10],"target":"selectedArtboards","clearExisting":true}); + let preview = guide_layout::calculate(&s, &p).unwrap(); + assert_eq!(preview.added.vertical, vec![210.0, 290.0, 250.0]); + assert_eq!(preview.added.horizontal, vec![105.0, 155.0]); + assert!(preview.guides.vertical.contains(&5.0)); + s.execute("view.newGuideLayout", p).unwrap(); + assert_eq!(s.active().unwrap().doc.guides, preview.guides); +} diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index b99b8780e6..a2bb654c36 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -3113,7 +3113,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: if app.ui.extras.grid && app.ui.view.extras { crate::rulers::draw_grid(app, &painter, &xf, &doc); } - if app.ui.view.shows(app.ui.view.show.canvas_guides) { + if app.ui.view.shows(app.ui.view.show.canvas_guides) || crate::guide_layout_ui::preview(app, &doc).is_some() { crate::rulers::draw_guides(app, &painter, &xf, &doc); } // The pending crop frame shows on its own document only, not on the other tiles (#1918). diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index c14b9fc48e..c3994e5916 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -210,6 +210,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { ui.add_space(8.0); about_tab_body(app, ui, chosen); } + DialogKind::Command if crate::guide_layout_ui::owns(&fields) => outcome = crate::guide_layout_ui::body(app, ui, &mut fields, interactive), DialogKind::Command if crate::fill_ui::owns(&fields) => crate::fill_ui::body(app, ui, &mut fields), DialogKind::Command if crate::stroke_ui::owns(&fields) => crate::stroke_ui::body(ui, &mut fields), DialogKind::Command if crate::shape_dialog::owns(&fields) => crate::shape_dialog::body(app, ui, &mut fields), @@ -249,7 +250,9 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { } } crate::field_tab::end(ui.ctx(), tab); - if crate::color_picker_ui::owns(&fields) { + if crate::guide_layout_ui::owns(&fields) { + // This dialog owns its right-side actions and validates Enter itself. + } else if crate::color_picker_ui::owns(&fields) { if interactive && outcome.is_none() && ui.input(|i| i.key_pressed(egui::Key::Enter)) { outcome = Some(true); } @@ -417,6 +420,12 @@ pub fn confirm(app: &mut PhotocraftApp, id: u64) -> Result { if crate::layer_style::color_picker::has_child(app, id) { return Err("confirm or cancel the Layer Style color picker first".into()); } + if let Some(d) = app.ui.dialogs.iter().find(|d| d.id == id).filter(|d| crate::guide_layout_ui::owns(&d.fields)) { + if app.ui.dialogs.iter().any(|child| crate::color_picker_ui::owns(&child.fields) && child.fields.get("__dialog").and_then(Value::as_u64) == Some(id)) { + return Err("confirm or cancel the guide color picker first".into()); + } + crate::guide_layout_ui::validate(app, &d.fields)?; + } let d = app.ui.close_dialog(id).ok_or_else(|| format!("no dialog {id}"))?; match d.kind { DialogKind::NewDocument => { @@ -429,6 +438,7 @@ pub fn confirm(app: &mut PhotocraftApp, id: u64) -> Result { } r } + DialogKind::Command if crate::guide_layout_ui::owns(&d.fields) => crate::guide_layout_ui::confirm(app, &d.fields), DialogKind::Command if crate::fill_ui::owns(&d.fields) => crate::fill_ui::confirm(app, &d.fields), DialogKind::Command if crate::stroke_ui::owns(&d.fields) => crate::stroke_ui::confirm(app, &d.fields), DialogKind::Command if crate::shape_dialog::owns(&d.fields) => crate::shape_dialog::confirm(app, &d.fields), @@ -474,7 +484,10 @@ pub fn confirm(app: &mut PhotocraftApp, id: u64) -> Result { /// Cancel a dialog and its dependent Layer Style picker, without applying edits. pub fn cancel(app: &mut PhotocraftApp, id: u64) -> Result { - app.ui.close_dialog(id).ok_or_else(|| format!("no dialog {id}"))?; + let closed = app.ui.close_dialog(id).ok_or_else(|| format!("no dialog {id}"))?; + if crate::guide_layout_ui::owns(&closed.fields) { + app.ui.dialogs.retain(|child| child.fields.get("__dialog").and_then(Value::as_u64) != Some(id)); + } app.ui.dialogs.retain(|d| !crate::layer_style::color_picker::child_of(&d.fields, id)); app.filter_preview = None; app.color_range = None; @@ -486,6 +499,9 @@ pub fn cancel(app: &mut PhotocraftApp, id: u64) -> Result { /// schema dialog for filters, the Color Range dialog for `select.colorRange`, otherwise a bare /// confirm dialog. pub fn open_command_dialog(app: &mut PhotocraftApp, command: &str, label: &str) -> u64 { + if command == "view.newGuideLayout" { + return crate::guide_layout_ui::open(app); + } if command == crate::stroke_ui::COMMAND { return crate::stroke_ui::open(app); } diff --git a/crates/ui-egui/src/guide_layout_ui.rs b/crates/ui-egui/src/guide_layout_ui.rs new file mode 100644 index 0000000000..d85daf3058 --- /dev/null +++ b/crates/ui-egui/src/guide_layout_ui.rs @@ -0,0 +1,359 @@ +//! Photoshop-style guide layout dialog. Its preview is a pure guide overlay, never an edit. + +use egui::{Color32, Stroke}; +use photocraft_doc::{Document, Guides}; +use serde_json::{Map, Value, json}; + +use crate::{PhotocraftApp, theme::Tokens, widgets}; + +const COMMAND: &str = "view.newGuideLayout"; +const MARK: &str = "__guideLayout"; +const COLORS: [(&str, &str); 5] = [("#4affff", "Cyan"), ("#ff00ff", "Magenta"), ("#378ef0", "Blue"), ("#00a86b", "Green"), ("#ffcc00", "Yellow")]; + +pub fn owns(f: &Map) -> bool { + f.contains_key(MARK) +} + +fn on(f: &Map, key: &str, fallback: bool) -> bool { + f.get(key).and_then(Value::as_bool).unwrap_or(fallback) +} +fn positive(f: &Map, key: &str) -> bool { + f.get(key).and_then(Value::as_f64).is_some_and(|n| n > 0.0) +} + +pub fn open(app: &mut PhotocraftApp) -> u64 { + let mut f = app.ui.view.guide_layout.as_object().cloned().unwrap_or_default(); + f.insert(MARK.into(), json!(true)); + f.insert("__command".into(), json!(COMMAND)); + f.insert("__label".into(), json!("New Guide Layout…")); + f.insert("__document".into(), app.session.active().map(|s| json!(s.doc.id)).unwrap_or(Value::Null)); + f.insert("__preview".into(), json!(true)); + f.insert("color".into(), json!(app.session.prefs().guides_grid_and_slices.guide_color)); + f.entry("target").or_insert_with(|| json!("document")); + if f.get("target").and_then(Value::as_str) == Some("selectedArtboards") && photocraft_engine::guide_layout::selected_artboards(&app.session).is_empty() { + f.insert("target".into(), json!("document")); + } + f.entry("__preset").or_insert_with(|| json!("custom")); + f.entry("width").or_insert(Value::Null); + f.entry("height").or_insert(Value::Null); + let margin = f.get("margin").cloned().unwrap_or(json!(0)); + if !margin.is_array() { + f.insert("margin".into(), json!([margin.clone(), margin.clone(), margin.clone(), margin])); + } + for key in ["__previewGuides", "__previewParams", "__previewSource"] { + f.remove(key); + } + app.ui.open_dialog(crate::state::DialogKind::Command, f) +} + +/// Preserve legacy command parameter names for automation and remembered defaults. +pub fn params(f: &Map) -> Value { + let mut p: Map = ["columns", "rows", "width", "height", "gutter", "rowGutter", "margin", "centerColumns", "clearExisting", "target"] + .into_iter() + .filter_map(|k| f.get(k).cloned().map(|v| (k.to_string(), v))) + .collect(); + for (toggle, key) in [("__columnsEnabled", "columns"), ("__rowsEnabled", "rows")] { + if !on(f, toggle, positive(f, key)) { + p.insert(key.into(), json!(0)); + } + } + if !on(f, "__marginEnabled", true) { + p.insert("margin".into(), json!(0)); + } + for key in ["width", "height"] { + if let Some(Value::String(s)) = p.get(key) { + let value = if s.trim().is_empty() { + Value::Null + } else { + widgets::parse_num(s).and_then(serde_json::Number::from_f64).map(Value::Number).unwrap_or_else(|| json!(s)) + }; + p.insert(key.into(), value); + } + } + // A disabled axis must not be rejected for a stale width or gap typed before disabling it. + for (key, size, gap) in [("columns", "width", "gutter"), ("rows", "height", "rowGutter")] { + if p.get(key).and_then(Value::as_u64) == Some(0) { + p.insert(size.into(), Value::Null); + p.insert(gap.into(), json!(0)); + } + } + Value::Object(p) +} + +fn source(app: &PhotocraftApp) -> Value { + app.session.active().map(|st| json!([st.doc.id, st.revision, st.active_layer, st.selected_layers])).unwrap_or(Value::Null) +} + +fn calculate(app: &PhotocraftApp, f: &Map) -> Result { + let st = app.session.active().ok_or("no document")?; + if f.get("__document") != Some(&json!(st.doc.id)) { + return Err("the guide layout belongs to another document".into()); + } + let params = params(f); + // Painting an unchanged dialog must not repeat the duplicate scans every frame. + if f.get("__previewParams") == Some(¶ms) + && f.get("__previewSource") == Some(&source(app)) + && let Some(guides) = f.get("__previewGuides").and_then(|v| serde_json::from_value(v.clone()).ok()) + { + return Ok(guides); + } + photocraft_engine::guide_layout::calculate(&app.session, ¶ms).map(|l| l.guides).map_err(|e| e.to_string()) +} + +pub fn validate(app: &PhotocraftApp, f: &Map) -> Result<(), String> { + let color = f.get("color").and_then(Value::as_str).unwrap_or("#4affff"); + crate::rulers::parse_guide_color(color).ok_or("invalid guide color")?; + calculate(app, f).map(|_| ()) +} + +pub fn confirm(app: &mut PhotocraftApp, f: &Map) -> Result { + validate(app, f)?; + let color = f.get("color").and_then(Value::as_str).unwrap_or("#4affff"); + // Colour is the existing global guide display preference, not document data. + let color = crate::rulers::parse_guide_color(color).ok_or("invalid guide color")?; + let hex = format!("#{:02x}{:02x}{:02x}", color.r(), color.g(), color.b()); + let result = app.run(COMMAND, params(f))?; + app.session.prefs.edit(|prefs| prefs.guides_grid_and_slices.guide_color = hex); + let mut remembered = f.clone(); + for key in [MARK, "__command", "__label", "__document", "__previewGuides", "__previewParams", "__previewSource"] { + remembered.remove(key); + } + app.ui.view.guide_layout = Value::Object(remembered); + Ok(result) +} + +/// Full replacement guide set for the dialog's own document. Cancel/removal drops it immediately. +pub fn preview(app: &PhotocraftApp, doc: &Document) -> Option<(Guides, Color32)> { + let dialog = app.ui.dialogs.iter().rev().find(|d| owns(&d.fields))?; + let f = &dialog.fields; + if !on(f, "__preview", true) || f.get("__document") != Some(&json!(doc.id)) { + return None; + } + let guides = calculate(app, f).ok().or_else(|| f.get("__previewGuides").and_then(|v| serde_json::from_value(v.clone()).ok()))?; + let color = f.get("color").and_then(Value::as_str).and_then(crate::rulers::parse_guide_color).unwrap_or(Color32::from_rgb(74, 255, 255)); + Some((guides, color)) +} + +fn check(ui: &mut egui::Ui, f: &mut Map, key: &str, label: &str, fallback: bool) -> bool { + let mut value = on(f, key, fallback); + if widgets::checkbox(ui, &mut value, label).changed() { + f.insert(key.into(), json!(value)); + } + value +} + +fn number(ui: &mut egui::Ui, f: &mut Map, key: &str, count: bool) { + let mut value = f.get(key).and_then(Value::as_f64).unwrap_or(0.0) as f32; + if widgets::value_field(ui, &mut value, (if count { 1.0 } else { 0.0 })..=if count { 1000.0 } else { 300_000.0 }, if count { "" } else { "px" }, 68.0) + .changed() + { + f.insert(key.into(), if count { json!(value.round() as u64) } else { json!(value) }); + } +} + +fn optional(ui: &mut egui::Ui, f: &mut Map, key: &str) { + let mut value = match f.get(key) { + Some(Value::String(s)) => s.clone(), + Some(v) if v.is_number() => v.to_string(), + _ => String::new(), + }; + let t = Tokens::get(ui.ctx()); + let response = ui.add(egui::TextEdit::singleline(&mut value).id_salt(key).desired_width(60.0).font(crate::theme::mono(12.0)).background_color(t.field)); + if ui.is_enabled() { + crate::field_tab::register(ui.ctx(), response.id); + } + if response.gained_focus() { + crate::field_tab::select_all(ui.ctx(), response.id, &value); + } + if response.changed() { + f.insert(key.into(), json!(value)); + } + response.on_hover_text(tl!("Leave empty for automatic size")); +} + +fn group(ui: &mut egui::Ui, content: impl FnOnce(&mut egui::Ui) -> R) -> R { + let t = Tokens::get(ui.ctx()); + egui::Frame::new().stroke(Stroke::new(1.0, t.field_border)).inner_margin(8).show(ui, |ui| ui.vertical(content).inner).inner +} + +fn axis(ui: &mut egui::Ui, f: &mut Map, rows: bool) { + let (toggle, count, size, gap, title, size_label) = if rows { + ("__rowsEnabled", "rows", "height", "rowGutter", tl!("Rows"), tl!("Height")) + } else { + ("__columnsEnabled", "columns", "width", "gutter", tl!("Columns"), tl!("Width")) + }; + group(ui, |ui| { + let enabled = check(ui, f, toggle, title, positive(f, count)); + if enabled && f.get(count).and_then(Value::as_f64) == Some(0.0) { + f.insert(count.into(), json!(1)); + } + ui.add_space(6.0); + ui.add_enabled_ui(enabled, |ui| { + egui::Grid::new(count).spacing([8.0, 6.0]).show(ui, |ui| { + ui.label(tl!("Number")); + number(ui, f, count, true); + ui.end_row(); + ui.label(size_label); + optional(ui, f, size); + ui.end_row(); + ui.label(tl!("Spacing")); + number(ui, f, gap, false); + ui.end_row(); + }); + }); + }); +} + +fn main_fields(app: &PhotocraftApp, ui: &mut egui::Ui, f: &mut Map) { + let before: Map = f.iter().filter(|(key, _)| !key.starts_with("__preview")).map(|(k, v)| (k.clone(), v.clone())).collect(); + egui::Grid::new("guide-header").spacing([8.0, 6.0]).show(ui, |ui| { + ui.label(tl!("Preset:")); + let mut preset = f.get("__preset").and_then(Value::as_str).unwrap_or("custom").to_string(); + if widgets::dropdown( + ui, + "guide-preset", + &mut preset, + &[("custom".into(), "Custom"), ("five".into(), "5 Columns, 3 Rows"), ("eight".into(), "8 Columns"), ("twelve".into(), "12 Columns")], + 222.0, + ) { + f.insert("__preset".into(), json!(preset)); + match preset.as_str() { + "five" | "eight" | "twelve" => { + let (cols, rows, gap) = match preset.as_str() { + "five" => (5, 3, 0), + "eight" => (8, 0, 20), + _ => (12, 0, 24), + }; + for (k, v) in [ + ("columns", json!(cols)), + ("rows", json!(rows)), + ("gutter", json!(gap)), + ("rowGutter", json!(0)), + ("width", Value::Null), + ("height", Value::Null), + ("margin", json!([0, 0, 0, 0])), + ("__columnsEnabled", json!(true)), + ("__rowsEnabled", json!(rows > 0)), + ("__marginEnabled", json!(true)), + ("centerColumns", json!(false)), + ] { + f.insert(k.into(), v); + } + } + _ => {} + } + } + ui.end_row(); + ui.label(tl!("Target:")); + let mut target = f.get("target").and_then(Value::as_str).unwrap_or("document").to_string(); + let mut options = vec![("document".to_string(), "Document")]; + if !photocraft_engine::guide_layout::selected_artboards(&app.session).is_empty() { + options.push(("selectedArtboards".into(), "Selected Artboards")); + } + if widgets::dropdown(ui, "guide-target", &mut target, &options, 222.0) { + f.insert("target".into(), json!(target)); + } + ui.end_row(); + }); + ui.add_space(10.0); + group(ui, |ui| { + ui.label(tl!("Color")); + ui.horizontal(|ui| { + ui.label(tl!("Color:")); + let mut color = f.get("color").and_then(Value::as_str).unwrap_or("#4affff").to_string(); + let mut colors: Vec<(String, &str)> = COLORS.iter().map(|(v, l)| (v.to_string(), *l)).collect(); + if !COLORS.iter().any(|(v, _)| *v == color) { + colors.push((color.clone(), "Custom")); + } + if widgets::dropdown(ui, "guide-color", &mut color, &colors, 174.0) { + f.insert("color".into(), json!(color)); + } + let shown = crate::rulers::parse_guide_color(&color).unwrap_or(Tokens::get(ui.ctx()).accent); + if widgets::color_swatch_button(ui, shown, tl!("Guide color")).clicked() { + crate::color_picker_ui::request(f, tl!("Guide color")); + } + }); + }); + ui.add_space(10.0); + ui.horizontal_top(|ui| { + axis(ui, f, false); + ui.add_space(4.0); + axis(ui, f, true); + }); + ui.add_space(10.0); + group(ui, |ui| { + let enabled = check(ui, f, "__marginEnabled", tl!("Margin"), true); + let mut margins = f.get("margin").and_then(Value::as_array).cloned().unwrap_or_else(|| vec![json!(0); 4]); + ui.add_space(5.0); + ui.add_enabled_ui(enabled, |ui| { + ui.horizontal(|ui| { + for (value, label) in margins.iter_mut().zip([tl!("Top:"), tl!("Left:"), tl!("Bottom:"), tl!("Right:")]) { + ui.vertical(|ui| { + ui.label(label); + let mut n = value.as_f64().unwrap_or(0.0) as f32; + if widgets::value_field(ui, &mut n, 0.0..=300_000.0, "px", 64.0).changed() { + *value = json!(n); + } + }); + } + }); + }); + f.insert("margin".into(), Value::Array(margins)); + }); + ui.add_space(8.0); + check(ui, f, "centerColumns", tl!("Center Columns"), false); + check(ui, f, "clearExisting", tl!("Clear Existing Guides"), false); + // A typed edit makes a named preset custom; changing target/colour/preview does not. + if ["columns", "rows", "width", "height", "gutter", "rowGutter", "margin", "centerColumns", "__columnsEnabled", "__rowsEnabled", "__marginEnabled"] + .iter() + .any(|k| before.get(*k) != f.get(*k)) + && before.get("__preset") == f.get("__preset") + { + f.insert("__preset".into(), json!("custom")); + } +} + +/// Own the action rail as well as the body, so OK/Cancel/Preview follow Photoshop's arrangement. +pub fn body(app: &PhotocraftApp, ui: &mut egui::Ui, f: &mut Map, interactive: bool) -> Option { + let before = (params(f), on(f, "__preview", true), f.get("color").cloned()); + let mut outcome = None; + ui.horizontal_top(|ui| { + ui.vertical(|ui| { + main_fields(app, ui, f); + }); + ui.add_space(12.0); + ui.vertical(|ui| { + let valid = validate(app, f).is_ok(); + if ui.add_enabled_ui(valid, |ui| widgets::primary_button(ui, tl!("OK"), 96.0)).inner.clicked() { + outcome = Some(true); + } + ui.add_space(4.0); + if widgets::secondary_button(ui, tl!("Cancel"), 96.0).clicked() { + outcome = Some(false); + } + ui.add_space(6.0); + check(ui, f, "__preview", tl!("Preview"), true); + }); + }); + match calculate(app, f) { + Ok(guides) => { + f.insert("__previewGuides".into(), json!(guides)); + f.insert("__previewParams".into(), params(f)); + f.insert("__previewSource".into(), source(app)); + } + Err(error) => { + ui.colored_label(Tokens::get(ui.ctx()).text_dim, tl!("Invalid guide layout")).on_hover_text(error); + } + } + if outcome.is_none() && interactive && validate(app, f).is_ok() && ui.input(|i| i.key_pressed(egui::Key::Enter)) { + outcome = Some(true); + } + // The canvas paints before the dialog. Schedule the frame that displays this draft edit. + if before != (params(f), on(f, "__preview", true), f.get("color").cloned()) { + ui.ctx().request_repaint(); + } + outcome +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/guide_layout_ui/tests.rs b/crates/ui-egui/src/guide_layout_ui/tests.rs new file mode 100644 index 0000000000..914a4a74b8 --- /dev/null +++ b/crates/ui-egui/src/guide_layout_ui/tests.rs @@ -0,0 +1,222 @@ +use super::*; + +#[test] +fn tab_includes_optional_sizes_and_shift_tab_selects_their_text() { + let mut app = app(); + let id = open(&mut app); + let f = &mut app.ui.dialog_mut(id).unwrap().fields; + f.insert("columns".into(), json!(5)); + f.insert("rows".into(), json!(3)); + f.insert("width".into(), json!(100)); + f.insert("height".into(), json!(80)); + let mut h = harness(app); + h.run_steps(3); + let original = h.state().session.active().unwrap().doc.guides.clone(); + for text in ["4", "120", "12", "2", "90"] { + h.key_press(egui::Key::Tab); + h.run_steps(2); + h.event(egui::Event::Text(text.into())); + h.run_steps(2); + } + let f = &h.state().ui.dialogs.first().unwrap().fields; + assert_eq!((f["columns"].as_u64(), f["rows"].as_u64()), (Some(4), Some(2))); + assert_eq!(params(f)["width"], 120.0); + assert_eq!(params(f)["height"], 90.0); + assert_eq!(f["gutter"], 12.0); + h.key_press_modifiers(egui::Modifiers::SHIFT, egui::Key::Tab); + h.run_steps(2); + h.event(egui::Event::Text("3".into())); + h.run_steps(2); + assert_eq!(h.state().ui.dialogs.first().unwrap().fields["rows"], 3); + assert_eq!(h.state().session.active().unwrap().doc.guides, original); +} + +#[test] +fn tab_skips_disabled_rows_and_margins() { + let mut app = app(); + let id = open(&mut app); + let f = &mut app.ui.dialog_mut(id).unwrap().fields; + f.insert("columns".into(), json!(2)); + f.insert("__rowsEnabled".into(), json!(false)); + f.insert("__marginEnabled".into(), json!(false)); + let mut h = harness(app); + h.run_steps(3); + for text in ["5", "100", "4", "6"] { + h.key_press(egui::Key::Tab); + h.run_steps(2); + h.event(egui::Event::Text(text.into())); + h.run_steps(2); + } + let f = &h.state().ui.dialogs.first().unwrap().fields; + assert_eq!(f["columns"], 6, "Tab wraps after column spacing, skipping disabled row and margin fields"); + assert_eq!(params(f)["width"], 100.0); + assert_eq!(f["gutter"], 4.0); +} + +fn harness(app: PhotocraftApp) -> egui_kittest::Harness<'static, PhotocraftApp> { + let mut initialized = false; + egui_kittest::Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_ui_state( + move |ui, app| { + if initialized { + crate::dialogs::show(app, ui.ctx()); + } else { + PhotocraftApp::setup_context(ui.ctx(), Default::default()); + initialized = true; + } + }, + app, + ) +} + +fn app() -> PhotocraftApp { + let mut session = photocraft_engine::Session::new(); + session.execute("file.new", json!({"width":1200,"height":800})).unwrap(); + PhotocraftApp::new(session, crate::Services::default()) +} + +fn draw(app: &mut PhotocraftApp, id: u64) { + let mut f = app.ui.dialog_mut(id).unwrap().fields.clone(); + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, Default::default()); + ctx.run_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0))), ..Default::default() }, |ui| { + body(app, ui, &mut f, false); + }) + .textures_delta + .clear(); + app.ui.dialog_mut(id).unwrap().fields = f; +} + +#[test] +fn typing_previews_without_editing_and_cancel_restores_preferences_and_lines() { + let mut app = app(); + app.run(COMMAND, json!({"margin":50})).unwrap(); + let original = app.session.active().unwrap().doc.guides.clone(); + let revision = app.session.active().unwrap().revision; + let color = app.session.prefs().guides_grid_and_slices.guide_color.clone(); + let id = open(&mut app); + for (k, v) in [ + ("columns", json!(5)), + ("rows", json!(3)), + ("gutter", json!(24)), + ("margin", json!([20, 40, 60, 80])), + ("color", json!("#ff00ff")), + ("clearExisting", json!(true)), + ] { + app.ui.dialog_mut(id).unwrap().fields.insert(k.into(), v); + } + let (pending, shown_color) = preview(&app, &app.session.active().unwrap().doc).unwrap(); + assert_ne!(pending, original); + assert_eq!(shown_color, Color32::from_rgb(255, 0, 255)); + assert_eq!(app.session.active().unwrap().revision, revision); + assert_eq!(app.session.prefs().guides_grid_and_slices.guide_color, color); + crate::dialogs::cancel(&mut app, id).unwrap(); + assert!(preview(&app, &app.session.active().unwrap().doc).is_none()); + assert_eq!(app.session.active().unwrap().doc.guides, original); + assert_eq!(app.session.prefs().guides_grid_and_slices.guide_color, color); +} + +#[test] +fn ok_matches_preview_and_is_one_undo_step() { + let mut app = app(); + app.run(COMMAND, json!({"columns":2})).unwrap(); + let original = app.session.active().unwrap().doc.guides.clone(); + let id = open(&mut app); + for (k, v) in [ + ("columns", json!(3)), + ("rows", json!(2)), + ("width", json!("100*2")), + ("height", json!(150)), + ("centerColumns", json!(true)), + ("clearExisting", json!(true)), + ("color", json!("#ff00ff")), + ] { + app.ui.dialog_mut(id).unwrap().fields.insert(k.into(), v); + } + let expected = preview(&app, &app.session.active().unwrap().doc).unwrap().0; + crate::dialogs::confirm(&mut app, id).unwrap(); + assert_eq!(app.session.active().unwrap().doc.guides, expected); + assert_eq!(app.session.prefs().guides_grid_and_slices.guide_color, "#ff00ff"); + assert!(preview(&app, &app.session.active().unwrap().doc).is_none()); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().doc.guides, original); +} + +#[test] +fn preview_off_and_foreign_document_never_replace_guides() { + let mut app = app(); + let id = open(&mut app); + app.ui.dialog_mut(id).unwrap().fields.insert("__preview".into(), json!(false)); + assert!(preview(&app, &app.session.active().unwrap().doc).is_none()); + app.ui.dialog_mut(id).unwrap().fields.insert("__preview".into(), json!(true)); + app.run("file.new", json!({"width":50,"height":50})).unwrap(); + assert!(preview(&app, &app.session.active().unwrap().doc).is_none()); + assert!(crate::dialogs::confirm(&mut app, id).is_err()); + assert!(app.ui.dialog_mut(id).is_some()); +} + +#[test] +fn invalid_fields_keep_last_valid_preview_and_dialog_open() { + let mut app = app(); + let id = open(&mut app); + draw(&mut app, id); + let expected = preview(&app, &app.session.active().unwrap().doc).unwrap().0; + app.ui.dialog_mut(id).unwrap().fields.insert("gutter".into(), json!(1000)); + assert!(crate::dialogs::confirm(&mut app, id).is_err()); + assert!(app.ui.dialog_mut(id).is_some()); + assert_eq!(preview(&app, &app.session.active().unwrap().doc).unwrap().0, expected); + app.ui.dialog_mut(id).unwrap().fields.insert("gutter".into(), json!(20)); + app.ui.dialog_mut(id).unwrap().fields.insert("color".into(), json!("invalid")); + assert!(crate::dialogs::confirm(&mut app, id).is_err()); + assert!(app.ui.dialog_mut(id).is_some()); +} + +#[test] +fn disabled_axes_preserve_values_and_do_not_validate_stale_inputs() { + let mut app = app(); + let id = open(&mut app); + let f = &mut app.ui.dialog_mut(id).unwrap().fields; + for (k, v) in [("columns", json!(8)), ("width", json!("invalid")), ("gutter", json!(2000)), ("__columnsEnabled", json!(false)), ("rows", json!(3))] { + f.insert(k.into(), v); + } + let p = params(f); + assert_eq!(p["columns"], 0); + assert_eq!(p["width"], Value::Null); + assert_eq!(f["columns"], 8); + crate::dialogs::confirm(&mut app, id).unwrap(); + assert!(app.session.active().unwrap().doc.guides.vertical.is_empty()); + let reopened = open(&mut app); + let f = &app.ui.dialog_mut(reopened).unwrap().fields; + assert_eq!(f["columns"], 8); + assert_eq!(f["__columnsEnabled"], false); +} + +#[test] +fn parent_cancel_also_closes_guide_color_picker() { + let mut app = app(); + let id = open(&mut app); + let child = crate::color_picker_ui::open_for_field(&mut app, "Color Picker", [0.0, 1.0, 1.0], id, "color"); + assert!(crate::dialogs::confirm(&mut app, id).is_err()); + crate::dialogs::cancel(&mut app, id).unwrap(); + assert!(app.ui.dialog_mut(child).is_none()); + assert!(app.ui.dialog_mut(id).is_none()); +} + +#[test] +fn automation_opens_the_same_guide_layout_dialog() { + let mut app = app(); + app.ui.view.guide_layout["target"] = json!("selectedArtboards"); + let id = crate::dialogs::open_command_dialog(&mut app, COMMAND, "New Guide Layout"); + assert!(owns(&app.ui.dialog_mut(id).unwrap().fields)); + assert_eq!(app.ui.dialog_mut(id).unwrap().fields["target"], "document"); + assert!(preview(&app, &app.session.active().unwrap().doc).is_some()); +} + +#[test] +fn preview_cache_tracks_document_revision() { + let mut app = app(); + let id = open(&mut app); + draw(&mut app, id); + assert!(!preview(&app, &app.session.active().unwrap().doc).unwrap().0.vertical.contains(&23.0)); + app.run(COMMAND, json!({"margin":23})).unwrap(); + assert!(preview(&app, &app.session.active().unwrap().doc).unwrap().0.vertical.contains(&23.0)); +} diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 02e36d68ab..f04b62e06c 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -19,6 +19,25 @@ # (PhotoCraft, ArtCraft, OpenType, CMYK, Lab ...) stay in Latin letters; the trailing "…" of # dialog commands is kept. +# Guide layout dialog + Columns Sloupce + Rows Řádky + Number Počet + Margin Okraj + Top: Nahoře: + Left: Vlevo: + Bottom: Dole: + Right: Vpravo: + Target: Cíl: + Selected Artboards Vybraná kreslicí plátna + Center Columns Vystředit sloupce + Clear Existing Guides Odstranit stávající vodítka + Invalid guide layout Neplatné rozvržení vodítek + Leave empty for automatic size Pro automatickou velikost ponechte prázdné + 5 Columns, 3 Rows 5 sloupců, 3 řádky + 8 Columns 8 sloupců + 12 Columns 12 sloupců + File Soubor Edit Úpravy Image Obraz diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index d5fe68f514..e5180a8b39 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -15,6 +15,25 @@ # way. Product and technology names (PhotoCraft, ArtCraft, OpenType, CMYK, Lab ...) stay in Latin # letters; the trailing "…" of dialog commands is kept. Plural rule: one|other (n != 1 -> other). +# Guide layout dialog + Columns Spalten + Rows Zeilen + Number Anzahl + Margin Rand + Top: Oben: + Left: Links: + Bottom: Unten: + Right: Rechts: + Target: Ziel: + Selected Artboards Ausgewählte Zeichenflächen + Center Columns Spalten zentrieren + Clear Existing Guides Vorhandene Hilfslinien löschen + Invalid guide layout Ungültiges Hilfslinien-Layout + Leave empty for automatic size Für automatische Größe leer lassen + 5 Columns, 3 Rows 5 Spalten, 3 Zeilen + 8 Columns 8 Spalten + 12 Columns 12 Spalten + File Datei Edit Bearbeiten Image Bild diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 3b0c12a11b..607740e675 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2,6 +2,24 @@ # Columns separated by TAB: context, English source, Greek translation. # Original translations based on general Greek graphics/computing terminology. # Covers every source label the i18n coverage check lists. + +# Guide layout dialog + Rows Γραμμές + Number Πλήθος + Top: Επάνω: + Left: Αριστερά: + Bottom: Κάτω: + Right: Δεξιά: + Target: Στόχος: + Selected Artboards Επιλεγμένοι πίνακες γραφικών + Center Columns Κεντράρισμα στηλών + Clear Existing Guides Διαγραφή υπαρχόντων οδηγών + Invalid guide layout Μη έγκυρη διάταξη οδηγών + Leave empty for automatic size Αφήστε κενό για αυτόματο μέγεθος + 5 Columns, 3 Rows 5 στήλες, 3 γραμμές + 8 Columns 8 στήλες + 12 Columns 12 στήλες + File Αρχείο Edit Επεξεργασία Image Εικόνα diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index df6dfd2aa0..4e0480bca9 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -11,6 +11,26 @@ # resource, string table or product UI was consulted or copied; add entries the same way. # Product and technology names (PhotoCraft, ArtCraft, OpenType, CMYK, Lab ...) stay in Latin # letters; the trailing "…" of dialog commands is kept. + +# Guide layout dialog + Columns Columnas + Rows Filas + Number Número + Margin Margen + Top: Superior: + Left: Izquierda: + Bottom: Inferior: + Right: Derecha: + Target: Destino: + Selected Artboards Mesas de trabajo seleccionadas + Center Columns Centrar columnas + Clear Existing Guides Eliminar guías existentes + Invalid guide layout Disposición de guías no válida + Leave empty for automatic size Dejar vacío para el tamaño automático + 5 Columns, 3 Rows 5 columnas, 3 filas + 8 Columns 8 columnas + 12 Columns 12 columnas + File Archivo Edit Edición Image Imagen diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 3dbc15e6cf..e071631426 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -18,6 +18,25 @@ # « : ; ? ! » and "%", and inside guillemets « … ». Product and technology names (PhotoCraft, # ArtCraft, OpenType, Lab ...) stay as they are; RGB/CMYK read RVB/CMJN; the trailing "…" of # dialog commands is kept. + +# Guide layout dialog + Rows Lignes + Number Nombre + Margin Marge + Top: Haut : + Left: Gauche : + Bottom: Bas : + Right: Droite : + Target: Cible : + Selected Artboards Plans de travail sélectionnés + Center Columns Centrer les colonnes + Clear Existing Guides Effacer les repères existants + Invalid guide layout Disposition des repères non valide + Leave empty for automatic size Laisser vide pour une taille automatique + 5 Columns, 3 Rows 5 colonnes, 3 lignes + 8 Columns 8 colonnes + 12 Columns 12 colonnes + File Fichier Edit Édition Image Image diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 6083c94dcc..73c038e93d 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -11,6 +11,25 @@ # resource, string table or product UI was consulted or copied; add entries the same way. # Product and technology names (PhotoCraft, ArtCraft, OpenType, CMYK, Lab ...) stay in Latin # letters; the trailing "…" of dialog commands is kept. + +# Guide layout dialog + Rows Baris + Number Jumlah + Margin Margin + Top: Atas: + Left: Kiri: + Bottom: Bawah: + Right: Kanan: + Target: Target: + Selected Artboards Artboard yang dipilih + Center Columns Pusatkan kolom + Clear Existing Guides Hapus panduan yang ada + Invalid guide layout Tata letak panduan tidak valid + Leave empty for automatic size Kosongkan untuk ukuran otomatis + 5 Columns, 3 Rows 5 kolom, 3 baris + 8 Columns 8 kolom + 12 Columns 12 kolom + File Berkas Edit Edit Image Gambar diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 4eeda8a3e0..e1180f8cd9 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -11,6 +11,26 @@ # resource, string table or product UI was consulted or copied; add entries the same way. # Product and technology names (PhotoCraft, ArtCraft, OpenType, CMYK, Lab ...) stay in Latin # letters; the trailing … of dialog commands is kept. + +# Guide layout dialog + Columns Colonne + Rows Righe + Number Numero + Margin Margine + Top: Alto: + Left: Sinistra: + Bottom: Basso: + Right: Destra: + Target: Destinazione: + Selected Artboards Tavole da disegno selezionate + Center Columns Centra colonne + Clear Existing Guides Elimina guide esistenti + Invalid guide layout Layout delle guide non valido + Leave empty for automatic size Lasciare vuoto per la dimensione automatica + 5 Columns, 3 Rows 5 colonne, 3 righe + 8 Columns 8 colonne + 12 Columns 12 colonne + File File Edit Modifica Image Immagine diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index c7777e64a2..1cb1358750 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -15,6 +15,23 @@ # Product and technology names (PhotoCraft, ArtCraft, OpenType, CMYK, Lab ...) stay in Latin # letters; the trailing "…" of dialog commands is kept. +# Guide layout dialog + Rows 行 + Number 数 + Top: 上: + Left: 左: + Bottom: 下: + Right: 右: + Target: 対象: + Selected Artboards 選択したアートボード + Center Columns 列を中央に配置 + Clear Existing Guides 既存のガイドを削除 + Invalid guide layout ガイドレイアウトが無効です + Leave empty for automatic size 自動サイズにするには空欄にします + 5 Columns, 3 Rows 5列、3行 + 8 Columns 8列 + 12 Columns 12列 + File ファイル Edit 編集 Image 画像 diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index f6b1bee14e..2f6347d6c1 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -7,6 +7,24 @@ # Licensed MIT OR Apache-2.0. See LICENSE-translations.txt and ATTRIBUTION.md. # Product names and technology names retain their spelling. +# Guide layout dialog + Columns 열 + Rows 행 + Number 개수 + Top: 위: + Left: 왼쪽: + Bottom: 아래: + Right: 오른쪽: + Target: 대상: + Selected Artboards 선택한 아트보드 + Center Columns 열 가운데 정렬 + Clear Existing Guides 기존 안내선 지우기 + Invalid guide layout 잘못된 안내선 레이아웃 + Leave empty for automatic size 자동 크기를 사용하려면 비워 두세요 + 5 Columns, 3 Rows 5열, 3행 + 8 Columns 8열 + 12 Columns 12열 + File 파일 Edit 편집 Image 이미지 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 8d1e1f6c6c..713f935b41 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -8,6 +8,23 @@ # stay as they are; the trailing "…" of dialog commands is kept. UI text addresses the user # informally ("je") and uses sentence case. +# Guide layout dialog + Rows Rijen + Number Aantal + Top: Boven: + Left: Links: + Bottom: Onder: + Right: Rechts: + Target: Doel: + Selected Artboards Geselecteerde tekengebieden + Center Columns Kolommen centreren + Clear Existing Guides Bestaande hulplijnen wissen + Invalid guide layout Ongeldige hulplijnindeling + Leave empty for automatic size Leeg laten voor automatische grootte + 5 Columns, 3 Rows 5 kolommen, 3 rijen + 8 Columns 8 kolommen + 12 Columns 12 kolommen + File Bestand Edit Bewerken Image Afbeelding diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 4e87d5b537..335b8d0690 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -18,6 +18,23 @@ # Conventions: menus are nouns (Plik, Edycja, Obraz ...), commands are infinitives (Otwórz…, # Zapisz jako…), sentence case as in the English source. Quotes: „…”. +# Guide layout dialog + Rows Wiersze + Number Liczba + Top: Góra: + Left: Lewo: + Bottom: Dół: + Right: Prawo: + Target: Cel: + Selected Artboards Wybrane obszary kompozycji + Center Columns Wyśrodkuj kolumny + Clear Existing Guides Usuń istniejące linie pomocnicze + Invalid guide layout Nieprawidłowy układ linii pomocniczych + Leave empty for automatic size Pozostaw puste dla rozmiaru automatycznego + 5 Columns, 3 Rows 5 kolumn, 3 wiersze + 8 Columns 8 kolumn + 12 Columns 12 kolumn + File Plik Edit Edycja Image Obraz diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 587069bd5d..beea57d3cf 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -15,6 +15,24 @@ # entries the same way. Product and technology names (PhotoCraft, ArtCraft, OpenType, CMYK, Lab ...) # stay as they are; the trailing "…" of dialog commands is kept. +# Guide layout dialog + Rows Linhas + Number Número + Margin Margem + Top: Superior: + Left: Esquerda: + Bottom: Inferior: + Right: Direita: + Target: Destino: + Selected Artboards Pranchetas selecionadas + Center Columns Centralizar colunas + Clear Existing Guides Limpar guias existentes + Invalid guide layout Layout de guias inválido + Leave empty for automatic size Deixe vazio para tamanho automático + 5 Columns, 3 Rows 5 colunas, 3 linhas + 8 Columns 8 colunas + 12 Columns 12 colunas + File Arquivo Edit Editar Image Imagem diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 0b950a69d9..3ec3ce023c 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -18,6 +18,25 @@ # the Russian typographic equivalent, with the space the source carries. # Menus + +# Guide layout dialog + Rows Строки + Number Количество + Margin Поля + Top: Сверху: + Left: Слева: + Bottom: Снизу: + Right: Справа: + Target: Цель: + Selected Artboards Выбранные монтажные области + Center Columns Центрировать столбцы + Clear Existing Guides Удалить существующие направляющие + Invalid guide layout Недопустимый макет направляющих + Leave empty for automatic size Оставьте пустым для автоматического размера + 5 Columns, 3 Rows 5 столбцов, 3 строки + 8 Columns 8 столбцов + 12 Columns 12 столбцов + File Файл Edit Редактирование Image Изображение diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 66ea4366cb..e15aee93a1 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -9,6 +9,24 @@ # Licensed MIT OR Apache-2.0. See LICENSE-translations.txt and ATTRIBUTION.md. # Menus + +# Guide layout dialog + Rows Рядки + Number Кількість + Top: Зверху: + Left: Ліворуч: + Bottom: Знизу: + Right: Праворуч: + Target: Ціль: + Selected Artboards Вибрані монтажні області + Center Columns Центрувати стовпці + Clear Existing Guides Видалити наявні напрямні + Invalid guide layout Неприпустимий макет напрямних + Leave empty for automatic size Залиште порожнім для автоматичного розміру + 5 Columns, 3 Rows 5 стовпців, 3 рядки + 8 Columns 8 стовпців + 12 Columns 12 стовпців + File Файл Edit Редагування Image Зображення diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 1c36a77ac6..362c3c9d84 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -11,6 +11,25 @@ # Licensed MIT OR Apache-2.0, as the code. # Product and technology names retain their spelling. See docs/localization-zh-hans.md. +# Guide layout dialog + Columns 列 + Rows 行 + Number 数量 + Margin 边距 + Top: 上: + Left: 左: + Bottom: 下: + Right: 右: + Target: 目标: + Selected Artboards 所选画板 + Center Columns 列居中 + Clear Existing Guides 清除现有参考线 + Invalid guide layout 参考线布局无效 + Leave empty for automatic size 留空以自动设置大小 + 5 Columns, 3 Rows 5列,3行 + 8 Columns 8列 + 12 Columns 12列 + File 文件 Edit 编辑 Image 图像 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index cba84fda39..e278e45501 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -19,6 +19,25 @@ # kept. Full-width punctuation (,。:) inside sentences; half-width parentheses and the " · " # separators as in the English. +# Guide layout dialog + Columns 欄 + Rows 列 + Number 數量 + Margin 邊界 + Top: 上: + Left: 左: + Bottom: 下: + Right: 右: + Target: 目標: + Selected Artboards 選取的工作區域 + Center Columns 欄置中 + Clear Existing Guides 清除現有參考線 + Invalid guide layout 參考線版面配置無效 + Leave empty for automatic size 留白以自動設定大小 + 5 Columns, 3 Rows 5欄,3列 + 8 Columns 8欄 + 12 Columns 12欄 + File 檔案 Edit 編輯 Image 影像 diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 406b9b1225..d60e774f7b 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -81,6 +81,7 @@ pub mod gallery_ui; pub mod gpu_canvas; pub mod gpu_status; pub mod gradient_ui; +pub mod guide_layout_ui; pub mod hold_keys; pub mod i18n; mod icon_data; diff --git a/crates/ui-egui/src/rulers.rs b/crates/ui-egui/src/rulers.rs index dde9c09ab9..eb36839d65 100644 --- a/crates/ui-egui/src/rulers.rs +++ b/crates/ui-egui/src/rulers.rs @@ -143,11 +143,25 @@ pub fn draw_grid(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform, d } } +pub(crate) fn parse_guide_color(value: &str) -> Option { + let value = value.strip_prefix('#')?; + if value.len() != 6 { + return None; + } + let r = u8::from_str_radix(value.get(0..2)?, 16).ok()?; + let g = u8::from_str_radix(value.get(2..4)?, 16).ok()?; + let b = u8::from_str_radix(value.get(4..6)?, 16).ok()?; + Some(Color32::from_rgb(r, g, b)) +} + pub fn draw_guides(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform, doc: &Document) { let clip = painter.clip_rect(); let drag = app.guide_drag; let g = &app.session.prefs().guides_grid_and_slices; - let (guide, style) = (pref_color(&g.guide_color, Color32::from_rgb(74, 255, 255)), g.guide_style); + let preview = crate::guide_layout_ui::preview(app, doc); + let guides = preview.as_ref().map(|(guides, _)| guides).unwrap_or(&doc.guides); + let (guide, style) = + (preview.as_ref().map(|(_, color)| *color).unwrap_or_else(|| pref_color(&g.guide_color, Color32::from_rgb(74, 255, 255))), g.guide_style); let line = |vertical: bool, pos: f64, color: Color32| { if vertical { let x = xf.to_screen(pos as f32, 0.0).x; @@ -157,8 +171,8 @@ pub fn draw_guides(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform, styled_line(painter, pos2(clip.left(), y), pos2(clip.right(), y), Stroke::new(1.0, color), style); } }; - if app.ui.extras.guides { - for (vertical, list) in [(true, &doc.guides.vertical), (false, &doc.guides.horizontal)] { + if app.ui.extras.guides || preview.is_some() { + for (vertical, list) in [(true, &guides.vertical), (false, &guides.horizontal)] { for (i, p) in list.iter().enumerate() { if drag.is_some_and(|d| d.vertical == vertical && d.index == Some(i)) { continue; diff --git a/crates/ui-egui/src/view_cmds.rs b/crates/ui-egui/src/view_cmds.rs index 48500e145f..435df87ec7 100644 --- a/crates/ui-egui/src/view_cmds.rs +++ b/crates/ui-egui/src/view_cmds.rs @@ -1003,10 +1003,7 @@ fn front(app: &mut PhotocraftApp, id: &str, params: &Value) -> Option { - let fields = app.ui.view.guide_layout.clone(); - dialog(app, fields, json!({})) - } + "view.newGuideLayout" => Some(Ok(json!({"dialog": crate::guide_layout_ui::open(app)}))), "type.warpText" => Some(Ok(json!({"dialog": crate::dialogs::open_command_dialog(app, id, label)}))), "file.export.layersToFiles" => { let (_, _, name) = doc?; diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 500ff3526e..ccd7877e1d 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -479,7 +479,9 @@ fn number_edit(ui: &mut Ui, value: &mut f32, range: std::ops::RangeInclusive Date: Sun, 11 Oct 2026 14:24:51 +0200 Subject: [PATCH 3/4] perf: pasting a layer recomposites only where it draws (#2901) (#2917) * perf: Duplicate Layer recomposites only where the copy draws (#2883) Duplicating a layer reported no damage, so the canvas recomposited the whole document after every Duplicate Layer (P8/P9). The copy itself was already cheap (tiles are shared Arcs). Report the copy's change bounds instead, through the step_damage walk extended to bounded additions: self-contained added layers (not an adjustment, not a new clipping base, no video or excluded channels) contribute their change bounds; anything else still recomposites everything. Co-Authored-By: Claude Opus 5.5 * perf: pasting a layer recomposites only where it draws (#2901) Paste (and Paste in Place, Paste Into, Paste Outside) inserted the pasted layer through Session::edit, which reports no damage, so every paste recomposited the whole document (P10/P11). Capture the document before the paste and report the new layer's change bounds with note_insert, as Duplicate Layer does (#2884). Anything that isn't self-contained (a new clipping base, video, excluded channels) still recomposites everything. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/engine/src/edit_cmds.rs | 44 +++++++++++++++++++++++++++++++++ crates/engine/src/extra_cmds.rs | 3 +++ 2 files changed, 47 insertions(+) diff --git a/crates/engine/src/edit_cmds.rs b/crates/engine/src/edit_cmds.rs index 439bfd6b7d..ebe642a679 100644 --- a/crates/engine/src/edit_cmds.rs +++ b/crates/engine/src/edit_cmds.rs @@ -235,6 +235,7 @@ fn paste(s: &mut Session, p: &Value, in_place: bool) -> Result { let moved = shifted(&clip.surface, dx, dy); let target = PixelFormat::new(fmt.mode, fmt.sample, true); let surf = if moved.format() == target { moved } else { moved.convert(target) }; + let before = d.doc.clone(); let id = s.edit("Paste", |doc, active| { let mut l = Layer::raster(doc.next_layer_name("Layer"), target); *crate::pixels_mut(&mut l)? = surf; @@ -243,6 +244,8 @@ fn paste(s: &mut Session, p: &Value, in_place: bool) -> Result { doc.selection = None; Ok(id) })?; + // Only where the pasted pixels land needs recompositing, not the whole document (#2901). + crate::layer_multi_cmds::note_insert(s, &before); Ok(json!({"layer": id.0, "offset": [dx, dy]})) } @@ -908,6 +911,47 @@ mod tests { assert!(px[0][0] > 0.9 && px[0][1] < 0.1 && px[0][2] < 0.1, "pasted content is red: {:?}", px[0]); } + /// #2901 (P10/P11): Paste, Paste in Place and Paste Into recomposite only where the pasted + /// layer draws, not the whole document; nothing outside that changes, and undo brings back + /// exactly the old pixels. + #[test] + fn paste_damages_only_the_pasted_layer() { + let render = |s: &Session| photocraft_compose::render(&s.active().unwrap().doc, s.active().unwrap().doc.bounds()); + for depth in [8, 16, 32] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 60, "height": 50, "depth": depth, "background": "white"})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("select.rect", json!({"x": 5, "y": 5, "width": 10, "height": 8})).unwrap(); + s.execute("edit.fill", json!({"color": "#3366cc"})).unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + // Half transparent, so an opaque copy pasted in place over it shows. + s.execute("layer.setProps", json!({"opacity": 0.5})).unwrap(); + for (id, p) in [ + ("edit.paste", json!({"center": [40, 30]})), + ("edit.pasteSpecial.pasteInPlace", json!({})), + ("edit.pasteSpecial.pasteInto", json!({"center": [40, 30]})), + ] { + s.execute("select.rect", json!({"x": 36, "y": 27, "width": 6, "height": 4})).unwrap(); + let shown = render(&s); + s.execute(id, p).unwrap(); + let st = s.active().unwrap(); + let area = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().content_bounds(); + let damage = st.last_damage.unwrap_or_else(|| panic!("{depth}-bit {id}: bounded damage")); + assert!(!damage.is_empty() && damage.intersect(&area) == damage, "{depth}-bit {id}: {damage:?} within {area:?}"); + let now = render(&s); + assert_ne!(now, shown, "{depth}-bit {id}: the paste shows"); + let w = shown.rect.width() as usize; + for (i, (a, b)) in shown.px.iter().zip(&now.px).enumerate() { + if !damage.contains((i % w) as i32, (i / w) as i32) { + assert_eq!(a, b, "{depth}-bit {id}: pixel {i} outside the damage changed"); + } + } + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(render(&s), shown, "{depth}-bit {id}: undo"); + } + } + } + /// #1035: a `depth`-bit document with a blue-grey square copied from layer `src` (at /// (5,5)-(15,15)) and an active layer `m` above it with a hide-all mask. fn mask_target_session(depth: u32) -> (Session, LayerId, LayerId) { diff --git a/crates/engine/src/extra_cmds.rs b/crates/engine/src/extra_cmds.rs index f46c53e169..f25ea9a2e9 100644 --- a/crates/engine/src/extra_cmds.rs +++ b/crates/engine/src/extra_cmds.rs @@ -414,6 +414,7 @@ fn paste_into(s: &mut Session, p: &Value, outside: bool) -> Result { let key = step_key(s, "pasteInto"); params["coalesce"] = json!(key); params["target"] = json!("pixels"); + let before = s.active().ok_or(EngineError::NoDocument)?.doc.clone(); let r = s.execute("edit.paste", params)?; let id = layer_param(s, &Value::Null)?; s.execute("layer.layerMask.revealAll", json!({"layer": id.0, "coalesce": key}))?; @@ -425,6 +426,8 @@ fn paste_into(s: &mut Session, p: &Value, outside: bool) -> Result { }); s.coalesce_request = None; r2?; + // Only where the masked paste draws needs recompositing (#2901). + crate::layer_multi_cmds::note_insert(s, &before); Ok(r) } From 0b4b1e4286436a3ce4cd8bb14199174fbc7482a5 Mon Sep 17 00:00:00 2001 From: Unemars <62496697+Unemars@users.noreply.github.com> Date: Sun, 11 Oct 2026 14:25:21 +0200 Subject: [PATCH 4/4] Image Size: Photoshop's resampling, measured (#2451) * Image Size: Photoshop's resampling, measured Photoshop 25.4's Image Size was measured as a black box (synthetic 16-bit images in, exact RAW out); every method but Preserve Details' enlargement is linear, so each was taken apart from its impulse responses. - Bicubic is the Keys cubic at a = -0.75, not Catmull-Rom. - Bicubic Smoother (stretched x1.15, a = -0.625) and Bicubic Sharper (x1.05, a = -1), with a growing with the reduction, and Bicubic Automatic. - Reducing widens the filter by 1/s; below 1/4 the image is first averaged down to four times the target. Bilinear is never widened and averages whole pixels below 1/2. Positions are rounded to 1/128 pixel and stop at the edge pixel's centre. - Two passes, the smaller scale first, clipped and stored between them; the bicubic filter is designed for the height's scale and serves both axes. Bicubic Automatic splits a mixed resize into Sharper, then Smoother. - Image Size and Fit Image take automatic, bicubicSmoother, bicubicSharper and bicubicAutomatic; the dialog lists Photoshop's methods and opens on the interpolation preference. On 225 probes the mean error falls from 240-550 to under 0.5 levels of 32768; 8-bit results are identical to Photoshop's for 99 % of values. Co-Authored-By: Claude Opus 5.5 (1M context) * Format: one rustfmt change main needs Co-Authored-By: Claude Opus 5.5 (1M context) --------- Co-authored-by: Claude Opus 5.5 (1M context) --- crates/algo/src/resample.rs | 464 +++++++++++++++++++++++----- crates/engine/src/file_cmds.rs | 2 +- crates/engine/src/image_cmds.rs | 49 ++- crates/ui-egui/src/i18n/cs.tsv | 3 + crates/ui-egui/src/i18n/de.tsv | 3 + crates/ui-egui/src/i18n/el.tsv | 2 + crates/ui-egui/src/i18n/es.tsv | 3 + crates/ui-egui/src/i18n/fr.tsv | 3 + crates/ui-egui/src/i18n/id.tsv | 3 + crates/ui-egui/src/i18n/it.tsv | 3 + crates/ui-egui/src/i18n/ja.tsv | 3 + crates/ui-egui/src/i18n/ko.tsv | 3 + crates/ui-egui/src/i18n/nl.tsv | 2 + crates/ui-egui/src/i18n/pl.tsv | 3 + crates/ui-egui/src/i18n/pt-br.tsv | 3 + crates/ui-egui/src/i18n/ru.tsv | 3 + crates/ui-egui/src/i18n/uk.tsv | 3 + crates/ui-egui/src/i18n/zh-hans.tsv | 3 + crates/ui-egui/src/i18n/zh-hant.tsv | 3 + crates/ui-egui/src/sizing.rs | 42 ++- 20 files changed, 510 insertions(+), 93 deletions(-) diff --git a/crates/algo/src/resample.rs b/crates/algo/src/resample.rs index 918eb899a0..bd728e379d 100644 --- a/crates/algo/src/resample.rs +++ b/crates/algo/src/resample.rs @@ -6,7 +6,7 @@ use serde::{Deserialize, Serialize}; use crate::image::{premultiply, unpremultiply}; -/// Resampling method (Photoshop's Image Size options). +/// Resampling method (Photoshop's Image Size options, and Lanczos). #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] #[serde(rename_all = "camelCase")] pub enum Resample { @@ -14,51 +14,121 @@ pub enum Resample { Bilinear, #[default] Bicubic, + /// Photoshop's Bicubic Smoother, for enlargement. + BicubicSmoother, + /// Photoshop's Bicubic Sharper, for reduction. + BicubicSharper, + /// Photoshop's Bicubic Automatic: Smoother where the image grows, Sharper where it shrinks. + BicubicAutomatic, Lanczos, - /// Lanczos followed by a light sharpening when enlarging. + /// Lanczos followed by a light sharpening when enlarging; Bicubic Sharper when reducing, as + /// Photoshop's Preserve Details reduces. PreserveDetails, } -impl Resample { - fn support(self) -> f64 { - match self { - Resample::Nearest => 0.5, - Resample::Bilinear => 1.0, - Resample::Bicubic => 2.0, - Resample::Lanczos | Resample::PreserveDetails => 3.0, - } +/// Sub-pixel positions Photoshop's filters resolve: a sample's offset is rounded to 1/128 pixel. +const PHASES: f64 = 128.0; + +/// The filter of one axis. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Kernel { + Nearest, + /// Linear interpolation, never widened. Below half size, each output pixel is the plain + /// average of the source pixels it covers. + Bilinear, + /// The Keys cubic with parameter `a`, stretched over `stretch` source pixels. + Keys { + a: f64, + stretch: f64, + }, + /// Lanczos-3, widened by 1/scale when reducing. + Lanczos, +} + +/// Photoshop's bicubic filters, measured on Photoshop 25.4 (the Keys cubic, phase table and +/// stretch fitted to within 1/4000 of every weight). `s` is the scale the filter is designed for. +/// +/// - Bicubic: a = −0.75. +/// - Bicubic Smoother: stretched by 1.15; a = −0.625, and −0.625 − 0.5·(1 − s) when reducing. +/// - Bicubic Sharper: stretched by 1.05; a = −1, and −1 − 1.6·(1 − s) when reducing. +/// +/// Reducing widens the filter by 1/s, down to ¼; below that [`taps`] first averages the image +/// down to four times the target. +fn keys(method: Resample, s: f64) -> Kernel { + let s = s.clamp(0.25, 1.0); + let (a, stretch) = match method { + Resample::BicubicSmoother => (-0.625 - 0.5 * (1.0 - s), 1.15), + Resample::BicubicSharper => (-1.0 - 1.6 * (1.0 - s), 1.05), + _ => (-0.75, 1.0), + }; + Kernel::Keys { a, stretch: stretch / s } +} + +fn keys_weight(x: f64, a: f64) -> f64 { + let x = x.abs(); + if x < 1.0 { + (a + 2.0) * x * x * x - (a + 3.0) * x * x + 1.0 + } else if x < 2.0 { + a * (x * x * x - 5.0 * x * x + 8.0 * x - 4.0) + } else { + 0.0 } - fn weight(self, x: f64) -> f64 { - let x = x.abs(); - match self { - Resample::Nearest => { - if x <= 0.5 { - 1.0 - } else { - 0.0 - } +} + +fn lanczos_weight(x: f64) -> f64 { + let x = x.abs(); + if x < 1e-9 { + 1.0 + } else if x < 3.0 { + let px = std::f64::consts::PI * x; + 3.0 * px.sin() * (px / 3.0).sin() / (px * px) + } else { + 0.0 + } +} + +/// One resampling pass: scale factors and the filter of each axis. +#[derive(Clone, Copy, Debug)] +struct Pass { + sx: f64, + sy: f64, + kx: Kernel, + ky: Kernel, +} + +/// Photoshop's passes for `filter` at `(sx, sy)`. +/// +/// A bicubic filter is designed for the height's scale, or the width's when the height stays, +/// and serves both axes; the axis with the smaller scale goes first, and the image is clipped and +/// stored between the passes. Bicubic Automatic with one axis growing and the other shrinking is +/// two Image Sizes: the shrinking axis with Sharper, then the growing one with Smoother, each +/// designed for its own scale. Nearest, Bilinear and Lanczos run both axes in one pass. +fn plan(filter: Resample, sx: f64, sy: f64) -> Vec { + let both = |k: Kernel| vec![Pass { sx, sy, kx: k, ky: k }]; + match filter { + Resample::Nearest => both(Kernel::Nearest), + Resample::Bilinear => both(Kernel::Bilinear), + Resample::Lanczos => both(Kernel::Lanczos), + Resample::PreserveDetails if sx > 1.0 || sy > 1.0 => both(Kernel::Lanczos), + Resample::PreserveDetails => plan(Resample::BicubicSharper, sx, sy), + Resample::BicubicAutomatic if sx <= 1.0 && sy <= 1.0 => plan(Resample::BicubicSharper, sx, sy), + Resample::BicubicAutomatic if sx >= 1.0 && sy >= 1.0 => plan(Resample::BicubicSmoother, sx, sy), + Resample::BicubicAutomatic => { + let (sharper, smoother) = (Resample::BicubicSharper, Resample::BicubicSmoother); + if sx < 1.0 { + vec![Pass { sx, sy: 1.0, kx: keys(sharper, sx), ky: Kernel::Nearest }, Pass { sx: 1.0, sy, kx: Kernel::Nearest, ky: keys(smoother, sy) }] + } else { + vec![Pass { sx: 1.0, sy, kx: Kernel::Nearest, ky: keys(sharper, sy) }, Pass { sx, sy: 1.0, kx: keys(smoother, sx), ky: Kernel::Nearest }] } - Resample::Bilinear => (1.0 - x).max(0.0), - Resample::Bicubic => { - // Keys cubic, a = -0.5 (Catmull-Rom). - let a = -0.5; - if x < 1.0 { - (a + 2.0) * x * x * x - (a + 3.0) * x * x + 1.0 - } else if x < 2.0 { - a * x * x * x - 5.0 * a * x * x + 8.0 * a * x - 4.0 * a - } else { - 0.0 - } - } - Resample::Lanczos | Resample::PreserveDetails => { - if x < 1e-9 { - 1.0 - } else if x < 3.0 { - let px = std::f64::consts::PI * x; - 3.0 * px.sin() * (px / 3.0).sin() / (px * px) - } else { - 0.0 - } + } + Resample::Bicubic | Resample::BicubicSmoother | Resample::BicubicSharper => { + let k = keys(filter, if sy != 1.0 { sy } else { sx }); + if sx == 1.0 || sy == 1.0 { + both(k) + } else if sy < sx { + vec![Pass { sx: 1.0, sy, kx: k, ky: k }, Pass { sx, sy: 1.0, kx: k, ky: k }] + } else { + vec![Pass { sx, sy: 1.0, kx: k, ky: k }, Pass { sx: 1.0, sy, kx: k, ky: k }] } } } @@ -72,36 +142,91 @@ struct Taps { outside: f32, } -/// Taps for mapping output coordinate `o` (in `[dst0, dst1)`) to the source -/// via `u = (o + 0.5) / scale - 0.5`. With `edge` (`[first, last]` source index), taps outside it -/// read the nearest sample inside it: the image repeats its edge instead of fading out. +/// The source position of output sample `o`, `(o + 0.5) / scale − 0.5`, kept on the edge +/// samples (`[first, last]`) when there is an edge, and rounded to Photoshop's 1/128 pixel. +fn position(o: i32, scale: f64, edge: Option<(i32, i32)>) -> f64 { + let mut u = (o as f64 + 0.5) / scale - 0.5; + if let Some((a, b)) = edge { + u = u.clamp(a as f64, b.max(a) as f64); + } + let j = u.floor(); + j + ((u - j) * PHASES).round() / PHASES +} + +/// The source pixels `[floor(o / scale), floor((o + 1) / scale))` output pixel `o` covers. +fn cover(o: i32, scale: f64) -> (i32, i32) { + let a = (o as f64 / scale + 1e-9).floor() as i32; + (a, ((o + 1) as f64 / scale + 1e-9).floor().max(a as f64 + 1.0) as i32) +} + +/// Unclamped weights of output sample `o` over source samples `lo..lo + len`. +fn weights(o: i32, scale: f64, kernel: Kernel, edge: Option<(i32, i32)>) -> (i32, Vec) { + match kernel { + Kernel::Nearest => { + let u = (o as f64 + 0.5) / scale - 0.5; + ((u + 0.5).floor() as i32, vec![1.0]) + } + Kernel::Bilinear if scale < 0.5 => { + let (a, b) = cover(o, scale); + (a, vec![1.0 / (b - a) as f64; (b - a) as usize]) + } + Kernel::Bilinear => { + let u = position(o, scale, edge); + let j = u.floor(); + (j as i32, vec![1.0 - (u - j), u - j]) + } + Kernel::Keys { a, stretch } if scale < 0.25 => { + // Averaged down to four times the target first (pixels of `inner`), then filtered. + let inner = 4.0 * scale; + let inner_edge = edge.map(|(a, b)| ((a as f64 * inner - 1e-9).ceil() as i32, ((b + 1) as f64 * inner - 1e-9).ceil() as i32 - 1)); + let (k0, kw) = weights(o, 0.25, Kernel::Keys { a, stretch }, inner_edge); + let clamp = |k: i32| inner_edge.map_or(k, |(a, b)| k.clamp(a, b.max(a))); + let boxes: Vec<(i32, i32)> = (k0..).zip(&kw).map(|(k, _)| cover(clamp(k), inner)).collect(); + let lo = boxes.iter().map(|b| b.0).min().unwrap_or(0); + let hi = boxes.iter().map(|b| b.1).max().unwrap_or(lo); + let mut w = vec![0.0; (hi - lo).max(0) as usize]; + for ((a, b), v) in boxes.into_iter().zip(kw) { + for slot in w.get_mut((a - lo) as usize..(b - lo) as usize).into_iter().flatten() { + *slot += v / (b - a) as f64; + } + } + (lo, w) + } + Kernel::Keys { a, stretch } => { + let u = position(o, scale, edge); + let lo = (u - 2.0 * stretch).floor() as i32; + let hi = (u + 2.0 * stretch).ceil() as i32; + let w: Vec = (lo..=hi).map(|i| keys_weight((u - i as f64) / stretch, a)).collect(); + let sum: f64 = w.iter().sum(); + (lo, w.into_iter().map(|v| v / sum).collect()) + } + Kernel::Lanczos => { + let stretch = if scale < 1.0 { 1.0 / scale } else { 1.0 }; + let u = (o as f64 + 0.5) / scale - 0.5; + let u = edge.map_or(u, |(a, b)| u.clamp(a as f64, b.max(a) as f64)); + let lo = (u - 3.0 * stretch).ceil() as i32; + let hi = (u + 3.0 * stretch).floor() as i32; + let w: Vec = (lo..=hi).map(|i| lanczos_weight((i as f64 - u) / stretch)).collect(); + let sum: f64 = w.iter().sum(); + let k = if sum.abs() > 1e-12 { 1.0 / sum } else { 1.0 }; + (lo, w.into_iter().map(|v| v * k).collect()) + } + } +} + +/// Taps for mapping output coordinate `o` (in `[dst0, dst1)`) to the source at `scale` +/// (a scale of 1 copies). With `edge` (`[first, last]` source index), taps outside it read the +/// nearest sample inside it: the image repeats its edge instead of fading out. /// Taps outside `content` (`[first, last]`) all read the default pixel, so they are folded into /// `outside` instead of being read: the read window never grows past the content, however small /// the scale (#713). -fn taps(dst0: i32, dst1: i32, scale: f64, filter: Resample, edge: Option<(i32, i32)>, content: (i32, i32)) -> Vec { - let stretch = if scale < 1.0 { 1.0 / scale } else { 1.0 }; - let support = filter.support() * stretch; +fn taps(dst0: i32, dst1: i32, scale: f64, kernel: Kernel, edge: Option<(i32, i32)>, content: (i32, i32)) -> Vec { let clamp = |i: i32| edge.map_or(i, |(a, b)| i.clamp(a, b)); + let kernel = if scale == 1.0 { Kernel::Nearest } else { kernel }; (dst0..dst1) .map(|o| { - let u = (o as f64 + 0.5) / scale - 0.5; - if filter == Resample::Nearest { - let i = clamp((u + 0.5).floor() as i32); - return if (content.0..=content.1).contains(&i) { - Taps { start: i, weights: vec![1.0], outside: 0.0 } - } else { - Taps { start: content.0, weights: Vec::new(), outside: 1.0 } - }; - } - let lo = (u - support).ceil() as i32; - let hi = (u + support).floor() as i32; - let mut w: Vec = (lo..=hi).map(|i| filter.weight((i as f64 - u) / stretch)).collect(); - let s: f64 = w.iter().sum(); - if s.abs() > 1e-12 { - for v in &mut w { - *v /= s; - } - } + let (lo, w) = weights(o, scale, kernel, edge); + let hi = lo + w.len() as i32 - 1; // Fold the weights of taps beyond the edge onto the edge sample. let start = clamp(lo); let mut folded = vec![0.0f32; (clamp(hi) - start + 1).max(1) as usize]; @@ -141,8 +266,7 @@ pub fn resize_surface(s: &Surface, sx: f64, sy: f64, filter: Resample) -> Surfac /// keeps it (an opaque layer stays opaque to the border) instead of fading into the default pixel. /// Pixels beyond the canvas count as the surface's own, and inside the canvas nothing changes. pub fn resize_surface_in_canvas(s: &Surface, sx: f64, sy: f64, filter: Resample, canvas: Rect) -> Surface { - let area = s.content_bounds().union(&canvas); - resize(s, sx, sy, filter, (!area.is_empty()).then_some(area)) + resize(s, sx, sy, filter, Some(canvas)) } /// Samples one source read may hold (64 MB of `f32`); larger windows are read in row chunks. @@ -183,11 +307,37 @@ fn horizontal_dynamic(row: &[f32], out: &mut [f32], taps: &[Taps], x_lo: i32, de } } -fn resize(s: &Surface, sx: f64, sy: f64, filter: Resample, edge: Option) -> Surface { - resize_with_budget(s, sx, sy, filter, edge, READ_BUDGET) +fn resize(s: &Surface, sx: f64, sy: f64, filter: Resample, canvas: Option) -> Surface { + resize_with_budget(s, sx, sy, filter, canvas, READ_BUDGET) } -fn resize_with_budget(s: &Surface, sx: f64, sy: f64, filter: Resample, edge: Option, budget: usize) -> Surface { +/// Runs `filter`'s passes. Between two passes the image is stored in its own format, which +/// clips it (and rounds it at 8 and 16 bits) as Photoshop does; the smaller scale goes first, so +/// the intermediate image is never larger than the result. +fn resize_with_budget(s: &Surface, sx: f64, sy: f64, filter: Resample, canvas: Option, budget: usize) -> Surface { + let mut cur: Option = None; + let mut canvas = canvas; + for p in plan(filter, sx, sy) { + let next = resize_pass(cur.as_ref().unwrap_or(s), p, canvas, budget); + canvas = canvas.map(|c| scaled_rect(c, p.sx, p.sy)); + cur = Some(next); + } + let mut out = cur.unwrap_or_else(|| s.clone()); + if filter == Resample::PreserveDetails && (sx > 1.0 || sy > 1.0) { + let dst = out.content_bounds(); + let p = crate::FilterParams::UnsharpMask { amount: 30.0, radius: 0.6 * sx.max(sy) as f32, threshold: 0.0 }; + let area = crate::output_area(&p, dst, dst, None); + out = crate::apply(&out, &p, area, dst, None); + } + out.prune(); + out +} + +/// One pass. With `canvas`, the content and the canvas repeat their edge outwards (see +/// [`resize_surface_in_canvas`]). +fn resize_pass(s: &Surface, pass: Pass, canvas: Option, budget: usize) -> Surface { + let Pass { sx, sy, kx, ky } = pass; + let edge = canvas.map(|c| s.content_bounds().union(&c)).filter(|a| !a.is_empty()); let fmt = s.format(); let mut out = Surface::with_default(fmt, &s.default_pixel()); let src = s.content_bounds(); @@ -199,8 +349,8 @@ fn resize_with_budget(s: &Surface, sx: f64, sy: f64, filter: Resample, edge: Opt let alpha = fmt.alpha; // With `edge`, every tap is clamped into the edge area, which holds the content. let area = edge.unwrap_or(src); - let hx = taps(dst.x0, dst.x1, sx, filter, edge.map(|r| (r.x0, r.x1 - 1)), (area.x0, area.x1 - 1)); - let vy = taps(dst.y0, dst.y1, sy, filter, edge.map(|r| (r.y0, r.y1 - 1)), (area.y0, area.y1 - 1)); + let hx = taps(dst.x0, dst.x1, sx, kx, edge.map(|r| (r.x0, r.x1 - 1)), (area.x0, area.x1 - 1)); + let vy = taps(dst.y0, dst.y1, sy, ky, edge.map(|r| (r.y0, r.y1 - 1)), (area.y0, area.y1 - 1)); let x_lo = hx.iter().filter(|t| !t.weights.is_empty()).map(|t| t.start).min().unwrap_or(area.x0); let x_hi = hx.iter().map(|t| t.start + t.weights.len() as i32).max().unwrap_or(area.x0).max(x_lo); let mut def = s.default_pixel(); @@ -312,12 +462,6 @@ fn resize_with_budget(s: &Surface, sx: f64, sy: f64, filter: Resample, edge: Opt out.write_region(r, &d); } } - if filter == Resample::PreserveDetails && (sx > 1.0 || sy > 1.0) { - let p = crate::FilterParams::UnsharpMask { amount: 30.0, radius: 0.6 * sx.max(sy) as f32, threshold: 0.0 }; - let area = crate::output_area(&p, out.content_bounds(), dst, None); - out = crate::apply(&out, &p, area, dst, None); - } - out.prune(); out } @@ -353,7 +497,7 @@ mod tests { fn fixed_channel_rows_match_dynamic_resampling() { fn check() { for scale in [0.12, 0.5, 1.0, 2.3] { - for filter in [Resample::Nearest, Resample::Bilinear, Resample::Bicubic, Resample::Lanczos] { + for filter in [Kernel::Nearest, Kernel::Bilinear, keys(Resample::Bicubic, scale), keys(Resample::BicubicSharper, scale), Kernel::Lanczos] { for clamp in [None, Some((-3, 31))] { let ts = taps(-5, 41, scale, filter, clamp, (-3, 31)); let row: Vec = (0..35 * N).map(|i| ((i * 73) % 251) as f32 / 250.0).collect(); @@ -374,6 +518,170 @@ mod tests { check::<5>(); } + /// Photoshop 25.4's Image Size of a 16-bit greyscale pattern, in levels of 32768. Covers the + /// filters and their 2-D rules: Sharper reducing the width while the height grows is designed + /// for the height (not widened) and runs the width first; Bicubic Automatic splits a mixed + /// resize into Sharper and Smoother; Bicubic widens for the height's 0.6 while the width + /// grows; Smoother below ¼ averages down first; Bilinear below ½ averages whole pixels. On black + /// and white the overshoot is clipped between the passes, so their order shows. + #[test] + fn matches_photoshop_image_size() { + // (black and white pattern, filter, size, new size, Photoshop's levels) + type Probe = (bool, Resample, (i32, i32), (i32, i32), &'static [u16]); + let cases: [Probe; 9] = [ + ( + false, + Resample::BicubicSharper, + (12, 10), + (7, 16), + &[ + 3777, 13165, 22219, 16176, 10460, 19488, 29643, 11249, 12634, 21696, 13330, 10319, 18965, 29120, 21280, 11204, 20279, 16184, 8200, 17548, + 27703, 21824, 10182, 19259, 26967, 5238, 16528, 26683, 17366, 8895, 17922, 32768, 2402, 15190, 25345, 17493, 7834, 16903, 31316, 1748, + 14172, 24326, 24718, 6368, 15746, 30390, 0, 13107, 23169, 31215, 4790, 14456, 27639, 5080, 11597, 21880, 29649, 3864, 13507, 24136, 20600, + 10264, 20931, 28009, 0, 12446, 21385, 28735, 8754, 19642, 26154, 4049, 10895, 20832, 23523, 7620, 18485, 23204, 20126, 8787, 19818, 21447, + 6173, 17467, 20390, 31862, 6616, 18480, 24094, 6500, 16129, 19749, 27472, 5810, 17460, 28281, 7655, 15108, 18394, 25515, 4427, 16043, + 28749, 7026, 13691, 17871, 24992, 3904, 15520, 27200, 6075, 13168, + ], + ), + ( + false, + Resample::BicubicAutomatic, + (12, 10), + (7, 16), + &[ + 4201, 12337, 27677, 15894, 4816, 20021, 29631, 10348, 9882, 27304, 14492, 3766, 19574, 29046, 18743, 5944, 25299, 16116, 4147, 17829, + 27787, 19399, 4206, 21790, 23748, 7966, 15117, 26569, 15941, 2695, 19445, 28341, 10104, 13050, 25465, 16251, 2613, 18023, 26770, 8432, + 11951, 24281, 22800, 7141, 15351, 24790, 5953, 11004, 23130, 28322, 10921, 12440, 24940, 9659, 9368, 22012, 27611, 10006, 10488, 26419, + 18657, 7071, 20807, 25492, 6937, 9239, 26574, 22363, 5435, 19688, 24808, 9136, 8184, 25295, 19708, 3939, 18677, 25053, 18234, 7120, 24061, + 17941, 2545, 17568, 24869, 23748, 6081, 21401, 21862, 6018, 15056, 23602, 22177, 4859, 17816, 28450, 11911, 11653, 22253, 20263, 3595, + 15790, 29734, 12969, 9683, 21668, 19678, 3010, 15424, 28429, 11728, 9300, + ], + ), + ( + false, + Resample::Bicubic, + (12, 10), + (20, 6), + &[ + 11517, 10000, 8617, 9364, 12272, 16362, 21396, 25508, 25506, 19474, 10887, 5289, 5842, 10286, 14986, 18566, 21910, 25511, 28611, 29922, + 24788, 17949, 8497, 4593, 7309, 12594, 17150, 20945, 24892, 26196, 22979, 16123, 9691, 7483, 10061, 14653, 18841, 22420, 25514, 26824, + 25702, 23396, 17586, 11378, 8127, 8882, 12310, 17039, 22345, 25871, 24700, 18125, 9951, 5493, 6802, 11215, 15576, 19259, 22384, 23694, + 26692, 26985, 22732, 14270, 6889, 4950, 8348, 13583, 17529, 21570, 25966, 27275, 22817, 14643, 8068, 6911, 10694, 15930, 19443, 20705, + 21499, 23413, 25601, 24336, 18665, 11686, 7800, 8947, 12974, 18067, 22707, 25285, 23077, 16645, 9789, 6586, 8147, 12329, 15935, 17465, + 17962, 20462, 24615, 25377, 20036, 11458, 5421, 5415, 9528, 14134, 17782, 22482, 26926, 27479, 21881, 13308, 7533, 7734, 11549, 13992, + ], + ), + ( + false, + Resample::BicubicSmoother, + (40, 3), + (9, 3), + &[ + 11315, 18740, 17475, 15974, 16503, 16042, 18215, 14712, 16238, 18482, 14351, 14664, 18012, 20260, 13338, 15511, 18468, 18275, 16790, 19168, + 14745, 14998, 20341, 18150, 13819, 16493, 16432, + ], + ), + ( + false, + Resample::Bilinear, + (12, 10), + (5, 4), + &[11316, 14541, 17920, 10855, 24679, 19763, 9933, 23757, 6247, 20070, 25601, 5325, 19149, 17306, 15463, 20992, 16384, 14541, 23143, 10854], + ), + ( + false, + Resample::Nearest, + (12, 10), + (7, 16), + &[ + 1638, 12698, 23757, 3482, 9011, 20070, 31130, 1638, 12698, 23757, 3482, 9011, 20070, 31130, 31130, 10854, 21914, 1638, 7168, 18227, 29286, + 29286, 9011, 20070, 31130, 5325, 16384, 27443, 29286, 9011, 20070, 31130, 5325, 16384, 27443, 27443, 7168, 18227, 29286, 3482, 14541, + 25600, 25600, 5325, 16384, 27443, 1638, 12698, 23757, 25600, 5325, 16384, 27443, 1638, 12698, 23757, 23757, 3482, 14541, 25600, 31130, + 10854, 21914, 23757, 3482, 14541, 25600, 31130, 10854, 21914, 21914, 1638, 12698, 23757, 29286, 9011, 20070, 20070, 31130, 10854, 21914, + 27443, 7168, 18227, 20070, 31130, 10854, 21914, 27443, 7168, 18227, 18227, 29286, 9011, 20070, 25600, 5325, 16384, 16384, 27443, 7168, + 18227, 23757, 3482, 14541, 16384, 27443, 7168, 18227, 23757, 3482, 14541, + ], + ), + ( + true, + Resample::Bicubic, + (12, 10), + (20, 6), + &[ + 9960, 6313, 993, 0, 4525, 14807, 26472, 32768, 32768, 23510, 10514, 0, 0, 0, 10110, 22576, 31764, 32768, 32768, 32768, 26136, 18594, 6164, + 0, 0, 2565, 14499, 26983, 32768, 32768, 26358, 14709, 3969, 0, 0, 6602, 17734, 27952, 32768, 32768, 31590, 27808, 18307, 7429, 0, 0, 3712, + 14435, 26473, 32768, 31131, 20665, 7535, 0, 0, 2177, 13238, 25049, 32768, 32768, 32768, 32768, 26136, 14174, 2548, 0, 0, 6190, 18705, + 30273, 32768, 32768, 25517, 13238, 2177, 0, 0, 7250, 19418, 26624, 32768, 32768, 32768, 28203, 18522, 7200, 0, 0, 3285, 14794, 26862, + 32768, 29913, 19013, 6667, 0, 0, 4443, 14506, 20751, 17344, 23066, 31075, 32361, 23949, 10738, 0, 0, 0, 10110, 22657, 32768, 32768, 32768, + 22658, 10192, 1004, 0, 0, 0, + ], + ), + ( + true, + Resample::BicubicSharper, + (12, 10), + (7, 16), + &[ + 801, 3050, 32489, 16260, 0, 29819, 32767, 9161, 1781, 29578, 14350, 0, 32768, 32767, 21132, 0, 25409, 17862, 0, 26925, 32767, 22769, 0, + 24839, 27566, 0, 9397, 32768, 19813, 0, 27795, 32768, 0, 0, 32768, 20744, 0, 25797, 32768, 0, 0, 32768, 27555, 0, 11184, 32768, 0, 0, + 32768, 32768, 0, 0, 32768, 5110, 0, 30386, 32768, 0, 0, 32768, 20385, 0, 23267, 32768, 0, 0, 32768, 29130, 0, 19191, 32768, 2670, 0, 31290, + 25387, 0, 21263, 32767, 20198, 0, 21586, 24510, 0, 23714, 32768, 32768, 0, 14165, 27804, 1007, 14254, 32768, 30149, 0, 16077, 32112, 2886, + 1884, 21043, 29607, 0, 16384, 32768, 3566, 0, 12683, 29616, 0, 16384, 32768, 3196, 0, + ], + ), + ( + true, + Resample::BicubicSharper, + (12, 10), + (20, 6), + &[ + 9273, 5043, 0, 0, 2698, 14484, 28464, 32768, 32768, 24841, 10877, 0, 0, 0, 9684, 22346, 31492, 32768, 32768, 32768, 25960, 18430, 4978, 0, + 0, 977, 15047, 28475, 32768, 32768, 27939, 14157, 1813, 0, 0, 5296, 17828, 28439, 32768, 32768, 32768, 27849, 17576, 6209, 0, 0, 2169, + 15076, 28935, 32768, 32768, 22167, 7399, 0, 0, 211, 12977, 24638, 32768, 32768, 32768, 32768, 25960, 14244, 824, 0, 0, 5093, 18802, 31993, + 32768, 32768, 26467, 12977, 211, 0, 0, 6300, 19418, 26712, 32768, 32768, 32768, 27907, 17874, 5820, 0, 0, 1853, 16055, 29518, 32768, 32768, + 20889, 5880, 0, 0, 2879, 13798, 20185, 19010, 25565, 32768, 32302, 25431, 11478, 0, 0, 0, 9684, 23083, 32768, 32768, 32768, 23084, 10422, + 1276, 0, 0, 0, + ], + ), + ]; + for (binary, filter, (w, h), (wo, ho), want) in cases { + let mut s = Surface::new(PixelFormat::new(ColorMode::Grayscale, SampleType::U16, false)); + let canvas = Rect::new(0, 0, w, h); + let level = |x: i32, y: i32| match ((x * 37 + y * 101) % 17) as f32 { + k if binary => { + if k > 8.0 { + 32767.0 / 32768.0 + } else { + 0.0 + } + } + k => ((k / 16.0 * 0.9 + 0.05) * 32768.0).round() / 32768.0, + }; + let px: Vec = (0..h).flat_map(|y| (0..w).map(move |x| level(x, y))).collect(); + s.write_region(canvas, &px); + let o = resize_surface_in_canvas(&s, wo as f64 / w as f64, ho as f64 / h as f64, filter, canvas); + let got = o.read_region(Rect::new(0, 0, wo, ho)); + assert_eq!(got.len(), want.len(), "{filter:?}"); + let worst = got.iter().zip(want).map(|(g, &p)| (g * 32768.0 - p as f32).abs()).fold(0.0f32, f32::max); + assert!(worst <= 8.0, "{filter:?} {w}x{h} to {wo}x{ho}: {worst} levels of 32768 from Photoshop"); + } + } + + /// Photoshop's Bicubic doubles with the Keys cubic at a = −0.75 (Catmull-Rom is −0.5): an + /// impulse spreads as −9, −27, 67, 225 /256 and back, as Photoshop 25.4 gives it. + #[test] + fn bicubic_is_photoshops_keys_cubic() { + let mut s = Surface::new(PixelFormat::new(ColorMode::Grayscale, SampleType::F32, false)); + let mut row = [0.25; 30]; + row[10] = 0.75; + s.write_region(Rect::new(0, 0, 30, 1), &row); + let o = resize_surface(&s, 2.0, 1.0, Resample::Bicubic); + let got: Vec = o.read_region(Rect::new(17, 0, 25, 1)).iter().map(|v| (v - 0.25) * 512.0).collect(); + for (g, want) in got.iter().zip([-9.0, -27.0, 67.0, 225.0, 225.0, 67.0, -27.0, -9.0]) { + assert!((g - want).abs() < 1e-3, "{got:?}"); + } + } + #[test] fn identity_scale_is_lossless() { for f in [Resample::Nearest, Resample::Bilinear, Resample::Bicubic, Resample::Lanczos] { diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index a6096ac96e..358b710e18 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -1396,7 +1396,7 @@ pub fn specs() -> Vec { "Fit Image…", &["File", "Automate"], None, - r##"{"width":px,"height":px,"dontEnlarge":bool=false,"resample":"bicubic|bilinear|nearest|lanczos|preserveDetails"="bicubic"}"##, + r##"{"width":px,"height":px,"dontEnlarge":bool=false,"resample":"automatic|preserveDetails|bicubicSmoother|bicubicSharper|bicubicAutomatic|bicubic|nearest|bilinear|lanczos"="bicubic"}"##, has_doc, fit_image ), diff --git a/crates/engine/src/image_cmds.rs b/crates/engine/src/image_cmds.rs index 8ab6ad0ff8..34ad2d6a55 100644 --- a/crates/engine/src/image_cmds.rs +++ b/crates/engine/src/image_cmds.rs @@ -131,11 +131,24 @@ pub(crate) fn scale_effects(fx: &mut Effects, k: f32) { } } -fn parse_resample(s: &str) -> Option { - Some(match s { - "none" => return None, +/// Image Size's resampling methods; `None` changes the resolution only. +#[derive(Clone, Copy)] +enum Method { + None, + Filter(Resample), + /// Photoshop's Automatic: Preserve Details where the image grows, Bicubic Sharper otherwise. + Automatic, +} + +fn parse_resample(s: &str) -> Method { + Method::Filter(match s { + "none" => return Method::None, + "automatic" => return Method::Automatic, "nearest" | "nearestNeighbor" => Resample::Nearest, "bilinear" => Resample::Bilinear, + "bicubicSmoother" => Resample::BicubicSmoother, + "bicubicSharper" => Resample::BicubicSharper, + "bicubicAutomatic" => Resample::BicubicAutomatic, "lanczos" => Resample::Lanczos, "preserveDetails" => Resample::PreserveDetails, _ => Resample::Bicubic, @@ -162,7 +175,7 @@ fn image_size(s: &mut Session, p: &Value) -> Result { let (nw, nh) = (nw.round().clamp(1.0, 300_000.0) as u32, nh.round().clamp(1.0, 300_000.0) as u32); // Each side may reach 300000 px, but resampling writes real pixels: refuse a canvas whose // raster alone would pass the budget, before allocating any of it (#1544). - if resample.is_some() && (nw, nh) != (ow, oh) { + if !matches!(resample, Method::None) && (nw, nh) != (ow, oh) { check_resample_budget("image.imageSize", &d.doc, nw, nh, ", or turn Resample off to change only the resolution")?; } let dpi = p.get("resolution").and_then(Value::as_f64).map(|v| v as f32); @@ -170,7 +183,12 @@ fn image_size(s: &mut Session, p: &Value) -> Result { if let Some(r) = dpi { doc.resolution_dpi = r.clamp(1.0, 10_000.0); } - let Some(filter) = resample else { return Ok(()) }; + let filter = match resample { + Method::None => return Ok(()), + Method::Filter(f) => f, + Method::Automatic if nw > ow || nh > oh => Resample::PreserveDetails, + Method::Automatic => Resample::BicubicSharper, + }; resample_doc(doc, nw, nh, filter); Ok(()) })?; @@ -462,7 +480,12 @@ fn crop_target(p: &Value) -> Result { }; let filter = match p.get("resample") { None | Some(Value::Null) => Some(Resample::Bicubic), - Some(v) => parse_resample(v.as_str().ok_or_else(|| bad(CMD, "`resample` must be a string"))?), + Some(v) => match parse_resample(v.as_str().ok_or_else(|| bad(CMD, "`resample` must be a string"))?) { + Method::None => None, + Method::Filter(f) => Some(f), + // The direction is known only once the frame is: bicubic's own automatic choice. + Method::Automatic => Some(Resample::BicubicAutomatic), + }, }; let filter = match (filter, size) { (Some(f), _) => f, @@ -639,7 +662,7 @@ pub fn specs() -> Vec { "image.imageSize", "Image Size…", ["Image"], - r##"{"width":px,"height":px,"resolution":ppi,"resample":"bicubic|bilinear|nearest|lanczos|preserveDetails|none"="bicubic"} → {width,height} (the document's size after the command; "none" changes the resolution only)"##, + r##"{"width":px,"height":px,"resolution":ppi,"resample":"automatic|preserveDetails|bicubicSmoother|bicubicSharper|bicubicAutomatic|bicubic|nearest|bilinear|lanczos|none"="bicubic"} → {width,height} (the document's size after the command; "none" changes the resolution only)"##, has_doc, image_size ), @@ -784,7 +807,7 @@ mod tests { #[test] fn image_size_scales_everything() { - for resample in ["bicubic", "bilinear", "nearest", "lanczos", "preserveDetails"] { + for resample in ["bicubic", "bicubicSmoother", "bicubicSharper", "bicubicAutomatic", "automatic", "bilinear", "nearest", "lanczos", "preserveDetails"] { let mut s = session(); s.execute("image.imageSize", json!({"width": 80, "resample": resample})).unwrap(); let d = doc(&s); @@ -819,7 +842,15 @@ mod tests { #[test] fn image_size_keeps_canvas_edges_opaque() { for depth in [8, 16, 32] { - for (w, resample) in [(60, "bicubic"), (41, "lanczos"), (15, "bilinear"), (77, "preserveDetails")] { + for (w, resample) in [ + (60, "bicubic"), + (41, "lanczos"), + (15, "bilinear"), + (77, "preserveDetails"), + (21, "bicubicSharper"), + (47, "automatic"), + (9, "bicubicAutomatic"), + ] { let mut s = Session::new(); s.execute("file.new", json!({"width": 30, "height": 20, "depth": depth, "background": "#336699"})).unwrap(); s.execute("select.all", json!({})).unwrap(); diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index f04b62e06c..4869d973b7 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -856,6 +856,9 @@ Bend: Ohyb: Bicubic Bikubická Bicubic (smooth gradients) Bikubická (plynulé přechody) + Automatic Automaticky + Bicubic Smoother (enlargement) Bikubická hladší (zvětšení) + Bicubic Sharper (reduction) Bikubická ostřejší (zmenšení) Bilinear Bilineární Black Černá Black & White Černobílá diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index e5180a8b39..53d3315018 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -833,6 +833,9 @@ Bend: Biegung: Bicubic Bikubisch Bicubic (smooth gradients) Bikubisch (sanfte Verläufe) + Automatic Automatisch + Bicubic Smoother (enlargement) Bikubisch glatter (Vergrößerung) + Bicubic Sharper (reduction) Bikubisch schärfer (Verkleinerung) Bilinear Bilinear Black Schwarz Black & White Schwarzweiß diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 607740e675..15b6593b27 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2038,6 +2038,8 @@ Bend: Καμπυλότητα: Bicubic Δικυβικό Bicubic (smooth gradients) Δικυβική (ομαλές διαβαθμίσεις) + Bicubic Smoother (enlargement) Δικυβική πιο ομαλή (μεγέθυνση) + Bicubic Sharper (reduction) Δικυβική πιο ευκρινής (σμίκρυνση) Bilinear Διγραμμική Black Point Compensation Αντιστάθμιση μαύρου σημείου Black, White Μαύρο, λευκό diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 4e0480bca9..f767709857 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -842,6 +842,9 @@ Bend: Curvatura: Bicubic Bicúbica Bicubic (smooth gradients) Bicúbica (degradados suaves) + Automatic Automático + Bicubic Smoother (enlargement) Bicúbica más suavizada (ampliación) + Bicubic Sharper (reduction) Bicúbica más enfocada (reducción) Bilinear Bilineal Black Negro Black & White Blanco y negro diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index e071631426..33c9ad0158 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -830,6 +830,9 @@ Bend: Courbure : Bicubic Bicubique Bicubic (smooth gradients) Bicubique (dégradés lisses) + Automatic Automatique + Bicubic Smoother (enlargement) Bicubique plus lisse (agrandissement) + Bicubic Sharper (reduction) Bicubique plus net (réduction) Bilinear Bilinéaire Black Noir Black & White Noir et blanc diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 73c038e93d..f182b0d42c 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -824,6 +824,9 @@ Bend: Lengkung: Bicubic Bicubic Bicubic (smooth gradients) Bicubic (gradien halus) + Automatic Otomatis + Bicubic Smoother (enlargement) Bicubic lebih halus (pembesaran) + Bicubic Sharper (reduction) Bicubic lebih tajam (pengecilan) Bilinear Bilinear Black Hitam Black & White Hitam & Putih diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index e1180f8cd9..34ba599222 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -840,6 +840,9 @@ Bend: Curvatura: Bicubic Bicubica Bicubic (smooth gradients) Bicubica (sfumature morbide) + Automatic Automatico + Bicubic Smoother (enlargement) Bicubica più morbida (ingrandimento) + Bicubic Sharper (reduction) Bicubica più nitida (riduzione) Bilinear Bilineare Black Nero Black & White Bianco e nero diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 1cb1358750..260da8f736 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -843,6 +843,9 @@ Bend: 曲げ: Bicubic バイキュービック Bicubic (smooth gradients) バイキュービック(滑らかな階調) + Automatic 自動 + Bicubic Smoother (enlargement) バイキュービック法 - 滑らか(拡大) + Bicubic Sharper (reduction) バイキュービック法 - シャープ(縮小) Bilinear バイリニア Black 黒 Black & White 白黒 diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 2f6347d6c1..7d159bb282 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -815,6 +815,9 @@ Bend: 구부림: Bicubic 쌍입방 Bicubic (smooth gradients) 쌍입방(부드러운 그레이디언트) + Automatic 자동 + Bicubic Smoother (enlargement) 쌍입방 더 부드럽게(확대) + Bicubic Sharper (reduction) 쌍입방 더 선명하게(축소) Bilinear 쌍선형 Black 검정 Black & White 흑백 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 713f935b41..16d31f534d 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -824,6 +824,8 @@ Bend: Buiging: Bicubic Bicubisch Bicubic (smooth gradients) Bicubisch (vloeiende verlopen) + Bicubic Smoother (enlargement) Bicubisch vloeiender (vergroten) + Bicubic Sharper (reduction) Bicubisch scherper (verkleinen) Bilinear Bilineair Black Zwart Black & White Zwart-wit diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 335b8d0690..ce187a37b1 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -840,6 +840,9 @@ Bend: Zgięcie: Bicubic Dwusześcienna Bicubic (smooth gradients) Dwusześcienna (gładkie gradienty) + Automatic Automatycznie + Bicubic Smoother (enlargement) Dwusześcienna wygładzona (powiększanie) + Bicubic Sharper (reduction) Dwusześcienna wyostrzona (zmniejszanie) Bilinear Dwuliniowa Black Czarny Black & White Czerń i biel diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index beea57d3cf..252fe4c64f 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -826,6 +826,9 @@ Bend: Curvatura: Bicubic Bicúbica Bicubic (smooth gradients) Bicúbica (degradês suaves) + Automatic Automático + Bicubic Smoother (enlargement) Bicúbica mais suave (ampliação) + Bicubic Sharper (reduction) Bicúbica mais nítida (redução) Bilinear Bilinear Black Preto Black & White Preto e branco diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 3ec3ce023c..ee4a1a5225 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1978,6 +1978,9 @@ Baseline Базовая линия Bicubic Бикубическая Bicubic (smooth gradients) Бикубическая (плавные градиенты) + Automatic Автоматически + Bicubic Smoother (enlargement) Бикубическая, глаже (увеличение) + Bicubic Sharper (reduction) Бикубическая, чётче (уменьшение) Bilinear Билинейная Black, White Чёрный, белый Blue, Red, Yellow Синий, красный, жёлтый diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index e15aee93a1..4d50b1c189 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1958,6 +1958,9 @@ Baseline Базова лінія Bicubic Бікубічна Bicubic (smooth gradients) Бікубічна (плавні градієнти) + Automatic Автоматично + Bicubic Smoother (enlargement) Бікубічна, гладкіша (збільшення) + Bicubic Sharper (reduction) Бікубічна, чіткіша (зменшення) Bilinear Білінійна Black, White Чорний, білий Blue, Red, Yellow Синій, червоний, жовтий diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 362c3c9d84..3116d73e61 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -844,6 +844,9 @@ Bend: 弯曲: Bicubic 双三次 Bicubic (smooth gradients) 双三次(平滑渐变) + Automatic 自动 + Bicubic Smoother (enlargement) 双三次(较平滑)(扩大) + Bicubic Sharper (reduction) 双三次(较锐利)(缩减) Bilinear 双线性 Black 黑色 Black & White 黑白 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index e278e45501..89433e2415 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -847,6 +847,9 @@ Bend: 彎曲: Bicubic 雙三次 Bicubic (smooth gradients) 雙三次 (平滑漸層) + Automatic 自動 + Bicubic Smoother (enlargement) 雙三次 (較平滑) (放大) + Bicubic Sharper (reduction) 雙三次 (較銳利) (縮小) Bilinear 雙線性 Black 黑色 Black & White 黑白 diff --git a/crates/ui-egui/src/sizing.rs b/crates/ui-egui/src/sizing.rs index f194cad33e..1863e44c02 100644 --- a/crates/ui-egui/src/sizing.rs +++ b/crates/ui-egui/src/sizing.rs @@ -31,11 +31,13 @@ fn pref_unit(u: photocraft_engine::prefs::Unit) -> &'static str { pub(crate) fn pref_resample(i: photocraft_engine::prefs::Interpolation) -> &'static str { use photocraft_engine::prefs::Interpolation; match i { + Interpolation::BicubicAutomatic => "automatic", Interpolation::Nearest => "nearest", Interpolation::Bilinear => "bilinear", - Interpolation::BicubicSharper => "lanczos", + Interpolation::Bicubic => "bicubic", + Interpolation::BicubicSmoother => "bicubicSmoother", + Interpolation::BicubicSharper => "bicubicSharper", Interpolation::PreserveDetails => "preserveDetails", - _ => "bicubic", } } const ANCHORS: [&str; 9] = ["topLeft", "top", "topRight", "left", "center", "right", "bottomLeft", "bottom", "bottomRight"]; @@ -65,6 +67,7 @@ pub fn open(app: &mut PhotocraftApp, command: &str) -> Option { f.insert("__constrain".into(), json!(true)); f.insert("resolution".into(), json!(res)); f.insert("resample".into(), json!(resample)); + f.insert("__resample".into(), json!(resample)); } else { f.insert("relative".into(), json!(false)); f.insert("anchor".into(), json!("center")); @@ -260,7 +263,9 @@ fn image_size(ui: &mut egui::Ui, f: &mut Map) { label(ui, "", 90.0); let mut on = resampling; if crate::widgets::checkbox(ui, &mut on, tl!("Resample")).changed() { - f.insert("resample".into(), json!(if on { "bicubic" } else { "none" })); + // Back on, it takes the method it had when the dialog opened. + let method = f.get("__resample").cloned().unwrap_or_else(|| json!("bicubic")); + f.insert("resample".into(), if on { method } else { json!("none") }); if !on { f.insert("width".into(), json!(ow)); f.insert("height".into(), json!(oh)); @@ -268,12 +273,16 @@ fn image_size(ui: &mut egui::Ui, f: &mut Map) { } if resampling { let mut cur = resample.clone(); + // Photoshop's list, then Lanczos. let opts = [ + ("automatic".to_string(), tl!("Automatic")), ("preserveDetails".to_string(), tl!("Preserve Details")), + ("bicubicSmoother".to_string(), tl!("Bicubic Smoother (enlargement)")), + ("bicubicSharper".to_string(), tl!("Bicubic Sharper (reduction)")), ("bicubic".to_string(), tl!("Bicubic (smooth gradients)")), - ("lanczos".to_string(), tl!("Lanczos (sharp)")), - ("bilinear".to_string(), tl!("Bilinear")), ("nearest".to_string(), tl!("Nearest Neighbor (hard edges)")), + ("bilinear".to_string(), tl!("Bilinear")), + ("lanczos".to_string(), tl!("Lanczos (sharp)")), ]; if crate::widgets::dropdown(ui, "is-resample", &mut cur, &opts, 200.0) { f.insert("resample".into(), json!(cur)); @@ -432,6 +441,29 @@ mod tests { assert_eq!(app.session.active().unwrap().doc.size, photocraft_doc::Size::new(120, 50)); } + /// The dialog starts on Preferences › General › Image Interpolation: Bicubic Automatic opens + /// as Automatic and the others as themselves (Bicubic Sharper used to open as Lanczos). + #[test] + fn resample_follows_the_interpolation_preference() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 200, "height": 100})).unwrap(); + for (pref, method) in + [("bicubicAutomatic", "automatic"), ("bicubicSharper", "bicubicSharper"), ("bicubicSmoother", "bicubicSmoother"), ("nearestNeighbor", "nearest")] + { + app.session.execute("prefs.set", json!({"path": "general.imageInterpolation", "value": pref})).unwrap(); + let id = open(&mut app, "image.imageSize").unwrap(); + let f = &app.ui.dialog_mut(id).unwrap().fields; + assert_eq!((f.get("resample"), f.get("__resample")), (Some(&json!(method)), Some(&json!(method))), "{pref}"); + app.ui.close_dialog(id); + } + let id = open(&mut app, "image.imageSize").unwrap(); + let d = app.ui.dialog_mut(id).unwrap(); + d.fields.insert("width".into(), json!(50)); + d.fields.insert("height".into(), json!(25)); + crate::dialogs::confirm(&mut app, id).unwrap(); + assert_eq!(app.session.active().unwrap().doc.size, photocraft_doc::Size::new(50, 25)); + } + /// #441: a typed zero width showed "0 px × 1 px" while OK resized to 1×1. #[test] fn typed_zero_width_shows_the_applied_size() {