Merge main into fix/transform-copies-raster-effects-groups

This commit is contained in:
dotCooCoo
2026-11-16 10:35:16 -08:00
437 changed files with 26949 additions and 2693 deletions
+3 -3
View File
@@ -17,10 +17,10 @@ vectorcraft-text = { workspace = true }
vectorcraft-plugins = { workspace = true }
vectorcraft-trace = { workspace = true }
image = { workspace = true }
craft-image-codecs = { workspace = true }
kurbo = { workspace = true }
# Effect › SVG Filters draws its filters with resvg (MIT OR Apache-2.0), at the usvg version the
# workspace reads SVG with; raster-images decodes the object's pixels it hands the filter as a PNG.
resvg = { version = "0.48", default-features = false, features = ["raster-images"] }
# Effect › SVG Filters draws its filters with craft-svg's resvg (`tree-render`).
craft-svg = { workspace = true, features = ["tree-render"] }
# The number lists of filter attributes, read as usvg reads them (MIT OR Apache-2.0; already used by usvg).
svgtypes = "0.16"
serde_json = { workspace = true }
+36 -14
View File
@@ -6,7 +6,6 @@
//! lies one pixel per point at 100 %, centered on the object's center and repeated in both
//! directions.
use std::io::Cursor;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, PoisonError};
@@ -85,9 +84,15 @@ impl LoadedTexture {
/// Its [`TEXTURE_IMAGE`] value: the gray levels as a grayscale PNG, base64; `None` when the
/// PNG can't be written.
pub fn to_stored(&self) -> Option<String> {
let img = image::GrayImage::from_raw(self.width, self.height, self.gray.clone())?;
let mut png = Vec::new();
img.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).ok()?;
let img = craft_image_codecs::Image::from_raw(
self.width,
self.height,
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U8,
self.gray.clone(),
)
.ok()?;
let png = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()?;
Some(base64_encode(&png))
}
@@ -95,21 +100,38 @@ impl LoadedTexture {
/// `None` when `png` isn't a PNG or holds no pixels.
/// `None` too when its gray levels would take the live textures past [`MAX_LIVE`].
fn from_png(png: &[u8]) -> Option<Self> {
let reader = || {
let mut reader = image::ImageReader::with_format(Cursor::new(png), image::ImageFormat::Png);
let mut limits = image::Limits::default();
limits.max_alloc = Some(vectorcraft_doc::MAX_RASTER_ALLOC);
reader.limits(limits);
reader
};
let (w, h) = reader().into_dimensions().ok()?;
let (w, h) = Self::png_ihdr_size(png)?;
let gray = (w as usize).checked_mul(h as usize)?;
if LIVE.load(Ordering::Relaxed).saturating_add(gray) > MAX_LIVE {
return None;
}
let img = reader().decode().ok()?.to_luma8();
let mut opts = craft_image_codecs::DecodeOptions::default();
opts.limits.max_alloc = vectorcraft_doc::MAX_RASTER_ALLOC;
// The codec default caps each side at 2^18; a stored texture can be longer than that and
// still fit the live and allocation budgets.
opts.limits.max_width = u32::MAX;
opts.limits.max_height = u32::MAX;
let img = craft_image_codecs::decode_as_with(craft_image_codecs::Format::Png, png, &opts).ok()?;
let (width, height) = img.dimensions();
(width > 0 && height > 0).then(|| Self::new(width, height, img.into_raw()))
if width == 0 || height == 0 {
return None;
}
use craft_image_codecs::{ChannelLayout as L, SampleType as S};
let luma = match (img.layout(), img.sample_type()) {
(L::Gray, S::U8) => img.into_data(),
_ => image::RgbaImage::from_raw(width, height, img.to_rgba8()).map(image::DynamicImage::ImageRgba8)?.into_luma8().into_raw(),
};
Some(Self::new(width, height, luma))
}
/// Read `(width, height)` from a PNG's IHDR chunk without decoding pixels.
fn png_ihdr_size(png: &[u8]) -> Option<(u32, u32)> {
if png.len() < 24 || &png[..8] != b"\x89PNG\r\n\x1a\n" || &png[12..16] != b"IHDR" {
return None;
}
let w = u32::from_be_bytes(png[16..20].try_into().ok()?);
let h = u32::from_be_bytes(png[20..24].try_into().ok()?);
Some((w, h))
}
/// The surface's height (points) at `p` (points at 100 %, from the object's center): the gray
+8
View File
@@ -1704,6 +1704,14 @@ fn a_loaded_texture_is_its_gray_over_middle_gray() {
assert!(texture("not base64!").is_none() && texture("aGVsbG8=").is_none(), "base64 of a PNG only");
}
/// A stored texture longer than the codec's default 2^18-pixel side still reads back.
#[test]
fn a_stored_texture_longer_than_the_codec_default_side_reads_back() {
let t = LoadedTexture::from_rgba(262_145, 1, &vec![128; 262_145 * 4]).and_then(|t| t.to_stored()).unwrap();
let loaded = texture(&t).unwrap();
assert_eq!(loaded.size(), (262_145, 1));
}
#[test]
fn glass_bends_the_image_by_a_loaded_texture() {
let (w, h) = (48, 40);
+28 -16
View File
@@ -8,7 +8,8 @@
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use resvg::{tiny_skia, usvg};
use craft_svg::tree::draw::{resvg, tiny_skia};
use craft_svg::tree::usvg;
use serde_json::Value;
use usvg::roxmltree;
use vectorcraft_doc::SvgFilter;
@@ -624,17 +625,27 @@ fn write_drop_shadow(n: roxmltree::Node, input: &str, result: Option<&str>, name
/// first bytes whatever its `data:` URL says, of at most [`MAX_IMAGE_PIXELS`] pixels by its header.
/// `None` for anything else, SVG and compressed SVG included.
fn raster_image_sized(data: Arc<Vec<u8>>) -> Option<(usvg::ImageKind, u64)> {
let format = image::guess_format(&data).ok()?;
let (w, h) = image::ImageReader::with_format(std::io::Cursor::new(data.as_slice()), format).into_dimensions().ok()?;
let format = craft_image_codecs::detect(&data)?;
let (w, h) = match format {
craft_image_codecs::Format::Png => {
if data.len() < 24 || &data[..8] != b"\x89PNG\r\n\x1a\n" || &data[12..16] != b"IHDR" {
return None;
}
(u32::from_be_bytes(data[16..20].try_into().ok()?), u32::from_be_bytes(data[20..24].try_into().ok()?))
}
craft_image_codecs::Format::Jpeg => craft_image_codecs::jpeg_info(&data).map(|j| (j.width, j.height))?,
craft_image_codecs::Format::Gif | craft_image_codecs::Format::WebP => craft_image_codecs::probe_size(&data).ok()?,
_ => return None,
};
let pixels = u64::from(w) * u64::from(h);
if pixels == 0 || pixels > MAX_IMAGE_PIXELS {
return None;
}
let kind = match format {
image::ImageFormat::Png => usvg::ImageKind::PNG(data),
image::ImageFormat::Jpeg => usvg::ImageKind::JPEG(data),
image::ImageFormat::Gif => usvg::ImageKind::GIF(data),
image::ImageFormat::WebP => usvg::ImageKind::WEBP(data),
craft_image_codecs::Format::Png => usvg::ImageKind::PNG(data),
craft_image_codecs::Format::Jpeg => usvg::ImageKind::JPEG(data),
craft_image_codecs::Format::Gif => usvg::ImageKind::GIF(data),
craft_image_codecs::Format::WebP => usvg::ImageKind::WEBP(data),
_ => return None,
};
Some((kind, pixels))
@@ -1636,7 +1647,6 @@ fn on_canvas(data: &[u8], w: usize, h: usize, cw: u32, ch: u32, to_canvas: Affin
/// The pixels of `data` (premultiplied RGBA8, `w` wide) in columns x0..x1 and rows y0..y1, as a PNG.
fn png_of(data: &[u8], w: usize, x0: usize, y0: usize, x1: usize, y1: usize) -> Option<Vec<u8>> {
use image::ImageEncoder;
let px = data.as_chunks::<4>().0;
let mut straight = Vec::with_capacity((x1 - x0) * (y1 - y0) * 4);
for y in y0..y1 {
@@ -1646,14 +1656,16 @@ fn png_of(data: &[u8], w: usize, x0: usize, y0: usize, x1: usize, y1: usize) ->
straight.extend_from_slice(&[un(p[0]), un(p[1]), un(p[2]), p[3]]);
}
}
let mut png = vec![];
let encoder = image::codecs::png::PngEncoder::new_with_quality(
&mut png,
image::codecs::png::CompressionType::Fast,
image::codecs::png::FilterType::NoFilter,
);
encoder.write_image(&straight, (x1 - x0) as u32, (y1 - y0) as u32, image::ExtendedColorType::Rgba8).ok()?;
Some(png)
let raw = craft_image_codecs::Image::from_raw(
(x1 - x0) as u32,
(y1 - y0) as u32,
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U8,
straight,
)
.ok()?;
let opts = craft_image_codecs::EncodeOptions { png_compression: craft_image_codecs::PngCompression::Fast, ..Default::default() };
craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &opts).ok()
}
/// `a` as an SVG `matrix(…)`.
+11 -8
View File
@@ -520,16 +520,15 @@ fn the_filter_is_drawn_and_written_from_its_filter_parts_alone() {
#[test]
fn filter_images_are_small_raster_images() {
fn png(w: u32, h: u32) -> Vec<u8> {
let mut out = vec![];
image::ImageEncoder::write_image(
image::codecs::png::PngEncoder::new(&mut out),
&vec![0; (w * h * 4) as usize],
let img = craft_image_codecs::Image::from_raw(
w,
h,
image::ExtendedColorType::Rgba8,
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U8,
vec![0; (w * h * 4) as usize],
)
.unwrap();
out
craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap()
}
let raster_image = |data| raster_image_sized(data).map(|(kind, _)| kind);
assert!(matches!(raster_image(Arc::new(png(2, 2))), Some(usvg::ImageKind::PNG(_))));
@@ -547,8 +546,12 @@ fn filter_images_are_small_raster_images() {
/// A 2 × 2 PNG whose header claims `w` × `h` pixels (its IHDR rewritten, with the CRC fixed).
fn png_claiming(w: u32, h: u32) -> Vec<u8> {
let mut out = vec![];
image::ImageEncoder::write_image(image::codecs::png::PngEncoder::new(&mut out), &[0; 16], 2, 2, image::ExtendedColorType::Rgba8).unwrap();
let mut out = craft_image_codecs::encode(
&craft_image_codecs::Image::from_raw(2, 2, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, vec![0; 16]).unwrap(),
craft_image_codecs::Format::Png,
&craft_image_codecs::EncodeOptions::default(),
)
.unwrap();
out[16..20].copy_from_slice(&w.to_be_bytes());
out[20..24].copy_from_slice(&h.to_be_bytes());
let crc = crc32(&out[12..29]);
+26 -20
View File
@@ -15,10 +15,13 @@ fn fx(id: &str) -> Effect {
}
/// `img` encoded as `format`.
fn encoded(img: image::DynamicImage, format: image::ImageFormat) -> Vec<u8> {
let mut out = vec![];
img.write_to(&mut std::io::Cursor::new(&mut out), format).unwrap();
out
fn encoded(img: image::DynamicImage, format: craft_image_codecs::Format) -> Vec<u8> {
let (layout, data) = match format {
craft_image_codecs::Format::Jpeg => (craft_image_codecs::ChannelLayout::Rgb, img.to_rgb8().into_raw()),
_ => (craft_image_codecs::ChannelLayout::Rgba, img.to_rgba8().into_raw()),
};
let raw = craft_image_codecs::Image::from_raw(img.width(), img.height(), layout, craft_image_codecs::SampleType::U8, data).unwrap();
craft_image_codecs::encode(&raw, format, &craft_image_codecs::EncodeOptions::default()).unwrap()
}
/// A 100×100 RGBA image, transparent but for an opaque disc of radius 30 in its middle.
@@ -130,7 +133,7 @@ fn outline_object_follows_the_opaque_area_of_an_image_with_alpha() {
let gray_alpha = image::DynamicImage::ImageLumaA8(disc().to_luma_alpha8());
let deep = image::DynamicImage::ImageRgba16(disc().to_rgba16());
for (name, img) in [("rgba", disc()), ("gray and alpha", gray_alpha), ("16 bits a channel", deep)] {
let (d, n) = image_doc(encoded(img, image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
let (d, n) = image_doc(encoded(img, craft_image_codecs::Format::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
let rows = row_bounds(&d, &n);
assert_eq!(rows.len(), 1, "{name}");
// The disc runs from 70 to 130; the frame from 50 to 150.
@@ -143,9 +146,9 @@ fn outline_object_follows_the_frame_of_an_image_without_transparency() {
let opaque = image::DynamicImage::ImageRgb8(image::RgbImage::from_pixel(100, 100, image::Rgb([0, 0, 255])));
let solid = image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(100, 100, image::Rgba([0, 0, 255, 200])));
let formats = [
("jpeg", encoded(opaque.clone(), image::ImageFormat::Jpeg)),
("rgb png", encoded(opaque, image::ImageFormat::Png)),
("rgba png, every pixel more than half opaque", encoded(solid, image::ImageFormat::Png)),
("jpeg", encoded(opaque.clone(), craft_image_codecs::Format::Jpeg)),
("rgb png", encoded(opaque, craft_image_codecs::Format::Png)),
("rgba png, every pixel more than half opaque", encoded(solid, craft_image_codecs::Format::Png)),
];
for (name, bytes) in formats {
let (d, n) = image_doc(bytes, vec![stroke(vec![fx("path.outlineObject")])], 1);
@@ -165,7 +168,7 @@ fn convert_to_shape_keeps_the_frame_beside_outline_object() {
let mut fill = FillLayer::new(Paint::solid(Color::rgb(0.0, 1.0, 0.0)));
fill.effects = vec![rect.clone()];
let items = vec![AppearanceItem::Fill(fill), stroke(vec![fx("path.outlineObject")]), stroke(vec![rect, fx("path.outlineObject")])];
let (d, n) = image_doc(encoded(disc(), image::ImageFormat::Png), items, 2);
let (d, n) = image_doc(encoded(disc(), craft_image_codecs::Format::Png), items, 2);
let rows = row_bounds(&d, &n);
assert_eq!(rows.len(), 3, "{rows:?}");
assert!(near(rows[0], [50.0, 50.0, 150.0, 150.0], 1e-9), "{rows:?}");
@@ -179,7 +182,7 @@ fn convert_to_shape_keeps_the_frame_beside_outline_object() {
#[test]
fn a_transparent_image_gives_outline_object_nothing_to_paint() {
let clear = image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(100, 100, image::Rgba([0, 0, 0, 100])));
let (d, n) = image_doc(encoded(clear, image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
let (d, n) = image_doc(encoded(clear, craft_image_codecs::Format::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
assert!(row_bounds(&d, &n).is_empty());
let art = reshape::reshape(Some(&d), &n, None).unwrap();
assert!(matches!(art.children().unwrap().as_slice(), [only] if matches!(only.kind, NodeKind::Image(_))));
@@ -190,7 +193,7 @@ fn the_outline_follows_the_images_own_pixels_and_placement() {
// Pixels kept on the image itself (art made outside a document), placed at half size.
let (_, mut n) = image_doc(vec![], vec![stroke(vec![fx("path.outlineObject")])], 1);
if let NodeKind::Image(im) = &mut n.kind {
im.pixels = Some(Arc::new(ImageBlob::new("image/png", encoded(disc(), image::ImageFormat::Png))));
im.pixels = Some(Arc::new(ImageBlob::new("image/png", encoded(disc(), craft_image_codecs::Format::Png))));
im.xf = Affine::translate((10.0, 20.0)) * Affine::scale(0.5);
}
let art = reshape::reshape(None, &n, None).unwrap();
@@ -206,7 +209,7 @@ fn an_off_center_outline_turns_and_reflects_with_a_smaller_copy_of_the_pixels()
let half = image::DynamicImage::ImageRgba8(image::RgbaImage::from_fn(60, 30, |x, y| {
image::Rgba([255, 0, 0, if (6..20).contains(&x) && (3..12).contains(&y) { 255 } else { 0 }])
}));
let (d, mut n) = image_doc(encoded(half, image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
let (d, mut n) = image_doc(encoded(half, craft_image_codecs::Format::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
let xf = Affine::translate((100.0, 40.0)) * Affine::rotate(std::f64::consts::FRAC_PI_2) * Affine::scale_non_uniform(-1.0, 1.0);
if let NodeKind::Image(im) = &mut n.kind {
(im.width, im.height, im.xf) = (120, 60, xf);
@@ -221,7 +224,7 @@ fn an_off_center_outline_turns_and_reflects_with_a_smaller_copy_of_the_pixels()
#[test]
fn an_image_in_a_group_exports_with_its_outline() {
let (mut d, n) = image_doc(encoded(disc(), image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
let (mut d, n) = image_doc(encoded(disc(), craft_image_codecs::Format::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
let l = d.layers[0].id;
d.remove(n.id).unwrap();
let g = d.alloc_id();
@@ -256,7 +259,7 @@ fn baked_strokes(d: &Document) -> Vec<Rect> {
fn an_image_under_a_clipping_mask_or_with_an_opacity_mask_exports_with_its_outline() {
let disc_outline = |paths: &[Rect]| matches!(paths, [b] if near(*b, [70.0, 70.0, 130.0, 130.0], 0.5));
// Under a clipping mask that covers the whole image.
let (mut d, n) = image_doc(encoded(disc(), image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
let (mut d, n) = image_doc(encoded(disc(), craft_image_codecs::Format::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
let l = d.layers[0].id;
d.remove(n.id).unwrap();
let clip = Node::path(d.alloc_id(), vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 200.0)), Default::default());
@@ -265,7 +268,7 @@ fn an_image_under_a_clipping_mask_or_with_an_opacity_mask_exports_with_its_outli
let paths = baked_strokes(&d);
assert!(disc_outline(&paths), "{paths:?}");
// With an opacity mask.
let (mut d, mut n) = image_doc(encoded(disc(), image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
let (mut d, mut n) = image_doc(encoded(disc(), craft_image_codecs::Format::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
let mut white = Node::path(NodeId(999), vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 200.0)), Default::default());
white.appearance.set_fill(Paint::solid(Color::WHITE));
n.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(Node::group(NodeId(998), vec![Arc::new(white)]), true)));
@@ -279,7 +282,7 @@ fn an_image_under_a_clipping_mask_or_with_an_opacity_mask_exports_with_its_outli
fn outline_object_on_a_fill_and_on_an_indexed_image_follows_the_opaque_area() {
let mut fill = FillLayer::new(Paint::solid(Color::rgb(0.0, 1.0, 0.0)));
fill.effects = vec![fx("path.outlineObject")];
let (d, n) = image_doc(encoded(disc(), image::ImageFormat::Png), vec![AppearanceItem::Fill(fill)], 1);
let (d, n) = image_doc(encoded(disc(), craft_image_codecs::Format::Png), vec![AppearanceItem::Fill(fill)], 1);
let rows = row_bounds(&d, &n);
assert!(matches!(rows.as_slice(), [b] if near(*b, [70.0, 70.0, 130.0, 130.0], 0.5)), "{rows:?}");
// A palette image whose first color is transparent (a tRNS chunk).
@@ -308,15 +311,18 @@ fn an_image_too_large_or_too_complex_to_outline_keeps_its_frame() {
}
// A checkerboard of 2 px squares, whose outline would need more than 100,000 anchor points.
let checker = image::RgbaImage::from_fn(640, 640, |x, y| image::Rgba([0, 0, 0, if (x / 2 + y / 2) % 2 == 0 { 255 } else { 0 }]));
let (d, n) =
image_doc(encoded(image::DynamicImage::ImageRgba8(checker), image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
let (d, n) = image_doc(
encoded(image::DynamicImage::ImageRgba8(checker), craft_image_codecs::Format::Png),
vec![stroke(vec![fx("path.outlineObject")])],
1,
);
assert!(matches!(row_bounds(&d, &n).as_slice(), [b] if near(*b, [50.0, 50.0, 150.0, 150.0], 1e-9)));
}
#[test]
fn an_outline_is_traced_once_for_its_pixels_and_dropped_with_them() {
let traces = || reshape::TRACES.with(std::cell::Cell::get);
let (d, n) = image_doc(encoded(disc(), image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
let (d, n) = image_doc(encoded(disc(), craft_image_codecs::Format::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
let NodeKind::Image(im) = &n.kind else { panic!("not an image") };
let before = traces();
let first = reshape::opaque_area(&[Some(&d)], im).unwrap();
@@ -331,7 +337,7 @@ fn an_outline_is_traced_once_for_its_pixels_and_dropped_with_them() {
// Once the document and its pixels are gone, the next trace drops their entry.
drop(d);
assert!(pixels.upgrade().is_none());
let (other, _) = image_doc(encoded(disc(), image::ImageFormat::Png), vec![], 1);
let (other, _) = image_doc(encoded(disc(), craft_image_codecs::Format::Png), vec![], 1);
reshape::opaque_area(&[Some(&other)], im).unwrap();
assert_eq!(traces(), before + 2);
assert!(!reshape::keeps_outline(&pixels));