Restore accepted brush sampling and fallible outside stroke accumulation

This commit is contained in:
yoriswind committed 2026-11-16 02:51:23 -08:00
1 parent a868842635
commit f95c65faa5
6 files changed
+939 -166

No files matched your search

+64 -3
View File
@@ -633,7 +633,7 @@ impl<'a> EffectPass<'a> {
}
let (w, h) = (self.w, self.h);
let base = alloc.clone(work)?;
let mut acc = vec![[0.0f32; 4]; w * h]; // premultiplied Σ share·blended
let mut acc = alloc.filled(self.big, [0.0; 4])?; // premultiplied Σ share·blended
let mut cover = vec![0.0f32; w * h];
for st in strokes.iter().copied() {
let (_, out_w) = stroke_widths(st);
@@ -647,7 +647,7 @@ impl<'a> EffectPass<'a> {
// The share already carries the Dissolve choice, so the paint itself composites as Normal.
let paint_blend = if st.common.blend == BlendMode::Dissolve { BlendMode::Normal } else { st.common.blend };
paint_fx(&mut blended, &ones, &st.paint, self.stroke_frame(st), self.anchor, self.big, paint_blend, 1.0, self.patterns);
for ((a, b), s) in acc.iter_mut().zip(&blended.px).zip(&share) {
for ((a, b), s) in acc.px.iter_mut().zip(&blended.px).zip(&share) {
if *s > 0.0 {
for c in 0..3 {
a[c] += s * b[c] * b[3];
@@ -656,7 +656,7 @@ impl<'a> EffectPass<'a> {
}
}
}
for ((p, a), c) in work.px.iter_mut().zip(&acc).zip(&cover) {
for ((p, a), c) in work.px.iter_mut().zip(&acc.px).zip(&cover) {
if *c <= 0.0 {
continue;
}
@@ -790,3 +790,64 @@ fn mix_premul(a: [f32; 4], b: [f32; 4], k: f32) -> [f32; 4] {
out[3] = alpha;
out
}
#[cfg(test)]
mod outside_stroke_allocation_tests {
use super::*;
use photocraft_color::{Color, PixelFormat};
use photocraft_doc::{FxCommon, StrokeFx};
struct RejectFilled;
impl BufferAlloc for RejectFilled {
type Error = &'static str;
fn filled(&self, _rect: Rect, _color: [f32; 4]) -> Result<Buffer, Self::Error> {
Err("outside stroke accumulator")
}
fn clone(&self, buffer: &Buffer) -> Result<Buffer, Self::Error> {
buffer.try_clone().map_err(|_| "clone allocation")
}
}
#[test]
fn enabled_outside_stroke_accumulator_propagates_allocation_failure_and_preserves_pixels() {
let rect = Rect::new(0, 0, 4, 4);
let mut layer = Layer::raster("outside stroke", PixelFormat::RGBA8);
layer.effects.items.push(Effect::Stroke(StrokeFx {
common: FxCommon::new(BlendMode::Normal, 1.0),
size: 1.0,
position: StrokePosition::Outside,
paint: FxPaint::Color(Color::rgb(0.0, 0.0, 1.0)),
overprint: false,
}));
let mut shape = Map::new(4, 4, 0.0);
for (index, value) in shape.v.iter_mut().enumerate() {
if matches!(index, 5 | 6 | 9 | 10) {
*value = 1.0;
}
}
let patterns = PreparedPatterns::new(&[], PREPARED_PATTERN_BYTES);
let texture = TextureCtx { rect, patterns: &[], anchor: (0.0, 0.0) };
let maps = build_maps(&layer, shape.v.clone(), rect, &GlobalLight::default(), &texture);
let pass = EffectPass::new(&layer, &maps, rect, rect, &patterns, None);
let strokes: Vec<_> = layer.effects.items.iter().filter_map(|effect| if let Effect::Stroke(stroke) = effect { Some(stroke) } else { None }).collect();
assert!(strokes.iter().any(|stroke| stroke_widths(stroke).1 > 0.0));
let fields = pass.stroke_fields(true);
let mut lay = Buffer::filled(rect, [0.0; 4]);
for (pixel, alpha) in lay.px.iter_mut().zip(&shape.v) {
pixel[3] = *alpha;
}
let original = Buffer::filled(rect, [1.0; 4]);
let mut failed = original.clone();
assert_eq!(pass.paint_outside_strokes_with(&mut failed, &lay, &shape, &strokes, &fields, &RejectFilled), Err("outside stroke accumulator"));
assert_eq!(failed, original, "a rejected accumulator cannot publish partial stroke pixels");
let mut legacy = original.clone();
pass.paint_outside_strokes_with(&mut legacy, &lay, &shape, &strokes, &fields, &InfallibleBufferAlloc).unwrap();
let mut fallible = original.clone();
pass.paint_outside_strokes_with(&mut fallible, &lay, &shape, &strokes, &fields, &crate::FallibleBufferAlloc).unwrap();
assert_ne!(legacy, original, "the enabled outside stroke must actually paint");
assert_eq!(fallible, legacy);
}
}
+39 -15
View File
@@ -1066,13 +1066,7 @@ fn presets_set_current(s: &mut Session, p: &Value) -> Result<Value> {
}
fn has_selection_and_pixels(s: &Session) -> std::result::Result<(), String> {
let d = s.active().ok_or("no document")?;
if d.doc.selection.is_none() {
return Err("no selection".into());
}
if d.active_layer.and_then(|id| d.doc.layer(id)).is_none() {
return Err("no active layer".into());
}
s.active().ok_or("no document")?;
Ok(())
}
@@ -1095,8 +1089,8 @@ fn define_from_selection_with_renderer(
let cmd = "brush.defineFromSelection";
let name = name_param(p, cmd)?;
let d = s.active().ok_or(EngineError::NoDocument)?;
let sel = d.doc.selection.as_ref().ok_or_else(|| bad(cmd, "no selection"))?;
let area = sel.content_bounds().intersect(&d.doc.bounds());
let sel = d.doc.selection.as_ref();
let area = sel.map_or_else(|| d.doc.bounds(), |sel| sel.content_bounds().intersect(&d.doc.bounds()));
if area.is_empty() {
return Err(bad(cmd, "the selection is empty"));
}
@@ -1110,7 +1104,7 @@ fn define_from_selection_with_renderer(
// Sparse canvases can span huge areas. Density and selection remain live while the
// compositor holds one RGBA band, not a full-canvas RGBA plane; account for that
// actual maximum band before allocating any sampling buffers.
let mask_bytes = (sel.channels() as u64).saturating_mul(4);
let mask_bytes = sel.map_or(0, |sel| (sel.channels() as u64).saturating_mul(4));
let band_rows = area.height().min(photocraft_compose::band_rows_for(area.width(), 0) as u32);
let band_bytes = u64::from(area.width()).saturating_mul(u64::from(band_rows)).saturating_mul(16);
let dense_bytes = (len as u64).saturating_mul(4u64.saturating_add(mask_bytes)).saturating_add(band_bytes);
@@ -1124,15 +1118,28 @@ fn define_from_selection_with_renderer(
)));
}
let mut v = crate::allocation::filled(len, 0.0, "defining a brush from the selection")?;
let sc = sel.channels();
let sc = sel.map_or(1, |sel| sel.channels());
// A selection mask, when present, is a second buffer of the same size; it must fail gracefully too
// (review of #5469), so read it through the fallible allocator.
let sv = crate::allocation::read_region(sel, area, "defining a brush from the selection")?;
let sv = sel.map(|sel| crate::allocation::read_region(sel, area, "defining a brush from the selection")).transpose()?;
// The compositor keeps RGB document encoding; other document models produce
// the existing RGB numeric view (including the document-profile CMYK conversion).
let source = if d.doc.mode == photocraft_color::ColorMode::Rgb {
crate::color_cmds::document_profile(&d.doc)
} else {
crate::color_cmds::working_profile(photocraft_color::ColorMode::Rgb)
};
let options = craft_cms::TransformOptions { intent: craft_cms::Intent::RelativeColorimetric, bpc: true, ..Default::default() };
let gray =
craft_cms::cached(&source, craft_cms::Builtin::SGray.profile(), options).map_err(|e| bad(cmd, format!("cannot convert brush source to gray: {e}")))?;
let mut converted = [0.0f32; 16];
// Keep the allocation boundary fallible before entering compositor-owned scratch storage.
crate::allocation::checkpoint("defining a brush from the selection")?;
let rendered = render(&d.doc, area, &mut |band| -> Result<()> {
for (row, pixels) in band.px.chunks_exact(w).enumerate() {
let y = (band.rect.y0 - area.y0) as usize + row;
for (x, c) in pixels.iter().enumerate() {
let selected = sv[(y * w + x) * sc];
let selected = sv.as_ref().map_or(1.0, |sv| sv[(y * w + x) * sc]);
// Known-zero contributions leave the freshly zeroed density alone.
if selected == 0.0 {
continue;
@@ -1140,8 +1147,19 @@ fn define_from_selection_with_renderer(
if c[3] == 0.0 {
continue;
}
let lum = photocraft_color::blend::lum([c[0], c[1], c[2]]);
v[y * w + x] = ((1.0 - lum) * c[3] * selected).clamp(0.0, 1.0);
// A sampled profile curve can clamp infinity to a finite endpoint;
// reject contributing invalid source values before the CMS can hide them.
if c.iter().any(|channel| !channel.is_finite()) {
return Err(bad(cmd, "brush source contains a non-finite colour channel"));
}
// Composite over white before the nonlinear gray conversion. The
// selection scales the resulting density once; alpha is already in it.
let over_white = [c[0], c[1], c[2]].map(|channel| channel * c[3] + (1.0 - c[3]));
gray.eval(&over_white, &mut converted).map_err(|e| bad(cmd, format!("cannot convert brush source to gray: {e}")))?;
if !converted[0].is_finite() {
return Err(bad(cmd, "brush source converted to a non-finite gray value"));
}
v[y * w + x] = ((1.0 - converted[0]) * selected).clamp(0.0, 1.0);
}
}
Ok(())
@@ -1537,3 +1555,9 @@ mod color_replacement_history_name_tests;
#[cfg(test)]
mod define_brush_merged_source_tests;
#[cfg(test)]
mod define_brush_no_selection_tests;
#[cfg(test)]
mod define_brush_color_density_tests;
@@ -0,0 +1,327 @@
//! Numeric falsifier for issue #14273; this does not change brush capture.
//!
//! Inputs are encoded sRGB RGB8 samples, composited over encoded white before
//! the cached sRGB -> sGray transform. Density is one minus encoded gray, then
//! multiplied by selection coverage exactly once. Arbitrary document profiles,
//! HDR/non-RGB sources and actual stamping remain outside this probe.
use std::sync::Arc;
use craft_cms::{Builtin, Intent, TransformOptions};
#[test]
fn sgray_matches_six_literal_density_targets_and_alpha_selection_controls() {
let source = Arc::new(Builtin::Srgb.profile().clone());
let gray = Arc::new(Builtin::SGray.profile().clone());
let options = TransformOptions { intent: Intent::RelativeColorimetric, bpc: true, ..Default::default() };
let transform = craft_cms::cached(&source, &gray, options).unwrap();
let gray_value = |rgb: [f32; 3]| {
// Same public API and output scratch size as color_cmds::swatch_in_doc.
let mut output = [0.0f32; 16];
transform.eval(&rgb, &mut output).unwrap();
assert!(output[0].is_finite(), "the CMS must return a finite gray value");
output[0].clamp(0.0, 1.0)
};
let density = |rgb: [f32; 3], alpha: f32, selection: f32| {
let over_white = rgb.map(|channel| channel * alpha + (1.0 - alpha));
(1.0 - gray_value(over_white)) * selection
};
// Independent measured targets from #14273, not values derived from the
// candidate transform or the command's existing fixed luminance weights.
let mut mismatches = Vec::new();
for (name, rgb, expected, tolerance) in [
("red", [255u8, 0, 0], 0.49f32, 0.03f32),
("green", [0, 255, 0], 0.14, 0.03),
("blue", [0, 0, 255], 0.72, 0.03),
("gray 128", [128, 128, 128], 0.50, 0.01),
("gray 200", [200, 200, 200], 0.22, 0.01),
("black", [0, 0, 0], 1.0, 0.0001),
] {
let actual = density(rgb.map(|value| f32::from(value) / 255.0), 1.0, 1.0);
eprintln!("{name}: density {actual:.6}, target {expected:.6} +/- {tolerance:.6}");
if (actual - expected).abs() > tolerance {
mismatches.push(format!("{name}: {actual:.6}, expected {expected:.6} +/- {tolerance:.6}"));
}
}
assert!(mismatches.is_empty(), "sGray candidate fails measured targets:\n{}", mismatches.join("\n"));
// Transparency is white, not an extra multiplier applied after the CMS.
assert!(density([0.0, 0.0, 1.0], 0.0, 1.0).abs() <= 0.0001);
assert!((density([0.0; 3], 0.5, 1.0) - 0.5).abs() <= 0.01);
assert!((density([0.0; 3], 1.0, 0.25) - 0.25).abs() <= 0.0001);
assert!((density([0.0; 3], 0.5, 0.5) - 0.25).abs() <= 0.01, "alpha or selection must not be applied twice");
assert_eq!(density([1.0, 0.0, 0.0], 1.0, 0.0), 0.0);
// This is an ordering control, not a new measured coloured-alpha target:
// half-transparent red is the explicit RGB sample [1, .5, .5] over white.
let half_red = density([1.0, 0.0, 0.0], 0.5, 1.0);
let explicit_over_white = 1.0 - gray_value([1.0, 0.5, 0.5]);
assert_eq!(half_red, explicit_over_white);
}
use super::{GrayTile, Session, TipShape, json};
const COMMANDS: [&str; 2] = ["brush.defineFromSelection", "edit.defineBrushPreset"];
fn rgb_source(depth: u32, rgba: [f32; 4]) -> Session {
let mut s = Session::new();
s.execute("file.new", json!({"width": 40, "height": 40, "depth": depth, "background": "#ffffff"})).unwrap();
s.edit("Colour square", |doc, active| {
doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(10, 10, 30, 30), &rgba);
Ok(())
})
.unwrap();
s
}
fn tip(s: &Session) -> &GrayTile {
let TipShape::Sampled(tip) = &s.tools.brush.tip else { panic!("expected a sampled tip") };
tip
}
fn define_square(s: &mut Session, command: &str, selected: bool) -> f32 {
if selected {
s.execute("select.rect", json!({"x": 8, "y": 8, "width": 24, "height": 24})).unwrap();
}
let doc = s.active().unwrap().doc.clone();
let history = s.active().unwrap().history.past_len();
let presets = s.tools.presets.len();
let result = s.execute(command, json!({"name": "Colour density"})).unwrap();
assert_eq!((result["width"].as_u64(), result["height"].as_u64()), (Some(20), Some(20)));
assert_eq!((tip(s).width, tip(s).height), (20, 20));
assert_eq!(s.tools.presets.len(), presets + 1);
assert_eq!(s.tools.current_preset.as_deref(), Some("Colour density"));
assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc));
assert_eq!(s.active().unwrap().history.past_len(), history);
assert_eq!(s.active().unwrap().doc.selection.is_some(), selected);
tip(s).get(10, 10)
}
#[test]
fn defined_tips_match_the_six_measured_density_targets_at_all_depths() {
for command in COMMANDS {
for depth in [8, 16, 32] {
for selected in [false, true] {
for (name, rgb, expected, tolerance) in [
("red", [255u8, 0, 0], 0.49f32, 0.03f32),
("green", [0, 255, 0], 0.14, 0.03),
("blue", [0, 0, 255], 0.72, 0.03),
("gray 128", [128, 128, 128], 0.50, 0.01),
("gray 200", [200, 200, 200], 0.22, 0.01),
("black", [0, 0, 0], 1.0, 0.0001),
] {
let [r, g, b] = rgb.map(|v| f32::from(v) / 255.0);
let mut s = rgb_source(depth, [r, g, b, 1.0]);
let actual = define_square(&mut s, command, selected);
assert!((actual - expected).abs() <= tolerance, "{command}, {name}, depth {depth}, selected {selected}: {actual}");
}
}
}
}
}
#[test]
fn command_density_applies_alpha_before_gray_and_selection_once() {
for command in COMMANDS {
for (alpha, coverage, expected) in [(0.5, 1.0, 0.5), (1.0, 0.25, 0.25), (0.5, 0.5, 0.25)] {
let mut s = rgb_source(32, [0.0, 0.0, 0.0, alpha]);
s.execute("select.rect", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap();
s.edit("Selection coverage", |doc, _| {
doc.selection.as_mut().unwrap().fill_rect(photocraft_geom::Rect::new(10, 10, 30, 30), &[coverage]);
Ok(())
})
.unwrap();
s.execute(command, json!({"name": "Coverage"})).unwrap();
assert!((tip(&s).get(10, 10) - expected).abs() <= 0.01, "{command}, alpha {alpha}, coverage {coverage}");
}
// An explicit over-white RGB square is an independent way to provide the
// same colour; this is an ordering control, not a new reference target.
let mut half_red = rgb_source(32, [1.0, 0.0, 0.0, 0.5]);
let mut over_white = rgb_source(32, [1.0, 0.5, 0.5, 1.0]);
let half = define_square(&mut half_red, command, false);
let opaque = define_square(&mut over_white, command, false);
assert!((half - opaque).abs() <= 1.0 / 65535.0);
let mut transparent = rgb_source(32, [0.0, 0.0, 1.0, 0.0]);
let brush = transparent.tools.brush.clone();
let presets = transparent.tools.presets.clone();
let err = transparent.execute(command, json!({"name": "Transparent colour"})).unwrap_err();
assert!(err.to_string().contains("contain no paint"), "{err}");
assert_eq!(transparent.tools.brush, brush);
assert_eq!(transparent.tools.presets, presets);
}
}
#[test]
fn tagged_rgb_uses_the_document_encoding() {
for command in COMMANDS {
let mut tagged = rgb_source(32, [0.5, 0.5, 0.5, 1.0]);
tagged
.edit("Assign linear RGB", |doc, _| {
doc.icc_profile = Some(Builtin::LinearSrgb.profile().to_bytes());
Ok(())
})
.unwrap();
let explicit = craft_cms::cached(Builtin::LinearSrgb.profile(), Builtin::SGray.profile(), TransformOptions::default()).unwrap();
let mut gray = [0.0f32; 16];
explicit.eval(&[0.5, 0.5, 0.5], &mut gray).unwrap();
let actual = define_square(&mut tagged, command, false);
assert!((actual - (1.0 - gray[0])).abs() <= 1.0 / 65535.0);
let mut srgb = rgb_source(32, [0.5, 0.5, 0.5, 1.0]);
let untagged = define_square(&mut srgb, command, false);
assert!((actual - untagged).abs() > 0.1, "the fixture must distinguish profile encoding");
}
}
#[test]
fn native_gray_keeps_numeric_density_in_its_existing_rgb_view() {
for command in COMMANDS {
for depth in [8, 16, 32] {
for profile in [None, Some(Builtin::DotGain20Compat), Some(Builtin::GrayGamma22)] {
for value in [128.0 / 255.0, 200.0 / 255.0, 0.0] {
let mut s = Session::new();
s.execute("file.new", json!({"width": 40, "height": 40, "mode": "gray", "depth": depth, "background": "white"})).unwrap();
s.edit("Native gray square", |doc, active| {
doc.icc_profile = profile.map(|p| p.profile().to_bytes());
doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(10, 10, 30, 30), &[value, 1.0]);
Ok(())
})
.unwrap();
let actual = define_square(&mut s, command, false);
assert!((actual - (1.0 - value)).abs() <= 0.0001, "{command}, depth {depth}, profile {profile:?}, value {value}: {actual}");
}
}
}
}
}
#[test]
fn zero_alpha_and_zero_selection_skip_hidden_colour() {
for command in COMMANDS {
for transparent in [true, false] {
for rgb in [[0.0, 0.0, 1.0], [f32::NAN, f32::INFINITY, f32::NEG_INFINITY]] {
let mut s = rgb_source(32, [0.0, 0.0, 0.0, 1.0]);
let hole = photocraft_geom::Rect::new(15, 15, 25, 25);
s.edit("Hidden colour", |doc, active| {
let alpha = if transparent { 0.0 } else { 1.0 };
doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(hole, &[rgb[0], rgb[1], rgb[2], alpha]);
Ok(())
})
.unwrap();
let st = s.active().unwrap();
let stored = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().rgba(20, 20);
assert_eq!(stored[3], if transparent { 0.0 } else { 1.0 });
for channel in 0..3 {
if rgb[channel].is_nan() {
assert!(stored[channel].is_nan(), "the non-finite fixture must reach the source read");
} else {
assert_eq!(stored[channel], rgb[channel]);
}
}
if !transparent {
s.execute("select.rect", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap();
s.edit("Zero coverage hole", |doc, _| {
doc.selection.as_mut().unwrap().fill_rect(hole, &[0.0]);
Ok(())
})
.unwrap();
// The hole stays inside the sampled area, rather than being
// removed by selection bounds before the per-pixel check.
assert_eq!(s.active().unwrap().doc.selection.as_ref().unwrap().content_bounds(), photocraft_geom::Rect::new(10, 10, 30, 30));
}
let doc = s.active().unwrap().doc.clone();
let history = s.active().unwrap().history.past_len();
let presets = s.tools.presets.len();
let made = s.execute(command, json!({"name": "Visible black border"})).unwrap();
assert_eq!((made["width"].as_u64(), made["height"].as_u64()), (Some(20), Some(20)));
assert_eq!(tip(&s).get(0, 0), 1.0);
assert_eq!(tip(&s).get(19, 19), 1.0);
assert_eq!(tip(&s).get(5, 5), 0.0, "hidden colour contributes no paint");
assert_eq!(tip(&s).get(14, 14), 0.0);
assert_eq!(s.tools.presets.len(), presets + 1);
assert_eq!(s.tools.current_preset.as_deref(), Some("Visible black border"));
assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc));
assert_eq!(s.active().unwrap().history.past_len(), history);
}
}
}
}
#[test]
fn sampled_trcs_cannot_hide_non_finite_contributing_channels() {
let mut profile = Builtin::Srgb.profile().clone();
profile.trc = profile.trc.take().map(|curves| curves.map(|curve| craft_cms::Curve::Table(curve.sample(256))));
// Reset the built-in's encoded bytes and cache key after replacing its curves.
let icc = profile.with_encoded_bytes().to_bytes();
let parsed = craft_cms::Profile::parse(&icc).unwrap();
assert!(parsed.trc.as_ref().unwrap().iter().all(|curve| matches!(curve, craft_cms::Curve::Table(_))));
let options = TransformOptions { intent: Intent::RelativeColorimetric, bpc: true, ..Default::default() };
let gray = craft_cms::cached(&parsed, Builtin::SGray.profile(), options).unwrap();
let mut converted = [0.0f32; 16];
gray.eval(&[f32::INFINITY, 0.0, 0.0], &mut converted).unwrap();
assert!(converted[0].is_finite(), "the sampled-TRC fixture must expose clamping before the command's gray check");
for command in COMMANDS {
for selected in [false, true] {
let mut finite = rgb_source(32, [1.0, 0.0, 0.0, 1.0]);
finite
.edit("Assign sampled sRGB", |doc, _| {
doc.icc_profile = Some(icc.clone());
Ok(())
})
.unwrap();
assert!((define_square(&mut finite, command, selected) - 0.49).abs() <= 0.03);
for rgba in [
[f32::INFINITY, 0.0, 0.0, 1.0],
[0.0, f32::INFINITY, 0.0, 1.0],
[0.0, 0.0, f32::INFINITY, 1.0],
[0.0, 0.0, 0.0, f32::INFINITY],
[f32::NAN, 0.0, 0.0, 1.0],
[f32::NEG_INFINITY, 0.0, 0.0, 1.0],
] {
let mut s = rgb_source(32, rgba);
s.edit("Assign sampled sRGB", |doc, _| {
doc.icc_profile = Some(icc.clone());
Ok(())
})
.unwrap();
if selected {
s.execute("select.rect", json!({"x": 8, "y": 8, "width": 24, "height": 24})).unwrap();
}
// An accepted invalid source would replace this existing preset.
s.execute("brush.presets.save", json!({"name": "Kept preset"})).unwrap();
let active = s.active().unwrap().active_layer.unwrap();
let stored = s.active().unwrap().doc.layer(active).unwrap().surface().unwrap().rgba(20, 20).map(f32::to_bits);
assert_eq!(stored, rgba.map(f32::to_bits), "non-finite values must reach the source read unchanged");
let doc = s.active().unwrap().doc.clone();
let history = s.active().unwrap().history.past_len();
let brush = s.tools.brush.clone();
let presets = s.tools.presets.clone();
let current = s.tools.current_preset.clone();
let revision = s.tools.brush_rev;
let journal = s.journal.clone();
let error = s.execute(command, json!({"name": "Kept preset"})).unwrap_err();
assert!(error.to_string().contains("non-finite"), "{command}: {error}");
assert!(Arc::ptr_eq(&doc, &s.active().unwrap().doc));
assert_eq!(s.active().unwrap().history.past_len(), history);
assert_eq!(s.active().unwrap().active_layer, Some(active));
assert_eq!(s.active().unwrap().doc.selection.is_some(), selected);
assert_eq!(s.active().unwrap().doc.icc_profile.as_ref(), Some(&icc));
assert_eq!(s.active().unwrap().doc.layer(active).unwrap().surface().unwrap().rgba(20, 20).map(f32::to_bits), stored);
assert_eq!(s.tools.brush, brush);
assert_eq!(s.tools.presets, presets);
assert_eq!(s.tools.current_preset, current);
assert_eq!(s.tools.brush_rev, revision);
assert_eq!(s.journal, journal);
}
}
}
}
@@ -23,7 +23,7 @@ fn source(depth: u32) -> Session {
}
#[test]
fn selected_visible_capture_is_identical_with_background_tip_group() {
fn visible_capture_is_identical_with_background_tip_group_or_no_active_layer() {
for command in COMMANDS {
for depth in [8, 16, 32] {
let mut s = source(depth);
@@ -31,9 +31,8 @@ fn selected_visible_capture_is_identical_with_background_tip_group() {
let painted = s.active().unwrap().active_layer.unwrap();
s.execute("layer.new.group", json!({"name": "Empty active group"})).unwrap();
let group = s.active().unwrap().active_layer.unwrap();
s.execute("select.rect", json!({"x": 50, "y": 40, "width": 100, "height": 50})).unwrap();
let mut expected = None;
for active in [Some(background), Some(painted), Some(group)] {
for active in [Some(background), Some(painted), Some(group), None] {
s.edit("Choose capture-independent active layer", |_, current| {
*current = active;
Ok(())
@@ -80,6 +79,277 @@ fn selection_limits_the_visible_composite_even_with_background_active() {
}
}
#[test]
fn visible_group_children_and_occlusion_count_but_hidden_layers_and_groups_do_not() {
for command in COMMANDS {
let mut s = Session::new();
s.execute("file.new", json!({"width": 8, "height": 8, "background": "white"})).unwrap();
s.edit("Visible and hidden composite contributors", |doc, active| {
let mut black = Layer::raster("Nested visible black", doc.pixel_format());
black.surface_mut().unwrap().fill_rect(Rect::new(1, 1, 5, 5), &[0.0, 0.0, 0.0, 1.0]);
let visible = Layer::group("Visible group", vec![black]);
let mut hidden_black = Layer::raster("Hidden black", doc.pixel_format());
hidden_black.surface_mut().unwrap().fill_rect(doc.bounds(), &[0.0, 0.0, 0.0, 1.0]);
hidden_black.visible = false;
let mut hidden_group = Layer::group("Hidden ancestor", vec![hidden_black.duplicate()]);
hidden_group.children_mut().unwrap()[0].visible = true;
hidden_group.visible = false;
let mut white = Layer::raster("Visible white occlusion", doc.pixel_format());
white.surface_mut().unwrap().fill_rect(Rect::new(1, 1, 3, 5), &[1.0, 1.0, 1.0, 1.0]);
*active = Some(hidden_black.id);
doc.layers.extend([visible, hidden_black, hidden_group, white]);
Ok(())
})
.unwrap();
s.execute(command, json!({"name": "Only visible ink"})).unwrap();
assert_eq!((tip(&s).width, tip(&s).height), (2, 4));
for y in 0..4 {
for x in 0..2 {
assert_eq!(tip(&s).get(x, y), 1.0);
}
}
}
}
#[test]
fn composite_transparency_and_selection_coverage_are_applied_once() {
for command in COMMANDS {
for depth in [8, 16, 32] {
let mut s = Session::new();
s.execute("file.new", json!({"width": 8, "height": 8, "depth": depth, "background": "transparent"})).unwrap();
s.edit("Nested translucent source", |doc, active| {
let mut black = Layer::raster("Half black", doc.pixel_format());
black.surface_mut().unwrap().fill_rect(Rect::new(1, 1, 6, 7), &[0.0, 0.0, 0.0, 0.5]);
let group = Layer::group("Active group", vec![black]);
*active = Some(group.id);
doc.layers.push(group);
Ok(())
})
.unwrap();
for selected in [false, true] {
if selected {
s.execute("select.rect", json!({"x": 0, "y": 0, "width": 8, "height": 8})).unwrap();
s.edit("Quarter coverage", |doc, _| {
doc.selection.as_mut().unwrap().fill_rect(Rect::new(0, 0, 8, 8), &[0.25]);
Ok(())
})
.unwrap();
}
s.execute(command, json!({"name": "Translucent composite"})).unwrap();
assert_eq!((tip(&s).width, tip(&s).height), (5, 6));
let expected = if selected { 0.125 } else { 0.5 };
for y in 0..6 {
for x in 0..5 {
assert!((tip(&s).get(x, y) - expected).abs() < 0.003);
}
}
}
}
}
}
#[test]
fn a_hidden_black_source_over_white_or_transparency_is_empty_and_does_not_replace_a_preset() {
for command in COMMANDS {
for background in ["white", "transparent"] {
let mut s = Session::new();
s.execute("file.new", json!({"width": 8, "height": 8, "background": background})).unwrap();
s.execute("layer.new.layer", json!({"name": "Hidden ink"})).unwrap();
s.edit("Hide all ink", |doc, active| {
let bounds = doc.bounds();
let layer = doc.layer_mut(active.unwrap()).unwrap();
layer.surface_mut().unwrap().fill_rect(bounds, &[0.0, 0.0, 0.0, 1.0]);
layer.visible = false;
Ok(())
})
.unwrap();
s.execute("brush.presets.save", json!({"name": "Kept"})).unwrap();
let brush = s.tools.brush.clone();
let presets = s.tools.presets.clone();
let current = s.tools.current_preset.clone();
let doc = s.active().unwrap().doc.clone();
let history = s.active().unwrap().history.past_len();
let err = s.execute(command, json!({"name": "Kept"})).unwrap_err();
assert!(err.to_string().contains("contain no paint"), "{err}");
assert_eq!(s.tools.brush, brush);
assert_eq!(s.tools.presets, presets);
assert_eq!(s.tools.current_preset, current);
assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc));
assert_eq!(s.active().unwrap().history.past_len(), history);
}
}
}
#[test]
fn merged_rgb_retains_the_document_profile_before_gray_conversion() {
for command in COMMANDS {
let mut s = Session::new();
s.execute("file.new", json!({"width": 8, "height": 8, "depth": 32, "background": "transparent"})).unwrap();
s.edit("Linear gray nested under active group", |doc, active| {
doc.icc_profile = Some(craft_cms::Builtin::LinearSrgb.profile().to_bytes());
let mut layer = Layer::raster("Linear half gray", doc.pixel_format());
layer.surface_mut().unwrap().fill_rect(Rect::new(1, 1, 5, 5), &[0.5, 0.5, 0.5, 1.0]);
let group = Layer::group("Active group", vec![layer]);
*active = Some(group.id);
doc.layers.push(group);
Ok(())
})
.unwrap();
s.execute(command, json!({"name": "Profiled merged tip"})).unwrap();
assert_eq!((tip(&s).width, tip(&s).height), (4, 4));
// Encoded sGray for linear RGB 0.5 is about 0.735, not encoded RGB 0.5.
assert!((tip(&s).get(0, 0) - 0.265).abs() < 0.01);
}
}
fn sparse_budget_source(width: u32, height: u32, selected: bool) -> Session {
let mut s = Session::new();
s.execute("file.new", json!({"width": width, "height": height, "background": "transparent"})).unwrap();
s.edit("Sparse composite budget fixture", |doc, active| {
let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap();
surf.fill_rect(Rect::new(0, 0, 1, 1), &[0.0, 0.0, 0.0, 1.0]);
assert_eq!(surf.tile_count(), 1);
if selected {
let mut mask = Surface::new(photocraft_color::PixelFormat::GRAY8);
mask.fill_rect(Rect::new(0, 0, 1, 1), &[1.0]);
mask.fill_rect(Rect::new(width as i32 - 1, height as i32 - 1, width as i32, height as i32), &[1.0]);
assert_eq!(mask.tile_count(), 2);
assert_eq!(mask.content_bounds(), doc.bounds());
doc.selection = Some(mask);
}
Ok(())
})
.unwrap();
s
}
#[test]
fn composite_storage_is_counted_with_density_and_mask_before_any_allocation() {
const WIDTH: u32 = 32768;
for command in COMMANDS {
for selected in [false, true] {
// Density plus optional mask fit exactly; the simultaneously live RGBA band
// must also count, even though the document itself is sparse.
let bytes = if selected { 8 } else { 4 };
let height = (crate::allocation::MAX_DENSE_BYTES / (bytes * u64::from(WIDTH))) as u32;
let mut s = sparse_budget_source(WIDTH, height, selected);
let doc = s.active().unwrap().doc.clone();
let brush = s.tools.brush.clone();
let presets = s.tools.presets.clone();
let current = s.tools.current_preset.clone();
let history = s.active().unwrap().history.past_len();
crate::allocation::fail_next_for_test();
let result = s.execute(command, json!({"name": "Composite over budget"}));
let unspent = crate::allocation::capacity::<u8>(0, "consume composite budget failpoint");
let err = result.unwrap_err();
assert!(err.to_string().contains("working memory"), "{err}");
assert!(unspent.is_err(), "budget refusal must precede the first allocation");
assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc));
assert_eq!(s.active().unwrap().history.past_len(), history);
assert_eq!(s.tools.brush, brush);
assert_eq!(s.tools.presets, presets);
assert_eq!(s.tools.current_preset, current);
}
}
}
#[test]
fn compositor_allocation_boundary_failure_preserves_source_and_preset_state() {
for command in COMMANDS {
for selected in [false, true] {
let mut s = source(8);
if selected {
s.execute("select.rect", json!({"x": 0, "y": 0, "width": 200, "height": 150})).unwrap();
}
let doc = s.active().unwrap().doc.clone();
let history = s.active().unwrap().history.past_len();
let brush = s.tools.brush.clone();
let presets = s.tools.presets.clone();
let current = s.tools.current_preset.clone();
crate::allocation::fail_after_for_test(if selected { 2 } else { 1 });
let result = s.execute(command, json!({"name": "Compositor allocation failure"}));
let _ = crate::allocation::capacity::<u8>(0, "reset compositor failpoint");
let err = result.unwrap_err();
assert!(err.to_string().contains("not enough memory"), "{err}");
assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc));
assert_eq!(s.active().unwrap().history.past_len(), history);
assert_eq!(s.tools.brush, brush);
assert_eq!(s.tools.presets, presets);
assert_eq!(s.tools.current_preset, current);
}
}
}
#[test]
fn a_banded_capture_that_fits_the_budget_is_not_charged_for_a_full_rgba_canvas() {
const WIDTH: u32 = 32768;
let band_rows = photocraft_compose::band_rows_for(WIDTH, 0) as u64;
let band_bytes = u64::from(WIDTH) * band_rows * 16;
for command in COMMANDS {
for selected in [false, true] {
let sample_bytes = if selected { 8 } else { 4 };
let height = ((crate::allocation::MAX_DENSE_BYTES - band_bytes) / (sample_bytes * u64::from(WIDTH))) as u32;
let pixels = u64::from(WIDTH) * u64::from(height);
assert!(pixels * sample_bytes + band_bytes <= crate::allocation::MAX_DENSE_BYTES);
assert!(pixels * (sample_bytes + 16) > crate::allocation::MAX_DENSE_BYTES, "a full-plane estimate would incorrectly reject this fixture");
let mut s = sparse_budget_source(WIDTH, height, selected);
let doc = s.active().unwrap().doc.clone();
let brush = s.tools.brush.clone();
let presets = s.tools.presets.clone();
// Refuse the first real allocation, after verifying that the budget allowed it.
crate::allocation::fail_next_for_test();
let result = s.execute(command, json!({"name": "Fits with bands"}));
let unspent = crate::allocation::capacity::<u8>(0, "consume band acceptance failpoint");
let err = result.unwrap_err().to_string();
assert!(err.contains("not enough memory") && !err.contains("working memory"), "{err}");
assert!(unspent.is_ok(), "the accepted budget must reach the first allocation");
assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc));
assert_eq!(s.tools.brush, brush);
assert_eq!(s.tools.presets, presets);
}
}
}
#[test]
fn selected_visible_capture_is_identical_with_background_tip_group() {
for command in COMMANDS {
for depth in [8, 16, 32] {
let mut s = source(depth);
let background = s.active().unwrap().doc.layers[0].id;
let painted = s.active().unwrap().active_layer.unwrap();
s.execute("layer.new.group", json!({"name": "Empty active group"})).unwrap();
let group = s.active().unwrap().active_layer.unwrap();
s.execute("select.rect", json!({"x": 50, "y": 40, "width": 100, "height": 50})).unwrap();
let mut expected = None;
for active in [Some(background), Some(painted), Some(group)] {
s.edit("Choose capture-independent active layer", |_, current| {
*current = active;
Ok(())
})
.unwrap();
let doc = s.active().unwrap().doc.clone();
let history = s.active().unwrap().history.past_len();
assert!(s.is_enabled(command));
let made = s.execute(command, json!({"name": "Merged tip"})).unwrap();
assert_eq!((made["width"].as_u64(), made["height"].as_u64()), (Some(100), Some(50)));
assert_eq!(s.tools.brush.size, 100.0);
assert_eq!(tip(&s).get(0, 0), 1.0);
assert_eq!(tip(&s).get(60, 0), 0.0);
assert!((tip(&s).get(70, 20) - 127.0 / 255.0).abs() < 0.003);
let pixels: Vec<_> = (0..50).flat_map(|y| (0..100).map(move |x| (x, y))).map(|(x, y)| tip(&s).get(x, y)).collect();
if let Some(expected) = &expected {
assert_eq!(&pixels, expected);
} else {
expected = Some(pixels);
}
assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc));
assert_eq!(s.active().unwrap().active_layer, active);
assert_eq!(s.active().unwrap().history.past_len(), history);
}
}
}
}
#[test]
fn visible_composite_keeps_occlusion_and_ignores_hidden_source() {
for command in COMMANDS {
@@ -109,122 +379,6 @@ fn visible_composite_keeps_occlusion_and_ignores_hidden_source() {
}
}
#[test]
fn composite_transparency_and_selection_coverage_are_applied_once() {
for command in COMMANDS {
for depth in [8, 16, 32] {
let mut s = Session::new();
s.execute("file.new", json!({"width": 8, "height": 8, "depth": depth, "background": "transparent"})).unwrap();
s.edit("Nested translucent source", |doc, active| {
let mut black = Layer::raster("Half black", doc.pixel_format());
black.surface_mut().unwrap().fill_rect(Rect::new(1, 1, 6, 7), &[0.0, 0.0, 0.0, 0.5]);
*active = Some(black.id);
doc.layers.push(black);
Ok(())
})
.unwrap();
for coverage in [1.0f32, 0.25] {
s.execute("select.rect", json!({"x": 0, "y": 0, "width": 8, "height": 8})).unwrap();
if coverage < 1.0 {
s.edit("Quarter coverage", |doc, _| {
doc.selection.as_mut().unwrap().fill_rect(Rect::new(0, 0, 8, 8), &[coverage]);
Ok(())
})
.unwrap();
}
s.execute(command, json!({"name": "Translucent composite"})).unwrap();
assert_eq!((tip(&s).width, tip(&s).height), (5, 6));
let expected = 0.5 * coverage;
for y in 0..6 {
for x in 0..5 {
assert!((tip(&s).get(x, y) - expected).abs() < 0.003);
}
}
}
}
}
}
#[test]
fn a_hidden_black_source_over_white_or_transparency_is_empty_and_does_not_replace_a_preset() {
for command in COMMANDS {
for background in ["white", "transparent"] {
let mut s = Session::new();
s.execute("file.new", json!({"width": 8, "height": 8, "background": background})).unwrap();
s.execute("layer.new.layer", json!({"name": "Hidden ink"})).unwrap();
s.edit("Hide all ink", |doc, active| {
let bounds = doc.bounds();
let layer = doc.layer_mut(active.unwrap()).unwrap();
layer.surface_mut().unwrap().fill_rect(bounds, &[0.0, 0.0, 0.0, 1.0]);
layer.visible = false;
Ok(())
})
.unwrap();
s.execute("select.rect", json!({"x": 0, "y": 0, "width": 8, "height": 8})).unwrap();
s.execute("brush.presets.save", json!({"name": "Kept"})).unwrap();
let brush = s.tools.brush.clone();
let presets = s.tools.presets.clone();
let current = s.tools.current_preset.clone();
let doc = s.active().unwrap().doc.clone();
let history = s.active().unwrap().history.past_len();
let err = s.execute(command, json!({"name": "Kept"})).unwrap_err();
assert!(err.to_string().contains("contain no paint"), "{err}");
assert_eq!(s.tools.brush, brush);
assert_eq!(s.tools.presets, presets);
assert_eq!(s.tools.current_preset, current);
assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc));
assert_eq!(s.active().unwrap().history.past_len(), history);
}
}
}
fn sparse_budget_source(width: u32, height: u32, selected: bool) -> Session {
let mut s = Session::new();
s.execute("file.new", json!({"width": width, "height": height, "background": "transparent"})).unwrap();
s.edit("Sparse composite budget fixture", |doc, active| {
let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap();
surf.fill_rect(Rect::new(0, 0, 1, 1), &[0.0, 0.0, 0.0, 1.0]);
assert_eq!(surf.tile_count(), 1);
if selected {
let mut mask = Surface::new(photocraft_color::PixelFormat::GRAY8);
mask.fill_rect(Rect::new(0, 0, 1, 1), &[1.0]);
mask.fill_rect(Rect::new(width as i32 - 1, height as i32 - 1, width as i32, height as i32), &[1.0]);
assert_eq!(mask.tile_count(), 2);
assert_eq!(mask.content_bounds(), doc.bounds());
doc.selection = Some(mask);
}
Ok(())
})
.unwrap();
s
}
#[test]
fn composite_storage_is_counted_with_density_and_mask_before_any_allocation() {
const WIDTH: u32 = 32768;
for command in COMMANDS {
// This selected case covers the density, selection mask and live compositor band.
let height = (crate::allocation::MAX_DENSE_BYTES / (8 * u64::from(WIDTH))) as u32;
let mut s = sparse_budget_source(WIDTH, height, true);
let doc = s.active().unwrap().doc.clone();
let brush = s.tools.brush.clone();
let presets = s.tools.presets.clone();
let current = s.tools.current_preset.clone();
let history = s.active().unwrap().history.past_len();
crate::allocation::fail_next_for_test();
let result = s.execute(command, json!({"name": "Composite over budget"}));
let unspent = crate::allocation::capacity::<u8>(0, "consume composite budget failpoint");
let err = result.unwrap_err();
assert!(err.to_string().contains("working memory"), "{err}");
assert!(unspent.is_err(), "budget refusal must precede the first allocation");
assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc));
assert_eq!(s.active().unwrap().history.past_len(), history);
assert_eq!(s.tools.brush, brush);
assert_eq!(s.tools.presets, presets);
assert_eq!(s.tools.current_preset, current);
}
}
#[test]
fn selection_buffer_failure_preserves_source_and_preset_state() {
for command in COMMANDS {
@@ -247,31 +401,3 @@ fn selection_buffer_failure_preserves_source_and_preset_state() {
assert_eq!(s.tools.current_preset, current);
}
}
#[test]
fn a_banded_capture_that_fits_the_budget_is_not_charged_for_a_full_rgba_canvas() {
const WIDTH: u32 = 32768;
let band_rows = photocraft_compose::band_rows_for(WIDTH, 0) as u64;
let band_bytes = u64::from(WIDTH) * band_rows * 16;
for command in COMMANDS {
let sample_bytes = 8;
let height = ((crate::allocation::MAX_DENSE_BYTES - band_bytes) / (sample_bytes * u64::from(WIDTH))) as u32;
let pixels = u64::from(WIDTH) * u64::from(height);
assert!(pixels * sample_bytes + band_bytes <= crate::allocation::MAX_DENSE_BYTES);
assert!(pixels * (sample_bytes + 16) > crate::allocation::MAX_DENSE_BYTES, "a full-plane estimate would incorrectly reject this fixture");
let mut s = sparse_budget_source(WIDTH, height, true);
let doc = s.active().unwrap().doc.clone();
let brush = s.tools.brush.clone();
let presets = s.tools.presets.clone();
// Refuse the first real allocation, after verifying that the budget allowed it.
crate::allocation::fail_next_for_test();
let result = s.execute(command, json!({"name": "Fits with bands"}));
let unspent = crate::allocation::capacity::<u8>(0, "consume band acceptance failpoint");
let err = result.unwrap_err().to_string();
assert!(err.contains("not enough memory") && !err.contains("working memory"), "{err}");
assert!(unspent.is_ok(), "the accepted budget must reach the first allocation");
assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc));
assert_eq!(s.tools.brush, brush);
assert_eq!(s.tools.presets, presets);
}
}
@@ -0,0 +1,235 @@
use super::*;
const COMMANDS: [&str; 2] = ["edit.defineBrushPreset", "brush.defineFromSelection"];
fn source(depth: u32) -> Session {
let mut s = Session::new();
s.execute("file.new", json!({"width": 200, "height": 150, "depth": depth, "background": "#ffffff"})).unwrap();
s.execute("layer.new.layer", json!({"name": "Tip"})).unwrap();
s.edit("BrushSrc", |doc, active| {
let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap();
surf.fill_rect(Rect::new(50, 40, 90, 70), &[0.0, 0.0, 0.0, 1.0]);
surf.fill_rect(Rect::new(120, 60, 150, 90), &[128.0 / 255.0, 128.0 / 255.0, 128.0 / 255.0, 1.0]);
Ok(())
})
.unwrap();
s
}
fn tip(s: &Session) -> &GrayTile {
let TipShape::Sampled(tip) = &s.tools.brush.tip else { panic!("expected a sampled tip") };
tip
}
#[test]
fn without_selection_the_canvas_is_trimmed_to_the_measured_content() {
for command in COMMANDS {
for depth in [8, 16, 32] {
let mut s = source(depth);
assert!(s.active().unwrap().doc.selection.is_none());
assert!(s.is_enabled(command), "{command}, depth {depth}");
let doc = s.active().unwrap().doc.clone();
let history = s.active().unwrap().history.past_len();
let presets = s.tools.presets.len();
let result = s.execute(command, json!({"name": "Canvas tip"})).unwrap();
assert_eq!((result["width"].as_u64(), result["height"].as_u64()), (Some(100), Some(50)));
assert_eq!(s.tools.brush.size, 100.0);
assert_eq!((tip(&s).width, tip(&s).height), (100, 50));
assert_eq!(tip(&s).get(0, 0), 1.0);
assert_eq!(tip(&s).get(60, 0), 0.0, "transparent gap contributes no paint");
assert!((tip(&s).get(70, 20) - 127.0 / 255.0).abs() < 0.003);
assert_eq!(s.tools.presets.len(), presets + 1);
assert_eq!(s.tools.current_preset.as_deref(), Some("Canvas tip"));
assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc), "source document is untouched");
assert_eq!(s.active().unwrap().history.past_len(), history);
assert!(s.active().unwrap().doc.selection.is_none(), "no synthetic selection is left behind");
}
}
}
#[test]
fn an_existing_selection_still_limits_the_tip_to_the_grey_square() {
for command in COMMANDS {
let mut s = source(8);
s.execute("select.rect", json!({"x": 115, "y": 55, "width": 40, "height": 40})).unwrap();
let result = s.execute(command, json!({"name": "Selected tip"})).unwrap();
assert_eq!((result["width"].as_u64(), result["height"].as_u64()), (Some(30), Some(30)));
assert_eq!(s.tools.brush.size, 30.0);
assert!((tip(&s).get(0, 0) - 127.0 / 255.0).abs() < 0.003);
assert!(s.active().unwrap().doc.selection.is_some());
}
}
#[test]
fn a_partial_selection_keeps_coverage_alpha_and_canvas_clipping() {
let mut s = Session::new();
s.execute("file.new", json!({"width": 8, "height": 8, "background": "transparent"})).unwrap();
s.edit("Half opaque source", |doc, active| {
let bounds = doc.bounds();
doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(bounds, &[0.0, 0.0, 0.0, 0.5]);
Ok(())
})
.unwrap();
s.execute("select.rect", json!({"x": -3, "y": -2, "width": 8, "height": 8})).unwrap();
s.edit("Partial coverage", |doc, _| {
doc.selection.as_mut().unwrap().fill_rect(Rect::new(0, 0, 5, 6), &[0.25]);
Ok(())
})
.unwrap();
s.execute("brush.defineFromSelection", json!({"name": "Masked tip"})).unwrap();
assert_eq!((tip(&s).width, tip(&s).height), (5, 6));
assert!((tip(&s).get(0, 0) - 0.125).abs() < 0.003, "density includes source alpha and selection coverage");
assert!((tip(&s).get(4, 5) - 0.125).abs() < 0.003);
}
#[test]
fn no_document_is_disabled_and_a_group_active_capture_uses_visible_pixels() {
let mut s = Session::new();
for command in COMMANDS {
assert!(!s.is_enabled(command));
assert!(s.execute(command, json!({"name": "No document"})).is_err());
}
s = source(8);
s.execute("layer.new.group", json!({"name": "Not pixels"})).unwrap();
for command in COMMANDS {
assert!(s.is_enabled(command));
s.execute(command, json!({"name": "Visible pixels"})).unwrap();
assert_eq!((tip(&s).width, tip(&s).height), (100, 50));
}
}
#[test]
fn a_large_canvas_is_trimmed_before_the_existing_tip_side_limit() {
let mut s = Session::new();
s.execute("file.new", json!({"width": MAX_TIP + 1, "height": 2, "background": "#ffffff"})).unwrap();
s.edit("One black pixel", |doc, active| {
doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(MAX_TIP as i32, 0, MAX_TIP as i32 + 1, 1), &[0.0, 0.0, 0.0, 1.0]);
Ok(())
})
.unwrap();
let made = s.execute("edit.defineBrushPreset", json!({"name": "One pixel"})).unwrap();
assert_eq!((made["width"].as_u64(), made["height"].as_u64()), (Some(1), Some(1)));
assert_eq!(tip(&s).get(0, 0), 1.0);
s.edit("Too wide painted area", |doc, active| {
let bounds = doc.bounds();
doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(bounds, &[0.0, 0.0, 0.0, 1.0]);
Ok(())
})
.unwrap();
let brush = s.tools.brush.clone();
let presets = s.tools.presets.clone();
let err = s.execute("edit.defineBrushPreset", json!({"name": "Too wide"})).unwrap_err();
assert!(err.to_string().contains("too large for a brush tip"), "{err}");
assert_eq!(s.tools.brush, brush);
assert_eq!(s.tools.presets, presets);
}
#[test]
fn a_canvas_capture_allocation_failure_leaves_the_source_and_presets_unchanged() {
let mut s = source(8);
let brush = s.tools.brush.clone();
let presets = s.tools.presets.clone();
let current = s.tools.current_preset.clone();
let doc = s.active().unwrap().doc.clone();
let history = s.active().unwrap().history.past_len();
crate::allocation::fail_next_for_test();
let result = s.execute("brush.defineFromSelection", json!({"name": "Allocation failure"}));
let _ = crate::allocation::capacity::<u8>(0, "reset failpoint");
let err = result.unwrap_err().to_string();
assert!(err.contains("not enough memory") && err.contains("defining a brush from the selection"), "{err}");
assert_eq!(s.tools.brush, brush);
assert_eq!(s.tools.presets, presets);
assert_eq!(s.tools.current_preset, current);
assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc));
assert_eq!(s.active().unwrap().history.past_len(), history);
}
// Sparse source and mask fixtures keep just one or two tiles, even when their
// bounds would require gigabytes of dense sampling buffers.
fn budget_source(width: u32, height: u32, selected: bool) -> Session {
let mut s = Session::new();
s.execute("file.new", json!({"width": width, "height": height, "background": "transparent"})).unwrap();
s.edit("Sparse budget source", |doc, active| {
let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap();
surf.fill_rect(Rect::new(0, 0, 1, 1), &[0.0, 0.0, 0.0, 1.0]);
assert_eq!(surf.tile_count(), 1);
if selected {
let mut mask = photocraft_raster::Surface::new(photocraft_color::PixelFormat::GRAY8);
mask.fill_rect(Rect::new(0, 0, 1, 1), &[1.0]);
mask.fill_rect(Rect::new(width as i32 - 1, height as i32 - 1, width as i32, height as i32), &[1.0]);
assert_eq!(mask.tile_count(), 2);
assert_eq!(mask.content_bounds(), doc.bounds());
doc.selection = Some(mask);
}
Ok(())
})
.unwrap();
s
}
fn assert_budget_refusal(s: &mut Session, command: &str) {
let brush = s.tools.brush.clone();
let presets = s.tools.presets.clone();
let current = s.tools.current_preset.clone();
let doc = s.active().unwrap().doc.clone();
let history = s.active().unwrap().history.past_len();
let revision = s.active().unwrap().revision;
// This also makes the regression safe on the unfixed code: its first dense
// allocation fails instead of trying to fill the enormous buffer.
crate::allocation::fail_next_for_test();
let result = s.execute(command, json!({"name": "Over budget"}));
let unspent = crate::allocation::capacity::<u8>(0, "consume budget test failpoint");
let err = result.unwrap_err().to_string();
assert!(err.contains("working memory") && err.contains("defining a brush from the selection"), "{err}");
assert!(unspent.is_err(), "the budget refusal must precede the first fallible allocation");
assert_eq!(s.tools.brush, brush);
assert_eq!(s.tools.presets, presets);
assert_eq!(s.tools.current_preset, current);
assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc));
assert_eq!(s.active().unwrap().history.past_len(), history);
assert_eq!(s.active().unwrap().revision, revision);
}
#[test]
fn an_over_budget_canvas_is_refused_before_sampling() {
const WIDTH: u32 = 32768;
// The pixel count fits usize on both targets, while its f32 density buffer
// alone is just over that target's dense-memory budget.
let height = (crate::allocation::MAX_DENSE_BYTES / (4 * u64::from(WIDTH))) as u32 + 1;
for command in COMMANDS {
let mut s = budget_source(WIDTH, height, false);
assert!(s.active().unwrap().doc.selection.is_none());
assert_budget_refusal(&mut s, command);
}
}
#[test]
fn selection_capture_counts_density_and_mask_buffers_together() {
const WIDTH: u32 = 32768;
let height = (crate::allocation::MAX_DENSE_BYTES / (4 * u64::from(WIDTH))) as u32;
let density_bytes = u64::from(WIDTH) * u64::from(height) * 4;
assert_eq!(density_bytes, crate::allocation::MAX_DENSE_BYTES, "density alone would fit; the live mask must also count");
for command in COMMANDS {
let mut s = budget_source(WIDTH, height, true);
assert_eq!(s.active().unwrap().doc.selection.as_ref().unwrap().channels(), 1);
assert_budget_refusal(&mut s, command);
}
}
#[test]
fn a_small_selection_on_an_over_budget_canvas_still_defines_a_tip() {
const WIDTH: u32 = 32768;
let height = (crate::allocation::MAX_DENSE_BYTES / (4 * u64::from(WIDTH))) as u32 + 1;
for command in COMMANDS {
let mut s = budget_source(WIDTH, height, false);
s.execute("select.rect", json!({"x": 0, "y": 0, "width": 1, "height": 1})).unwrap();
let result = s.execute(command, json!({"name": "Small selected tip"})).unwrap();
assert_eq!((result["width"].as_u64(), result["height"].as_u64()), (Some(1), Some(1)));
assert_eq!(tip(&s).get(0, 0), 1.0);
}
}
@@ -756,7 +756,7 @@ fn preset_manager_brush_delete_clears_current_preset() {
#[test]
fn define_brush_preset_wraps_define_from_selection() {
let mut s = session(8);
assert!(!s.is_enabled("edit.defineBrushPreset"));
assert!(s.is_enabled("edit.defineBrushPreset"));
s.execute("edit.fill", json!({"color": "#000000"})).unwrap();
s.execute("select.rect", json!({"x": 2, "y": 2, "width": 10, "height": 10})).unwrap();
s.execute("edit.defineBrushPreset", json!({})).unwrap();