mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
feat(frame): rework the Frame tool's selection, handles and placement (#8920)
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.
This commit is contained in:
1 parent
7ba589e01c
commit
e3ecd73569
88 files changed
+3582
-470
No files matched your search
@@ -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
|
||||
|
||||
@@ -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.")
|
||||
{
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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<Rect> {
|
||||
/// 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<Rect> {
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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<ShapeLayer> {
|
||||
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() })
|
||||
|
||||
@@ -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<ShapeStroke>,
|
||||
}
|
||||
|
||||
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<ShapeLayer> {
|
||||
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 })
|
||||
}
|
||||
}
|
||||
+19
-4
@@ -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<Box<Frame>>,
|
||||
/// 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<LayerPath> {
|
||||
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<LayerId>, 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<LayerId>, 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),
|
||||
}
|
||||
|
||||
@@ -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<dyn std::error::Error>> {
|
||||
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(())
|
||||
}
|
||||
@@ -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}");
|
||||
|
||||
@@ -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)
|
||||
{
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -292,7 +292,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"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<CommandSpec> {
|
||||
"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)
|
||||
),
|
||||
|
||||
@@ -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<Document> {
|
||||
@@ -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<u8>, linked: Option<String>, p: &Value) -> Result<Value> {
|
||||
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<u8>, linked: Option<S
|
||||
let fit = p.get("fit").and_then(Value::as_bool).unwrap_or(s.prefs().general.resize_image_during_place);
|
||||
let scale = match f64_param(p, "scale") {
|
||||
Some(k) => (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<u8>, linked: Option<S
|
||||
_ => (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<u8>, linked: Option<S
|
||||
let label = if matches!(&source, SmartSource::Linked { .. }) { "Place Linked" } else { PLACE_EMBEDDED };
|
||||
let id = s.edit(label, |doc, active| {
|
||||
let layer = if smart {
|
||||
let mut so = SmartObject::new(source, Affine { m: [scale, 0.0, 0.0, scale, dx, dy] }, Some(px));
|
||||
let mut so = SmartObject::new(source, placement, px);
|
||||
// A vector source (SVG) renders at its placement scale instead of as a resampled raster.
|
||||
if vector && let Some(sharp) = crate::smart_cmds::render(doc, &so)? {
|
||||
if (vector || frame.is_some())
|
||||
&& let Some(sharp) = crate::smart_cmds::render(doc, &so)?
|
||||
{
|
||||
so.cache = Some(sharp);
|
||||
}
|
||||
if so.cache.is_none() {
|
||||
return Err(EngineError::Other(format!("{name}: the placed image could not be rendered")));
|
||||
}
|
||||
Layer::new(layer_name, LayerContent::Smart(so))
|
||||
} else {
|
||||
let px = px.ok_or_else(|| EngineError::Other(format!("{name}: a frame's image must be a smart object")))?;
|
||||
Layer::new(layer_name, LayerContent::Raster(px))
|
||||
};
|
||||
let id = crate::layer_place::insert_new(doc, *active, layer, crate::layer_place::Place::AutoEditable);
|
||||
*active = Some(id);
|
||||
let id = layer.id;
|
||||
if let Some((frame_id, _)) = &frame {
|
||||
crate::frame_cmds::put_content(doc, *frame_id, layer)?;
|
||||
*active = Some(*frame_id);
|
||||
} else {
|
||||
crate::layer_place::insert_new(doc, *active, layer, crate::layer_place::Place::AutoEditable);
|
||||
*active = Some(id);
|
||||
}
|
||||
Ok(id)
|
||||
})?;
|
||||
Ok(json!({"layer": id.0, "scale": scale * 100.0, "bounds": [dx, dy, dx + w * scale, dy + h * scale], "smartObject": smart}))
|
||||
Ok(json!({"layer": id.0, "frame": frame.as_ref().map(|(id,_)|id.0), "scale": scale * 100.0, "bounds": bounds, "smartObject": smart}))
|
||||
}
|
||||
|
||||
pub(super) fn place(s: &mut Session, p: &Value, linked: bool) -> Result<Value> {
|
||||
|
||||
+343
-272
@@ -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<String>) -> 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<LayerId> {
|
||||
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<LayerId> {
|
||||
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<Frame> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Clips the group `layer.new.groupFromLayers` returned (`grouped`) to its contents' bounds.
|
||||
fn frame_group(s: &mut Session, grouped: &Value) -> Result<Value> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
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<f64> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
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<CommandSpec> {
|
||||
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::<Vec<_>>();
|
||||
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;
|
||||
@@ -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::<Vec<_>>();
|
||||
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::<Vec<_>>())).collect::<Vec<_>>()
|
||||
)
|
||||
})
|
||||
.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<u8> {
|
||||
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));
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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())?,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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<String>) -> EngineError {
|
||||
EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }
|
||||
|
||||
@@ -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
|
||||
{
|
||||
|
||||
@@ -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<LayerId>, 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
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<Layer>) -> Result<Layer> {
|
||||
// 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(),
|
||||
|
||||
@@ -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<photocraft_doc::Frame>,
|
||||
/// (4-char key as hex, blob)
|
||||
pub psd_blocks: Vec<(String, Hash)>,
|
||||
pub psd_id: Option<u32>,
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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) => {
|
||||
|
||||
@@ -236,7 +236,18 @@ pub(super) fn link_group_resource(layers: &[Layer]) -> Option<Vec<u8>> {
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -421,6 +421,17 @@ impl Ctx<'_> {
|
||||
}
|
||||
|
||||
fn apply_common(&mut self, l: &mut Layer, rec: &LayerRecord, blend_override: Option<photocraft_psd::BlendMode>) {
|
||||
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::<photocraft_doc::Frame>(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 };
|
||||
|
||||
@@ -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<photocraft_doc::Layer>, stroke: Option<photocraft_doc::ShapeStroke>) -> 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);
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -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<Pos2> = 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
|
||||
|
||||
@@ -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<Document>, 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;
|
||||
}
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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<Value, String> {
|
||||
// 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<Option<crate::theme::ThemeKind>
|
||||
struct ToolSet {
|
||||
gradient_blend: Option<photocraft_color::BlendMode>,
|
||||
shape_stroke: Option<Option<photocraft_doc::ShapeStroke>>,
|
||||
frame_shape: Option<String>,
|
||||
frame_sides: Option<u32>,
|
||||
frame_target: Option<crate::frame_tool::Target>,
|
||||
tool: Option<Tool>,
|
||||
gradient_classic: Option<bool>,
|
||||
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<Option<String>, 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<Option<u32>, 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<Option<crate::frame_tool::Target>, String> {
|
||||
p.get("frameTarget")
|
||||
.filter(|v| !v.is_null())
|
||||
.map(|v| serde_json::from_value::<crate::frame_tool::Target>(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<Option<String>, String> {
|
||||
let Some(v) = p.get("penMode") else { return Ok(None) };
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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<DropPlace>, frame: Option<photocraft_doc::LayerId> },
|
||||
/// 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<egui::DroppedFileHandle>, at: Option<egui::Pos2>) {
|
||||
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<u8>, linked: Option<String>) -> Result<serde_json::Value, String> {
|
||||
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<u8>, linked: Option<String>, params: &serde_json::Value) -> Result<serde_json::Value, String> {
|
||||
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
|
||||
}
|
||||
|
||||
@@ -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ý
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -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
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -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
|
||||
|
Can't render this file because it contains an unexpected character in line 47 and column 53.
|
@@ -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
|
||||
|
Can't render this file because it contains an unexpected character in line 4 and column 47.
|
@@ -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
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -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} एक्शन
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -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
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -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
|
||||
|
Can't render this file because it contains an unexpected character in line 4 and column 47.
|
@@ -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
|
||||
|
Can't render this file because it contains an unexpected character in line 79 and column 53.
|
@@ -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 フレームを利用できません
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -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
|
||||
|
Can't render this file because it contains an unexpected character in line 63 and column 53.
|
@@ -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
|
||||
|
Can't render this file because it contains an unexpected character in line 8 and column 34.
|
@@ -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
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -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
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -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 Рамка недоступна
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -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 Оквир није доступан
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -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
|
||||
|
Can't render this file because it contains an unexpected character in line 8 and column 34.
|
@@ -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 Рамка недоступна
|
||||
|
Can't render this file because it contains an unexpected character in line 152 and column 53.
|
@@ -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
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -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
|
||||
|
Can't render this file because it contains an unexpected character in line 63 and column 53.
|
@@ -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
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -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);
|
||||
|
||||
@@ -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<canvas::TabStrip>,
|
||||
/// Files dropped on the canvas still to place, one Free Transform at a time.
|
||||
pub(crate) frame_tool_ctx: Option<egui::Context>,
|
||||
pub(crate) frame_preview: Option<frame_tool::Preview>,
|
||||
pub(crate) drop_places: std::collections::VecDeque<file_open::DropPlace>,
|
||||
/// The document each of `ui.views` belongs to, as of the last [`Self::sync_views`].
|
||||
view_docs: Vec<DocId>,
|
||||
|
||||
@@ -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<Value, String> {
|
||||
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<Result<Value, String>> {
|
||||
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()));
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -64,6 +64,9 @@ pub fn entries(l: &Layer, multi: bool, has_selection: bool) -> Vec<Entry> {
|
||||
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 {
|
||||
|
||||
@@ -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<Rect>, 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<Pos2> =
|
||||
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);
|
||||
|
||||
@@ -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});
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -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) }
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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(),
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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<PhotocraftApp>, 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();
|
||||
}
|
||||
@@ -69,6 +69,10 @@ pub fn confirm(app: &mut PhotocraftApp) -> Result<Value, String> {
|
||||
|
||||
/// 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();
|
||||
|
||||
@@ -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(),
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -97,6 +97,9 @@ pub(super) fn front_vertices(h: &Homography, n: usize) -> Vec<bool> {
|
||||
/// 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
|
||||
|
||||
@@ -774,6 +774,10 @@ available in custom workspaces. `window.panel.<id> {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.
|
||||
@@ -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.
|
||||
@@ -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. |
|
||||
|
||||
@@ -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 |
|
||||
|
||||
+2
-1
@@ -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 |
|
||||
|
||||
Reference in new issue
Block a user