From e3ecd73569431b9b87435ed2817fa61c621dfd90 Mon Sep 17 00:00:00 2001 From: Khawar Zamman Wani Date: Thu, 5 Nov 2026 17:09:02 +0530 Subject: [PATCH] feat(frame): rework the Frame tool's selection, handles and placement (#8920) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Thanks @wanikhawar — merging the Frame Tool rework. Summary: Frame Tool selection/handles/placement now distinguish frame vs image (border / click / double-click and Layers thumbnails), with independent transforms, shape variants, Properties/options-bar stroke and fit commands, Convert to Frame, CLI/MCP `layer.frame.*` commands, native `.pcraft` persistence, and PSD export via editable groups + `pcFr` metadata (not Photoshop's native frame type). Tests cover selection, transforms, fitting, locks/hostile geometry, and native/PSD round-trips. --- crates/automation/src/server.rs | 5 +- crates/automation/src/workspace/tests.rs | 1 + crates/compose/src/composite.rs | 1 + crates/compose/src/extents.rs | 17 + crates/compose/src/fx_cache.rs | 1 + crates/compose/src/proxy.rs | 9 + crates/compose/src/shape_split.rs | 10 +- crates/doc/src/frame.rs | 55 + crates/doc/src/lib.rs | 23 +- crates/engine/examples/bench_frame.rs | 58 ++ crates/engine/src/actions_record/tests.rs | 2 + crates/engine/src/canvas_geom.rs | 8 + crates/engine/src/cmd.rs | 2 +- crates/engine/src/cmd/extra_cmds.rs | 2 + crates/engine/src/cmd/file_cmds.rs | 4 +- crates/engine/src/cmd/file_cmds/open.rs | 72 +- crates/engine/src/cmd/frame_cmds.rs | 615 ++++++----- crates/engine/src/cmd/frame_cmds/tests.rs | 553 ++++++++++ .../engine/src/cmd/layer_multi_cmds/damage.rs | 2 + crates/engine/src/cmd/smart_cmds.rs | 2 +- crates/engine/src/cmd/smart_cmds/rendering.rs | 10 +- crates/engine/src/cmd/transform_cmds.rs | 29 + crates/engine/src/cmd/vector_cmds.rs | 2 +- crates/engine/src/cmd/vector_cmds/shape.rs | 8 + crates/engine/src/layer_place.rs | 6 +- crates/engine/src/lib.rs | 2 +- .../engine/tests/it/actions_single_history.rs | 1 + .../tests/it/background_and_mask_depth.rs | 17 +- crates/format/src/convert.rs | 5 + crates/format/src/manifest.rs | 2 + crates/gpu/src/plan/planner.rs | 1 + crates/io/src/psd_export.rs | 41 + crates/io/src/psd_export/smart.rs | 13 +- crates/io/src/psd_import.rs | 48 +- crates/io/tests/it/roundtrip.rs | 66 ++ crates/ui-egui/src/app.rs | 2 + crates/ui-egui/src/canvas.rs | 17 + crates/ui-egui/src/canvas/display.rs | 3 + crates/ui-egui/src/canvas/tool_input.rs | 4 + crates/ui-egui/src/control.rs | 1 + crates/ui-egui/src/control/dispatch.rs | 53 + crates/ui-egui/src/control/params.rs | 5 +- crates/ui-egui/src/file_open.rs | 40 +- crates/ui-egui/src/i18n/cs.tsv | 18 + crates/ui-egui/src/i18n/de.tsv | 20 + crates/ui-egui/src/i18n/el.tsv | 20 + crates/ui-egui/src/i18n/es.tsv | 18 + crates/ui-egui/src/i18n/fr.tsv | 18 + crates/ui-egui/src/i18n/hi.tsv | 31 + crates/ui-egui/src/i18n/hu.tsv | 18 + crates/ui-egui/src/i18n/id.tsv | 19 + crates/ui-egui/src/i18n/it.tsv | 18 + crates/ui-egui/src/i18n/ja.tsv | 18 + crates/ui-egui/src/i18n/ko.tsv | 20 + crates/ui-egui/src/i18n/nl.tsv | 18 + crates/ui-egui/src/i18n/pl.tsv | 18 + crates/ui-egui/src/i18n/pt-br.tsv | 18 + crates/ui-egui/src/i18n/ru.tsv | 18 + crates/ui-egui/src/i18n/sr.tsv | 18 + crates/ui-egui/src/i18n/tr.tsv | 18 + crates/ui-egui/src/i18n/uk.tsv | 18 + crates/ui-egui/src/i18n/vi.tsv | 18 + crates/ui-egui/src/i18n/zh-hans.tsv | 21 + crates/ui-egui/src/i18n/zh-hant.tsv | 21 + crates/ui-egui/src/input/shortcuts.rs | 7 + crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/menus/invoke.rs | 20 + crates/ui-egui/src/menus/view_cmds/dialogs.rs | 4 +- crates/ui-egui/src/panels/layer_drag.rs | 16 + crates/ui-egui/src/panels/layer_menu_ui.rs | 3 + crates/ui-egui/src/panels/layer_row.rs | 95 +- crates/ui-egui/src/panels/layer_transfer.rs | 14 + crates/ui-egui/src/panels/layer_tree_ui.rs | 4 + crates/ui-egui/src/panels/mask_thumbs_ui.rs | 7 +- crates/ui-egui/src/panels/properties.rs | 6 + crates/ui-egui/src/panels/props_layout.rs | 3 + crates/ui-egui/src/tool_memory.rs | 3 + crates/ui-egui/src/tools/frame_tool.rs | 954 +++++++++++++++--- crates/ui-egui/src/tools/frame_tool/tests.rs | 572 +++++++++++ crates/ui-egui/src/tools/tool_reset.rs | 6 + .../ui-egui/src/tools/transform_tool/begin.rs | 12 +- .../src/tools/transform_tool/commit.rs | 16 + .../ui-egui/src/tools/transform_tool/draw.rs | 5 +- docs/control-protocol.md | 4 + docs/frame-tool.md | 71 ++ docs/gaps.md | 2 + docs/target-app-parity.md | 1 + docs/ui-parity.md | 3 +- 88 files changed, 3582 insertions(+), 470 deletions(-) create mode 100644 crates/doc/src/frame.rs create mode 100644 crates/engine/examples/bench_frame.rs create mode 100644 crates/engine/src/cmd/frame_cmds/tests.rs create mode 100644 crates/ui-egui/src/tools/frame_tool/tests.rs create mode 100644 docs/frame-tool.md diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rs index e1be8db85c..1b125bf6be 100644 --- a/crates/automation/src/server.rs +++ b/crates/automation/src/server.rs @@ -369,7 +369,10 @@ pub struct UiSetParams { /// combine, subtract, intersect or exclude: how the next Pen path joins the selected shape /// layer or path), shapeStroke (an object patching width, align, cap, join, miterLimit, /// dashes, dashOffset and opacity; null disables the stroke). Shape stroke fields use - /// `shape.edit` names and units; colour comes from `tools.setColors`. camTransformOnDrop (bool, + /// `shape.edit` names and units; colour comes from `tools.setColors`. frameShape (rectangle, + /// ellipse, triangle, polygon or custom: the Frame tool's shape), frameSides (3..100, the + /// polygon's sides), frameTarget (frame, content or both: what the selected frame's handles + /// edit). camTransformOnDrop (bool, /// the Content-Aware Move tool's Transform On Drop). tileGrid (bool, a developer overlay of the /// active layer's storage tiles). layerFilter (an object patching by ("kind", "name", "effect", /// "mode", "attribute", "color", "smartObject" or "artboard", which lists the artboards that diff --git a/crates/automation/src/workspace/tests.rs b/crates/automation/src/workspace/tests.rs index 5ea4a5b3fe..3aeb908de3 100644 --- a/crates/automation/src/workspace/tests.rs +++ b/crates/automation/src/workspace/tests.rs @@ -747,6 +747,7 @@ fn documents_filesystem_path_params(id: &str, params: &str) -> bool { | "layer.combineShapes.intersectShapeAreas" | "layer.combineShapes.excludeOverlappingShapes" | "layer.combineShapes.mergeShapeComponents" + | "layer.new.frame" ) || id.starts_with("layer.newFillLayer.") || id.starts_with("layer.newAdjustmentLayer.") { diff --git a/crates/compose/src/composite.rs b/crates/compose/src/composite.rs index 4ef497672f..679a2298c0 100644 --- a/crates/compose/src/composite.rs +++ b/crates/compose/src/composite.rs @@ -363,6 +363,7 @@ pub(crate) fn composite_layer_plain(layer: &Layer, clipped: &[Layer], backdrop: let clip_base_adjusts = clipped.iter().any(|c| c.visible) && matches!(&layer.content, LayerContent::Group(g) if g.children.iter().any(|c| c.visible && matches!(c.content, LayerContent::Adjustment(_)))); if let LayerContent::Group(g) = &layer.content + && layer.frame.is_none() && layer.blend == BlendMode::PassThrough && layer.fill_opacity >= 1.0 && !effects::has_effects(layer) diff --git a/crates/compose/src/extents.rs b/crates/compose/src/extents.rs index 7e4f8d234e..c0ae28d340 100644 --- a/crates/compose/src/extents.rs +++ b/crates/compose/src/extents.rs @@ -5,6 +5,16 @@ use super::{BlendMode, Document, Layer, LayerContent, Rect, advanced, bounds, ef /// Bounds of a layer's own pixels (union over group children; the canvas /// for fill layers; an artboard's board). pub fn layer_bounds(layer: &Layer, canvas: Rect) -> Rect { + if let Some(f) = &layer.frame { + // Empty placeholders are shell overlays, so they must not schedule a full frame-sized + // mask/composite on either renderer (particularly on 24+ MP documents). + if layer.children().is_some_and(|c| c.is_empty()) && f.stroke.as_ref().is_none_or(|s| s.width <= 0.0 || s.opacity <= 0.0) { + return Rect::EMPTY; + } + let b = f.bounds(); + let n = f.stroke.as_ref().map_or(0, |s| s.width.ceil() as i32); + return Rect::new(b.x0.saturating_sub(n), b.y0.saturating_sub(n), b.x1.saturating_add(n), b.y1.saturating_add(n)); + } // Transparency Shapes Layer off: effects and knockout cover the whole layer (the canvas). if advanced::shapeless(layer) { return canvas; @@ -61,6 +71,9 @@ fn frame_stroke_bounds(layer: &Layer, canvas: Rect) -> Rect { /// children count with their own effects (a child's outside stroke shapes the group's drop /// shadow and must not be cut off at the child's pixels, #3274). pub fn effect_source_bounds(layer: &Layer, canvas: Rect) -> Rect { + if layer.frame.is_some() { + return layer_bounds(layer, canvas); + } match &layer.content { // A Frame's stroke is part of the group's content its effects are built from. LayerContent::Group(g) if g.artboard.is_none() && !advanced::shapeless(layer) => { @@ -359,6 +372,10 @@ pub(crate) fn shapeless_stroke_bounds(layer: &Layer) -> Option { /// Adjustment layers count as empty: they only change pixels already there (which is what an /// isolated group needs; see [`change_bounds`] for the document-level question). pub fn composite_bounds(layer: &Layer, canvas: Rect) -> Option { + if layer.frame.is_some() { + let bounds = layer_bounds(layer, canvas); + return Some(if bounds.is_empty() { bounds } else { bounds.inflate(effects::margin(layer)).intersect(&canvas) }); + } if !transparent_outside(layer) { return None; } diff --git a/crates/compose/src/fx_cache.rs b/crates/compose/src/fx_cache.rs index b24aabc29b..e1cd209002 100644 --- a/crates/compose/src/fx_cache.rs +++ b/crates/compose/src/fx_cache.rs @@ -45,6 +45,7 @@ pub(crate) fn layer_identity(layer: &Layer, h: &mut std::collections::hash_map:: layer_identity(c, h, pin); } format!("{:?}{:?}", g.artboard, g.frame_stroke).hash(h); + format!("{:?}", layer.frame).hash(h); } LayerContent::Fill(f) => { format!("{f:?}").hash(h); diff --git a/crates/compose/src/proxy.rs b/crates/compose/src/proxy.rs index dba123e21c..e0b68a6b51 100644 --- a/crates/compose/src/proxy.rs +++ b/crates/compose/src/proxy.rs @@ -36,6 +36,15 @@ pub fn downsample(s: &Surface, k: u32) -> Surface { } fn shrink_layer(l: &mut Layer, k: u32) { + if let Some(f) = &mut l.frame { + f.transform = Affine::scale(1.0 / f64::from(k)).mul(&f.transform); + if let Some(s) = &mut f.stroke { + s.width /= k as f32; + } + if let Some(mask) = &mut l.vector_mask { + mask.path = f.outline(); + } + } if let Some(m) = &mut l.mask { m.surface = downsample(&m.surface, k); } diff --git a/crates/compose/src/shape_split.rs b/crates/compose/src/shape_split.rs index 53875d5922..5a44e739bb 100644 --- a/crates/compose/src/shape_split.rs +++ b/crates/compose/src/shape_split.rs @@ -106,11 +106,15 @@ pub fn split(sh: &ShapeLayer, canvas: Rect, depth: SampleType) -> Option<(Surfac Some(parts) } -/// The stroke-only shape a Photoshop Frame's stroke draws: `Group::frame_stroke` along the -/// group's enabled vector mask (the frame outline). `None` for other layers and for a frame -/// without a visible stroke or a vector mask. +/// The stroke-only shape a Frame's stroke draws: the Frame tool's own border (`Layer::frame`), +/// else a Photoshop Frame's `Group::frame_stroke` along the group's enabled vector mask (the +/// frame outline). `None` for other layers and for a frame without a visible stroke (or, for a +/// Photoshop Frame, a vector mask). pub fn frame_shape(layer: &Layer) -> Option { let LayerContent::Group(g) = &layer.content else { return None }; + if let Some(shape) = layer.frame.as_ref().and_then(|f| f.stroke_shape()) { + return Some(shape); + } let stroke = g.frame_stroke.as_ref().filter(|s| s.width.is_finite() && s.width > 0.0 && s.opacity > 0.0)?; let vm = layer.vector_mask.as_ref().filter(|m| m.enabled && !m.path.is_empty())?; Some(ShapeLayer { path: vm.path.clone(), fill: None, stroke: Some(stroke.clone()), ..ShapeLayer::default() }) diff --git a/crates/doc/src/frame.rs b/crates/doc/src/frame.rs new file mode 100644 index 0000000000..251671111b --- /dev/null +++ b/crates/doc/src/frame.rs @@ -0,0 +1,55 @@ +//! Image-placeholder geometry. The outline is normalized to the unit square; its affine +//! placement is independent of the image's placement, so resizing a frame never resamples it. +use crate::{Path, ShapeLayer, ShapeStroke}; +use photocraft_geom::{Affine, Point, Rect}; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Frame { + pub path: Path, + pub transform: Affine, + #[serde(default)] + pub stroke: Option, +} + +impl Frame { + pub fn outline(&self) -> Path { + self.path.transform(&self.transform) + } + pub fn corners(&self) -> [Point; 4] { + [Point::new(0.0, 0.0), Point::new(1.0, 0.0), Point::new(1.0, 1.0), Point::new(0.0, 1.0)].map(|p| self.transform.apply(p)) + } + pub fn bounds(&self) -> Rect { + let [a, b, c, d] = self.corners(); + let x0 = a.x.min(b.x).min(c.x).min(d.x); + let y0 = a.y.min(b.y).min(c.y).min(d.y); + let x1 = a.x.max(b.x).max(c.x).max(d.x); + let y1 = a.y.max(b.y).max(c.y).max(d.y); + Rect::new(x0.floor() as i32, y0.floor() as i32, x1.ceil() as i32, y1.ceil() as i32) + } + /// Reject invalid metadata before it can enter geometry or rasterization. + pub fn valid(&self) -> bool { + self.transform.m.iter().all(|n| n.is_finite() && n.abs() <= 600_000.0) + && self.transform.inverse().is_some() + && { + let [a, b, c, d, _, _] = self.transform.m; + (0.01..=300_000.0).contains(&a.hypot(b)) && (0.01..=300_000.0).contains(&c.hypot(d)) + } + && !self.path.is_empty() + && self.path.subpaths.len() <= 4096 + && self.path.subpaths.iter().fold(0usize, |n, s| n.saturating_add(s.knots.len())) <= 100_000 + && self + .path + .subpaths + .iter() + .flat_map(|s| &s.knots) + .flat_map(|k| [k.anchor, k.in_ctrl, k.out_ctrl]) + .all(|p| p.x.is_finite() && p.y.is_finite() && p.x.abs() <= 10.0 && p.y.abs() <= 10.0) + && self.corners().iter().all(|p| p.x.abs() <= 600_000.0 && p.y.abs() <= 600_000.0) + && self.stroke.as_ref().is_none_or(|s| s.validate().is_ok() && (0.0..=1000.0).contains(&s.width) && s.opacity.is_finite()) + } + pub fn stroke_shape(&self) -> Option { + let stroke = self.stroke.clone()?; + Some(ShapeLayer { path: self.outline(), fill: None, stroke: Some(stroke), cache: None, psd_raw: None, live: None, density: 1.0, feather: 0.0 }) + } +} diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 915ddca7da..aa376fea02 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -14,6 +14,7 @@ pub mod analysis; pub mod blend_if; pub mod comps; pub mod effects; +pub mod frame; pub mod mode; pub mod pattern; pub mod slices; @@ -35,6 +36,7 @@ pub use effects::{ Bevel, BevelContour, BevelStyle, BevelTechnique, BevelTexture, Contour, Effect, FxCommon, FxPaint, GlobalLight, Glow, GlowSource, GlowTechnique, Gradient, GradientStyle, Satin, Shadow, StrokeFx, StrokePosition, }; +pub use frame::Frame; pub use mode::{ColorTable, Duotone, DuotoneInk, StackMode}; pub use pattern::Pattern; pub use photocraft_color::{BlendMode, Color, ColorMode, PixelFormat, SampleType}; @@ -646,6 +648,9 @@ pub struct Layer { pub effects: Effects, pub label: LabelColor, pub content: LayerContent, + /// Frame Tool container; its clipping outline and image have independent placements. Boxed: + /// inline it grows every layer by 224 bytes, and deep documents recurse on small stacks. + pub frame: Option>, /// Preserved PSD additional-layer-info blocks (key, data) for lossless /// round-trip of anything not modelled above: vector masks, blending /// options, layer version, and the original adjustment/fill blocks (the @@ -703,6 +708,7 @@ impl Layer { effects: Effects { enabled: true, ..Default::default() }, label: LabelColor::None, content, + frame: None, psd_blocks: Vec::new(), psd_id: None, fill_cache: None, @@ -1249,20 +1255,29 @@ impl Document { Some((p.children_mut()?, last)) } - /// Insert `layer` directly above the layer `above` (or at the top of the root if None). + /// Frames expose their image as an editable target, rather than as a layer-stack container. + /// New layers beside that image belong beside the frame, keeping the image slot intact. + pub fn insertion_path(&self, relative: LayerId) -> Option { + let mut path = self.path_of(relative)?; + let end = (1..path.len()).find(|n| path.get(..*n).and_then(|p| self.layer_at(p)).is_some_and(|l| l.frame.is_some())).unwrap_or(path.len()); + path.truncate(end); + Some(path) + } + + /// Insert `layer` above `above` (beside its frame for frame content), or at the root's top. pub fn insert_above(&mut self, above: Option, layer: Layer) -> LayerId { let id = layer.id; - match above.and_then(|a| self.path_of(a)).and_then(|path| self.siblings_mut(&path)) { + match above.and_then(|a| self.insertion_path(a)).and_then(|path| self.siblings_mut(&path)) { Some((sib, idx)) => sib.insert(idx + 1, layer), None => self.layers.push(layer), } id } - /// Insert `layer` directly below the layer `below` (or at the bottom of the root if None). + /// Insert `layer` below `below` (beside its frame for frame content), or at the root's bottom. pub fn insert_below(&mut self, below: Option, layer: Layer) -> LayerId { let id = layer.id; - match below.and_then(|b| self.path_of(b)).and_then(|path| self.siblings_mut(&path)) { + match below.and_then(|b| self.insertion_path(b)).and_then(|path| self.siblings_mut(&path)) { Some((sib, idx)) => sib.insert(idx, layer), None => self.layers.insert(0, layer), } diff --git a/crates/engine/examples/bench_frame.rs b/crates/engine/examples/bench_frame.rs new file mode 100644 index 0000000000..55e85f80f8 --- /dev/null +++ b/crates/engine/examples/bench_frame.rs @@ -0,0 +1,58 @@ +//! 24 MP frame creation: vector commands versus the previous raster-mask construction. +//! `cargo run --release -p photocraft-engine --example bench_frame` +//! The baseline times only the former mask work; command times include history/validation. +use std::hint::black_box; +use std::time::Instant; + +use photocraft_doc::LayerMask; +use photocraft_engine::Session; +use photocraft_geom::Rect; +use serde_json::json; + +fn raster_mask(rect: Rect, ellipse: bool) -> LayerMask { + let mut mask = LayerMask::hide_all(); + if !ellipse { + mask.surface.fill_rect(rect, &[1.0]); + return mask; + } + let (rx, ry) = (f64::from(rect.width()) / 2., f64::from(rect.height()) / 2.); + let (cx, cy) = (f64::from(rect.x0) + rx, f64::from(rect.y0) + ry); + for y in rect.y0..rect.y1 { + for x in rect.x0..rect.x1 { + let covered = (0..16) + .filter(|i| { + let dx = (f64::from(x) + (f64::from(i % 4) + 0.5) / 4. - cx) / rx; + let dy = (f64::from(y) + (f64::from(i / 4) + 0.5) / 4. - cy) / ry; + dx * dx + dy * dy <= 1. + }) + .count(); + if covered > 0 { + mask.surface.write_pixel(x, y, &[covered as f32 / 16.]); + } + } + } + mask.surface.prune(); + mask +} + +fn main() -> Result<(), Box> { + let mut session = Session::new(); + session.execute("file.new", json!({"width":6000,"height":4000}))?; + let rect = Rect::new(100, 100, 5900, 3900); + for (shape, ellipse) in [("rectangle", false), ("ellipse", true)] { + let mut before = f64::INFINITY; + let mut after = f64::INFINITY; + for _ in 0..3 { + let start = Instant::now(); + let mask = black_box(raster_mask(rect, ellipse)); + before = before.min(start.elapsed().as_secs_f64() * 1000.); + drop(mask); + let start = Instant::now(); + session.execute("layer.new.frame", json!({"x":100,"y":100,"width":5800,"height":3800,"shape":shape}))?; + after = after.min(start.elapsed().as_secs_f64() * 1000.); + session.undo(); + } + println!("{shape}, 6000x4000 canvas, best of 3: previous mask {before:.3} ms; vector command {after:.3} ms"); + } + Ok(()) +} diff --git a/crates/engine/src/actions_record/tests.rs b/crates/engine/src/actions_record/tests.rs index dfffc2c08f..60c93f370a 100644 --- a/crates/engine/src/actions_record/tests.rs +++ b/crates/engine/src/actions_record/tests.rs @@ -100,6 +100,7 @@ fn a_background_job_journals_the_same_way() { fn frame_action_keeps_the_layer_it_wraps() { let mut s = session(); let picture = new_layer(&mut s, "Picture"); + s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); s.execute("actions.record", json!({"name": "Frame picture"})).unwrap(); s.execute("layer.new.frame", json!({"x": 1, "y": 1, "width": 20, "height": 20, "layer": picture})).unwrap(); s.execute("actions.stop", json!({})).unwrap(); @@ -108,6 +109,7 @@ fn frame_action_keeps_the_layer_it_wraps() { s.execute("file.new", json!({"width": 32, "height": 32, "background": "white"})).unwrap(); new_layer(&mut s, "Spare"); let target = new_layer(&mut s, "Picture"); + s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap(); assert_ne!(target, picture, "the replay target has a different document-local id"); let played = s.execute("actions.play", json!({"action": "Frame picture"})).unwrap(); assert!(played.get("failed").is_none(), "{played}"); diff --git a/crates/engine/src/canvas_geom.rs b/crates/engine/src/canvas_geom.rs index 6276e432a3..92e7f00af5 100644 --- a/crates/engine/src/canvas_geom.rs +++ b/crates/engine/src/canvas_geom.rs @@ -156,6 +156,14 @@ fn grown(v: f32, k: f64) -> f32 { /// the parts Free Transform (`transform_layer`) doesn't move are touched: unlinked vector masks, /// gradient fill angles, effect reference points and artboards. pub(crate) fn transform_layer_geometry(l: &mut Layer, a: &Affine, content: bool, dpi: f32) { + if content && let Some(f) = &mut l.frame { + f.transform = a.mul(&f.transform); + // Past `Frame::valid`'s bounds it would no longer load; the vector mask, moved below, + // keeps the clip as a plain masked group. + if !f.valid() { + l.frame = None; + } + } if let Some(vm) = l.vector_mask.as_mut() && (content || !vm.linked) { diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index ded6c4871b..1bf4fb34b5 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -83,7 +83,7 @@ pub mod fill_cmds; pub mod fill_key_cmds; pub mod float_cmds; pub mod font_library_cmds; -pub(super) mod frame_cmds; +pub mod frame_cmds; pub mod fx_view_cmds; pub mod fx_visibility_cmds; pub mod gallery_cmds; diff --git a/crates/engine/src/cmd/extra_cmds.rs b/crates/engine/src/cmd/extra_cmds.rs index 290c129507..2637eab8c1 100644 --- a/crates/engine/src/cmd/extra_cmds.rs +++ b/crates/engine/src/cmd/extra_cmds.rs @@ -762,6 +762,8 @@ fn rasterize_content(s: &mut Session, id: LayerId, only: Option<&str>, key: &str let px = content_pixels(doc, &snap); let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; l.content = LayerContent::Raster(px); + l.frame = None; + l.psd_blocks.retain(|(k, _)| k != b"pcFr"); l.fill_cache = None; // The PSD fill or placed-layer blocks no longer describe the layer: kept, they // would reopen it as a fill layer or smart object and drop these pixels. diff --git a/crates/engine/src/cmd/file_cmds.rs b/crates/engine/src/cmd/file_cmds.rs index 1d70e3a731..74e02cfba0 100644 --- a/crates/engine/src/cmd/file_cmds.rs +++ b/crates/engine/src/cmd/file_cmds.rs @@ -292,7 +292,7 @@ pub fn specs() -> Vec { "Place Embedded…", &["File"], None, - r##"{"path":str,"scale":%? (default: fit when larger than the canvas),"fit":bool? (default: Preferences > General > Resize Image During Place),"smartObject":bool? (default: Preferences > General > Always Create Smart Objects When Placing),"center":[x,y]?,"approveHighMemory":bool=false (explicitly approve high memory usage)}"##, + r##"{"path":str,"scale":%? (default: fit when larger than the canvas),"fit":bool? (default: Preferences > General > Resize Image During Place),"smartObject":bool? (default: Preferences > General > Always Create Smart Objects When Placing),"center":[x,y]?,"approveHighMemory":bool=false (explicitly approve high memory usage),"frame":id|false? (default: selected frame)}"##, native_doc, |s, p| place(s, p, false) ), @@ -301,7 +301,7 @@ pub fn specs() -> Vec { "Place Linked…", &["File"], None, - r##"{"path":str,"scale":%?,"fit":bool? (default: Preferences > General > Resize Image During Place),"center":[x,y]?,"approveHighMemory":bool=false (explicitly approve high memory usage)}"##, + r##"{"path":str,"scale":%?,"fit":bool? (default: Preferences > General > Resize Image During Place),"center":[x,y]?,"approveHighMemory":bool=false (explicitly approve high memory usage),"frame":id|false? (default: selected frame)}"##, native_doc, |s, p| place(s, p, true) ), diff --git a/crates/engine/src/cmd/file_cmds/open.rs b/crates/engine/src/cmd/file_cmds/open.rs index 1397702318..89e8c81193 100644 --- a/crates/engine/src/cmd/file_cmds/open.rs +++ b/crates/engine/src/cmd/file_cmds/open.rs @@ -1,7 +1,7 @@ use super::paths::{file_name, read_file, stem, template_name}; use super::{ - Affine, Arc, Document, EngineError, Layer, LayerContent, Resample, Result, Session, SmartObject, SmartSource, Value, f64_param, flattened_checked, json, - resize_surface, str_param, translate_surface, + Affine, Arc, Document, EngineError, Layer, LayerContent, LayerId, Resample, Result, Session, SmartObject, SmartSource, Value, f64_param, flattened_checked, + json, resize_surface, str_param, translate_surface, }; pub(crate) fn import(name: &str, bytes: &[u8]) -> Result { @@ -247,7 +247,20 @@ pub const PLACE_EMBEDDED: &str = "Place Embedded"; /// lands as a plain pixel layer instead (an explicit `"smartObject": false` asks for one). pub fn place_bytes(s: &mut Session, name: &str, bytes: Vec, linked: Option, 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 frame_id = match p.get("frame") { + Some(Value::Bool(false)) => None, + Some(v) if !v.is_null() => Some(LayerId(v.as_u64().ok_or_else(|| EngineError::Other("frame must be a frame id or false".into()))?)), + _ => d.active_layer.and_then(|id| crate::frame_cmds::frame_of(&d.doc, id)), + }; + let frame = frame_id + .map(|id| { + d.doc.layer(id).and_then(|l| l.frame.clone()).map(|f| (id, f)).ok_or_else(|| EngineError::Other("the destination frame is unavailable".into())) + }) + .transpose()?; + let (cw, ch) = frame.as_ref().map_or((d.doc.size.width as f64, d.doc.size.height as f64), |(_, f)| { + let [a, b, c, d, _, _] = f.transform.m; + (a.hypot(b), c.hypot(d)) + }); let fmt = d.doc.pixel_format(); let vector = photocraft_io::svg::is_svg(&bytes); let approve = match p.get("approveHighMemory") { @@ -272,6 +285,7 @@ pub fn place_bytes(s: &mut Session, name: &str, bytes: Vec, linked: Option (k / 100.0).max(1e-4), + None if frame.is_some() && fit => (cw / w).max(ch / h), None if fit && (w > cw || h > ch) => (cw / w).min(ch / h), None => 1.0, }; @@ -280,14 +294,32 @@ pub fn place_bytes(s: &mut Session, name: &str, bytes: Vec, linked: Option (cw / 2.0, ch / 2.0), }; let (dx, dy) = ((center.0 - w * scale / 2.0).round(), (center.1 - h * scale / 2.0).round()); - let mut px = flattened_checked(&src, fmt, "file.place")?; - if (scale - 1.0).abs() > 1e-9 { - px = resize_surface(&px, scale, scale, Resample::Bicubic); - } - let px = translate_surface(&px, dx as i32, dy as i32); + // A frame's image renders through its smart object below, which refuses a placement past the + // memory budget; resampling it to the frame's size first would allocate that surface twice. + let px = if frame.is_none() { + let mut px = flattened_checked(&src, fmt, "file.place")?; + if (scale - 1.0).abs() > 1e-9 { + px = resize_surface(&px, scale, scale, Resample::Bicubic); + } + Some(translate_surface(&px, dx as i32, dy as i32)) + } else { + None + }; + let placement = frame + .as_ref() + .map_or(Affine { m: [scale, 0.0, 0.0, scale, dx, dy] }, |(_, f)| f.transform.mul(&Affine { m: [scale / cw, 0.0, 0.0, scale / ch, dx / cw, dy / ch] })); + let corners = [(0.0, 0.0), (w, 0.0), (0.0, h), (w, h)].map(|(x, y)| placement.apply(photocraft_geom::Point::new(x, y))); + let bounds = [ + corners.iter().map(|q| q.x).fold(f64::INFINITY, f64::min), + corners.iter().map(|q| q.y).fold(f64::INFINITY, f64::min), + corners.iter().map(|q| q.x).fold(f64::NEG_INFINITY, f64::max), + corners.iter().map(|q| q.y).fold(f64::NEG_INFINITY, f64::max), + ]; // Preferences ▸ General ▸ Always Create Smart Objects When Placing (on by default): off, an // embedded place lands as a plain pixel layer. A linked place is always a smart object. - let smart = linked.is_some() || p.get("smartObject").and_then(Value::as_bool).unwrap_or(s.prefs().general.always_create_smart_objects_when_placing); + let smart = frame.is_some() + || linked.is_some() + || p.get("smartObject").and_then(Value::as_bool).unwrap_or(s.prefs().general.always_create_smart_objects_when_placing); let source = match linked { Some(path) => SmartSource::Linked { path }, None => SmartSource::Embedded { file_name: file_name(name), bytes: Arc::new(bytes) }, @@ -296,20 +328,32 @@ pub fn place_bytes(s: &mut Session, name: &str, bytes: Vec, linked: Option Result { diff --git a/crates/engine/src/cmd/frame_cmds.rs b/crates/engine/src/cmd/frame_cmds.rs index 9bfcb257de..8e2ea786b5 100644 --- a/crates/engine/src/cmd/frame_cmds.rs +++ b/crates/engine/src/cmd/frame_cmds.rs @@ -1,55 +1,172 @@ -//! Layer › New › Frame from Layers. A frame clips its contents to a rectangle, so a template can -//! 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. -//! `layer.new.frame` is the Frame tool's (K) command: a rectangular or elliptical frame drawn on -//! the canvas, empty or holding the layer it was drawn over. Headless and scriptable like -//! every other command. - -use photocraft_doc::{Layer, LayerContent, LayerId, LayerMask, PixelFormat}; -use photocraft_geom::Rect; -use serde_json::{Value, json}; - +//! Photoshop-style image frames: independently editable vector containers with smart content. use crate::commands::CommandSpec; use crate::{EngineError, Result, Session}; +use photocraft_color::{BlendMode, Color}; +use photocraft_doc::{Document, Frame, Layer, LayerContent, LayerId, Path, VectorMask}; +use photocraft_geom::Affine; +use serde_json::{Value, json}; +fn bad(msg: impl Into) -> EngineError { + EngineError::BadParams { cmd: "layer.frame".into(), msg: msg.into() } +} +fn has_doc(s: &Session) -> std::result::Result<(), String> { + s.active().map(|_| ()).ok_or("no document open".into()) +} fn has_layer(s: &Session) -> std::result::Result<(), String> { - match s.active() { - Some(d) if !d.selected_layers.is_empty() || d.active_layer.is_some() => Ok(()), - Some(_) => Err("select a layer".into()), - None => Err("no document".into()), + s.active().and_then(|d| d.active_layer).map(|_| ()).ok_or("select a layer".into()) +} +/// The enclosing frame, including a frame's selected content. +pub fn frame_of(doc: &Document, id: LayerId) -> Option { + let path = doc.path_of(id)?; + (1..=path.len()).rev().filter_map(|n| doc.layer_at(path.get(..n)?)).find(|l| l.frame.is_some()).map(|l| l.id) +} +fn frame_id(s: &Session, p: &Value) -> Result { + let id = crate::vector_cmds::layer_id(s, p)?; + frame_of(&s.active().ok_or(EngineError::NoDocument)?.doc, id).ok_or_else(|| bad("select a frame")) +} +fn check_lock(doc: &Document, id: LayerId) -> Result<()> { + let locks = doc.effective_locks(id); + if locks.all || locks.position { Err(bad("the frame or its containing group is locked")) } else { Ok(()) } +} +fn geometry(p: &Value) -> Result { + let get = |key: &str| crate::commands::int_i32("layer.new.frame", p, key)?.ok_or_else(|| bad(format!("missing `{key}`"))); + let (x, y, w, h) = (get("x")?, get("y")?, get("width")?, get("height")?); + if !(1..=300_000).contains(&w) || !(1..=300_000).contains(&h) || x.checked_add(w).is_none() || y.checked_add(h).is_none() { + return Err(bad("frame sides must be 1..=300000 pixels, within the coordinate range")); + } + let shape = p.get("shape").map_or(Some("rectangle"), Value::as_str).ok_or_else(|| bad("shape must be a string"))?; + let path = match shape { + "rectangle" | "ellipse" | "triangle" | "polygon" => { + let sides = p.get("sides").map_or(Some(5), Value::as_u64).ok_or_else(|| bad("sides must be an integer"))?; + if !(3..=100).contains(&sides) { + return Err(bad("sides must be 3..=100")); + } + crate::vector_cmds::shape_path(&json!({"kind": match shape { "rectangle" => "rect", "ellipse" => "ellipse", _ => "polygon" }, + "rect": [0, 0, 1, 1], "sides": if shape == "triangle" { 3 } else { sides }}))? + } + "custom" => { + let path = crate::vector_cmds::parse_path(p.get("path").ok_or_else(|| bad("a custom frame needs path"))?).map_err(bad)?; + normalized(&path)?.0 + } + _ => return Err(bad("shape must be rectangle, ellipse, triangle, polygon or custom")), + }; + let stroke = p.get("stroke").map(|v| crate::vector_cmds::parse_stroke(v, None, Color::BLACK).map_err(bad)).transpose()?.flatten(); + let f = Frame { path, transform: Affine { m: [f64::from(w), 0.0, 0.0, f64::from(h), f64::from(x), f64::from(y)] }, stroke }; + if !f.valid() { + return Err(bad("invalid or excessively complex frame geometry")); + } + Ok(f) +} +fn normalized(path: &Path) -> Result<(Path, Affine)> { + let (x0, y0, x1, y1) = path.control_bounds().ok_or_else(|| bad("the outline is empty"))?; + let (w, h) = (x1 - x0, y1 - y0); + if ![x0, y0, x1, y1, w, h].iter().all(|v| v.is_finite()) || w <= 0.0 || h <= 0.0 { + return Err(bad("the outline must have finite nonzero dimensions")); + } + let transform = Affine { m: [w, 0.0, 0.0, h, x0, y0] }; + let inverse = transform.inverse().ok_or_else(|| bad("the outline is too small"))?; + Ok((path.transform(&inverse), transform)) +} +/// Keep the clipping path in the ordinary document model, so every compositor and exporter masks it. +pub fn refresh(layer: &mut Layer) { + if let Some(f) = &layer.frame { + layer.vector_mask = Some(VectorMask { path: f.outline(), enabled: true, linked: true, density: 1.0, feather: 0.0 }); } } - -/// A reveal mask that is on inside `rect` and off (hidden) everywhere else. -fn clip_mask(rect: Rect) -> LayerMask { - let mut mask = LayerMask::hide_all(); - let (w, h) = (rect.width() as usize, rect.height() as usize); - if w > 0 && h > 0 { - mask.surface.write_region(rect, &vec![1.0f32; w * h]); - mask.surface.prune(); - } - // Default to GRAY8 like the other mask constructors. - debug_assert_eq!(mask.surface.format(), PixelFormat::GRAY8); - mask +fn info(layer: &Layer) -> Value { + layer.frame.as_ref().map_or( + Value::Null, + |f| json!({"layer":layer.id.0,"name":layer.name,"transform":f.transform.m,"frame":[f.bounds().x0,f.bounds().y0,f.bounds().width(),f.bounds().height()],"stroke":f.stroke,"content":layer.children().and_then(|c| c.first()).map(|l|l.id.0)}), + ) +} +fn query(s: &mut Session, p: &Value) -> Result { + let id = frame_id(s, p)?; + Ok(info(s.active().and_then(|st| st.doc.layer(id)).ok_or(EngineError::NoLayer(id))?)) +} +fn new_frame(s: &mut Session, p: &Value) -> Result { + let f = geometry(p)?; + let content = match p.get("layer") { + None | Some(Value::Null) => None, + Some(_) => Some(crate::commands::layer_param(s, p)?), + }; + let name = p.get("name").map(|v| v.as_str().map(str::to_owned).ok_or_else(|| bad("name must be a string"))).transpose()?; + let gid = s.edit("New Frame", |doc, active| { + let child = match content { + None => None, + Some(id) => { + check_lock(doc, id)?; + let l = doc.layer(id).ok_or(EngineError::NoLayer(id))?; + if !matches!(l.content, LayerContent::Raster(_) | LayerContent::Text(_) | LayerContent::Shape(_) | LayerContent::Smart(_)) + || doc.is_background(id) + { + return Err(bad("a frame takes a pixel, type, shape or smart object layer other than the Background")); + } + if frame_of(doc, id).is_some() { + return Err(bad("that layer is already a frame's image")); + } + let mut child = if matches!(l.content, LayerContent::Smart(_)) { l.clone() } else { crate::smart_cmds::layer_to_smart(doc, l)? }; + child.id = id; + Some(child) + } + }; + let mut g = Layer::group(name.unwrap_or_else(|| doc.next_layer_name("Frame")), vec![]); + g.blend = BlendMode::Normal; + g.frame = Some(Box::new(f)); + refresh(&mut g); + // A frame is one row, as in Photoshop: closed, so the next new layer goes above it rather + // than into it. + if let LayerContent::Group(group) = &mut g.content { + group.expanded = false; + } + let gid = crate::layer_place::insert_new(doc, content.or(*active), g, crate::layer_place::Place::AutoEditable); + if let Some(child) = child { + doc.remove(child.id).ok_or(EngineError::NoLayer(child.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")?; + *active = Some(gid); + Ok(gid) + })?; + crate::layer_multi_cmds::reselect(s, vec![gid], Some(gid)); + let mut result = info(s.active().and_then(|st| st.doc.layer(gid)).ok_or(EngineError::NoLayer(gid))?); + result["shape"] = p.get("shape").cloned().unwrap_or(json!("rectangle")); + let (x, y, w, h) = (p["x"].clone(), p["y"].clone(), p["width"].clone(), p["height"].clone()); + result["frame"] = json!([x, y, w, h]); + Ok(result) } - -/// Groups the selected layers, then turns the group into a frame, as one history step: one undo -/// takes the whole command back (#496). fn frame_from_layers(s: &mut Session, p: &Value) -> Result { - let mut gp = serde_json::Map::new(); - if let Some(name) = p.get("name") { - gp.insert("name".into(), name.clone()); - } + let st = s.active().ok_or(EngineError::NoDocument)?; + let ids = st.selected_layers(); + let bounds = ids + .iter() + .filter_map(|id| st.doc.layer(*id)) + .map(|l| crate::transform_cmds::transform_frame(&st.doc, l)) + .reduce(|a, b| a.union(&b)) + .filter(|b| !b.is_empty()) + .unwrap_or(st.doc.bounds()); + let f = geometry(&json!({"x":bounds.x0,"y":bounds.y0,"width":bounds.width(),"height":bounds.height()}))?; let journal = s.journal.len(); - let grouped = s.execute("layer.new.groupFromLayers", Value::Object(gp))?; - match frame_group(s, &grouped) { - Ok(r) => { - // Fold the grouping step into the frame step. + let grouped = s.execute("layer.new.groupFromLayers", p.clone())?; + let id = LayerId(grouped.get("layer").and_then(Value::as_u64).ok_or_else(|| bad("grouping returned no layer"))?); + let r = s.edit("Frame from Layers", |doc, _| { + let group = doc.layer(id).ok_or(EngineError::NoLayer(id))?; + let children = group.children().ok_or_else(|| bad("not a group"))?.to_vec(); + let image = crate::smart_cmds::layers_to_smart(doc, &group.name, children)?; + let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; + if let Some(children) = l.children_mut() { + *children = vec![image]; + } + l.frame = Some(Box::new(f)); + l.blend = BlendMode::Normal; + refresh(l); + Ok(()) + }); + match r { + Ok(()) => { if let Some(st) = s.active_mut() { st.history.purge_last(); } - Ok(r) + Ok(json!({"layer":id.0,"frame":[bounds.x0,bounds.y0,bounds.width(),bounds.height()]})) } Err(e) => { // The group couldn't be framed: take the grouping back, leaving nothing to redo and @@ -60,247 +177,201 @@ fn frame_from_layers(s: &mut Session, p: &Value) -> Result { } } } - -/// Clips the group `layer.new.groupFromLayers` returned (`grouped`) to its contents' bounds. -fn frame_group(s: &mut Session, grouped: &Value) -> Result { - let gid = LayerId(grouped.get("layer").and_then(Value::as_u64).ok_or_else(|| EngineError::Other("grouping did not return a layer".into()))?); - let d = s.active().ok_or(EngineError::NoDocument)?; - let rect = - crate::layer_multi_cmds::layer_bounds(d.doc.layer(gid).ok_or(EngineError::NoLayer(gid))?).filter(|r| !r.is_empty()).unwrap_or_else(|| d.doc.bounds()); - - s.edit("Frame from Layers", |doc, _| { - let mask = crate::commands::mask_at_depth(clip_mask(rect), doc.depth)?; - doc.layer_mut(gid).ok_or(EngineError::NoLayer(gid))?.mask = Some(mask); +fn set(s: &mut Session, p: &Value) -> Result { + if !["transform", "stroke", "name"].iter().any(|key| p.get(key).is_some()) { + return Err(bad("supply transform, stroke or name")); + } + let id = frame_id(s, p)?; + s.edit("Frame Properties", |doc, _| { + check_lock(doc, id)?; + let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; + let f = l.frame.as_mut().ok_or_else(|| bad("not a frame"))?; + if let Some(v) = p.get("transform") { + let m: [f64; 6] = serde_json::from_value(v.clone()).map_err(|_| bad("transform must be six finite numbers"))?; + f.transform = Affine { m }; + } + if let Some(v) = p.get("stroke") { + f.stroke = crate::vector_cmds::parse_stroke(v, f.stroke.clone(), Color::BLACK).map_err(bad)?; + } + if let Some(v) = p.get("name") { + l.name = v.as_str().ok_or_else(|| bad("name must be a string"))?.into(); + } + if !f.valid() { + return Err(bad("invalid frame geometry or stroke")); + } + refresh(l); Ok(()) })?; - Ok(json!({"layer": gid.0, "frame": [rect.x0, rect.y0, rect.width(), rect.height()]})) + Ok(info(s.active().and_then(|st| st.doc.layer(id)).ok_or(EngineError::NoLayer(id))?)) } - -/// 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, type, shape or smart object layer, not the Background), -/// that layer becomes the frame's content, as when a frame is drawn over a selected 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 = crate::commands::explicit_layer(s, p)?; - let name = p.get("name").and_then(Value::as_str).map(str::to_string); - let gid = s.edit("New Frame", |doc, active| { - let mask = - crate::commands::mask_at_depth(if ellipse { ellipse_mask(rect, doc.bounds()) } else { clip_mask(rect.intersect(&doc.bounds())) }, doc.depth)?; - 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))?; - let framable = matches!(l.content, LayerContent::Raster(_) | LayerContent::Text(_) | LayerContent::Shape(_) | LayerContent::Smart(_)); - if !framable || doc.is_background(id) { - return Err(bad("only a pixel, type, shape or smart object 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 => crate::layer_place::insert_new(doc, *active, Layer::group(name, vec![]), crate::layer_place::Place::AutoEditable), +fn convert(s: &mut Session, p: &Value) -> Result { + let id = crate::vector_cmds::layer_id(s, p)?; + s.edit("Convert to Frame", |doc, active| { + check_lock(doc, id)?; + let l = doc.layer(id).ok_or(EngineError::NoLayer(id))?; + let outline = match &l.content { + LayerContent::Shape(sh) => sh.path.clone(), + LayerContent::Text(t) => crate::type_extra_cmds::text_path(doc, t), + _ => return Err(bad("select a shape or type layer")), }; - let frame = doc.layer_mut(gid).ok_or(EngineError::NoLayer(gid))?; - frame.mask = Some(mask); - // A frame is one row, as in Photoshop: closed, so the next new layer goes above it rather - // than into it. - if let LayerContent::Group(g) = &mut frame.content { - g.expanded = false; + let (path, transform) = normalized(&outline)?; + let mut f = Frame { path, transform, stroke: None }; + if p.get("width").is_some() || p.get("height").is_some() { + let [a, b, c, d, x, y] = f.transform.m; + let n = |k: &str, old: f64| -> Result { + match p.get(k) { + None => Ok(old), + Some(v) => v.as_f64().filter(|v| v.is_finite() && (1.0..=300_000.0).contains(v)).ok_or_else(|| bad(format!("{k} must be 1..=300000"))), + } + }; + f.transform.m = [n("width", a)?, b, c, n("height", d)?, x, y]; } - *active = Some(gid); - Ok(gid) + if !f.valid() { + return Err(bad("invalid converted frame")); + } + let name = p.get("name").map(|v| v.as_str().ok_or_else(|| bad("name must be a string"))).transpose()?.unwrap_or(&l.name).to_string(); + let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; + l.content = LayerContent::Group(photocraft_doc::Group { children: vec![], expanded: false, artboard: None, frame_stroke: None }); + l.name = name; + l.frame = Some(Box::new(f)); + l.mask = None; + l.effects = Default::default(); + // The group would otherwise still carry the type or shape layer's PSD content blocks. + l.fill_cache = None; + l.psd_blocks.retain(|(k, _)| !crate::vector_cmds::SHAPE_BLOCKS.contains(&k) && !matches!(k, b"TySh" | b"tySh" | b"lmfx")); + l.blend = BlendMode::Normal; + refresh(l); + *active = Some(id); + Ok(()) })?; - 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" }})) + Ok(info(s.active().and_then(|st| st.doc.layer(id)).ok_or(EngineError::NoLayer(id))?)) +} +/// Insert/replace the image, preserving the container's identity and placement. +pub fn put_content(doc: &mut Document, id: LayerId, layer: Layer) -> Result<()> { + check_lock(doc, id)?; + let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; + if l.frame.is_none() { + return Err(bad("not a frame")); + } + let children = l.children_mut().ok_or_else(|| bad("frame is not a container"))?; + *children = vec![layer]; + Ok(()) +} +fn set_content(s: &mut Session, p: &Value) -> Result { + let id = frame_id(s, p)?; + let source = LayerId(p.get("content").and_then(Value::as_u64).ok_or_else(|| bad("content must name an image layer"))?); + let copy = p.get("copy").map_or(Some(false), Value::as_bool).ok_or_else(|| bad("copy must be a boolean"))?; + let child_id = s.edit("Replace Frame Content", |doc, active| { + check_lock(doc, source)?; + let src = doc.layer(source).ok_or(EngineError::NoLayer(source))?; + if !matches!(src.content, LayerContent::Raster(_) | LayerContent::Smart(_)) || frame_of(doc, source) == Some(source) { + return Err(bad("content must be a pixel or smart object layer")); + } + let mut child = if matches!(src.content, LayerContent::Smart(_)) { src.clone() } else { crate::smart_cmds::layer_to_smart(doc, src)? }; + if copy { + child = child.duplicate(); + } else { + child.id = source; + doc.remove(source).ok_or(EngineError::NoLayer(source))?; + } + let child_id = child.id; + put_content(doc, id, child)?; + *active = Some(id); + Ok(child_id) + })?; + Ok(json!({"layer":id.0,"content":child_id.0})) +} +fn fit(s: &mut Session, p: &Value) -> Result { + let id = frame_id(s, p)?; + let st = s.active().ok_or(EngineError::NoDocument)?; + let l = st.doc.layer(id).ok_or(EngineError::NoLayer(id))?; + let f = l.frame.as_ref().ok_or_else(|| bad("not a frame"))?.clone(); + let child = l.children().and_then(|c| c.first()).ok_or_else(|| bad("the frame has no image"))?; + check_lock(&st.doc, id)?; + check_lock(&st.doc, child.id)?; + // Transparent margins are part of a placed image. Fitting its painted-pixel bounds would + // progressively zoom a PNG on every click; use the immutable source canvas instead. + if let LayerContent::Smart(smart) = &child.content + && smart.warp.is_none() + && smart.perspective.is_none() + && let Some([x0, y0, x1, y1]) = crate::smart_cmds::source_box(&st.doc, smart) + { + let (w, h) = (x1 - x0, y1 - y0); + if w <= 0.0 || h <= 0.0 { + return Err(bad("the frame image has no canvas")); + } + match p.get("mode").map_or(Some("contentToFrame"), Value::as_str) { + Some("frameToContent") => { + let transform = smart.transform.mul(&Affine { m: [w, 0.0, 0.0, h, x0, y0] }); + return set(s, &json!({"layer":id.0,"transform":transform.m})); + } + Some("contentToFrame") => { + let [a, b, c, d, _, _] = f.transform.m; + let (fw, fh) = (a.hypot(b), c.hypot(d)); + let k = (fw / w).max(fh / h); + let transform = + f.transform.mul(&Affine { m: [k / fw, 0.0, 0.0, k / fh, (1.0 - w * k / fw) / 2.0 - x0 * k / fw, (1.0 - h * k / fh) / 2.0 - y0 * k / fh] }); + let child_id = child.id; + let relative = transform.mul(&smart.transform.inverse().ok_or_else(|| bad("the frame image has a degenerate transform"))?); + // The same path as `edit.transform`, so the image's linked masks and Smart Filter + // mask move with it. + return s.edit("Fit Content to Frame", |doc, _| { + crate::transform_cmds::transform_by(doc, child_id, relative, photocraft_algo::transform::Interp::Bicubic)?; + Ok(json!({"layer":id.0,"content":child_id.0})) + }); + } + _ => return Err(bad("mode must be contentToFrame or frameToContent")), + } + } + let b = crate::transform_cmds::transform_frame(&st.doc, child); + if b.is_empty() { + return Err(bad("the frame content is empty")); + } + match p.get("mode").map_or(Some("contentToFrame"), Value::as_str) { + Some("frameToContent") => set(s, &json!({"layer":id.0,"transform":[b.width(),0,0,b.height(),b.x0,b.y0]})), + Some("contentToFrame") => { + let [a, bv, c, d, _, _] = f.transform.m; + let (w, h) = (a.hypot(bv), c.hypot(d)); + let k = (w / f64::from(b.width())).max(h / f64::from(b.height())); + let (nw, nh) = (f64::from(b.width()) * k / w, f64::from(b.height()) * k / h); + let quad = [ + (-0.5 * (nw - 1.0), -0.5 * (nh - 1.0)), + (0.5 * (nw + 1.0), -0.5 * (nh - 1.0)), + (0.5 * (nw + 1.0), 0.5 * (nh + 1.0)), + (-0.5 * (nw - 1.0), 0.5 * (nh + 1.0)), + ] + .map(|(x, y)| { + let q = f.transform.apply(photocraft_geom::Point::new(x, y)); + [q.x, q.y] + }); + s.execute("edit.transform", json!({"layer":child.id.0,"rect":[b.x0,b.y0,b.x1,b.y1],"quad":quad})) + } + _ => Err(bad("mode must be contentToFrame or frameToContent")), + } } - pub fn specs() -> Vec { + let spec = |id, label, params, enabled, run| CommandSpec { id, label, params, menu: &[], shortcut: None, journal: true, enabled, run }; 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, type, shape or smart object 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), - }, + spec( + "layer.new.frame", + "New Frame", + r#"{"x":i32,"y":i32,"width":u32,"height":u32,"shape":"rectangle|ellipse|triangle|polygon|custom"="rectangle","sides":3..100=5,"path":object?,"stroke":object|null?,"layer":id?,"name":str?} → {layer,frame:[x,y,w,h],shape}"#, + has_doc, + new_frame, + ), + CommandSpec { menu: &["Layer", "New"], ..spec("layer.new.frameFromLayers", "Frame from Layers", r#"{name?:str}"#, has_layer, frame_from_layers) }, + spec("layer.frame.set", "Frame Properties", r#"{"layer":id?,"transform":[a,b,c,d,x,y]?,"stroke":object|null?,"name":str?}"#, has_doc, set), + CommandSpec { journal: false, ..spec("layer.frame.info", "Frame Info", r#"{"layer":id?}"#, has_doc, query) }, + spec("layer.frame.convert", "Convert to Frame", r#"{"layer":id?,"name":str?,"width":px?,"height":px?}"#, has_doc, convert), + spec( + "layer.frame.setContent", + "Replace Frame Content", + r#"{"layer":id?,"content":id,"copy":bool=false}: a layer dragged into a frame keeps its original size"#, + has_doc, + set_content, + ), + spec("layer.frame.fit", "Fit Frame / Content", r#"{"layer":id?,"mode":"contentToFrame|frameToContent"="contentToFrame"}"#, has_doc, fit), ] } - #[cfg(test)] -mod tests { - use super::*; - use photocraft_doc::{Layer, LayerContent}; - use photocraft_geom::Rect; - - fn session() -> (Session, LayerId, LayerId) { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 80, "height": 60})).unwrap(); - let (a, b) = s - .edit("setup", |doc, _| { - let fmt = doc.pixel_format(); - let mut a = Layer::raster("A", fmt); - a.surface_mut().unwrap().fill_rect(Rect::new(4, 4, 24, 24), &photocraft_raster::from_rgba(&fmt, [1.0, 0.0, 0.0, 1.0])); - let mut b = Layer::raster("B", fmt); - b.surface_mut().unwrap().fill_rect(Rect::new(30, 20, 50, 40), &photocraft_raster::from_rgba(&fmt, [0.0, 0.0, 1.0, 1.0])); - let (ia, ib) = (a.id, b.id); - doc.layers.push(a); - doc.layers.push(b); - Ok((ia, ib)) - }) - .unwrap(); - (s, a, b) - } - - #[test] - fn frames_selected_layers_into_a_masked_group() { - let (mut s, a, b) = session(); - s.execute("layer.select", json!({"layer": a.0, "mode": "replace"})).unwrap(); - s.execute("layer.select", json!({"layer": b.0, "mode": "add"})).unwrap(); - let r = s.execute("layer.new.frameFromLayers", json!({"name": "Frame 1"})).unwrap(); - let gid = LayerId(r["layer"].as_u64().unwrap()); - // frame rect = union of the two layers' bounds (4,4)..(50,40). - let frame = r["frame"].as_array().unwrap(); - assert_eq!(frame[2].as_i64().unwrap(), 50 - 4); // width - assert_eq!(frame[3].as_i64().unwrap(), 40 - 4); // height - let st = s.active().unwrap(); - let g = st.doc.layer(gid).unwrap(); - assert!(matches!(g.content, LayerContent::Group(_)), "it's a group"); - assert!(g.mask.is_some(), "the group has a clip mask"); - // Undoable (last step is the frame). - assert_eq!(st.history.entries().last().map(|e| e.as_str()), Some("Frame from Layers")); - } - - #[test] - fn frame_from_layers_is_one_history_step() { - // #496: grouping and framing undo together. - let (mut s, a, b) = session(); - let entries = s.active().unwrap().history.entries(); - let layers = |s: &Session| s.active().unwrap().doc.layers.iter().map(|l| l.id).collect::>(); - let before = layers(&s); - s.execute("layer.select", json!({"layer": a.0, "mode": "replace"})).unwrap(); - s.execute("layer.select", json!({"layer": b.0, "mode": "add"})).unwrap(); - let gid = LayerId(s.execute("layer.new.frameFromLayers", json!({})).unwrap()["layer"].as_u64().unwrap()); - let mut framed = entries.clone(); - framed.push("Frame from Layers".into()); - assert_eq!(s.active().unwrap().history.entries(), framed); - assert!(s.undo()); - assert_eq!(s.active().unwrap().history.entries(), entries); - assert_eq!(layers(&s), before, "one undo leaves no group behind"); - assert!(s.redo()); - 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()); - } - } - - /// #4435: a type layer (and the other rendered layer kinds) goes into a frame like a pixel layer. - #[test] - fn new_frame_takes_a_type_layer() { - let (mut s, a, _) = session(); - let tid = s - .edit("setup", |doc, _| { - let cache = doc.layer(a).and_then(|l| l.surface()).cloned(); - let t = Layer::new("T", LayerContent::Text(photocraft_doc::TextLayer { cache, ..Default::default() })); - let id = t.id; - doc.layers.push(t); - Ok(id) - }) - .unwrap(); - let r = s.execute("layer.new.frame", json!({"x": 0, "y": 0, "width": 40, "height": 30, "layer": tid.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([tid])), "the frame holds the type layer"); - assert!(s.undo()); - assert!(s.active().unwrap().doc.layer(tid).is_some(), "undo gives the type layer back"); - } - - #[test] - fn needs_a_selected_layer() { - let mut s = Session::new(); - assert!(s.execute("layer.new.frameFromLayers", json!({})).is_err()); - } -} +mod tests; diff --git a/crates/engine/src/cmd/frame_cmds/tests.rs b/crates/engine/src/cmd/frame_cmds/tests.rs new file mode 100644 index 0000000000..d399af33cf --- /dev/null +++ b/crates/engine/src/cmd/frame_cmds/tests.rs @@ -0,0 +1,553 @@ +use super::*; +use photocraft_doc::{Layer, LayerContent}; +use photocraft_geom::Rect; + +fn session() -> (Session, LayerId, LayerId) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 80, "height": 60})).unwrap(); + let (a, b) = s + .edit("setup", |doc, _| { + let fmt = doc.pixel_format(); + let mut a = Layer::raster("A", fmt); + a.surface_mut().unwrap().fill_rect(Rect::new(4, 4, 24, 24), &photocraft_raster::from_rgba(&fmt, [1.0, 0.0, 0.0, 1.0])); + let mut b = Layer::raster("B", fmt); + b.surface_mut().unwrap().fill_rect(Rect::new(30, 20, 50, 40), &photocraft_raster::from_rgba(&fmt, [0.0, 0.0, 1.0, 1.0])); + let (ia, ib) = (a.id, b.id); + doc.layers.push(a); + doc.layers.push(b); + Ok((ia, ib)) + }) + .unwrap(); + (s, a, b) +} + +#[test] +fn frames_selected_layers_into_a_masked_group() { + let (mut s, a, b) = session(); + s.execute("layer.select", json!({"layer": a.0, "mode": "replace"})).unwrap(); + s.execute("layer.select", json!({"layer": b.0, "mode": "add"})).unwrap(); + let r = s.execute("layer.new.frameFromLayers", json!({"name": "Frame 1"})).unwrap(); + let gid = LayerId(r["layer"].as_u64().unwrap()); + // frame rect = union of the two layers' bounds (4,4)..(50,40). + let frame = r["frame"].as_array().unwrap(); + assert_eq!(frame[2].as_i64().unwrap(), 50 - 4); // width + assert_eq!(frame[3].as_i64().unwrap(), 40 - 4); // height + let st = s.active().unwrap(); + let g = st.doc.layer(gid).unwrap(); + assert!(matches!(g.content, LayerContent::Group(_)), "it's a group"); + assert!(g.frame.is_some() && g.vector_mask.is_some(), "the group has a clip mask"); + // Undoable (last step is the frame). + assert_eq!(st.history.entries().last().map(|e| e.as_str()), Some("Frame from Layers")); +} + +#[test] +fn frame_from_layers_is_one_history_step() { + // #496: grouping and framing undo together. + let (mut s, a, b) = session(); + let entries = s.active().unwrap().history.entries(); + let layers = |s: &Session| s.active().unwrap().doc.layers.iter().map(|l| l.id).collect::>(); + let before = layers(&s); + s.execute("layer.select", json!({"layer": a.0, "mode": "replace"})).unwrap(); + s.execute("layer.select", json!({"layer": b.0, "mode": "add"})).unwrap(); + let gid = LayerId(s.execute("layer.new.frameFromLayers", json!({})).unwrap()["layer"].as_u64().unwrap()); + let mut framed = entries.clone(); + framed.push("Frame from Layers".into()); + assert_eq!(s.active().unwrap().history.entries(), framed); + assert!(s.undo()); + assert_eq!(s.active().unwrap().history.entries(), entries); + assert_eq!(layers(&s), before, "one undo leaves no group behind"); + assert!(s.redo()); + assert!(s.active().unwrap().doc.layer(gid).is_some_and(|g| g.frame.is_some() && g.vector_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 = TestMask(g.vector_mask.as_ref().unwrap().path.clone()); + 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 = TestMask(g.vector_mask.as_ref().unwrap().path.clone()); + 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()); + } +} + +/// #4435: a type layer (and the other rendered layer kinds) goes into a frame like a pixel layer. +#[test] +fn new_frame_takes_a_type_layer() { + let (mut s, a, _) = session(); + let tid = s + .edit("setup", |doc, _| { + let cache = doc.layer(a).and_then(|l| l.surface()).cloned(); + let t = Layer::new("T", LayerContent::Text(photocraft_doc::TextLayer { cache, ..Default::default() })); + let id = t.id; + doc.layers.push(t); + Ok(id) + }) + .unwrap(); + let r = s.execute("layer.new.frame", json!({"x": 0, "y": 0, "width": 40, "height": 30, "layer": tid.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([tid])), "the frame holds the type layer"); + assert!(s.undo()); + assert!(s.active().unwrap().doc.layer(tid).is_some(), "undo gives the type layer back"); +} + +#[test] +fn needs_a_selected_layer() { + let mut s = Session::new(); + assert!(s.execute("layer.new.frameFromLayers", json!({})).is_err()); +} + +struct TestMask(photocraft_doc::Path); +impl TestMask { + fn value(&self, x: i32, y: i32) -> f32 { + photocraft_vector::path_coverage(&self.0, Rect::new(x, y, x + 1, y + 1))[0] + } +} + +#[test] +fn frame_and_smart_image_transform_independently_at_every_depth() { + for depth in [8, 16, 32] { + let mut s = Session::new(); + s.execute("file.new", json!({"width":80,"height":60,"depth":depth})).unwrap(); + let source = s + .edit("Image", |doc, _| { + let mut l = Layer::raster("Photo", doc.pixel_format()); + l.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 80, 60), &photocraft_raster::from_rgba(&doc.pixel_format(), [1., 0., 0., 1.])); + let id = l.id; + doc.layers.push(l); + Ok(id) + }) + .unwrap(); + let id = LayerId(s.execute("layer.new.frame", json!({"x":10,"y":10,"width":40,"height":30,"layer":source.0})).unwrap()["layer"].as_u64().unwrap()); + let original = s.active().unwrap().doc.layer(source).unwrap().clone(); + assert!(matches!(original.content, LayerContent::Smart(_))); + s.execute("layer.frame.set", json!({"layer":id.0,"transform":[20,0,0,25,30,12]})).unwrap(); + assert_eq!(s.active().unwrap().doc.layer(source).unwrap(), &original, "frame-only editing preserves the complete image"); + let frame = s.active().unwrap().doc.layer(id).unwrap().frame.clone(); + s.execute("layer.translate", json!({"layer":source.0,"dx":4,"dy":6})).unwrap(); + assert_eq!(s.active().unwrap().doc.layer(id).unwrap().frame, frame, "content-only movement leaves the frame"); + s.execute("layer.translate", json!({"layer":id.0,"dx":5,"dy":7})).unwrap(); + let f = s.active().unwrap().doc.layer(id).unwrap().frame.as_ref().unwrap(); + assert_eq!(f.transform.m, [20., 0., 0., 25., 35., 19.]); + let before = s.active().unwrap().doc.clone(); + s.execute("edit.transform", json!({"layer":id.0,"rect":[35,19,55,44],"quad":[[35,19],[75,19],[75,69],[35,69]]})).unwrap(); + assert_eq!(s.active().unwrap().doc.layer(id).unwrap().frame.as_ref().unwrap().transform.m, [40., 0., 0., 50., 35., 19.]); + assert!(s.undo()); + assert_eq!(s.active().unwrap().doc.layer(id).unwrap().frame, before.layer(id).unwrap().frame); + } +} + +#[test] +fn frame_placement_covers_and_replaces_with_one_undo() { + let (mut s, _, _) = session(); + let id = LayerId(s.execute("layer.new.frame", json!({"x":10,"y":10,"width":40,"height":30})).unwrap()["layer"].as_u64().unwrap()); + let mut image = Document::new("Image", photocraft_geom::Size::new(20, 10), photocraft_color::ColorMode::Rgb, photocraft_color::SampleType::U8); + let mut l = Layer::raster("Photo", image.pixel_format()); + l.surface_mut().unwrap().fill_rect(image.bounds(), &[0., 0., 1., 1.]); + image.layers.push(l); + let png = photocraft_io::export(&image, "png", &Default::default()).unwrap().bytes; + let result = crate::file_cmds::place_bytes(&mut s, "blue.png", png.clone(), None, &json!({"smartObject":false})).unwrap(); + assert_eq!(result["frame"], id.0); + assert_eq!(result["scale"], 300.0); + let frame = s.active().unwrap().doc.layer(id).unwrap(); + let child = frame.children().unwrap().first().unwrap(); + let first = child.id; + let LayerContent::Smart(sm) = &child.content else { panic!("a placed frame image must remain smart") }; + assert_eq!(sm.transform.m, [3., 0., 0., 3., 0., 10.]); + crate::file_cmds::place_bytes(&mut s, "again.png", png, None, &json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc.layer(id).unwrap().children().unwrap().len(), 1); + assert_ne!(s.active().unwrap().doc.layer(id).unwrap().children().unwrap()[0].id, first); + assert!(s.undo()); + assert_eq!(s.active().unwrap().doc.layer(id).unwrap().children().unwrap()[0].id, first); +} + +#[test] +fn frame_shapes_strokes_and_editability_survive_native_and_psd() { + for depth in [8, 16, 32] { + for shape in ["rectangle", "ellipse", "triangle", "polygon", "custom"] { + let mut s = Session::new(); + s.execute("file.new", json!({"width":64,"height":48,"depth":depth,"background":"transparent"})).unwrap(); + let p = json!({"x":12,"y":10,"width":32,"height":24,"shape":shape,"sides":6, + "path":{"subpaths":[{"closed":true,"knots":[[0,0],[100,0],[50,100]]}]},"stroke":{"color":"#ff0000","width":3,"align":"outside"}}); + let id = LayerId(s.execute("layer.new.frame", p).unwrap()["layer"].as_u64().unwrap()); + let original = &s.active().unwrap().doc; + let rendered = photocraft_compose::render(original, original.bounds()); + assert!(rendered.px.iter().any(|p| p[0] > 0.9 && p[3] > 0.5), "empty {shape} stroke at {depth}"); + for name in ["pcraft", "psd"] { + let bytes = photocraft_io::export(original, name, &Default::default()).unwrap().bytes; + let restored = photocraft_io::import(name, &bytes).unwrap().document; + let l = restored + .walk() + .into_iter() + .find(|(_, _, l)| l.frame.is_some()) + .unwrap_or_else(|| { + panic!( + "no frame in {name} {shape} {depth}; {:?}", + restored.walk().iter().map(|(_, _, l)| (&l.name, l.psd_blocks.iter().map(|(k, _)| k).collect::>())).collect::>() + ) + }) + .2; + assert_eq!(l.frame, original.layer(id).unwrap().frame, "{name} {shape} {depth}"); + assert!(l.children().unwrap().is_empty(), "export-only vector border is not frame content"); + let after = photocraft_compose::render(&restored, restored.bounds()); + let error = rendered.px.iter().zip(after.px.iter()).flat_map(|(a, b)| a.iter().zip(b).map(|(a, b)| (a - b).abs())).fold(0.0f32, f32::max); + assert!(error < 0.025, "{name} {shape} {depth}: {error}"); + } + } + } +} + +#[test] +fn frame_commands_reject_invalid_geometry_and_locks_without_history_changes() { + let (mut s, _, _) = session(); + let id = s.execute("layer.new.frame", json!({"x":10,"y":10,"width":20,"height":20})).unwrap()["layer"].as_u64().unwrap(); + let before = s.active().unwrap().doc.clone(); + let history = s.active().unwrap().history.entries(); + for p in [ + json!({"layer":id,"transform":[0,0,0,0,1,1]}), + json!({"layer":id,"transform":[1e200,0,0,1,0,0]}), + json!({"layer":id,"stroke":{"width":1e8}}), + json!({"layer":id,"transform":"bad"}), + ] { + assert!(s.execute("layer.frame.set", p).is_err()); + assert_eq!(s.active().unwrap().doc.layer(LayerId(id)).unwrap(), before.layer(LayerId(id)).unwrap()); + assert_eq!(s.active().unwrap().history.entries(), history); + } + s.execute("layer.setProps", json!({"layer":id,"locks":{"position":true}})).unwrap(); + assert!(s.execute("layer.frame.set", json!({"layer":id,"transform":[30,0,0,30,10,10]})).is_err()); + assert!(s.execute("layer.frame.fit", json!({"layer":id})).is_err()); + assert!(s.execute("layer.frame.setContent", json!({"layer":id,"content":id})).is_err()); +} + +#[test] +fn converting_a_shape_uses_its_outline_and_leaves_an_empty_frame() { + let (mut s, _, _) = session(); + let r = s.execute("shape.create", json!({"kind":"ellipse","rect":[10,15,40,30],"fill":"#123456"})).unwrap(); + let id = r["layer"].as_u64().unwrap(); + s.execute("layer.frame.convert", json!({"layer":id,"name":"Portrait","width":20,"height":25})).unwrap(); + let l = s.active().unwrap().doc.layer(LayerId(id)).unwrap(); + assert_eq!(l.name, "Portrait"); + assert!(l.children().unwrap().is_empty()); + assert_eq!(l.frame.as_ref().unwrap().transform.m, [20., 0., 0., 25., 10., 15.]); + assert_eq!(TestMask(l.vector_mask.as_ref().unwrap().path.clone()).value(10, 15), 0.0); + assert!(s.undo()); + assert!(matches!(s.active().unwrap().doc.layer(LayerId(id)).unwrap().content, LayerContent::Shape(_))); +} + +#[test] +fn fitting_transparent_images_uses_their_canvas_and_is_idempotent() { + let (mut s, _, _) = session(); + let frame = s.execute("layer.new.frame", json!({"x":10,"y":10,"width":40,"height":30})).unwrap()["layer"].as_u64().unwrap(); + let mut image = Document::new("Transparent", photocraft_geom::Size::new(20, 10), photocraft_color::ColorMode::Rgb, photocraft_color::SampleType::U8); + let mut l = Layer::raster("Mark", image.pixel_format()); + l.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 4, 4), &[0., 0., 1., 1.]); + image.layers.push(l); + let bytes = photocraft_io::export(&image, "png", &Default::default()).unwrap().bytes; + crate::file_cmds::place_bytes(&mut s, "transparent.png", bytes, None, &json!({})).unwrap(); + let child = s.active().unwrap().doc.layer(LayerId(frame)).unwrap().children().unwrap()[0].id; + let pose = |s: &Session| { + let LayerContent::Smart(sm) = &s.active().unwrap().doc.layer(child).unwrap().content else { panic!("smart") }; + sm.transform + }; + let before = pose(&s); + assert_eq!(before.m, [3., 0., 0., 3., 0., 10.]); + for _ in 0..3 { + s.execute("layer.frame.fit", json!({"layer":frame})).unwrap(); + assert_eq!(pose(&s), before); + } + s.execute("layer.frame.fit", json!({"layer":frame,"mode":"frameToContent"})).unwrap(); + assert_eq!(s.active().unwrap().doc.layer(LayerId(frame)).unwrap().frame.as_ref().unwrap().bounds(), Rect::new(0, 10, 60, 40)); + assert_eq!(pose(&s), before); +} + +#[test] +fn explicit_frames_accept_layer_drops_when_the_dragged_image_is_active() { + let (mut s, a, _) = session(); + let frame = s.execute("layer.new.frame", json!({"x":10,"y":10,"width":40,"height":30})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.select", json!({"layer":a.0})).unwrap(); + let before = crate::transform_cmds::transform_frame(&s.active().unwrap().doc, s.active().unwrap().doc.layer(a).unwrap()); + s.execute("layer.frame.setContent", json!({"layer":frame,"content":a.0})).unwrap(); + let child = s.active().unwrap().doc.layer(LayerId(frame)).unwrap().children().unwrap().first().unwrap(); + assert_eq!(child.id, a); + assert!(matches!(child.content, LayerContent::Smart(_))); + assert_eq!(crate::transform_cmds::transform_frame(&s.active().unwrap().doc, child), before, "a layer drop does not resize or recenter the image"); + s.execute("layer.select", json!({"layer":s.active().unwrap().doc.layers.first().unwrap().id.0})).unwrap(); + assert!(s.execute("layer.frame.set", json!({"layer":frame,"name":"Portrait"})).is_ok()); + let (history, journal) = (s.active().unwrap().history.entries(), s.journal.len()); + let info = s.execute("layer.frame.info", json!({"layer":frame})).unwrap(); + assert_eq!(info["name"], "Portrait"); + assert_eq!(info["frame"], json!([10, 10, 40, 30])); + assert_eq!(info["content"], a.0); + assert_eq!(s.active().unwrap().history.entries(), history); + assert_eq!(s.journal.len(), journal); +} + +#[test] +fn copying_an_image_into_a_frame_preserves_the_source_and_undoes_together() { + let (mut s, a, _) = session(); + let frame = s.execute("layer.new.frame", json!({"x":10,"y":10,"width":40,"height":30})).unwrap()["layer"].as_u64().unwrap(); + let source = s.active().unwrap().doc.layer(a).unwrap().clone(); + let entries = s.active().unwrap().history.entries(); + let placed = s.execute("layer.frame.setContent", json!({"layer":frame,"content":a.0,"copy":true})).unwrap(); + assert_ne!(placed["content"], a.0); + assert_eq!(s.active().unwrap().doc.layer(a).unwrap(), &source); + let child = s.active().unwrap().doc.layer(LayerId(frame)).unwrap().children().unwrap().first().unwrap(); + assert_eq!( + crate::transform_cmds::transform_frame(&s.active().unwrap().doc, child), + crate::transform_cmds::transform_frame(&s.active().unwrap().doc, &source) + ); + s.undo(); + assert_eq!(s.active().unwrap().history.entries(), entries); + assert!(s.active().unwrap().doc.layer(LayerId(frame)).unwrap().children().unwrap().is_empty()); + assert_eq!(s.active().unwrap().doc.layer(a).unwrap(), &source); +} + +#[test] +fn empty_frame_placeholders_do_not_schedule_canvas_sized_composites() { + let mut s = Session::new(); + s.execute("file.new", json!({"width":6000,"height":4000})).unwrap(); + let frame = LayerId(s.execute("layer.new.frame", json!({"x":100,"y":100,"width":5800,"height":3800})).unwrap()["layer"].as_u64().unwrap()); + let st = s.active().unwrap(); + let layer = st.doc.layer(frame).unwrap(); + assert_eq!(crate::transform_cmds::transform_frame(&st.doc, layer), Rect::new(100, 100, 5900, 3900), "the editable container still has its full geometry"); + assert_eq!(photocraft_compose::layer_bounds(layer, st.doc.bounds()), Rect::EMPTY); + assert_eq!(photocraft_compose::composite_bounds(layer, st.doc.bounds()), Some(Rect::EMPTY)); + s.execute("layer.frame.set", json!({"layer":frame.0,"stroke":{"color":"#ff0000","width":2}})).unwrap(); + let st = s.active().unwrap(); + assert!(!photocraft_compose::layer_bounds(st.doc.layer(frame).unwrap(), st.doc.bounds()).is_empty()); +} + +#[test] +fn new_layers_and_outside_placement_do_not_enter_a_frames_image_slot() { + let (mut s, image, _) = session(); + let frame = LayerId(s.execute("layer.new.frame", json!({"x":10,"y":10,"width":40,"height":30,"layer":image.0})).unwrap()["layer"].as_u64().unwrap()); + s.execute("layer.select", json!({"layer":image.0})).unwrap(); + let new = s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap(); + assert_eq!(s.active().unwrap().doc.path_of(LayerId(new)).unwrap().len(), 1); + s.execute("layer.select", json!({"layer":image.0})).unwrap(); + let bytes = photocraft_io::export(&s.active().unwrap().doc, "png", &Default::default()).unwrap().bytes; + let placed = crate::file_cmds::place_bytes(&mut s, "outside.png", bytes, None, &json!({"frame":false})).unwrap(); + assert_eq!(placed["frame"], Value::Null); + let st = s.active().unwrap(); + assert_eq!(st.doc.path_of(LayerId(placed["layer"].as_u64().unwrap())).unwrap().len(), 1); + assert_eq!(st.doc.layer(frame).unwrap().children().unwrap().len(), 1); + assert_eq!(st.doc.layer(frame).unwrap().children().unwrap()[0].id, image); + let mut doc = (*st.doc).clone(); + let below = Layer::raster("Below", doc.pixel_format()); + let id = doc.insert_below(Some(image), below); + assert_eq!(doc.path_of(id).unwrap().len(), 1); + assert_eq!(doc.layer(frame).unwrap().children().unwrap().len(), 1); +} + +fn blue_png(w: u32, h: u32) -> Vec { + let mut image = Document::new("Image", photocraft_geom::Size::new(w, h), photocraft_color::ColorMode::Rgb, photocraft_color::SampleType::U8); + let mut l = Layer::raster("Photo", image.pixel_format()); + l.surface_mut().unwrap().fill_rect(image.bounds(), &[0., 0., 1., 1.]); + image.layers.push(l); + photocraft_io::export(&image, "png", &Default::default()).unwrap().bytes +} + +#[test] +fn frame_placement_reports_document_bounds() { + let (mut s, _, _) = session(); + s.execute("layer.new.frame", json!({"x":10,"y":10,"width":40,"height":30})).unwrap(); + // 20×10 covers 40×30 at 3×: 60×30, centred on the frame, so 10 px overhangs each side. + let r = crate::file_cmds::place_bytes(&mut s, "blue.png", blue_png(20, 10), None, &json!({})).unwrap(); + assert_eq!(r["bounds"], json!([0.0, 10.0, 60.0, 40.0]), "{r}"); +} + +#[test] +fn placing_into_a_huge_frame_does_not_resample_to_the_frame_size() { + // Filling this frame scales the image to 300000×150000 px (45 Gpx). Placement used to + // bicubic-resize it to that size, and the smart object render warped it unclipped: either + // filled memory until the OS killed the process. The render now refuses it up front. + let (mut s, _, _) = session(); + let id = LayerId(s.execute("layer.new.frame", json!({"x":0,"y":0,"width":200_000,"height":150_000})).unwrap()["layer"].as_u64().unwrap()); + let before = s.active().unwrap().history.entries(); + let err = crate::file_cmds::place_bytes(&mut s, "blue.png", blue_png(20, 10), None, &json!({})).unwrap_err(); + assert!(err.to_string().contains("too large"), "{err}"); + let st = s.active().unwrap(); + assert_eq!(st.history.entries(), before, "a failed place leaves no history"); + assert!(st.doc.layer(id).unwrap().children().unwrap().is_empty()); +} + +#[test] +fn fitting_content_to_a_huge_frame_is_refused_before_rendering() { + let (mut s, image, _) = session(); + let id = s.execute("layer.new.frame", json!({"x":0,"y":0,"width":40,"height":30,"layer":image.0})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.frame.set", json!({"layer":id,"transform":[200_000,0,0,150_000,0,0]})).unwrap(); + let before = s.active().unwrap().history.entries(); + let err = s.execute("layer.frame.fit", json!({"layer":id,"mode":"contentToFrame"})).unwrap_err(); + assert!(err.to_string().contains("too large"), "{err}"); + assert_eq!(s.active().unwrap().history.entries(), before); +} + +#[test] +fn converting_drops_the_layers_own_psd_content_blocks() { + let (mut s, _, _) = session(); + let id = s.execute("shape.create", json!({"kind":"rectangle","rect":[10,15,40,30],"fill":"#123456"})).unwrap()["layer"].as_u64().unwrap(); + s.edit("blocks", |doc, _| { + let l = doc.layer_mut(LayerId(id)).unwrap(); + for k in [b"TySh", b"tySh", b"SoCo", b"vscg", b"vstk", b"lmfx", b"luni"] { + l.psd_blocks.push((*k, std::sync::Arc::new(vec![0; 4]))); + } + Ok(()) + }) + .unwrap(); + s.execute("layer.frame.convert", json!({"layer":id})).unwrap(); + let l = s.active().unwrap().doc.layer(LayerId(id)).unwrap(); + let keys: Vec<_> = l.psd_blocks.iter().map(|(k, _)| k).collect(); + assert_eq!(keys, [b"luni"], "only blocks unrelated to the shape survive"); + assert!(l.fill_cache.is_none()); +} + +#[test] +fn a_frames_image_cannot_be_framed_again() { + let (mut s, image, _) = session(); + let first = LayerId(s.execute("layer.new.frame", json!({"x":0,"y":0,"width":40,"height":30,"layer":image.0})).unwrap()["layer"].as_u64().unwrap()); + let before = s.active().unwrap().history.entries(); + assert!(s.execute("layer.new.frame", json!({"x":20,"y":20,"width":40,"height":30,"layer":image.0})).is_err()); + let st = s.active().unwrap(); + assert_eq!(st.doc.layer(first).unwrap().children().unwrap()[0].id, image, "the image stays in its frame"); + assert_eq!(st.history.entries(), before); +} + +#[test] +fn moving_a_frame_past_its_limits_keeps_a_plain_masked_group() { + // An invalid frame would make the saved file fail to load; the clip survives as the mask. + let (mut s, _, _) = session(); + let id = LayerId(s.execute("layer.new.frame", json!({"x":10,"y":10,"width":40,"height":30})).unwrap()["layer"].as_u64().unwrap()); + let doc = (*s.active().unwrap().doc).clone(); + let mut l = doc.layer(id).unwrap().clone(); + crate::vector_cmds::translate_vectors(&doc, &mut l, 700_000.0, 0.0); + assert!(l.frame.is_none()); + assert!(l.vector_mask.is_some()); + let mut l = doc.layer(id).unwrap().clone(); + crate::canvas_geom::transform_layer_geometry(&mut l, &photocraft_geom::Affine::scale(10_000.0), true, 72.0); + assert!(l.frame.is_none()); + assert!(l.vector_mask.is_some()); +} + +#[test] +fn linked_layers_keep_their_links_beside_a_frame_in_psd() { + // The frame's extra PSD records ("Frame Image" group, divider, stroke) used to shift every + // later Link Layers entry onto the wrong record. + let (mut s, a, b) = session(); + s.execute("layer.new.frame", json!({"x":0,"y":0,"width":20,"height":20,"layer":a.0,"stroke":{"color":"#ff0000","width":2}})).unwrap(); + let doc = &mut (*s.active().unwrap().doc).clone(); + let top = Layer::raster("C", doc.pixel_format()); + let c = top.id; + doc.layers.push(top); + for id in [b, c] { + doc.layer_mut(id).unwrap().link_group = Some(5); + } + let bytes = photocraft_io::export(doc, "psd", &Default::default()).unwrap().bytes; + let restored = photocraft_io::import("psd", &bytes).unwrap().document; + let links: Vec<_> = restored.walk().iter().map(|(_, _, l)| (l.name.clone(), l.link_group)).filter(|(_, g)| g.is_some()).collect(); + let names: Vec<_> = links.iter().map(|(n, _)| n.as_str()).collect(); + assert_eq!(names, ["B", "C"], "{links:?}"); + assert_eq!(links[0].1, links[1].1); +} + +#[test] +fn a_pcraft_with_unusable_frame_metadata_still_opens() { + let (mut s, _, _) = session(); + let id = LayerId(s.execute("layer.new.frame", json!({"x":10,"y":10,"width":40,"height":30})).unwrap()["layer"].as_u64().unwrap()); + let mut doc = (*s.active().unwrap().doc).clone(); + doc.layer_mut(id).unwrap().frame.as_mut().unwrap().transform.m[4] = 900_000.0; + let bytes = photocraft_io::export(&doc, "pcraft", &Default::default()).unwrap().bytes; + let restored = photocraft_io::import("pcraft", &bytes).unwrap().document; + let l = restored.layer(id).unwrap(); + assert!(l.frame.is_none()); + assert!(l.vector_mask.is_some(), "the clip survives as the group's vector mask"); +} + +/// A frame at (40,28) 32×32 holding session layer `A` (a 20×20 patch at (4,4)), with `setup` run on +/// the image before it is fitted. Returns the session, the frame and the image ids. +fn fitted(setup: impl FnOnce(&mut Layer)) -> (Session, LayerId, LayerId) { + let (mut s, a, _) = session(); + let frame = LayerId(s.execute("layer.new.frame", json!({"x":40,"y":28,"width":32,"height":32,"layer":a.0})).unwrap()["layer"].as_u64().unwrap()); + let child = s.active().unwrap().doc.layer(frame).unwrap().children().unwrap()[0].id; + s.edit("setup", |doc, _| { + setup(doc.layer_mut(child).unwrap()); + Ok(()) + }) + .unwrap(); + s.execute("layer.frame.fit", json!({"layer":frame.0,"mode":"contentToFrame"})).unwrap(); + (s, frame, child) +} + +fn near(a: Rect, b: Rect) -> bool { + (a.x0 - b.x0).abs() <= 1 && (a.y0 - b.y0).abs() <= 1 && (a.x1 - b.x1).abs() <= 1 && (a.y1 - b.y1).abs() <= 1 +} + +fn image_bounds(s: &Session, child: LayerId) -> Rect { + let LayerContent::Smart(sm) = &s.active().unwrap().doc.layer(child).unwrap().content else { panic!("smart") }; + sm.cache.as_ref().unwrap().content_bounds() +} + +fn patch_mask(bounds: Rect) -> photocraft_doc::LayerMask { + let mut m = photocraft_doc::LayerMask::hide_all(); + m.surface.fill_rect(bounds, &[1.0]); + m +} + +#[test] +fn fitting_content_moves_a_linked_raster_mask_with_the_image() { + let (mut s, frame, child) = fitted(|l| l.mask = Some(patch_mask(Rect::new(4, 4, 24, 24)))); + let image = image_bounds(&s, child); + assert!(image.x0 >= 30, "the image moved into the frame: {image:?}"); + let mask = s.active().unwrap().doc.layer(child).unwrap().mask.as_ref().unwrap().surface.content_bounds(); + assert!(near(mask, image), "the mask {mask:?} follows the image {image:?}"); + assert!(s.undo()); + let l = s.active().unwrap().doc.layer(child).unwrap(); + assert_eq!(l.mask.as_ref().unwrap().surface.content_bounds(), Rect::new(4, 4, 24, 24)); + assert!(s.active().unwrap().doc.layer(frame).is_some()); +} + +#[test] +fn fitting_content_moves_a_linked_vector_mask_with_the_image() { + let outline = photocraft_doc::Path::new(vec![photocraft_doc::Subpath::polygon(&[(4., 4.), (24., 4.), (24., 24.), (4., 24.)])]); + let (mut s, _, child) = fitted(|l| l.vector_mask = Some(photocraft_doc::VectorMask::new(outline.clone()))); + let image = image_bounds(&s, child); + let (x0, y0, x1, y1) = s.active().unwrap().doc.layer(child).unwrap().vector_mask.as_ref().unwrap().path.control_bounds().unwrap(); + assert!(near(Rect::new(x0.round() as i32, y0.round() as i32, x1.round() as i32, y1.round() as i32), image), "{x0} {y0} {x1} {y1} vs {image:?}"); + assert!(s.undo()); + let vm = s.active().unwrap().doc.layer(child).unwrap().vector_mask.clone().unwrap(); + assert_eq!(vm.path, outline); +} + +#[test] +fn fitting_content_moves_the_smart_filter_mask_with_the_image() { + let (mut s, _, child) = fitted(|l| { + if let LayerContent::Smart(sm) = &mut l.content { + sm.filter_mask = Some(patch_mask(Rect::new(4, 4, 24, 24))); + } + }); + let image = image_bounds(&s, child); + let LayerContent::Smart(sm) = &s.active().unwrap().doc.layer(child).unwrap().content else { panic!("smart") }; + let mask = sm.filter_mask.as_ref().unwrap().surface.content_bounds(); + assert!(near(mask, image), "the filter mask {mask:?} follows the image {image:?}"); + assert!(s.undo()); + let LayerContent::Smart(sm) = &s.active().unwrap().doc.layer(child).unwrap().content else { panic!("smart") }; + assert_eq!(sm.filter_mask.as_ref().unwrap().surface.content_bounds(), Rect::new(4, 4, 24, 24)); +} diff --git a/crates/engine/src/cmd/layer_multi_cmds/damage.rs b/crates/engine/src/cmd/layer_multi_cmds/damage.rs index 8440fab75b..a3fb64f032 100644 --- a/crates/engine/src/cmd/layer_multi_cmds/damage.rs +++ b/crates/engine/src/cmd/layer_multi_cmds/damage.rs @@ -156,6 +156,7 @@ fn layer_pixels_cmp(a: &Layer, b: &Layer, surf: SurfaceCmp) -> bool { clipped, mask, vector_mask, + frame, effects, label: _, content, @@ -176,6 +177,7 @@ fn layer_pixels_cmp(a: &Layer, b: &Layer, surf: SurfaceCmp) -> bool { && *fill_opacity == b.fill_opacity && *clipped == b.clipped && *vector_mask == b.vector_mask + && *frame == b.frame && *effects == b.effects && *excluded_channels == b.excluded_channels && *blend_if == b.blend_if diff --git a/crates/engine/src/cmd/smart_cmds.rs b/crates/engine/src/cmd/smart_cmds.rs index 6cb8fccaed..1f7de3d281 100644 --- a/crates/engine/src/cmd/smart_cmds.rs +++ b/crates/engine/src/cmd/smart_cmds.rs @@ -151,9 +151,9 @@ use filters::smart_mut; pub(crate) use filters::{add_smart_filter, filter_mask_paintable, filter_mask_surface, refresh_after_filter_mask_edit}; use filters::{blending_options, delete_filter, edit_filters, move_filter, set_filter_params, set_filter_visible, smart, transfer_filters}; pub(crate) use placing::detach_psd; +pub(crate) use placing::{affine_homography, set_placement, shift_smart, transform_placement}; use placing::{convert, shift_layer, via_copy}; pub use placing::{layer_to_smart, layers_to_smart, placement}; -pub(crate) use placing::{set_placement, shift_smart, transform_placement}; #[cfg(test)] pub(crate) use rendering::DISPLAY_NATIVE_HASH_BYTES; use rendering::refresh_or_fail; diff --git a/crates/engine/src/cmd/smart_cmds/rendering.rs b/crates/engine/src/cmd/smart_cmds/rendering.rs index ab862d5545..abcac8c489 100644 --- a/crates/engine/src/cmd/smart_cmds/rendering.rs +++ b/crates/engine/src/cmd/smart_cmds/rendering.rs @@ -4,7 +4,7 @@ use super::source::{ }; use super::{ Affine, Arc, BlendMode, Document, EngineError, Homography, JobCtx, Layer, LayerContent, LayerId, PixelFormat, Rect, Result, SmartFilter, SmartObject, - SmartSource, Stage, StageKey, Surface, Value, decode_source, other, stack_cache, + SmartSource, Stage, StageKey, Surface, Value, affine_homography, decode_source, other, placement, stack_cache, }; use std::sync::Mutex; @@ -176,11 +176,13 @@ pub(super) fn place(name: &str, bytes: &[u8], doc: &Document, sm: &SmartObject) Some(p) => { let [h0, h1, h2, h3, h4, h5, h6, h7, h8] = *p; let h = Homography([h0 / k, h1 / k, h2, h3 / k, h4 / k, h5, h6 / k, h7 / k, h8]); + crate::transform_cmds::check_budget(img.bounds, &h, "smart object", fmt)?; photocraft_algo::warp::place_source_projective(&img.surface, img.bounds, &h, None)? } None => { let [a, b, c, d, e, f] = sm.transform.m; let t = Affine { m: [a / k, b / k, c / k, d / k, e, f] }; + crate::transform_cmds::check_budget(img.bounds, &affine_homography(&t), "smart object", fmt)?; photocraft_algo::warp::place_source(&img.surface, img.bounds, &t, None)? } }); @@ -191,9 +193,13 @@ pub(super) fn place(name: &str, bytes: &[u8], doc: &Document, sm: &SmartObject) Some(mode) => stack_image(name, bytes, fmt, mode)?, None => source_image(name, bytes, fmt)?, }; + // The placed stage is unclipped: a large enough placement (an image scaled to fill a huge + // frame) would otherwise fill memory before any allocation could fail. + let h = placement(sm); + crate::transform_cmds::check_budget(img.bounds, &h, "smart object", fmt)?; // Through the warp (source space) and the transform in one pass; whole-pixel moves are exact. Ok(match &sm.perspective { - Some(p) => photocraft_algo::warp::place_source_projective(&img.surface, img.bounds, &Homography(*p), sm.warp.as_ref())?, + Some(_) => photocraft_algo::warp::place_source_projective(&img.surface, img.bounds, &h, sm.warp.as_ref())?, None => photocraft_algo::warp::place_source(&img.surface, img.bounds, &sm.transform, sm.warp.as_ref())?, }) } diff --git a/crates/engine/src/cmd/transform_cmds.rs b/crates/engine/src/cmd/transform_cmds.rs index 48aac9eedd..ce305de293 100644 --- a/crates/engine/src/cmd/transform_cmds.rs +++ b/crates/engine/src/cmd/transform_cmds.rs @@ -58,6 +58,9 @@ fn framed_by_selection(doc: &Document, bounds: Rect) -> Rect { /// A group moves all its descendants, so its frame must not clip raster children to the selection. pub(crate) fn whole_layer_bounds(doc: &Document, layer: &Layer) -> Rect { + if let Some(f) = &layer.frame { + return f.bounds(); + } let content = match &layer.content { LayerContent::Group(g) => g.children.iter().map(|c| whole_layer_bounds(doc, c)).fold(Rect::EMPTY, |a, b| a.union(&b)), // A soft shape (Density below 100 % or a Feather) renders past its path, over the whole @@ -485,6 +488,13 @@ fn apply_transform( // The masks (and so a fill's frame) move, but a fill layer's cached render isn't warped: // drop it, the fill re-renders from its model (as `transform_layer_geometry` does). l.fill_cache = None; + if let Some(f) = &mut l.frame { + let a = affine.ok_or_else(|| bad("a frame supports affine transforms; select its image for perspective transforms"))?; + f.transform = a.mul(&f.transform); + if !f.valid() { + return Err(bad("invalid frame transform")); + } + } match &mut l.content { LayerContent::Group(g) => { for c in g.children.iter_mut() { @@ -605,6 +615,25 @@ pub fn split_selected(surf: &Surface, sel: &Surface) -> Result<(Surface, Surface Ok((lifted, rest)) } +/// Moves layer `id` by `affine` (document → document) as `edit.transform` does: its content, linked +/// masks and Smart Filter mask follow, and type, shapes and smart objects re-render. The document +/// selection is left alone. +pub(crate) fn transform_by(doc: &mut Document, id: LayerId, affine: Affine, interp: Interp) -> Result<()> { + let h = crate::smart_cmds::affine_homography(&affine); + let group = group_locks(doc, id); + let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; + // Price the smart object caches before they are taken: the fallback warp below isn't budgeted. + check_layer_budget(None, l, &h)?; + let taken = crate::smart_cmds::take_caches(std::slice::from_mut(l)); + apply_transform(None, group, l, &h, Some(affine), interp, &Interrupt::NONE)?; + let snapshot = doc.clone(); + if let Some(l) = doc.layer_mut(id) { + refresh_text(&snapshot, l); + } + crate::smart_cmds::restore_unrendered(doc, taken, |c| warp_surface(c, c.content_bounds(), &h, interp))?; + Ok(()) +} + pub(crate) fn refresh_text(doc: &Document, l: &mut Layer) { match &mut l.content { LayerContent::Text(t) => crate::type_cmds::refresh(doc, t), diff --git a/crates/engine/src/cmd/vector_cmds.rs b/crates/engine/src/cmd/vector_cmds.rs index f331a30335..c4cb0d9471 100644 --- a/crates/engine/src/cmd/vector_cmds.rs +++ b/crates/engine/src/cmd/vector_cmds.rs @@ -30,7 +30,7 @@ use crate::commands::{CommandSpec, blend_from_str}; use crate::{EngineError, Result, Session}; /// Keys PSD uses for a shape layer's vector data; dropped when a shape is rasterized. -const SHAPE_BLOCKS: [&[u8; 4]; 8] = [b"vmsk", b"vsms", b"vogk", b"vstk", b"vscg", b"SoCo", b"GdFl", b"PtFl"]; +pub(crate) const SHAPE_BLOCKS: [&[u8; 4]; 8] = [b"vmsk", b"vsms", b"vogk", b"vstk", b"vscg", b"SoCo", b"GdFl", b"PtFl"]; pub(crate) fn bad(cmd: &str, msg: impl Into) -> EngineError { EngineError::BadParams { cmd: cmd.into(), msg: msg.into() } diff --git a/crates/engine/src/cmd/vector_cmds/shape.rs b/crates/engine/src/cmd/vector_cmds/shape.rs index 33e1bfe3cf..860b890343 100644 --- a/crates/engine/src/cmd/vector_cmds/shape.rs +++ b/crates/engine/src/cmd/vector_cmds/shape.rs @@ -107,6 +107,14 @@ pub fn preview_shape_stroke(doc: &Document, id: LayerId, params: &Value) -> Resu /// masks, recursing into groups. For the Move tool / `layer.move`. pub fn translate_vectors(doc: &Document, l: &mut Layer, dx: f64, dy: f64) { let a = Affine::translate(dx, dy); + if let Some(f) = &mut l.frame { + f.transform = a.mul(&f.transform); + // Past `Frame::valid`'s bounds it would no longer load; the vector mask, moved below, + // keeps the clip as a plain masked group. + if !f.valid() { + l.frame = None; + } + } if let Some(vm) = l.vector_mask.as_mut() && vm.linked { diff --git a/crates/engine/src/layer_place.rs b/crates/engine/src/layer_place.rs index b5a296cd0c..b129eca883 100644 --- a/crates/engine/src/layer_place.rs +++ b/crates/engine/src/layer_place.rs @@ -30,7 +30,8 @@ pub enum Place { /// parent's children (bottom to top). A missing or stale `anchor` means the top of the stack. pub fn insertion_point(doc: &Document, anchor: Option, layer: &Layer, place: Place) -> (LayerPath, usize) { let root_top = (Vec::new(), doc.layers.len()); - let Some(path) = anchor.and_then(|a| doc.path_of(a)) else { return root_top }; + // Beside a frame's image means beside the frame: the image slot stays whole. + let Some(path) = anchor.and_then(|a| doc.insertion_path(a)) else { return root_top }; // An artboard stays at the top level: beside the anchor's top-level layer. let path = if layer.artboard().is_some() { path.get(..1).map(<[usize]>::to_vec).unwrap_or_default() } else { path }; let (Some((&k, parent)), Some(target)) = (path.split_last(), doc.layer_at(&path)) else { return root_top }; @@ -101,7 +102,8 @@ fn takes_new_layers(target: &Layer, depth: usize, layer: &Layer) -> bool { Some(board) => on_board(board.rect), None => g.expanded, }; - open && layer.artboard().is_none() && depth + subtree_depth(layer) <= MAX_GROUP_DEPTH + // A frame holds its image only (`layer.frame.set`/`setContent`), never new layers. + open && target.frame.is_none() && layer.artboard().is_none() && depth + subtree_depth(layer) <= MAX_GROUP_DEPTH } /// Group nesting inside `layer` itself: 0 for a layer or an empty group, as diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 9cae6dcaa9..9d34baa7e9 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -96,7 +96,7 @@ pub use cmd::fill_cmds; pub use cmd::fill_key_cmds; pub use cmd::float_cmds; pub use cmd::font_library_cmds; -use cmd::frame_cmds; +pub use cmd::frame_cmds; pub use cmd::fx_view_cmds; pub use cmd::fx_visibility_cmds; pub use cmd::gallery_cmds; diff --git a/crates/engine/tests/it/actions_single_history.rs b/crates/engine/tests/it/actions_single_history.rs index 00c54274e5..95c19b016a 100644 --- a/crates/engine/tests/it/actions_single_history.rs +++ b/crates/engine/tests/it/actions_single_history.rs @@ -443,6 +443,7 @@ fn frame_compound_retains_undo_redo_content_and_layer_targets() { for single in [true, false] { let mut s = session(); s.execute("layer.new.layer", json!({"name":"Subject"})).unwrap(); + s.execute("edit.fill", json!({"color":"#ff0000"})).unwrap(); s.execute("actions.setHistory", json!({"singleState":single})).unwrap(); let before = s.active().unwrap().doc.clone(); let target = s.active().unwrap().active_layer; diff --git a/crates/engine/tests/it/background_and_mask_depth.rs b/crates/engine/tests/it/background_and_mask_depth.rs index 1fa400e244..b10ef85aea 100644 --- a/crates/engine/tests/it/background_and_mask_depth.rs +++ b/crates/engine/tests/it/background_and_mask_depth.rs @@ -56,7 +56,7 @@ fn painted(depth: u32) -> Session { } #[test] -fn frame_and_remove_background_masks_match_the_document_depth() { +fn frame_clips_and_remove_background_masks_match_the_document_depth() { for depth in [16, 32] { let want = if depth == 16 { SampleType::U16 } else { SampleType::F32 }; for (cmd, params) in [ @@ -67,7 +67,20 @@ fn frame_and_remove_background_masks_match_the_document_depth() { ] { let mut s = painted(depth); s.execute(cmd, params.clone()).unwrap_or_else(|e| panic!("{cmd} {params}: {e}")); - assert_eq!(mask_sample(&s), want, "{cmd} {params} in a {depth}-bit document"); + if cmd == "layer.removeBackground" { + assert_eq!(mask_sample(&s), want, "{cmd} {params} in a {depth}-bit document"); + } else { + let st = s.active().unwrap(); + let frame = st.doc.layer(st.active_layer.unwrap()).unwrap(); + assert!(frame.frame.as_ref().is_some_and(|f| f.valid())); + assert!(frame.vector_mask.is_some() && frame.mask.is_none(), "frames retain vector geometry at every depth"); + let output = photocraft_compose::flatten_to_surface(&st.doc, st.doc.pixel_format(), None); + assert_eq!(output.format().sample, want); + if cmd == "layer.new.frameFromLayers" { + let image = photocraft_compose::render_layer_in(&st.doc, frame, st.doc.bounds()); + assert!(image.px.iter().any(|p| p[3] > 0.), "framed image remains visible"); + } + } } } } diff --git a/crates/format/src/convert.rs b/crates/format/src/convert.rs index 8ea8c5cc3e..543587ac37 100644 --- a/crates/format/src/convert.rs +++ b/crates/format/src/convert.rs @@ -211,6 +211,7 @@ fn layer_m(l: &Layer, sink: &mut dyn Sink) -> LayerM { feather: m.feather, }), vector_mask: l.vector_mask.clone(), + frame: l.frame.as_deref().cloned(), effects: EffectsM { enabled: l.effects.enabled, items: l.effects.items.clone(), @@ -463,6 +464,9 @@ impl Loader<'_> { /// One layer, given its already converted group children. #[inline(never)] fn layer_with(&mut self, m: &LayerM, children: Vec) -> Result { + // Unusable frame metadata is dropped rather than making the whole document unreadable; + // the group and its vector mask still load. + let frame = m.frame.clone().filter(|f| f.valid() && matches!(m.content, ContentM::Group { .. })); let content = match &m.content { ContentM::Raster { surface } => LayerContent::Raster(self.surface(surface)?), ContentM::Group { expanded, artboard, frame_stroke, .. } => { @@ -569,6 +573,7 @@ impl Loader<'_> { clipped: m.clipped, mask, vector_mask: m.vector_mask.clone(), + frame: frame.map(Box::new), effects: Effects { enabled: m.effects.enabled, items: m.effects.items.clone(), diff --git a/crates/format/src/manifest.rs b/crates/format/src/manifest.rs index 5d725b6bf2..9392c78312 100644 --- a/crates/format/src/manifest.rs +++ b/crates/format/src/manifest.rs @@ -205,6 +205,8 @@ pub struct LayerM { pub effects: EffectsM, pub label: LabelColor, pub content: ContentM, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub frame: Option, /// (4-char key as hex, blob) pub psd_blocks: Vec<(String, Hash)>, pub psd_id: Option, diff --git a/crates/gpu/src/plan/planner.rs b/crates/gpu/src/plan/planner.rs index ef0924640a..5b4f96026e 100644 --- a/crates/gpu/src/plan/planner.rs +++ b/crates/gpu/src/plan/planner.rs @@ -408,6 +408,7 @@ impl<'a> Planner<'a> { let clip_base_adjusts = !visible_clipped.is_empty() && matches!(&layer.content, LayerContent::Group(g) if g.children.iter().any(|c| c.visible && matches!(c.content, LayerContent::Adjustment(_)))); if let LayerContent::Group(g) = &layer.content + && layer.frame.is_none() && layer.blend == BlendMode::PassThrough && layer.fill_opacity >= 1.0 && !has_effects(layer) diff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rs index 89bf250b4e..8984de49c5 100644 --- a/crates/io/src/psd_export.rs +++ b/crates/io/src/psd_export.rs @@ -605,6 +605,14 @@ impl Ex<'_> { if !matches!(l.content, LayerContent::Shape(_)) { self.vector_mask_block(l, &mut raw); } + // The document field owns frame state, including an imported frame's removal. + raw.retain(|(k, _)| k != b"pcFr"); + if let Some(frame) = &l.frame { + match serde_json::to_vec(frame) { + Ok(data) => raw.push((*b"pcFr", data)), + Err(e) => self.warnings.push(format!("frame metadata could not be written: {e}")), + } + } crate::comps_map::artboard_block(&self.guides, l, &mut raw); if let Some((comps, last)) = &self.comps { // Ids are assigned to every layer before emitting. @@ -1011,6 +1019,39 @@ impl Ex<'_> { /// it reports progress and returns `false` to stop early (a cancelled save, #3389). fn emit(&mut self, layers: &[Layer], tick: &mut dyn FnMut() -> bool) { for l in layers { + // Export a frame as ordinary editable groups, a vector clip and a separate border. + // Photoshop's private native-frame metadata is deliberately not fabricated. + let expanded; + let l = if let (Some(frame), Some(children)) = (&l.frame, l.children()) { + let mut clip = Layer::group("Frame Image", children.to_vec()); + clip.blend = photocraft_color::BlendMode::Normal; + clip.mask = l.mask.clone(); + clip.vector_mask = l.vector_mask.clone(); + clip.psd_blocks.push((*b"pcFc", std::sync::Arc::new(vec![1]))); + let cid = self.fresh_id(); + self.layer_ids.insert(clip.id, cid); + let mut outer = l.clone(); + outer.mask = None; + outer.vector_mask = None; + let mut parts = vec![clip]; + if let Some(mut shape) = frame.stroke_shape() { + // Readers that composite pixels see the border too, as for any shape layer. + shape.cache = Some(photocraft_vector::render_shape(&shape, self.fmt, self.canvas)); + let mut border = Layer::new("Frame Stroke", LayerContent::Shape(shape)); + border.psd_blocks.push((*b"pcFs", std::sync::Arc::new(vec![1]))); + let bid = self.fresh_id(); + self.layer_ids.insert(border.id, bid); + parts.push(border); + } + if let Some(target) = outer.children_mut() { + *target = parts; + } + // Emit this prepared group directly, retaining its typed frame for content_blocks. + expanded = outer; + &expanded + } else { + l + }; let extra = self.content_blocks(l); match &l.content { LayerContent::Group(g) => { diff --git a/crates/io/src/psd_export/smart.rs b/crates/io/src/psd_export/smart.rs index f1ac7431b6..3bda3e3240 100644 --- a/crates/io/src/psd_export/smart.rs +++ b/crates/io/src/psd_export/smart.rs @@ -236,7 +236,18 @@ pub(super) fn link_group_resource(layers: &[Layer]) -> Option> { for l in layers { if let LayerContent::Group(g) = &l.content { out.push(None); - walk(&g.children, out); + // `emit` writes a frame as its group around a "Frame Image" group (divider, + // children, record) and an optional "Frame Stroke" shape; none of those is linked. + if let Some(frame) = &l.frame { + out.push(None); + walk(&g.children, out); + out.push(None); + if frame.stroke.is_some() { + out.push(None); + } + } else { + walk(&g.children, out); + } } out.push(l.link_group); } diff --git a/crates/io/src/psd_import.rs b/crates/io/src/psd_import.rs index 993318a386..20e366458e 100644 --- a/crates/io/src/psd_import.rs +++ b/crates/io/src/psd_import.rs @@ -421,6 +421,17 @@ impl Ctx<'_> { } fn apply_common(&mut self, l: &mut Layer, rec: &LayerRecord, blend_override: Option) { + if l.is_group() + && let Some(data) = rec.block(b"pcFr").filter(|b| b.data.len() <= 8 << 20) + { + let end = data.data.iter().rposition(|b| *b != 0).map_or(0, |n| n.saturating_add(1)); + l.frame = data + .data + .get(..end) + .and_then(|bytes| serde_json::from_slice::(bytes).ok()) + .filter(photocraft_doc::Frame::valid) + .map(Box::new); + } l.visible = rec.is_visible(); l.opacity = f32::from(rec.opacity) / 255.0; l.fill_opacity = f32::from(rec.fill_opacity()) / 255.0; @@ -771,6 +782,17 @@ impl Ctx<'_> { l.psd_blocks = preserved_blocks(rec); self.apply_common(&mut l, rec, sd.and_then(|s| s.blend_mode)); self.apply_vector_mask(&mut l, rec); + if l.frame.is_some() { + let clip = + l.children().and_then(|children| children.first()).filter(|child| child.psd_blocks.iter().any(|(k, _)| k == b"pcFc")).cloned(); + if let Some(mut clip) = clip { + if let (Some(target), Some(children)) = (l.children_mut(), clip.children_mut()) { + *target = std::mem::take(children); + } + l.mask = clip.mask; + l.vector_mask = clip.vector_mask; + } + } l } }) @@ -778,18 +800,32 @@ impl Ctx<'_> { } } -/// Sets `Layer::link_group` from resource 1026's per-record ids (`nodes` and `layers` correspond). -fn apply_link_groups(nodes: &[LayerNode], layers: &mut [Layer], ids: &[u16]) { - fn rec(nodes: &[LayerNode], layers: &mut [Layer], ids: &[u16], depth: usize) { +/// Sets `Layer::link_group` from resource 1026's per-record ids (`nodes` and `layers` correspond, +/// except that a frame holds its `pcFc` clip group's children, as `build` adopted them). +fn apply_link_groups(nodes: &[LayerNode], layers: &mut [Layer], records: &[LayerRecord], ids: &[u16]) { + fn rec(nodes: &[LayerNode], layers: &mut [Layer], records: &[LayerRecord], ids: &[u16], depth: usize) { for (n, l) in nodes.iter().zip(layers.iter_mut()) { let index = match n { LayerNode::Layer { index } => *index, LayerNode::Group { index, children, .. } => { + // The frame's children are its clip group's, one level further down. + let clip = match children.first() { + Some(LayerNode::Group { index, children, .. }) + if l.frame.is_some() && records.get(*index).is_some_and(|r| r.block(b"pcFc").is_some()) => + { + Some(children) + } + _ => None, + }; + let (children, depth) = match clip { + Some(c) => (c, depth + 1), + None => (children, depth), + }; // Matches the importer's nesting cap: deeper children were not imported. if depth < photocraft_doc::MAX_GROUP_DEPTH && let LayerContent::Group(g) = &mut l.content { - rec(children, &mut g.children, ids, depth + 1); + rec(children, &mut g.children, records, ids, depth + 1); } *index } @@ -797,7 +833,7 @@ fn apply_link_groups(nodes: &[LayerNode], layers: &mut [Layer], ids: &[u16]) { l.link_group = ids.get(index).copied().filter(|&g| g != 0).map(u64::from); } } - rec(nodes, layers, ids, 0); + rec(nodes, layers, records, ids, 0); } /// Rejects a file whose groups nest deeper than the document model's cap, with the actionable @@ -1428,7 +1464,7 @@ fn import_layered(import: DecodedImport<'_>, doc: &mut Document, cx: &mut Ctx<'_ if let Some(Ok(photocraft_psd::resources::ResourceData::LayerGroupInfo(groups))) = file.resources.iter().find(|r| r.id == ids::LAYER_GROUP_INFO).and_then(photocraft_psd::resources::ImageResource::parsed) { - apply_link_groups(&tree, &mut doc.layers, &groups); + apply_link_groups(&tree, &mut doc.layers, file.layers(), &groups); } let Some((n, plane)) = sizes else { return }; let Some(Ok(all)) = merged else { return }; diff --git a/crates/io/tests/it/roundtrip.rs b/crates/io/tests/it/roundtrip.rs index 155429eba2..f418c900da 100644 --- a/crates/io/tests/it/roundtrip.rs +++ b/crates/io/tests/it/roundtrip.rs @@ -608,3 +608,69 @@ fn psd_16bit_layers_with_compatibility_section_open_visible() { assert!(imported.layers[0].surface().unwrap().tile_count() > 0); assert!(imported.layers[1].surface().unwrap().tile_count() > 0); } + +fn framed(children: Vec, stroke: Option) -> photocraft_doc::Layer { + let mut g = photocraft_doc::Layer::group("frame", children); + g.frame = Some(Box::new(photocraft_doc::Frame { + path: photocraft_vector::shapes::rect(0.0, 0.0, 1.0, 1.0), + transform: photocraft_geom::Affine { m: [6.0, 0.0, 0.0, 6.0, 1.0, 1.0] }, + stroke, + })); + g +} + +#[test] +fn frame_children_keep_their_links() { + use photocraft_doc::{Document, Layer, LayerContent, Size}; + let mut d = Document::new("l", Size::new(8, 8), ColorMode::Rgb, SampleType::U8); + let fmt = d.pixel_format(); + let mut a = Layer::raster("a", fmt); + a.link_group = Some(5); + let b = Layer::raster("b", fmt); + let mut outside = Layer::raster("outside", fmt); + outside.link_group = Some(5); + d.layers = vec![framed(vec![a, b], Some(photocraft_doc::ShapeStroke::default())), outside]; + let back = roundtrip(&d); + let LayerContent::Group(g) = &back.layers[0].content else { panic!("frame is not a group") }; + let names: Vec<_> = g.children.iter().map(|l| (l.name.as_str(), l.link_group)).collect(); + assert_eq!(names, [("a", Some(5)), ("b", None)]); + assert_eq!(back.layers[0].link_group, None); + assert_eq!(back.layers[1].link_group, Some(5)); +} + +#[test] +fn frame_stroke_exports_its_pixels() { + use photocraft_doc::{Document, Layer, Size}; + let mut d = Document::new("s", Size::new(8, 8), ColorMode::Rgb, SampleType::U8); + let fmt = d.pixel_format(); + let stroke = photocraft_doc::ShapeStroke { width: 2.0, ..Default::default() }; + d.layers = vec![framed(vec![Layer::raster("a", fmt)], Some(stroke))]; + let r = export(&d, "x.psd", &ExportOptions::default()).unwrap(); + let f = PsdFile::from_bytes(&r.bytes).unwrap(); + let rec = f.layers().iter().find(|r| r.name() == "Frame Stroke").expect("stroke record"); + assert!(!rec.rect.is_empty(), "the border has no pixels: {:?}", rec.rect); +} + +/// Invalidating an imported frame must not restore it from its preserved PSD metadata. +#[test] +fn an_invalidated_frame_stays_removed_after_psd_roundtrip() { + use photocraft_doc::{Document, Layer, Size}; + + for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { + let mut doc = Document::new("frame", Size::new(8, 8), ColorMode::Rgb, depth); + doc.layers = vec![framed(vec![Layer::raster("image", doc.pixel_format())], None)]; + let mut imported = roundtrip(&doc); + let frame = &mut imported.layers[0]; + assert!(frame.frame.is_some(), "{depth:?}: the frame must first survive import"); + assert!(frame.psd_blocks.iter().any(|(key, _)| key == b"pcFr")); + frame.frame = None; + + let exported = export(&imported, "invalidated.psd", &ExportOptions::default()).unwrap(); + let psd = PsdFile::from_bytes(&exported.bytes).unwrap(); + assert!(psd.layers().iter().all(|layer| layer.block(b"pcFr").is_none()), "{depth:?}: stale frame metadata was exported"); + let reopened = import("invalidated.psd", &exported.bytes).unwrap().document; + assert!(reopened.layers[0].frame.is_none(), "{depth:?}: the obsolete frame was restored"); + assert!(reopened.layers[0].is_group()); + assert_eq!(reopened.layers[0].children().unwrap().len(), 1); + } +} diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 1b99f8647c..41af7fe81c 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -99,6 +99,8 @@ impl PhotocraftApp { ppp: 1.0, drop_canvas_rect: None, tab_strip: None, + frame_tool_ctx: None, + frame_preview: None, drop_places: Default::default(), view_docs: Vec::new(), path_document: None, diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 4262dc0805..9ebeeede52 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1211,6 +1211,15 @@ fn handle_canvas_tool_clicks( } } } + // A Frame drag uses a temporary Free Transform for its image/both target. That owns + // the release, so the generic tool-click gate can be false even for a double click. + if tool == Tool::Frame + && response.contains_pointer() + && ctx.input(|i| i.pointer.button_double_clicked(PointerButton::Primary)) + && let Some(p) = response.interact_pointer_pos().or_else(|| ctx.pointer_hover_pos()) + { + crate::frame_tool::double_click(app, xf.to_doc(p)); + } // Magnetic Lasso: between clicks the border follows the pointer with the button up. if tool == Tool::MagneticLasso && app.ui.magnetic.active() && !(buttons.started || buttons.dragged || buttons.stopped) && response.hovered() { let moves: Vec = ui.input(|i| i.events.iter().filter_map(|e| if let egui::Event::PointerMoved(p) = e { Some(*p) } else { None }).collect()); @@ -1349,6 +1358,7 @@ fn paint_primary_overlays(app: &mut PhotocraftApp, ui: &mut egui::Ui, view: &mut 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::frame_tool::task_bar(app, ui, xf); crate::artboard_tool::draw_overlay(app, painter, xf); draw_canvas_tool_cursor(app, ui, input, resizing); @@ -1414,6 +1424,8 @@ fn draw_canvas_tool_cursor(app: &mut PhotocraftApp, ui: &mut egui::Ui, input: &C crate::type_transform::cursor(app, ctx, xf, p, mods) }) { ui.ctx().set_cursor_icon(c); + } else if let Some(c) = response.hover_pos().filter(|_| tool == Tool::Frame).and_then(|p| crate::frame_tool::cursor(app, xf.to_doc(p))) { + ui.ctx().set_cursor_icon(c); } else if let Some(c) = response.hover_pos().filter(|_| tool == Tool::Artboard).and_then(|p| crate::artboard_tool::cursor(app, xf, xf.to_doc(p))) { ui.ctx().set_cursor_icon(c); } else if let Some((p, c)) = response.hover_pos().filter(|_| tool == Tool::Crop).and_then(|p| Some((p, crate::crop_ui::cursor(app, xf.to_doc(p))?))) { @@ -1798,6 +1810,11 @@ fn update_polygon_camera(app: &mut PhotocraftApp, ctx: &egui::Context, (idx, pri pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: Rect, mut view: View, primary: bool) -> View { let ctx = ui.ctx().clone(); + // The Frame tool starts transforms from pointer events, which carry no context; the options + // bar that also records it can be hidden. + if primary { + app.frame_tool_ctx = Some(ctx.clone()); + } // The camera as the app holds it before this frame's input. The canvas works on its own copy // (`view`) and writes it back at the end; a tool that moves the camera itself meanwhile (the // Crop tool's default mode pans and turns the view with the image, `crop_mode`) must not be diff --git a/crates/ui-egui/src/canvas/display.rs b/crates/ui-egui/src/canvas/display.rs index d1d8e219e1..a171bd17bf 100644 --- a/crates/ui-egui/src/canvas/display.rs +++ b/crates/ui-egui/src/canvas/display.rs @@ -107,6 +107,9 @@ pub(crate) const GPU_OUTPUT: u32 = u32::MAX; /// The document to render: the committed one, or a clone with the live adjustment preview applied. pub(crate) fn display_doc(app: &mut PhotocraftApp, idx: usize) -> (std::sync::Arc, u64) { + if let Some(shown) = crate::frame_tool::display_doc(app, idx) { + return shown; + } if let Some(shown) = crate::type_panels_ui::color_picker::display_doc(app, idx) { return shown; } diff --git a/crates/ui-egui/src/canvas/tool_input.rs b/crates/ui-egui/src/canvas/tool_input.rs index 671b507723..6db5aace3e 100644 --- a/crates/ui-egui/src/canvas/tool_input.rs +++ b/crates/ui-egui/src/canvas/tool_input.rs @@ -124,6 +124,10 @@ fn filter_event_before_tool(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui:: // can land outside the corner's grab area and turn a corner drag into a move of the whole box. let transform_ev = if matches!(raw, ToolEvent::Down { .. }) { raw } else { ev }; if crate::transform_tool::pointer(app, transform_ev, mods) { + if matches!(transform_ev, ToolEvent::Up { .. }) && app.ui.frame_tool.auto_transform { + app.ui.frame_tool.auto_transform = false; + crate::transform_tool::commit(app); + } return None; } if crate::distort_ui::pointer(app, ev, mods) { diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index e979d3d829..0b557492ca 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -170,6 +170,7 @@ fn run_waiting(app: &mut PhotocraftApp, wait: bool, run: impl FnOnce(&mut Photoc const SHELL_DIALOG: &str = "shell"; pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest) -> Outcome { + app.frame_tool_ctx = Some(ctx.clone()); let saved = app.session.authorize; if let Some(gate) = app.services.automation_authorize { app.session.authorize = Some(gate); diff --git a/crates/ui-egui/src/control/dispatch.rs b/crates/ui-egui/src/control/dispatch.rs index 262cd9d639..3e276935cf 100644 --- a/crates/ui-egui/src/control/dispatch.rs +++ b/crates/ui-egui/src/control/dispatch.rs @@ -266,6 +266,9 @@ impl UiSet { /// Apply (nothing but the final `brushSize` command can fail). fn apply(mut self, app: &mut PhotocraftApp, ctx: &egui::Context, p: &Value) -> std::result::Result { + // All fields are validated. Select the requested frame thumbnail before applying the + // remaining view state, so a denied selection leaves the other fields intact. + self.tools.select_frame_target(app)?; self.tools.apply(app); self.crop.apply(app); self.panels.apply_options(app); @@ -296,6 +299,9 @@ fn theme_param(p: &Value) -> std::result::Result struct ToolSet { gradient_blend: Option, shape_stroke: Option>, + frame_shape: Option, + frame_sides: Option, + frame_target: Option, tool: Option, gradient_classic: Option, stroke_trace: Option<&'static str>, @@ -314,6 +320,9 @@ impl ToolSet { Ok(Self { gradient_blend: gradient_blend_param(p)?, shape_stroke: shape_stroke_param(app, p)?, + frame_shape: frame_shape_param(p)?, + frame_sides: frame_sides_param(p)?, + frame_target: frame_target_param(p)?, tool: tool_param(p)?, gradient_classic: bool_field(p, "gradientClassic")?, stroke_trace: stroke_trace_param(p)?, @@ -331,7 +340,25 @@ impl ToolSet { }) } + fn select_frame_target(&self, app: &mut PhotocraftApp) -> std::result::Result<(), String> { + let Some(target) = self.frame_target else { return Ok(()) }; + if let Some(id) = crate::frame_tool::selected(app).map(|l| l.id) { + crate::frame_tool::select_result(app, id, target)?; + } else { + app.ui.frame_tool.target = target; + app.ui.frame_tool.selected = None; + } + Ok(()) + } + fn apply(self, app: &mut PhotocraftApp) { + if let Some(shape) = &self.frame_shape { + app.ui.frame_tool.ellipse = shape == "ellipse"; + app.ui.frame_tool.shape.clone_from(shape); + } + if let Some(sides) = self.frame_sides { + app.ui.frame_tool.sides = sides; + } if let Some(stroke) = &self.shape_stroke { if let Some(stroke) = stroke { app.ui.tool_options.stroke_width = stroke.width; @@ -390,6 +417,32 @@ impl ToolSet { } } +fn frame_shape_param(p: &Value) -> std::result::Result, String> { + p.get("frameShape") + .filter(|v| !v.is_null()) + .map(|v| { + v.as_str() + .filter(|s| ["rectangle", "ellipse", "triangle", "polygon", "custom"].contains(s)) + .map(str::to_string) + .ok_or_else(|| "frameShape must be rectangle, ellipse, triangle, polygon or custom".to_string()) + }) + .transpose() +} + +fn frame_sides_param(p: &Value) -> std::result::Result, String> { + match uint_field(p, "frameSides")? { + Some(n) if !(3..=100).contains(&n) => Err("frameSides must be 3..=100".into()), + n => Ok(n.map(|n| n as u32)), + } +} + +fn frame_target_param(p: &Value) -> std::result::Result, String> { + p.get("frameTarget") + .filter(|v| !v.is_null()) + .map(|v| serde_json::from_value::(v.clone()).map_err(|_| "frameTarget must be frame, content or both".to_string())) + .transpose() +} + /// The Pen tools' options bar (#1397): Path or Shape mode. fn pen_mode_param(p: &Value) -> std::result::Result, String> { let Some(v) = p.get("penMode") else { return Ok(None) }; diff --git a/crates/ui-egui/src/control/params.rs b/crates/ui-egui/src/control/params.rs index d294cd06fb..9e5cae2308 100644 --- a/crates/ui-egui/src/control/params.rs +++ b/crates/ui-egui/src/control/params.rs @@ -4,7 +4,7 @@ use super::{Outcome, PhotocraftApp, Value, json}; /// field's value is validated before the first one is applied, so a typo, an unknown field, a /// bad value or a bad nested key can't reply with success while nothing — or only half of it — /// changed (#412). -pub const UI_SET_FIELDS: [&str; 45] = [ +pub const UI_SET_FIELDS: [&str; 48] = [ "updatesOpen", "tool", "strokeTrace", @@ -44,6 +44,9 @@ pub const UI_SET_FIELDS: [&str; 45] = [ "penMode", "penPathOp", "shapeStroke", + "frameShape", + "frameSides", + "frameTarget", "camTransformOnDrop", "tileGrid", "layerFilter", diff --git a/crates/ui-egui/src/file_open.rs b/crates/ui-egui/src/file_open.rs index 814fc4e114..ed5c3a642e 100644 --- a/crates/ui-egui/src/file_open.rs +++ b/crates/ui-egui/src/file_open.rs @@ -35,6 +35,8 @@ pub enum DropTarget { /// A file dropped on the canvas, waiting its turn to be placed. pub(crate) enum DropPlace { + /// Destination captured when the file is dropped, before a later pointer move. + At { source: Box, frame: Option }, /// Dropped onto the window (desktop): read from its path, or through egui. File(egui::DroppedFileHandle), /// Read by the shell itself (the browser reads dropped files asynchronously): its name and @@ -256,6 +258,7 @@ impl PhotocraftApp { /// absolute path, read in bounded reads (#375) rather than egui's whole-file read. pub fn open_dropped(&mut self, ctx: &egui::Context, files: Vec, at: Option) { let target = self.drop_target(ctx, at); + let frame = at.and_then(|at| crate::canvas::ViewXform::active(self).map(|xf| xf.to_doc(at))).and_then(|p| crate::frame_tool::frame_at(self, p)); let mut slot = match target { DropTarget::Tabs(slot) => Some(slot), DropTarget::Canvas | DropTarget::Elsewhere => None, @@ -269,7 +272,7 @@ impl PhotocraftApp { for f in files { let name = dropped_name(&f); if target == DropTarget::Canvas && !crate::preset_files_ui::is_preset_file(&name) { - self.drop_places.push_back(DropPlace::File(f)); + self.drop_places.push_back(DropPlace::At { source: Box::new(DropPlace::File(f)), frame }); continue; } match self.open_dropped_file(&f, &name, slot) { @@ -337,22 +340,42 @@ impl PhotocraftApp { pub(crate) fn place_next_dropped(&mut self, ctx: &egui::Context) { while self.ui.transform.is_none() { let Some(next) = self.drop_places.pop_front() else { return }; + let (next, frame) = match next { + DropPlace::At { source, frame } => (*source, Some(frame)), + next => (next, None), + }; + let params = frame.map_or_else( + || serde_json::json!({}), + |frame| serde_json::json!({"frame": frame.map_or(serde_json::Value::Bool(false), |id| serde_json::json!(id.0))}), + ); let (name, placed) = match next { - DropPlace::File(f) if f.path().is_absolute() => { - (dropped_name(&f), path_text(f.path(), false).and_then(|path| self.run("file.placeEmbedded", serde_json::json!({"path": path})))) + DropPlace::At { .. } => { + self.failed(tl!("Invalid nested file drop").into()); + continue; } + DropPlace::File(f) if f.path().is_absolute() => ( + dropped_name(&f), + path_text(f.path(), false).and_then(|path| { + let mut p = params.clone(); + p["path"] = serde_json::json!(path); + self.run("file.placeEmbedded", p) + }), + ), DropPlace::File(f) => { let name = dropped_name(&f); - let placed = crate::read_dropped(&*f).and_then(|bytes| self.place_bytes(&name, bytes, None)); + let placed = crate::read_dropped(&*f).and_then(|bytes| self.place_bytes_with(&name, bytes, None, ¶ms)); (name, placed) } DropPlace::Bytes(name, bytes) => { - let placed = self.place_bytes(&name, bytes, None); + let placed = self.place_bytes_with(&name, bytes, None, ¶ms); (name, placed) } }; match placed { - Ok(_) => { + Ok(result) => { + if result.get("frame").and_then(serde_json::Value::as_u64).is_some() { + continue; + } if let Err(e) = crate::transform_tool::begin_placed(self, ctx) { self.ui.status = e; } @@ -365,7 +388,10 @@ impl PhotocraftApp { /// Place a file's bytes as a smart object layer (File › Place; `linked`: Place Linked, to that /// path), for files that weren't read from a path the command can read. pub(crate) fn place_bytes(&mut self, name: &str, bytes: Vec, linked: Option) -> Result { - let r = photocraft_engine::file_cmds::place_bytes(&mut self.session, name, bytes, linked, &serde_json::json!({})).map_err(|e| e.to_string()); + self.place_bytes_with(name, bytes, linked, &serde_json::json!({})) + } + fn place_bytes_with(&mut self, name: &str, bytes: Vec, linked: Option, params: &serde_json::Value) -> Result { + let r = photocraft_engine::file_cmds::place_bytes(&mut self.session, name, bytes, linked, params).map_err(|e| e.to_string()); self.sync_views(); r } diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 2a1f92c039..40fc3691de 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4278,3 +4278,21 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Learn Učit se No recent files Žádné nedávné soubory Website Web + +# Frame Tool and other branch translations. + A frame supports affine transforms; select its image for perspective transforms Rámeček podporuje afinní transformace; pro perspektivní transformace vyberte jeho obrázek + A frame supports affine transforms; select its image to warp it Rámeček podporuje afinní transformace; pro pokřivení vyberte jeho obrázek + Convert to Frame… Převést na rámeček… + Create a new custom frame Vytvořit nový vlastní rámeček + Create a new polygonal frame Vytvořit nový mnohoúhelníkový rámeček + Create a new triangular frame Vytvořit nový trojúhelníkový rámeček + Fit Content to Frame Přizpůsobit obsah rámečku + Fit Frame to Content Přizpůsobit rámeček obsahu + Frame coordinates must be finite and within 600000 pixels Souřadnice rámečku musí být konečné a v rozsahu 600000 pixelů + Import Image… Importovat obrázek… + Invalid frame transform Neplatná transformace rámečku + Invalid nested file drop Neplatné vnořené přetažení souboru + New Frame Nový rámeček + Replace Image… Nahradit obrázek… + The frame is locked Rámeček je zamčený + The frame is unavailable Rámeček není dostupný diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 7250a46a5a..280558ff25 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -3562,3 +3562,23 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Learn Lernen No recent files Keine zuletzt verwendeten Dateien Website Website + +# Frame Tool and other branch translations. + A frame supports affine transforms; select its image for perspective transforms Ein Rahmen unterstützt affine Transformationen; für perspektivische Transformationen sein Bild auswählen + A frame supports affine transforms; select its image to warp it Ein Rahmen unterstützt affine Transformationen; zum Verformen sein Bild auswählen + Convert to Frame… In Rahmen konvertieren… + Create a new custom frame Neuen benutzerdefinierten Rahmen erstellen + Create a new polygonal frame Neuen polygonalen Rahmen erstellen + Create a new triangular frame Neuen dreieckigen Rahmen erstellen + Fit Content to Frame Inhalt an Rahmen anpassen + Fit Frame to Content Rahmen an Inhalt anpassen + Frame coordinates must be finite and within 600000 pixels Rahmenkoordinaten müssen endlich sein und innerhalb von 600000 Pixeln liegen + Import Image… Bild importieren… + Invalid frame transform Ungültige Rahmentransformation + Invalid nested file drop Ungültiges verschachteltes Ablegen einer Datei + New Frame Neuer Rahmen + Replace Image… Bild ersetzen… + The frame is locked Der Rahmen ist gesperrt + The frame is unavailable Der Rahmen ist nicht verfügbar + X X + Y Y diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 6d80fd69ef..cf1acf1474 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -4232,3 +4232,23 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded New file Νέο αρχείο Learn Εκμάθηση Website Ιστότοπος + +# Frame Tool and other branch translations. + A frame supports affine transforms; select its image for perspective transforms Το πλαίσιο υποστηρίζει αφινικούς μετασχηματισμούς· επιλέξτε την εικόνα του για μετασχηματισμούς προοπτικής + A frame supports affine transforms; select its image to warp it Το πλαίσιο υποστηρίζει αφινικούς μετασχηματισμούς· επιλέξτε την εικόνα του για στρέβλωση + Convert to Frame… Μετατροπή σε πλαίσιο… + Create a new custom frame Δημιουργία νέου προσαρμοσμένου πλαισίου + Create a new polygonal frame Δημιουργία νέου πολυγωνικού πλαισίου + Create a new triangular frame Δημιουργία νέου τριγωνικού πλαισίου + Fit Content to Frame Προσαρμογή περιεχομένου στο πλαίσιο + Fit Frame to Content Προσαρμογή πλαισίου στο περιεχόμενο + Frame coordinates must be finite and within 600000 pixels Οι συντεταγμένες του πλαισίου πρέπει να είναι πεπερασμένες και εντός 600000 pixel + Import Image… Εισαγωγή εικόνας… + Invalid frame transform Μη έγκυρος μετασχηματισμός πλαισίου + Invalid nested file drop Μη έγκυρη ένθετη απόθεση αρχείου + New Frame Νέο πλαίσιο + Replace Image… Αντικατάσταση εικόνας… + The frame is locked Το πλαίσιο είναι κλειδωμένο + The frame is unavailable Το πλαίσιο δεν είναι διαθέσιμο + X X + Y Y diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 616df65bc8..186e679e30 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -4443,3 +4443,21 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded New file Nuevo archivo Learn Aprender Website Sitio web + +# Frame Tool and other branch translations. + A frame supports affine transforms; select its image for perspective transforms Un marco admite transformaciones afines; seleccione su imagen para transformaciones de perspectiva + A frame supports affine transforms; select its image to warp it Un marco admite transformaciones afines; seleccione su imagen para deformarla + Convert to Frame… Convertir en marco… + Create a new custom frame Crear un nuevo marco personalizado + Create a new polygonal frame Crear un nuevo marco poligonal + Create a new triangular frame Crear un nuevo marco triangular + Fit Content to Frame Ajustar contenido al marco + Fit Frame to Content Ajustar marco al contenido + Frame coordinates must be finite and within 600000 pixels Las coordenadas del marco deben ser finitas y estar dentro de 600000 píxeles + Import Image… Importar imagen… + Invalid frame transform Transformación de marco no válida + Invalid nested file drop Soltado de archivo anidado no válido + New Frame Nuevo marco + Replace Image… Reemplazar imagen… + The frame is locked El marco está bloqueado + The frame is unavailable El marco no está disponible diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index ef992054db..7eaaf6b3cf 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -4566,3 +4566,21 @@ shape Appearance Apparence New file Nouveau fichier Learn Apprendre Website Site web + +# Frame Tool and other branch translations. + A frame supports affine transforms; select its image for perspective transforms Un cadre accepte les transformations affines ; sélectionnez son image pour les transformations de perspective + A frame supports affine transforms; select its image to warp it Un cadre accepte les transformations affines ; sélectionnez son image pour la déformer + Convert to Frame… Convertir en cadre… + Create a new custom frame Créer un cadre personnalisé + Create a new polygonal frame Créer un cadre polygonal + Create a new triangular frame Créer un cadre triangulaire + Fit Content to Frame Adapter le contenu au cadre + Fit Frame to Content Adapter le cadre au contenu + Frame coordinates must be finite and within 600000 pixels Les coordonnées du cadre doivent être finies et comprises dans une limite de 600000 pixels + Import Image… Importer une image… + Invalid frame transform Transformation du cadre non valide + Invalid nested file drop Dépôt de fichier imbriqué non valide + New Frame Nouveau cadre + Replace Image… Remplacer l’image… + The frame is locked Le cadre est verrouillé + The frame is unavailable Le cadre n’est pas disponible diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 0acf7e4bf1..6274ae7272 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -590,6 +590,37 @@ cameraRaw Yellow पीला Invalid numeric entry. An integer between {min}% and {max}% is required. Previous value was inserted. अमान्य संख्यात्मक प्रविष्टि। {min}% और {max}% के बीच एक पूर्णांक आवश्यक है। पिछला मान डाला गया। Edit Brush… ब्रश संपादित करें… +# Frame Tool and other branch translations. + A frame supports affine transforms; select its image for perspective transforms फ़्रेम एफ़ाइन रूपांतरणों का समर्थन करता है; परिप्रेक्ष्य रूपांतरणों के लिए उसकी छवि चुनें + A frame supports affine transforms; select its image to warp it फ़्रेम एफ़ाइन रूपांतरणों का समर्थन करता है; वार्प करने के लिए उसकी छवि चुनें + Convert to Frame… फ़्रेम में बदलें… + Create a new custom frame नया कस्टम फ़्रेम बनाएँ + Create a new polygonal frame नया बहुभुजीय फ़्रेम बनाएँ + Create a new triangular frame नया त्रिकोणीय फ़्रेम बनाएँ + Fit Content to Frame सामग्री को फ़्रेम में फ़िट करें + Fit Frame to Content फ़्रेम को सामग्री के अनुसार फ़िट करें + Frame coordinates must be finite and within 600000 pixels फ़्रेम के निर्देशांक परिमित और 600000 पिक्सेल की सीमा में होने चाहिए + Import Image… छवि आयात करें… + Invalid frame transform अमान्य फ़्रेम रूपांतरण + Invalid nested file drop अमान्य नेस्टेड फ़ाइल ड्रॉप + New Frame नया फ़्रेम + Replace Image… छवि बदलें… + The frame is locked फ़्रेम लॉक है + The frame is unavailable फ़्रेम उपलब्ध नहीं है + Both दोनों + Center केंद्र + Create a new elliptical frame नया अंडाकार फ़्रेम बनाएँ + Create a new rectangular frame नया आयताकार फ़्रेम बनाएँ + Frame फ़्रेम + H H + Inside अंदर + Outside बाहर + Sides: भुजाएँ: + Stroke स्ट्रोक + W W + X X + Y Y + # Actions panel: loading several action files at once {message} ({note}) {message} ({note}) @plural {n} action|{n} actions {n} एक्शन|{n} एक्शन diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 71d6f854d6..f830df374e 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -4450,3 +4450,21 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded New file Új fájl Learn Tanulás Website Weboldal + +# Frame Tool and other branch translations. + A frame supports affine transforms; select its image for perspective transforms A keret affin transzformációkat támogat; perspektivikus transzformációhoz válassza ki a képét + A frame supports affine transforms; select its image to warp it A keret affin transzformációkat támogat; a hajlításhoz válassza ki a képét + Convert to Frame… Átalakítás keretté… + Create a new custom frame Új egyéni keret létrehozása + Create a new polygonal frame Új sokszögű keret létrehozása + Create a new triangular frame Új háromszögű keret létrehozása + Fit Content to Frame Tartalom igazítása a kerethez + Fit Frame to Content Keret igazítása a tartalomhoz + Frame coordinates must be finite and within 600000 pixels A keret koordinátáinak végesnek és 600000 képponton belülinek kell lenniük + Import Image… Kép importálása… + Invalid frame transform Érvénytelen kerettranszformáció + Invalid nested file drop Érvénytelen beágyazott fájlejtés + New Frame Új keret + Replace Image… Kép cseréje… + The frame is locked A keret zárolva van + The frame is unavailable A keret nem érhető el diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 3b95878dd9..75c3f972c9 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -3555,3 +3555,22 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Learn Pelajari No recent files Tidak ada file terbaru Website Situs web + +# Frame Tool and other branch translations. + A frame supports affine transforms; select its image for perspective transforms Bingkai mendukung transformasi afin; pilih gambarnya untuk transformasi perspektif + A frame supports affine transforms; select its image to warp it Bingkai mendukung transformasi afin; pilih gambarnya untuk dilengkungkan + Convert to Frame… Konversi ke Bingkai… + Create a new custom frame Buat bingkai kustom baru + Create a new polygonal frame Buat bingkai poligon baru + Create a new triangular frame Buat bingkai segitiga baru + Fit Content to Frame Sesuaikan Konten ke Bingkai + Fit Frame to Content Sesuaikan Bingkai ke Konten + Frame coordinates must be finite and within 600000 pixels Koordinat bingkai harus berhingga dan berada dalam batas 600000 piksel + Import Image… Impor Gambar… + Invalid frame transform Transformasi bingkai tidak valid + Invalid nested file drop Penjatuhan berkas bersarang tidak valid + New Frame Bingkai Baru + Replace Image… Ganti Gambar… + The frame is locked Bingkai terkunci + The frame is unavailable Bingkai tidak tersedia + Frame Bingkai diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index b37de52c64..931fd6240f 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4642,3 +4642,21 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded New file Nuovo file Learn Impara Website Sito web + +# Frame Tool and other branch translations. + A frame supports affine transforms; select its image for perspective transforms Una cornice supporta trasformazioni affini; selezionate la sua immagine per le trasformazioni prospettiche + A frame supports affine transforms; select its image to warp it Una cornice supporta trasformazioni affini; selezionate la sua immagine per alterarla + Convert to Frame… Converti in cornice… + Create a new custom frame Crea una nuova cornice personalizzata + Create a new polygonal frame Crea una nuova cornice poligonale + Create a new triangular frame Crea una nuova cornice triangolare + Fit Content to Frame Adatta contenuto alla cornice + Fit Frame to Content Adatta cornice al contenuto + Frame coordinates must be finite and within 600000 pixels Le coordinate della cornice devono essere finite e comprese entro 600000 pixel + Import Image… Importa immagine… + Invalid frame transform Trasformazione della cornice non valida + Invalid nested file drop Rilascio di file annidato non valido + New Frame Nuova cornice + Replace Image… Sostituisci immagine… + The frame is locked La cornice è bloccata + The frame is unavailable La cornice non è disponibile diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 5b1a2fbbad..8849d49db7 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -4211,3 +4211,21 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Learn 学ぶ No recent files 最近使ったファイルはありません Website Web サイト + +# Frame Tool and other branch translations. + A frame supports affine transforms; select its image for perspective transforms フレームはアフィン変換に対応しています。遠近法変換を行うにはフレーム内の画像を選択してください + A frame supports affine transforms; select its image to warp it フレームはアフィン変換に対応しています。ワープするにはフレーム内の画像を選択してください + Convert to Frame… フレームに変換… + Create a new custom frame 新しいカスタムフレームを作成 + Create a new polygonal frame 新しい多角形フレームを作成 + Create a new triangular frame 新しい三角形フレームを作成 + Fit Content to Frame 内容をフレームに合わせる + Fit Frame to Content フレームを内容に合わせる + Frame coordinates must be finite and within 600000 pixels フレームの座標は有限値で、600000 ピクセル以内である必要があります + Import Image… 画像を読み込み… + Invalid frame transform フレームの変形が無効です + Invalid nested file drop 入れ子のファイルドロップは無効です + New Frame 新規フレーム + Replace Image… 画像を置き換え… + The frame is locked フレームはロックされています + The frame is unavailable フレームを利用できません diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 674ece97cd..83c9790573 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3753,3 +3753,23 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Learn 학습 No recent files 최근 파일 없음 Website 웹사이트 + +# Frame Tool and other branch translations. + A frame supports affine transforms; select its image for perspective transforms 프레임은 아핀 변환을 지원합니다. 원근 변환을 하려면 프레임의 이미지를 선택하세요 + A frame supports affine transforms; select its image to warp it 프레임은 아핀 변환을 지원합니다. 뒤틀려면 프레임의 이미지를 선택하세요 + Convert to Frame… 프레임으로 변환… + Create a new custom frame 새 사용자 정의 프레임 만들기 + Create a new polygonal frame 새 다각형 프레임 만들기 + Create a new triangular frame 새 삼각형 프레임 만들기 + Fit Content to Frame 내용을 프레임에 맞추기 + Fit Frame to Content 프레임을 내용에 맞추기 + Frame coordinates must be finite and within 600000 pixels 프레임 좌표는 유한한 값이며 600000픽셀 이내여야 합니다 + Import Image… 이미지 가져오기… + Invalid frame transform 잘못된 프레임 변환 + Invalid nested file drop 잘못된 중첩 파일 드롭 + New Frame 새 프레임 + Replace Image… 이미지 바꾸기… + The frame is locked 프레임이 잠겨 있습니다 + The frame is unavailable 프레임을 사용할 수 없습니다 + X X + Y Y diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 7e76c4da50..0ad0a96291 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -4288,3 +4288,21 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded New file Nieuw bestand Learn Leren Website Website + +# Frame Tool and other branch translations. + A frame supports affine transforms; select its image for perspective transforms Een kader ondersteunt affiene transformaties; selecteer de afbeelding voor perspectieftransformaties + A frame supports affine transforms; select its image to warp it Een kader ondersteunt affiene transformaties; selecteer de afbeelding om deze te verdraaien + Convert to Frame… Omzetten naar kader… + Create a new custom frame Nieuw aangepast kader maken + Create a new polygonal frame Nieuw veelhoekig kader maken + Create a new triangular frame Nieuw driehoekig kader maken + Fit Content to Frame Inhoud aanpassen aan kader + Fit Frame to Content Kader aanpassen aan inhoud + Frame coordinates must be finite and within 600000 pixels Kadercoördinaten moeten eindig zijn en binnen 600000 pixels liggen + Import Image… Afbeelding importeren… + Invalid frame transform Ongeldige kadertransformatie + Invalid nested file drop Ongeldige geneste bestandsneerzetting + New Frame Nieuw kader + Replace Image… Afbeelding vervangen… + The frame is locked Het kader is vergrendeld + The frame is unavailable Het kader is niet beschikbaar diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 1e7c4abdc5..1a86582093 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4151,3 +4151,21 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Learn Nauka No recent files Brak ostatnich plików Website Strona internetowa + +# Frame Tool and other branch translations. + A frame supports affine transforms; select its image for perspective transforms Ramka obsługuje przekształcenia afiniczne; do przekształceń perspektywicznych wybierz jej obraz + A frame supports affine transforms; select its image to warp it Ramka obsługuje przekształcenia afiniczne; aby ją wypaczyć, wybierz obraz + Convert to Frame… Konwertuj na ramkę… + Create a new custom frame Utwórz nową ramkę niestandardową + Create a new polygonal frame Utwórz nową ramkę wielokątną + Create a new triangular frame Utwórz nową ramkę trójkątną + Fit Content to Frame Dopasuj zawartość do ramki + Fit Frame to Content Dopasuj ramkę do zawartości + Frame coordinates must be finite and within 600000 pixels Współrzędne ramki muszą być skończone i mieścić się w granicach 600000 pikseli + Import Image… Importuj obraz… + Invalid frame transform Nieprawidłowe przekształcenie ramki + Invalid nested file drop Nieprawidłowe zagnieżdżone upuszczenie pliku + New Frame Nowa ramka + Replace Image… Zastąp obraz… + The frame is locked Ramka jest zablokowana + The frame is unavailable Ramka jest niedostępna diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 8239211be7..afe96a6cc9 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -4457,3 +4457,21 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded New file Novo arquivo Learn Aprender Website Site + +# Frame Tool and other branch translations. + A frame supports affine transforms; select its image for perspective transforms Uma moldura permite transformações afins; selecione sua imagem para transformações de perspectiva + A frame supports affine transforms; select its image to warp it Uma moldura permite transformações afins; selecione sua imagem para deformá-la + Convert to Frame… Converter em moldura… + Create a new custom frame Criar nova moldura personalizada + Create a new polygonal frame Criar nova moldura poligonal + Create a new triangular frame Criar nova moldura triangular + Fit Content to Frame Ajustar conteúdo à moldura + Fit Frame to Content Ajustar moldura ao conteúdo + Frame coordinates must be finite and within 600000 pixels As coordenadas da moldura devem ser finitas e estar dentro de 600000 pixels + Import Image… Importar imagem… + Invalid frame transform Transformação de moldura inválida + Invalid nested file drop Soltura de arquivo aninhada inválida + New Frame Nova moldura + Replace Image… Substituir imagem… + The frame is locked A moldura está bloqueada + The frame is unavailable A moldura não está disponível diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 361526a014..226b0c51d0 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -4728,3 +4728,21 @@ shape Appearance Оформление New file Новый файл Learn Обучение Website Сайт + +# Frame Tool and other branch translations. + A frame supports affine transforms; select its image for perspective transforms Рамка поддерживает аффинные преобразования; для перспективных преобразований выберите её изображение + A frame supports affine transforms; select its image to warp it Рамка поддерживает аффинные преобразования; для деформации выберите её изображение + Convert to Frame… Преобразовать в рамку… + Create a new custom frame Создать новую произвольную рамку + Create a new polygonal frame Создать новую многоугольную рамку + Create a new triangular frame Создать новую треугольную рамку + Fit Content to Frame Подогнать содержимое под рамку + Fit Frame to Content Подогнать рамку под содержимое + Frame coordinates must be finite and within 600000 pixels Координаты рамки должны быть конечными и находиться в пределах 600000 пикселей + Import Image… Импортировать изображение… + Invalid frame transform Недопустимое преобразование рамки + Invalid nested file drop Недопустимое вложенное перетаскивание файла + New Frame Новая рамка + Replace Image… Заменить изображение… + The frame is locked Рамка заблокирована + The frame is unavailable Рамка недоступна diff --git a/crates/ui-egui/src/i18n/sr.tsv b/crates/ui-egui/src/i18n/sr.tsv index e37a9aea69..2dc6bc9020 100644 --- a/crates/ui-egui/src/i18n/sr.tsv +++ b/crates/ui-egui/src/i18n/sr.tsv @@ -4609,3 +4609,21 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded New file Novi fajl Learn Učenje Website Veb-sajt + +# Frame Tool and other branch translations. + A frame supports affine transforms; select its image for perspective transforms Оквир подржава афине трансформације; за перспективне трансформације изаберите његову слику + A frame supports affine transforms; select its image to warp it Оквир подржава афине трансформације; за изобличавање изаберите његову слику + Convert to Frame… Претвори у оквир… + Create a new custom frame Направи нови прилагођени оквир + Create a new polygonal frame Направи нови многоугаони оквир + Create a new triangular frame Направи нови троугаони оквир + Fit Content to Frame Прилагоди садржај оквиру + Fit Frame to Content Прилагоди оквир садржају + Frame coordinates must be finite and within 600000 pixels Координате оквира морају бити коначне и унутар 600000 пиксела + Import Image… Увези слику… + Invalid frame transform Неважећа трансформација оквира + Invalid nested file drop Неважеће угнежђено испуштање датотеке + New Frame Нови оквир + Replace Image… Замени слику… + The frame is locked Оквир је закључан + The frame is unavailable Оквир није доступан diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index f225a7cddf..c209cee829 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4265,3 +4265,21 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded New file Yeni dosya Learn Öğrenin Website Web sitesi + +# Frame Tool and other branch translations. + A frame supports affine transforms; select its image for perspective transforms Çerçeve afin dönüşümleri destekler; perspektif dönüşümleri için içindeki görüntüyü seçin + A frame supports affine transforms; select its image to warp it Çerçeve afin dönüşümleri destekler; çarpıtmak için içindeki görüntüyü seçin + Convert to Frame… Çerçeveye Dönüştür… + Create a new custom frame Yeni özel çerçeve oluştur + Create a new polygonal frame Yeni çokgen çerçeve oluştur + Create a new triangular frame Yeni üçgen çerçeve oluştur + Fit Content to Frame İçeriği Çerçeveye Sığdır + Fit Frame to Content Çerçeveyi İçeriğe Sığdır + Frame coordinates must be finite and within 600000 pixels Çerçeve koordinatları sonlu olmalı ve 600000 piksel sınırları içinde kalmalıdır + Import Image… Görüntü İçe Aktar… + Invalid frame transform Geçersiz çerçeve dönüşümü + Invalid nested file drop Geçersiz iç içe dosya bırakma + New Frame Yeni Çerçeve + Replace Image… Görüntüyü Değiştir… + The frame is locked Çerçeve kilitli + The frame is unavailable Çerçeve kullanılamıyor diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 43edc2f4a7..eaacf70553 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -4244,3 +4244,21 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Learn Навчання No recent files Немає останніх файлів Website Вебсайт + +# Frame Tool and other branch translations. + A frame supports affine transforms; select its image for perspective transforms Рамка підтримує афінні перетворення; для перспективних перетворень виберіть її зображення + A frame supports affine transforms; select its image to warp it Рамка підтримує афінні перетворення; для деформації виберіть її зображення + Convert to Frame… Перетворити на рамку… + Create a new custom frame Створити нову довільну рамку + Create a new polygonal frame Створити нову багатокутну рамку + Create a new triangular frame Створити нову трикутну рамку + Fit Content to Frame Припасувати вміст до рамки + Fit Frame to Content Припасувати рамку до вмісту + Frame coordinates must be finite and within 600000 pixels Координати рамки мають бути скінченними та в межах 600000 пікселів + Import Image… Імпортувати зображення… + Invalid frame transform Неприпустиме перетворення рамки + Invalid nested file drop Неприпустиме вкладене перетягування файлу + New Frame Нова рамка + Replace Image… Замінити зображення… + The frame is locked Рамку заблоковано + The frame is unavailable Рамка недоступна diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 60ef9d8197..863a17ede7 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -4039,3 +4039,21 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Learn Học hỏi No recent files Không có tệp gần đây Website Trang web + +# Frame Tool and other branch translations. + A frame supports affine transforms; select its image for perspective transforms Khung hỗ trợ các phép biến đổi affine; chọn ảnh trong khung để biến đổi phối cảnh + A frame supports affine transforms; select its image to warp it Khung hỗ trợ các phép biến đổi affine; chọn ảnh trong khung để làm cong + Convert to Frame… Chuyển thành khung… + Create a new custom frame Tạo khung tùy chỉnh mới + Create a new polygonal frame Tạo khung đa giác mới + Create a new triangular frame Tạo khung tam giác mới + Fit Content to Frame Khớp nội dung với khung + Fit Frame to Content Khớp khung với nội dung + Frame coordinates must be finite and within 600000 pixels Tọa độ khung phải hữu hạn và nằm trong giới hạn 600000 pixel + Import Image… Nhập ảnh… + Invalid frame transform Phép biến đổi khung không hợp lệ + Invalid nested file drop Thả tệp lồng nhau không hợp lệ + New Frame Khung mới + Replace Image… Thay ảnh… + The frame is locked Khung đã bị khóa + The frame is unavailable Khung không khả dụng diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 240d18d5b5..9f4388d63c 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -3218,3 +3218,24 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Learn 学习 No recent files 没有最近使用的文件 Website 网站 + +# Frame Tool and other branch translations. + A frame supports affine transforms; select its image for perspective transforms 框架支持仿射变换;要进行透视变换,请选择框架中的图像 + A frame supports affine transforms; select its image to warp it 框架支持仿射变换;要进行变形,请选择框架中的图像 + Convert to Frame… 转换为框架… + Create a new custom frame 创建新的自定义框架 + Create a new polygonal frame 创建新的多边形框架 + Create a new triangular frame 创建新的三角形框架 + Fit Content to Frame 使内容适合框架 + Fit Frame to Content 使框架适合内容 + Frame coordinates must be finite and within 600000 pixels 框架坐标必须为有限值,且在 600000 像素范围内 + Import Image… 导入图像… + Invalid frame transform 无效的框架变换 + Invalid nested file drop 无效的嵌套文件拖放 + New Frame 新建框架 + Replace Image… 替换图像… + The frame is locked 框架已锁定 + The frame is unavailable 框架不可用 + Frame 框架 + X X + Y Y diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index a520e7435b..8a303bdb68 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -3174,3 +3174,24 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Learn 學習 No recent files 沒有最近使用的檔案 Website 網站 + +# Frame Tool and other branch translations. + A frame supports affine transforms; select its image for perspective transforms 框架支援仿射變形;若要進行透視變形,請選取框架中的影像 + A frame supports affine transforms; select its image to warp it 框架支援仿射變形;若要進行彎曲變形,請選取框架中的影像 + Convert to Frame… 轉換為框架… + Create a new custom frame 建立新的自訂框架 + Create a new polygonal frame 建立新的多邊形框架 + Create a new triangular frame 建立新的三角形框架 + Fit Content to Frame 使內容符合框架 + Fit Frame to Content 使框架符合內容 + Frame coordinates must be finite and within 600000 pixels 框架座標必須為有限值,且在 600000 像素範圍內 + Import Image… 讀入影像… + Invalid frame transform 無效的框架變形 + Invalid nested file drop 無效的巢狀檔案拖放 + New Frame 新增框架 + Replace Image… 取代影像… + The frame is locked 框架已鎖定 + The frame is unavailable 框架無法使用 + Frame 框架 + X X + Y Y diff --git a/crates/ui-egui/src/input/shortcuts.rs b/crates/ui-egui/src/input/shortcuts.rs index fb3f2cae5d..26dfa5e96f 100644 --- a/crates/ui-egui/src/input/shortcuts.rs +++ b/crates/ui-egui/src/input/shortcuts.rs @@ -620,6 +620,9 @@ fn handle_modal_canvas_keys(app: &mut PhotocraftApp, ctx: &egui::Context, focus: if focus == Focus::None && crate::perspective_crop_ui::keys(app, ctx) { return true; } + if focus == Focus::None && crate::frame_tool::keys(app, ctx) { + return true; + } // Move tool / Free Transform: arrows nudge (⇧ ×10, ⌥ duplicates first). if focus == Focus::None && crate::move_mods::arrow_keys(app, ctx) { return true; @@ -788,6 +791,10 @@ fn handle_registry_and_tool_keys(app: &mut PhotocraftApp, ctx: &egui::Context, f return true; } } + if app.ui.frame_tool.drag.is_some() && pressed(Key::Escape) { + crate::frame_tool::cancel(app); + return true; + } // Enter / Escape commit or cancel in-progress tool state (polygonal lasso, crop). if crate::lasso_ui::active(app) { let mods = ctx.input(|i| i.modifiers); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 05039b303b..8563f65faf 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -481,6 +481,8 @@ pub struct PhotocraftApp { /// The document tab strip last frame: a drop there opens the file at the slot under it. pub(crate) tab_strip: Option, /// Files dropped on the canvas still to place, one Free Transform at a time. + pub(crate) frame_tool_ctx: Option, + pub(crate) frame_preview: Option, pub(crate) drop_places: std::collections::VecDeque, /// The document each of `ui.views` belongs to, as of the last [`Self::sync_views`]. view_docs: Vec, diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index a089803be8..e1f52d934c 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -56,12 +56,32 @@ pub fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: Va Ok(r) } +/// Layer › New › Convert to Frame without params: asks for the frame's name and size first. +fn frame_convert_dialog(app: &mut PhotocraftApp, id: &str) -> Result { + let st = app.session.active().ok_or("no document")?; + let layer = st.active_layer.and_then(|id| st.doc.layer(id)).ok_or("select a shape or type layer")?; + let b = photocraft_engine::transform_cmds::transform_frame(&st.doc, layer); + let mut fixed = serde_json::Map::new(); + fixed.insert("layer".into(), json!(layer.id.0)); + let dialog = crate::filter_dialog::open_with_spec(app, id, tl!("New Frame"), r#"{"name":text,"width":1..300000=100,"height":1..300000=100}"#, fixed); + if let Some(d) = app.ui.dialog_mut(dialog) { + d.fields.insert("__preview".into(), json!(false)); + d.fields.insert("name".into(), json!("Frame")); + d.fields.insert("width".into(), json!(b.width().max(1))); + d.fields.insert("height".into(), json!(b.height().max(1))); + } + Ok(json!({"dialog":dialog})) +} + /// [`invoke`] without the unsaved-changes prompt, for once the user has already answered it. fn invoke_early_commands(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &Value) -> Option> { if let Some(tool) = crate::tool_shortcuts::tool(id) { crate::tool_memory::select(app, tool); return Some(Ok(json!({"tool": tool}))); } + if id == "layer.frame.convert" && params.as_object().is_none_or(|o| o.is_empty()) { + return Some(frame_convert_dialog(app, id)); + } if id == "help.checkForUpdates" { return Some(crate::updates_ui::check(app, ctx, params.clone())); } diff --git a/crates/ui-egui/src/menus/view_cmds/dialogs.rs b/crates/ui-egui/src/menus/view_cmds/dialogs.rs index 2df2c64bd6..2a380909f1 100644 --- a/crates/ui-egui/src/menus/view_cmds/dialogs.rs +++ b/crates/ui-egui/src/menus/view_cmds/dialogs.rs @@ -314,7 +314,9 @@ pub(super) fn front(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, para app.refocus(doc)?; let linked = linked.then(|| name.clone()); let result = app.place_bytes(&name, bytes, linked)?; - crate::transform_tool::begin_placed(app, &ctx)?; + if result.get("frame").and_then(Value::as_u64).is_none() { + crate::transform_tool::begin_placed(app, &ctx)?; + } Ok(result) })) } diff --git a/crates/ui-egui/src/panels/layer_drag.rs b/crates/ui-egui/src/panels/layer_drag.rs index f778ccec75..35903dcf61 100644 --- a/crates/ui-egui/src/panels/layer_drag.rs +++ b/crates/ui-egui/src/panels/layer_drag.rs @@ -154,6 +154,22 @@ pub(super) fn layer_drag_and_drop( "below" }; let Some(st) = app.session.active() else { return }; + if position == "into" && l.frame.is_some() { + let selected = st.selected_layers(); + if selected.len() > 1 && selected.iter().any(|id| id.0 == dragged) { + return; + } + let source = LayerId(dragged); + if st.doc.layer(source).is_none_or(|l| !matches!(l.content, photocraft_doc::LayerContent::Raster(_) | photocraft_doc::LayerContent::Smart(_))) { + return; + } + ui.painter().rect_stroke(rect.shrink(1.0), t.radius_sm, Stroke::new(2.0, t.accent), StrokeKind::Inside); + if released { + app.reorder_preview = None; + actions.push(("layer.frame.setContent".into(), json!({"layer":l.id.0,"content":dragged,"copy":copy}))); + } + return; + } let mut payload = layer_drop_payload(dragged, l.id, position, &st.selected_layers()); if background_drop_refused(&st.doc, &payload, l.id, position, copy) { return; diff --git a/crates/ui-egui/src/panels/layer_menu_ui.rs b/crates/ui-egui/src/panels/layer_menu_ui.rs index f274e28620..c025f005da 100644 --- a/crates/ui-egui/src/panels/layer_menu_ui.rs +++ b/crates/ui-egui/src/panels/layer_menu_ui.rs @@ -64,6 +64,9 @@ pub fn entries(l: &Layer, multi: bool, has_selection: bool) -> Vec { v.push(None); v.push(Some((tl!("Artboard from Layers…"), "layer.new.artboardFromLayers"))); v.push(Some((tl!("Frame from Layers…"), "layer.new.frameFromLayers"))); + if !multi && matches!(l.content, LayerContent::Shape(_) | LayerContent::Text(_)) { + v.push(Some((tl!("Convert to Frame…"), "layer.frame.convert"))); + } v.push(None); v.push(Some((tl!("Convert to Smart Object"), "layer.smartObjects.convertToSmartObject"))); if multi { diff --git a/crates/ui-egui/src/panels/layer_row.rs b/crates/ui-egui/src/panels/layer_row.rs index cb29276091..d622a0e9db 100644 --- a/crates/ui-egui/src/panels/layer_row.rs +++ b/crates/ui-egui/src/panels/layer_row.rs @@ -104,6 +104,59 @@ fn swept_pointer_range(ctx: &egui::Context) -> Option<(f32, f32)> { Some(((p.y - delta.y).min(p.y), (p.y - delta.y).max(p.y))) } +/// A Frame row's second thumbnail (its image) beside the frame outline's: paints both targets' +/// brackets and handles the click that picks Frame / Image / Both and a double-click that opens +/// a smart-object image. Returns whether the click was taken. +#[allow(clippy::too_many_arguments)] +fn frame_content_thumb( + app: &mut PhotocraftApp, + ctx: &egui::Context, + ui: &egui::Ui, + painter: &egui::Painter, + (doc, l, rect): (&photocraft_doc::Document, &Layer, Rect), + (thumb, x, ts, selected): (Rect, f32, f32, bool), + resp: &egui::Response, + actions: &mut Vec<(String, Value)>, +) -> bool { + let t = Tokens::get(ctx); + let target = crate::frame_tool::target(app, l); + if selected && target != crate::frame_tool::Target::Content { + crate::mask_thumbs_ui::paint_brackets(painter, thumb, t.text); + } + let content_thumb = Rect::from_min_size(pos2(x, rect.center().y - ts / 2.0), vec2(ts, ts)); + let child = l.children().and_then(|c| c.first()); + if let Some(child) = child { + draw_layer_thumb(app, ctx, ui, doc, child, content_thumb, false); + } else { + icons::paint(ui, content_thumb, "frame-placeholder", ts.min(24.0), t.icon); + } + if selected && target != crate::frame_tool::Target::Frame { + crate::mask_thumbs_ui::paint_brackets(painter, content_thumb, t.text); + } + let pos = resp.interact_pointer_pos(); + let on_content = pos.is_some_and(|p| content_thumb.contains(p)); + let mut clicked = false; + if resp.clicked() && !ui.input(|i| i.modifiers.command) && (on_content || pos.is_some_and(|p| thumb.contains(p))) { + let target = if ui.input(|i| i.modifiers.shift) { + crate::frame_tool::Target::Both + } else if on_content { + crate::frame_tool::Target::Content + } else { + crate::frame_tool::Target::Frame + }; + crate::frame_tool::select(app, l.id, target); + clicked = true; + } + if resp.double_clicked() + && on_content + && let Some(child) = child + && matches!(child.content, LayerContent::Smart(_)) + { + actions.push(("layer.smartObjects.editContents".into(), json!({"layer": child.id.0}))); + } + clicked +} + /// Marker in the clipped row's existing 12-point slot, beside its thumbnail. pub(super) fn paint_clipping_indicator(painter: &egui::Painter, at: Pos2, color: Color32) { let tip = at + vec2(5.0, 3.0); @@ -130,6 +183,7 @@ pub(super) fn layer_row( row: RowSel, actions: &mut Vec<(String, Value)>, ) -> Rect { + let row = RowSel { selected: row.selected || (l.frame.is_some() && crate::frame_tool::selected(app).is_some_and(|f| f.id == l.id)), ..row }; let selected = row.selected; let t = Tokens::get(ctx); // The Layers Panel Options thumbnail size controls rows and both layer/mask thumbnails. @@ -197,6 +251,11 @@ pub(super) fn layer_row( draw_layer_thumb(app, ctx, ui, doc, l, thumb, row.primary); x += ts + 6.0; } + let mut frame_clicked = false; + if l.frame.is_some() && ts > 0.0 { + frame_clicked = frame_content_thumb(app, ctx, ui, &painter, (doc, l, rect), (thumb, x, ts, selected), &resp, actions); + x += ts + 6.0; + } // With thumbnails disabled the labels and disclosure controls remain interactive. let masks = if ts > 0.0 { crate::mask_thumbs_ui::paint(app, ctx, ui, &painter, doc, l, &mut x, rect.center().y, ts, actions) } else { Default::default() }; let rc = RowCtx { l, doc, row, rect, ts, thumb, resp: &resp, masks: &masks }; @@ -229,6 +288,9 @@ pub(super) fn layer_row( if !m.command { return None; } + if l.frame.is_some() && thumb.contains(p) { + return Some(crate::mask_thumbs_ui::load_params(l, crate::mask_thumbs_ui::MaskKind::Vector, m)); + } if let Some(kind) = masks.hit(p) { return Some(crate::mask_thumbs_ui::load_params(l, kind, m)); } @@ -253,7 +315,12 @@ pub(super) fn layer_row( actions.push(("select.loadSelection".into(), p)); } else if let Some(cmd) = mask_toggle { actions.push(cmd); - } else if resp.clicked() && !eye_resp.clicked() && !toggled && !fx_toggled && !masks.clicked { + } else if resp.clicked() && !frame_clicked && !eye_resp.clicked() && !toggled && !fx_toggled && !masks.clicked { + if l.frame.is_some() { + app.ui.frame_tool.selected = Some(l.id.0); + app.ui.frame_tool.target = + if l.children().is_some_and(|c| !c.is_empty()) { crate::frame_tool::Target::Both } else { crate::frame_tool::Target::Frame }; + } select_row_on_click(app, ui, &rc, actions); } // Double-click: the name renames in place (over the row's full height, not just the glyphs: @@ -398,6 +465,7 @@ fn paint_row_name(painter: &egui::Painter, t: &Tokens, rc: &RowCtx<'_>, x: f32, if !is_pixel { let sub = match &l.content { LayerContent::Adjustment(a) => tl!(a.label()).to_string(), + LayerContent::Group(_) if l.frame.is_some() => tl!("Frame").to_string(), LayerContent::Group(g) => crate::i18n::trn(crate::i18n::current(), g.children.len() as u64, "Group · {n} layer", "Group · {n} layers"), other => tl!(other.kind_name()).to_string(), }; @@ -453,7 +521,16 @@ fn select_row_on_click(app: &mut PhotocraftApp, ui: &egui::Ui, rc: &RowCtx<'_>, /// Double-click: rename, un-background, open the thumbnail's settings or the row's Layer Style. fn handle_row_double_click(app: &mut PhotocraftApp, ctx: &egui::Context, rc: &RowCtx<'_>, name_rect: Option, actions: &mut Vec<(String, Value)>) { let (l, doc, resp, masks, ts, thumb, rect) = (rc.l, rc.doc, rc.resp, rc.masks, rc.ts, rc.thumb, rc.rect); - if resp.double_clicked() { + // A frame row's thumbnails are handled in the row; its name still renames in place. + if resp.double_clicked() + && l.frame.is_some() + && name_rect.is_some_and(|n| resp.interact_pointer_pos().is_some_and(|p| Rect::from_x_y_ranges(n.x_range(), rect.y_range()).expand(2.0).contains(p))) + && let Some(done) = crate::layer_row_ui::start_rename(ctx, l.id.0, &l.name) + { + // One rename at a time: starting this one commits any other (#314). + actions.push(done); + } + if resp.double_clicked() && l.frame.is_none() { let pos = resp.interact_pointer_pos(); let on = |r: Rect| pos.is_some_and(|p| r.expand(2.0).contains(p)); if crate::doc_props_ui::is_background(doc, l) { @@ -528,6 +605,20 @@ pub(super) fn layer_thumb_fit(cell: Rect, w: u32, h: u32) -> (Rect, Rect) { fn draw_layer_thumb(app: &mut PhotocraftApp, ctx: &egui::Context, ui: &egui::Ui, doc: &photocraft_doc::Document, l: &Layer, rect: Rect, selected: bool) { let t = Tokens::get(ctx); let p = ui.painter(); + if let Some(f) = &l.frame { + let path = f.path.clone(); + for line in photocraft_vector::flatten::flatten_path(&path, 0.01) { + let mut points: Vec = + line.pts.iter().map(|&(x, y)| pos2(rect.left() + x as f32 * rect.width(), rect.top() + y as f32 * rect.height())).collect(); + if line.closed + && let Some(p) = points.first().copied() + { + points.push(p); + } + ui.painter().add(egui::Shape::line(points, Stroke::new(1.0, t.icon))); + } + return; + } match &l.content { LayerContent::Adjustment(_) | LayerContent::Group(_) => { p.rect_filled(rect, 6.0, t.field); diff --git a/crates/ui-egui/src/panels/layer_transfer.rs b/crates/ui-egui/src/panels/layer_transfer.rs index c9e45225f4..7534d63fbc 100644 --- a/crates/ui-egui/src/panels/layer_transfer.rs +++ b/crates/ui-egui/src/panels/layer_transfer.rs @@ -149,6 +149,20 @@ fn drop(app: &mut PhotocraftApp, ctx: &egui::Context, dest: usize, at: Option<[f clear(ctx); let docs = app.session.documents(); let Some(src) = docs.iter().position(|d| d.doc.id == t.source) else { return }; + if dest == src + && let Some(at) = at + { + if let Some(frame) = crate::frame_tool::frame_at(app, at) + && let [source] = t.layers.as_slice() + { + let r = app.run("layer.frame.setContent", json!({"layer":frame.0,"content":source})); + if let Err(e) = r { + app.ui.status = e; + app.ui.status_error = true; + } + } + return; + } let Some(to) = docs.get(dest).filter(|_| dest != src) else { return }; let same_size = to.doc.size == docs[src].doc.size; let mut p = json!({"document": dest, "source": src, "layers": t.layers}); diff --git a/crates/ui-egui/src/panels/layer_tree_ui.rs b/crates/ui-egui/src/panels/layer_tree_ui.rs index 858fe432fc..0bd071c520 100644 --- a/crates/ui-egui/src/panels/layer_tree_ui.rs +++ b/crates/ui-egui/src/panels/layer_tree_ui.rs @@ -24,6 +24,7 @@ pub fn display_rows(doc: &Document, show_all: bool) -> Vec<(usize, &Layer)> { for l in layers.iter().rev() { out.push((depth, l)); if let LayerContent::Group(g) = &l.content + && l.frame.is_none() && (g.expanded || show_all) { rec(&g.children, depth + 1, show_all, out); @@ -54,6 +55,9 @@ pub fn triangle_rect(row: Rect, x: f32) -> Rect { /// Paint and handle a group row's disclosure triangle at `*x` (advancing it). Returns true when /// it was clicked this frame, so the row doesn't also treat the click as a selection. pub fn disclosure(ui: &mut egui::Ui, row: Rect, x: &mut f32, l: &Layer, actions: &mut Vec<(String, Value)>) -> bool { + if l.frame.is_some() { + return false; + } let LayerContent::Group(g) = &l.content else { return false }; let hit = triangle_rect(row, *x); let resp = ui.interact(hit, ui.scope_id().with(("disclosure", l.id.0)), Sense::click()); diff --git a/crates/ui-egui/src/panels/mask_thumbs_ui.rs b/crates/ui-egui/src/panels/mask_thumbs_ui.rs index c19b14928d..e232fdcf99 100644 --- a/crates/ui-egui/src/panels/mask_thumbs_ui.rs +++ b/crates/ui-egui/src/panels/mask_thumbs_ui.rs @@ -49,6 +49,9 @@ impl MaskKind { /// `(kind, enabled, linked)` for each of `l`'s masks, in row order. pub fn masks(l: &Layer) -> Vec<(MaskKind, bool, bool)> { + if l.frame.is_some() { + return Vec::new(); + } let mut v = Vec::with_capacity(2); if let Some(m) = &l.mask { v.push((MaskKind::Pixel, m.enabled, m.linked)); @@ -61,13 +64,13 @@ pub fn masks(l: &Layer) -> Vec<(MaskKind, bool, bool)> { /// Width `l`'s masks take in a row with `ts`-point thumbnails (chain + thumbnail + gap each). pub fn width(l: &Layer, ts: f32) -> f32 { - masks(l).len() as f32 * (CHAIN_W + ts + 6.0) + if l.frame.is_some() { ts + 6.0 } else { masks(l).len() as f32 * (CHAIN_W + ts + 6.0) } } /// Thumbnail size for `l`'s row: `ts`, shrunk (down to 14 pt) when the layer and mask /// thumbnails would leave the name less than its minimum of the `room` they share. pub fn thumb_size(l: &Layer, ts: f32, room: f32) -> f32 { - let n = masks(l).len() as f32; + let n = if l.frame.is_some() { 1.0 } else { masks(l).len() as f32 }; let need = ts + 6.0 + width(l, ts) + crate::layer_row_ui::MIN_NAME_W; let short = need - room; if short <= 0.0 { ts } else { (ts - short / (1.0 + n)).clamp(14.0_f32.min(ts), ts) } diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index 0607c5ca30..9f20214104 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -151,6 +151,10 @@ fn properties_body_inner(app: &mut PhotocraftApp, ui: &mut egui::Ui) { && crate::mask_props_ui::targeted(app, layer) { crate::props_layout::header(ui, layer); + if layer.frame.is_some() { + crate::frame_tool::properties(app, ui, layer); + return; + } crate::mask_props_ui::properties(app, ui, layer); return; } @@ -186,6 +190,8 @@ fn properties_body_inner(app: &mut PhotocraftApp, ui: &mut egui::Ui) { adjustment_controls(app, ui, id, adj); } else if layer.artboard().is_some() { crate::artboard_ui::properties(app, ui, layer); + } else if layer.frame.is_some() { + crate::frame_tool::properties(app, ui, layer); } else if t.pro { // Transform, Align, the kind's sections and Quick Actions. crate::layer_props_ui::properties(app, ui, layer); diff --git a/crates/ui-egui/src/panels/props_layout.rs b/crates/ui-egui/src/panels/props_layout.rs index 08d3f79e6b..8d604995bc 100644 --- a/crates/ui-egui/src/panels/props_layout.rs +++ b/crates/ui-egui/src/panels/props_layout.rs @@ -43,6 +43,9 @@ pub fn kind_icon(content: &LayerContent) -> &'static str { /// "Type Layer", "Curves", "Artboard"… pub fn kind_label(layer: &Layer) -> String { + if layer.frame.is_some() { + return tl!("Frame").into(); + } match &layer.content { LayerContent::Adjustment(a) => a.label().to_string(), LayerContent::Group(g) if g.artboard.is_some() => "Artboard".to_string(), diff --git a/crates/ui-egui/src/tool_memory.rs b/crates/ui-egui/src/tool_memory.rs index 2b05c523d6..960fb83a07 100644 --- a/crates/ui-egui/src/tool_memory.rs +++ b/crates/ui-egui/src/tool_memory.rs @@ -25,6 +25,9 @@ pub(crate) type ToolBrushes = (Tool, Vec<(Tool, BrushSettings)>); pub(crate) fn select(app: &mut PhotocraftApp, tool: Tool) { app.stylus.tool_before_eraser = None; app.ui.spring = None; + if app.ui.tool == Tool::Frame && tool != Tool::Frame { + crate::frame_tool::cancel(app); + } app.ui.tool = tool; } diff --git a/crates/ui-egui/src/tools/frame_tool.rs b/crates/ui-egui/src/tools/frame_tool.rs index b2102b1cfb..190b0509c2 100644 --- a/crates/ui-egui/src/tools/frame_tool.rs +++ b/crates/ui-egui/src/tools/frame_tool.rs @@ -1,190 +1,870 @@ -//! 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 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; +//! Frame Tool: persistent placeholders and independently selectable frame/image geometry. +use crate::{ + PhotocraftApp, + canvas::{ToolEvent, ViewXform}, + state::Tool, + theme::Tokens, +}; +use egui::{CursorIcon, Pos2, Stroke, StrokeKind}; +use photocraft_doc::{DocId, Frame, Layer, LayerContent, LayerId}; +use photocraft_geom::{Affine, Point, Rect}; use serde::{Deserialize, Serialize}; -use serde_json::json; +use serde_json::{Value, 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)] +const HANDLE_PX: f64 = 7.0; +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Target { + #[default] + Frame, + Content, + Both, +} +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(default)] pub struct FrameToolUi { - /// Options bar: draw elliptical frames (else rectangular). + /// Kept for old saved UI state; the current shape selector also supports polygons/custom shapes. pub ellipse: bool, - /// The drag in progress: press and current point (document pixels), ⇧ and ⌥ at the last event. + pub shape: String, + pub sides: u32, + pub stroke: Option, + pub target: Target, + pub selected: Option, #[serde(skip)] pub drag: Option, + #[serde(skip)] + pub auto_transform: bool, } - -#[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)); +impl Default for FrameToolUi { + fn default() -> Self { + Self { ellipse: false, shape: "rectangle".into(), sides: 5, stroke: None, target: Target::Frame, selected: None, drag: None, auto_transform: false } } - 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]) }; +} +#[derive(Clone, Debug, PartialEq)] +pub enum FrameDrag { + New { start: [f64; 2], cur: [f64; 2], square: bool, centred: bool, doc: DocId, revision: u64 }, + Edit { layer: LayerId, doc: DocId, revision: u64, original: Box, proposed: Affine, start: [f64; 2], mode: EditMode }, +} +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum EditMode { + Move, + Resize(i8, i8), + Rotate, +} +pub(crate) struct Preview { + doc: std::sync::Arc, + revision: u64, + key: u64, +} + +fn drawn(start: [f64; 2], cur: [f64; 2], square: bool, centred: bool) -> [i64; 4] { + let [sx, sy] = start; + let [x, y] = cur; + let (mut dx, mut dy) = (x - sx, y - sy); + if square { + let side = dx.abs().max(dy.abs()); + dx = side.copysign(dx); + dy = side.copysign(dy); + } + let (a, b) = if centred { ([sx - dx, sy - dy], [sx + dx, sy + dy]) } else { (start, [sx + dx, sy + 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, type, shape or smart object layer the frame `r` takes in: one whose content -/// it overlaps and that can move (not the Background or a position-locked layer). +pub fn selected(app: &PhotocraftApp) -> Option<&Layer> { + let st = app.session.active()?; + let id = photocraft_engine::frame_cmds::frame_of(&st.doc, st.active_layer?)?; + st.doc.layer(id) +} +fn path_visible(doc: &photocraft_doc::Document, path: &[usize]) -> bool { + (1..=path.len()).all(|n| path.get(..n).and_then(|p| doc.layer_at(p)).is_some_and(|l| l.visible)) +} +fn visible(app: &PhotocraftApp, id: LayerId) -> bool { + app.session.active().is_some_and(|st| st.doc.path_of(id).is_some_and(|p| path_visible(&st.doc, &p))) +} fn content_layer(app: &PhotocraftApp, r: [i64; 4]) -> Option { let st = app.session.active()?; let l = st.doc.layer(st.active_layer?)?; - let framable = matches!(l.content, LayerContent::Raster(_) | LayerContent::Text(_) | LayerContent::Shape(_) | LayerContent::Smart(_)); - if !framable || l.locks.position || l.locks.all { + if !matches!(l.content, LayerContent::Raster(_) | LayerContent::Text(_) | LayerContent::Shape(_) | LayerContent::Smart(_)) || st.doc.is_background(l.id) { 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) + let locks = st.doc.effective_locks(l.id); + if locks.position || locks.all { + return None; + } + // Another frame's image stays in its frame; the drag draws an empty frame instead. + if photocraft_engine::frame_cmds::frame_of(&st.doc, l.id).is_some() { + return None; + } + let b = photocraft_engine::transform_cmds::transform_frame(&st.doc, l); + (!b.is_empty() && i64::from(b.x0) < r[2] && r[0] < i64::from(b.x1) && i64::from(b.y0) < r[3] && r[1] < i64::from(b.y1)).then_some(l.id.0) +} +fn report(app: &mut PhotocraftApp, r: Result) { + if let Err(e) = r { + app.ui.status = e; + app.ui.status_error = true; + } +} +pub(crate) fn select(app: &mut PhotocraftApp, id: LayerId, target: Target) { + let r = select_result(app, id, target); + if let Err(e) = r { + report(app, Err(e)); + } +} +pub(crate) fn select_result(app: &mut PhotocraftApp, id: LayerId, target: Target) -> Result<(), String> { + let child = app.session.active().and_then(|st| st.doc.layer(id)).and_then(|l| l.children()).and_then(|c| c.first()).map(|l| l.id); + let layer = if target == Target::Content { child.unwrap_or(id) } else { id }; + app.run("layer.select", json!({"layer":layer.0}))?; + app.ui.frame_tool.target = if child.is_none() { Target::Frame } else { target }; + app.ui.frame_tool.selected = Some(id.0); + app.ui.mask_target = false; + app.ui.vector_mask_target = false; + app.ui.selected_path = None; + Ok(()) +} +pub(crate) fn target(app: &PhotocraftApp, l: &Layer) -> Target { + if app.ui.frame_tool.selected != Some(l.id.0) { + if app.session.active().is_some_and(|st| st.active_layer != Some(l.id)) { Target::Content } else { Target::Frame } + } else { + app.ui.frame_tool.target + } +} +fn shape_params(app: &PhotocraftApp, r: [i64; 4]) -> Value { + let [x, y, x1, y1] = r; + let shape = if app.ui.frame_tool.ellipse { + "ellipse" + } else if app.ui.frame_tool.shape.is_empty() { + "rectangle" + } else { + &app.ui.frame_tool.shape + }; + let mut p = json!({"x":x,"y":y,"width":x1.saturating_sub(x),"height":y1.saturating_sub(y),"shape":shape,"sides":app.ui.frame_tool.sides.clamp(3,100)}); + if shape == "custom" { + let name = app.ui.presets_ui.shape(); + if let Some(sh) = photocraft_engine::presets::shapes::all_groups(&app.session).iter().flat_map(|g| &g.items).find(|s| s.name == name) { + p["path"] = photocraft_engine::vector_cmds::path_json(&sh.path); + } + } + if let Some(s) = &app.ui.frame_tool.stroke { + p["stroke"] = stroke_json(s); + } + p +} +fn outline(app: &PhotocraftApp, r: [i64; 4]) -> Option { + let p = shape_params(app, r); + let shape = p.get("shape").and_then(Value::as_str)?; + if shape == "custom" { + let sh = photocraft_engine::vector_cmds::parse_path(p.get("path")?).ok()?; + let (x0, y0, x1, y1) = sh.control_bounds()?; + if x1 <= x0 || y1 <= y0 { + return None; + } + let [x, y, xe, ye] = r; + let (sx, sy) = ((xe - x) as f64 / (x1 - x0), (ye - y) as f64 / (y1 - y0)); + return Some(sh.transform(&Affine { m: [sx, 0.0, 0.0, sy, x as f64 - x0 * sx, y as f64 - y0 * sy] })); + } + let [x, y, xe, ye] = r; + photocraft_engine::vector_cmds::shape_path(&json!({"kind":match shape{"ellipse"=>"ellipse","triangle"|"polygon"=>"polygon",_=>"rect"},"rect":[x,y,xe-x,ye-y],"sides":if shape=="triangle"{3}else{app.ui.frame_tool.sides.clamp(3,100)}})).ok() +} +fn handles(f: &Frame) -> [(Point, i8, i8); 8] { + [(0., 0., -1, -1), (0.5, 0., 0, -1), (1., 0., 1, -1), (1., 0.5, 1, 0), (1., 1., 1, 1), (0.5, 1., 0, 1), (0., 1., -1, 1), (0., 0.5, -1, 0)] + .map(|(x, y, hx, hy)| (f.transform.apply(Point::new(x, y)), hx, hy)) +} +fn control_hit(f: &Frame, p: [f64; 2], zoom: f64) -> Option { + if let Some((_, hx, hy)) = handles(f).into_iter().find(|(q, _, _)| (q.x - p[0]).hypot(q.y - p[1]) * zoom <= HANDLE_PX) { + return Some(EditMode::Resize(hx, hy)); + } + let local = f.transform.inverse()?.apply(Point::new(p[0], p[1])); + if (!(0.0..=1.0).contains(&local.x) || !(0.0..=1.0).contains(&local.y)) && f.corners().iter().any(|q| (q.x - p[0]).hypot(q.y - p[1]) * zoom <= 20.0) { + return Some(EditMode::Rotate); + } + None +} +fn on_border(f: &Frame, p: [f64; 2], zoom: f64) -> bool { + let path = f.outline(); + photocraft_vector::flatten::flatten_path(&path, 0.5 / zoom.max(0.01)).iter().any(|line| { + let segments = line.pts.windows(2).filter_map(|s| Some((*s.first()?, *s.get(1)?))); + let closing = line.closed.then(|| Some((*line.pts.last()?, *line.pts.first()?))).flatten(); + segments.chain(closing).any(|((ax, ay), (bx, by))| { + let (dx, dy) = (bx - ax, by - ay); + let n = dx * dx + dy * dy; + let t = if n > 0.0 { ((p[0] - ax) * dx + (p[1] - ay) * dy) / n } else { 0.0 }.clamp(0.0, 1.0); + (p[0] - ax - t * dx).hypot(p[1] - ay - t * dy) * zoom <= 5.0 + }) + }) +} +fn inside(f: &Frame, p: [f64; 2]) -> bool { + let (x, y) = (p[0].floor() as i32, p[1].floor() as i32); + let (Some(x1), Some(y1)) = (x.checked_add(1), y.checked_add(1)) else { return false }; + photocraft_vector::path_coverage(&f.outline(), Rect::new(x, y, x1, y1)).first().is_some_and(|v| *v > 0.0) +} +pub(crate) fn frame_at(app: &PhotocraftApp, p: [f64; 2]) -> Option { + let st = app.session.active()?; + let zoom = f64::from(app.point_zoom()); + st.doc + .walk() + .into_iter() + .rev() + .find(|(path, _, l)| { + path_visible(&st.doc, path) + && l.frame.as_ref().is_some_and(|f| { + let b = f.bounds().inflate((20.0 / zoom.max(0.01)).ceil() as i32); + p[0] >= f64::from(b.x0) + && p[0] <= f64::from(b.x1) + && p[1] >= f64::from(b.y0) + && p[1] <= f64::from(b.y1) + && (inside(f, p) || on_border(f, p, zoom)) + }) + }) + .map(|(_, _, l)| l.id) +} +fn edit_transform(f: &Frame, mode: EditMode, start: [f64; 2], p: [f64; 2], mods: egui::Modifiers) -> Affine { + match mode { + EditMode::Move => { + let (mut dx, mut dy) = (p[0] - start[0], p[1] - start[1]); + if mods.shift { + if dx.abs() > dy.abs() { dy = 0.0 } else { dx = 0.0 } + } + Affine::translate(dx.round(), dy.round()).mul(&f.transform) + } + EditMode::Rotate => { + let center = f.transform.apply(Point::new(0.5, 0.5)); + let mut a = (p[1] - center.y).atan2(p[0] - center.x) - (start[1] - center.y).atan2(start[0] - center.x); + if mods.shift { + let step = std::f64::consts::PI / 12.; + a = (a / step).round() * step; + } + Affine::translate(center.x, center.y).mul(&Affine::rotate(a)).mul(&Affine::translate(-center.x, -center.y)).mul(&f.transform) + } + EditMode::Resize(hx, hy) => { + let Some(inv) = f.transform.inverse() else { return f.transform }; + let (s, c) = (inv.apply(Point::new(start[0], start[1])), inv.apply(Point::new(p[0], p[1]))); + let (dx, dy) = (c.x - s.x, c.y - s.y); + let (mut x0, mut y0, mut x1, mut y1) = (0., 0., 1., 1.); + if hx < 0 { + x0 += dx; + if mods.alt { + x1 -= dx; + } + } else if hx > 0 { + x1 += dx; + if mods.alt { + x0 -= dx; + } + } + if hy < 0 { + y0 += dy; + if mods.alt { + y1 -= dy; + } + } else if hy > 0 { + y1 += dy; + if mods.alt { + y0 -= dy; + } + } + if mods.shift { + let k = if hx == 0 { + (y1 - y0).abs() + } else if hy == 0 { + (x1 - x0).abs() + } else { + (x1 - x0).abs().max((y1 - y0).abs()) + }; + let anchor = |lo: f64, hi: f64, h: i8| { + if mods.alt || h == 0 { + ((lo + hi - k) / 2., (lo + hi + k) / 2.) + } else if h < 0 { + (hi - k, hi) + } else { + (lo, lo + k) + } + }; + (x0, x1) = anchor(x0, x1, hx); + (y0, y1) = anchor(y0, y1, hy); + } + let [a, b, c, d, _, _] = f.transform.m; + let minimum = |n: f64, size: f64| n.signum().copysign(if n == 0.0 { 1.0 } else { n }) * n.abs().max(1.0 / size.max(1.0)); + let (w, h) = (minimum(x1 - x0, a.hypot(b)), minimum(y1 - y0, c.hypot(d))); + f.transform.mul(&Affine { m: [w, 0., 0., h, x0, y0] }) + } + } +} +fn update_preview(app: &mut PhotocraftApp) { + let Some(FrameDrag::Edit { layer, doc, revision, proposed, .. }) = app.ui.frame_tool.drag.as_ref() else { return }; + let Some(st) = app.session.active().filter(|st| st.doc.id == *doc && st.revision == *revision) else { + app.frame_preview = None; + return; + }; + let (id, revision, proposed) = (*layer, *revision, *proposed); + let mut shown = (*st.doc).clone(); + if let Some(l) = shown.layer_mut(id) { + if let Some(f) = &mut l.frame { + f.transform = proposed; + if !f.valid() { + app.frame_preview = None; + return; + } + } + photocraft_engine::frame_cmds::refresh(l); + } + let key = app.frame_preview.as_ref().map_or(1, |p| p.key.wrapping_add(1)); + app.frame_preview = Some(Preview { doc: std::sync::Arc::new(shown), revision, key }); +} +pub(crate) fn display_doc(app: &mut PhotocraftApp, idx: usize) -> Option<(std::sync::Arc, u64)> { + if let Some(t) = app.ui.transform.clone().filter(frame_transform) { + let transform = transformed_frame(app, &t).ok()?; + let st = app.session.documents().get(idx)?; + if app.transform_preview.as_ref().is_none_or(|pv| pv.doc.id != st.doc.id) { + return None; + } + use std::hash::Hasher; + let mut hash = std::collections::hash_map::DefaultHasher::new(); + hash.write_u64(t.session); + for value in transform.m { + hash.write_u64(value.to_bits()); + } + let key = hash.finish(); + if app.frame_preview.as_ref().is_none_or(|p| p.doc.id != st.doc.id || p.revision != st.revision || p.key != key) { + let mut doc = (*st.doc).clone(); + let l = doc.layer_mut(LayerId(t.layer))?; + l.frame.as_mut()?.transform = transform; + photocraft_engine::frame_cmds::refresh(l); + app.frame_preview = Some(Preview { doc: std::sync::Arc::new(doc), revision: st.revision, key }); + } + } + let st = app.session.documents().get(idx)?; + let p = app.frame_preview.as_ref()?; + (app.ui.tool == Tool::Frame && st.doc.id == p.doc.id && st.revision == p.revision).then(|| (p.doc.clone(), (1 << 57) | p.key)) +} +pub fn cancel(app: &mut PhotocraftApp) { + app.ui.frame_tool.drag = None; + app.frame_preview = None; +} +/// A native double click (also driven by ui.click count=2) toggles content-only selection. +pub fn double_click(app: &mut PhotocraftApp, p: [f64; 2]) { + let Some(id) = frame_at(app, p) else { return }; + let next = if selected(app).is_some_and(|l| l.id == id && target(app, l) == Target::Content) { Target::Both } else { Target::Content }; + select(app, id, next); + cancel(app); } - -/// 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 { - // ⌘ is the Move tool (`hold_keys::cmd_moves`): a press with it held is not this tool's, - // so it drags a guide or the layer (#6288). A drag already under way keeps its events. - if app.ui.tool != Tool::Frame || (app.ui.frame_tool.drag.is_none() && crate::canvas::event_tool(app, mods) != Tool::Frame) { + if app.ui.tool != Tool::Frame { return false; } - let (square, centred) = (mods.shift, mods.alt); + if app.ui.frame_tool.drag.is_none() && crate::canvas::event_tool(app, mods) != Tool::Frame { + return false; + } + let (x, y) = match ev { + ToolEvent::Down { x, y, .. } | ToolEvent::Move { x, y, .. } | ToolEvent::Up { x, y } => (x, y), + }; + if !x.is_finite() || !y.is_finite() || x.abs() > 600_000.0 || y.abs() > 600_000.0 { + cancel(app); + app.ui.status = tl!("Frame coordinates must be finite and within 600000 pixels").into(); + app.ui.status_error = true; + return true; + } + if app.ui.transform.is_none() { + app.ui.frame_tool.auto_transform = false; + } 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 }); + cancel(app); + let p = [x, y]; + let zoom = f64::from(app.point_zoom()); + let active = selected(app).map(|l| (l.id, l.frame.clone(), target(app, l))); + let selected_control = + active.as_ref().and_then(|(id, f, t)| (*t == Target::Frame).then(|| Some((*id, control_hit(f.as_ref()?, p, zoom)?))).flatten()); + let content_control = active.as_ref().is_some_and(|(id, _, t)| { + if *t != Target::Content { + return false; + } + let Some(st) = app.session.active() else { return false }; + let Some(child) = st.doc.layer(*id).and_then(|l| l.children()).and_then(|c| c.first()) else { return false }; + let b = photocraft_engine::transform_cmds::transform_frame(&st.doc, child); + let (x0, y0, x1, y1) = (f64::from(b.x0), f64::from(b.y0), f64::from(b.x1), f64::from(b.y1)); + [(x0, y0), ((x0 + x1) / 2., y0), (x1, y0), (x1, (y0 + y1) / 2.), (x1, y1), ((x0 + x1) / 2., y1), (x0, y1), (x0, (y0 + y1) / 2.)] + .iter() + .any(|(x, y)| (x - p[0]).hypot(y - p[1]) * zoom <= HANDLE_PX) + }); + let id = selected_control + .map(|(id, _)| id) + .or_else(|| content_control.then(|| active.as_ref().map(|(id, _, _)| *id)).flatten()) + .or_else(|| frame_at(app, p)); + if let Some(id) = id { + let Some(st) = app.session.active() else { return true }; + let Some(l) = st.doc.layer(id) else { return true }; + let Some(f) = l.frame.clone() else { return true }; + let locks = st.doc.effective_locks(id); + if locks.all || locks.position { + app.ui.status = tl!("The frame is locked").into(); + app.ui.status_error = true; + return true; + } + let t = if content_control { + Target::Content + } else if selected_control.is_some() || on_border(&f, p, zoom) || l.children().is_none_or(|c| c.is_empty()) { + Target::Frame + } else if active.as_ref().is_some_and(|(prev, _, t)| *prev == id && *t == Target::Content) { + Target::Content + } else { + Target::Both + }; + select(app, id, t); + if t != Target::Frame { + // The canvas's own context: preview textures loaded into another never draw. + let Some(ctx) = app.frame_tool_ctx.clone() else { return true }; + match crate::transform_tool::begin(app, &ctx) { + Ok(()) => { + app.ui.frame_tool.auto_transform = true; + crate::transform_tool::pointer(app, ev, mods); + } + Err(e) => { + app.ui.status = e; + app.ui.status_error = true; + } + } + return true; + } + let Some(st) = app.session.active() else { return true }; + app.ui.frame_tool.drag = Some(FrameDrag::Edit { + layer: id, + doc: st.doc.id, + revision: st.revision, + original: f.clone(), + proposed: f.transform, + start: p, + mode: selected_control.map_or(EditMode::Move, |(_, m)| m), + }); + } else if let Some(st) = app.session.active() { + app.ui.frame_tool.drag = + Some(FrameDrag::New { start: p, cur: p, square: mods.shift, centred: mods.alt, doc: st.doc.id, revision: st.revision }); } } ToolEvent::Move { x, y, .. } => { if let Some(d) = &mut app.ui.frame_tool.drag { - *d = FrameDrag { cur: [x, y], square, centred, ..*d }; + match d { + FrameDrag::New { cur, square, centred, .. } => { + *cur = [x, y]; + *square = mods.shift; + *centred = mods.alt; + } + FrameDrag::Edit { original, proposed, start, mode, .. } => *proposed = edit_transform(original, *mode, *start, [x, y], mods), + } } + update_preview(app); } 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] { + let Some(d) = app.ui.frame_tool.drag.take() else { return true }; + app.frame_preview = None; + let (doc, revision) = match &d { + FrameDrag::New { doc, revision, .. } | FrameDrag::Edit { doc, revision, .. } => (*doc, *revision), + }; + if !app.session.active().is_some_and(|st| st.doc.id == doc && st.revision == revision) { 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; + match d { + FrameDrag::New { start, .. } => { + if (x - start[0]).hypot(y - start[1]) * f64::from(app.point_zoom()) < CLICK_PX { + return true; + } + let r = drawn(start, [x, y], mods.shift, mods.alt); + if r[2] <= r[0] || r[3] <= r[1] { + return true; + } + let mut p = shape_params(app, r); + if let Some(id) = content_layer(app, r) { + p["layer"] = json!(id); + } + match app.run("layer.new.frame", p) { + Ok(v) => { + if let Some(id) = v.get("layer").and_then(Value::as_u64) { + select(app, LayerId(id), Target::Frame); + } + } + Err(e) => report(app, Err(e)), + } + } + FrameDrag::Edit { layer, original, start, mode, .. } => { + let transform = edit_transform(&original, mode, start, [x, y], mods); + if transform != original.transform { + let r = app.run("layer.frame.set", json!({"layer":layer.0,"transform":transform.m})); + report(app, r); + } + } } } } true } - -/// The frame a drag in progress would leave. +fn paint_path(painter: &egui::Painter, xf: &ViewXform, path: &photocraft_doc::Path, stroke: Stroke) { + for line in photocraft_vector::flatten::flatten_path(path, 0.5 / f64::from(xf.zoom).max(0.01)) { + let mut points: Vec = line.pts.iter().map(|&(x, y)| xf.to_screen(x as f32, y as f32)).collect(); + if line.closed + && let Some(first) = points.first().copied() + { + points.push(first); + } + painter.add(egui::Shape::line(points, stroke)); + } +} 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() + if let Some(st) = app.session.active() { + for (path, _, l) in st.doc.walk() { + if !path_visible(&st.doc, &path) { + continue; + } + let Some(f) = &l.frame else { continue }; + if l.children().is_some_and(|c| c.is_empty()) { + let q = f.corners().map(|p| xf.to_screen(p.x as f32, p.y as f32)); + paint_path(painter, xf, &f.outline(), Stroke::new(1., t.text_faint)); + painter.line_segment([q[0], q[2]], Stroke::new(1., t.text_faint)); + painter.line_segment([q[1], q[3]], Stroke::new(1., t.text_faint)); + } + } + } + if app.ui.tool != Tool::Frame { + return; + } + if let Some(FrameDrag::New { start, cur, square, centred, .. }) = &app.ui.frame_tool.drag { + if let Some(path) = outline(app, drawn(*start, *cur, *square, *centred)) { + paint_path(painter, xf, &path, stroke); + } + return; + } + let Some(l) = selected(app) else { return }; + if !visible(app, l.id) { + return; + } + let Some(original) = &l.frame else { return }; + let mut f = original.clone(); + if let Some(t) = app.ui.transform.as_ref().filter(|t| frame_transform(t)) + && let Ok(transform) = transformed_frame(app, t) + { + f.transform = transform; + } + if let Some(FrameDrag::Edit { proposed, .. }) = &app.ui.frame_tool.drag { + f.transform = *proposed; + } + if !f.valid() { + return; + } + paint_path(painter, xf, &f.outline(), stroke); + if app.ui.transform.is_some() { + return; + } + let target = target(app, l); + if target == Target::Content { + if let Some(st) = app.session.active() + && let Some(child) = l.children().and_then(|c| c.first()) + { + let b = photocraft_engine::transform_cmds::transform_frame(&st.doc, child); + let r = egui::Rect::from_two_pos(xf.to_screen(b.x0 as f32, b.y0 as f32), xf.to_screen(b.x1 as f32, b.y1 as f32)); + painter.rect_stroke(r, 0., stroke, StrokeKind::Inside); + for p in [r.left_top(), r.center_top(), r.right_top(), r.right_center(), r.right_bottom(), r.center_bottom(), r.left_bottom(), r.left_center()] { + paint_handle(painter, p, &t); + } + } + } else if target == Target::Frame { + for (p, _, _) in handles(&f) { + paint_handle(painter, xf.to_screen(p.x as f32, p.y as f32), &t); + } + } +} +fn paint_handle(p: &egui::Painter, at: Pos2, t: &Tokens) { + let r = egui::Rect::from_center_size(at, egui::vec2(6., 6.)); + p.rect_filled(r, 0., t.card); + p.rect_stroke(r, 0., Stroke::new(1., t.accent), StrokeKind::Inside); +} +pub fn cursor(app: &PhotocraftApp, p: [f64; 2]) -> Option { + let zoom = f64::from(app.point_zoom()); + if let Some(l) = selected(app) + && let Some(f) = &l.frame + && target(app, l) == Target::Frame + && let Some(hit) = control_hit(f, p, zoom) + { + return Some(match hit { + EditMode::Resize(0, _) => CursorIcon::ResizeVertical, + EditMode::Resize(_, 0) => CursorIcon::ResizeHorizontal, + EditMode::Resize(x, y) if x == y => CursorIcon::ResizeNwSe, + EditMode::Resize(..) => CursorIcon::ResizeNeSw, + _ => CursorIcon::Crosshair, + }); + } + frame_at(app, p).map(|_| CursorIcon::Move) +} +fn stroke_json(s: &photocraft_doc::ShapeStroke) -> Value { + let fill = match &s.paint { + photocraft_doc::Fill::Solid(c) => { + let [r, g, b] = c.to_rgb(); + json!([r, g, b, c.alpha]) + } + _ => Value::Null, }; - painter.add(egui::Shape::line(points, stroke)); + json!({"color":fill,"width":s.width,"opacity":s.opacity*100.,"align":match s.align{photocraft_doc::StrokeAlign::Inside=>"inside",photocraft_doc::StrokeAlign::Outside=>"outside",_=>"center"}}) +} +fn stroke_controls(ui: &mut egui::Ui, value: &mut Option) -> bool { + let before = value.clone(); + let mut enabled = value.is_some(); + if crate::widgets::checkbox(ui, &mut enabled, tl!("Stroke")).changed() { + *value = enabled.then(photocraft_doc::ShapeStroke::default); + } + if let Some(s) = value { + let c = match s.paint { + photocraft_doc::Fill::Solid(c) => c, + _ => photocraft_doc::Color::BLACK, + }; + let [r, g, b] = c.to_rgb(); + let mut rgba = [r, g, b, c.alpha]; + if ui.color_edit_button_rgba_unmultiplied(&mut rgba).changed() { + s.paint = photocraft_doc::Fill::Solid(photocraft_doc::Color::rgba(rgba[0], rgba[1], rgba[2], rgba[3])); + } + crate::widgets::value_field_named(ui, tl!("Stroke:"), &mut s.width, 0.0..=1000.0, "px", 58.0); + craft_ui::ComboBox::from_id_salt("frame-stroke-align") + .selected_text(match s.align { + photocraft_doc::StrokeAlign::Inside => tl!("Inside"), + photocraft_doc::StrokeAlign::Outside => tl!("Outside"), + _ => tl!("Center"), + }) + .show_ui(ui, |ui| { + for (a, label) in [ + (photocraft_doc::StrokeAlign::Inside, tl!("Inside")), + (photocraft_doc::StrokeAlign::Center, tl!("Center")), + (photocraft_doc::StrokeAlign::Outside, tl!("Outside")), + ] { + ui.selectable_value(&mut s.align, a, label); + } + }); + } + *value != before } - -/// 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; + app.frame_tool_ctx = Some(ui.ctx().clone()); + for (icon, shape, label) in [ + ("square", "rectangle", tl!("Create a new rectangular frame")), + ("circle", "ellipse", tl!("Create a new elliptical frame")), + ("triangle", "triangle", tl!("Create a new triangular frame")), + ("pentagon", "polygon", tl!("Create a new polygonal frame")), + ("shapes", "custom", tl!("Create a new custom frame")), + ] { + let current = if app.ui.frame_tool.ellipse { + "ellipse" + } else if app.ui.frame_tool.shape.is_empty() { + "rectangle" + } else { + &app.ui.frame_tool.shape + }; + if crate::icons::button(ui, icon, 24., current == shape, label).clicked() { + app.ui.frame_tool.shape = shape.into(); + app.ui.frame_tool.ellipse = shape == "ellipse"; + } } - if crate::icons::button(ui, "circle", 24.0, ellipse, tl!("Create a new elliptical frame")).clicked() { - app.ui.frame_tool.ellipse = true; + if app.ui.frame_tool.shape == "polygon" { + ui.label(tl!("Sides:")); + let mut n = app.ui.frame_tool.sides.clamp(3, 100) as f32; + crate::widgets::value_field_named(ui, tl!("Sides:"), &mut n, 3.0..=100.0, "", 44.); + app.ui.frame_tool.sides = n as u32; + } + if app.ui.frame_tool.shape == "custom" { + crate::preset_panels::shape_picker(app, ui); + } + crate::widgets::vline(ui, 22.); + let gesture = crate::vector_ui::paint_gesture(ui, ui.scope_id().with("frame-options-gesture")); + let coalesce = format!("frame-stroke-{}-{gesture}", ui.scope_id().value()); + let mut stroke = selected(app).and_then(|l| l.frame.as_ref()).map_or_else(|| app.ui.frame_tool.stroke.clone(), |f| f.stroke.clone()); + if stroke_controls(ui, &mut stroke) { + app.ui.frame_tool.stroke = stroke.clone(); + if let Some(id) = selected(app).map(|l| l.id) { + let params = stroke.as_ref().map(stroke_json).unwrap_or(Value::Null); + let r = app.run("layer.frame.set", json!({"layer":id.0,"stroke":params,"coalesce":coalesce})); + report(app, r); + } } 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); +/// Frame-aware Properties: W/H/X/Y edit the container; the content can be selected/fitted/replaced. +pub fn properties(app: &mut PhotocraftApp, ui: &mut egui::Ui, l: &Layer) { + let Some(f) = &l.frame else { return }; + if app.session.active().is_some_and(|st| { + let locks = st.doc.effective_locks(l.id); + locks.all || locks.position + }) { + ui.disable(); } - - /// 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); + let gesture = crate::vector_ui::paint_gesture(ui, ui.scope_id().with("frame-properties-gesture")); + let coalesce = format!("frame-properties-{}-{gesture}", l.id.0); + let [a, b, c, d, x, y] = f.transform.m; + let (w, h) = (a.hypot(b), c.hypot(d)); + let mut values = [w as f32, h as f32, x as f32, y as f32]; + let mut changed = false; + ui.label(tl!("Frame")); + ui.horizontal(|ui| { + for (i, label) in [(0, tl!("W")), (1, tl!("H"))] { + ui.label(label); + if let Some(v) = values.get_mut(i) { + changed |= crate::widgets::value_field_named(ui, label, v, 1.0..=300_000.0, "px", 66.).changed(); + } + } + }); + ui.horizontal(|ui| { + for (i, label) in [(2, tl!("X")), (3, tl!("Y"))] { + ui.label(label); + if let Some(v) = values.get_mut(i) { + changed |= crate::widgets::value_field_named(ui, label, v, -300_000.0..=300_000.0, "px", 66.).changed(); + } + } + }); + if changed && w > 0. && h > 0. { + let [nw, nh, nx, ny] = values; + let r = app.run( + "layer.frame.set", + json!({"layer":l.id.0,"transform":[a*f64::from(nw)/w,b*f64::from(nw)/w,c*f64::from(nh)/h,d*f64::from(nh)/h,nx,ny],"coalesce":coalesce}), + ); + report(app, r); + } + let mut stroke = f.stroke.clone(); + ui.horizontal_wrapped(|ui| { + if stroke_controls(ui, &mut stroke) { + let r = app.run("layer.frame.set", json!({"layer":l.id.0,"stroke":stroke.as_ref().map(stroke_json).unwrap_or(Value::Null),"coalesce":coalesce})); + report(app, r); + } + }); + ui.separator(); + ui.horizontal_wrapped(|ui| { + if ui.selectable_label(target(app, l) == Target::Frame, tl!("Frame")).clicked() { + select(app, l.id, Target::Frame); + } + if l.children().is_some_and(|c| !c.is_empty()) { + if ui.selectable_label(target(app, l) == Target::Content, tl!("Image")).clicked() { + select(app, l.id, Target::Content); + } + if ui.selectable_label(target(app, l) == Target::Both, tl!("Both")).clicked() { + select(app, l.id, Target::Both); + } + } + }); + if ui.button(if l.children().is_some_and(|c| !c.is_empty()) { tl!("Replace Image…") } else { tl!("Import Image…") }).clicked() { + select(app, l.id, Target::Frame); + let ctx = ui.ctx().clone(); + let r = crate::menus::invoke(app, &ctx, "file.placeEmbedded", json!({})); + report(app, r); + } + if l.children().is_some_and(|c| !c.is_empty()) { + for (mode, label) in [("contentToFrame", tl!("Fit Content to Frame")), ("frameToContent", tl!("Fit Frame to Content"))] { + if ui.button(label).clicked() { + let r = app.run("layer.frame.fit", json!({"layer":l.id.0,"mode":mode})); + report(app, r); + } + } } } +#[cfg(test)] +mod tests; + +/// A compact on-canvas import/replace bar, following the currently selected frame. +pub fn task_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, xf: &ViewXform) { + if app.ui.tool != Tool::Frame || app.ui.frame_tool.drag.is_some() || app.ui.transform.is_some() || !app.ui.dialogs.is_empty() { + return; + } + let Some(l) = selected(app) else { return }; + if !visible(app, l.id) { + return; + } + let (id, empty) = (l.id, l.children().is_none_or(|c| c.is_empty())); + let Some(f) = &l.frame else { return }; + let bounds = f.bounds(); + let p = xf.to_screen((f64::from(bounds.x0) + f64::from(bounds.x1)) as f32 / 2., bounds.y1 as f32); + let width = if empty { 170.0 } else { 290.0 }; + let at = egui::pos2( + (p.x - width / 2.).clamp(xf.rect.left() + 8., (xf.rect.right() - width - 8.).max(xf.rect.left() + 8.)), + (p.y + 18.).min(xf.rect.bottom() - 42.).max(xf.rect.top() + 8.), + ); + let ctx = ui.ctx().clone(); + let t = Tokens::get(&ctx); + egui::Area::new(egui::Id::unique("frame-context-bar")).order(egui::Order::Middle).fixed_pos(at).show(&ctx, |ui| { + egui::Frame::NONE.fill(t.card).stroke(Stroke::new(1., t.field_border)).corner_radius(t.radius).inner_margin(6.).show(ui, |ui| { + ui.horizontal(|ui| { + if ui.button(if empty { tl!("Import Image…") } else { tl!("Replace Image…") }).clicked() { + select(app, id, Target::Frame); + let r = crate::menus::invoke(app, &ctx, "file.placeEmbedded", json!({})); + report(app, r); + } + if !empty && ui.button(tl!("Fit Content to Frame")).clicked() { + let r = app.run("layer.frame.fit", json!({"layer":id.0})); + report(app, r); + } + }); + }); + }); +} + +/// Free Transform on the frame thumbnail edits the clipping geometry, leaving its image intact. +pub(crate) fn frame_transform(t: &crate::state::TransformSession) -> bool { + t.target.as_ref().and_then(|v| v.get("frame")).and_then(Value::as_u64) == Some(t.layer) +} +pub(crate) fn transformed_frame(app: &PhotocraftApp, t: &crate::state::TransformSession) -> Result { + if t.warp.is_some() { + return Err(tl!("A frame supports affine transforms; select its image to warp it").into()); + } + let [x0, y0, x1, y1] = t.rect; + let (w, h) = (x1 - x0, y1 - y0); + let [q0, q1, q2, q3] = t.quad; + if w <= 0. + || h <= 0. + || !t.quad.iter().flatten().all(|v| v.is_finite()) + || ((q1[0] + q3[0] - q0[0]) - q2[0]).abs() > 0.001 + || ((q1[1] + q3[1] - q0[1]) - q2[1]).abs() > 0.001 + { + return Err(tl!("A frame supports affine transforms; select its image for perspective transforms").into()); + } + let (a, b, c, d) = ((q1[0] - q0[0]) / w, (q1[1] - q0[1]) / w, (q3[0] - q0[0]) / h, (q3[1] - q0[1]) / h); + let map = Affine { m: [a, b, c, d, q0[0] - a * x0 - c * y0, q0[1] - b * x0 - d * y0] }; + let original = app + .session + .active() + .and_then(|st| st.doc.layer(LayerId(t.layer))) + .and_then(|l| l.frame.as_ref()) + .ok_or_else(|| tl!("The frame is unavailable").to_string())?; + let mut f = original.clone(); + f.transform = map.mul(&f.transform); + if !f.valid() { + return Err(tl!("Invalid frame transform").into()); + } + Ok(f.transform) +} + +/// Arrow keys respect which thumbnail is selected; Shift moves ten document pixels. +pub fn keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { + if app.ui.tool != Tool::Frame + || app.ui.transform.is_some() + || app.ui.frame_tool.drag.is_some() + || ctx.input(|i| i.modifiers.command || i.modifiers.ctrl || i.modifiers.alt) + { + return false; + } + let Some(l) = selected(app) else { return false }; + let (id, t, frame, child) = (l.id, target(app, l), l.frame.clone(), l.children().and_then(|c| c.first()).map(|l| l.id)); + for (key, dx, dy) in [(egui::Key::ArrowLeft, -1., 0.), (egui::Key::ArrowRight, 1., 0.), (egui::Key::ArrowUp, 0., -1.), (egui::Key::ArrowDown, 0., 1.)] { + for mods in [egui::Modifiers::SHIFT, egui::Modifiers::NONE] { + if ctx.input_mut(|i| i.consume_key(mods, key)) { + let k = if mods.shift { 10. } else { 1. }; + app.nudge_bundle.now = ctx.input(|i| i.time); + let (command, params) = if t == Target::Frame { + let Some(mut f) = frame.clone() else { return true }; + f.transform = Affine::translate(dx * k, dy * k).mul(&f.transform); + ("layer.frame.set", json!({"layer":id.0,"transform":f.transform.m})) + } else { + ("layer.translate", json!({"layer":if t==Target::Content{child.unwrap_or(id).0}else{id.0},"dx":dx*k,"dy":dy*k})) + }; + let r = crate::nudge_bundle::run(app, "frame", command, params); + report(app, r); + return true; + } + } + } + false +} diff --git a/crates/ui-egui/src/tools/frame_tool/tests.rs b/crates/ui-egui/src/tools/frame_tool/tests.rs new file mode 100644 index 0000000000..f0be9a649f --- /dev/null +++ b/crates/ui-egui/src/tools/frame_tool/tests.rs @@ -0,0 +1,572 @@ +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, TestMask(l.vector_mask.as_ref().unwrap().path.clone())) + }; + 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); +} + +struct TestMask(photocraft_doc::Path); +impl TestMask { + fn value(&self, x: i32, y: i32) -> f32 { + photocraft_vector::path_coverage(&self.0, Rect::new(x, y, x + 1, y + 1))[0] + } +} + +fn app() -> PhotocraftApp { + 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; + app.ui.tool = Tool::Frame; + app +} + +#[test] +fn markers_survive_release_and_handles_resize_the_frame_without_creating_another() { + let mut app = app(); + drag(&mut app, [20., 30.], [120., 110.]); + let id = selected(&app).unwrap().id; + let count = app.session.active().unwrap().doc.layer_count(); + let ctx = egui::Context::default(); + let xf = ViewXform { + rect: egui::Rect::from_min_size(Pos2::ZERO, egui::vec2(400., 300.)), + zoom: 1.0, + center: [200., 150.], + flip: false, + rotation: 0., + aspect: 1., + }; + let mut output = ctx.run_ui(egui::RawInput::default(), |ui| draw_overlay(&app, ui.painter(), &xf)); + output.textures_delta.clear(); + assert!(app.ui.frame_tool.drag.is_none()); + assert!(output.shapes.iter().filter(|s| matches!(s.shape, egui::Shape::Rect(_))).count() >= 8, "eight visible handles after release"); + drag(&mut app, [120., 110.], [145., 130.]); + assert_eq!(app.session.active().unwrap().doc.layer_count(), count, "resizing does not create another frame"); + assert_eq!(selected(&app).unwrap().id, id); + assert_eq!(selected(&app).unwrap().frame.as_ref().unwrap().transform.m, [125., 0., 0., 100., 20., 30.]); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(selected(&app).unwrap().frame.as_ref().unwrap().transform.m, [100., 0., 0., 80., 20., 30.]); +} + +#[test] +fn dragging_border_moves_only_frame_and_escape_discards_live_preview() { + let mut app = app(); + drag(&mut app, [20., 30.], [120., 110.]); + let before = selected(&app).unwrap().frame.clone(); + let entries = app.session.active().unwrap().history.entries(); + pointer(&mut app, ToolEvent::Down { x: 50., y: 30., pressure: 1. }, egui::Modifiers::NONE); + pointer(&mut app, ToolEvent::Move { x: 80., y: 50., pressure: 1. }, egui::Modifiers::NONE); + assert_eq!(selected(&app).unwrap().frame, before, "preview never changes document"); + assert!(app.frame_preview.is_some()); + let ctx = egui::Context::default(); + ctx.begin_pass(egui::RawInput { + events: vec![egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }], + ..Default::default() + }); + crate::shortcuts::handle(&mut app, &ctx); + ctx.end_pass().textures_delta.clear(); + assert!(app.frame_preview.is_none()); + assert!(app.ui.frame_tool.drag.is_none()); + assert_eq!(app.session.active().unwrap().history.entries(), entries); + drag(&mut app, [50., 30.], [80., 50.]); + assert_eq!(selected(&app).unwrap().frame.as_ref().unwrap().transform.m, [100., 0., 0., 80., 50., 50.]); +} + +#[test] +fn frame_content_and_both_selection_follow_clicks_and_double_clicks() { + let mut app = app(); + let source = app + .session + .edit("Photo", |doc, active| { + let mut l = Layer::raster("Photo", doc.pixel_format()); + l.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 200, 200), &[1., 0., 0., 1.]); + let id = l.id; + doc.layers.push(l); + *active = Some(id); + Ok(id) + }) + .unwrap(); + drag(&mut app, [20., 30.], [120., 110.]); + let frame = selected(&app).unwrap().id; + let original = selected(&app).unwrap().frame.clone(); + double_click(&mut app, [65., 65.]); + assert_eq!(app.ui.frame_tool.target, Target::Content); + assert_eq!(app.session.active().unwrap().active_layer, Some(source)); + double_click(&mut app, [65., 65.]); + assert_eq!(app.ui.frame_tool.target, Target::Both); + assert_eq!(app.session.active().unwrap().active_layer, Some(frame)); + drag(&mut app, [50., 30.], [65., 40.]); + assert_eq!(app.ui.frame_tool.target, Target::Frame); + assert_ne!(selected(&app).unwrap().frame, original); + let source_before = app.session.active().unwrap().doc.layer(source).unwrap().clone(); + double_click(&mut app, [70., 75.]); + let f = selected(&app).unwrap().frame.clone(); + let ctx = egui::Context::default(); + crate::PhotocraftApp::setup_context(&ctx, Default::default()); + ctx.begin_pass(Default::default()); + app.frame_tool_ctx = Some(ctx.clone()); + drag(&mut app, [70., 75.], [85., 85.]); + ctx.end_pass().textures_delta.clear(); + assert!(!app.ui.frame_tool.auto_transform); + assert!(app.ui.transform.is_none()); + assert_eq!(selected(&app).unwrap().frame, f, "image-only transform leaves the mask"); + assert_ne!(app.session.active().unwrap().doc.layer(source).unwrap(), &source_before); +} + +#[test] +fn modifiers_shape_selection_and_invalid_control_params_are_consistent() { + let mut app = app(); + let ctx = egui::Context::default(); + let call = |app: &mut PhotocraftApp, p: Value| { + let (req, _) = crate::control::ControlRequest::new("ui.set", p); + let crate::control::Outcome::Done(v) = crate::control::handle(app, &ctx, &req) else { panic!("immediate state update") }; + v + }; + assert_eq!(call(&mut app, json!({"frameShape":"triangle","frameSides":6}))["ok"], true); + assert_eq!(call(&mut app, json!({"frameShape":"invalid","tool":"brush"}))["ok"], false); + assert_eq!(app.ui.tool, Tool::Frame); + assert_eq!(call(&mut app, json!({"frameSides":100000}))["ok"], false); + let mods = egui::Modifiers { shift: true, alt: true, ..Default::default() }; + pointer(&mut app, ToolEvent::Down { x: 100., y: 100., pressure: 1. }, mods); + pointer(&mut app, ToolEvent::Up { x: 130., y: 120. }, mods); + let f = selected(&app).unwrap().frame.as_ref().unwrap(); + assert_eq!(f.bounds(), Rect::new(70, 70, 130, 130)); + assert_eq!(TestMask(f.outline()).value(70, 70), 0.0, "triangle rather than bounding rectangle"); + let frame = selected(&app).unwrap().id; + let content = app + .session + .edit("Image", |doc, _| { + let mut l = Layer::raster("Photo", doc.pixel_format()); + l.surface_mut().unwrap().fill_rect(Rect::new(20, 20, 100, 100), &[1., 0., 0., 1.]); + let id = l.id; + doc.layers.push(l); + Ok(id) + }) + .unwrap(); + app.run("layer.frame.setContent", json!({"layer":frame.0,"content":content.0})).unwrap(); + assert_eq!(call(&mut app, json!({"frameTarget":"content"}))["ok"], true); + assert_eq!(app.session.active().unwrap().active_layer, Some(content)); + assert_eq!(call(&mut app, json!({"frameTarget":"both"}))["ok"], true); + assert_eq!(app.session.active().unwrap().active_layer, Some(frame)); +} + +#[test] +fn frame_creation_handles_render_at_native_scales() { + let Some(out) = std::env::var_os("PHOTOCRAFT_FRAME_SNAPSHOTS") else { return }; + let _guard = photocraft_testkit::gpu_lock(); + let out = std::path::PathBuf::from(out); + std::fs::create_dir_all(&out).unwrap(); + for theme in crate::theme::ThemeKind::ALL { + for (width, height) in [(1280.0, 720.0), (800.0, 480.0)] { + for scale in [1.0, 2.0] { + let mut app = app(); + app.ui.theme = theme; + app.run("prefs.set", json!({"path":"interface.theme","value":theme.id()})).unwrap(); + app.custom_titlebar = true; + app.session.prefs.edit(|p| p.general.animated_zoom = false); + drag(&mut app, [20.0, 30.0], [180.0, 130.0]); + let empty = selected(&app).unwrap().id; + let source = app + .session + .edit("Synthetic image", |doc, active| { + let mut layer = Layer::raster("Sample", doc.pixel_format()); + for y in 0..100 { + for x in 0..100 { + layer.surface_mut().unwrap().write_pixel(x + 200, y + 60, &[x as f32 / 100.0, y as f32 / 100.0, 0.7, 1.0]); + } + } + let id = layer.id; + doc.layers.push(layer); + *active = Some(id); + Ok(id) + }) + .unwrap(); + app.run("layer.new.frame",json!({"x":210,"y":70,"width":120,"height":160,"shape":"ellipse","layer":source.0,"stroke":{"color":"#50a0ef","width":4,"align":"outside"}})).unwrap(); + select(&mut app, empty, Target::Frame); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(width, height)).with_pixels_per_point(scale).wgpu().build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, theme); + if let Some(rs) = cc.wgpu_render_state.as_ref() { + app.set_wgpu(rs.clone()); + } + app + }); + h.run_steps(6); + assert_eq!(h.state().ui.theme, theme); + let img = h.render().unwrap(); + assert_eq!((img.width(), img.height()), ((width * scale) as u32, (height * scale) as u32)); + img.save(out.join(format!("frame-{theme:?}-{width}-{scale}x.png"))).unwrap(); + } + } + } +} + +#[test] +fn free_transform_on_the_frame_thumbnail_previews_and_commits_only_the_clip() { + let mut app = app(); + let source = app + .session + .edit("Photo", |doc, active| { + let mut l = Layer::raster("Photo", doc.pixel_format()); + l.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 200, 200), &[1., 0., 0., 1.]); + let id = l.id; + doc.layers.push(l); + *active = Some(id); + Ok(id) + }) + .unwrap(); + drag(&mut app, [20., 30.], [120., 110.]); + let frame = selected(&app).unwrap().id; + let original = app.session.active().unwrap().doc.layer(source).unwrap().clone(); + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, Default::default()); + ctx.begin_pass(Default::default()); + crate::transform_tool::begin(&mut app, &ctx).unwrap(); + assert!(frame_transform(app.ui.transform.as_ref().unwrap())); + app.ui.transform.as_mut().unwrap().quad = [[40., 40.], [90., 40.], [90., 80.], [40., 80.]]; + let (shown, _) = crate::canvas::display_doc(&mut app, 0); + assert_eq!(shown.layer(frame).unwrap().frame.as_ref().unwrap().bounds(), Rect::new(40, 40, 90, 80)); + assert_eq!(shown.layer(source).unwrap(), &original); + assert_eq!(selected(&app).unwrap().frame.as_ref().unwrap().bounds(), Rect::new(20, 30, 120, 110)); + crate::transform_tool::commit(&mut app); + assert!(app.ui.transform.is_none()); + assert_eq!(selected(&app).unwrap().frame.as_ref().unwrap().bounds(), Rect::new(40, 40, 90, 80)); + assert_eq!(app.session.active().unwrap().doc.layer(source).unwrap(), &original); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(selected(&app).unwrap().frame.as_ref().unwrap().bounds(), Rect::new(20, 30, 120, 110)); + crate::transform_tool::begin(&mut app, &ctx).unwrap(); + app.ui.transform.as_mut().unwrap().quad = [[50., 50.], [100., 50.], [100., 90.], [50., 90.]]; + crate::transform_tool::cancel(&mut app); + assert_eq!(selected(&app).unwrap().frame.as_ref().unwrap().bounds(), Rect::new(20, 30, 120, 110)); + ctx.end_pass().textures_delta.clear(); +} + +#[test] +fn real_canvas_clicks_select_both_then_double_click_selects_the_image() { + let mut app = app(); + app.session + .edit("Photo", |doc, active| { + let mut l = Layer::raster("Photo", doc.pixel_format()); + l.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 200, 200), &[1., 0., 0., 1.]); + let id = l.id; + doc.layers.push(l); + *active = Some(id); + Ok(()) + }) + .unwrap(); + drag(&mut app, [20., 30.], [120., 110.]); + let frame = selected(&app).unwrap().id; + let mut h = egui_kittest::Harness::builder().with_step_dt(1.0 / 60.0).with_size(egui::vec2(1000., 700.)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + app.frame_tool_ctx = Some(ui.ctx().clone()); + crate::canvas::document_area(app, ui); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, Default::default()); + h.run_steps(4); + let p = ViewXform::active(h.state()).unwrap().to_screen(65., 65.); + for press in [true, false] { + h.event(egui::Event::PointerMoved(p)); + h.event(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed: press, modifiers: egui::Modifiers::NONE }); + h.step(); + } + assert_eq!(h.state().ui.frame_tool.target, Target::Both); + assert_eq!(h.state().session.active().unwrap().active_layer, Some(frame)); + for press in [true, false] { + h.event(egui::Event::PointerMoved(p)); + h.event(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed: press, modifiers: egui::Modifiers::NONE }); + h.step(); + } + assert_eq!(h.state().ui.frame_tool.target, Target::Content); + assert_ne!(h.state().session.active().unwrap().active_layer, Some(frame)); +} + +#[test] +fn hostile_frame_pointer_coordinates_never_publish_an_invalid_preview() { + let mut app = app(); + app.ui.frame_tool.shape = "custom".into(); + let before = app.session.active().unwrap().doc.clone(); + for x in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, f64::MAX, f64::MIN, 1e30, -1e30] { + assert!(pointer(&mut app, ToolEvent::Down { x, y: 30., pressure: 1. }, Default::default())); + pointer(&mut app, ToolEvent::Move { x: -x, y: 40., pressure: 1. }, Default::default()); + pointer(&mut app, ToolEvent::Up { x, y: 50. }, Default::default()); + assert!(app.ui.frame_tool.drag.is_none()); + assert!(app.frame_preview.is_none()); + assert_eq!(app.session.active().unwrap().doc.layers, before.layers); + } +} + +#[test] +fn frame_keyboard_nudges_change_only_the_selected_thumbnail() { + let mut app = app(); + app.session + .edit("Photo", |doc, active| { + let mut l = Layer::raster("Photo", doc.pixel_format()); + l.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 200, 200), &[1., 0., 0., 1.]); + let id = l.id; + doc.layers.push(l); + *active = Some(id); + Ok(()) + }) + .unwrap(); + drag(&mut app, [20., 30.], [120., 110.]); + let frame = selected(&app).unwrap().id; + let child = selected(&app).unwrap().children().unwrap()[0].clone(); + let ctx = egui::Context::default(); + for (key, mods) in [(egui::Key::ArrowRight, egui::Modifiers::NONE), (egui::Key::ArrowDown, egui::Modifiers::SHIFT)] { + ctx.begin_pass(egui::RawInput { + events: vec![egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: mods }], + ..Default::default() + }); + assert!(keys(&mut app, &ctx)); + ctx.end_pass().textures_delta.clear(); + } + assert_eq!(selected(&app).unwrap().frame.as_ref().unwrap().bounds(), Rect::new(21, 40, 121, 120)); + assert_eq!(app.session.active().unwrap().doc.layer(child.id).unwrap(), &child); + select(&mut app, frame, Target::Content); + let f = selected(&app).unwrap().frame.clone(); + ctx.begin_pass(egui::RawInput { + events: vec![egui::Event::Key { key: egui::Key::ArrowRight, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }], + ..Default::default() + }); + assert!(keys(&mut app, &ctx)); + ctx.end_pass().textures_delta.clear(); + assert_eq!(selected(&app).unwrap().frame, f); + assert_ne!(app.session.active().unwrap().doc.layer(child.id).unwrap(), &child); +} + +#[test] +fn hidden_frame_ancestors_hide_placeholders_and_handles() { + let mut app = app(); + drag(&mut app, [20., 30.], [120., 110.]); + let id = selected(&app).unwrap().id; + app.session + .edit("Hide group", |doc, _| { + let frame = doc.remove(id).unwrap(); + let mut parent = Layer::group("Hidden", vec![frame]); + parent.visible = false; + doc.layers.push(parent); + Ok(()) + }) + .unwrap(); + assert_eq!(frame_at(&app, [50., 50.]), None); + let ctx = egui::Context::default(); + let xf = ViewXform { + rect: egui::Rect::from_min_size(Pos2::ZERO, egui::vec2(400., 300.)), + zoom: 1., + center: [200., 150.], + flip: false, + rotation: 0., + aspect: 1., + }; + let mut output = ctx.run_ui(Default::default(), |ui| draw_overlay(&app, ui.painter(), &xf)); + output.textures_delta.clear(); + assert!(output.shapes.iter().all(|s| matches!(s.shape, egui::Shape::Noop))); +} + +#[test] +fn drawing_a_frame_with_another_frames_image_selected_leaves_that_image_in_place() { + let mut app = app(); + let source = app + .session + .edit("Photo", |doc, active| { + let mut l = Layer::raster("Photo", doc.pixel_format()); + l.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 200, 200), &[1., 0., 0., 1.]); + let id = l.id; + doc.layers.push(l); + *active = Some(id); + Ok(id) + }) + .unwrap(); + drag(&mut app, [20., 30.], [120., 110.]); + let first = selected(&app).unwrap().id; + double_click(&mut app, [65., 65.]); + assert_eq!(app.session.active().unwrap().active_layer, Some(source)); + // Starts outside the first frame but overlaps the image's own bounds. + drag(&mut app, [150., 150.], [250., 250.]); + let doc = &app.session.active().unwrap().doc; + assert_eq!(photocraft_engine::frame_cmds::frame_of(doc, source), Some(first), "the image stays in its frame"); + let second = selected(&app).unwrap(); + assert_ne!(second.id, first); + assert!(second.children().unwrap().is_empty(), "the new frame is empty"); +} + +/// Esc during a frame's content drag ends its automatic transform: a Free Transform started +/// afterwards waits for Enter instead of committing on its first pointer release. +#[test] +fn cancelling_a_frame_content_drag_clears_its_auto_commit() { + let mut app = app(); + app.session + .edit("Photo", |doc, active| { + let mut l = Layer::raster("Photo", doc.pixel_format()); + l.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 200, 200), &[1., 0., 0., 1.]); + let id = l.id; + doc.layers.push(l); + *active = Some(id); + Ok(id) + }) + .unwrap(); + drag(&mut app, [20., 30.], [120., 110.]); + double_click(&mut app, [65., 65.]); + let ctx = egui::Context::default(); + crate::PhotocraftApp::setup_context(&ctx, Default::default()); + ctx.begin_pass(Default::default()); + app.frame_tool_ctx = Some(ctx.clone()); + tool_event(&mut app, ToolEvent::Down { x: 70., y: 75., pressure: 1.0 }, egui::Modifiers::NONE); + assert!(app.ui.frame_tool.auto_transform, "a content drag transforms automatically"); + crate::transform_tool::cancel(&mut app); + ctx.end_pass().textures_delta.clear(); + assert!(app.ui.transform.is_none()); + assert!(!app.ui.frame_tool.auto_transform); +} + +/// Double-clicking a frame's content thumbnail opens a Smart Object's contents; a pixel layer +/// inside a frame (as PSD files can hold) has no contents to open. +#[test] +fn double_clicking_frame_content_opens_only_smart_objects() { + use egui::{Event, PointerButton, vec2}; + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 400, "height": 300})).unwrap(); + let photo = s.execute("layer.new.layer", json!({"name": "Photo"})).unwrap()["layer"].as_u64().unwrap(); + s.execute("edit.fill", json!({"contents": "black"})).unwrap(); + let smart = s.execute("layer.new.frame", json!({"x": 10, "y": 10, "width": 100, "height": 80, "layer": photo})).unwrap()["layer"].as_u64().unwrap(); + let pixels = s.execute("layer.new.frame", json!({"x": 200, "y": 10, "width": 100, "height": 80})).unwrap()["layer"].as_u64().unwrap(); + s.edit("Pixels", |doc, _| { + let l = Layer::raster("Pixels", doc.pixel_format()); + doc.layer_mut(LayerId(pixels)).and_then(Layer::children_mut).unwrap().push(l); + Ok(()) + }) + .unwrap(); + let mut h = egui_kittest::Harness::builder().with_size(vec2(1440.0, 900.0)).with_step_dt(1.0 / 60.0).with_max_steps(64).build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + PhotocraftApp::new(s, crate::Services::default()) + }); + let ctx = h.ctx.clone(); + let (r, _) = crate::control::ControlRequest::new("ui.set", json!({"dock": {"collapsed": ["color", "properties", "history", "navigator"]}})); + crate::control::handle(h.state_mut(), &ctx, &r); + h.run_steps(8); + let double_click_content = |h: &mut egui_kittest::Harness, layer: u64| { + // Past egui's double-click window, so the last pair's clicks don't run on into these. + h.run_steps(30); + let row = crate::layer_row_ui::recorded(&h.ctx).into_iter().find(|r| r.layer == layer).unwrap(); + let thumb = row.thumbnail.unwrap(); + let at = thumb.center() + vec2(thumb.width() + 6.0, 0.0); + h.hover_at(at); + h.run_steps(1); + for _ in 0..2 { + h.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }); + h.run_steps(1); + h.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); + h.run_steps(1); + } + h.run_steps(3); + }; + double_click_content(&mut h, pixels); + assert_eq!(h.state().session.documents().len(), 1, "a pixel layer has no contents to open"); + assert!(!h.state().ui.status_error, "{}", h.state().ui.status); + double_click_content(&mut h, smart); + assert_eq!(h.state().session.documents().len(), 2, "the Smart Object's contents open"); +} + +#[test] +fn filled_frame_closing_border_selects_frame() { + let mut app = app(); + app.session + .edit("Photo", |doc, active| { + let mut l = Layer::raster("Photo", doc.pixel_format()); + l.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 200, 200), &[1., 0., 0., 1.]); + let id = l.id; + doc.layers.push(l); + *active = Some(id); + Ok(id) + }) + .unwrap(); + drag(&mut app, [20., 30.], [120., 110.]); + double_click(&mut app, [65., 65.]); + pointer(&mut app, ToolEvent::Down { x: 20., y: 50., pressure: 1. }, egui::Modifiers::NONE); + assert_eq!(app.ui.frame_tool.target, Target::Frame); + assert!(matches!(app.ui.frame_tool.drag, Some(FrameDrag::Edit { .. }))); +} + +#[test] +fn overhanging_content_handles_start_transform_and_cancel() { + let mut app = app(); + app.session + .edit("Photo", |doc, active| { + let mut l = Layer::raster("Photo", doc.pixel_format()); + l.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 200, 100), &[1., 0., 0., 1.]); + let id = l.id; + doc.layers.push(l); + *active = Some(id); + Ok(id) + }) + .unwrap(); + drag(&mut app, [20., 30.], [120., 110.]); + double_click(&mut app, [65., 65.]); + let ctx = egui::Context::default(); + crate::PhotocraftApp::setup_context(&ctx, Default::default()); + ctx.begin_pass(Default::default()); + app.frame_tool_ctx = Some(ctx.clone()); + let st = app.session.active().unwrap(); + let frame = selected(&app).unwrap(); + let child = frame.children().unwrap().first().unwrap(); + let b = photocraft_engine::transform_cmds::transform_frame(&st.doc, child); + assert!(b.x0 < 20, "image must overhang the frame: {b:?}"); + let entries = st.history.entries(); + for (x, y) in [(f64::from(b.x0), f64::from(b.y0)), (f64::from(b.x0), f64::from(b.y0 + b.y1) / 2.)] { + tool_event(&mut app, ToolEvent::Down { x, y, pressure: 1. }, egui::Modifiers::NONE); + assert!(app.ui.transform.is_some()); + assert!(app.ui.frame_tool.auto_transform); + crate::transform_tool::cancel(&mut app); + assert!(app.ui.transform.is_none()); + } + assert_eq!(app.session.active().unwrap().history.entries(), entries); + ctx.end_pass().textures_delta.clear(); +} diff --git a/crates/ui-egui/src/tools/tool_reset.rs b/crates/ui-egui/src/tools/tool_reset.rs index 4a6ee2c2d8..e1f31e8e32 100644 --- a/crates/ui-egui/src/tools/tool_reset.rs +++ b/crates/ui-egui/src/tools/tool_reset.rs @@ -69,6 +69,10 @@ pub fn confirm(app: &mut PhotocraftApp) -> Result { /// Reset Tool: `tool`'s options, its selection mode and its brush. fn reset_tool(app: &mut PhotocraftApp, tool: Tool) { + if tool == Tool::Frame { + crate::frame_tool::cancel(app); + app.ui.frame_tool = Default::default(); + } reset_options(&mut app.ui.tool_options, tool); if is_selection_tool(tool) { app.ui.selection_mode = 0; @@ -83,6 +87,8 @@ fn reset_tool(app: &mut PhotocraftApp, tool: Tool) { /// Reset All Tools: every option, the selection mode and every tool's brush. fn reset_all(app: &mut PhotocraftApp) { + crate::frame_tool::cancel(app); + app.ui.frame_tool = Default::default(); app.ui.tool_options = ToolOptions::default(); app.ui.selection_mode = 0; app.ui.tool_brushes.clear(); diff --git a/crates/ui-egui/src/tools/transform_tool/begin.rs b/crates/ui-egui/src/tools/transform_tool/begin.rs index 8411f747ff..ee5d58e952 100644 --- a/crates/ui-egui/src/tools/transform_tool/begin.rs +++ b/crates/ui-egui/src/tools/transform_tool/begin.rs @@ -37,6 +37,8 @@ pub fn begin(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String> return begin_several(app, ctx, doc, revision, id, targets); } let layer = doc.layer(id).ok_or("no layer")?; + let frame_only = + app.ui.tool == crate::state::Tool::Frame && layer.frame.is_some() && crate::frame_tool::target(app, layer) == crate::frame_tool::Target::Frame; if photocraft_engine::transform_cmds::locked_for_transform(&doc, id) { // Photoshop refuses before the box opens rather than when it is committed (#2585). app.ui.open_dialog(crate::state::DialogKind::Error, json!({"message": tl!(LOCKED)}).as_object().cloned().unwrap_or_default()); @@ -78,12 +80,12 @@ pub fn begin(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String> let texture = crate::transform_tex::PreviewTextures::new(ctx, format!("transform-{session}"), image, uv); app.transform_preview = Some(TransformPreview { session, - doc: Arc::new(pd), + doc: if frame_only { doc.clone() } else { Arc::new(pd) }, texture, opacity: layer.opacity * layer.fill_opacity, - above: Some(above), - styled: styled.then(|| crate::transform_fx::StyledPreview::new(format!("transform-{session}-styled"))), - follow: Some(Follow { revision, hidden: if lifted.is_none() { vec![id] } else { Vec::new() } }), + above: (!frame_only).then_some(above), + styled: (styled && !frame_only).then(|| crate::transform_fx::StyledPreview::new(format!("transform-{session}-styled"))), + follow: Some(Follow { revision, hidden: if lifted.is_none() && !frame_only { vec![id] } else { Vec::new() } }), committing: None, gesture: None, warp_drag: None, @@ -106,7 +108,7 @@ pub fn begin(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String> interpolation: default_interpolation(app).into(), warp: None, selection: false, - target: None, + target: frame_only.then(|| json!({"frame": id.0})), path: None, made: None, mode: Default::default(), diff --git a/crates/ui-egui/src/tools/transform_tool/commit.rs b/crates/ui-egui/src/tools/transform_tool/commit.rs index c00a59e971..3e3e950af5 100644 --- a/crates/ui-egui/src/tools/transform_tool/commit.rs +++ b/crates/ui-egui/src/tools/transform_tool/commit.rs @@ -22,6 +22,17 @@ pub fn commit(app: &mut PhotocraftApp) { let type_layer = warps_type(app); let Some(t) = app.ui.transform.take() else { return }; let mut preview = app.transform_preview.take(); + if crate::frame_tool::frame_transform(&t) { + app.frame_preview = None; + if t.quad != corners(t.rect) { + let result = crate::frame_tool::transformed_frame(app, &t) + .and_then(|transform| app.run("layer.frame.set", json!({"layer": t.layer, "transform": transform.m}))); + if let Err(error) = result { + keep_open(app, t, preview, error); + } + } + return; + } if let Some(options) = &t.content_aware { crate::cas_transform::commit(app, &t, options); return; @@ -232,6 +243,11 @@ pub fn follow_edits(app: &mut PhotocraftApp) { } pub fn cancel(app: &mut PhotocraftApp) { + if app.ui.transform.as_ref().is_some_and(crate::frame_tool::frame_transform) { + app.frame_preview = None; + } + // A frame drag's session (frame or content) ends here; a later one must not commit on release. + app.ui.frame_tool.auto_transform = false; // Esc while the commit runs cancels the job; the session ends when it does. if let Some(job) = committing(app) { crate::jobs_ui::cancel(app, job); diff --git a/crates/ui-egui/src/tools/transform_tool/draw.rs b/crates/ui-egui/src/tools/transform_tool/draw.rs index 7a012db134..0ed1b74bdd 100644 --- a/crates/ui-egui/src/tools/transform_tool/draw.rs +++ b/crates/ui-egui/src/tools/transform_tool/draw.rs @@ -97,6 +97,9 @@ pub(super) fn front_vertices(h: &Homography, n: usize) -> Vec { /// Photoshop. The box, handles and reference point are [`draw_overlay`], drawn over the guides. pub fn draw_content(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform) { let (Some(t), Some(pv)) = (&app.ui.transform, &app.transform_preview) else { return }; + if crate::frame_tool::frame_transform(t) { + return; + } let output = crate::monitor_status::view_display(app, painter.ctx()); let (display, _) = crate::canvas::canvas_display(app, &pv.doc, output); // Selection tint and lone mask/channel values are UI diagnostics, not document colors. @@ -237,7 +240,7 @@ pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform /// `edit.transform.warp` map it like the pixels. Not Transform Selection (its ants are hidden), a /// path, Content-Aware Scale or a type layer's Warp Text, which leave the selection alone. fn carries_selection(app: &PhotocraftApp, t: &TransformSession) -> bool { - !t.selection && t.path.is_none() && t.content_aware.is_none() && !(t.warp.is_some() && warps_type(app)) + !t.selection && !crate::frame_tool::frame_transform(t) && t.path.is_none() && t.content_aware.is_none() && !(t.warp.is_some() && warps_type(app)) } /// A transform of `document` is open that carries its selection along (#5297): the canvas traces diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 7fcadbc08b..5f69c63122 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -774,6 +774,10 @@ available in custom workspaces. `window.panel. {show:true}` always reveals, and expands the panel, including when another tab is selected. Workspace snapshots retain custom collapse settings and Timeline visibility. +### Frame Tool controls + +`ui.set {"tool":"frame","frameShape":"rectangle|ellipse|triangle|polygon|custom","frameSides":5,"frameTarget":"frame|content|both"}` selects creation options or the target inside the active frame. `ui.inspect` includes `frameTool`. `layer.frame.info {"layer":id}` queries geometry, stroke, and content without adding history. Frame edits use `layer.frame.set`, `layer.frame.fit`, `layer.frame.convert` and `layer.frame.setContent`; placement accepts `frame: id` to target an explicit frame or `frame: false` to place outside frames. See [Frame Tool behavior and persistence limits](frame-tool.md). + ### Select the layer under the pointer Assign **Select Layer Under Cursor** in Keyboard Shortcuts to choose the topmost visible, pickable layer beneath the canvas pointer. Empty pixels and points outside the document leave the selection unchanged; dialogs, strokes and brush-resize gestures block it. The command follows zoom, pan, view rotation and horizontal flipping. Agents can invoke `ui.menu.invoke {"id":"layer.selectUnderCursor"}` after moving the screen pointer with `ui.move {"x": ..., "y": ...}`. The command has no default shortcut. diff --git a/docs/frame-tool.md b/docs/frame-tool.md new file mode 100644 index 0000000000..836894a0a3 --- /dev/null +++ b/docs/frame-tool.md @@ -0,0 +1,71 @@ +# Frame Tool + +The Frame Tool (`K`) creates image placeholders with independent container and image geometry. +Its controls follow Adobe's documented desktop workflows, researched on 2026-10-23: +[draw frames](https://helpx.adobe.com/photoshop/desktop/create-manage-layers/layout-design-tools/draw-frames.html), +[select frame or image](https://helpx.adobe.com/photoshop/desktop/create-manage-layers/layout-design-tools/select-frame-content.html), +[place images](https://helpx.adobe.com/photoshop/desktop/create-manage-layers/layout-design-tools/place-image-frame.html), +[convert shapes and type](https://helpx.adobe.com/photoshop/desktop/create-manage-layers/layout-design-tools/convert-to-frame.html), +and [strokes](https://helpx.adobe.com/photoshop/desktop/create-manage-layers/layout-design-tools/add-stroke-to-frame.html). + +Choose Rectangle, Ellipse, Triangle, Polygon (3–100 sides), or Custom in the options bar and drag. +Shift constrains a square/circle; Alt/Option draws from the center. Custom uses the same original, +editable shape library as the Custom Shape tool. Drawing across an eligible selected layer puts +that layer into the frame as a Smart Object without fitting or resampling its source. + +Empty frames keep a non-printing crossed placeholder. A selected frame keeps its outline and +handles after release. Its border selects the frame; clicking its image selects both; double-clicking +the image selects only the image (double-click again for both). The two Layers thumbnails also +select the frame and image; Shift-click selects both. Frame-only handles move, resize, and rotate +the clipping boundary while the image stays put. Shift preserves proportions during resizing or +snaps rotation to 15 degrees; Alt/Option resizes around the center. Escape cancels a drag. +Free Transform honors the selected thumbnail; frame-only transformations preview the changing +clip and leave the image intact. Arrow keys move the selected frame/image/both 1 px, or 10 with Shift. + +Properties provides frame W/H/X/Y, solid stroke color/width/alignment, import/replace, and fitting. +The options bar also edits solid strokes. Import/replace is available beside the selected frame +on the canvas. File > Place Embedded/Linked and file drops fill or replace frames with Smart Objects; +external images fill the frame proportionally and are centered. Files dropped outside a frame +remain ordinary placed layers even when a frame is selected. Images dragged from Layers onto the canvas or a frame row retain +their existing size; Alt/Option copies a layer dropped on a frame row. Frame > Fit Content to Frame fills proportionally; Fit Frame to Content +changes the clipping boundary. A shape or type layer's context menu offers Convert to Frame, +with name and dimensions; its outline becomes an empty frame, including custom-shape holes. + +## Engine and persistence + +`layer.new.frame`, `layer.new.frameFromLayers`, `layer.frame.set`, `layer.frame.convert`, +`layer.frame.setContent`, `layer.frame.fit`, and the read-only `layer.frame.info` expose the operations to CLI, MCP, and control clients. +A frame is a group with `Layer::frame` (unit-square path, affine placement, stroke) and a vector +clipping mask. Contents remain independently transformable Smart Objects. UI selection and +pending gestures live in `frameTool`; `ui.set` accepts `frameShape`, `frameSides`, and +`frameTarget` (`frame`, `content`, `both`). A completed drag is one undo step; previews do not +change the document. Locks and invalid geometry are rejected before committing an edit. + +Native `.pcraft` saves keep the complete frame model, with a default for old files. PSD export +uses editable groups, vector masks, Smart Objects, and a separate vector border to preserve the +appearance. Private `pcFr` metadata restores PhotoCraft frame editability when reopened here; +unknown Photoshop blocks remain preserved. These exports are **not Photoshop's native frame layer +type**: its private frame metadata has not been independently established. Old anonymous masked +groups are not guessed to be frames from their names. + +Adobe's cloud Generate Image service is not implemented. Independent Photoshop replay and native +frame-file oracles remain necessary before claiming exact Photoshop parity. In particular, native +Photoshop frame metadata, cloud actions, and every interaction detail of its content preview have +not been established by the documentation or these synthetic tests. No readiness percentage or +parity floor is raised by this change. + +## Validation + +Frame Tool UI strings are provided in all 21 translated catalogs. Empty placeholders schedule no +frame-sized compositor mask until content or a visible stroke is added. + +Regression tests cover persistent handles after release, existing-frame resizing, cancel/undo, +frame/content/both selection, frame-only Free Transform, independent transforms at 8/16/32-bit, +proportional placement/replacement, conversion, hostile geometry, locks, and native/PSD round trips. +Set `PHOTOCRAFT_FRAME_SNAPSHOTS` when running +`frame_tool::tests::frame_creation_handles_render_at_native_scales` to render the full production +shell with a synthetic image in every theme, at 1280×720 and 800×480 points, at 1× and 2×. + +Measure 24 MP creation with `cargo run --release -p photocraft-engine --example bench_frame`. +The comparison times the former raster-mask construction against the complete vector creation +command; it does not measure image placement or a full canvas render. diff --git a/docs/gaps.md b/docs/gaps.md index 1a9291e50c..b13fc78fcd 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -241,6 +241,7 @@ what an agent can't finish alone. ## UI / UX gaps ### G3. User-reported bug backlog +- **2026-10-23 (#8864):** Frame Tool placeholders and handles persist after release; existing frames can be selected, moved/resized/rotated, filled/replaced and edited independently of their image. Shape/type conversion, solid strokes and two Layers thumbnails are available. [Behavior, evidence and remaining native Photoshop frame-file limits](frame-tool.md); no estimate or percentage changed. - **Missing:** fixes for 579 open issues (2026-10-10), filed mostly by 0.5/0.6 users. By title: ~150 UI/panels/menus/shortcuts, 94 file/format, 87 layers, 54 painting, 54 selection, 46 type, 41 performance, 34 transform/move, 25 Linux/Wayland, 24 Windows, 20 macOS. @@ -455,6 +456,7 @@ what an agent can't finish alone. | 2026-11-01 | minor | G9: 11 of 183 preferences do nothing (was 12): Graphics Adapter (`performance.gpuAdapter`) always worked, but startup read it by raw JSON key, which the scorecard prefs audit can't see; it now reads the typed Performance section; no estimate changed | | 2026-10-27 | minor | G9: 12 of 181 preferences do nothing, the scorecard's count with integration batch 9 (#9775) on main; no estimate changed | | 2026-10-26 | minor | Expand/Contract/Border distance work, mask reads and replacement cropped to nonzero bounds; bounded distances for radii ≤5; 36 MP exact-output comparisons improve 1.54–37.82× across eight cases; percentages, estimates and scorecard budgets unchanged | +| 2026-10-23 | minor | Frame Tool interaction and persistence work (#8864); documented remaining native Photoshop frame metadata and independent-oracle limits; no percentage changed | | 2026-10-26 | minor | Embedded AI/PDF/EPS save-back retains native format and a separate source-bound display preview; original sources remain undoable. Native Adobe interoperability and standalone EPS/DCS remain unverified; no corpus floor or percentage changed. | | 2026-10-25 | minor | Selected colour channel sets: drawing, combined and per-component Levels/Curves, adjustments and supported filters; [scope, evidence and benchmarks](multi-channel-editing.md). Move/transform remains open; percentages unchanged | | 2026-10-22 | minor | Embedded PSD vectors gain explicit bounded SVG editor/save-back; standalone EPS/DCS and native-format fidelity remain open. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index eae6565baa..069267e8f2 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -598,6 +598,7 @@ See [method, raw measurements and reproduction](five-algorithm-performance.md). | 2026-10-30 | minor | Art History Brush Opacity on the options bar, #10263; no estimate changed | | 2026-10-27 | minor | Smooth/Feather command reads and replacement use selection bounds plus blur reach; full-canvas reference and release comparisons extended; percentages and scorecard budgets unchanged | | 2026-10-26 | minor | Expand/Contract/Border distance work, mask reads and replacement cropped to nonzero bounds; bounded distances for radii ≤5; 36 MP exact-output comparisons improve 1.54–37.82× across eight cases; percentages, estimates and scorecard budgets unchanged | +| 2026-10-23 | minor | Frame Tool interaction and persistence work (#8864); documented remaining native Photoshop frame metadata and independent-oracle limits; no percentage changed | | 2026-10-25 | minor | Selected colour channel sets: drawing, combined and per-component Levels/Curves, adjustments and supported filters; [scope, evidence and benchmarks](multi-channel-editing.md). Move/transform remains open; percentages unchanged | | 2026-10-23 | minor | Select and Mask is Photoshop's workspace with its own tools (#7069, #8148); TOOL-214-1 stays partial (Refine Hair, Object Aware, Presets); percentages and estimates unchanged | | 2026-10-25 | minor | UI / UX and Workspace rows: 12 of 178 preferences do nothing, the scorecard's count. Camera Raw row: the Calibration panel landed on 2026-10-13 (#5128); what is missing is per-camera colour for non-DNG cameras ([gaps.md](gaps.md) G14). Percentages and estimates unchanged | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 4458c6047c..80664d314b 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 | Object Selection's Object Finder (on by default in its options bar): resting the pointer highlights the object a click selects (`select.object` with `point`; ⇧ adds, ⌥ subtracts, ⇧⌥ intersects); dragging keeps the rectangle mode (#4087). Where the active layer has no pixels under the pointer (Sample All Layers off), the status bar says so instead of showing nothing (#6549). Dominant enclosed objects are retained; regions covering most of the canvas boundary are treated as background (#6548). Heuristic, not a learned segmenter (#2788). | | Crop and slice | Crop, Perspective Crop, Slice, Slice Select | | -| Frame | Frame (frames are groups clipped by a rectangular or elliptical mask) | | +| Frame | Frame: persistent handles, frame/image/both selection, transforms, fitting, replacement, solid strokes, shape/type conversion and modern shapes ([behavior and limits](frame-tool.md), #8864, 2026-10-23) | Native Photoshop frame metadata and independent Photoshop replay remain open | | Eyedropper | Eyedropper, Color Sampler, Ruler, Note, Count | | | Retouch | Remove, Spot Healing, Healing, Patch, Content-Aware Move, Red Eye | | | Brush | Brush, Pencil, Mixer Brush | | @@ -285,6 +285,7 @@ Paragraph; the rest open as in-app floating windows. | 2026-10-24 | minor | Type options bar: the alignment and paragraph-direction buttons show the edited or selected type layer's paragraph instead of the tool defaults, as Photoshop's bar does. Scores unchanged. | | 2026-10-24 | minor | Font menus (options bar, Character panel): the current family is marked in the recent group when it is a recent one, and the menu opens showing it, as Photoshop's does, scrolled to the marked row when it sits below the fold; the arrows walk on from the marked row (#9160). Scores unchanged. | | 2026-10-24 | minor | Properties › Transform shows and edits a shape layer's path geometry (W/H/X/Y), not the pixel bounds its stroke adds, as in Photoshop; W/H scale the path to exactly the typed size. Scores unchanged. | +| 2026-10-23 | minor | Frame Tool interaction and persistence work (#8864); documented remaining native Photoshop frame metadata and independent-oracle limits; no percentage changed | | 2026-10-22 | minor | Crop default mode: a drag inside an upright box snaps the frame's edges and centre to the document, layers, guides and grid, as a Classic Mode frame's move does (#8580); no percentage changed | | 2026-10-21 | minor | Adjustment clipping moved above Properties editors to remain visible in compact docks (#5231); scope, undo/redo and 8/16/32-bit pixel regressions; readiness estimate unchanged | | 2026-10-19 | minor | Pen, Freeform Pen and Curvature Pen Path Operations menu (#1397): the operation a new path is added with, and Merge Shape Components for paths (`path.mergeShapeComponents`); row stays partial until the Shape tools and Path Selection have it; no percentage changed |