mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
Merge PR #11458: Crop: fill the active layer and Background with Content-Aware Fill
This commit is contained in:
commit
1d5c69dda4
5 files changed
+525
-50
No files matched your search
@@ -279,7 +279,7 @@ fn content_aware_native_with_options(
|
||||
let window = sampling_window(hole_bounds, canvas);
|
||||
let n = surf.format().channels();
|
||||
let (w, h) = window_size(window)?;
|
||||
let img = surf.read_region(window);
|
||||
let img = crate::allocation::read_region(surf, window, "Content-Aware fill samples")?;
|
||||
let len = w.checked_mul(h).ok_or_else(|| EngineError::Other("the area is too large for Content-Aware fill".into()))?;
|
||||
let mut hole = crate::allocation::filled(len, false, "Content-Aware fill")?;
|
||||
let mut source = crate::allocation::filled(len, false, "Content-Aware fill")?;
|
||||
|
||||
@@ -714,6 +714,7 @@ fn crop_with(s: &mut Session, p: &Value, keep_background: bool) -> Result<Value>
|
||||
// Only the Crop tool's frame (an explicit rectangle) resizes a canvas-sized artboard; a
|
||||
// selection crop leaves boards as they are.
|
||||
let tool_frame = explicit.is_some();
|
||||
let mut filled = false;
|
||||
s.edit("Crop", |doc, active| {
|
||||
let original = doc.size;
|
||||
let board = if tool_frame { canvas_artboard(doc) } else { None };
|
||||
@@ -725,12 +726,15 @@ fn crop_with(s: &mut Session, p: &Value, keep_background: bool) -> Result<Value>
|
||||
// A straight crop fills all of the area past the old canvas, pixels an earlier Delete Cropped
|
||||
// Pixels off crop hid there included, as Photoshop does; only a turned frame keeps them (#8060).
|
||||
if content_aware {
|
||||
crate::crop_fill::fill_uncovered(doc, *active, &crate::crop_fill::Coverage::crop(r, original.width, original.height))?;
|
||||
filled = crate::crop_fill::fill_uncovered(doc, *active, &crate::crop_fill::Coverage::crop(r, original.width, original.height), delete)?;
|
||||
}
|
||||
doc.selection = None;
|
||||
target.apply(doc);
|
||||
Ok(())
|
||||
})?;
|
||||
if filled && let Some(st) = s.active_mut() {
|
||||
st.history.set_current_label("Content-aware Crop");
|
||||
}
|
||||
Ok(crop_result(s, json!({ "x": r.x0, "y": r.y0, "width": r.width(), "height": r.height() })))
|
||||
}
|
||||
|
||||
@@ -897,6 +901,7 @@ fn rotated_crop(s: &mut Session, r: Rect, angle: f64, delete: bool, content_awar
|
||||
};
|
||||
// The canvas board, found before the turn, fits the frame as in a straight crop.
|
||||
let board = s.active().and_then(|d| canvas_artboard(&d.doc));
|
||||
let mut filled = false;
|
||||
crate::analysis_cmds::compound(s, "Crop", |s| {
|
||||
// Pixels the crop deletes needn't be turned first: keeping only what lands in the frame
|
||||
// makes the rotation cost the frame's size, not the canvas's (a small turned crop of a
|
||||
@@ -934,13 +939,16 @@ fn rotated_crop(s: &mut Session, r: Rect, angle: f64, delete: bool, content_awar
|
||||
crop_doc(doc, CMD, target, delete, extension)?;
|
||||
fit_canvas_artboard(doc, board);
|
||||
if content_aware {
|
||||
crate::crop_fill::fill_uncovered(doc, *active, &coverage)?;
|
||||
filled = crate::crop_fill::fill_uncovered(doc, *active, &coverage, delete)?;
|
||||
}
|
||||
doc.selection = None;
|
||||
crop_target.apply(doc);
|
||||
Ok(())
|
||||
})
|
||||
})?;
|
||||
if filled && let Some(st) = s.active_mut() {
|
||||
st.history.set_current_label("Content-aware Crop");
|
||||
}
|
||||
Ok(crop_result(s, json!({ "x": r.x0, "y": r.y0, "width": r.width(), "height": r.height(), "angle": angle })))
|
||||
}
|
||||
|
||||
@@ -1109,7 +1117,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"image.crop",
|
||||
"Crop",
|
||||
["Image"],
|
||||
r##"{"x":px,"y":px,"width":px,"height":px,"angle":-3600..3600=0,"deleteCroppedPixels":bool=true,"contentAware":bool=false,"targetWidth":px,"targetHeight":px,"resolution":ppi,"resample":"bicubic|bilinear|nearest|lanczos|preserveDetails"="bicubic"} → {x,y,width,height,documentWidth,documentHeight,resolution} (targetWidth/targetHeight, both or neither: the cropped area is resampled to exactly that size, as Image Size, in the same undo step; resolution: the document's new ppi; deleteCroppedPixels false: the pixels past the frame are kept and, unless contentAware, the Background becomes a normal layer, "Layer 0", so an extension is transparent on every layer (with contentAware the Background stays); contentAware: the Crop tool's Fill › Content-Aware Fill, the area a rotated or extending crop uncovers filled from its surroundings on the Background, else the active pixel layer)"##,
|
||||
r##"{"x":px,"y":px,"width":px,"height":px,"angle":-3600..3600=0,"deleteCroppedPixels":bool=true,"contentAware":bool=false,"targetWidth":px,"targetHeight":px,"resolution":ppi,"resample":"bicubic|bilinear|nearest|lanczos|preserveDetails"="bicubic"} → {x,y,width,height,documentWidth,documentHeight,resolution} (targetWidth/targetHeight, both or neither: the cropped area is resampled to exactly that size, as Image Size, in the same undo step; resolution: the document's new ppi; deleteCroppedPixels false: the pixels past the frame are kept and, unless contentAware, the Background becomes a normal layer, "Layer 0", so an extension is transparent on every layer (with contentAware the Background stays); contentAware: the Crop tool's Fill › Content-Aware Fill uses surrounding pixels to fill areas uncovered by a rotated or extending crop. The fill targets the Background, or the active pixel layer if there is no Background. With Delete Cropped Pixels on, it also targets a separate active pixel layer if it is visible and unlocked.)"##,
|
||||
has_doc,
|
||||
crop
|
||||
),
|
||||
|
||||
+133
-46
@@ -3,9 +3,10 @@
|
||||
//! strips an extension adds) is filled from its surroundings instead of holding the background
|
||||
//! colour or transparency.
|
||||
//!
|
||||
//! Which layer: the Background when the document has one (the layer the crop filled with the
|
||||
//! background colour), otherwise the active pixel layer (where the crop left transparency). Other
|
||||
//! layers keep their transparency there, as after a plain crop. Each connected piece of the
|
||||
//! Which layers: the Background and the active pixel layer, each sampled independently. Unmeasured
|
||||
//! cases (Delete Cropped Pixels off, or a hidden, locked or nonpixel active layer) retain the
|
||||
//! Background-else-active target. Other layers keep their transparency, as after a plain crop.
|
||||
//! Each connected piece of the
|
||||
//! uncovered area (each corner, each edge strip) is filled on its own, with Photoshop's sampling
|
||||
//! window around that piece, and only pixels the image covers are sampled.
|
||||
//!
|
||||
@@ -27,6 +28,9 @@ const SEED: u64 = 1;
|
||||
/// The largest canvas (pixels) the uncovered area is worked out for: the Content-Aware window cap.
|
||||
const MAX_PIXELS: u64 = 400_000_000;
|
||||
|
||||
/// Limit for the dense native-float input read when reaching beyond the normal sampling window.
|
||||
const MAX_WIDENED_SAMPLE_BYTES: usize = 512 << 20;
|
||||
|
||||
/// Where the cropped canvas came from in the original document.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct Coverage {
|
||||
@@ -38,10 +42,10 @@ pub(crate) struct Coverage {
|
||||
pub height: f64,
|
||||
/// Whether the map rotates (its resampled edge is antialiased against the background colour).
|
||||
pub rotated: bool,
|
||||
/// The filled layer's pixels before a turned crop (original document px), set by
|
||||
/// Each candidate target's pixels before a turned crop (original document px), set by
|
||||
/// [`Coverage::holding`]: where they lie past the old canvas they are hidden image, not
|
||||
/// uncovered area. A straight crop has none: Photoshop fills over hidden pixels there.
|
||||
pub held: Option<Surface>,
|
||||
pub held: Option<Vec<(LayerId, Surface)>>,
|
||||
}
|
||||
|
||||
impl Coverage {
|
||||
@@ -53,7 +57,14 @@ impl Coverage {
|
||||
/// Takes the pixels of the layer the fill will go to from `doc` before a turned crop (the
|
||||
/// surface is shared, not copied), so hidden pixels past the old canvas count as covered.
|
||||
pub fn holding(mut self, doc: &Document, active: Option<LayerId>) -> Self {
|
||||
self.held = target_layer(doc, active).ok().and_then(|id| doc.layer(id)).and_then(|l| l.surface()).cloned();
|
||||
self.held = Some(
|
||||
target_layer(doc, active)
|
||||
.ok()
|
||||
.into_iter()
|
||||
.chain(additional_target(doc, active))
|
||||
.filter_map(|id| doc.layer(id).and_then(|l| l.surface()).map(|surface| (id, surface.clone())))
|
||||
.collect(),
|
||||
);
|
||||
self
|
||||
}
|
||||
|
||||
@@ -61,19 +72,19 @@ impl Coverage {
|
||||
/// the original canvas by at least half the pixel's projected size (exact for an unrotated
|
||||
/// crop); a rotated crop also refills the one-pixel antialiased edge, which the resampling
|
||||
/// blended with the background colour.
|
||||
fn covered(&self, u: i32, v: i32, margin: f64) -> bool {
|
||||
fn covered(&self, u: i32, v: i32, margin: f64, held: Option<&Surface>) -> bool {
|
||||
let [a, b, c, d, e, f] = self.map;
|
||||
let (cu, cv) = (f64::from(u) + 0.5, f64::from(v) + 0.5);
|
||||
let (x, y) = (a * cu + b * cv + e, c * cu + d * cv + f);
|
||||
(x >= margin && y >= margin && x <= self.width - margin && y <= self.height - margin) || self.holds(x, y)
|
||||
(x >= margin && y >= margin && x <= self.width - margin && y <= self.height - margin) || Self::holds(held, x, y)
|
||||
}
|
||||
|
||||
/// Whether the layer held an image pixel at original document point (x, y) past the canvas
|
||||
/// (#8060): mostly opaque there and one pixel around it too (the turned edge is blended with
|
||||
/// the background colour, as at the canvas edge). Without an alpha channel
|
||||
/// hidden pixels can't be told from empty ones: nothing is held.
|
||||
fn holds(&self, x: f64, y: f64) -> bool {
|
||||
let Some(surf) = &self.held else { return false };
|
||||
fn holds(held: Option<&Surface>, x: f64, y: f64) -> bool {
|
||||
let Some(surf) = held else { return false };
|
||||
let format = surf.format();
|
||||
if !(format.alpha && x.is_finite() && y.is_finite()) {
|
||||
return false;
|
||||
@@ -100,8 +111,20 @@ const UNLABELLED: u32 = u32::MAX;
|
||||
|
||||
/// Fills the area of the cropped `doc` that `cov` says the original image doesn't cover (see the
|
||||
/// module docs). Nothing uncovered: nothing changes. Errors leave `doc` to be rolled back by the
|
||||
/// caller's history step.
|
||||
pub(crate) fn fill_uncovered(doc: &mut Document, active: Option<LayerId>, cov: &Coverage) -> Result<()> {
|
||||
/// caller's history step. Returns whether any uncovered pixels were filled, for the history name.
|
||||
pub(crate) fn fill_uncovered(doc: &mut Document, active: Option<LayerId>, cov: &Coverage, delete: bool) -> Result<bool> {
|
||||
let first = target_layer(doc, active);
|
||||
let additional = if delete { additional_target(doc, active) } else { None };
|
||||
let mut filled = fill_layer(doc, first, cov, false)?;
|
||||
if let Some(id) = additional {
|
||||
filled |= fill_layer(doc, Ok(id), cov, true)?;
|
||||
}
|
||||
Ok(filled)
|
||||
}
|
||||
|
||||
/// One target at a time keeps the label/window allocations bounded to one canvas. The caller's
|
||||
/// existing edit/compound transaction rolls every target back if a later fill fails.
|
||||
fn fill_layer(doc: &mut Document, id: Result<LayerId>, cov: &Coverage, own_pixels: bool) -> Result<bool> {
|
||||
let canvas = doc.bounds();
|
||||
let (w, h) = (canvas.width(), canvas.height());
|
||||
if u64::from(w) * u64::from(h) > MAX_PIXELS {
|
||||
@@ -110,62 +133,126 @@ pub(crate) fn fill_uncovered(doc: &mut Document, active: Option<LayerId>, cov: &
|
||||
let (w, h) = (w as usize, h as usize);
|
||||
let len = w.checked_mul(h).ok_or_else(|| EngineError::Other("the crop is too large for Content-Aware fill".into()))?;
|
||||
if len == 0 {
|
||||
return Ok(());
|
||||
return Ok(false);
|
||||
}
|
||||
let margin = cov.margin();
|
||||
let held = id.as_ref().ok().and_then(|id| cov.held.as_ref()?.iter().find(|(held_id, _)| held_id == id).map(|(_, surface)| surface));
|
||||
let mut labels = crate::allocation::filled(len, 0u32, "Content-Aware crop fill")?;
|
||||
labels.par_chunks_mut(w).enumerate().for_each(|(y, row)| {
|
||||
for (x, l) in row.iter_mut().enumerate() {
|
||||
if !cov.covered(x as i32, y as i32, margin) {
|
||||
if !cov.covered(x as i32, y as i32, margin, held) {
|
||||
*l = UNLABELLED;
|
||||
}
|
||||
}
|
||||
});
|
||||
if !labels.contains(&UNLABELLED) {
|
||||
return Ok(());
|
||||
return Ok(false);
|
||||
}
|
||||
if !labels.contains(&0) {
|
||||
return Err(EngineError::Other("Content-Aware fill needs some of the image inside the crop to sample from".into()));
|
||||
return if own_pixels {
|
||||
Ok(false)
|
||||
} else {
|
||||
Err(EngineError::Other("Content-Aware fill needs some of the image inside the crop to sample from".into()))
|
||||
};
|
||||
}
|
||||
let id = target_layer(doc, active)?;
|
||||
let pieces = label_components(&mut labels, w, h)?;
|
||||
// Resolve an absent target only after the no-fill/sample checks, preserving the legacy path.
|
||||
let id = id?;
|
||||
let surf = doc.layer(id).and_then(|l| l.surface()).ok_or_else(|| EngineError::Other("Content-Aware fill needs a pixel layer".into()))?;
|
||||
let n = surf.format().channels().max(1);
|
||||
let has_alpha = surf.format().alpha;
|
||||
let has_pixel = |x, y| !has_alpha || surf.sample_channel(x, y, n - 1) > 0.0;
|
||||
let donor_bounds = own_pixels.then(|| if has_alpha { surf.content_bounds().intersect(&canvas) } else { canvas });
|
||||
// The added target is optional when it has no covered pixels of its own to sample.
|
||||
// This check does not absorb errors from synthesis or allocation.
|
||||
if donor_bounds.is_some_and(|bounds| !contains_donor(bounds, |x, y| labels[y as usize * w + x as usize] == 0 && has_pixel(x, y))) {
|
||||
return Ok(false);
|
||||
}
|
||||
let pieces = label_components(&mut labels, w, h)?;
|
||||
let label = |x: i32, y: i32| -> u32 {
|
||||
if x < 0 || y < 0 {
|
||||
return 0;
|
||||
}
|
||||
(y as usize).checked_mul(w).and_then(|i| i.checked_add(x as usize)).and_then(|i| labels.get(i)).copied().unwrap_or(0)
|
||||
};
|
||||
let n = surf.format().channels().max(1);
|
||||
let filled: Vec<(Rect, Vec<f32>)> = pieces
|
||||
.par_iter()
|
||||
.enumerate()
|
||||
.map(|(k, bounds)| -> Result<(Rect, Vec<f32>)> {
|
||||
let k = k as u32 + 1;
|
||||
let (window, px) = crate::fill_cmds::content_aware_native(surf, *bounds, canvas, true, SEED, |x, y| label(x, y) == k, |x, y| label(x, y) == 0)?;
|
||||
// The piece's bounds, its pixels from the fill and the rest as they were.
|
||||
let mut out = surf.read_region(*bounds);
|
||||
let ww = window.width() as usize;
|
||||
for y in bounds.y0..bounds.y1 {
|
||||
for x in bounds.x0..bounds.x1 {
|
||||
if label(x, y) != k || !window.contains(x, y) {
|
||||
continue;
|
||||
}
|
||||
let src = ((y - window.y0) as usize * ww + (x - window.x0) as usize) * n;
|
||||
let dst = ((y - bounds.y0) as usize * bounds.width() as usize + (x - bounds.x0) as usize) * n;
|
||||
if let (Some(s), Some(d)) = (px.get(src..src + n), out.get_mut(dst..dst + n)) {
|
||||
d.copy_from_slice(s);
|
||||
}
|
||||
let fill_piece = |(k, bounds): (usize, &Rect)| -> Result<(Rect, Vec<f32>)> {
|
||||
let k = k as u32 + 1;
|
||||
// A partial active layer can have no donor near a distant turned corner. Only that
|
||||
// added target may widen its sampling envelope; its hole and output stay unchanged.
|
||||
let usable = |x, y| label(x, y) == 0 && (!own_pixels || has_pixel(x, y));
|
||||
let sampling_bounds = if let Some(donor_bounds) = donor_bounds {
|
||||
let window = crate::fill_cmds::sampling_window(*bounds, canvas).intersect(&donor_bounds);
|
||||
if contains_donor(window, usable) { *bounds } else { widened_sampling_bounds(*bounds, donor_bounds, canvas, n)? }
|
||||
} else {
|
||||
*bounds
|
||||
};
|
||||
let (window, px) = crate::fill_cmds::content_aware_native(
|
||||
surf,
|
||||
sampling_bounds,
|
||||
canvas,
|
||||
true,
|
||||
SEED,
|
||||
|x, y| label(x, y) == k,
|
||||
// A partial active layer (EdgeHalf in #10868) must extend its own image, not
|
||||
// sample its empty canvas rows into the new strip. Keep legacy sampling intact.
|
||||
usable,
|
||||
)?;
|
||||
// The piece's bounds, its pixels from the fill and the rest as they were.
|
||||
let mut out = crate::allocation::read_region(surf, *bounds, "Content-Aware crop output")?;
|
||||
let ww = window.width() as usize;
|
||||
for y in bounds.y0..bounds.y1 {
|
||||
for x in bounds.x0..bounds.x1 {
|
||||
if label(x, y) != k || !window.contains(x, y) {
|
||||
continue;
|
||||
}
|
||||
let src = ((y - window.y0) as usize * ww + (x - window.x0) as usize) * n;
|
||||
let dst = ((y - bounds.y0) as usize * bounds.width() as usize + (x - bounds.x0) as usize) * n;
|
||||
if let (Some(s), Some(d)) = (px.get(src..src + n), out.get_mut(dst..dst + n)) {
|
||||
d.copy_from_slice(s);
|
||||
}
|
||||
}
|
||||
Ok((*bounds, out))
|
||||
})
|
||||
.collect::<Result<_>>()?;
|
||||
}
|
||||
Ok((*bounds, out))
|
||||
};
|
||||
let filled: Vec<(Rect, Vec<f32>)> = if own_pixels {
|
||||
// A fallback window can span the canvas: keep only one added-target window live.
|
||||
pieces.iter().enumerate().map(fill_piece).collect::<Result<_>>()?
|
||||
} else {
|
||||
pieces.par_iter().enumerate().map(fill_piece).collect::<Result<_>>()?
|
||||
};
|
||||
let surf = doc.layer_mut(id).and_then(|l| l.surface_mut()).ok_or_else(|| EngineError::Other("Content-Aware fill needs a pixel layer".into()))?;
|
||||
for (r, px) in filled {
|
||||
surf.write_region(r, &px);
|
||||
}
|
||||
Ok(())
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Checks the candidate rectangle for a covered pixel that passes the target's donor policy.
|
||||
fn contains_donor(bounds: Rect, usable: impl Fn(i32, i32) -> bool) -> bool {
|
||||
(bounds.y0..bounds.y1).any(|y| (bounds.x0..bounds.x1).any(|x| usable(x, y)))
|
||||
}
|
||||
|
||||
/// Widens the sampling envelope to include distant donors, after pricing the actual float read.
|
||||
fn widened_sampling_bounds(piece: Rect, donors: Rect, canvas: Rect, channels: usize) -> Result<Rect> {
|
||||
let expanded = piece.union(&donors);
|
||||
let window = crate::fill_cmds::sampling_window(expanded, canvas);
|
||||
let bytes = (window.width() as usize)
|
||||
.checked_mul(window.height() as usize)
|
||||
.and_then(|pixels| pixels.checked_mul(channels))
|
||||
.and_then(|samples| samples.checked_mul(std::mem::size_of::<f32>()));
|
||||
if bytes.is_none_or(|bytes| bytes > MAX_WIDENED_SAMPLE_BYTES) {
|
||||
return Err(EngineError::Other("the expanded Content-Aware crop sampling window is too large".into()));
|
||||
}
|
||||
Ok(expanded)
|
||||
}
|
||||
|
||||
/// Only the measured, editable active-raster case adds a target to the Background. Ancestor
|
||||
/// visibility and locks count too; all unmeasured cases keep the original target selection.
|
||||
fn additional_target(doc: &Document, active: Option<LayerId>) -> Option<LayerId> {
|
||||
let background = doc.background()?.id;
|
||||
let id = active.filter(|id| *id != background)?;
|
||||
let path = doc.path_of(id)?;
|
||||
let layer = doc.layer_at(&path)?;
|
||||
(matches!(layer.content, photocraft_doc::LayerContent::Raster(_)) && doc.shown_at(&path) && !doc.locks_at(&path).any()).then_some(id)
|
||||
}
|
||||
|
||||
/// The Background, else the active pixel layer.
|
||||
@@ -242,9 +329,9 @@ mod tests {
|
||||
fn unrotated_coverage_is_exact() {
|
||||
let c = Coverage::crop(Rect::new(-2, 0, 8, 4), 5, 4);
|
||||
let m = c.margin();
|
||||
assert!(!c.covered(1, 0, m), "x = -1");
|
||||
assert!(c.covered(2, 0, m), "x = 0");
|
||||
assert!(c.covered(6, 0, m), "x = 4");
|
||||
assert!(!c.covered(7, 0, m), "x = 5");
|
||||
assert!(!c.covered(1, 0, m, None), "x = -1");
|
||||
assert!(c.covered(2, 0, m, None), "x = 0");
|
||||
assert!(c.covered(6, 0, m, None), "x = 4");
|
||||
assert!(!c.covered(7, 0, m, None), "x = 5");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,379 @@
|
||||
//! #10868: crop fill samples the Background and editable active raster independently.
|
||||
|
||||
use photocraft_doc::{Document, Layer, LayerContent, LayerId, TextLayer};
|
||||
use photocraft_engine::Session;
|
||||
use photocraft_geom::Rect;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
const WHITE: [f32; 4] = [1.0, 1.0, 1.0, 1.0];
|
||||
const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0];
|
||||
const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0];
|
||||
const BLUE: [f32; 4] = [0.0, 0.0, 1.0, 1.0];
|
||||
const YELLOW: [f32; 4] = [1.0, 1.0, 0.0, 1.0];
|
||||
|
||||
struct Layers {
|
||||
background: LayerId,
|
||||
quads: LayerId,
|
||||
small: LayerId,
|
||||
edge: LayerId,
|
||||
hidden: LayerId,
|
||||
text: LayerId,
|
||||
}
|
||||
|
||||
fn doc(s: &Session) -> &Document {
|
||||
&s.active().unwrap().doc
|
||||
}
|
||||
|
||||
fn raster(d: &Document, name: &str, bounds: Rect, color: [f32; 4]) -> Layer {
|
||||
let fmt = d.pixel_format();
|
||||
let mut layer = Layer::raster(name, fmt);
|
||||
layer.surface_mut().unwrap().fill_rect(bounds, &photocraft_raster::from_rgba(&fmt, color));
|
||||
layer
|
||||
}
|
||||
|
||||
/// Keeps the measured straight geometry and fits turned controls under the 1 MiB transform limit
|
||||
/// that the preference test can set process-wide.
|
||||
fn scene_divisor(turned: bool) -> i32 {
|
||||
if turned { 2 } else { 1 }
|
||||
}
|
||||
|
||||
/// The measured scene, with a deliberately different crop extension colour.
|
||||
fn scene(turned: bool) -> (Session, Layers) {
|
||||
let divisor = scene_divisor(turned);
|
||||
let rect = |x0, y0, x1, y1| Rect::new(x0 / divisor, y0 / divisor, x1 / divisor, y1 / divisor);
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width":800/divisor,"height":500/divisor,"depth":8,"background":"white"})).unwrap();
|
||||
s.execute("tools.setColors", json!({"background":"#ff00ff"})).unwrap();
|
||||
let ids = s
|
||||
.edit("Fixture", |d, _| {
|
||||
let background = d.background().unwrap().id;
|
||||
let mut quads = raster(d, "Quads", rect(0, 0, 800, 500), RED);
|
||||
let fmt = d.pixel_format();
|
||||
let surf = quads.surface_mut().unwrap();
|
||||
for (bounds, color) in [(rect(400, 0, 800, 250), GREEN), (rect(0, 250, 400, 500), BLUE), (rect(400, 250, 800, 500), YELLOW)] {
|
||||
surf.fill_rect(bounds, &photocraft_raster::from_rgba(&fmt, color));
|
||||
}
|
||||
let small = raster(d, "Small", rect(350, 200, 450, 300), RED);
|
||||
let edge = raster(d, "EdgeHalf", rect(600, 0, 800, 250), BLUE);
|
||||
let mut hidden = raster(d, "Hidden", rect(0, 0, 800, 500), RED);
|
||||
hidden.visible = false;
|
||||
let text = Layer::new("T", LayerContent::Text(TextLayer { text: "T".into(), ..Default::default() }));
|
||||
let ids = Layers { background, quads: quads.id, small: small.id, edge: edge.id, hidden: hidden.id, text: text.id };
|
||||
d.layers.extend([quads, small, edge, hidden, text]);
|
||||
Ok(ids)
|
||||
})
|
||||
.unwrap();
|
||||
(s, ids)
|
||||
}
|
||||
|
||||
fn select(s: &mut Session, id: LayerId) {
|
||||
s.execute("layer.select", json!({"layer":id.0})).unwrap();
|
||||
}
|
||||
|
||||
/// Extends the frame to the right by one eighth of the original width.
|
||||
fn frame(turned: bool) -> Value {
|
||||
let divisor = scene_divisor(turned);
|
||||
json!({"x":0,"y":0,"width":900/divisor,"height":500/divisor,"angle":if turned { 10 } else { 0 },"deleteCroppedPixels":true})
|
||||
}
|
||||
|
||||
/// Samples the same relative point inside the new strip in both fixture sizes.
|
||||
fn extension_sample(turned: bool) -> (i32, i32) {
|
||||
let divisor = scene_divisor(turned);
|
||||
(850 / divisor, 400 / divisor)
|
||||
}
|
||||
|
||||
fn crop(s: &mut Session, mut p: Value, aware: bool) {
|
||||
p["contentAware"] = json!(aware);
|
||||
s.execute("image.crop", p).unwrap();
|
||||
}
|
||||
|
||||
fn plain_control(s: &mut Session, p: &Value) -> Document {
|
||||
crop(s, p.clone(), false);
|
||||
let plain = doc(s).clone();
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
plain
|
||||
}
|
||||
|
||||
/// Checks donor colour with room for the resampling and synthesis tolerance.
|
||||
fn pixel(d: &Document, id: LayerId, x: i32, y: i32, want: [f32; 4]) {
|
||||
let actual = d.layer(id).unwrap().surface().unwrap().rgba(x, y);
|
||||
assert!(actual.iter().zip(want).all(|(a, b)| (a - b).abs() < 0.06), "layer {id:?} at ({x},{y}): {actual:?}, expected {want:?}");
|
||||
}
|
||||
|
||||
/// Compares complete layers with plain crop, including any legitimate turn or clipping.
|
||||
fn unchanged(d: &Document, plain: &Document, ids: &[LayerId]) {
|
||||
for id in ids {
|
||||
// Includes bounds, pixels and metadata; turned crops legitimately transform these layers.
|
||||
assert_eq!(d.layer(*id), plain.layer(*id), "non-target {id:?} differs from plain crop");
|
||||
}
|
||||
}
|
||||
|
||||
fn named_one_step(s: &Session, past: usize, name: &str) {
|
||||
let st = s.active().unwrap();
|
||||
assert_eq!(st.history.past_len(), past + 1);
|
||||
assert_eq!(st.history.undo_label(), Some(name));
|
||||
}
|
||||
|
||||
fn undo_redo(s: &mut Session, before: &Document) {
|
||||
let after = doc(s).clone();
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(doc(s), before);
|
||||
s.execute("edit.redo", json!({})).unwrap();
|
||||
assert_eq!(doc(s), &after);
|
||||
assert_eq!(s.active().unwrap().history.undo_label(), Some("Content-aware Crop"));
|
||||
}
|
||||
|
||||
/// Matches the three measured rows at their original size, bounds and sample points.
|
||||
#[test]
|
||||
fn measured_straight_rows_fill_background_and_only_the_active_raster() {
|
||||
for row in 0..3 {
|
||||
let (mut s, ids) = scene(false);
|
||||
let active = if row == 1 { ids.edge } else { ids.quads };
|
||||
if row == 2 {
|
||||
s.edit("Layer 0", |d, _| {
|
||||
let bg = d.layer_mut(ids.background).unwrap();
|
||||
bg.name = "Layer 0".into();
|
||||
bg.locks = Default::default();
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
select(&mut s, active);
|
||||
let before = doc(&s).clone();
|
||||
let p = frame(false);
|
||||
let plain = plain_control(&mut s, &p);
|
||||
let past = s.active().unwrap().history.past_len();
|
||||
crop(&mut s, p, true);
|
||||
let d = doc(&s);
|
||||
assert_eq!((d.size.width, d.size.height), (900, 500));
|
||||
let mut untouched = vec![ids.small, ids.hidden, ids.text];
|
||||
untouched.push(if row == 1 { ids.quads } else { ids.edge });
|
||||
if row == 2 {
|
||||
assert!(d.background().is_none());
|
||||
untouched.push(ids.background);
|
||||
} else {
|
||||
assert_eq!(d.layer(ids.background).unwrap().surface().unwrap().content_bounds(), Rect::new(0, 0, 900, 500));
|
||||
pixel(d, ids.background, 850, 400, WHITE);
|
||||
}
|
||||
let bounds = if row == 1 { Rect::new(600, 0, 900, 500) } else { Rect::new(0, 0, 900, 500) };
|
||||
assert_eq!(d.layer(active).unwrap().surface().unwrap().content_bounds(), bounds);
|
||||
pixel(d, active, 850, if row == 1 { 400 } else { 125 }, if row == 1 { BLUE } else { GREEN });
|
||||
unchanged(d, &plain, &untouched);
|
||||
named_one_step(&s, past, "Content-aware Crop");
|
||||
undo_redo(&mut s, &before);
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks own-layer donors and exact non-target parity after rotation.
|
||||
#[test]
|
||||
fn turned_rows_sample_each_target_and_leave_other_layers_at_plain_crop() {
|
||||
let (x, y) = extension_sample(true);
|
||||
for row in 0..3 {
|
||||
let (mut s, ids) = scene(true);
|
||||
// Uniform donors isolate target selection from the existing turned-fill sampling policy.
|
||||
s.edit("Uniform Quads", |d, _| {
|
||||
let fmt = d.pixel_format();
|
||||
let bounds = d.bounds();
|
||||
d.layer_mut(ids.quads).unwrap().surface_mut().unwrap().fill_rect(bounds, &photocraft_raster::from_rgba(&fmt, GREEN));
|
||||
if row == 2 {
|
||||
d.layer_mut(ids.background).unwrap().locks = Default::default();
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let active = if row == 1 { ids.edge } else { ids.quads };
|
||||
select(&mut s, active);
|
||||
let before = doc(&s).clone();
|
||||
let p = frame(true);
|
||||
let plain = plain_control(&mut s, &p);
|
||||
let past = s.active().unwrap().history.past_len();
|
||||
let mut p = p;
|
||||
p["contentAware"] = json!(true);
|
||||
s.execute("image.crop", p).unwrap_or_else(|error| panic!("turned row {row}, active {active:?}: {error}"));
|
||||
let d = doc(&s);
|
||||
pixel(d, active, x, y, if row == 1 { BLUE } else { GREEN });
|
||||
assert!(d.layer(active).unwrap().surface().unwrap().content_bounds().contains(x, y));
|
||||
let mut untouched = vec![ids.small, ids.hidden, ids.text, if row == 1 { ids.quads } else { ids.edge }];
|
||||
if row == 2 {
|
||||
untouched.push(ids.background);
|
||||
} else {
|
||||
pixel(d, ids.background, x, y, WHITE);
|
||||
}
|
||||
unchanged(d, &plain, &untouched);
|
||||
named_one_step(&s, past, "Content-aware Crop");
|
||||
undo_redo(&mut s, &before);
|
||||
}
|
||||
}
|
||||
|
||||
/// Selecting the Background leaves each other layer identical to its plain crop.
|
||||
#[test]
|
||||
fn background_active_is_not_a_second_target() {
|
||||
for turned in [false, true] {
|
||||
let (x, y) = extension_sample(turned);
|
||||
let (mut s, ids) = scene(turned);
|
||||
select(&mut s, ids.background);
|
||||
let p = frame(turned);
|
||||
let plain = plain_control(&mut s, &p);
|
||||
let past = s.active().unwrap().history.past_len();
|
||||
crop(&mut s, p, true);
|
||||
pixel(doc(&s), ids.background, x, y, WHITE);
|
||||
unchanged(doc(&s), &plain, &[ids.quads, ids.small, ids.edge, ids.hidden, ids.text]);
|
||||
named_one_step(&s, past, "Content-aware Crop");
|
||||
}
|
||||
}
|
||||
|
||||
/// Verifies Background-only fill for ineligible active layers and Delete Cropped Pixels off.
|
||||
#[test]
|
||||
fn unmeasured_active_targets_and_delete_off_keep_the_legacy_target() {
|
||||
for turned in [false, true] {
|
||||
let (x, y) = extension_sample(turned);
|
||||
for case in 0..10 {
|
||||
let (mut s, ids) = scene(turned);
|
||||
let active = match case {
|
||||
0 => ids.text,
|
||||
1 => ids.hidden,
|
||||
_ => ids.quads,
|
||||
};
|
||||
if (2..7).contains(&case) {
|
||||
s.edit("Lock active", |d, _| {
|
||||
assert!(d.layer_mut(active).unwrap().locks.set(["all", "pixels", "transparency", "position", "artboard"][case - 2], true));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
if case >= 8 {
|
||||
s.edit("Group active", |d, _| {
|
||||
let i = d.layers.iter().position(|layer| layer.id == active).unwrap();
|
||||
let child = d.layers.remove(i);
|
||||
let mut group = Layer::group("Ancestor", vec![child]);
|
||||
if case == 8 {
|
||||
group.visible = false;
|
||||
} else {
|
||||
assert!(group.locks.set("pixels", true));
|
||||
}
|
||||
d.layers.insert(i, group);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
select(&mut s, active);
|
||||
let mut p = frame(turned);
|
||||
if case == 7 {
|
||||
p["deleteCroppedPixels"] = json!(false);
|
||||
}
|
||||
let plain = plain_control(&mut s, &p);
|
||||
crop(&mut s, p, true);
|
||||
pixel(doc(&s), ids.background, x, y, WHITE);
|
||||
unchanged(doc(&s), &plain, &[ids.quads, ids.small, ids.edge, ids.hidden, ids.text]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks the plain history name for interior crops and crops with synthesis disabled.
|
||||
#[test]
|
||||
fn no_fill_or_content_aware_off_keeps_the_crop_history_name() {
|
||||
for (p, aware, turned) in [
|
||||
(json!({"x":20,"y":20,"width":40,"height":30}), true, false),
|
||||
(json!({"x":20,"y":20,"width":40,"height":30,"angle":10}), true, true),
|
||||
(frame(false), false, false),
|
||||
(frame(true), false, true),
|
||||
] {
|
||||
let (mut s, ids) = scene(turned);
|
||||
select(&mut s, ids.quads);
|
||||
let past = s.active().unwrap().history.past_len();
|
||||
crop(&mut s, p, aware);
|
||||
named_one_step(&s, past, "Crop");
|
||||
}
|
||||
}
|
||||
|
||||
/// Gives exactly one target a strip of held pixels outside the original canvas.
|
||||
fn overhang_scene(held_active: bool) -> (Session, LayerId, LayerId) {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width":64,"height":48,"background":"white"})).unwrap();
|
||||
s.execute("tools.setColors", json!({"background":"#ff00ff"})).unwrap();
|
||||
let (bg, active) = s
|
||||
.edit("Distinct hidden pixels", |d, active| {
|
||||
let bg = d.background().unwrap().id;
|
||||
let mut layer = raster(d, "Active", Rect::new(0, 0, 64, 48), GREEN);
|
||||
let fmt = d.pixel_format();
|
||||
let surf = if held_active { layer.surface_mut().unwrap() } else { d.layer_mut(bg).unwrap().surface_mut().unwrap() };
|
||||
surf.fill_rect(Rect::new(-16, 0, 0, 48), &photocraft_raster::from_rgba(&fmt, if held_active { BLUE } else { RED }));
|
||||
let id = layer.id;
|
||||
d.layers.push(layer);
|
||||
*active = Some(id);
|
||||
Ok((bg, id))
|
||||
})
|
||||
.unwrap();
|
||||
(s, bg, active)
|
||||
}
|
||||
|
||||
/// Confirms that held pixels protect only the layer that owned them before the turn.
|
||||
#[test]
|
||||
fn turned_hidden_overhang_coverage_belongs_to_each_layer() {
|
||||
for held_active in [false, true] {
|
||||
let (mut s, bg, active) = overhang_scene(held_active);
|
||||
crop(&mut s, json!({"x":-10,"y":14,"width":20,"height":20,"angle":45}), true);
|
||||
let mut held_pixels = 0;
|
||||
for y in 0..20 {
|
||||
for x in 0..20 {
|
||||
let (held, other, want) = if held_active { (active, bg, WHITE) } else { (bg, active, GREEN) };
|
||||
pixel(doc(&s), other, x, y, want);
|
||||
let px = doc(&s).layer(held).unwrap().surface().unwrap().rgba(x, y);
|
||||
let color = if held_active { BLUE } else { RED };
|
||||
held_pixels += usize::from(px.iter().zip(color).all(|(a, b)| (a - b).abs() < 0.06));
|
||||
}
|
||||
}
|
||||
assert!(held_pixels >= 100, "the target's own hidden pixels survive: {held_pixels}");
|
||||
}
|
||||
}
|
||||
|
||||
/// An empty active raster leaves the successful Background fill and undo step intact.
|
||||
#[test]
|
||||
fn donorless_added_target_keeps_the_background_fill() {
|
||||
for turned in [false, true] {
|
||||
let (x, y) = extension_sample(turned);
|
||||
let (mut s, ids) = scene(turned);
|
||||
let empty = s
|
||||
.edit("Empty target", |d, active| {
|
||||
let layer = Layer::raster("Empty", d.pixel_format());
|
||||
let id = layer.id;
|
||||
d.layers.push(layer);
|
||||
*active = Some(id);
|
||||
Ok(id)
|
||||
})
|
||||
.unwrap();
|
||||
assert_ne!(empty, ids.background);
|
||||
let before = doc(&s).clone();
|
||||
let p = frame(turned);
|
||||
let plain = plain_control(&mut s, &p);
|
||||
let past = s.active().unwrap().history.past_len();
|
||||
crop(&mut s, p, true);
|
||||
pixel(doc(&s), ids.background, x, y, WHITE);
|
||||
unchanged(doc(&s), &plain, &[empty, ids.quads, ids.small, ids.edge, ids.hidden, ids.text]);
|
||||
assert_eq!(s.active().unwrap().active_layer, Some(empty));
|
||||
named_one_step(&s, past, "Content-aware Crop");
|
||||
undo_redo(&mut s, &before);
|
||||
}
|
||||
}
|
||||
|
||||
/// Confirms both layers synthesize their own colours at every RGB depth.
|
||||
#[test]
|
||||
fn both_target_colours_remain_native_at_each_rgb_depth() {
|
||||
for depth in [8, 16, 32] {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width":32,"height":24,"depth":depth,"background":"white"})).unwrap();
|
||||
let (bg, active) = s
|
||||
.edit("Own colours", |d, active| {
|
||||
let bg = d.background().unwrap().id;
|
||||
let layer = raster(d, "Green", Rect::new(0, 0, 32, 24), GREEN);
|
||||
let id = layer.id;
|
||||
d.layers.push(layer);
|
||||
*active = Some(id);
|
||||
Ok((bg, id))
|
||||
})
|
||||
.unwrap();
|
||||
crop(&mut s, json!({"x":0,"y":0,"width":40,"height":24}), true);
|
||||
pixel(doc(&s), bg, 36, 12, WHITE);
|
||||
pixel(doc(&s), active, 36, 12, GREEN);
|
||||
}
|
||||
}
|
||||
@@ -36,6 +36,7 @@ mod convert_keeps_references;
|
||||
mod copy_shape_placement;
|
||||
mod corpus_atn;
|
||||
mod crop_content_aware;
|
||||
mod crop_content_aware_layers;
|
||||
mod crop_delete_off_background;
|
||||
mod current_affinity_artboards;
|
||||
mod duplicate_layer_comps;
|
||||
|
||||
Reference in new issue
Block a user