Merge remote-tracking branch 'upstream/main' into feat/save-pdf-transparency-confirmation-8097

# Conflicts:
#	crates/engine/src/cmd/flatten/analysis.rs
This commit is contained in:
el-j
2026-11-17 12:06:12 +01:00
470 changed files with 30806 additions and 3094 deletions
+4
View File
@@ -893,6 +893,10 @@ pub use buildcmds::live_paint_gaps;
/// Control bar enable it when it changes one).
pub use brushsym::reset_transformation_changes;
/// The Symbols panel's current symbol, as `symbol.list` answers it (the panel reads it on every
/// frame without running the command).
pub use brushsym::current_symbol;
/// The byte order of UTF-16 text without a byte-order mark, by Import Data Sets' rule (the Graph
/// Data window reads files by it too).
pub use variablecmds::utf16_order_without_mark;
+2 -3
View File
@@ -147,9 +147,8 @@ fn is_of_kind(d: &Document, n: &Node, kind: &str) -> bool {
/// Are the encoded image `bytes` grayscale or 1-bit? Reads only the header.
fn is_gray(bytes: &[u8]) -> bool {
use image::ImageDecoder as _;
let decoder = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().ok().and_then(|r| r.into_decoder().ok());
decoder.is_some_and(|d| matches!(d.color_type(), image::ColorType::L8 | image::ColorType::La8 | image::ColorType::L16 | image::ColorType::La16))
craft_image_codecs::decode(bytes)
.is_ok_and(|img| matches!(img.layout(), craft_image_codecs::ChannelLayout::Gray | craft_image_codecs::ChannelLayout::GrayA))
}
fn filter(s: &mut Session, p: &Value) -> Result<Value> {
+35 -1
View File
@@ -111,7 +111,41 @@ fn image(s: &mut Session, key: &str, blob: vectorcraft_doc::ImageBlob, x: f64) -
fn png(img: image::DynamicImage) -> vectorcraft_doc::ImageBlob {
let mut bytes = vec![];
img.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap();
{
let __dyn: image::DynamicImage = img;
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| bytes.extend_from_slice(&__b))
}
.unwrap();
vectorcraft_doc::ImageBlob::png(bytes)
}
+35 -1
View File
@@ -228,7 +228,41 @@ fn export_all_open_documents_writes_one_file_each() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100, "name": "pic"})).unwrap();
let mut png = vec![];
image::RgbaImage::from_pixel(4, 4, image::Rgba([1, 2, 3, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
{
let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(4, 4, image::Rgba([1, 2, 3, 255]))).into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| png.extend_from_slice(&__b))
}
.unwrap();
s.execute("file.place", &json!({"name": "a.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap();
s.execute("document.save", &json!({"path": dir.join("pic.svg"), "format": "svg", "options": {"images": "link"}})).unwrap();
let saved: Vec<_> = std::fs::read_dir(&dir).unwrap().filter_map(|e| e.ok()).filter(|e| e.path().is_file()).collect();
+83 -38
View File
@@ -13,10 +13,9 @@ mod tests;
pub(crate) use mask::refresh as refresh_color_masks;
use std::collections::{HashMap, HashSet};
use std::io::Cursor;
use std::sync::{Arc, Weak};
use image::{DynamicImage, ImageBuffer, LumaA, Rgba};
use image::{ImageBuffer, Rgba};
use serde_json::{Value, json};
use vectorcraft_color::Color;
use vectorcraft_doc::{ImageBlob, ImageObject, NodeId, NodeKind};
@@ -412,23 +411,36 @@ pub(crate) fn clear(blob: &ImageBlob, settings: &Settings, mut kept: Option<&mut
bad(cmd, "every pixel matches the background: no image would be left")
});
}
let out = match (px, gray) {
(Pixels::Eight(img), false) => DynamicImage::ImageRgba8(img),
(Pixels::Sixteen(img), false) => DynamicImage::ImageRgba16(img),
(Pixels::Eight(img), true) => {
DynamicImage::ImageLumaA8(ImageBuffer::from_fn(w, h, |x, y| LumaA([img.get_pixel(x, y).0[0], img.get_pixel(x, y).0[3]])))
let raw = match (px, gray) {
(Pixels::Eight(img), false) => {
craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, img.into_raw())
}
(Pixels::Sixteen(img), true) => {
DynamicImage::ImageLumaA16(ImageBuffer::from_fn(w, h, |x, y| LumaA([img.get_pixel(x, y).0[0], img.get_pixel(x, y).0[3]])))
}
};
let mut png = Vec::new();
let mut encoder = image::codecs::png::PngEncoder::new(&mut png);
if let Some(icc) = icc {
use image::ImageEncoder as _;
encoder.set_icc_profile(icc).map_err(|e| bad(cmd, e.to_string()))?;
(Pixels::Sixteen(img), false) => craft_image_codecs::Image::from_raw(
w,
h,
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
img.into_raw().into_iter().flat_map(u16::to_ne_bytes).collect(),
),
(Pixels::Eight(img), true) => craft_image_codecs::Image::from_raw(
w,
h,
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U8,
img.pixels().flat_map(|p| [p.0[0], p.0[3]]).collect(),
),
(Pixels::Sixteen(img), true) => craft_image_codecs::Image::from_raw(
w,
h,
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
img.pixels().flat_map(|p| [p.0[0], p.0[3]]).flat_map(u16::to_ne_bytes).collect(),
),
}
out.write_with_encoder(encoder).map_err(|e| bad(cmd, e.to_string()))?;
.map_err(|e| bad(cmd, e.to_string()))?
.with_icc(icc);
let mut png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map_err(|e| bad(cmd, e.to_string()))?;
// The resolution the file declares, which sizes the image at 100% when it is replaced or relinked.
if let Some(r) = ppi::resolution(&blob.bytes) {
png = ppi::with_png_resolution(&png, r);
@@ -436,37 +448,70 @@ pub(crate) fn clear(blob: &ImageBlob, settings: &Settings, mut kept: Option<&mut
Ok(Some(Cleared { blob: ImageBlob::png(png), width: w, height: h, cleared }))
}
/// The image's size and the bytes a pixel of it takes to change, read from its header: its
/// samples as decoded (bitmaps as 8-bit gray, palettes as RGB, or RGBA with a transparent entry),
/// those worked on and kept for the PNG, and the work. A header that gives only the size (one
/// whose file can't hold its pixels) counts the fewest: one 8-bit sample. `None` when the header
/// doesn't say.
fn header_pixels(bytes: &[u8]) -> Option<(u32, u32, u64)> {
use craft_image_codecs::RasterColorType as T;
let Some(i) = craft_image_codecs::inspect_raster(bytes).ok().flatten() else {
return vectorcraft_doc::header_size(bytes).map(|(w, h)| (w, h, 1 + 2 * 4 + WORK_BYTES));
};
let deep = i.bits_per_sample > 8 && i.color_type != T::Indexed;
let channels = match i.color_type {
T::Indexed => 3 + u64::from(i.transparent_index.is_some()),
T::Bitmap => 1,
_ => u64::from(i.channels.max(1)),
};
let samples = channels * if deep { 2 } else { 1 };
Some((i.width, i.height, samples + 2 * if deep { 8 } else { 4 } + WORK_BYTES))
}
/// `blob`'s pixels as straight RGBA, whether they were gray, and its ICC profile. An image that
/// can't be decoded or is too large to change is an error. The pixels are kept in `kept`, when it
/// is given, if a copy of them fits the decode allowance beside the work. Errors are command `cmd`'s.
fn decode(blob: &ImageBlob, kept: Option<&mut DecodedImages>, cmd: &str) -> Result<(Arc<Pixels>, bool, Option<Vec<u8>>)> {
let reader = || {
image::ImageReader::new(Cursor::new(blob.bytes.as_slice())).with_guessed_format().map_err(|_| bad(cmd, "the image's pixels can't be read"))
};
let mut decoder = reader()?.into_decoder().map_err(|e| bad(cmd, format!("the image's pixels can't be read: {e}")))?;
// The ICC profile the colors are in goes with them into the PNG.
let (w, h, kind, icc) = {
use image::ImageDecoder as _;
let (w, h) = decoder.dimensions();
(w, h, decoder.color_type(), decoder.icc_profile().ok().flatten())
};
drop(decoder);
// The file's pixels, those worked on (as many again for the PNG made of them) and the work,
// checked from the header before anything is decoded.
let deep = kind.bytes_per_pixel() > kind.channel_count();
let per_pixel = u64::from(kind.bytes_per_pixel()) + 2 * if deep { 8 } else { 4 } + WORK_BYTES;
if u64::from(w).checked_mul(u64::from(h)).and_then(|n| n.checked_mul(per_pixel)).is_none_or(|n| n > MAX_RASTER_ALLOC) {
let too_large = |w: u32, h: u32, per_pixel: u64| {
u64::from(w).checked_mul(u64::from(h)).and_then(|n| n.checked_mul(per_pixel)).is_none_or(|n| n > MAX_RASTER_ALLOC)
};
let header = header_pixels(&blob.bytes);
if let Some((w, h, per_pixel)) = header
&& too_large(w, h, per_pixel)
{
return Err(bad(cmd, format!("an image of {w} × {h} pixels is too large to change")));
}
let mut opts = craft_image_codecs::DecodeOptions::default();
opts.limits.max_alloc = MAX_RASTER_ALLOC;
let img = craft_image_codecs::decode_with(&blob.bytes, &opts).map_err(|e| match e {
// Within the allowance from its header: a file that can't hold the pixels it declares.
craft_image_codecs::CodecError::LimitExceeded(_) if header.is_none() => bad(cmd, "the image is too large to change"),
_ => bad(cmd, format!("the image's pixels can't be read: {e}")),
})?;
let (w, h) = img.dimensions();
let icc = img.icc.clone();
let deep = img.sample_type() == craft_image_codecs::SampleType::U16;
let gray = matches!(img.layout(), craft_image_codecs::ChannelLayout::Gray | craft_image_codecs::ChannelLayout::GrayA);
let per_pixel = u64::from(img.layout().channels() as u32 * img.sample_type().bytes() as u32) + 2 * if deep { 8 } else { 4 } + WORK_BYTES;
if too_large(w, h, per_pixel) {
return Err(bad(cmd, format!("an image of {w} × {h} pixels is too large to change")));
}
let mut reader = reader()?;
let mut limits = image::Limits::default();
limits.max_alloc = Some(MAX_RASTER_ALLOC);
reader.limits(limits);
let img = reader.decode().map_err(|e| bad(cmd, format!("the image's pixels can't be read: {e}")))?;
#[cfg(test)]
DECODES.with(|c| c.set(c.get() + 1));
let gray = matches!(img.color(), image::ColorType::L8 | image::ColorType::La8 | image::ColorType::L16 | image::ColorType::La16);
let px = Arc::new(if deep { Pixels::Sixteen(img.into_rgba16()) } else { Pixels::Eight(img.into_rgba8()) });
let px = Arc::new(if deep {
let rgba16 = match (img.layout(), img.to_u16_samples()) {
(craft_image_codecs::ChannelLayout::Rgba, Some(v)) => v,
(craft_image_codecs::ChannelLayout::Rgb, Some(v)) => v.as_chunks::<3>().0.iter().flat_map(|c| [c[0], c[1], c[2], u16::MAX]).collect(),
(craft_image_codecs::ChannelLayout::GrayA, Some(v)) => v.as_chunks::<2>().0.iter().flat_map(|c| [c[0], c[0], c[0], c[1]]).collect(),
(craft_image_codecs::ChannelLayout::Gray, Some(v)) => v.into_iter().flat_map(|g| [g, g, g, u16::MAX]).collect(),
_ => img.to_rgba8().into_iter().map(|b| u16::from(b) * 257).collect(),
};
Pixels::Sixteen(ImageBuffer::from_raw(w, h, rgba16).ok_or_else(|| bad(cmd, "invalid 16-bit pixel buffer"))?)
} else {
Pixels::Eight(ImageBuffer::from_raw(w, h, img.to_rgba8()).ok_or_else(|| bad(cmd, "invalid 8-bit pixel buffer"))?)
});
// A kept copy is worked on as a copy: one more set of the pixels worked on.
let with_copy = per_pixel + if deep { 8 } else { 4 };
if let Some(kept) = kept
+1 -3
View File
@@ -287,9 +287,7 @@ fn apply_color_mask(s: &mut Session, p: &Value) -> Result<Value> {
/// The size in pixels of masked pixels `blob` (from its header), or the object's when it can't be
/// read.
fn mask_size(blob: Option<&ImageBlob>, width: u32, height: u32) -> (u32, u32) {
blob.and_then(|b| image::ImageReader::new(std::io::Cursor::new(b.bytes.as_slice())).with_guessed_format().ok()?.into_dimensions().ok())
.filter(|(w, h)| *w > 0 && *h > 0)
.unwrap_or((width, height))
blob.and_then(|b| b.pixel_size()).filter(|(w, h)| *w > 0 && *h > 0).unwrap_or((width, height))
}
/// The mask of image node `n` made again for the image's own pixels, with the masked pixels when
+218 -13
View File
@@ -1,5 +1,3 @@
use std::io::Cursor;
use image::DynamicImage;
use serde_json::{Value, json};
use vectorcraft_color::{Color, Paint};
@@ -15,7 +13,41 @@ const RED: [u8; 4] = [200, 0, 0, 255];
fn png(img: DynamicImage) -> Vec<u8> {
let mut out = Vec::new();
img.write_to(&mut Cursor::new(&mut out), image::ImageFormat::Png).unwrap();
{
let __dyn: image::DynamicImage = img;
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| out.extend_from_slice(&__b))
}
.unwrap();
out
}
@@ -138,7 +170,24 @@ fn applying_the_mask_makes_it_part_of_the_pixels() {
assert_eq!(s.execute(APPLY_COLOR_MASK, &json!({})).unwrap(), json!({"changed": 1, "ids": [id.0]}));
let d = doc(&s);
assert_eq!((image_of(d, id).key, mask_of(d, id)), (m.key.clone(), None));
let px = image::load_from_memory(&d.images[&m.key].bytes).unwrap().to_rgba8();
let px = craft_image_codecs::decode(&d.images[&m.key].bytes)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8();
assert_eq!((px.get_pixel(0, 0).0[3], px.get_pixel(4, 4).0), (0, RED));
assert_eq!(drawn(d, id, 0, 0)[3], 0);
assert_eq!(undo_len(&s), steps + 1);
@@ -149,7 +198,23 @@ fn applying_the_mask_makes_it_part_of_the_pixels() {
fn svg_image(svg: &str) -> DynamicImage {
let at = svg.find("data:image/png;base64,").expect("an embedded PNG") + "data:image/png;base64,".len();
let end = at + svg[at..].find('"').unwrap();
image::load_from_memory(&vectorcraft_format::base64_decode(&svg[at..end]).unwrap()).unwrap()
craft_image_codecs::decode(&vectorcraft_format::base64_decode(&svg[at..end]).unwrap())
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
}
#[test]
@@ -159,7 +224,28 @@ fn outputs_write_the_masked_pixels() {
|s: &Session, format: &str| crate::cmd::fileio::encode_all(doc(s), format, &json!({"useArtboards": true})).unwrap().files.remove(0).1;
let (png0, svg0, pdf0, eps0) = (export(&s, "png"), export(&s, "svg"), export(&s, "pdf"), export(&s, "eps"));
s.execute(COLOR_MASK, &hide_white()).unwrap();
let alpha = |bytes: &[u8]| image::load_from_memory(bytes).unwrap().to_rgba8().get_pixel(0, 0).0[3];
let alpha = |bytes: &[u8]| {
craft_image_codecs::decode(bytes)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8()
.get_pixel(0, 0)
.0[3]
};
assert_eq!((alpha(&png0), alpha(&export(&s, "png"))), (255, 0), "PNG");
let svg_alpha = |bytes: &[u8]| svg_image(std::str::from_utf8(bytes).unwrap()).to_rgba8().get_pixel(0, 0).0[3];
assert_eq!((svg_alpha(&svg0), svg_alpha(&export(&s, "svg"))), (255, 0), "SVG");
@@ -344,7 +430,24 @@ fn cropping_off_the_pixel_grid_keeps_the_hidden_colors_in_the_pixels() {
let d = doc(&s);
let (im, m) = (image_of(d, id), mask_of(d, id).unwrap());
assert_eq!(m.from, im.key, "the mask is made for the cut pixels");
let own = image::load_from_memory(&d.images[&im.key].bytes).unwrap().to_rgba8();
let own = craft_image_codecs::decode(&d.images[&im.key].bytes)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8();
assert!(own.pixels().all(|p| p.0[3] == 255), "the cut pixels are the image's own, white included");
assert_eq!(drawn(d, id, 0, 0)[3], 0, "white is hidden");
s.execute(REMOVE_COLOR_MASK, &json!({"ids": [id.0]})).unwrap();
@@ -377,7 +480,24 @@ fn applying_a_mask_made_for_older_pixels_makes_it_again_and_keeps_the_size() {
assert_eq!((im.width, im.height, mask_of(d, id)), (24, 20, None));
let after = d.node(id).unwrap().geometric_bounds().unwrap();
assert!((after.width() - before.width()).abs() < 1e-9 && (after.height() - before.height()).abs() < 1e-9, "{before:?} {after:?}");
let px = image::load_from_memory(&d.images[&im.key].bytes).unwrap().to_rgba8();
let px = craft_image_codecs::decode(&d.images[&im.key].bytes)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8();
assert_eq!((px.get_pixel(0, 0).0[3], px.get_pixel(10, 10).0), (0, RED));
}
@@ -435,7 +555,24 @@ fn another_image_colorized_with_transparency_does_not_change_the_refusal() {
s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap();
assert_eq!(s.execute(COLOR_MASK, &hide_white()).unwrap()["changed"], 1, "an image colorized with black takes the mask beside the other");
let m = mask_of(doc(&s), id).unwrap();
let masked = image::load_from_memory(&doc(&s).images[&m.key].bytes).unwrap().to_luma_alpha8();
let masked = craft_image_codecs::decode(&doc(&s).images[&m.key].bytes)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_luma_alpha8();
assert_eq!((masked.get_pixel(0, 0).0[1], masked.get_pixel(4, 4).0[1]), (0, 255), "white is hidden and black shows");
}
@@ -580,7 +717,24 @@ fn masks_outside_the_layers_are_made_again() {
let art = &d.node(holder_id).unwrap().extras().mask.as_ref().unwrap().art;
assert_eq!(from(art), key, "in the opacity mask's art");
let m = Document::color_mask_of(art).unwrap();
let px = image::load_from_memory(&d.images[&m.key].bytes).unwrap().to_rgba8();
let px = craft_image_codecs::decode(&d.images[&m.key].bytes)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8();
assert_eq!((px.get_pixel(0, 0).0[3], px.get_pixel(1, 0).0), (0, RED));
}
@@ -696,7 +850,24 @@ fn a_linked_file_read_again_on_open_takes_the_mask_again() {
let d = doc(&s);
let (im, m) = (image_of(d, id), mask_of(d, id).unwrap());
assert_eq!(m.from, im.key, "made for the file's new pixels");
let px = image::load_from_memory(&d.images[&m.key].bytes).unwrap().to_rgba8();
let px = craft_image_codecs::decode(&d.images[&m.key].bytes)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8();
assert_eq!((px.get_pixel(0, 0).0[3], px.get_pixel(4, 4).0), (0, [0, 0, 200, 255]));
}
@@ -812,7 +983,24 @@ fn a_live_color_adjustment_recolors_the_image_when_its_masked_pixels_are_missing
let NodeKind::Image(im) = &out.kind else { panic!("an image") };
assert_ne!(im.key, image_of(&d, id).key, "the expanded image is recolored");
assert_eq!(Document::color_mask_of(&out), None, "the expanded image has no mask to make again from the recolored pixels");
let px = image::load_from_memory(&d.images[&im.key].bytes).unwrap().to_rgba8();
let px = craft_image_codecs::decode(&d.images[&im.key].bytes)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8();
assert_eq!(px.get_pixel(1, 1).0, WHITE, "the expanded image shows the white");
}
@@ -1002,6 +1190,23 @@ fn placing_a_document_brings_the_masked_pixels() {
}
let [(im, placed)] = found.as_slice() else { panic!("one masked image: {found:?}") };
assert!(placed.made_for(im) && placed.from != m.from, "the image was renamed and the mask follows: {placed:?}");
let px = image::load_from_memory(&d.images[&placed.key].bytes).unwrap().to_rgba8();
let px = craft_image_codecs::decode(&d.images[&placed.key].bytes)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8();
assert_eq!((px.get_pixel(0, 0).0[3], px.get_pixel(4, 4).0), (0, RED));
}
+81 -17
View File
@@ -1,4 +1,3 @@
use std::io::Cursor;
use std::sync::Arc;
use image::{DynamicImage, ImageBuffer, Luma, LumaA, Rgb};
@@ -21,7 +20,41 @@ fn settings(background: Background) -> Settings {
fn png(img: DynamicImage) -> Vec<u8> {
let mut out = Vec::new();
img.write_to(&mut Cursor::new(&mut out), image::ImageFormat::Png).unwrap();
{
let __dyn: image::DynamicImage = img;
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| out.extend_from_slice(&__b))
}
.unwrap();
out
}
@@ -53,7 +86,32 @@ fn bytes_of(s: &Session, id: NodeId) -> Arc<Vec<u8>> {
}
fn pixels(s: &Session, id: NodeId) -> DynamicImage {
image::load_from_memory(&bytes_of(s, id)).unwrap()
craft_image_codecs::decode(&bytes_of(s, id))
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(layout, craft_image_codecs::SampleType::U16) => {
let v = __cimg.to_u16_samples().unwrap();
match layout {
craft_image_codecs::ChannelLayout::Gray => image::DynamicImage::ImageLuma16(ImageBuffer::from_raw(__w, __h, v).unwrap()),
craft_image_codecs::ChannelLayout::GrayA => image::DynamicImage::ImageLumaA16(ImageBuffer::from_raw(__w, __h, v).unwrap()),
craft_image_codecs::ChannelLayout::Rgb => image::DynamicImage::ImageRgb16(ImageBuffer::from_raw(__w, __h, v).unwrap()),
_ => image::DynamicImage::ImageRgba16(ImageBuffer::from_raw(__w, __h, v).unwrap()),
}
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
}
fn alpha(img: &DynamicImage, x: u32, y: u32) -> u8 {
@@ -164,13 +222,13 @@ fn preview_steps_on_the_same_pixels_decode_them_once() {
/// image with an ICC profile comes out as a run on freshly decoded pixels gives it.
#[test]
fn reused_pixels_keep_their_depth_gray_and_profile() {
use image::{ImageDecoder as _, ImageEncoder as _};
let icc = b"a profile's bytes".to_vec();
let gray16 = ImageBuffer::from_fn(8, 8, |x, y| Luma([if (2..6).contains(&x) && (2..6).contains(&y) { 7_000u16 } else { 61_000 }]));
let mut bytes = Vec::new();
let mut encoder = image::codecs::png::PngEncoder::new(&mut bytes);
encoder.set_icc_profile(icc.clone()).unwrap();
DynamicImage::ImageLuma16(gray16).write_with_encoder(encoder).unwrap();
let raw: Vec<u8> = gray16.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect();
let mut cimg =
craft_image_codecs::Image::from_raw(8, 8, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U16, raw).unwrap();
cimg.icc = Some(icc.clone());
let bytes = craft_image_codecs::encode(&cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap();
let decodes = || super::DECODES.with(std::cell::Cell::get);
let (mut s, id) = open(&bytes);
let start = decodes();
@@ -184,8 +242,8 @@ fn reused_pixels_keep_their_depth_gray_and_profile() {
let DynamicImage::ImageLumaA16(out) = pixels(&s, id) else { panic!("16-bit gray with alpha") };
assert_eq!((out.get_pixel(0, 0).0, out.get_pixel(3, 3).0), ([61_000, 0], [7_000, 65_535]));
let result = bytes_of(&s, id);
let mut decoder = image::codecs::png::PngDecoder::new(Cursor::new(result.as_slice())).unwrap();
assert_eq!(decoder.icc_profile().unwrap(), Some(icc));
let decoded = craft_image_codecs::decode_as(craft_image_codecs::Format::Png, result.as_slice()).unwrap();
assert_eq!(decoded.icc, Some(icc));
}
/// Once the background is cleared, most edge pixels are clear and a second run clears nothing: the
@@ -385,16 +443,22 @@ fn a_gray_image_colorized_with_a_process_color_is_refused() {
/// The ICC profile the colors are in stays with them.
#[test]
fn the_color_profile_is_kept() {
use image::{ImageDecoder as _, ImageEncoder as _};
let icc = b"a profile's bytes".to_vec();
let mut bytes = Vec::new();
let mut encoder = image::codecs::png::PngEncoder::new(&mut bytes);
encoder.set_icc_profile(icc.clone()).unwrap();
DynamicImage::ImageRgba8(framed()).write_with_encoder(encoder).unwrap();
let f = framed();
let mut cimg = craft_image_codecs::Image::from_raw(
f.width(),
f.height(),
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U8,
f.into_raw(),
)
.unwrap();
cimg.icc = Some(icc.clone());
let bytes = craft_image_codecs::encode(&cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap();
let blob = ImageBlob::png(bytes);
let out = super::clear(&blob, &settings(Background::Edges), None, super::C).unwrap().unwrap();
let mut decoder = image::codecs::png::PngDecoder::new(Cursor::new(out.blob.bytes.as_slice())).unwrap();
assert_eq!(decoder.icc_profile().unwrap(), Some(icc));
let decoded = craft_image_codecs::decode_as(craft_image_codecs::Format::Png, out.blob.bytes.as_slice()).unwrap();
assert_eq!(decoded.icc, Some(icc));
}
/// The resolution the file declares stays with the pixels, so a later Replace or relink sizes the
+6 -2
View File
@@ -1,9 +1,11 @@
//! Packaging Tools (`addon.packaging.*`), a built-in add-on for the dielines of boxes and other
//! folded packaging. A path is a fold line when its top stroke is painted with the swatch of a line
//! role: Cut, Crease, Partial Cut or Perforation ([`roles`]). The document's role table maps each
//! role to its swatch, so every format that keeps the stroke's swatch keeps the role. Its submenu
//! role to its swatch, so every format that keeps the stroke's swatch keeps the role. Check Fold
//! Lines ([`check`]) finds the panels and hinges the lines make and what is wrong with them. Its submenu
//! (Object › Plug-ins › Packaging Tools) and its Fold Lines panel are the UI's.
mod check;
mod roles;
pub(crate) use roles::{role_swatch_edited, role_swatches_merged};
@@ -11,7 +13,9 @@ pub(crate) use roles::{role_swatch_edited, role_swatches_merged};
use super::super::CommandSpec;
pub fn specs() -> Vec<CommandSpec> {
roles::specs()
let mut v = roles::specs();
v.extend(check::specs());
v
}
#[cfg(test)]
@@ -0,0 +1,179 @@
//! Check Fold Lines (`addon.packaging.check`): the blanks the fold lines make, their panels and
//! hinges, and what is wrong with the lines, found by [`vectorcraft_three_d::fold::blanks`].
use serde_json::{Value, json};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
use vectorcraft_geom::PathData;
use vectorcraft_three_d::fold::{FoldLine, IssueCode, LineKind, MAX_SEGMENTS, blanks};
use super::super::super::pathops::length_given;
use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, switch_or};
use super::roles::{Role, RoleTable, can_carry, role_targets};
use crate::{Result, Session};
const CHECK: &str = "addon.packaging.check";
/// How far apart the ends of two lines may be and still be joined, in points.
const TOLERANCE: (f64, f64, f64) = (0.01, 0.1, 10.0);
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"addon.packaging.check",
"Check Fold Lines",
["Object", "Plug-ins", "Packaging Tools"],
None,
"{ids?: [id…] (default: the selection), select?: bool (false), tolerance?: pt 0.01..10 (0.1)} check the fold lines (addon.packaging.roles) among the objects (through groups and clip groups), or, while nothing is selected and ids is left out, every fold line of the document; hidden lines are left out, also in a selected group. Cut lines bound the blanks: each connected piece of them that encloses material is one blank, its outline is its largest closed cut line, and a closed cut line inside it is a hole, so a slot drawn as a rectangle across the outline leaves the same material as a notch drawn in it; open cut lines that meet end to end count as one closed cut line. Crease, Partial Cut and Perforation lines divide a blank into panels; the pieces of them between two panels are that pair's hinge. A cut line end that comes within tolerance of another cut line is joined to it. Issues, in this order: noCut, open, looseEnd (errors), gap (a warning: the gap is closed), tooComplex (an error: more than 65,536 segments or 256 panels in a blank), cutOverCrease (an error), duplicate (two cut lines, or two lines that fold of any role), danglingCrease, noSplit, outside (wholly, or in part for tolerance or more), notStraight (a hinge's pieces are not on one straight line), sliver, ambiguous, loosePanel (joined to the largest panel by no chain of hinges), nonPrinting (warnings). With select, the objects the issues name become the selection, unless no issue names one. Changes nothing in the document → {ok (no error), blanks, panels, hinges, holes, issues: [{severity: error|warning, code, message (English), ids, at?: [x, y]}], scope: ids|selection|document}",
has_doc,
check
)]
}
/// The English message for an issue (the Fold Lines panel shows it in the interface language).
fn message(code: IssueCode, scope: &str) -> &'static str {
match code {
IssueCode::NoCut if scope == "document" => "No cut lines are in the document.",
IssueCode::NoCut if scope == "ids" => "No cut lines are among the given objects.",
IssueCode::NoCut => "No cut lines are in the selection.",
IssueCode::Open => "The cut lines do not enclose an area.",
IssueCode::LooseEnd => "A cut line ends without meeting another cut line.",
IssueCode::Gap => "A gap between cut lines was closed.",
IssueCode::TooComplex => "The fold lines are too complex to check.",
IssueCode::CutOverCrease => "A cut line and a crease lie on top of each other.",
IssueCode::Duplicate => "Two fold lines lie on top of each other.",
IssueCode::DanglingCrease => "A crease ends inside a panel.",
IssueCode::NoSplit => "A crease does not divide two panels.",
IssueCode::Outside => "A crease lies outside the cut outline, wholly or in part.",
IssueCode::NotStraight => "The pieces of a hinge are not on one straight line.",
IssueCode::Sliver => "A gap between cut lines is too narrow to tell apart.",
IssueCode::Ambiguous => "A cut-out area holds other fold lines or another blank.",
IssueCode::LoosePanel => "A panel is not joined to the rest by a crease.",
IssueCode::NonPrinting => "A fold line is on a non-printing layer.",
}
}
/// Every object of the document that can carry a role and is shown: on a shown layer, in shown
/// groups, and shown itself.
fn shown_targets(d: &Document) -> Vec<NodeId> {
fn walk(n: &Node, out: &mut Vec<NodeId>) {
if !n.visible {
return;
}
match &n.kind {
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => children.iter().for_each(|c| walk(c, out)),
_ if can_carry(n) => out.push(n.id),
_ => {}
}
}
let mut out = vec![];
d.layers.iter().for_each(|l| walk(l, &mut out));
out
}
/// The path of object `n` in document coordinates: a path's own, or a compound path's members'.
fn path_of(n: &Node) -> Option<PathData> {
match &n.kind {
NodeKind::Path { path, .. } => Some(path.clone()),
NodeKind::Compound { children, .. } => Some(PathData::new(
children
.iter()
.filter_map(|c| match &c.kind {
NodeKind::Path { path, .. } => Some(path.subpaths.iter().cloned()),
_ => None,
})
.flatten()
.collect(),
)),
_ => None,
}
}
/// Whether object `id` is on a layer, or a sublayer, that does not print.
fn on_non_printing_layer(d: &Document, id: NodeId) -> bool {
d.ancestry(id).unwrap_or_default().iter().filter_map(|a| d.node(*a)).any(|n| matches!(n.kind, NodeKind::Layer { printable: false, .. }))
}
fn kind(role: Role) -> LineKind {
match role {
Role::Cut => LineKind::Cut,
Role::Crease => LineKind::Crease,
Role::PartialCut => LineKind::PartialCut,
Role::Perforation => LineKind::Perforation,
}
}
fn check(s: &mut Session, p: &Value) -> Result<Value> {
let select = switch_or(p, "select", false, CHECK)?;
let tolerance = match length_given(p, "tolerance", CHECK)? {
None => TOLERANCE.1,
Some(t) if (TOLERANCE.0..=TOLERANCE.2).contains(&t) => t,
Some(_) => return Err(bad(CHECK, format!("`tolerance` must be from {} to {} pt", TOLERANCE.0, TOLERANCE.2))),
};
let given = p.get("ids").is_some_and(|v| !v.is_null());
let roots = checked_ids_or_selection(s, p, CHECK)?;
let d = &s.doc()?.doc;
// Hidden lines are left out in every scope, members of a selected group included.
let shown = |ids: Vec<NodeId>| ids.into_iter().filter(|id| d.is_visible(*id)).collect::<Vec<_>>();
let (scope, targets) = match (given, roots.is_empty()) {
(true, _) => ("ids", shown(role_targets(d, &roots, false).0)),
(false, false) => ("selection", shown(role_targets(d, &roots, false).0)),
(false, true) => ("document", shown_targets(d)),
};
let table = RoleTable::of(d);
let mut lines = vec![];
let mut non_printing = vec![];
let mut segments = 0usize;
for id in targets {
// Once the lines have more segments than the check takes, it reports them as too complex:
// the rest are not copied.
if segments > MAX_SEGMENTS {
break;
}
let Some(n) = d.node(id) else { continue };
let (Some(role), Some(path)) = (table.role_of(n), path_of(n)) else { continue };
if on_non_printing_layer(d, id) {
non_printing.push(id.0);
}
segments = segments.saturating_add(path.subpaths.iter().map(|sp| sp.segment_count()).sum());
lines.push(FoldLine { path, kind: kind(role), key: id.0 });
}
let (found, mut issues) = blanks(&lines, tolerance);
if !non_printing.is_empty() {
issues.push(vectorcraft_three_d::fold::Issue { code: IssueCode::NonPrinting, keys: non_printing, at: None });
}
let ok = !issues.iter().any(|i| i.code.is_error());
let rows: Vec<Value> = issues
.iter()
.map(|i| {
let mut row = json!({
"severity": if i.code.is_error() { "error" } else { "warning" },
"code": i.code.id(),
"message": message(i.code, scope),
"ids": i.keys,
});
if let (Some(at), Some(o)) = (i.at, row.as_object_mut()) {
o.insert("at".into(), json!([at.x, at.y]));
}
row
})
.collect();
if select {
let mut ids: Vec<NodeId> = issues.iter().flat_map(|i| i.keys.iter().map(|k| NodeId(*k))).filter(|id| d.node(*id).is_some()).collect();
ids.sort_unstable_by_key(|id| id.0);
ids.dedup();
if !ids.is_empty() {
s.select(|_, sel| sel.set(ids.iter().copied()))?;
}
}
Ok(json!({
"ok": ok,
"blanks": found.len(),
"panels": found.iter().map(|b| b.panels.len()).sum::<usize>(),
"hinges": found.iter().map(|b| b.hinges.len()).sum::<usize>(),
"holes": found.iter().map(|b| b.holes.len()).sum::<usize>(),
"issues": rows,
"scope": scope,
}))
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,180 @@
//! Tests for Check Fold Lines: the blanks, panels, hinges and issues of fold lines drawn in a
//! document.
use serde_json::{Value, json};
use crate::*;
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap();
s
}
fn path(s: &mut Session, d: &str) -> u64 {
s.execute("path.create", &json!({ "d": d })).unwrap()["id"].as_u64().unwrap()
}
fn role(s: &mut Session, role: &str, ids: &[u64]) {
s.execute("addon.packaging.setRole", &json!({ "role": role, "ids": ids })).unwrap();
}
fn check(s: &mut Session, p: Value) -> Value {
s.execute("addon.packaging.check", &p).unwrap()
}
fn codes(r: &Value) -> Vec<&str> {
r["issues"].as_array().unwrap().iter().map(|i| i["code"].as_str().unwrap()).collect()
}
/// A tray blank: a 100 pt base with a 40 pt wall on each side, its outline a cut line and the
/// base's four sides creases → (outline, creases).
fn tray(s: &mut Session) -> (u64, Vec<u64>) {
let outline = path(s, "M140 100 L240 100 L240 140 L280 140 L280 240 L240 240 L240 280 L140 280 L140 240 L100 240 L100 140 L140 140 Z");
let creases = vec![path(s, "M140 140 L240 140"), path(s, "M240 140 L240 240"), path(s, "M240 240 L140 240"), path(s, "M140 240 L140 140")];
role(s, "cut", &[outline]);
role(s, "crease", &creases);
s.execute("select.none", &json!({})).unwrap();
(outline, creases)
}
#[test]
fn a_tray_checks_clean_with_five_panels_and_four_hinges() {
let mut s = session();
tray(&mut s);
let steps = s.doc().unwrap().history.undo.len();
let r = check(&mut s, json!({}));
assert_eq!(r["ok"], true, "{r}");
assert_eq!((r["blanks"].as_u64(), r["panels"].as_u64(), r["hinges"].as_u64(), r["holes"].as_u64()), (Some(1), Some(5), Some(4), Some(0)), "{r}");
assert!(codes(&r).is_empty(), "{r}");
assert_eq!(r["scope"], "document");
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "a check records no undo step");
}
#[test]
fn the_selection_or_ids_limit_the_check_to_their_lines() {
let mut s = session();
let (outline, creases) = tray(&mut s);
s.execute("select.set", &json!({ "ids": [creases[0]] })).unwrap();
let r = check(&mut s, json!({}));
assert_eq!((r["scope"].as_str(), r["ok"].as_bool()), (Some("selection"), Some(false)));
assert_eq!(codes(&r), ["noCut"]);
assert_eq!(r["issues"][0]["message"], "No cut lines are in the selection.");
let r = check(&mut s, json!({ "ids": [outline] }));
assert_eq!((r["scope"].as_str(), r["ok"].as_bool(), r["panels"].as_u64()), (Some("ids"), Some(true), Some(1)), "{r}");
let r = check(&mut s, json!({ "ids": [creases[1]] }));
assert_eq!((r["scope"].as_str(), codes(&r)), (Some("ids"), vec!["noCut"]));
assert_eq!(r["issues"][0]["message"], "No cut lines are among the given objects.");
// No fold lines at all in the document.
let mut s = session();
let r = check(&mut s, json!({}));
assert_eq!(codes(&r), ["noCut"]);
assert_eq!(r["issues"][0]["message"], "No cut lines are in the document.");
}
#[test]
fn issues_name_their_lines_and_select_selects_them() {
let mut s = session();
let (_, creases) = tray(&mut s);
// A slit from the outline that stops in the middle of the base.
let slit = path(&mut s, "M190 100 L190 190");
role(&mut s, "cut", &[slit]);
s.execute("select.none", &json!({})).unwrap();
let r = check(&mut s, json!({}));
assert_eq!(r["ok"], false);
let loose = r["issues"].as_array().unwrap().iter().find(|i| i["code"] == "looseEnd").cloned().unwrap();
assert_eq!((loose["severity"].as_str(), loose["ids"].clone()), (Some("error"), json!([slit])), "{r}");
assert_eq!(loose["at"], json!([190.0, 190.0]));
assert!(s.doc().unwrap().selection.objects.is_empty(), "without select, the selection stays");
let r = check(&mut s, json!({ "select": true }));
let named: std::collections::BTreeSet<u64> =
r["issues"].as_array().unwrap().iter().flat_map(|i| i["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap())).collect();
let selected: std::collections::BTreeSet<u64> = s.doc().unwrap().selection.objects.iter().map(|id| id.0).collect();
assert!(selected.contains(&slit) && selected == named, "{selected:?} {named:?}");
assert!(!selected.contains(&creases[1]));
}
#[test]
fn a_clean_check_with_select_leaves_the_selection_alone() {
let mut s = session();
let (outline, _) = tray(&mut s);
s.execute("select.set", &json!({ "ids": [outline] })).unwrap();
let r = check(&mut s, json!({ "ids": [outline], "select": true }));
assert!(codes(&r).is_empty(), "{r}");
assert_eq!(s.doc().unwrap().selection.objects.iter().map(|id| id.0).collect::<Vec<_>>(), [outline]);
}
#[test]
fn tolerance_is_checked_and_joins_gaps_up_to_it() {
let mut s = session();
tray(&mut s);
for bad in [json!(0.005), json!(10.5), json!("x"), json!(true)] {
let e = s.execute("addon.packaging.check", &json!({ "tolerance": bad })).unwrap_err().to_string();
assert!(e.contains("tolerance"), "{e}");
}
let e = s.execute("addon.packaging.check", &json!({ "select": 1 })).unwrap_err().to_string();
assert!(e.contains("select"), "{e}");
for edge in [json!(0.01), json!(10), json!("2 mm")] {
assert_eq!(check(&mut s, json!({ "tolerance": edge }))["ok"], true);
}
// A slit that stops 0.5 pt short of a crease: a gap at a tolerance of 1 pt, a loose end at 0.1 pt.
let mut s = session();
tray(&mut s);
let slit = path(&mut s, "M190 100 L190 139.5");
role(&mut s, "cut", &[slit]);
s.execute("select.none", &json!({})).unwrap();
assert!(codes(&check(&mut s, json!({ "tolerance": 0.1 }))).contains(&"looseEnd"));
let near = check(&mut s, json!({ "tolerance": 1 }));
assert!(!codes(&near).contains(&"looseEnd"), "{near}");
}
#[test]
fn hidden_lines_are_left_out_and_lines_on_a_non_printing_layer_are_noted() {
let mut s = session();
let (_, creases) = tray(&mut s);
// A hidden crease is not checked while nothing is selected: the tray has three hinges and a
// panel joined by none.
s.execute("layer.setProps", &json!({ "ids": [creases[0]], "visible": false })).unwrap();
s.execute("select.none", &json!({})).unwrap();
let r = check(&mut s, json!({}));
assert_eq!((r["panels"].as_u64(), r["hinges"].as_u64()), (Some(4), Some(3)), "{r}");
// The same in a selected group, and with the group named by `ids`: the hidden member is left
// out too.
let mut s = session();
let (outline, creases) = tray(&mut s);
s.execute("select.set", &json!({ "ids": [outline, creases[0], creases[1], creases[2], creases[3]] })).unwrap();
let group = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap();
s.execute("layer.setProps", &json!({ "ids": [creases[0]], "visible": false })).unwrap();
s.execute("select.set", &json!({ "ids": [group] })).unwrap();
for p in [json!({}), json!({ "ids": [group] })] {
let r = check(&mut s, p);
assert_eq!((r["panels"].as_u64(), r["hinges"].as_u64()), (Some(4), Some(3)), "{r}");
}
// A cut line on a layer that does not print.
let mut s = session();
s.execute("layer.new", &json!({ "printable": false })).unwrap();
let (outline, _) = tray(&mut s);
let r = check(&mut s, json!({}));
assert_eq!(r["ok"], true, "a warning only");
let note = r["issues"].as_array().unwrap().iter().find(|i| i["code"] == "nonPrinting").cloned().unwrap();
assert_eq!(note["severity"], "warning");
assert!(note["ids"].as_array().unwrap().contains(&json!(outline)), "{note}");
assert_eq!(note["message"], "A fold line is on a non-printing layer.");
}
#[test]
fn a_compound_path_and_a_grouped_line_are_checked() {
let mut s = session();
let (outline, creases) = tray(&mut s);
// A window: a closed cut line in the base, made a compound path with nothing else.
let window = path(&mut s, "M170 170 L210 170 L210 210 L170 210 Z");
s.execute("select.set", &json!({ "ids": [window] })).unwrap();
let compound = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64();
let window = compound.unwrap_or(window);
role(&mut s, "cut", &[window]);
s.execute("select.set", &json!({ "ids": [outline, creases[0], creases[1], creases[2], creases[3], window] })).unwrap();
s.execute("object.group", &json!({})).unwrap();
let r = check(&mut s, json!({}));
assert_eq!(r["scope"], "selection");
assert_eq!((r["ok"].as_bool(), r["panels"].as_u64(), r["holes"].as_u64()), (Some(true), Some(5), Some(1)), "{r}");
}
@@ -186,7 +186,7 @@ fn free_role_name(d: &Document, table: &RoleTable, role: Role) -> String {
/// Whether `n` can carry a role: a path (a live shape too) that is neither a clipping path nor a
/// guide, or a compound path.
fn can_carry(n: &Node) -> bool {
pub(super) fn can_carry(n: &Node) -> bool {
match &n.kind {
NodeKind::Path { clipping, guide, .. } => !clipping && !guide,
NodeKind::Compound { .. } => true,
@@ -199,7 +199,7 @@ fn can_carry(n: &Node) -> bool {
/// how many of `roots` and their members can't (text, images, symbol instances and other objects).
/// With `editable`, objects that are locked or hidden, are in a locked or hidden group or layer, or
/// are on a locked artboard are left out and counted as skipped.
fn role_targets(d: &Document, roots: &[NodeId], editable: bool) -> (Vec<NodeId>, usize) {
pub(super) fn role_targets(d: &Document, roots: &[NodeId], editable: bool) -> (Vec<NodeId>, usize) {
fn walk(n: &Node, out: &mut Vec<NodeId>, skipped: &mut usize) {
match &n.kind {
NodeKind::Group { children, .. } => {
@@ -96,7 +96,8 @@ fn common_tangents(s: &mut Session, p: &Value) -> Result<Value> {
};
return Ok(json!({ "ids": [], "external": 0, "internal": 0, "centerline": null, "warning": warning.to_string() }));
}
let center = (centerline && (a.center() - b.center()).hypot() > 1e-9).then(|| (a.center(), b.center()));
// Centers closer than a billionth of the larger path's size count as one point: no line.
let center = (centerline && (a.center() - b.center()).hypot() > 1e-9 * a.size().max(b.size())).then(|| (a.center(), b.center()));
let fill = Paint::None;
let stroke = if s.paint.stroke.is_none() { Paint::solid(Color::BLACK) } else { s.paint.stroke.clone() };
let mut look = s.new_art_look(fill, stroke, s.paint.stroke_width.max(0.1));
@@ -162,6 +162,19 @@ fn a_convex_bezier_path_and_the_centerline() {
}
}
#[test]
fn tiny_paths_close_together_still_get_the_centerline() {
// Two circles a ten-billionth of a point wide, half a billionth apart: separate, with all four
// tangents, and centers apart by far more than their sizes' rounding.
let mut s = session();
let a = circle(&mut s, 1.0, 1.0, 1e-10);
let b = circle(&mut s, 1.0 + 5e-10, 1.0, 1e-10);
let r = s.execute(C, &json!({"ids": [a.0, b.0], "centerline": true})).unwrap();
assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(2), Some(2)), "{r}");
assert_eq!(r["ids"].as_array().map(Vec::len), Some(5), "{r}");
assert_eq!(r["centerline"], r["ids"][4]);
}
#[test]
fn the_lines_take_the_current_stroke_and_no_fill() {
let mut s = session();
+3
View File
@@ -27,6 +27,9 @@ use crate::EngineError;
/// Whether Reset Transformation changes a symbol instance.
pub use symbols::reset_transformation_changes;
/// The Symbols panel's current symbol, as `symbol.list` answers it.
pub use symbols::current_symbol;
mod brushes;
mod dynamic;
mod symbols;
+12 -11
View File
@@ -162,7 +162,7 @@ pub(super) fn symbol_sort(s: &mut Session, _: &Value) -> Result<Value> {
if d.symbols.is_sorted_by_key(key) {
return ok();
}
let current = current_symbol(d).or_else(|| symbol_names(d).into_iter().next());
let current = current_symbol(d);
s.edit("Sort by Name", |d, _| {
if let Some(name) = current {
d.unknown.insert(CURRENT_SYMBOL.into(), json!(name));
@@ -173,12 +173,15 @@ pub(super) fn symbol_sort(s: &mut Session, _: &Value) -> Result<Value> {
ok()
}
fn symbol_names(d: &Document) -> Vec<String> {
d.symbols.iter().map(|s| s.name.clone()).collect()
}
fn current_symbol(d: &Document) -> Option<String> {
d.unknown.get(CURRENT_SYMBOL).and_then(Value::as_str).filter(|n| d.symbols.iter().any(|s| s.name == *n)).map(str::to_string)
/// The Symbols panel's current symbol, as `symbol.list` answers it: the stored current symbol
/// while `d` has a symbol of that name, else the first symbol; `None` when `d` has no symbols.
pub fn current_symbol(d: &Document) -> Option<String> {
d.unknown
.get(CURRENT_SYMBOL)
.and_then(Value::as_str)
.filter(|n| d.symbols.iter().any(|s| s.name == *n))
.or_else(|| d.symbols.first().map(|s| s.name.as_str()))
.map(str::to_string)
}
pub(super) fn symbol_list(s: &mut Session, _: &Value) -> Result<Value> {
@@ -200,7 +203,7 @@ pub(super) fn symbol_list(s: &mut Session, _: &Value) -> Result<Value> {
})
})
.collect();
Ok(json!({ "symbols": list, "current": current_symbol(d).or_else(|| symbol_names(d).into_iter().next()) }))
Ok(json!({ "symbols": list, "current": current_symbol(d) }))
}
/// Store `art` ([`normalize`]d, of natural size `size`) as symbol `name`, which becomes the
@@ -398,9 +401,7 @@ fn resolve_symbol(d: &Document, p: &Value, cmd: &str) -> Result<String> {
match str_param(p, "name") {
Some(n) if d.symbols.iter().any(|s| s.name == n) => Ok(n.to_string()),
Some(n) => Err(bad(cmd, format!("no symbol named `{n}`"))),
None => {
current_symbol(d).or_else(|| symbol_names(d).into_iter().next()).ok_or_else(|| EngineError::Other("the document has no symbols".into()))
}
None => current_symbol(d).ok_or_else(|| EngineError::Other("the document has no symbols".into())),
}
}
+1 -1
View File
@@ -126,7 +126,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Live Paint Bucket (Stroke)",
[],
None,
"{group: id, point: [x,y], color?|swatch?|none? (default: current stroke), width?: pt (default: current weight), tolerance?: pt (4), scope?: \"one\" (default: the edge alone) | \"connected\" (a double-click: also each edge joined to it, end to end, through edges that draw with stroke paint match) | \"samePaint\" (a triple-click: also every edge of the group that draws with stroke paint match), match?: paint (as the document stores it; scope connected or samePaint only; default: the stroke paint the edge draws with; an edge draws with the paint of its topmost stroke that is shown, with paint, above 0 pt and not fully transparent, and with none when the edge is fully transparent or has no such stroke), through?: [id…] (scope connected only; at most 4096 of the group's edges, each given once, counted as drawing with stroke paint match whatever they draw with, such as another edge a double-click's clicks painted; any other id is an error), tint?: 0..100, keepModel?: bool (both as paint.setFill)} paint the edge nearest point, skipping hidden edges: each edge reached has its strokes replaced by one stroke with the paint and width, shown, fully opaque and blending normally, in the place of its topmost stroke and with the dashes, caps and arrowheads of its topmost shown stroke (a new stroke above the fills when it has none; none leaves one stroke of none), and its fills stay as they are; when every edge it reaches already has only that one stroke (at any width for none), nothing changes (no undo step, and the recent colors stay as they are) → {group, edge, count (edges reached)}",
"{group: id, point: [x,y], color?|swatch?|none? (default: current stroke), width?: pt (default: current weight), tolerance?: pt (4), points?: [[x,y]…] (a drag polyline starting at point; 1 to 4096 finite canvas points; also paints every edge of the group, hidden edges skipped, that the polyline crosses or comes within 0.0001 pt of), continuation?: [[[x,y]…]…] (further path chunks of 1 to 4096 finite canvas points each; each starts at the preceding chunk's last point; requires points), scope?: \"one\" (default: the edge alone) | \"connected\" (a double-click: also each edge joined to it, end to end, through edges that draw with stroke paint match) | \"samePaint\" (a triple-click: also every edge of the group that draws with stroke paint match; \"connected\" and \"samePaint\" are refused with points), match?: paint (as the document stores it; scope connected or samePaint only; default: the stroke paint the edge draws with; an edge draws with the paint of its topmost stroke that is shown, with paint, above 0 pt and not fully transparent, and with none when the edge is fully transparent or has no such stroke), through?: [id…] (scope connected only; at most 4096 of the group's edges, each given once, counted as drawing with stroke paint match whatever they draw with, such as another edge a double-click's clicks painted; any other id is an error), tint?: 0..100, keepModel?: bool (both as paint.setFill)} paint the edge nearest point, skipping hidden edges: each edge reached has its strokes replaced by one stroke with the paint and width, shown, fully opaque and blending normally, in the place of its topmost stroke and with the dashes, caps and arrowheads of its topmost shown stroke (a new stroke above the fills when it has none; none leaves one stroke of none), and its fills stay as they are; when every edge it reaches already has only that one stroke (at any width for none), nothing changes (no undo step, and the recent colors stay as they are) → {group, edge, count (edges reached)}",
has_doc,
lp_stroke_edge
),
+49 -22
View File
@@ -409,43 +409,61 @@ fn match_param(p: &Value, c: &str, allowed: bool, scopes: &str) -> Result<Option
serde_json::from_value::<super::Paint>(v.clone()).map(Some).map_err(|_| bad(c, "match must be a paint as the document stores it"))
}
pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "livePaint.fill";
let pt = point_param(p, "point").filter(|q| finite(*q)).ok_or_else(|| bad(C, "missing point [x,y]"))?;
let scope = scope_param(p, C)?;
let like = match_param(p, C, scope == LpScope::SamePaint, "\"samePaint\"")?;
/// The drag path of `livePaint.fill` or `livePaint.strokeEdge` (command `c`) pressed at `start`:
/// `points` followed by each chunk of `continuation`, where every chunk holds 1 to
/// [`b::LP_FILL_CHUNK_POINTS`] finite canvas points and starts at the last point of the chunk
/// before it (`points` at `start`). None when `points` is left out. With a `scope` other than
/// `one`, `points` is an error.
fn path_param(p: &Value, c: &str, start: Point, scope: LpScope) -> Result<Option<Vec<Vec<Point>>>> {
if scope != LpScope::One && p.get("points").is_some() {
return Err(bad(C, "scope applies to a click: leave out points"));
return Err(bad(c, "scope applies to a click: leave out points"));
}
let parse_chunk = |input: &Value, start: Point| -> Result<Vec<Point>> {
let values = input
.as_array()
.filter(|points| !points.is_empty() && points.len() <= b::LP_FILL_CHUNK_POINTS)
.ok_or_else(|| bad(C, "each path chunk must contain 1 to 4096 points"))?;
.ok_or_else(|| bad(c, "each path chunk must contain 1 to 4096 points"))?;
let points: Vec<_> = values
.iter()
.map(|point| {
let pair = point.as_array().filter(|pair| pair.len() == 2).ok_or_else(|| bad(C, "points must be [x,y] pairs"))?;
let x = pair.first().and_then(Value::as_f64).ok_or_else(|| bad(C, "point x must be a number"))?;
let y = pair.get(1).and_then(Value::as_f64).ok_or_else(|| bad(C, "point y must be a number"))?;
let pair = point.as_array().filter(|pair| pair.len() == 2).ok_or_else(|| bad(c, "points must be [x,y] pairs"))?;
let x = pair.first().and_then(Value::as_f64).ok_or_else(|| bad(c, "point x must be a number"))?;
let y = pair.get(1).and_then(Value::as_f64).ok_or_else(|| bad(c, "point y must be a number"))?;
let point = Point::new(x, y);
if !finite(point) {
return Err(bad(C, "points must be finite canvas points"));
return Err(bad(c, "points must be finite canvas points"));
}
Ok(point)
})
.collect::<Result<_>>()?;
if points.first() != Some(&start) {
return Err(bad(C, "path chunks must share their boundary point"));
return Err(bad(c, "path chunks must share their boundary point"));
}
Ok(points)
};
let points = p.get("points");
let Some(points) = p.get("points") else {
return if p.get("continuation").is_some() { Err(bad(c, "continuation requires points")) } else { Ok(None) };
};
let continuation = match p.get("continuation") {
None => &[][..],
Some(input) if points.is_some() => input.as_array().ok_or_else(|| bad(C, "continuation must be an array of path chunks"))?.as_slice(),
Some(_) => return Err(bad(C, "continuation requires points")),
Some(input) => input.as_array().ok_or_else(|| bad(c, "continuation must be an array of path chunks"))?.as_slice(),
};
let mut chunks: Vec<Vec<Point>> = Vec::with_capacity(continuation.len() + 1);
let mut last = start;
for input in std::iter::once(points).chain(continuation) {
let chunk = parse_chunk(input, last)?;
last = chunk.last().copied().unwrap_or(last);
chunks.push(chunk);
}
Ok(Some(chunks))
}
pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "livePaint.fill";
let pt = point_param(p, "point").filter(|q| finite(*q)).ok_or_else(|| bad(C, "missing point [x,y]"))?;
let scope = scope_param(p, C)?;
let like = match_param(p, C, scope == LpScope::SamePaint, "\"samePaint\"")?;
let path = path_param(p, C, pt, scope)?;
crate::cmd::paint::check_keep_model(p, C)?;
let paint = paint_from(s, p)?.unwrap_or_else(|| s.paint.fill.clone());
let group = object_param(p, "group", C)?;
@@ -472,7 +490,7 @@ pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> {
targets.extend(b::faces(n).into_iter().filter(|f| f.visible && f.appearance.fill_paint() == like).map(|f| f.id));
}
}
if let Some(points) = points {
if let Some(chunks) = &path {
let n = d.node(gid).ok_or(EngineError::NoNode(gid))?;
// Use the existing region-crossing probes, so even a face narrower than the distance
// between pointer events is filled. Reversing matches visible_face_at's front first.
@@ -488,11 +506,8 @@ pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> {
}
}
let map = b::BuilderMap { regions, ..Default::default() };
let mut last = pt;
for input in std::iter::once(points).chain(continuation) {
let chunk = parse_chunk(input, last)?;
last = chunk.last().copied().unwrap_or(last);
targets.extend(map.hits_along(&chunk, None).regions.iter().filter_map(|i| face_ids.get(*i).copied()));
for chunk in chunks {
targets.extend(map.hits_along(chunk, None).regions.iter().filter_map(|i| face_ids.get(*i).copied()));
}
}
Ok((fid, targets))
@@ -567,6 +582,7 @@ pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result<Value> {
let tol = number_or(p, "tolerance", 4.0, C)?.clamp(0.0, 1000.0);
let scope = scope_param(p, C)?;
let like = match_param(p, C, scope != LpScope::One, "\"connected\" or \"samePaint\"")?;
let path = path_param(p, C, pt, scope)?;
let through: Vec<NodeId> = match p.get("through") {
None => vec![],
Some(_) if scope != LpScope::Connected => return Err(bad(C, "through applies to scope \"connected\"")),
@@ -590,7 +606,18 @@ pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result<Value> {
let eid = start.id;
let like = like.unwrap_or_else(|| b::lp_stroke_paint(start));
let targets = match scope {
LpScope::One => vec![eid],
// A drag also reaches every edge of the group that is not hidden and that its path
// crosses or touches.
LpScope::One => std::iter::once(eid)
.chain(
path.as_deref()
.map(|chunks| b::visible_edges_along(n, chunks))
.unwrap_or_default()
.into_iter()
.map(|e| e.id)
.filter(|id| *id != eid),
)
.collect(),
LpScope::Connected => b::connected_edges_through(n, eid, &like, &through),
LpScope::SamePaint => std::iter::once(eid)
.chain(b::edges(n).into_iter().filter(|e| e.visible && e.id != eid && b::lp_stroke_paint(e) == like).map(|e| e.id))
+51 -19
View File
@@ -64,7 +64,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Arc",
[],
None,
"{x1, y1, x2, y2, closed?, slope?} or {x, y, lengthX, lengthY, reference?, baseAlong?: x|y, slope?, closed?, fillArc?} → {id}",
"{x1, y1, x2, y2, closed?, slope?: −100…100 (default 100), rotation?: deg clockwise about (x1, y1)} or {x, y, lengthX, lengthY, reference?: 0–8 (default 0), baseAlong?: x|y (either case; default x), slope?: −100…100 (default 50), closed?, fillArc?, rotation?: deg clockwise about the reference point (x, y)} (0: upright); a reference or baseAlong given as anything else (null included) or a slope outside its range is an error and draws nothing → {id}",
has_doc,
arc
),
@@ -73,7 +73,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Rectangular Grid",
[],
None,
"{x, y, width, height, rows=5, columns=5, rowSkew=0, columnSkew=0 (−500…500 %: + crowds the horizontal dividers toward the top, the vertical ones toward the right), frame=true (the outside as one rectangle, else its four sides), fill=false (the current fill, else none), rotation?: deg clockwise about the centre (0: upright)} → {id}",
"{x, y, width, height, rows=5, columns=5 (whole numbers; at most 999), rowSkew=0, columnSkew=0 (−500…500 %: + crowds the horizontal dividers toward the top, the vertical ones toward the right), frame=true (the outside as one rectangle, else its four sides), fill=false (the current fill, else none), rotation?: deg clockwise about the centre (0: upright)} → {id}",
has_doc,
rect_grid
),
@@ -82,7 +82,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Polar Grid",
[],
None,
"{x, y, width, height, concentric=5, radial=5, concentricSkew=0, radialSkew=0 (−500…500 %: + crowds the ellipses toward the outside, the radial dividers clockwise of the top one), compound=false (the ellipses pair up into compound-path rings), fill=false (the current fill, else none), rotation?: deg clockwise about the centre (0: upright)} → {id}",
"{x, y, width, height, concentric=5, radial=5 (whole numbers; at most 999), concentricSkew=0, radialSkew=0 (−500…500 %: + crowds the ellipses toward the outside, the radial dividers clockwise of the top one), compound=false (the ellipses pair up into compound-path rings), fill=false (the current fill, else none), rotation?: deg clockwise about the centre (0: upright)} → {id}",
has_doc,
polar_grid
),
@@ -299,7 +299,8 @@ fn path_kind(path: PathData, live: Option<LiveShape>) -> NodeKind {
/// (<https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/rotate-objects-by-specific-angles.html>):
/// a box (rectangle, ellipse, grid) runs along the turned axes from `pivot`, the point the dialog
/// placed at the click (its top-left corner `x`, `y`, or a grid's reference point), which stays
/// put; a polygon or star turns its base orientation about its centre. The params as they are at
/// put; an arc sized by its lengths turns about its reference point `x`, `y`, which the dialog
/// placed at the click; a polygon or star turns its base orientation about its centre. The params as they are at
/// 0° or a whole turn, for other commands and when they already carry a `rotation`.
pub fn constrain_click(s: &Session, cmd: &str, mut params: Value, pivot: Point) -> Value {
let base = s.prefs.constrain_angle;
@@ -318,6 +319,9 @@ pub fn constrain_click(s: &Session, cmd: &str, mut params: Value, pivot: Point)
"shape.polygon" | "shape.star" => {
o.insert("rotation".into(), json!(rotation));
}
"shape.arc" if o.contains_key("lengthX") || o.contains_key("lengthY") => {
o.insert("rotation".into(), json!(rotation));
}
_ => {}
}
params
@@ -590,26 +594,56 @@ fn spiral(s: &mut Session, p: &Value) -> Result<Value> {
}
fn arc(s: &mut Session, p: &Value) -> Result<Value> {
let rotation = if p.get("rotation").is_some() { f64_req(p, "rotation", "shape.arc")? } else { 0.0 };
if !rotation.is_finite() {
return Err(bad("shape.arc", "rotation must be finite"));
}
let closed = switch_or(p, "closed", false, "shape.arc")?;
let fill_arc = switch_or(p, "fillArc", false, "shape.arc")?;
let base_x = !matches!(p.get("baseAlong").and_then(Value::as_str), Some("y" | "Y"));
let path = if p.get("lengthX").is_some() || p.get("lengthY").is_some() {
// Given values are checked in both forms, null included; only a left-out key takes its default.
let base_x = match p.get("baseAlong") {
None => true,
Some(Value::String(v)) if v.eq_ignore_ascii_case("x") || v.eq_ignore_ascii_case("y") => v.eq_ignore_ascii_case("x"),
Some(_) => return Err(bad("shape.arc", "`baseAlong` must be one of x, y")),
};
let reference = match p.get("reference") {
None => 0,
Some(v) => match (v.as_u64(), v.as_f64()) {
(Some(n), _) if n <= 8 => n as usize,
(None, Some(x)) if (0.0..=8.0).contains(&x) && x.fract() == 0.0 => x as usize,
_ => return Err(bad("shape.arc", "`reference` must be a whole number from 0 to 8")),
},
};
let slope = |default: f64| {
let (key, lo, hi) = ("slope", -100.0, 100.0);
let v = number_or(p, key, default, "shape.arc")?;
if (lo..=hi).contains(&v) { Ok(v) } else { Err(bad("shape.arc", format!("`{key}` must be from {lo} to {hi}, not {v}"))) }
};
// The upright path, and the point `rotation` turns it about.
let (path, pivot) = if p.get("lengthX").is_some() || p.get("lengthY").is_some() {
let anchor = Point::new(f64_req(p, "x", "shape.arc")?, f64_req(p, "y", "shape.arc")?);
let reference = p.get("reference").and_then(Value::as_u64).unwrap_or(0) as usize;
shapes::arc_segment(
let path = shapes::arc_segment(
anchor,
reference,
number_or(p, "lengthX", 100.0, "shape.arc")?,
number_or(p, "lengthY", 100.0, "shape.arc")?,
base_x,
number_or(p, "slope", 50.0, "shape.arc")?,
slope(50.0)?,
closed,
)
);
(path, anchor)
} else {
let a = Point::new(f64_req(p, "x1", "shape.arc")?, f64_req(p, "y1", "shape.arc")?);
let b = Point::new(f64_req(p, "x2", "shape.arc")?, f64_req(p, "y2", "shape.arc")?);
let slope = number_or(p, "slope", 100.0, "shape.arc")?;
shapes::arc(a, b, slope, closed, base_x)
(shapes::arc(a, b, slope(100.0)?, closed, base_x), a)
};
// 0 and whole turns leave the path as it is; quarter turns are exact.
let bbox_angle = bbox_turn(rotation);
let path = if bbox_angle == 0.0 {
path
} else {
let c = pivot.to_vec2();
path.transformed(Affine::translate(c) * vectorcraft_geom::rotate_deg(rotation) * Affine::translate(-c))
};
let fill = if fill_arc { s.paint.fill.clone() } else { vectorcraft_color::Paint::None };
let look = s.new_art_look(
@@ -617,7 +651,7 @@ fn arc(s: &mut Session, p: &Value) -> Result<Value> {
if s.paint.stroke.is_none() { vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK) } else { s.paint.stroke.clone() },
s.paint.stroke_width.max(0.1),
);
add_look(s, "Arc", path_kind(path, None), look, None)
insert_look_turned(s, "Arc", path_kind(path, None), look, None, true, bbox_angle)
}
/// The grid `paths` (bottom first) as one selected group in the new-art stroke, filled with the
@@ -655,13 +689,11 @@ fn grid_group(s: &mut Session, label: &str, (paths, bbox_angle): (Vec<PathData>,
Ok(json!({ "id": id.0 }))
}
/// A grid's divider count `count` (an error unless it is a number or null; 5 unless it is a JSON
/// whole number of 0 or more, so 4.0 gives 4 and 2.5 gives 5; at most 999) with its skew `key` in percent (0 when
/// absent, clamped to ±[`shapes::GRID_SKEW_MAX`]).
/// A grid's divider count `count` (5 when absent or null; a whole number of 0 or more, so 4.0 gives
/// 4, and anything else, such as 2.5, -1 or `"3"`, is an error; at most 999) with its skew `key` in
/// percent (0 when absent, clamped to ±[`shapes::GRID_SKEW_MAX`]).
fn dividers(p: &Value, count: &str, key: &str, cmd: &str) -> Result<(u32, f64)> {
check_numbers(p, &[count], cmd)?;
let whole = |v: &Value| v.as_u64().or_else(|| v.as_f64().filter(|f| f.is_finite() && *f >= 0.0 && f.fract() == 0.0).map(|f| f as u64));
let n = p.get(count).and_then(whole).unwrap_or(5).min(999) as u32;
let n = count_or(p, count, 5, cmd)?.min(999) as u32;
let skew = match p.get(key) {
None | Some(Value::Null) => 0.0,
Some(v) => v.as_f64().filter(|v| v.is_finite()).ok_or_else(|| bad(cmd, format!("`{key}` must be a number")))?,
+70 -6
View File
@@ -1498,9 +1498,41 @@ mod tests {
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
s.execute("swatch.new", &json!({"name": "Ink", "color": {"model": "cmyk", "c": 0, "m": 1, "y": 1, "k": 0}, "spot": true})).unwrap();
let mut bytes = Vec::new();
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(2, 1, vec![0, 255]).unwrap())
.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png)
.unwrap();
{
let __dyn: image::DynamicImage = image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(2, 1, vec![0, 255]).unwrap());
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| bytes.extend_from_slice(&__b))
}
.unwrap();
let image = s
.edit("Place", |d, sel| {
d.images.insert("gray".into(), vectorcraft_doc::ImageBlob::png(bytes));
@@ -1655,9 +1687,41 @@ mod tests {
s.execute("paint.setStroke", &json!({"ids": [word], "none": true})).unwrap();
// A grayscale image colorized with the spot color.
let mut bytes = Vec::new();
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(2, 1, vec![0, 255]).unwrap())
.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png)
.unwrap();
{
let __dyn: image::DynamicImage = image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(2, 1, vec![0, 255]).unwrap());
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| bytes.extend_from_slice(&__b))
}
.unwrap();
let image = s
.edit("Place", |d, sel| {
d.images.insert("gray".into(), vectorcraft_doc::ImageBlob::png(bytes));
+1 -1
View File
@@ -31,6 +31,6 @@ mod freehand;
mod smooth;
pub use commands::specs;
pub(super) use common::{ids_json, replace_with_pieces, usize_opt};
pub(super) use common::{center_strokes, ids_json, replace_with_pieces, usize_opt};
pub(super) use cut::{components, erase_outline};
pub(super) use freehand::freehand_brushed;
+1 -1
View File
@@ -74,7 +74,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Split Path",
[],
None,
"{id, subpath?, segment, t: 0–1 (0.5)} or {id, subpath?, anchor}: closed paths open there, open paths become two; one of the two new end points is left selected → {ids}. A t outside 0–1 is refused with an error, and nothing changes",
"{id, subpath?, segment, t: 0–1 (0.5)} or {id, subpath?, anchor}: closed paths open there, open paths become two; one of the two new end points is left selected; the paths keep the source's fill and stroke settings except that every stroke's alignment becomes Center (in a path of several subpaths, the other subpaths' strokes too) → {ids}. A t outside 0–1 is refused with an error, and nothing changes",
has_doc,
split
),
+20
View File
@@ -406,6 +406,26 @@ pub(super) fn sibling_with(d: &mut Document, id: NodeId, pd: PathData) -> Result
Ok(n)
}
/// Set every stroke of node `id`, and every stroke of the compound path it is a member of (whose
/// strokes its members show), to Center alignment. Every other stroke and fill setting stays as it
/// is, and an appearance whose strokes are all centered stays shared with its other copies.
pub(in super::super) fn center_strokes(d: &mut Document, id: NodeId) {
use vectorcraft_doc::{AppearanceItem, StrokeAlign};
let parent = d.parent_of(id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })));
for n in [Some(id), parent].into_iter().flatten() {
let Some(n) = d.node_mut(n) else { continue };
let off = |it: &AppearanceItem| matches!(it, AppearanceItem::Stroke(st) if st.align != StrokeAlign::Center);
if !n.appearance.items.iter().any(off) {
continue;
}
for it in &mut n.appearance.items {
if let AppearanceItem::Stroke(st) = it {
st.align = StrokeAlign::Center;
}
}
}
}
/// Replace path or compound path `id` with `pieces` (first keeps the id, the rest go right above
/// it; none removes it). `cut` removes the path or puts the other pieces above it. Returns ids.
pub(in super::super) fn replace_with_pieces(d: &mut Document, cut: &mut Beside, id: NodeId, pieces: Vec<PathData>) -> Result<Vec<NodeId>> {
+6 -2
View File
@@ -1,6 +1,6 @@
use super::common::{
PenRecord, SIZE_VARIATIONS, SIZES, Sample, dist_to_polyline, fill_targets, ids_json, path_mut, path_of, points_param, poly_bounds,
pressure_region, ranged, replace_with_pieces, samples_param, sibling_with, size_pressure, target_paths, usize_opt,
PenRecord, SIZE_VARIATIONS, SIZES, Sample, center_strokes, dist_to_polyline, fill_targets, ids_json, path_mut, path_of, points_param,
poly_bounds, pressure_region, ranged, replace_with_pieces, samples_param, sibling_with, size_pressure, target_paths, usize_opt,
};
use super::{
Anchor, AnchorKind, Beside, BezPath, BoolOp, Cap, EngineError, FillRule, Join, NodeId, Paint, ParamCurve, PathData, Point, Rect, Result, Session,
@@ -225,14 +225,17 @@ pub(super) fn split(s: &mut Session, p: &Value) -> Result<Value> {
sel.add(id);
sel.anchors.entry(id).or_default().insert((si, 0));
};
// The paths a cut makes keep the source's appearance with every stroke centered.
if sp.closed {
path.subpaths[si] = pieces.pop().ok_or_else(|| EngineError::Other("no such anchor".into()))?;
center_strokes(d, id);
pick(sel, id, si);
return Ok(vec![id]);
}
let [left, right] = <[SubPath; 2]>::try_from(pieces).map_err(|_| EngineError::Other("cannot split an open path at its end point".into()))?;
if path.subpaths.len() == 1 {
path.subpaths[0] = left;
center_strokes(d, id);
let node = sibling_with(d, id, PathData::single(right))?;
let (parent, idx, _) = d.position(id).ok_or(EngineError::NoNode(id))?;
let nid = d.insert(parent, idx + 1, node)?;
@@ -241,6 +244,7 @@ pub(super) fn split(s: &mut Session, p: &Value) -> Result<Value> {
} else {
path.subpaths[si] = left;
path.subpaths.insert(si + 1, right);
center_strokes(d, id);
pick(sel, id, si + 1);
Ok(vec![id])
}
+23 -17
View File
@@ -526,26 +526,34 @@ fn doc_compare(s: &mut Session, p: &Value) -> Result<Value> {
/// RGBA: a PNG, JPEG, WebP, TIFF or BMP within the allocation an opened image may take.
#[cfg(not(target_arch = "wasm32"))]
fn compare_image(path: &str) -> Result<image::RgbaImage> {
use image::ImageDecoder as _;
const C: &str = "document.compare";
let bytes = super::fileio::read_file(path)?;
if let Some((w, h)) = vectorcraft_doc::cmyk::oversized_tiff(&bytes) {
return Err(bad(C, format!("an image of {w} × {h} pixels is too large to draw")));
}
let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().map_err(|e| bad(C, format!("{path}: {e}")))?;
let readable = [image::ImageFormat::Png, image::ImageFormat::Jpeg, image::ImageFormat::WebP, image::ImageFormat::Tiff, image::ImageFormat::Bmp];
if !reader.format().is_some_and(|f| readable.contains(&f)) {
let format = craft_image_codecs::detect(&bytes);
let readable = [
craft_image_codecs::Format::Png,
craft_image_codecs::Format::Jpeg,
craft_image_codecs::Format::WebP,
craft_image_codecs::Format::Tiff,
craft_image_codecs::Format::Bmp,
];
let Some(format) = format.filter(|f| readable.contains(f)) else {
return Err(bad(C, format!("{path}: not a PNG, JPEG, WebP, TIFF or BMP image")));
}
let mut limits = image::Limits::default();
limits.max_alloc = Some(vectorcraft_doc::MAX_RASTER_ALLOC);
reader.limits(limits);
let decoder = reader.into_decoder().map_err(|e| bad(C, format!("{path}: {e}")))?;
let (w, h) = decoder.dimensions();
if decoder.total_bytes() > vectorcraft_doc::MAX_RASTER_ALLOC || u64::from(w) * u64::from(h) * 4 > vectorcraft_doc::MAX_RASTER_ALLOC {
return Err(bad(C, format!("an image of {w} × {h} pixels is too large to draw")));
}
Ok(image::DynamicImage::from_decoder(decoder).map_err(|e| bad(C, format!("{path}: {e}")))?.to_rgba8())
};
let mut opts = craft_image_codecs::DecodeOptions::default();
opts.limits.max_alloc = vectorcraft_doc::MAX_RASTER_ALLOC;
opts.limits.max_pixels = vectorcraft_doc::MAX_RASTER_ALLOC / 4;
let img = match craft_image_codecs::decode_as_with(format, &bytes, &opts) {
Ok(img) => img,
Err(craft_image_codecs::CodecError::LimitExceeded(_)) => {
return Err(bad(C, "image is too large to draw"));
}
Err(e) => return Err(bad(C, format!("{path}: {e}"))),
};
let (w, h) = img.dimensions();
image::RgbaImage::from_raw(w, h, img.to_rgba8()).ok_or_else(|| bad(C, format!("{path}: invalid pixel buffer")))
}
#[cfg(target_arch = "wasm32")]
@@ -1181,9 +1189,7 @@ fn clear(s: &mut Session, p: &Value) -> Result<Value> {
d.retain_guides(sel, |g| !g.id.is_some_and(|id| gone.contains(&id)));
}
if is_explicit {
for id in &ids {
sel.remove(*id);
}
sel.remove_all(ids.iter().copied());
sel.prune(d);
} else {
sel.clear();
+83 -10
View File
@@ -1238,6 +1238,69 @@ fn expand_node_except(
}
}
/// Replace `n`, a group or layer whose Transform effect's copies each carry the raster effects
/// listed before it ([`effects::outer_effects`]), with its art ([`effects::evaluate_container`]):
/// the copies become groups of their own with those effects, and they and what they hold get ids
/// of their own, so they expand as its members do; the raster effects after the Transform effect
/// stay on `n`. A copy that repeats an id ([`repeats_an_id`]) and holds a random Transform effect
/// ([`has_seeded`]) expands before its ids change ([`expand_in_place`]), as [`expand_pieces`] does,
/// and `members` gets what that expansion lists, by the copy's new id. `kept` gets the new id of
/// each copy of an object `skip` lists, and `out` gets `n` unless `listed` says it is there.
/// Returns whether `n` changed; any other object stays as it is. `Err`, with `n` as it is, when
/// such a copy still holds a random Transform effect after the raster budget left part of it as
/// it is: its new ids would give that effect another seed.
fn copies_carrying_raster(
d: &mut Document,
n: &mut Node,
(brushes, skip): (&[vectorcraft_brush::Brush], &[NodeId]),
kept: &mut Vec<NodeId>,
members: &mut std::collections::HashMap<NodeId, Vec<Listed>>,
(out, listed): (&mut Vec<Listed>, &mut bool),
raster: &mut RasterBudget,
) -> std::result::Result<bool, OverBudget> {
if !carries_copies(n) {
return Ok(false);
}
let Some(mut m) = effects::evaluate_container(Some(&*d), n) else { return Ok(false) };
let mut seen = std::collections::HashSet::from([n.id]);
for c in m.children_mut().into_iter().flatten().filter(|c| !c.is_ruler_guide()) {
let c = Arc::make_mut(c);
let left = raster.left;
let mut expanded = (has_seeded(c) && repeats_an_id(c, &seen)).then(|| expand_in_place(d, c, brushes, skip, raster));
if expanded.is_some() && raster.left > left && has_seeded(c) {
return Err(OverBudget);
}
let mut was = vec![];
if !skip.is_empty() {
c.walk(&mut |n| was.push(n.id));
}
fresh_ids_listed(d, c, &mut seen, expanded.as_deref_mut().unwrap_or_default());
// A copy of an object `skip` lists is left as it is too.
let mut at = 0;
c.walk(&mut |n| {
if was.get(at).is_some_and(|old| *old != n.id && skip.contains(old)) {
kept.push(n.id);
}
at += 1;
});
if let Some(expanded) = expanded {
members.insert(c.id, expanded);
}
}
if !*listed {
out.push((n.id, 0));
*listed = true;
}
*n = m;
Ok(true)
}
/// Is `n` a group or layer whose Transform effect's copies each carry the raster effects listed
/// before it ([`copies_carrying_raster`])?
fn carries_copies(n: &Node) -> bool {
is_container(n) && effects::outer_effects(n).len() != n.appearance.effects.len()
}
/// [`expand_node`] of `n`, which need not be in `d`: `n` with its appearance expanded, `None` when
/// it has nothing to expand. `out` gets the objects whose appearance expands, by places in the walk
/// of the expanded `n`, `n`'s first when its own does. The objects `skip` lists are not expanded.
@@ -1267,10 +1330,13 @@ fn expanded_node(
}
_ => None,
};
// The embedded images before the adjustment, when the raster budget may yet leave `n` as it
// is: the recolored copies the adjustment adds then go again.
let images_before = (effects::has_adjustment(&n) && !rasterfx::raster_fx(&n).is_empty())
// The embedded images before the adjustment and the expansions of the copies
// ([`copies_carrying_raster`]), when the raster budget may yet leave `n` as it is: the
// recolored copies and the images those add then go again.
let images_before = ((effects::has_adjustment(&n) && !rasterfx::raster_fx(&n).is_empty()) || carries_copies(&n))
.then(|| d.images.keys().cloned().collect::<std::collections::HashSet<_>>());
// What the raster budget had left before those expansions: it gets back what they took.
let budget_before = (raster.images, raster.pixels);
if effects::has_adjustment(&n)
&& let Some(m) = effects::adjust_in_document(d, &n, symbol_art)
{
@@ -1316,23 +1382,30 @@ fn expanded_node(
}
return Some(m);
}
// New ids of the copies of objects `skip` lists among the members.
let mut kept = vec![];
// Members of a group or layer that `expand_pieces` or `copies_carrying_raster` expanded, by id,
// with what their expansion lists.
let mut members = std::collections::HashMap::new();
let copies = copies_carrying_raster(d, &mut n, (brushes, skip), &mut kept, &mut members, (out, &mut listed_n), raster);
// Raster effects whose image would go past the budget stay: so does the object, with what is
// inside it and its color adjustments (a symbol instance stays an instance of its symbol).
let Ok(image) = raster_image(d, &n, raster) else {
// inside it and its color adjustments (a symbol instance stays an instance of its symbol), and
// so does a group or layer whose copies keep a random Transform effect the budget left.
let Ok(image) = copies.and_then(|copied| {
changed |= copied;
raster_image(d, &n, raster)
}) else {
out.truncate(listed_before);
if let Some(keys) = images_before {
d.images.retain(|k, _| keys.contains(k));
}
(raster.images, raster.pixels) = budget_before;
return None;
};
let mut v = n.clone();
rasterfx::strip_raster(&mut v, false);
let mut stroke_art =
|d: &mut Document, path: &PathData, rule: FillRule, st: &StrokeLayer| super::pathops::outlined_stroke(d, brushes, path, rule, st);
// Members of a group or layer that `expand_pieces` expanded, by id, with what their expansion lists.
let mut members = std::collections::HashMap::new();
// New ids of the copies of objects `skip` lists among those members.
let mut kept = vec![];
let expanded = match image {
// Blur, feather and inner glow change the object itself: it becomes the image (a layer
// keeps it as its only member).
@@ -1344,7 +1417,7 @@ fn expanded_node(
} else if container {
// A group's or layer's own fills and strokes become art among its members.
effects::evaluate_container(Some(&*d), &v).map(|mut m| {
members = expand_pieces(d, &mut m, false, brushes, skip, &mut kept, &mut stroke_art, raster);
members.extend(expand_pieces(d, &mut m, false, brushes, skip, &mut kept, &mut stroke_art, raster));
m
})
} else if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })
+39
View File
@@ -1150,3 +1150,42 @@ fn an_image_past_the_pixels_left_stays_unmade() {
let mut budget = super::RasterBudget { images: 0, pixels, left: 0 };
assert!(super::raster_image(&mut d, &n, &mut budget).is_err(), "no image is left");
}
/// A group whose Transform effect's copies each carry the drop shadow listed before it, with a
/// symbol instance whose random Transform effect takes its seed from the instance's id, stays as it
/// is when the raster budget has no image left for a copy's shadow, with none left or with one for
/// the first copy's: the copies keep the ids their random moves are drawn with, the group draws as
/// before, and the document holds no image the first copy's expansion made, nor the budget its
/// charge.
#[test]
fn copies_the_raster_budget_leaves_keep_their_random_moves() {
let (mut s, id) = session_with_rect();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
let id = NodeId(s.execute("symbol.new", &json!({"name": "Box"})).unwrap()["id"].as_u64().unwrap());
let random = json!({"moveH": 40, "moveV": 40, "random": true});
s.execute("effect.apply", &json!({"ids": [id.0], "effect": "distort.transform", "params": random})).unwrap();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
let shadow = json!({"x": 10, "y": 0, "blur": 0, "opacity": 100, "mode": "normal", "color": "#00ff00"});
s.execute("effect.apply", &json!({"ids": [g.0], "effect": "stylize.dropShadow", "params": shadow})).unwrap();
s.execute("effect.apply", &json!({"ids": [g.0], "effect": "distort.transform", "params": {"moveV": 150, "copies": 1}})).unwrap();
let draw = |d: &vectorcraft_doc::Document| {
vectorcraft_render::Renderer::new().render(d, 400, 400, vectorcraft_geom::Affine::IDENTITY, &Default::default()).pixels
};
for images in [0, 1] {
let mut d = s.doc().unwrap().doc.as_ref().clone();
let before = d.node(g).cloned().unwrap();
assert!(effects::outer_effects(&before).len() < before.appearance.effects.len(), "each copy carries the shadow");
let (drawn, keys) = (draw(&d), d.images.keys().cloned().collect::<Vec<_>>());
let mut budget = super::RasterBudget { images, pixels: u64::MAX, left: 0 };
let mut out = vec![];
super::expand_node(&mut d, g, &[], &mut out, &mut budget);
assert!(budget.left > 0, "{images}: a copy's shadow is left");
assert!(out.is_empty(), "{images}: nothing expands: {out:?}");
assert_eq!(d.node(g), Some(&before), "{images}: the group stays as it is");
assert!(draw(&d) == drawn, "{images}: the group draws as before");
assert_eq!(d.images.keys().cloned().collect::<Vec<_>>(), keys, "{images}: no image is added");
assert_eq!((budget.images, budget.pixels), (images, u64::MAX), "{images}: the budget gets back what the copies took");
}
}
-1
View File
@@ -4,7 +4,6 @@
//! native document can't be read opens as its embedded preview instead, with a warning that says
//! why, and can't be placed.
use std::io::Cursor;
use std::sync::Arc;
use kurbo::{Affine, BezPath, Point, Rect, Vec2};
@@ -1,4 +1,4 @@
use super::{Builder, Cursor, Document, Result, err, raster_doc};
use super::{Builder, Document, Result, err, raster_doc};
/// What an Affinity file opened as.
pub(in super::super) struct Imported {
@@ -30,13 +30,11 @@ fn preview(name: &str, bytes: &[u8], native: &vectorcraft_affinity::Error) -> Re
let p = vectorcraft_affinity::preview(bytes).map_err(|e| err(format!("{native}; its embedded preview can't be read either ({e})")))?;
// `raster_doc` normally probes PNG dimensions and keeps its encoded bytes. Verify this
// untrusted preview's complete pixels first, so corrupt data cannot create a blank image.
let mut reader = image::ImageReader::with_format(Cursor::new(p.png), image::ImageFormat::Png);
let mut limits = image::Limits::default();
limits.max_image_width = Some(4096);
limits.max_image_height = Some(4096);
limits.max_alloc = Some(128 << 20);
reader.limits(limits);
let _pixels = reader.decode().map_err(err)?;
let mut opts = craft_image_codecs::DecodeOptions::default();
opts.limits.max_width = 4096;
opts.limits.max_height = 4096;
opts.limits.max_alloc = 128 << 20;
let _pixels = craft_image_codecs::decode_as_with(craft_image_codecs::Format::Png, p.png, &opts).map_err(err)?;
let d = raster_doc(name, p.png)?;
Ok((
d,
@@ -1,5 +1,5 @@
use super::nodes::MAX_DEPTH;
use super::{AfAlign, CharStyle, Cursor, Justify, Kind, Rect, TextKind, TextObject, VerticalAlign, af, shapes};
use super::{AfAlign, CharStyle, Justify, Kind, Rect, TextKind, TextObject, VerticalAlign, af, shapes};
/// The master page instances among `nodes` (also inside layers and groups): (master, first page,
/// first master page, page count).
@@ -131,10 +131,9 @@ pub(super) fn fit_lines(obj: &mut TextObject, w: f64, h: f64) -> bool {
/// RGBA pixels as a PNG file.
pub(super) fn png(width: u32, height: u32, rgba: Vec<u8>) -> Option<Vec<u8>> {
let buf = image::RgbaImage::from_raw(width, height, rgba)?;
let mut png = Vec::new();
buf.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).ok()?;
Some(png)
let raw =
craft_image_codecs::Image::from_raw(width, height, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, rgba).ok()?;
craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()
}
/// Where a line of `w` starts in a span from 0 to `room` (as a share of `room - w`).
+1 -1
View File
@@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export for Screens",
["File", "Export"],
None,
"{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboard?: index | artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N; a row whose file would take a name another row's file has, in any case, gets -2, -3… too, and identical rows write one file; row folders that differ only in case are one folder, spelled as the first row spells it) → {files: [path…]} (into the folder of exportPreset, outside the automation read roots: no ZIP path, and files relative to that folder); no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step). A key it doesn't take, a key no format takes in a format row or in settings, settings for a format it doesn't write, and an unknown key inside a PDF, EPS or SVG option's object, are refused; a key only another format takes in a row or in settings is not used, and warnings name it as given (formats[0].quality; a key in settings only when no row of that format reads it; not a key of an exportPreset). Under automation read roots, an svg or svgz row, and a row whose files carry the native document (vectorcraft, eps, ai but a version 7 file, a pdf with preserveEditing on that holds every artboard of the document it is written from), is refused, before the folder is made or any file is written, while the document links a JavaScript file outside them, or while the row's file would name a linked image's file outside them, as document.export refuses it",
"{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboard?: index | artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document; refused with assets, layers or selection: each), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N; a row whose file would take a name another row's file has, in any case, gets -2, -3… too, and identical rows write one file; row folders that differ only in case are one folder, spelled as the first row spells it) → {files: [path…]} (into the folder of exportPreset, outside the automation read roots: no ZIP path, and files relative to that folder); no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step). A key it doesn't take, a key no format takes in a format row or in settings, settings for a format it doesn't write, and an unknown key inside a PDF, EPS or SVG option's object, are refused; a key only another format takes in a row or in settings is not used, and warnings name it as given (formats[0].quality; a key in settings only when no row of that format reads it; not a key of an exportPreset). Under automation read roots, an svg or svgz row, and a row whose files carry the native document (vectorcraft, eps, ai but a version 7 file, a pdf with preserveEditing on that holds every artboard of the document it is written from), is refused, before the folder is made or any file is written, while the document links a JavaScript file outside them, or while the row's file would name a linked image's file outside them, as document.export refuses it",
has_doc,
screens::export_for_screens
),
+44 -227
View File
@@ -1,7 +1,7 @@
//! JPEG 2000 JP2 and codestream images for File › Open and File › Place. The decoded image is
//! bounded before allocation and converted to RGBA for the common PNG storage path.
use hayro_jpeg2000::{ColorSpace, DecodeSettings, DecoderContext, Image};
use craft_image_codecs::{ChannelLayout, CodecError, Format, Limits};
use vectorcraft_color::cms::{IccProfile, Intent};
/// Recognize a JP2 signature box or the start of a raw codestream. The decoder checks the rest.
@@ -31,249 +31,66 @@ pub(super) fn boxes(b: &[u8]) -> impl Iterator<Item = (&[u8], &[u8])> {
})
}
/// The decoder ignores JPX layers and composition and silently uses the last top-level jp2c.
fn unsupported_jpx_content(bytes: &[u8]) -> bool {
fn association_has_content(data: &[u8], depth: usize) -> bool {
if depth >= 16 {
return true;
}
boxes(data).any(|(ty, child)| {
matches!(ty, b"jp2c" | b"jpch" | b"jplh" | b"comp" | b"ftbl") || (ty == b"asoc" && association_has_content(child, depth + 1))
})
}
let mut codestreams = 0u8;
for (ty, data) in boxes(bytes) {
match ty {
b"jp2c" => {
codestreams = codestreams.saturating_add(1);
if codestreams > 1 {
return true;
}
}
b"jpch" | b"jplh" | b"comp" | b"ftbl" => return true,
b"asoc" if association_has_content(data, 0) => return true,
_ => {}
}
}
false
}
/// The largest embedded ICC profile read.
const MAX_PROFILE: usize = 4 * 1024 * 1024;
/// A codestream numbers its tiles 0 to 65,534 (Isot in SOT, ITU-T T.800 A.4.2).
const MAX_TILES: u64 = 65_535;
/// Bytes the decoder keeps for each component of each tile before decoding any of them.
const TILE_COMPONENT_BYTES: u64 = 256;
/// SIZ follows SOC in the codestream; Lsiz includes its two length bytes. Returns the component
/// count, the image size and the tile count.
fn codestream_size(bytes: &[u8]) -> Option<(u64, u32, u32, u64)> {
let stream = if bytes.starts_with(b"\xff\x4f") { bytes } else { boxes(bytes).find_map(|(ty, data)| (ty == b"jp2c").then_some(data))? };
if stream.get(..4)? != b"\xff\x4f\xff\x51" {
return None;
}
let length = u16::from_be_bytes(stream.get(4..6)?.try_into().ok()?) as usize;
let count = u16::from_be_bytes(stream.get(40..42)?.try_into().ok()?) as usize;
if count == 0 || length != 38usize.checked_add(count.checked_mul(3)?)? || stream.get(4..4usize.checked_add(length)?)?.len() != length {
return None;
}
let be32 = |range: std::ops::Range<usize>| stream.get(range).and_then(|v| v.try_into().ok()).map(u32::from_be_bytes);
let width = be32(8..12)?.checked_sub(be32(16..20)?)?;
let height = be32(12..16)?.checked_sub(be32(20..24)?)?;
// Tiles across and down (T.800 B-5): the grid from the tile offset, in whole tiles.
let tiles = |grid: u32, offset: u32, tile: u32| match (grid.checked_sub(offset), tile) {
(Some(span), 1..) => Some(u64::from(span).div_ceil(u64::from(tile))),
_ => None,
};
let across = tiles(be32(8..12)?, be32(32..36)?, be32(24..28)?)?;
let down = tiles(be32(12..16)?, be32(36..40)?, be32(28..32)?)?;
Some((count as u64, width, height, across.checked_mul(down)?))
}
/// One `jp2h` header with at most one palette, component mapping and channel definition box, so
/// the checks below read the boxes the decoder uses.
fn single_header_boxes(bytes: &[u8]) -> bool {
let mut headers = boxes(bytes).filter(|(ty, _)| *ty == b"jp2h");
let (Some((_, header)), None) = (headers.next(), headers.next()) else {
return false;
};
[b"pclr", b"cmap", b"cdef"].iter().all(|kind| boxes(header).filter(|(ty, _)| ty == kind).count() <= 1)
}
/// The number of channel definitions in a JP2 `cdef` box, `None` without one. Only color channels
/// 1 to n, in any order, followed by at most one opacity channel for the whole image are read;
/// any other layout (premultiplied opacity, opacity before a color, an unassociated channel) gives
/// `Some(0)`, which no image matches.
fn channel_definitions(bytes: &[u8]) -> Option<u64> {
if bytes.starts_with(b"\xff\x4f") {
return None;
}
let header = boxes(bytes).find_map(|(ty, data)| (ty == b"jp2h").then_some(data))?;
let cdef = boxes(header).find_map(|(ty, data)| (ty == b"cdef").then_some(data))?;
let count = cdef.get(..2).and_then(|n| n.try_into().ok()).map_or(0, |n: [u8; 2]| usize::from(u16::from_be_bytes(n)));
let Some(entries) = cdef.get(2..).filter(|rest| count > 0 && rest.len() == count * 6) else {
return Some(0);
};
// (channel, type, association) by channel.
let mut defs: Vec<[u16; 3]> =
entries.as_chunks::<6>().0.iter().map(|&[a, b, c, d, e, f]| [[a, b], [c, d], [e, f]].map(u16::from_be_bytes)).collect();
defs.sort_unstable();
let opacity = defs.last().is_some_and(|&[_, kind, association]| kind == 1 && association == 0);
let colors = defs.len() - usize::from(opacity);
let mut seen = vec![false; colors];
let layout_ok = defs.iter().enumerate().all(|(i, &[channel, kind, association])| {
usize::from(channel) == i
&& (i >= colors
|| (kind == 0
&& usize::from(association).checked_sub(1).and_then(|slot| seen.get_mut(slot)).is_some_and(|s| !std::mem::replace(s, true))))
});
Some(if layout_ok { defs.len() as u64 } else { 0 })
}
/// The column count of a JP2 palette (`pclr`), `Ok(None)` without one. A component mapping (`cmap`)
/// beside it needs one entry per column, each naming a codestream component and, when it maps
/// through the palette, a palette column; anything else is `Err`.
fn palette_columns(bytes: &[u8], components: u64) -> Result<Option<u64>, ()> {
if bytes.starts_with(b"\xff\x4f") {
return Ok(None);
}
let Some(header) = boxes(bytes).find_map(|(ty, data)| (ty == b"jp2h").then_some(data)) else {
return Ok(None);
};
let Some(palette) = boxes(header).find_map(|(ty, data)| (ty == b"pclr").then_some(data)) else {
return Ok(None);
};
let columns = palette.get(2).copied().ok_or(())?;
// Each column's descriptor: unsigned, 1 to 31 bits, as codestream samples are.
let depths = palette.get(3..3 + usize::from(columns)).ok_or(())?;
if columns == 0 || depths.iter().any(|&d| d & 0x80 != 0 || (d & 0x7f) + 1 > 31) {
return Err(());
}
// Without a mapping the decoder maps every column from the first component.
let Some(mapping) = boxes(header).find_map(|(ty, data)| (ty == b"cmap").then_some(data)) else {
return Ok(Some(u64::from(columns)));
};
if mapping.len() != usize::from(columns) * 4 {
return Err(());
}
for &[c0, c1, kind, column] in mapping.as_chunks::<4>().0 {
let valid = u64::from(u16::from_be_bytes([c0, c1])) < components
&& match kind {
0 => true,
1 => column < columns,
_ => false,
};
if !valid {
return Err(());
}
}
Ok(Some(u64::from(columns)))
}
/// Decode within the raster allocation allowance, counting source samples, RGBA output, and
/// decoder intermediates. The decoder may need multiple full-sized component planes.
/// Decode `bytes` to RGBA, checking memory limits and converting embedded ICC/CMYK color spaces
/// to sRGB via `vectorcraft_color`.
pub(super) fn decode(bytes: &[u8], max_alloc: u64) -> Result<image::RgbaImage, String> {
if bytes.starts_with(b"\0\0\0\x0cjP \r\n\x87\n") && unsupported_jpx_content(bytes) {
return Err("the JPEG 2000 file has an unsupported color space or JPX content".into());
}
if bytes.starts_with(b"\0\0\0\x0cjP \r\n\x87\n") && !single_header_boxes(bytes) {
if !is_jpeg2000(bytes) {
return Err("the JPEG 2000 file can't be read".into());
}
let (codestream_channels, declared_w, declared_h, tile_count) = codestream_size(bytes).ok_or("the JPEG 2000 file can't be read")?;
if tile_count == 0 || tile_count > MAX_TILES {
return Err("the JPEG 2000 file can't be read".into());
}
let declared_pixels = u64::from(declared_w).checked_mul(u64::from(declared_h));
if declared_w == 0
|| declared_h == 0
|| declared_pixels.and_then(|n| n.checked_mul(codestream_channels)).and_then(|n| n.checked_mul(4)).is_none_or(|n| n > max_alloc)
|| tile_count.checked_mul(codestream_channels).and_then(|n| n.checked_mul(TILE_COMPONENT_BYTES)).is_none_or(|n| n > max_alloc)
{
return Err(format!("an image of {declared_w} × {declared_h} pixels is too large to draw"));
}
// The decoder copies an embedded profile (after a 3-byte `colr` header) when it reads the file.
let header = boxes(bytes).find_map(|(ty, data)| (ty == b"jp2h").then_some(data)).unwrap_or_default();
if boxes(header).any(|(ty, data)| ty == b"colr" && data.len() > MAX_PROFILE + 3) {
return Err("the JPEG 2000 file has an unsupported color space or JPX content".into());
}
let palette = palette_columns(bytes, codestream_channels).map_err(|()| "the JPEG 2000 file can't be read")?;
// The decoder keeps each palette value in 8 bytes and each row in its own list.
let palette_rows = boxes(header).find_map(|(ty, data)| (ty == b"pclr").then(|| data.get(..2)).flatten());
if let (Some(columns), Some(&[r0, r1])) = (palette, palette_rows)
&& u64::from(u16::from_be_bytes([r0, r1])) * (columns * 8 + 24) > max_alloc
{
return Err(format!("an image of {declared_w} × {declared_h} pixels is too large to draw"));
}
let image = Image::new(bytes, &DecodeSettings::default()).map_err(|_| "the JPEG 2000 file can't be read")?;
let limits = Limits { max_alloc, max_pixels: max_alloc / 4, ..Limits::default() };
let opts = craft_image_codecs::DecodeOptions { limits, ..craft_image_codecs::DecodeOptions::default() };
let image = craft_image_codecs::decode_as_with(Format::Jp2, bytes, &opts).map_err(|e| match e {
CodecError::LimitExceeded(_) => "an image is too large to draw".to_string(),
CodecError::Unsupported { .. } => "the JPEG 2000 file has an unsupported color space or JPX content".to_string(),
_ => "the JPEG 2000 file can't be read".to_string(),
})?;
let (w, h) = (image.width(), image.height());
let color = image.color_space();
let channels = match color {
ColorSpace::Gray => 1,
ColorSpace::RGB => 3,
ColorSpace::CMYK => 4,
ColorSpace::Icc { num_channels: 1 | 3 | 4, profile } if profile.len() <= MAX_PROFILE => color.num_channels(),
_ => return Err("the JPEG 2000 file has an unsupported color space or JPX content".into()),
};
let stride = u64::from(channels) + u64::from(image.has_alpha());
// The decoder sizes its output by the palette's columns and writes one channel per mapping
// entry, so the columns, the entries and the output channels must all match.
if palette.is_some_and(|columns| columns != stride) {
return Err("the JPEG 2000 file can't be read".into());
}
// The decoder reorders the channels by their definitions (`cdef`) and drops any channel without
// one, so a definition is needed for every channel it writes.
if channel_definitions(bytes).is_some_and(|count| count != stride || count != palette.unwrap_or(codestream_channels)) {
return Err("the JPEG 2000 file can't be read".into());
}
let plane_channels = codestream_channels.max(stride).max(palette.unwrap_or(0));
let too_large = || format!("an image of {w} × {h} pixels is too large to draw");
let pixels = u64::from(w).checked_mul(u64::from(h)).ok_or_else(too_large)?;
let size = pixels.checked_mul(stride).ok_or_else(too_large)?;
let rgba_size = pixels.checked_mul(4).ok_or_else(too_large)?;
// hayro 0.3.5 keeps a f32 plane per component, including alpha, and a second
// f32 coefficient plane per component. Palette mapping or channel definitions
// can temporarily clone the component planes. Reserve another 8 bytes per
// pixel for IDWT and code-block scratch while samples and RGBA coexist.
let plane_bytes = pixels.checked_mul(plane_channels).and_then(|n| n.checked_mul(4)).ok_or_else(too_large)?;
let scratch_bytes = plane_bytes.checked_mul(2).and_then(|n| n.checked_add(pixels.checked_mul(8)?)).ok_or_else(too_large)?;
let working =
size.checked_add(rgba_size).and_then(|n| n.checked_add(plane_bytes)).and_then(|n| n.checked_add(scratch_bytes)).ok_or_else(too_large)?;
if w == 0 || h == 0 || working > max_alloc {
if rgba_size > max_alloc {
return Err(too_large());
}
let len = usize::try_from(size).map_err(|_| too_large())?;
let mut samples = vec![0; len];
image.decode_into(&mut samples, &mut DecoderContext::default()).map_err(|_| "the JPEG 2000 file can't be read")?;
let profile = match color {
ColorSpace::Icc { profile, .. } => {
Some(IccProfile::from_bytes(None, profile).map_err(|_| "the JPEG 2000 file has an unsupported color space or JPX content")?)
}
_ => None,
let layout = image.layout();
let (channels, has_alpha) = match layout {
ChannelLayout::Gray => (1usize, false),
ChannelLayout::GrayA => (1, true),
ChannelLayout::Rgb => (3, false),
ChannelLayout::Rgba => (3, true),
ChannelLayout::Cmyk => (4, false),
ChannelLayout::CmykA => (4, true),
_ => return Err("the JPEG 2000 file has an unsupported color space or JPX content".into()),
};
let stride = channels + usize::from(has_alpha);
let profile = match image.icc.as_deref() {
Some(icc) => Some(IccProfile::from_bytes(None, icc).map_err(|_| "the JPEG 2000 file has an unsupported color space or JPX content")?),
None => None,
};
let cms = vectorcraft_color::cms::active();
let mut rgba = Vec::with_capacity(usize::try_from(rgba_size).map_err(|_| too_large())?);
for sample in samples.chunks_exact(stride as usize) {
for sample in image.data().chunks_exact(stride) {
let at = |i: usize| sample.get(i).copied().unwrap_or(0);
let rgb = match (color, profile.as_ref()) {
(ColorSpace::Gray, _) => [at(0); 3],
(ColorSpace::RGB, _) => [at(0), at(1), at(2)],
(ColorSpace::CMYK, _) => {
cms.cmyk_to_srgb([at(0), at(1), at(2), at(3)].map(|v| f32::from(v) / 255.0), false).map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8)
let rgb = if let Some(profile) = profile.as_ref() {
let mut values = [0.0f32; 4];
for (dst, src) in values.iter_mut().zip(sample.iter().take(channels)) {
*dst = f32::from(*src) / 255.0;
}
(ColorSpace::Icc { .. }, Some(profile)) => {
let mut values = [0.0f32; 4];
for (dst, src) in values.iter_mut().zip(sample.iter().take(usize::from(channels))) {
*dst = f32::from(*src) / 255.0;
}
profile
.to_srgb_into(&values[..usize::from(channels)], Intent::RelativeColorimetric)
.ok_or("the JPEG 2000 file has an unsupported color space or JPX content")?
.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8)
profile
.to_srgb_into(&values[..channels], Intent::RelativeColorimetric)
.ok_or("the JPEG 2000 file has an unsupported color space or JPX content")?
.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8)
} else {
match layout {
ChannelLayout::Gray | ChannelLayout::GrayA => [at(0); 3],
ChannelLayout::Rgb | ChannelLayout::Rgba => [at(0), at(1), at(2)],
ChannelLayout::Cmyk | ChannelLayout::CmykA => cms
.cmyk_to_srgb([at(0), at(1), at(2), at(3)].map(|v| f32::from(v) / 255.0), false)
.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8),
_ => return Err("the JPEG 2000 file has an unsupported color space or JPX content".into()),
}
_ => return Err("the JPEG 2000 file has an unsupported color space or JPX content".into()),
};
let [r, g, b] = rgb;
rgba.extend_from_slice(&[r, g, b, if image.has_alpha() { at(usize::from(channels)) } else { 255 }]);
rgba.extend_from_slice(&[r, g, b, if has_alpha { at(channels) } else { 255 }]);
}
image::RgbaImage::from_raw(w, h, rgba).ok_or_else(|| "the JPEG 2000 file can't be read".into())
}
+53 -47
View File
@@ -1,7 +1,5 @@
//! `document.open`: every readable format into a new document.
use std::io::Cursor;
use serde_json::{Value, json};
use vectorcraft_doc::{Document, ImageBlob, ImageObject, Node, NodeKind};
use vectorcraft_geom::Affine;
@@ -133,7 +131,7 @@ pub fn detect(name: &str, bytes: &[u8]) -> Option<&'static Format> {
if super::heifread::is_heif(bytes) {
return format("heif");
}
if let Some(f) = image::guess_format(bytes).ok().and_then(image_format) {
if let Some(f) = craft_image_codecs::detect(bytes).and_then(image_format) {
return Some(f);
}
// A version 2 PICT is known by its version opcodes after the picture's frame, at byte 522 of a
@@ -159,9 +157,17 @@ pub fn detect(name: &str, bytes: &[u8]) -> Option<&'static Format> {
by_name
}
/// The readable raster format behind an `image` crate format.
fn image_format(f: image::ImageFormat) -> Option<&'static Format> {
f.extensions_str().iter().find_map(|e| format(e)).filter(|f| f.read && f.raster)
/// The readable raster format behind a craft-image-codecs format.
fn image_format(f: craft_image_codecs::Format) -> Option<&'static Format> {
f.extensions().iter().find_map(|e| format(e)).filter(|f| f.read && f.raster)
}
/// The image's size and the bytes a pixel of it takes decoded, from its header
/// ([`vectorcraft_doc::decode::decoded_layout`]), for bytes in a format craft-image-codecs tells.
fn header_layout(bytes: &[u8]) -> Option<(craft_image_codecs::Format, u32, u32, u64)> {
let format = craft_image_codecs::detect(bytes)?;
let (w, h, per_pixel) = vectorcraft_doc::decode::decoded_layout(bytes, format)?;
Some((format, w, h, per_pixel))
}
/// Why a file carrying editing data (an SVG or PDF saved with Preserve Editing) opened as plain
@@ -280,16 +286,24 @@ fn editing_copy(opened: &vectorcraft_pdf::Opened, opts: &LoadOptions) -> Option<
/// A `.ai`, or a PDF saved with the editing data, whose PDF part can't be read (`e`, the import's
/// error) from the editor's own copy of its art alone, as a file saved without PDF compatibility
/// is read, its first note saying why: `None` when pages are picked, layers or the editing data
/// are off, or the file has no editing data that reads. Its type is outlines when `opts` asks.
fn without_pdf_part(bytes: &[u8], opts: &LoadOptions, e: &EngineError) -> Option<(Document, Vec<String>)> {
/// is read, its first note saying why. Else `e`: as it is when pages are picked, layers or the
/// editing data are off, or the file has no editing data, and followed by why when the file has
/// editing data that can't be read. Its type is outlines when `opts` asks.
fn without_pdf_part(bytes: &[u8], opts: &LoadOptions, e: EngineError) -> Result<(Document, Vec<String>)> {
if opts.pages.is_some() || !opts.layers || !opts.editing_data {
return None;
return Err(e);
}
let read = vectorcraft_pdf::read_illustrator_data_without_pdf_part(bytes, opts.password.as_deref())
.and_then(|private| private.map(|p| vectorcraft_eps::ai_alone_on_page(&p.data, p.trim, p.user_unit, opts.legacy_names)).transpose());
match read {
Ok(Some((doc, warnings))) => {
let notes =
std::iter::once(format!("the PDF part couldn't be read ({e}): the file opened from its editing data")).chain(warnings).collect();
Ok(outlined_if_asked(doc, notes, opts))
}
Ok(None) => Err(e),
Err(why) => Err(err(format!("{e}; its editing data couldn't be read either ({why})"))),
}
let private = vectorcraft_pdf::illustrator_data_without_pdf_part(bytes, opts.password.as_deref())?;
let (doc, warnings) = vectorcraft_eps::ai_alone_on_page(&private.data, private.trim, private.user_unit, opts.legacy_names).ok()?;
let notes = std::iter::once(format!("the PDF part couldn't be read ({e}): the file opened from its editing data")).chain(warnings).collect();
Some(outlined_if_asked(doc, notes, opts))
}
/// Is `w` a note on the PDF part as a page, which says nothing was skipped: that the art off the
@@ -491,7 +505,7 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
.inspect(|_| editing_data = true),
// A PDF part that can't be read (a stream the import refuses): the editing copy
// alone where it reads, else the error.
Err(e) => without_pdf_part(bytes, opts, &e).inspect(|_| editing_data = true).ok_or(e),
Err(e) => without_pdf_part(bytes, opts, e).inspect(|_| editing_data = true),
}
})?;
// The File Info of a file read from its pages or its editing copy.
@@ -892,22 +906,18 @@ pub(crate) use vectorcraft_doc::MAX_RASTER_ALLOC;
/// says so; the pixels aren't read): Open, Place and the Links panel say it ([`size_note`], #1479).
/// `None` for images within the allowance, and for bytes that aren't an image.
pub(crate) fn too_large_note(bytes: &[u8]) -> Option<String> {
use image::ImageDecoder as _;
if let Some((w, h)) = vectorcraft_doc::cmyk::oversized_tiff(bytes) {
return Some(format!("an image of {w} × {h} pixels is too large to draw"));
}
let reader = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?;
let format = reader.format()?;
let d = reader.into_decoder().ok()?;
let (w, h) = d.dimensions();
let (format, w, h, per_pixel) = header_layout(bytes)?;
// The allowance also counts the pixels as RGBA: an image of fewer than 4 bytes a pixel (gray,
// gray with alpha, RGB) takes more than the decoder counts (#1717).
let rgba_over = u64::from(w) * u64::from(h) > MAX_RASTER_ALLOC / 4;
let samples_over = d.total_bytes() > MAX_RASTER_ALLOC;
let samples_over = (u64::from(w) * u64::from(h)).saturating_mul(per_pixel) > MAX_RASTER_ALLOC;
// The renderer can stream a non-interlaced PNG a row at a time when those buffers fit. Its
// full decoded byte count can exceed the allowance even though drawing it at native size is
// safe; use the renderer's decision for that case instead of warning from total_bytes alone.
let png_streams_at_size = samples_over && format == image::ImageFormat::Png && vectorcraft_render::reduced_size(bytes) == Some((w, h));
let png_streams_at_size = samples_over && format == craft_image_codecs::Format::Png && vectorcraft_render::reduced_size(bytes) == Some((w, h));
(rgba_over || (samples_over && !png_streams_at_size)).then(|| format!("an image of {w} × {h} pixels is too large to draw"))
}
@@ -918,7 +928,7 @@ pub(crate) fn too_large_note(bytes: &[u8]) -> Option<String> {
pub(crate) fn size_note(bytes: &[u8]) -> Option<String> {
let note = too_large_note(bytes)?;
let Some(drawn) = vectorcraft_render::reduced_size(bytes) else { return Some(note) };
let (w, h) = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?.into_dimensions().ok()?;
let (w, h) = vectorcraft_doc::header_size(bytes)?;
(drawn != (w, h)).then(|| format!("an image of {w} × {h} pixels is shown at reduced size"))
}
@@ -978,17 +988,14 @@ pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> {
if super::pxrread::is_pxr(bytes) {
return as_png(super::pxrread::decode(bytes, MAX_RASTER_ALLOC).map_err(err)?, None, ppi);
}
let mut reader = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().map_err(err)?;
if reader.format().is_none() && super::tgaread::is_targa(bytes) {
reader.set_format(image::ImageFormat::Tga);
let mut detected = craft_image_codecs::detect(bytes);
if detected.is_none() && super::tgaread::is_targa(bytes) {
detected = Some(craft_image_codecs::Format::Tga);
}
if reader.format().is_none() && super::pcxread::is_pcx(bytes) {
if (detected.is_none() || detected == Some(craft_image_codecs::Format::Pcx)) && super::pcxread::is_pcx(bytes) {
return as_png(super::pcxread::decode(bytes, MAX_RASTER_ALLOC).map_err(err)?, None, ppi);
}
let mut limits = image::Limits::default();
limits.max_alloc = Some(MAX_RASTER_ALLOC);
reader.limits(limits);
let kind = reader.format().ok_or_else(|| err("not an image VectorCraft reads (see document.formats)"))?;
let kind = detected.ok_or_else(|| err("not an image VectorCraft reads (see document.formats)"))?;
let f = image_format(kind).ok_or_else(|| err(format!("{kind:?} images can't be opened (see document.formats)")))?;
// A photo whose EXIF orientation turns or flips it (a camera held upright) is stored as it is
// seen, so it places the way it was taken (#4284); the others keep their own bytes.
@@ -1009,8 +1016,8 @@ pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> {
_ => None,
};
if let Some(kept) = kept {
let (width, height) = reader.into_dimensions().map_err(err)?;
return stored(kept, f.mime, (width, height), ppi);
let size = vectorcraft_doc::header_size(bytes).ok_or_else(|| err("the image's size can't be read"))?;
return stored(kept, f.mime, size, ppi);
}
let extra_samples = || {
let cms = vectorcraft_color::cms::active();
@@ -1023,21 +1030,23 @@ pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> {
None => match (f.id == "tiff").then(|| vectorcraft_doc::cmyk::group3_tiff_rgba(bytes)).flatten() {
Some(read) => image::DynamicImage::ImageRgba8(read.map_err(err)?),
None => {
use image::ImageDecoder as _;
let mut decoder = reader.into_decoder().map_err(err)?;
// The allowance counts the decoded samples and the RGBA pixels they become (#1717).
let (w, h) = decoder.dimensions();
if decoder.total_bytes() > MAX_RASTER_ALLOC || u64::from(w) * u64::from(h) * 4 > MAX_RASTER_ALLOC {
// A Targa file's size is read from its header, which no signature points a probe at.
let tga = || (kind == craft_image_codecs::Format::Tga).then(|| super::tgaread::size(bytes)).flatten().map(|(w, h)| (w, h, 4));
let (w, h, per_pixel) =
vectorcraft_doc::decode::decoded_layout(bytes, kind).or_else(tga).ok_or_else(|| err("the image's size can't be read"))?;
let pixels = u64::from(w) * u64::from(h);
if pixels.saturating_mul(per_pixel) > MAX_RASTER_ALLOC || pixels * 4 > MAX_RASTER_ALLOC {
return Err(err(format!("an image of {w} × {h} pixels is too large to draw")));
}
// A profile the decoder can't read leaves the image without one. The image decoder
// reads a TIFF's tags within the size of its pixels, so a small TIFF's profile is
// read by the TIFF decoder itself.
let (img, profile) = vectorcraft_doc::decode::decode_image(kind, bytes, MAX_RASTER_ALLOC).map_err(err)?;
// A profile the decoder can't read leaves the image without one. A TIFF's profile is
// read by the TIFF reader, as before.
icc = match f.id {
"tiff" => vectorcraft_doc::cmyk::tiff_icc_profile(bytes),
_ => decoder.icc_profile().ok().flatten(),
_ => profile,
};
image::DynamicImage::from_decoder(decoder).map_err(err)?
img
}
},
};
@@ -1109,11 +1118,8 @@ pub fn texture_image(bytes: &[u8]) -> Result<String> {
LoadedTexture::from_rgba(inks.width, inks.height, &rgba)
}
None => {
let mut reader = image::ImageReader::new(Cursor::new(blob.bytes.as_slice())).with_guessed_format().map_err(err)?;
let mut limits = image::Limits::default();
limits.max_alloc = Some(MAX_RASTER_ALLOC);
reader.limits(limits);
let img = reader.decode().map_err(err)?.to_rgba8();
let kind = craft_image_codecs::detect(&blob.bytes).ok_or_else(|| err("the image can't be read as a texture"))?;
let img = vectorcraft_doc::decode::decode_image(kind, &blob.bytes, MAX_RASTER_ALLOC).map_err(err)?.0.to_rgba8();
LoadedTexture::from_rgba(img.width(), img.height(), img.as_raw())
}
};
+17 -1
View File
@@ -39,7 +39,23 @@ mod tests {
let out = with_text(png.clone(), &[("Title", "Café".into()), ("Author", "Łukasz".into()), ("bad\u{1}", "x".into())]);
assert_eq!(text(&out), [("Title".to_string(), "Café".to_string()), ("Author".into(), "Łukasz".into())]);
// Still a PNG every decoder reads (the CRCs check out).
let img = image::load_from_memory(&out).unwrap();
let img = craft_image_codecs::decode(&out)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap();
assert_eq!((img.width(), img.height()), (2, 1));
assert_eq!(with_text(b"not a png".to_vec(), &[("Title", "x".into())]), b"not a png");
assert_eq!(with_text(png.clone(), &[]), png);
+122 -4
View File
@@ -114,7 +114,41 @@ mod tests {
fn png_of(w: u32, h: u32) -> Vec<u8> {
let mut out = Vec::new();
image::RgbaImage::new(w, h).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap();
{
let __dyn: image::DynamicImage = (image::RgbaImage::new(w, h)).into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| out.extend_from_slice(&__b))
}
.unwrap();
out
}
@@ -131,14 +165,64 @@ mod tests {
let again = with_png_resolution(&tagged, (72.0, 72.0));
assert!(close(resolution(&again).unwrap(), (72.0, 72.0)), "replaced, not duplicated");
assert_eq!(again.len(), tagged.len());
let img = image::load_from_memory(&again).unwrap();
let img = craft_image_codecs::decode(&again)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap();
assert_eq!((img.width(), img.height()), (4, 3));
}
#[test]
fn jpeg_jfif_density_in_dpi_and_dpcm() {
let mut jpg = Vec::new();
image::RgbImage::new(2, 2).write_to(&mut std::io::Cursor::new(&mut jpg), image::ImageFormat::Jpeg).unwrap();
{
let __dyn: image::DynamicImage = (image::RgbImage::new(2, 2)).into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Jpeg, &craft_image_codecs::EncodeOptions::default())
.map(|__b| jpg.extend_from_slice(&__b))
}
.unwrap();
// The encoder writes JFIF with units 0 (aspect only).
assert_eq!(resolution(&jpg), None);
let jfif = jpg.windows(5).position(|w| w == b"JFIF\0").unwrap();
@@ -202,7 +286,41 @@ mod tests {
#[test]
fn bmp_pixels_per_metre() {
let mut bmp = Vec::new();
image::RgbImage::new(2, 2).write_to(&mut std::io::Cursor::new(&mut bmp), image::ImageFormat::Bmp).unwrap();
{
let __dyn: image::DynamicImage = (image::RgbImage::new(2, 2)).into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Bmp, &craft_image_codecs::EncodeOptions::default())
.map(|__b| bmp.extend_from_slice(&__b))
}
.unwrap();
bmp[38..42].copy_from_slice(&11811u32.to_le_bytes());
bmp[42..46].copy_from_slice(&11811u32.to_le_bytes());
assert!(close(resolution(&bmp).unwrap(), (300.0, 300.0)));
+9 -3
View File
@@ -350,8 +350,8 @@ struct ScreenParams {
/// Where files go: `none` (all in the folder), `rows` (the rows' sub-folders, as
/// `subfolders`), `format` (a folder per extension), `item`, or `itemFormat`.
folders: Option<String>,
/// Export PDFs As: `single` (the artboards a PDF row writes are the pages of one file) or
/// `multiple` (a file per artboard, the default).
/// Export PDFs As: `single` (the artboards a PDF row writes are the pages of one file; refused
/// with assets, layers or `selection: "each"`) or `multiple` (a file per artboard, the default).
pdfs: Option<String>,
}
@@ -399,12 +399,18 @@ impl ScreenParams {
if p.is_object() { Self::deserialize(p).map_err(|e| bad(C, e.to_string())) } else { Ok(Self::default()) }
}
/// An error when more than one of `assets`, `layers`, `selection` and `fullDocument` is given.
/// An error when more than one of `assets`, `layers`, `selection` and `fullDocument` is given,
/// and when `pdfs: "single"` is given with `assets`, `layers` or `selection: "each"`, whose
/// files each hold the art of one item.
fn one_source(&self) -> Result<()> {
let sources = [self.full_document, self.assets.is_some(), self.layers.is_some(), self.selection.is_some()].iter().filter(|b| **b).count();
if sources > 1 {
return Err(bad(C, "give one of assets, layers, selection or fullDocument"));
}
let per_piece = self.assets.is_some() || self.layers.is_some() || self.selection.as_deref() == Some("each");
if per_piece && self.pdfs.as_deref() == Some("single") {
return Err(bad(C, "pdfs `single` writes artboards as the pages of one PDF: assets, layers and selection `each` write a PDF each"));
}
Ok(())
}
+35 -2
View File
@@ -4,12 +4,45 @@
use super::*;
use proptest::prelude::*;
use serde_json::json;
use std::io::Cursor;
fn png() -> Vec<u8> {
let im = image::RgbaImage::from_fn(2, 1, |x, _| if x == 0 { image::Rgba([220, 40, 60, 255]) } else { image::Rgba([0, 0, 0, 0]) });
let mut bytes = Vec::new();
im.write_to(&mut Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap();
{
let __dyn: image::DynamicImage = im.into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| bytes.extend_from_slice(&__b))
}
.unwrap();
bytes
}
+56 -4
View File
@@ -571,7 +571,24 @@ fn a_one_bit_rgb_image_opens_from_the_editing_data_in_its_colors() {
assert_eq!(names(&doc.layers), ["Art"], "{r}");
let mut found = vec![];
doc.visit_images(|_, im| {
let img = image::load_from_memory(&doc.images[&im.key].bytes).unwrap().to_rgb8();
let img = craft_image_codecs::decode(&doc.images[&im.key].bytes)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgb8();
found.push(img.pixels().map(|p| p.0).collect::<Vec<_>>());
});
assert_eq!(found, [[[255, 0, 0], [0, 255, 0], [0, 0, 255]]], "{r}");
@@ -589,7 +606,27 @@ fn a_zero_width_stroke_in_the_editing_data_draws_a_hairline() {
assert_eq!(names(&s.doc().unwrap().doc.layers), ["Art"], "{r}");
let v = s.execute("document.export", &json!({"format": "png", "background": "transparent"})).unwrap();
let png = vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap();
image::load_from_memory(&png).unwrap().to_rgba8().pixels().filter(|p| p.0[3] > 0).count()
craft_image_codecs::decode(&png)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8()
.pixels()
.filter(|p| p.0[3] > 0)
.count()
};
assert!(drawn("0 1 1 0 1 0 0 XA\n0 w\n20 20 m\n180 80 L\nS\n") > 0, "the hairline draws");
assert_eq!(drawn("0 1 1 0 1 0 0 XA\n0 w\n20 20 m\n180 80 L\nN\n"), 0, "the unstroked path draws nothing");
@@ -762,7 +799,7 @@ fn unread_pdf_part(e: &str) -> String {
/// #4366: a `.ai`, or a PDF saved with the editing data, whose PDF part can't be read opens from
/// its editing data, with a first note saying why. Pages picked, layers off or the editing data
/// off keep the error, and so does editing data that can't be read.
/// off keep the error. Editing data that can't be read keeps it too, followed by why.
#[test]
fn a_file_whose_pdf_part_cant_be_read_opens_from_its_editing_data() {
let mut s = Session::new();
@@ -780,10 +817,25 @@ fn a_file_whose_pdf_part_cant_be_read_opens_from_its_editing_data() {
}
for (name, file) in refused_files(b"%AI12_CompressedData not zlib", ai::page_pdf()) {
let plain = open(&mut s, name, &file, json!({"editingData": false})).unwrap_err().to_string();
assert_eq!(open(&mut s, name, &file, json!({})).unwrap_err().to_string(), plain, "{name}");
let both = format!("{plain}; its editing data couldn't be read either (its zlib compression is damaged)");
assert_eq!(open(&mut s, name, &file, json!({})).unwrap_err().to_string(), both, "{name}");
for p in [json!({"pages": "1"}), json!({"layers": false})] {
assert_eq!(open(&mut s, name, &file, p.clone()).unwrap_err().to_string(), plain, "{name}: {p}");
}
}
}
/// #4366: editing data stored in a form the reader doesn't take, beside a PDF part that can't be
/// read, is named in the error.
#[test]
fn the_error_says_why_the_editing_data_couldnt_be_read() {
let mut s = Session::new();
let file = ai::ai_with_private_streams(&compressed(&ai::sample_data()), ai::page_pdf(), REFUSED_CONTENT, "/Filter /Bogus ");
let plain = open(&mut s, "art.ai", &file, json!({"editingData": false})).unwrap_err().to_string();
let e = open(&mut s, "art.ai", &file, json!({})).unwrap_err().to_string();
assert_eq!(e, format!("{plain}; its editing data couldn't be read either (it is stored in a form that isn't read)"));
}
/// A file saved in units of 10 points (`/UserUnit 10`, as in
/// `an_ai_file_with_a_user_unit_opens_at_its_size_in_points`) whose PDF part can't be read opens
/// from its editing data at its size in points.
@@ -32,7 +32,24 @@ fn with(mut p: Value, more: &Value) -> Value {
/// The pixels of the PNG `document.export` writes of the active document with `p`, on transparency.
fn png(s: &mut Session, p: Value) -> image::RgbaImage {
let v = s.execute("document.export", &with(json!({"format": "png", "background": "transparent"}), &p)).unwrap();
image::load_from_memory(&b64(&v)).unwrap().to_rgba8()
craft_image_codecs::decode(&b64(&v))
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8()
}
/// The file `document.export` writes with `p`.
@@ -61,7 +78,26 @@ fn raster_exports_paint_the_color_behind_the_art() {
assert_eq!(png(&mut s, json!({"artboard": 0, "includeArtboardFill": false})).get_pixel(2, 2)[3], 0, "left out");
assert_eq!(png(&mut s, json!({"artboard": 1})).get_pixel(2, 2)[3], 0, "an artboard without a color");
let jpg = file(&mut s, json!({"format": "jpg", "artboard": 0, "quality": 100}));
let px = image::load_from_memory(&jpg).unwrap().to_rgb8().get_pixel(2, 2).0;
let px = craft_image_codecs::decode(&jpg)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgb8()
.get_pixel(2, 2)
.0;
assert!(px[0] > 240 && px[1] < 16 && px[2] < 16, "JPEG too: {px:?}");
for bad in [json!("no"), json!(1)] {
assert!(s.execute("document.export", &json!({"format": "png", "includeArtboardFill": bad})).is_err(), "{bad}");
@@ -163,7 +199,28 @@ fn export_for_screens_includes_the_fill_unless_unchecked() {
let p = with(json!({"artboards": [0], "formats": [{"format": "png"}], "settings": {"png": {"background": "transparent"}}}), &more);
s.execute("document.exportForScreens", &p).unwrap()
};
let corner = |r: &Value| image::load_from_memory(&b64(&r["files"][0])).unwrap().to_rgba8().get_pixel(2, 2).0;
let corner = |r: &Value| {
craft_image_codecs::decode(&b64(&r["files"][0]))
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8()
.get_pixel(2, 2)
.0
};
assert_eq!(corner(&screens(&mut s, json!({}))), RED, "on by default");
assert_eq!(corner(&screens(&mut s, json!({"includeArtboardFill": false})))[3], 0, "unchecked");
assert_eq!(s.execute("document.exportSettings", &json!({})).unwrap()["settings"]["includeArtboardFill"], false, "remembered");
+53 -3
View File
@@ -50,7 +50,23 @@ fn eps_covers_the_art_y_up_from_the_first_artboard_with_a_preview_and_the_docume
let bytes = b64(&r);
// The default TIFF preview sits behind the binary header.
let (_, tiff) = vectorcraft_eps::sections(&bytes).unwrap();
let preview = image::load_from_memory_with_format(tiff.unwrap(), image::ImageFormat::Tiff).unwrap();
let preview = craft_image_codecs::decode_as(craft_image_codecs::Format::Tiff, tiff.unwrap())
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap();
assert_eq!((preview.width(), preview.height()), (100, 40));
let ps = postscript(&bytes);
assert_eq!(dsc(&ps, "BoundingBox").as_deref(), Some("50 100 150 140"), "60..100 down is 100..140 up");
@@ -221,13 +237,47 @@ fn placed_images_are_written_and_previews_are_black_and_white_on_request() {
/// The PNG thumbnail of an EPS file, decoded.
fn thumbnail_png(bytes: &[u8]) -> image::RgbaImage {
let png = vectorcraft_eps::thumbnail(bytes).expect("a thumbnail");
image::load_from_memory_with_format(&png, image::ImageFormat::Png).unwrap().to_rgba8()
craft_image_codecs::decode_as(craft_image_codecs::Format::Png, &png)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8()
}
/// The TIFF preview of an EPS file, decoded.
fn preview_tiff(bytes: &[u8]) -> image::RgbaImage {
let tiff = vectorcraft_eps::sections(bytes).unwrap().1.expect("a preview");
image::load_from_memory_with_format(tiff, image::ImageFormat::Tiff).unwrap().to_rgba8()
craft_image_codecs::decode_as(craft_image_codecs::Format::Tiff, tiff)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8()
}
/// The size of a thumbnail render of the rect an EPS file's preview shows (its bounding box).
@@ -115,7 +115,25 @@ fn tiff_predicted_4_bit_images_open_from_eps_and_postscript_ai_files() {
let mut grays = vec![];
d.walk(|n| {
if let vectorcraft_doc::NodeKind::Image(im) = &n.kind {
grays = image::load_from_memory(&d.images[&im.key].bytes).unwrap().to_luma8().into_raw();
grays = craft_image_codecs::decode(&d.images[&im.key].bytes)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_luma8()
.into_raw();
}
});
assert_eq!(grays, [0, 5, 15, 3, 9, 9, 2, 0].map(|v| v * 17), "{name}");
+18 -1
View File
@@ -16,7 +16,24 @@ fn b64(v: &Value) -> Vec<u8> {
}
fn rgba(bytes: &[u8]) -> image::RgbaImage {
image::load_from_memory(bytes).unwrap().to_rgba8()
craft_image_codecs::decode(bytes)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8()
}
fn tmp_dir(tag: &str) -> std::path::PathBuf {
+69 -3
View File
@@ -12,7 +12,27 @@ const COLORS: [[u8; 4]; 4] = [[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 25
fn pixels(bytes: &[u8]) -> Vec<[u8; 4]> {
let raster = load::raster_image(bytes).unwrap();
image::load_from_memory(&raster.blob.bytes).unwrap().to_rgba8().pixels().map(|p| p.0).collect()
craft_image_codecs::decode(&raster.blob.bytes)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8()
.pixels()
.map(|p| p.0)
.collect()
}
fn boxed(ty: &[u8; 4], data: &[u8]) -> Vec<u8> {
@@ -54,12 +74,58 @@ fn checker_opens_and_places_with_exact_pixels() {
assert_eq!(opened["format"], "jpeg2000");
assert_eq!(s.doc().unwrap().doc.artboards[0].rect.size(), vectorcraft_geom::Size::new(2.0, 2.0));
let blob = s.doc().unwrap().doc.images.values().next().unwrap();
assert_eq!(image::load_from_memory(&blob.bytes).unwrap().to_rgba8().pixels().map(|p| p.0).collect::<Vec<_>>(), COLORS);
assert_eq!(
craft_image_codecs::decode(&blob.bytes)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8()
.pixels()
.map(|p| p.0)
.collect::<Vec<_>>(),
COLORS
);
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
let placed = s.execute("file.place", &json!({"name": name, "dataBase64": encoded})).unwrap();
assert_eq!(placed["format"], "jpeg2000");
let blob = s.doc().unwrap().doc.images.values().next().unwrap();
assert_eq!(image::load_from_memory(&blob.bytes).unwrap().to_rgba8().pixels().map(|p| p.0).collect::<Vec<_>>(), COLORS);
assert_eq!(
craft_image_codecs::decode(&blob.bytes)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8()
.pixels()
.map(|p| p.0)
.collect::<Vec<_>>(),
COLORS
);
assert!(load::texture_image(bytes).is_ok());
}
}
+57 -3
View File
@@ -33,14 +33,48 @@ fn png8_and_gif_export_palettes() {
let png8 = b64(&s.execute("document.export", &json!({"format": "png8", "colors": 16})).unwrap());
assert_eq!(png8[25], 3, "colour type 3");
assert!(plte_len(&png8) <= 16);
let img = image::load_from_memory(&png8).unwrap().to_rgba8();
let img = craft_image_codecs::decode(&png8)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8();
assert_eq!(img.dimensions(), (40, 30));
assert_eq!(img.get_pixel(5, 15).0, [255, 0, 0, 255]);
assert_eq!(img.get_pixel(39, 0)[3], 0, "transparent where there is no art");
let gif = b64(&s.execute("document.export", &json!({"format": "gif", "background": "white", "dither": "none"})).unwrap());
assert_eq!(&gif[..6], b"GIF89a");
let img = image::load_from_memory_with_format(&gif, image::ImageFormat::Gif).unwrap().to_rgba8();
let img = craft_image_codecs::decode_as(craft_image_codecs::Format::Gif, &gif)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8();
assert_eq!(img.get_pixel(5, 15).0, [255, 0, 0, 255]);
assert_eq!(img.get_pixel(39, 0).0, [255, 255, 255, 255], "the white background");
@@ -68,5 +102,25 @@ fn palette_formats_reach_export_as_and_screens() {
let names: Vec<&str> = r["files"].as_array().unwrap().iter().map(|f| f["name"].as_str().unwrap()).collect();
assert_eq!(names, ["Artboard-1@2x.gif", "Artboard-1.png"]);
let gif = vectorcraft_format::base64_decode(r["files"][0]["dataBase64"].as_str().unwrap()).unwrap();
assert_eq!(image::load_from_memory(&gif).unwrap().width(), 80);
assert_eq!(
craft_image_codecs::decode(&gif)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.width(),
80
);
}
+21 -1
View File
@@ -49,7 +49,27 @@ fn rle(raw: &[u8]) -> Vec<u8> {
/// The pixels `raster_image` stores for `f`, row by row.
fn pixels(f: &[u8]) -> Vec<[u8; 4]> {
let img = raster_image(f).unwrap();
image::load_from_memory(&img.blob.bytes).unwrap().to_rgba8().pixels().map(|p| p.0).collect()
craft_image_codecs::decode(&img.blob.bytes)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8()
.pixels()
.map(|p| p.0)
.collect()
}
/// The 16 colors of a header palette: entry `i` is (16 i, 255 − 16 i, i).
+35 -1
View File
@@ -375,7 +375,41 @@ fn a_16_bit_png_is_written_at_8_bits_before_pdf_1_5() {
let mut s = session(1);
let deep = image::ImageBuffer::from_fn(8, 8, |x, y| image::Rgb([x as u16 * 8000, y as u16 * 8000, 40000]));
let mut png = vec![];
image::DynamicImage::ImageRgb16(deep).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
{
let __dyn: image::DynamicImage = image::DynamicImage::ImageRgb16(deep);
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| png.extend_from_slice(&__b))
}
.unwrap();
s.execute("file.place", &json!({"name": "deep.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [50, 40]})).unwrap();
let readable = json!({"compressText": false});
for (cmd, p, depth) in [
+35 -3
View File
@@ -26,9 +26,41 @@ fn session() -> Session {
run(&mut s, "paint.setFill", json!({"color": "#e0c020"}));
run(&mut s, "effect.apply", json!({"effect": "stylize.dropShadow", "ids": [shadowed]}));
let mut png = vec![];
image::RgbaImage::from_fn(8, 8, |x, _| image::Rgba([0, 120, 255, if x < 4 { 0 } else { 255 }]))
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
.unwrap();
{
let __dyn: image::DynamicImage = (image::RgbaImage::from_fn(8, 8, |x, _| image::Rgba([0, 120, 255, if x < 4 { 0 } else { 255 }]))).into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| png.extend_from_slice(&__b))
}
.unwrap();
run(&mut s, "file.place", json!({"name": "dots.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [150, 120]}));
s
}
+57 -2
View File
@@ -807,7 +807,28 @@ fn image_outline(doc: &vectorcraft_doc::Document) -> Vec<String> {
((p.x * 100.0).round() / 100.0, (p.y * 100.0).round() / 100.0)
});
let link = im.link.as_ref().map(|l| (l.path.clone(), l.relative.clone()));
let pixels = doc.image_blob(im).and_then(|b| image::load_from_memory(&b.bytes).ok()).map(|i| i.to_rgba8().into_raw());
let pixels = doc
.image_blob(im)
.and_then(|b| {
craft_image_codecs::decode(&b.bytes)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.ok()
})
.map(|i| i.to_rgba8().into_raw());
out.push(format!("{}x{} {corners:?} {link:?} {pixels:?}", im.width, im.height));
}
});
@@ -825,7 +846,41 @@ fn images_come_back_from_the_editing_copy() {
std::fs::create_dir_all(format!("{dir}/art")).unwrap();
let png = |w: u32, h: u32, f: &dyn Fn(u32, u32) -> [u8; 4]| {
let mut out = vec![];
image::RgbaImage::from_fn(w, h, |x, y| image::Rgba(f(x, y))).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap();
{
let __dyn: image::DynamicImage = (image::RgbaImage::from_fn(w, h, |x, y| image::Rgba(f(x, y)))).into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| out.extend_from_slice(&__b))
}
.unwrap();
out
};
let linked = format!("{dir}/art/linked.png");
@@ -97,7 +97,23 @@ fn pdf_info_lists_pages_boxes_and_a_thumbnail() {
assert_eq!(p2["boxes"]["trim"], json!([15.0, 15.0, 185.0, 385.0]));
assert_eq!(p2["boxes"]["media"], json!([0.0, 0.0, 200.0, 400.0]));
let png = vectorcraft_format::base64_decode(v["thumbnail"].as_str().unwrap()).unwrap();
let img = image::load_from_memory(&png).unwrap();
let img = craft_image_codecs::decode(&png)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap();
assert_eq!((img.width(), img.height()), (50, 100), "the art box at 100 px on its longest side");
assert!(s.execute("document.pdfInfo", &json!({"dataBase64": b64(&bytes), "thumbnail": 4})).is_err());
// Locked: no pages until the password is given.
@@ -214,7 +230,27 @@ fn pdf_info_refuses_a_thumbnail_size_that_is_not_a_number() {
assert!(e.contains("`colorMode` must be a string"), "{e}");
let v = s.execute("document.pdfInfo", &json!({"dataBase64": b64(&bytes), "thumbnail": 1, "thumbnailSize": null})).unwrap();
let png = vectorcraft_format::base64_decode(v["thumbnail"].as_str().unwrap()).unwrap();
assert_eq!(image::load_from_memory(&png).unwrap().width(), 160);
assert_eq!(
craft_image_codecs::decode(&png)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.width(),
160
);
}
#[test]
@@ -284,7 +320,23 @@ fn pdf_info_reads_postscript_as_one_page() {
] {
let v = s.execute("document.pdfInfo", &json!({"dataBase64": b64(bytes), "thumbnail": 1, "thumbnailSize": 100})).unwrap();
let png = vectorcraft_format::base64_decode(v["thumbnail"].as_str().unwrap()).unwrap();
let img = image::load_from_memory(&png).unwrap();
let img = craft_image_codecs::decode(&png)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap();
assert_eq!(img.width().max(img.height()), 100, "{name}");
let mut v = v;
v["thumbnail"] = json!("png");
@@ -314,7 +366,23 @@ fn pdf_info_refuses_a_thumbnail_that_is_not_a_page_number() {
}
let v = s.execute("document.pdfInfo", &json!({"dataBase64": b64(bytes), "thumbnail": 1, "thumbnailSize": 64})).unwrap();
let png = vectorcraft_format::base64_decode(v["thumbnail"].as_str().unwrap()).unwrap();
let img = image::load_from_memory(&png).unwrap();
let img = craft_image_codecs::decode(&png)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap();
assert_eq!(img.width().max(img.height()), 64, "{pages}");
}
}
+144 -13
View File
@@ -17,9 +17,41 @@ fn session() -> Session {
s.execute("paint.setFill", &json!({"color": {"model": "rgb", "r": 1.0, "g": 0.2, "b": 0.0}})).unwrap();
s.execute("transparency.set", &json!({"opacity": 50})).unwrap();
let mut png = vec![];
image::RgbaImage::from_fn(8, 8, |x, _| image::Rgba([0, 120, 255, if x < 4 { 0 } else { 255 }]))
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
.unwrap();
{
let __dyn: image::DynamicImage = (image::RgbaImage::from_fn(8, 8, |x, _| image::Rgba([0, 120, 255, if x < 4 { 0 } else { 255 }]))).into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| png.extend_from_slice(&__b))
}
.unwrap();
s.execute("file.place", &json!({"name": "dots.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [150, 50]})).unwrap();
s
}
@@ -175,9 +207,41 @@ fn pdfx_1a_flattening_keeps_the_inks_behind_an_image_in_a_cmyk_document() {
s.execute("paint.setFill", &json!({"color": {"c": teal[0], "m": teal[1], "y": teal[2], "k": teal[3]}})).unwrap();
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
let mut png = vec![];
image::RgbaImage::from_fn(40, 40, |x, _| image::Rgba([0, 120, 255, if x < 20 { 0 } else { 255 }]))
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
.unwrap();
{
let __dyn: image::DynamicImage = (image::RgbaImage::from_fn(40, 40, |x, _| image::Rgba([0, 120, 255, if x < 20 { 0 } else { 255 }]))).into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| png.extend_from_slice(&__b))
}
.unwrap();
s.execute("file.place", &json!({"name": "logos.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [100, 50]})).unwrap();
let v = s.execute("document.exportPdf", &json!({"standard": "pdfX1a"})).unwrap();
let bytes = vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap();
@@ -228,10 +292,45 @@ fn cropped_by(mode: &str, width: f64, art: Art, layer: bool) -> (Session, u64) {
let art = match art {
Art::Image { see_through } => {
let mut png = vec![];
image::RgbaImage::from_fn(240, 160, |x, y| {
image::Rgba([200, (x % 256) as u8, (y % 256) as u8, if see_through && x < 60 { 128 } else { 255 }])
})
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
{
let __dyn: image::DynamicImage = (image::RgbaImage::from_fn(240, 160, |x, y| {
image::Rgba([200, (x % 256) as u8, (y % 256) as u8, if see_through && x < 60 { 128 } else { 255 }])
}))
.into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => {
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw())
}
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| png.extend_from_slice(&__b))
}
.unwrap();
let placed =
run(&mut s, "file.place", json!({"name": "photo.png", "dataBase64": vectorcraft_format::base64_encode(&png), "rect": FRAME}));
@@ -486,9 +585,41 @@ fn flat_pdf_files_of_art_that_no_clip_group_hides_are_unchanged() {
run(&mut fitted, "shape.rectangle", json!({"x": 180, "y": 90, "width": 160, "height": 160}));
run(&mut fitted, "paint.setFill", json!({"color": "#203040"}));
let mut png = vec![];
image::RgbaImage::from_fn(240, 160, |x, y| image::Rgba([200, x as u8, y as u8, 255]))
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
.unwrap();
{
let __dyn: image::DynamicImage = (image::RgbaImage::from_fn(240, 160, |x, y| image::Rgba([200, x as u8, y as u8, 255]))).into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| png.extend_from_slice(&__b))
}
.unwrap();
let photo =
run(&mut fitted, "file.place", json!({"name": "photo.png", "dataBase64": vectorcraft_format::base64_encode(&png), "rect": FRAME}))["ids"][0]
.clone();
@@ -274,7 +274,24 @@ fn image_of(s: &Session, l: &Node) -> ((f64, f64), image::RgbaImage) {
fn pixels_of(s: &Session, c: &Node) -> ((f64, f64), image::RgbaImage) {
let NodeKind::Image(img) = &c.kind else { panic!("{} isn't an image", name(c)) };
let blob = &s.doc().unwrap().doc.images[&img.key];
let px = image::load_from_memory(&blob.bytes).unwrap().to_rgba8();
let px = craft_image_codecs::decode(&blob.bytes)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8();
assert_eq!((px.width(), px.height()), (img.width, img.height));
let o = img.xf * kurbo::Point::ZERO;
((o.x, o.y), px)
+18 -1
View File
@@ -215,7 +215,24 @@ fn exported(s: &mut Session, p: Value) -> Vec<u8> {
#[test]
fn psd_exports_open_and_place_again() {
let mut s = art();
let png = image::load_from_memory(&exported(&mut s, json!({"format": "png"}))).unwrap().to_rgba8();
let png = craft_image_codecs::decode(&exported(&mut s, json!({"format": "png"})))
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8();
for (options, what) in [(json!({}), "layered RGB"), (json!({"layers": false}), "flat RGB"), (json!({"colorModel": "gray"}), "grey")] {
let f = exported(&mut s, merge(json!({"format": "psd"}), options));
let back = decode(&f, 1 << 30, naive).unwrap();
+74 -3
View File
@@ -72,7 +72,27 @@ fn wide(samples: &[u16]) -> Vec<u8> {
/// The pixels `raster_image` stores for `f`, row by row.
fn pixels(f: &[u8]) -> Vec<[u8; 4]> {
let img = raster_image(f).unwrap();
image::load_from_memory(&img.blob.bytes).unwrap().to_rgba8().pixels().map(|p| p.0).collect()
craft_image_codecs::decode(&img.blob.bytes)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8()
.pixels()
.map(|p| p.0)
.collect()
}
const RGBA: u16 = 15;
@@ -241,13 +261,64 @@ fn pxr_files_open_place_and_paste() {
let node = doc.node(vectorcraft_doc::NodeId(r["ids"][0].as_u64().unwrap())).unwrap();
let vectorcraft_doc::NodeKind::Image(im) = &node.kind else { panic!("link {link}: an image, got {:?}", node.kind) };
assert_eq!((im.link.is_some(), im.width, im.height), (link, 2, 1), "link {link}");
let shown = image::load_from_memory(&doc.images[&im.key].bytes).unwrap().to_rgba8();
let shown = craft_image_codecs::decode(&doc.images[&im.key].bytes)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8();
assert_eq!(shown.pixels().map(|p| p.0).collect::<Vec<_>>(), pixels(&f), "link {link}");
}
let _ = std::fs::remove_dir_all(&dir);
// Open sizes it as a PNG of 2 × 1 pixels without a resolution.
let mut png = vec![];
image::RgbaImage::new(2, 1).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
{
let __dyn: image::DynamicImage = (image::RgbaImage::new(2, 1)).into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| png.extend_from_slice(&__b))
}
.unwrap();
let mut t = Session::new();
t.execute("document.open", &json!({"name": "same.png", "dataBase64": b64(&png)})).unwrap();
assert_eq!(t.doc().unwrap().doc.artboards[0].rect.size(), size);
+70 -1
View File
@@ -16,7 +16,24 @@ fn b64(v: &Value) -> Vec<u8> {
}
fn rgba(bytes: &[u8]) -> image::RgbaImage {
image::load_from_memory(bytes).unwrap().to_rgba8()
craft_image_codecs::decode(bytes)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8()
}
/// A chunk's data by type (first match) in a PNG file.
@@ -427,3 +444,55 @@ fn export_for_screens_rows_keep_their_own_size() {
.unwrap();
assert_eq!(rgba(&b64(&r["files"][0])).dimensions(), (512, 256), "{r}");
}
/// File › Open's raster path reads images through craft-image-codecs (#778) as it read them with
/// the image crate: each format the image crate decoded for it (BMP, TGA, TIFF at 8 and 16 bits,
/// gray and color, with and without alpha; a PNG, JPEG, GIF and WebP stored as they are) gives
/// the same size, sample depth and pixels.
#[test]
fn opened_rasters_are_the_pixels_the_image_crate_read() {
use image::{DynamicImage as D, ImageFormat as F};
let rgba = image::RgbaImage::from_fn(11, 6, |x, y| image::Rgba([(x * 23) as u8, (y * 41) as u8, ((x ^ y) * 13) as u8, 255 - (x * y * 3) as u8]));
let deep = image::ImageBuffer::<image::Rgba<u16>, _>::from_fn(11, 6, |x, y| {
image::Rgba([(x * 5_003) as u16, (y * 9_011) as u16, 77, 65_535 - (x * y) as u16])
});
let images = [
D::ImageRgba8(rgba.clone()),
D::ImageRgb8(D::ImageRgba8(rgba.clone()).to_rgb8()),
D::ImageLuma8(D::ImageRgba8(rgba.clone()).to_luma8()),
D::ImageLumaA8(D::ImageRgba8(rgba).to_luma_alpha8()),
D::ImageRgba16(deep.clone()),
D::ImageRgb16(D::ImageRgba16(deep.clone()).to_rgb16()),
D::ImageLuma16(D::ImageRgba16(deep).to_luma16()),
];
let mut checked = 0;
for img in &images {
for f in [F::Bmp, F::Tga, F::Tiff, F::Png, F::Jpeg, F::Gif, F::WebP] {
let mut bytes = Vec::new();
if img.write_to(&mut std::io::Cursor::new(&mut bytes), f).is_err() {
continue;
}
let what = format!("{f:?} {:?}", img.color());
let mut want = image::load_from_memory_with_format(&bytes, f).unwrap();
let opened = super::load::raster_image(&bytes).unwrap_or_else(|e| panic!("{what}: {e}"));
assert_eq!((opened.width, opened.height), (want.width(), want.height()), "{what}");
if opened.blob.mime != "image/png" {
// Stored as they are: the file's own bytes.
assert_eq!(opened.blob.bytes.as_slice(), bytes.as_slice(), "{what}");
checked += 1;
continue;
}
if f == F::Tga {
let mut px = want.to_rgba8();
super::tgaread::fix_alpha(&bytes, &mut px);
want = D::ImageRgba8(px);
}
let got = image::load_from_memory_with_format(&opened.blob.bytes, F::Png).unwrap();
let deep_samples = |c: image::ColorType| c.bytes_per_pixel() > c.channel_count();
assert_eq!(deep_samples(got.color()), deep_samples(want.color()), "{what}: {:?} {:?}", got.color(), want.color());
assert_eq!(got.to_rgba16().as_raw(), want.to_rgba16().as_raw(), "{what}");
checked += 1;
}
}
assert!(checked >= 25, "{checked}");
}
+120 -4
View File
@@ -34,7 +34,25 @@ fn names(r: &Value) -> Vec<String> {
}
fn size(png: &[u8]) -> (u32, u32) {
image::load_from_memory(png).unwrap().to_rgba8().dimensions()
craft_image_codecs::decode(png)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8()
.dimensions()
}
#[test]
@@ -413,7 +431,28 @@ fn rich_black_reaches_the_files() {
s.execute("paint.setFill", &json!({"color": {"c": 0, "m": 0, "y": 0, "k": 1}})).unwrap();
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 40, "height": 30})).unwrap();
let p = json!({"formats": [{"format": "png"}]});
let px = |r: &Value| image::load_from_memory(&files(r)[0].1).unwrap().to_rgba8().get_pixel(10, 10).0;
let px = |r: &Value| {
craft_image_codecs::decode(&files(r)[0].1)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8()
.get_pixel(10, 10)
.0
};
let accurate = px(&export(&mut s, p.clone()));
assert!(accurate[0] > 10, "accurate: dark grey, {accurate:?}");
s.execute("prefs.set", &json!({"key": "blackOutput", "value": "rich"})).unwrap();
@@ -589,7 +628,28 @@ fn png_8_rows_write_indexed_colour() {
#[test]
fn a_second_file_with_a_taken_name_is_numbered() {
let mut s = session(1);
let px = |png: &[u8]| image::load_from_memory(png).unwrap().to_rgba8().get_pixel(1, 1).0;
let px = |png: &[u8]| {
craft_image_codecs::decode(png)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8()
.get_pixel(1, 1)
.0
};
let rows = json!([{"format": "png", "background": "black"}, {"format": "png", "background": "white"}, {"format": "png", "background": "black"}]);
let r = export(&mut s, json!({ "formats": rows }));
assert_eq!(names(&r), ["Artboard-1.png", "Artboard-1-2.png"]);
@@ -873,7 +933,28 @@ fn kept_settings_leave_out_a_folder_outside_the_read_root() {
#[test]
fn format_settings_apply_to_their_rows_and_rows_win() {
let mut s = session(1);
let px = |png: &[u8]| image::load_from_memory(png).unwrap().to_rgba8().get_pixel(1, 1).0;
let px = |png: &[u8]| {
craft_image_codecs::decode(png)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8()
.get_pixel(1, 1)
.0
};
let r = export(
&mut s,
json!({"settings": {"png": {"background": "black", "scale": 9, "artboard": 7}, "jpg": {"quality": 5}}, "formats": [{"format": "png"}, {"format": "png", "suffix": "-w", "background": "white"}, {"format": "jpg"}, {"format": "jpg", "quality": 100, "suffix": "-100"}]}),
@@ -1164,6 +1245,41 @@ fn single_file_pdfs_hold_every_chosen_artboard() {
assert!(s.execute("document.exportForScreens", &json!({"pdfs": "both", "formats": [{"format": "pdf"}]})).is_err());
}
/// Export PDFs As › Single file holds artboards: with assets, layers or a file per selected object,
/// whose files each hold one item's art, it is refused (the Example line too) instead of writing
/// the first item alone under the document's name; Multiple files writes a PDF of each item. The
/// selection as one file is one PDF either way.
#[test]
fn single_file_pdfs_are_refused_for_assets_layers_and_each_object() {
let mut s = session(1);
s.execute("layer.new", &json!({"name": "Second"})).unwrap();
s.execute("shape.ellipse", &json!({"x": 30, "y": 5, "width": 8, "height": 8})).unwrap();
let doc = s.doc().unwrap().doc.clone();
let layers: Vec<u64> = doc.layers.iter().map(|l| l.id.0).collect();
let art: Vec<u64> = doc.layers.iter().filter_map(|l| l.children()).flatten().map(|c| c.id.0).collect();
assert_eq!((layers.len(), art.len()), (2, 2));
let a = s.execute("assets.add", &json!({"ids": [art[0]], "name": "Square"})).unwrap()["assets"][0].as_u64().unwrap();
let b = s.execute("assets.add", &json!({"ids": [art[1]], "name": "Dot"})).unwrap()["assets"][0].as_u64().unwrap();
s.execute("select.all", &json!({})).unwrap();
let pdf = json!([{"format": "pdf"}]);
for source in [json!({"assets": [a, b]}), json!({"layers": layers}), json!({"selection": "each"})] {
let mut p = source.clone();
p["formats"] = pdf.clone();
p["pdfs"] = json!("multiple");
let r = export(&mut s, p.clone());
assert_eq!(names(&r).len(), 2, "a PDF each: {:?} ({source})", names(&r));
for (name, bytes) in files(&r) {
assert_eq!(vectorcraft_pdf::import(&bytes).unwrap().artboards.len(), 1, "{name}");
}
p["pdfs"] = json!("single");
let e = s.execute("document.exportForScreens", &p).unwrap_err().to_string();
assert!(e.contains("pdfs `single`"), "{e} ({source})");
assert!(super::screens::first_file(&s, &p).is_err(), "{source}");
}
let r = export(&mut s, json!({"selection": "one", "pdfs": "single", "formats": pdf}));
assert_eq!(names(&r), ["Selection.pdf"]);
}
/// The warnings of reply `r` that name an option the file doesn't read.
fn unused(r: &Value) -> Vec<String> {
r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).filter(|w| w.contains("was not used")).map(str::to_string).collect()
+200 -9
View File
@@ -43,13 +43,47 @@ fn rect_of(v: &Value) -> Rect {
/// What the canvas draws of the whole document over `r`, at 1 px per point.
fn canvas(s: &Session, r: Rect) -> image::RgbaImage {
let img = vectorcraft_render::Renderer::new().render_region(&s.doc().unwrap().doc, r, 1.0, false);
image::load_from_memory(&img.to_png().unwrap()).unwrap().to_rgba8()
craft_image_codecs::decode(&img.to_png().unwrap())
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8()
}
/// The pixels of `png` that differ from `want` by more than 64 in a channel (anti-aliased edges
/// differ by less), and every pixel when the sizes differ.
fn differing(png: &[u8], want: &image::RgbaImage) -> usize {
let got = image::load_from_memory(png).unwrap().to_rgba8();
let got = craft_image_codecs::decode(png)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8();
if got.dimensions() != want.dimensions() {
return (want.width() * want.height()) as usize;
}
@@ -86,7 +120,41 @@ fn export_selection_of_a_clipped_object_keeps_its_clip() {
let board = t.doc().unwrap().doc.artboards[0].rect;
let reopened = canvas(&t, board);
let mut png = vec![];
reopened.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
{
let __dyn: image::DynamicImage = reopened.into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| png.extend_from_slice(&__b))
}
.unwrap();
let off = differing(&png, &canvas(&s, Rect::new(150.0, 150.0, 350.0, 350.0)));
assert!(off < 200, "the reopened SVG: {off} pixels differ from the canvas");
}
@@ -162,7 +230,24 @@ fn a_selected_clipping_path_and_a_blend_object_export_on_their_own() {
// The clipping path alone: the clip group's other art stays out.
run(&mut s, "select.set", json!({"ids": [circle]}));
let r = run(&mut s, "document.exportSelection", json!({"format": "png", "scale": 1}));
let img = image::load_from_memory(&b64(&r)).unwrap().to_rgba8();
let img = craft_image_codecs::decode(&b64(&r))
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8();
assert_eq!(img.dimensions(), (200, 200), "cropped to the clipping path");
assert!(!img.pixels().any(|p| p[0] > 200 && p[1] < 80 && p[3] > 0), "the clipped square is left out");
// An object of a blend goes in on its own, without the blend's steps.
@@ -176,7 +261,24 @@ fn a_selected_clipping_path_and_a_blend_object_export_on_their_own() {
let r = run(&mut s, "document.exportSelection", json!({"format": "png", "scale": 1}));
let got = rect_of(&r["bounds"]);
assert!(got.x1 < 90.0 && got.y1 < 90.0, "the blend object's own bounds: {got:?}");
let img = image::load_from_memory(&b64(&r)).unwrap().to_rgba8();
let img = craft_image_codecs::decode(&b64(&r))
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8();
let centre = img.get_pixel(img.width() / 2, img.height() / 2);
assert!(centre[0] > 200 && centre[3] > 200, "the object is drawn: {centre:?}");
}
@@ -191,7 +293,25 @@ fn a_css_picture_of_a_clipped_object_is_clipped() {
let r = run(&mut s, "css.export", json!({"ids": [star], "rasterize": true, "unnamed": true}));
let image = r["images"].as_array().and_then(|i| i.first()).unwrap_or_else(|| panic!("no picture: {r}"));
let png = b64(image);
let size = image::load_from_memory(&png).unwrap().to_rgba8().dimensions();
let size = craft_image_codecs::decode(&png)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8()
.dimensions();
assert_eq!(size, (100, 100), "the picture is cropped to the clip");
assert!(differing(&png, &canvas(&s, Rect::new(200.0, 200.0, 300.0, 300.0))) < 100, "the picture matches the canvas");
}
@@ -204,7 +324,24 @@ fn an_asset_on_a_hidden_layer_is_drawn_clipped() {
let asset = run(&mut s, "assets.add", json!({"ids": [square]}))["assets"][0].as_u64().unwrap();
run(&mut s, "layer.setProps", json!({"id": layer, "visible": false}));
let r = run(&mut s, "assets.export", json!({"assets": [asset], "formats": [{"format": "png", "scale": 1}]}));
let img = image::load_from_memory(&b64(&r["files"][0])).unwrap().to_rgba8();
let img = craft_image_codecs::decode(&b64(&r["files"][0]))
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8();
assert_eq!(img.dimensions(), (200, 200), "cropped to the clip");
let (centre, corner) = (img.get_pixel(100, 100), img.get_pixel(3, 3));
assert!(centre[0] > 200 && centre[3] > 200, "the square is drawn: {centre:?}");
@@ -233,7 +370,27 @@ fn export_for_screens_and_assets_by_selection_keep_the_clip() {
/// The red pixels of `png`.
fn red(png: &[u8]) -> usize {
image::load_from_memory(png).unwrap().to_rgba8().pixels().filter(|p| p[0] > 200 && p[1] < 80 && p[3] > 200).count()
craft_image_codecs::decode(png)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8()
.pixels()
.filter(|p| p[0] > 200 && p[1] < 80 && p[3] > 200)
.count()
}
#[test]
@@ -248,7 +405,41 @@ fn a_selection_on_a_non_printing_layer_exports_to_pdf() {
run(&mut t, "document.open", json!({"name": "sel.pdf", "dataBase64": vectorcraft_format::base64_encode(&pdf)}));
let page = t.doc().unwrap().doc.artboards[0].rect;
let mut png = vec![];
canvas(&t, page).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
{
let __dyn: image::DynamicImage = (canvas(&t, page)).into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| png.extend_from_slice(&__b))
}
.unwrap();
assert!(red(&png) > 20_000, "the PDF draws the square: {} red pixels", red(&png));
assert!(differing(&png, &canvas(&s, Rect::new(150.0, 150.0, 350.0, 350.0))) < 300, "the PDF draws what the canvas draws");
}
+55 -4
View File
@@ -27,9 +27,41 @@ fn tmp_dir(tag: &str) -> std::path::PathBuf {
/// A session whose document holds one embedded 2×2 PNG.
pub(super) fn image_session() -> Session {
let mut png = Vec::new();
image::RgbaImage::from_pixel(2, 2, image::Rgba([10, 200, 30, 255]))
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
.unwrap();
{
let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(2, 2, image::Rgba([10, 200, 30, 255]))).into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| png.extend_from_slice(&__b))
}
.unwrap();
let mut s = Session::new();
s.execute("document.open", &json!({"name": "dot.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap();
s
@@ -120,7 +152,26 @@ fn linked_images_are_written_next_to_the_svg() {
let path = dir.join("pic.svg").to_string_lossy().to_string();
let r = s.execute("document.export", &json!({"path": path, "images": "link"})).unwrap();
let linked = r["linked"][0].as_str().unwrap();
assert!(image::load_from_memory(&std::fs::read(linked).unwrap()).is_ok(), "{linked}");
assert!(
craft_image_codecs::decode(&std::fs::read(linked).unwrap())
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.is_ok(),
"{linked}"
);
let text = std::fs::read_to_string(&path).unwrap();
let name = std::path::Path::new(linked).file_name().unwrap().to_string_lossy().to_string();
assert!(text.contains(&format!("href=\"{name}\"")), "{text}");
@@ -32,9 +32,41 @@ impl Drop for Folder {
fn png(w: u32, h: u32) -> Vec<u8> {
let mut out = vec![];
image::RgbaImage::from_pixel(w, h, image::Rgba([230, 20, 20, 255]))
.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png)
.unwrap();
{
let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(w, h, image::Rgba([230, 20, 20, 255]))).into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| out.extend_from_slice(&__b))
}
.unwrap();
out
}
+64 -3
View File
@@ -65,7 +65,29 @@ fn webp_is_lossless_and_says_so_when_lossy_is_asked_for() {
let r = s.execute("document.export", &json!({"format": "webp", "lossless": false, "quality": 60, "background": "black"})).unwrap();
assert_eq!(&b64(&r)[12..16], b"VP8L");
assert!(r["warnings"][0].as_str().unwrap().contains("lossless"), "{r}");
assert_eq!(image::load_from_memory(&b64(&r)).unwrap().to_rgba8().get_pixel(29, 19).0, [0, 0, 0, 255]);
assert_eq!(
craft_image_codecs::decode(&b64(&r))
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8()
.get_pixel(29, 19)
.0,
[0, 0, 0, 255]
);
}
#[test]
@@ -74,12 +96,51 @@ fn save_for_office_writes_a_png_at_the_resolution() {
s.execute("file.new", &json!({"width": 612, "height": 792, "artboards": 2})).unwrap();
let r = s.execute("document.exportForOffice", &json!({"ppi": 150})).unwrap();
assert_eq!((r["width"].as_u64(), r["height"].as_u64()), (Some(1275), Some(1650)), "Letter at 150 ppi");
let img = image::load_from_memory(&b64(&r)).unwrap().to_rgba8();
let img = craft_image_codecs::decode(&b64(&r))
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8();
assert_eq!(img.dimensions(), (1275, 1650));
assert_eq!(img.get_pixel(0, 0).0, [255, 255, 255, 255], "on white");
let r = s.execute("document.exportForOffice", &json!({"ppi": 72, "transparent": true, "artboard": 1})).unwrap();
assert_eq!((r["width"].as_u64(), r["height"].as_u64()), (Some(612), Some(792)));
assert_eq!(image::load_from_memory(&b64(&r)).unwrap().to_rgba8().get_pixel(0, 0)[3], 0, "transparent");
assert_eq!(
craft_image_codecs::decode(&b64(&r))
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8()
.get_pixel(0, 0)[3],
0,
"transparent"
);
assert!(s.execute("document.exportForOffice", &json!({"artboard": 2})).is_err());
assert!(s.execute("document.exportForOffice", &json!({"ppi": -3})).is_err());
let spec = crate::cmd::find_command("document.exportForOffice").unwrap();
+9
View File
@@ -23,6 +23,15 @@ pub(super) fn is_targa(bytes: &[u8]) -> bool {
&& descriptor & 0xc0 == 0
}
/// A Targa file's size, from its header (there is no signature for a size probe to go by).
pub(super) fn size(bytes: &[u8]) -> Option<(u32, u32)> {
let le = |at: usize| Some(u32::from(u16::from_le_bytes(bytes.get(at..at + 2)?.try_into().ok()?)));
if !is_targa(bytes) {
return None;
}
Some((le(12)?, le(14)?))
}
/// Give `img`, decoded from Targa file `bytes`, the transparency the file stores. Bits 0 to 3 of
/// the image descriptor give the number of attribute bits per pixel, and the extension area's
/// Attributes Type, when the file has one, says what they hold:
+1 -3
View File
@@ -70,9 +70,7 @@ pub(crate) fn carry(from: &Node, mut to: Node) -> Node {
/// The keys of `doc`'s images that have see-through pixels (an alpha channel that isn't opaque
/// everywhere).
pub fn see_through_images(doc: &Document) -> BTreeSet<String> {
let see_through = |b: &ImageBlob| {
b.mime != "image/jpeg" && image::load_from_memory(&b.bytes).is_ok_and(|i| i.color().has_alpha() && i.to_rgba8().pixels().any(|p| p[3] < 255))
};
let see_through = |b: &ImageBlob| b.mime != "image/jpeg" && b.has_transparency();
doc.images.iter().filter(|(_, b)| see_through(b)).map(|(k, _)| k.clone()).collect()
}
+1 -1
View File
@@ -58,7 +58,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Show Similar Fonts",
[],
None,
"{family (any of its names), limit?: whole number 1..100000 (default: all)} → {family: the family's own name, families: [names]}: the families `text.fontList` lists, ordered as a font menu's Show Similar Fonts orders them: the family itself first, then those that set the same script (Japanese, Thai or neither), then the others, each group nearest first by VectorCraft's own measure of the faces nearest an upright Regular (OS/2 PANOSE digits, weight and width classes, x-height, cap height and average character width, the italic angle, and the kind); an error when the family isn't available or the font menus don't list it, or `limit` is not a whole number from 1 to 100000",
"{family (any of its names), limit?: whole number 1..100000 (default: all)} → {family: the family's own name, families: [names]}: the families `text.fontList` lists, ordered as a font menu's Show Similar Fonts orders them: the family itself first, then those that set the same script (Japanese, Thai or neither), then the others, each group nearest first by VectorCraft's own measure of the faces nearest an upright Regular (OS/2 PANOSE digits, weight and width classes, x-height, cap height and average character width, the italic angle, and the kind; a family that shares none of these numbers with it comes after those that share one); an error when the family isn't available or the font menus don't list it, or `limit` is not a whole number from 1 to 100000",
always,
similar_fonts
),
+1 -1
View File
@@ -244,7 +244,7 @@ impl Gen<'_> {
let slot = g.series_paints.get(s);
let fill =
slot.and_then(|p| p.fill.clone().or_else(|| p.stroke.clone().filter(|st| !st.is_none()))).unwrap_or_else(|| default_series_paint(s));
return self.path(band, fill, Paint::solid(Color::BLACK), 0.25);
return self.path(band, fill, Paint::solid(Color::BLACK), vectorcraft_doc::FILLED_LINE_OUTLINE_WIDTH);
}
let (fill, stroke, w) = series_marks(g, s, false, default_series_paint(s), 1.0);
self.path(pd, fill, stroke, w)
+52
View File
@@ -9505,6 +9505,58 @@ fn a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns() {
}
}
/// A line graph the graph tools draw with Draw Filled Lines, saved as `.ai` in either form, opens again as the same graph
/// with its filled lines and Line Width, the default 3 pt included, and without a warning about graphs. A Line Width past
/// the records' 100 pt is saved as the graph's art, with the warning.
#[test]
fn a_drawn_graph_with_filled_lines_saved_as_ai_opens_with_them() {
let dir = vectorcraft_testkit::temp_dir("graph-ai-filled");
for (width, live) in [(None, true), (Some(8.0), true), (Some(150.0), false)] {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
let csv = ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,1,6";
let id = s.execute("graph.create", &json!({"type": "line", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap()["id"]
.as_u64()
.unwrap();
let mut options = json!({"id": id, "filledLines": true});
if let Some(w) = width {
options["lineWidth"] = json!(w);
}
s.execute("graph.setType", &options).unwrap();
let written = spec(&s, NodeId(id));
assert_eq!((written.filled_lines, written.line_width), (true, width));
for (name, version) in [("v7.ai", Some("7")), ("pdf.ai", None)] {
let path = dir.join(format!("{width:?}-{name}"));
let mut p = json!({"path": path, "format": "ai"});
if let Some(v) = version {
p["aiVersion"] = json!(v);
}
let r = s.execute("file.saveAs", &p).unwrap();
let notes = r["warnings"].as_array().cloned().unwrap_or_default();
let warned = notes.iter().any(|w| w.as_str().is_some_and(|w| w.starts_with("graphs are written as their art")));
assert_eq!(warned, !live, "{width:?} {name}: {r}");
let mut again = Session::new();
again.execute("document.open", &json!({"path": path})).unwrap();
let mut graphs = vec![];
again.doc().unwrap().doc.walk(|n| graphs.extend(n.extras().graph.as_deref().map(|g| (n.id, g.clone()))));
assert_eq!(graphs.len(), usize::from(live), "{width:?} {name}");
if let Some((gid, g)) = graphs.first() {
assert_eq!((g.kind, g.cells(), g.filled_lines, g.line_width), (written.kind, written.cells(), true, width), "{width:?} {name}");
assert_eq!(g.filled_line_width(), written.filled_line_width(), "{width:?} {name}");
// With Draw Filled Lines turned off, each series draws its thin 1 pt line again.
again.execute("select.set", &json!({"ids": [gid.0]})).unwrap();
again.execute("graph.setType", &json!({"id": gid.0, "filledLines": false})).unwrap();
for series in 0..2 {
let line = series_parts(&again, *gid, series)
.into_iter()
.any(|p| p.appearance.fill_paint().is_none() && !p.appearance.stroke_paint().is_none() && p.appearance.stroke_width() == 1.0);
assert!(line, "{width:?} {name}: series {series} draws no thin line");
}
}
}
}
}
/// A default legend swatch has the stroke paint and weight of its series' marks, beside the plot or across the top: the
/// thin white line of stacked columns and bars, areas and pie wedges, and none on columns and bars. A stroke color kept
/// on the series, with or without a weight of its own, is on the swatch too.
+1 -10
View File
@@ -6,6 +6,7 @@ use vectorcraft_doc::text::INLINE_MAX_SCALE;
use vectorcraft_doc::{Document, InlineArt, NodeId, NodeKind, TextRun};
use vectorcraft_text::edit;
use super::brushsym::current_symbol;
use super::typecmd::refresh_bounds;
use super::{CommandSpec, EngineError, Result, Session, bad, cmd, has_doc, id_param, str_param};
@@ -97,13 +98,3 @@ fn insert_inline(s: &mut Session, p: &Value) -> Result<Value> {
}
Ok(json!({"id": id.0, "caret": caret}))
}
/// The Symbols panel's current symbol, else the first one.
fn current_symbol(d: &Document) -> Option<String> {
d.unknown
.get("currentSymbol")
.and_then(Value::as_str)
.filter(|n| d.symbols.iter().any(|s| s.name == *n))
.map(str::to_string)
.or_else(|| d.symbols.first().map(|s| s.name.clone()))
}
+56 -17
View File
@@ -509,7 +509,16 @@ pub(crate) fn linked_files(d: &Document, base: LinkBase) -> Vec<LinkedFile> {
.filter(|g| seen.insert(g.link.path.clone()))
.map(|g| {
let named = fileio::format_for_name(g.link.name()).or_else(|| fileio::readable_format_for_name(g.link.name()));
let own = |b: &&ImageBlob| !b.is_proxy() && named.is_some_and(|f| f.mime == b.mime);
// A placed document's PostScript bytes are its file's own only when its name is one that
// PostScript is read from (`.eps`, `.epsf`, `.ps`, a PostScript `.ai` or `.ait`).
let postscript_name = matches!(fileio::extension(g.link.name()).as_str(), "eps" | "epsf" | "ps" | "ai" | "ait");
let postscript = |b: &ImageBlob| {
g.document.is_some()
&& postscript_name
&& b.mime == super::place::document::POSTSCRIPT
&& super::place::document::is_postscript(&b.bytes)
};
let own = |b: &&ImageBlob| !b.is_proxy() && (named.is_some_and(|f| f.mime == b.mime) || postscript(b));
let found = locate(&g.link, base);
let found_path = found.as_ref().map(|f| f.path.clone());
let bytes = found.and_then(|mut f| f.read().ok()).or_else(|| d.images.get(&g.key).filter(own).map(|b| b.bytes.to_vec()));
@@ -593,8 +602,8 @@ pub(crate) fn store_image(d: &mut Document, key: &str, full: ImageBlob, linked:
/// Whether `bytes` are a PNG, JPEG, GIF or WebP file: the formats [`fileio::raster_image`] keeps
/// as they are after reading only their header.
pub(crate) fn kept_unread(bytes: &[u8]) -> bool {
use image::ImageFormat as F;
matches!(image::guess_format(bytes), Ok(F::Png | F::Jpeg | F::Gif | F::WebP))
use craft_image_codecs::Format as F;
matches!(craft_image_codecs::detect(bytes), Some(F::Png | F::Jpeg | F::Gif | F::WebP))
}
/// `blob`, an image [`fileio::raster_image`] read from a file, ready to keep. When `unread` (the
@@ -2361,12 +2370,20 @@ fn format_label(d: &Document, im: &ImageObject) -> &'static str {
.map_or("Image", |f| f.label)
}
/// A placed document's `links.list` fields: `format` (`VectorCraft`, or the PDF or `.ai` file's
/// format), `document: true` and its artboard's or page's size (`pageWidth`, `pageHeight`, pt)
/// instead of pixels.
fn document_row(p: &PlacedDocument) -> Value {
let pdf = fileio::format_for_name(p.link.name()).filter(|f| matches!(f.id, "pdf" | "ai" | "ait"));
json!({ "format": pdf.map_or("VectorCraft", |f| f.label), "document": true, "pageWidth": p.width, "pageHeight": p.height })
/// A placed document's `links.list` fields (of `d`): `format` (`VectorCraft`, the PDF or `.ai`
/// file's format, or for an EPS or PostScript file `EPS` or `PostScript`), `document: true` and its
/// artboard's or page's size (`pageWidth`, `pageHeight`, pt) instead of pixels. A PostScript `.ai`
/// is told by its stored bytes or, when a save kept only its preview, by its key.
fn document_row(d: &Document, p: &PlacedDocument) -> Value {
use super::place::document::{POSTSCRIPT, is_postscript_ai_key};
let postscript = d.images.get(&p.key).is_some_and(|b| b.mime == POSTSCRIPT) || is_postscript_ai_key(&p.key);
let format = match fileio::format_for_name(p.link.name()) {
Some(f) if matches!(f.id, "eps" | "ps") => f.label,
_ if postscript => "PostScript",
Some(f) if matches!(f.id, "pdf" | "ai" | "ait") => f.label,
_ => "VectorCraft",
};
json!({ "format": format, "document": true, "pageWidth": p.width, "pageHeight": p.height })
}
/// The size in bytes of the file that link `l` (of `st`) names, as Link Info shows it: the file's
@@ -2488,7 +2505,7 @@ fn list(s: &mut Session, p: &Value) -> Result<Value> {
}
(im.link.as_ref(), row)
}
NodeKind::PlacedDocument(p) => (Some(&p.link), document_row(p)),
NodeKind::PlacedDocument(p) => (Some(&p.link), document_row(&doc, p)),
_ => continue,
};
let name = link.map_or_else(|| n.display_name(), |l| l.name().to_string());
@@ -2639,12 +2656,34 @@ const UNEMBED_EXTS: &[&str] = &["png", "jpg", "jpeg", "gif", "webp", "tif", "tif
/// Encoded image `bytes` re-encoded in the format of extension `ext` (JPEG without alpha).
fn convert_image(bytes: &[u8], ext: &str) -> std::result::Result<Vec<u8>, String> {
let format = image::ImageFormat::from_extension(ext).ok_or_else(|| format!("can't write .{ext} images"))?;
let img = image::load_from_memory(bytes).map_err(|e| e.to_string())?;
let img = if format == image::ImageFormat::Jpeg { image::DynamicImage::ImageRgb8(img.to_rgb8()) } else { img };
let mut out = vec![];
img.write_to(&mut std::io::Cursor::new(&mut out), format).map_err(|e| e.to_string())?;
Ok(out)
let format = match ext.to_ascii_lowercase().as_str() {
"png" => craft_image_codecs::Format::Png,
"jpg" | "jpeg" => craft_image_codecs::Format::Jpeg,
"gif" => craft_image_codecs::Format::Gif,
"webp" => craft_image_codecs::Format::WebP,
"tif" | "tiff" => craft_image_codecs::Format::Tiff,
"bmp" => craft_image_codecs::Format::Bmp,
_ => return Err(format!("can't write .{ext} images")),
};
let mut opts = craft_image_codecs::DecodeOptions::default();
opts.limits.max_alloc = vectorcraft_doc::MAX_RASTER_ALLOC;
opts.limits.max_width = u32::MAX;
opts.limits.max_height = u32::MAX;
let img = craft_image_codecs::decode_with(bytes, &opts).map_err(|e| e.to_string())?;
let raw = if format == craft_image_codecs::Format::Jpeg {
let rgb: Vec<u8> = img.to_rgba8().as_chunks::<4>().0.iter().flat_map(|p| [p[0], p[1], p[2]]).collect();
craft_image_codecs::Image::from_raw(
img.width(),
img.height(),
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U8,
rgb,
)
.map_err(|e| e.to_string())?
} else {
img
};
craft_image_codecs::encode(&raw, format, &craft_image_codecs::EncodeOptions::default()).map_err(|e| e.to_string())
}
fn unembed(s: &mut Session, p: &Value) -> Result<Value> {
@@ -2744,7 +2783,7 @@ fn placed_info(st: &crate::DocState, doc: &Document, id: NodeId) -> Result<Value
let NodeKind::PlacedDocument(pl) = &n.kind else { return Err(bad("links.info", format!("object {} is not a placed document", id.0))) };
let size = n.geometric_bounds().unwrap_or_default();
let (scale, rotation) = scale_rotation(pl.xf, (1.0, 1.0));
let mut out = document_row(pl);
let mut out = document_row(doc, pl);
let fields = [
("id", json!(id.0)),
("name", json!(n.display_name())),
+39 -21
View File
@@ -719,10 +719,16 @@ fn cmyk_raster(
if alpha.iter().all(|&a| a == 255) {
return Ok((blob, None));
}
let mask = image::GrayImage::from_raw(img.width, img.height, alpha)
.ok_or_else(|| EngineError::Other("the image's transparency doesn't fit it".into()))?;
let mut png = Vec::new();
mask.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).map_err(|e| EngineError::Other(e.to_string()))?;
let mask = craft_image_codecs::Image::from_raw(
img.width,
img.height,
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U8,
alpha,
)
.map_err(|_| EngineError::Other("the image's transparency doesn't fit it".into()))?;
let png = craft_image_codecs::encode(&mask, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map_err(|e| EngineError::Other(e.to_string()))?;
Ok((blob, Some(png)))
}
@@ -1072,9 +1078,16 @@ pub(crate) fn check_resample_size(sw: u32, sh: u32, w: u32, h: u32) -> Result<()
/// `img` as PNG bytes.
fn encode_png(img: &image::RgbaImage) -> Result<Vec<u8>> {
let mut png = Vec::new();
img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).map_err(|e| bad("object.cropImage", e.to_string()))?;
Ok(png)
let fail = |e: craft_image_codecs::CodecError| bad("object.cropImage", e.to_string());
let raw = craft_image_codecs::Image::from_raw(
img.width(),
img.height(),
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U8,
img.as_raw().clone(),
)
.map_err(fail)?;
craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).map_err(fail)
}
fn crop_image(s: &mut Session, p: &Value) -> Result<Value> {
@@ -1221,22 +1234,24 @@ fn crop_image(s: &mut Session, p: &Value) -> Result<Value> {
/// The image's pixels as RGBA, held to the allowance opening a raster has.
fn decode_rgba(c: &str, blob: &vectorcraft_doc::ImageBlob) -> Result<image::RgbaImage> {
// Print rasters run to gigabytes decoded: the same allowance opening them has.
let reader = || {
image::ImageReader::new(std::io::Cursor::new(blob.bytes.as_slice()))
.with_guessed_format()
.map_err(|_| bad(c, "the image's pixels can't be read"))
};
// The image's size as RGBA, read from its header, is held to that allowance before anything
// is decoded (#1717).
let (w, h) = reader()?.into_dimensions().map_err(|e| bad(c, format!("the image's pixels can't be read: {e}")))?;
if u64::from(w) * u64::from(h) > crate::cmd::fileio::MAX_RASTER_ALLOC / 4 {
let header = vectorcraft_doc::header_size(&blob.bytes);
if let Some((w, h)) = header
&& u64::from(w) * u64::from(h) > crate::cmd::fileio::MAX_RASTER_ALLOC / 4
{
return Err(bad(c, format!("an image of {w} × {h} pixels is too large to draw")));
}
let mut reader = reader()?;
let mut limits = image::Limits::default();
limits.max_alloc = Some(crate::cmd::fileio::MAX_RASTER_ALLOC);
reader.limits(limits);
Ok(reader.decode().map_err(|e| bad(c, format!("the image's pixels can't be read: {e}")))?.to_rgba8())
let mut opts = craft_image_codecs::DecodeOptions::default();
opts.limits.max_pixels = crate::cmd::fileio::MAX_RASTER_ALLOC / 4;
opts.limits.max_alloc = crate::cmd::fileio::MAX_RASTER_ALLOC;
let img = craft_image_codecs::decode_with(&blob.bytes, &opts).map_err(|e| match e {
// Within the allowance from its header: a file that can't hold the pixels it declares.
craft_image_codecs::CodecError::LimitExceeded(_) if header.is_none() => bad(c, "the image is too large to draw"),
_ => bad(c, format!("the image's pixels can't be read: {e}")),
})?;
let (w, h) = img.dimensions();
image::RgbaImage::from_raw(w, h, img.to_rgba8()).ok_or_else(|| bad(c, "the image's pixels can't be read"))
}
/// Crop Image's trim: the image cut to the box of its pixels that aren't fully transparent, the
@@ -1265,9 +1280,12 @@ fn trim_image(s: &mut Session, id: NodeId, im: ImageObject) -> Result<Value> {
return Ok(json!({ "id": id.0, "width": w, "height": h, "trimmed": false }));
}
let cut = image::imageops::crop_imm(&px, x0, y0, x1 - x0, y1 - y0).to_image();
let mut png = Vec::new();
cut.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).map_err(|e| bad(C, e.to_string()))?;
let (cw, ch) = (x1 - x0, y1 - y0);
let raw =
craft_image_codecs::Image::from_raw(cw, ch, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, cut.into_raw())
.map_err(|e| bad(C, e.to_string()))?;
let png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map_err(|e| bad(C, e.to_string()))?;
put_pixels(s, id, png, cw, ch, im.xf * Affine::translate((f64::from(x0), f64::from(y0))))?;
Ok(json!({ "id": id.0, "width": cw, "height": ch, "trimmed": true }))
}
+3 -1
View File
@@ -149,7 +149,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Cut Path at Selected Anchor Points",
[],
None,
"{} cut the paths at their direct-selected anchors (one undo step): a closed path opens there, an open one becomes one path per piece; one of each cut's two coincident anchors stays selected → {ids}",
"{} cut the paths at their direct-selected anchors (one undo step): a closed path opens there, an open one becomes one path per piece; one of each cut's two coincident anchors stays selected; the paths keep the source's fill and stroke settings except that every stroke's alignment becomes Center (in a path of several subpaths, the other subpaths' strokes too) → {ids}",
has_anchors,
cut_at_anchors
),
@@ -1858,6 +1858,8 @@ fn cut_at_anchors(s: &mut Session, _: &Value) -> Result<Value> {
let (mut all, mut picked) = (vec![], vec![]);
let mut cut = Beside::replacing(d, &cuts.iter().map(|(id, ..)| *id).collect::<Vec<_>>());
for (id, subs, starts) in cuts {
// The paths a cut makes keep the source's appearance with every stroke centered.
super::draw2::center_strokes(d, id);
// A path of one subpath becomes one path per piece (the first keeps the id); the
// pieces of a compound shape stay subpaths of it.
if d.node(id).and_then(|n| n.path_data()).is_some_and(|pd| pd.subpaths.len() == 1) {
+162 -38
View File
@@ -9,7 +9,7 @@ use serde_json::{Value, json};
use vectorcraft_color::BlendMode;
use vectorcraft_doc::appearance::{AppearanceItem, StrokeLayer};
use vectorcraft_doc::{AnchorRef, Appearance, Document, Node, NodeId, NodeKind, SegmentRef, TextObject};
use vectorcraft_geom::{FillRule, PathData};
use vectorcraft_geom::{FillRule, PathData, SubPath};
use vectorcraft_pathops as po;
use vectorcraft_pathops::{BoolOp, PathfinderOp};
@@ -352,6 +352,94 @@ pub(crate) fn pf_leaves(d: &Document, n: &Node, out: &mut Vec<Node>) {
}
}
/// The region a clip group's members show through: its clipping path's outline
/// ([`vectorcraft_render::effects::clip_outline`]), cut by the clip groups around it.
struct Clip {
path: PathData,
rule: FillRule,
}
/// Does `path` have an anchor or handle that isn't a finite number?
fn has_invalid_coordinates(path: &PathData) -> bool {
path.subpaths.iter().flat_map(|sp| &sp.anchors).any(|a| [a.p, a.h_in, a.h_out].iter().any(|q| !(q.x.is_finite() && q.y.is_finite())))
}
/// A Pathfinder operation's leaf shape ([`pf_leaves`]) with the region its clip groups show it
/// through, `None` outside any clip group.
type ClippedLeaf = (Node, Option<Arc<Clip>>);
/// [`pf_leaves`], each with the region the clip groups it is in show it through (#8093). A clip
/// group's clipping path is not a leaf, and the members of one whose clipping path clips by nothing
/// are hidden, as on the canvas: their region is empty.
fn clipped_pf_leaves(d: &Document, n: &Node, clip: Option<&Arc<Clip>>, precision: f64, out: &mut Vec<ClippedLeaf>) -> Result<()> {
let (NodeKind::Group { children, clip: clips } | NodeKind::Layer { children, clip: clips, .. }) = &n.kind else {
let mut lv = vec![];
leaves(n, &mut lv);
out.extend(lv.into_iter().map(|l| (l, clip.cloned())));
return Ok(());
};
let hook = |c: &Node| vectorcraft_render::effects::outline_object(Some(d), c);
if let Some(art) = vectorcraft_render::effects::compound_shape_art(Some(d), n, Some(&hook)) {
out.push((art, clip.cloned()));
return Ok(());
}
if !*clips {
return children.iter().try_for_each(|c| clipped_pf_leaves(d, c, clip, precision, out));
}
let Some((first, rest)) = children.split_first() else { return Ok(()) };
let mut region = match vectorcraft_render::effects::clip_outline(first) {
Some((outline, rule)) => Clip { path: PathData::from_bezpath(&outline), rule },
None => Clip { path: PathData::default(), rule: FillRule::NonZero },
};
if has_invalid_coordinates(&region.path) {
return Err(EngineError::Other("paths contain invalid coordinates".into()));
}
if let Some(outer) = clip.filter(|_| !region.path.is_empty()) {
let path = po::try_boolean(&region.path, region.rule, &outer.path, outer.rule, BoolOp::Intersect, precision)
.map_err(|e| EngineError::Other(e.to_string()))?;
region = Clip { path, rule: FillRule::NonZero };
}
let region = Arc::new(region);
rest.iter().try_for_each(|c| clipped_pf_leaves(d, c, Some(&region), precision, out))
}
/// `path`, filled by `rule`, where `clip` shows it: its area intersected with the region, filled
/// non-zero, and with `lines` (Divide, whose open contours cut) its open contours' parts inside the
/// region, so their hidden parts cut nothing.
fn clipped(path: PathData, rule: FillRule, clip: &Clip, lines: bool, precision: f64) -> Result<(PathData, FillRule)> {
if has_invalid_coordinates(&path) {
// Left as it is for the operation to refuse ("paths contain invalid coordinates").
return Ok((path, rule));
}
let (Some(within), Some(bounds)) = (clip.path.control_bounds(), path.control_bounds()) else { return Ok((PathData::default(), rule)) };
if within.intersect(bounds).is_zero_area() && !bounds.is_zero_area() {
// Wholly outside the region (a line's bounds may be flat, so only an area's are trusted).
return Ok((PathData::default(), rule));
}
let (open, closed): (Vec<SubPath>, Vec<SubPath>) =
if lines { path.subpaths.into_iter().partition(|sp| !sp.closed) } else { (vec![], path.subpaths) };
let mut subs = vec![];
if !closed.is_empty() {
let area = po::try_boolean(&PathData::new(closed), rule, &clip.path, clip.rule, BoolOp::Intersect, precision)
.map_err(|e| EngineError::Other(e.to_string()))?;
subs.extend(area.subpaths);
}
if !open.is_empty() {
let open = PathData::new(open);
// Each segment is sampled at least every 1/16 of the region's shorter side (and 24 times),
// and the crossings found are refined: a part of the region narrower than that, which a
// line crosses between two samples, can be missed.
let step = (within.width().min(within.height()) / 16.0).max(precision);
let outline = clip.path.to_bezpath();
let outside = |q| !vectorcraft_geom::hit::fill_contains(&outline, clip.rule, q);
match super::draw2::erase_outline(&open, step, &outside) {
Some(pieces) => subs.extend(pieces.into_iter().flat_map(|p| p.subpaths)),
None => subs.extend(open.subpaths),
}
}
Ok((PathData::new(subs), FillRule::NonZero))
}
/// How many shapes a Pathfinder operation takes from `n` selected alone: its leaf shapes, however
/// deep its groups nest (an expanded stroke is a group inside the group, #1635). Inside a compound
/// shape, a blend, an envelope or another live object and a symbol instance count as one shape
@@ -591,6 +679,10 @@ fn run_pf(s: &mut Session, p: &Value, op: PathfinderOp) -> Result<Value> {
}
let shape_mode =
matches!(op, PathfinderOp::Unite | PathfinderOp::MinusFront | PathfinderOp::Intersect | PathfinderOp::Exclude | PathfinderOp::MinusBack);
// An operand its clipping masks hide altogether is an empty shape for the operations whose
// result it changes (Intersect gives nothing, Minus Front loses its back object, Minus Back its
// front one, Crop its cropping shape); the others leave it out, which gives the same art.
let keeps_hidden = matches!(op, PathfinderOp::Intersect | PathfinderOp::MinusFront | PathfinderOp::MinusBack | PathfinderOp::Crop);
let label = pf_label(op);
let options = pf_options(s, p, &format!("object.pathfinder.{}", pf_id(op)))?;
let ids = s.edit(label, |d, sel| {
@@ -598,63 +690,95 @@ fn run_pf(s: &mut Session, p: &Value, op: PathfinderOp) -> Result<Value> {
let mut styles: Vec<Style> = vec![];
let mut shapes: Vec<po::Shape> = vec![];
let mut names: Vec<Option<String>> = vec![];
let mut push = |mut path: PathData, rule: FillRule, mut st: Style, name: Option<String>| {
if path.is_empty() {
return;
}
// Trim, Merge and Crop remove any strokes (and Merge then merges by fill alone), as the
// public Pathfinder documentation describes.
if matches!(op, PathfinderOp::Trim | PathfinderOp::Merge | PathfinderOp::Crop) {
st.appearance.items.retain(|i| !matches!(i, AppearanceItem::Stroke(_)));
}
if op == PathfinderOp::Divide && st.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Fill(f) if !f.paint.is_none())) {
// Filled open contours keep their implicit closing edge. A zero-area line
// stays a cutter; normalised area also catches zero-signed-area self crossings.
for sub in path.subpaths.iter_mut().filter(|sp| !sp.closed) {
sub.closed = po::encloses_area(sub) || po::area(&PathData::single(sub.clone()), rule) > 0.0;
// `hidden`: the masks hide the operand altogether, and its empty path stands for it.
let mut push =
|mut path: PathData, mut rule: FillRule, mut st: Style, name: Option<String>, clip: Option<&Clip>, hidden: bool| -> Result<()> {
if path.is_empty() && !(hidden && keeps_hidden) {
return Ok(());
}
}
let key = match styles.iter().position(|x| *x == st) {
Some(k) => k,
None => {
styles.push(st);
styles.len() - 1
// Trim, Merge and Crop remove any strokes (and Merge then merges by fill alone), as the
// public Pathfinder documentation describes.
if matches!(op, PathfinderOp::Trim | PathfinderOp::Merge | PathfinderOp::Crop) {
st.appearance.items.retain(|i| !matches!(i, AppearanceItem::Stroke(_)));
}
if op == PathfinderOp::Divide && st.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Fill(f) if !f.paint.is_none())) {
// Filled open contours keep their implicit closing edge. A zero-area line
// stays a cutter; normalised area also catches zero-signed-area self crossings.
for sub in path.subpaths.iter_mut().filter(|sp| !sp.closed) {
sub.closed = po::encloses_area(sub) || po::area(&PathData::single(sub.clone()), rule) > 0.0;
}
}
if let Some(clip) = clip {
(path, rule) = clipped(path, rule, clip, op == PathfinderOp::Divide, options.precision)?;
if path.is_empty() && !keeps_hidden {
return Ok(());
}
}
let key = match styles.iter().position(|x| *x == st) {
Some(k) => k,
None => {
styles.push(st);
styles.len() - 1
}
};
shapes.push(po::Shape::new(path, rule, key as u64));
names.push(name);
Ok(())
};
shapes.push(po::Shape::new(path, rule, key as u64));
names.push(name);
};
// Whether a clip group was among the selection, for the error when its mask hides it all.
let mut masked = false;
for id in &roots {
let n = d.node(*id).ok_or(EngineError::NoNode(*id))?;
let mut lv = vec![];
pf_leaves(d, n, &mut lv);
clipped_pf_leaves(d, n, None, options.precision, &mut lv)?;
masked |= lv.iter().any(|(_, clip)| clip.is_some());
if lv.is_empty() {
continue;
}
if shape_mode
&& roots.len() > 1
&& lv.len() > 1
&& let Some(top) = lv.last()
{
// Among other objects, a group acts as one shape (the union of its leaves) with
// its top leaf's style. Selected alone, its members are the shapes (#1450).
let parts: Vec<(PathData, FillRule)> = lv.iter().filter_map(node_path).collect();
let refs: Vec<(&PathData, FillRule)> = parts.iter().map(|(p, r)| (p, *r)).collect();
let name = n.name.clone().or_else(|| lv.iter().find_map(|l| l.name.clone()));
if shape_mode && roots.len() > 1 && lv.len() > 1 {
// Among other objects, a group acts as one shape (the union of its leaves, each
// where its clip groups show it) with the style of its top leaf that shows.
// Selected alone, its members are the shapes (#1450).
let mut parts: Vec<(&Node, PathData, FillRule)> = vec![];
for (l, clip) in &lv {
let Some((p, r)) = node_path(l) else { continue };
let (p, r) = match clip {
Some(clip) => clipped(p, r, clip, false, options.precision)?,
None => (p, r),
};
if !p.is_empty() {
parts.push((l, p, r));
}
}
let name = n.name.clone().or_else(|| parts.iter().find_map(|(l, ..)| l.name.clone()));
let Some((top, ..)) = parts.last() else {
// The masks hide the whole group.
if let Some((top, _)) = lv.last() {
push(PathData::default(), FillRule::NonZero, style_of(top), name, None, true)?;
}
continue;
};
let top = *top;
let refs: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, p, r)| (p, *r)).collect();
push(
po::try_unite_all_with(&refs, options.precision).map_err(|e| EngineError::Other(e.to_string()))?,
FillRule::NonZero,
style_of(top),
name,
);
None,
false,
)?;
} else {
for l in &lv {
for (l, clip) in &lv {
if let Some((p, r)) = node_path(l) {
push(p, r, style_of(l), n.name.clone().or_else(|| l.name.clone()));
push(p, r, style_of(l), n.name.clone().or_else(|| l.name.clone()), clip.as_deref(), clip.is_some())?;
}
}
}
}
if shapes.is_empty() && masked {
return Err(EngineError::Other(format!("{label}: the clipping masks hide the selected art")));
}
if shapes.is_empty() {
return Err(EngineError::Other(format!("{label}: select paths, compound paths, groups or text")));
}
File diff suppressed because one or more lines are too long
+53 -13
View File
@@ -1,6 +1,6 @@
//! Placed documents (`file.place` of a VectorCraft document, a PDF or a `.ai` file from a file,
//! with `link`): one locked object showing an artboard of the document or a page of the PDF, a
//! [`PlacedDocument`].
//! Placed documents (`file.place` of a VectorCraft document, a PDF, a `.ai` file or an EPS file
//! from a file, with `link`): one locked object showing an artboard of the document, a page of the
//! PDF or the EPS file's art, a [`PlacedDocument`].
//!
//! The object keeps the file's bytes (in the document's images, like image data) and the link; the
//! art it shows is read from them the way placing the file without Link reads it
@@ -33,6 +33,16 @@ pub(crate) const MAX_FILE: usize = 256 << 20;
const NATIVE: [&str; 2] = ["vectorcraft", "template"];
/// The type a placed VectorCraft document's bytes are stored with (a PDF's: its format's).
const MIME: &str = "application/json";
/// The type a placed EPS or PostScript file's bytes are stored with.
pub(crate) const POSTSCRIPT: &str = "application/postscript";
/// What follows the hash in the key of a placed PostScript `.ai` file ([`key_for`]).
const AI_MARK: &str = "-ai";
/// Is `key` (of a placed document) a PostScript `.ai` file's ([`AI_MARK`])? Hashes are hex, so
/// only the mark puts `-ai-` in a key.
pub(crate) fn is_postscript_ai_key(key: &str) -> bool {
key.contains(&format!("{AI_MARK}-"))
}
/// Is `name` with `bytes` a VectorCraft document?
pub(crate) fn is_native(name: &str, bytes: &[u8]) -> bool {
@@ -44,6 +54,12 @@ pub(crate) fn is_pdf(name: &str, bytes: &[u8]) -> bool {
fileio::detect(name, bytes).is_some_and(|f| matches!(f.id, "pdf" | "ai" | "ait")) && !vectorcraft_pdf::is_postscript(bytes)
}
/// Is `bytes` an EPS file, a PostScript file or a PostScript `.ai` or `.ait` file, read by the EPS
/// importer (not a DCS file, which is placed as a linked image)?
pub(crate) fn is_postscript(bytes: &[u8]) -> bool {
vectorcraft_pdf::is_postscript(bytes) && !super::dcs::is_dcs(bytes)
}
/// The editing data of the `.ai` file `name` (`bytes`) when its PDF part is only a placeholder, or
/// can't be read:
/// the document its pages are read from ([`super::pdf_art`]), with the files it links. `None` for
@@ -60,9 +76,12 @@ pub(crate) fn editing_data(name: &str, bytes: &[u8]) -> Option<Document> {
}
}
/// The type the bytes of placed file `name` (`bytes`) are stored with: a PDF's format's, else
/// [`MIME`].
/// The type the bytes of placed file `name` (`bytes`) are stored with: a PDF's format's,
/// [`POSTSCRIPT`] for an EPS or PostScript file, else [`MIME`].
fn mime(name: &str, bytes: &[u8]) -> &'static str {
if is_postscript(bytes) {
return POSTSCRIPT;
}
fileio::detect(name, bytes).filter(|_| is_pdf(name, bytes)).map_or(MIME, |f| f.mime)
}
@@ -108,7 +127,9 @@ pub(crate) struct DocumentArt {
/// Artboard `page` (1-based) of the VectorCraft document `name` (`bytes`, read from `path` when
/// there is one, so its linked images are found), clipped to the artboard unless `bounding`; or
/// page `page` of the PDF or `.ai` file `name`, clipped to its box `page_box` unless `bounding`
/// ([`super::pdf_art`]).
/// ([`super::pdf_art`]); or the art of the EPS or PostScript file `name` ([`is_postscript`]) on
/// its page `page`, clipped to its bounding box unless `bounding`, as placing it without Link reads
/// it.
pub(crate) fn document_art(
name: &str,
bytes: &[u8],
@@ -135,7 +156,7 @@ fn opened_document_art(
) -> Result<DocumentArt> {
let file = fileio::file_name(name);
let pdf = is_pdf(name, bytes);
if !pdf && !is_native(name, bytes) {
if !pdf && !is_native(name, bytes) && !is_postscript(bytes) {
return Err(bad(cmd, format!("`{file}` isn't a VectorCraft document, a PDF or a PDF-compatible .ai file")));
}
if bytes.len() > MAX_FILE {
@@ -145,6 +166,8 @@ fn opened_document_art(
let o = fileio::LoadOptions { crop: crop_to(page_box), ..Default::default() };
return super::pdf_art(name, (bytes, opened), path, page as usize, o, bounding, cmd);
}
// A VectorCraft document, or an EPS or PostScript file: the document our EPS files carry, else
// what its PostScript draws.
let mut l = fileio::load(name, bytes)?;
// Its linked images show their files; its placed documents stay as they are, unless their
// stored bytes are lost, when resolving reads their files, which can place this one again.
@@ -292,6 +315,10 @@ fn read_source(
let hash = shared.map_or_else(|| hash_bytes(bytes), |f| f.hash.to_string());
let opened = shared.map(|f| f.opened);
let shared = shared.map(|f| f.bytes);
// A PostScript `.ai` is read with the artboard its header gives, an EPS file on its page: the
// same bytes under the two names show different art, so they have keys of their own.
let ai = is_postscript(bytes) && fileio::detect(name, bytes).is_some_and(|f| matches!(f.id, "ai" | "ait"));
let hash = if ai { format!("{hash}{AI_MARK}") } else { hash };
// The same document placed the same way is read once (placing it again is free).
let key = key_for(&hash, page, bounding, page_box);
// Resolving its links depends on where the file is and on what the caller may read, so a hit
@@ -366,17 +393,30 @@ fn preview(doc: &Document, art: &Node, frame: Rect) -> Option<Vec<u8>> {
})
.collect();
let rgba = image::RgbaImage::from_raw(w, h, px)?;
let mut out = vec![];
// Opaque but for the edge's anti-aliasing (an artboard drawn to whole pixels) and compositing's
// rounding: JPEG.
let inner = |x: u32, y: u32| x > 0 && y > 0 && x + 1 < w && y + 1 < h;
if rgba.enumerate_pixels().all(|(x, y, p)| p[3] >= 250 || !inner(x, y)) {
let rgb = image::DynamicImage::ImageRgba8(rgba).to_rgb8();
image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, 80).encode_image(&rgb).ok()?;
let raw = craft_image_codecs::Image::from_raw(
rgb.width(),
rgb.height(),
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U8,
rgb.into_raw(),
)
.ok()?;
let opts = craft_image_codecs::EncodeOptions { jpeg_quality: 80, ..Default::default() };
craft_image_codecs::encode(&raw, craft_image_codecs::Format::Jpeg, &opts).ok()
} else {
rgba.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).ok()?;
let raw = craft_image_codecs::Image::from_raw(
rgba.width(),
rgba.height(),
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U8,
rgba.into_raw(),
)
.ok()?;
craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()
}
Some(out)
}
/// `s` stored in `d` (objects showing the same thing share one blob).
@@ -40,6 +40,7 @@ pub(super) const ALLOWED: &[&str] = &[
"addon.image.colorMask",
"addon.image.removeBackground",
"addon.image.removeColorMask",
"addon.packaging.check",
"addon.packaging.roles",
"addon.packaging.setRole",
"addon.packaging.setRoleSwatch",
+4 -1
View File
@@ -314,7 +314,10 @@ pub const PREF_SPECS: &[PrefSpec] = &[
("or", "Odia"),
("as", "Assamese"),
("sa", "Sanskrit"),
("ur", "Urdu")
("ur", "Urdu"),
("ne", "Nepali"),
("kok", "Konkani"),
("sd", "Sindhi")
])
),
p!("hyphenationExceptions", "Hyphenation", "", "Exceptions (comma separated)", text),
+71 -4
View File
@@ -1984,7 +1984,41 @@ mod tests {
/// A `size` px image of one color `rgba`.
fn blob(rgba: [u8; 4], size: u32) -> ImageBlob {
let mut png = Vec::new();
image::RgbaImage::from_pixel(size, size, image::Rgba(rgba)).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
{
let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(size, size, image::Rgba(rgba))).into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| png.extend_from_slice(&__b))
}
.unwrap();
ImageBlob::png(png)
}
@@ -2025,9 +2059,42 @@ mod tests {
let d = Document::new(100.0, 100.0);
let red = blob([255, 0, 0, 255], 64);
let mut png = Vec::new();
image::RgbaImage::from_fn(64, 64, |x, y| image::Rgba(if x >= 56 && y >= 56 { [0, 0, 255, 255] } else { [255, 0, 0, 255] }))
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
.unwrap();
{
let __dyn: image::DynamicImage =
(image::RgbaImage::from_fn(64, 64, |x, y| image::Rgba(if x >= 56 && y >= 56 { [0, 0, 255, 255] } else { [255, 0, 0, 255] }))).into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| png.extend_from_slice(&__b))
}
.unwrap();
let corner = ImageBlob::png(png);
let mut t = Theme::new(&d);
let whole = ImageRead { clip: None, ..clipped(&corner, 64.0, 4) };
+140 -44
View File
@@ -4,7 +4,7 @@ use std::collections::BTreeSet;
use serde_json::{Value, json};
use vectorcraft_color::Paint;
use vectorcraft_doc::{Document, LockedArtboards, Node, NodeId, NodeKind};
use vectorcraft_doc::{AnchorRef, Document, LockedArtboards, Node, NodeId, NodeKind, Selection};
use vectorcraft_tools::builder::is_live_paint;
use super::object::can_align;
@@ -930,52 +930,145 @@ fn anchors_many(s: &mut Session, p: &Value) -> Result<Value> {
None if bool_or(p, "add", false) => "add",
None => "set",
};
s.select(|d, sel| {
if mode == "set" {
sel.clear();
}
for (id, refs) in items {
// A segment pick's endpoints aren't selected anchors: start from none of them.
let segment_pick = sel.segments.remove(&id).is_some();
let all: BTreeSet<(usize, usize)> =
d.node(id).and_then(|n| n.path_data()).map(|p| p.anchors().map(|(s, i, _)| (s, i)).collect()).unwrap_or_default();
// Anything but a path is selected, toggled or deselected as a whole.
if all.is_empty() {
match mode {
"toggle" => sel.toggle(id),
"subtract" => sel.remove(id),
_ => sel.add(id),
}
continue;
}
// From the anchors selected now (all of them for a path selected as a whole).
let now = match sel.partial(id) {
_ if segment_pick => BTreeSet::new(),
Some(a) => a.clone(),
None if sel.contains(id) => all.clone(),
None => BTreeSet::new(),
};
let refs: BTreeSet<(usize, usize)> = refs.intersection(&all).copied().collect();
let next: BTreeSet<(usize, usize)> = match mode {
"toggle" => now.symmetric_difference(&refs).copied().collect(),
"subtract" => now.difference(&refs).copied().collect(),
_ => now.union(&refs).copied().collect(),
};
if next.is_empty() {
sel.remove(id);
continue;
}
sel.add(id);
if next.len() < all.len() {
sel.anchors.insert(id, next);
} else {
sel.anchors.remove(&id);
}
}
})?;
s.select(|d, sel| select_anchor_items(d, sel, items, mode))?;
ok()
}
/// `select.anchorsMany`'s change to `sel`: each item in order, with the selected objects kept in a
/// [`Members`] map while the items run, so that an item's membership check and change don't go
/// through `sel.objects`.
fn select_anchor_items(d: &Document, sel: &mut Selection, items: Vec<(NodeId, BTreeSet<AnchorRef>)>, mode: &str) {
if mode == "set" {
sel.clear();
}
if items.is_empty() {
return;
}
let mut members = Members::of(sel);
for (id, refs) in items {
// A segment pick's endpoints aren't selected anchors: start from none of them.
let segment_pick = sel.segments.remove(&id).is_some();
let all: BTreeSet<AnchorRef> =
d.node(id).and_then(|n| n.path_data()).map(|p| p.anchors().map(|(s, i, _)| (s, i)).collect()).unwrap_or_default();
// Anything but a path is selected, toggled or deselected as a whole.
if all.is_empty() {
match mode {
"toggle" => members.toggle(sel, id),
"subtract" => members.remove(sel, id),
_ => members.add(sel, id),
}
continue;
}
// From the anchors selected now (all of them for a path selected as a whole).
let now = match sel.partial(id) {
_ if segment_pick => BTreeSet::new(),
Some(a) => a.clone(),
None if members.contains(id) => all.clone(),
None => BTreeSet::new(),
};
let refs: BTreeSet<AnchorRef> = refs.intersection(&all).copied().collect();
let next: BTreeSet<AnchorRef> = match mode {
"toggle" => now.symmetric_difference(&refs).copied().collect(),
"subtract" => now.difference(&refs).copied().collect(),
_ => now.union(&refs).copied().collect(),
};
if next.is_empty() {
members.remove(sel, id);
continue;
}
members.add(sel, id);
if next.len() < all.len() {
sel.anchors.insert(id, next);
} else {
sel.anchors.remove(&id);
}
}
members.finish(sel);
}
/// The selected objects of a [`Selection`] while [`select_anchor_items`] changes them. Each
/// selected id maps to the activation that selected it: 0 for the objects selected before, and
/// a new number for each later [`Members::add`] of an unselected id, which `added` lists in order.
/// [`Members::finish`] writes them back to `objects`.
struct Members {
live: std::collections::HashMap<NodeId, usize>,
added: Vec<(NodeId, usize)>,
removed: bool,
}
impl Members {
fn of(sel: &Selection) -> Self {
count_objects_walk();
Self { live: sel.objects.iter().map(|id| (*id, 0)).collect(), added: Vec::new(), removed: false }
}
fn contains(&self, id: NodeId) -> bool {
self.live.contains_key(&id)
}
/// [`Selection::add`]: clears what any selection change clears, and selects `id` at the end
/// unless it is selected.
fn add(&mut self, sel: &mut Selection, id: NodeId) {
sel.target = None;
sel.slices.clear();
sel.symbol_part = None;
sel.on_path_member = None;
if let std::collections::hash_map::Entry::Vacant(e) = self.live.entry(id) {
let activation = self.added.len() + 1;
e.insert(activation);
self.added.push((id, activation));
}
}
/// [`Selection::remove`]: clears what any selection change clears, and deselects `id` with
/// its anchors, segments, and the key or key anchor it is.
fn remove(&mut self, sel: &mut Selection, id: NodeId) {
sel.target = None;
sel.slices.clear();
sel.symbol_part = None;
sel.on_path_member = None;
if self.live.remove(&id).is_some() {
self.removed = true;
}
sel.anchors.remove(&id);
sel.segments.remove(&id);
if sel.key == Some(id) {
sel.key = None;
}
if sel.key_anchor.is_some_and(|(k, _)| k == id) {
sel.key_anchor = None;
}
}
/// [`Selection::toggle`].
fn toggle(&mut self, sel: &mut Selection, id: NodeId) {
if self.contains(id) { self.remove(sel, id) } else { self.add(sel, id) }
}
/// Writes the selected objects to `sel.objects`: the slots of the objects selected before and
/// still selected by that activation, in their order, then the ids selected since and still
/// selected by the activation that added them, in the order they were added.
fn finish(self, sel: &mut Selection) {
if self.removed {
count_objects_walk();
sel.objects.retain(|id| self.live.get(id) == Some(&0));
}
sel.objects.extend(self.added.into_iter().filter(|(id, n)| self.live.get(id) == Some(n)).map(|(id, _)| id));
}
}
#[cfg(test)]
thread_local! {
/// Tests: how many walks [`select_anchor_items`] made over the selected objects on this thread.
pub(crate) static OBJECTS_WALKS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// Tests: count one walk over the selected objects.
fn count_objects_walk() {
#[cfg(test)]
OBJECTS_WALKS.set(OBJECTS_WALKS.get() + 1);
}
/// Select › Same › Fill/Stroke Color: is `a` the same colour as `b`? Tints of one global or spot
/// swatch are, unless `tint` (General › Select Same Tint %) asks for the same tint too.
pub(crate) fn same_paint(a: &Paint, b: &Paint, tint: bool) -> bool {
@@ -1287,3 +1380,6 @@ fn not_pixel_aligned(s: &mut Session, _: &Value) -> Result<Value> {
s.select(|_, sel| sel.set(ids))?;
Ok(json!({ "count": s.doc()?.selection.objects.len() }))
}
#[cfg(test)]
mod tests;
+286
View File
@@ -0,0 +1,286 @@
//! `select.anchorsMany`'s item loop ([`select_anchor_items`]) against a loop that changes the
//! selection one item at a time through [`Selection::add`], [`Selection::remove`] and
//! [`Selection::toggle`].
use std::collections::{BTreeSet, HashSet};
use std::sync::Arc;
use std::time::{Duration, Instant};
use vectorcraft_color::Color;
use vectorcraft_doc::{AnchorRef, Document, NodeId, Selection, SymbolPart};
use vectorcraft_geom::Rect;
use vectorcraft_testkit::fixtures::DocBuilder;
use super::{OBJECTS_WALKS, select_anchor_items};
type Items = Vec<(NodeId, BTreeSet<AnchorRef>)>;
const MODES: [&str; 4] = ["set", "add", "toggle", "subtract"];
/// The item loop through `Selection`'s own methods, each of which goes through `objects`.
fn item_by_item(d: &Document, sel: &mut Selection, items: Items, mode: &str) {
if mode == "set" {
sel.clear();
}
for (id, refs) in items {
let segment_pick = sel.segments.remove(&id).is_some();
let all: BTreeSet<AnchorRef> =
d.node(id).and_then(|n| n.path_data()).map(|p| p.anchors().map(|(s, i, _)| (s, i)).collect()).unwrap_or_default();
if all.is_empty() {
match mode {
"toggle" => sel.toggle(id),
"subtract" => sel.remove(id),
_ => sel.add(id),
}
continue;
}
let now = match sel.partial(id) {
_ if segment_pick => BTreeSet::new(),
Some(a) => a.clone(),
None if sel.contains(id) => all.clone(),
None => BTreeSet::new(),
};
let refs: BTreeSet<AnchorRef> = refs.intersection(&all).copied().collect();
let next: BTreeSet<AnchorRef> = match mode {
"toggle" => now.symmetric_difference(&refs).copied().collect(),
"subtract" => now.difference(&refs).copied().collect(),
_ => now.union(&refs).copied().collect(),
};
if next.is_empty() {
sel.remove(id);
continue;
}
sel.add(id);
if next.len() < all.len() {
sel.anchors.insert(id, next);
} else {
sel.anchors.remove(&id);
}
}
}
/// A document with `n` four-anchor rectangles and, after them, a group of two more → the
/// rectangles' ids and the group's.
fn doc(n: usize) -> (Document, Vec<NodeId>, NodeId) {
let mut b = DocBuilder::new(2000.0, 2000.0);
let rects = (0..n)
.map(|i| {
let (x, y) = ((i % 200) as f64 * 10.0, (i / 200) as f64 * 10.0);
b.rect(Rect::new(x, y, x + 5.0, y + 5.0), Color::rgb(0.2, 0.4, 0.6), |_| {})
})
.collect();
let black = Color::rgb(0.0, 0.0, 0.0);
let kids = vec![b.rect_node(Rect::new(0.0, 0.0, 1.0, 1.0), black), b.rect_node(Rect::new(2.0, 0.0, 3.0, 1.0), black)];
let group = b.group(kids, false);
(b.build(), rects, group)
}
fn anchors(refs: &[(usize, usize)]) -> BTreeSet<AnchorRef> {
refs.iter().copied().collect()
}
/// A selection with every field set: rectangles 0 to 4 and the group, rectangle 2 listed twice,
/// partial anchors on 1 and 3, a segment pick on 4, rectangle 1 the key, a key anchor on 3, and a
/// target, slices, guides, a key guide, new art, a symbol part and an on-path member.
fn seeded(r: &[NodeId], group: NodeId) -> Selection {
let mut s = Selection { objects: vec![r[0], r[1], r[2], r[3], group, r[2], r[4]], ..Selection::default() };
s.anchors.insert(r[1], anchors(&[(0, 0), (0, 1)]));
s.anchors.insert(r[3], anchors(&[(0, 2)]));
s.anchors.insert(r[4], anchors(&[(0, 0), (0, 1)]));
s.segments.insert(r[4], anchors(&[(0, 0)]));
s.key = Some(r[1]);
s.key_anchor = Some((r[3], (0, 2)));
s.target = Some(r[0]);
s.slices = vec![r[5]];
s.guides = vec![r[6]];
s.key_guide = Some(r[6]);
s.new_art = Arc::new(HashSet::from([r[2]]));
s.symbol_part = Some(SymbolPart { instance: r[0], path: vec![0] });
s.on_path_member = Some(r[7]);
s
}
/// Item lists with repeated ids, removals followed by additions, the group, anchors outside a
/// path, items that empty a path, and the empty list, then pseudo-random lists.
fn item_streams(r: &[NodeId], group: NodeId) -> Vec<Items> {
let all = [(0, 0), (0, 1), (0, 2), (0, 3)];
let mut streams: Vec<Items> = vec![
vec![],
vec![(r[2], anchors(&[(0, 0)]))],
vec![(r[2], anchors(&all)), (r[2], anchors(&all))],
vec![(r[2], anchors(&all)), (r[5], anchors(&[(0, 1)])), (r[2], anchors(&[(0, 3)]))],
vec![(group, anchors(&[])), (group, anchors(&[(0, 0)])), (group, anchors(&[]))],
vec![(r[6], anchors(&[(0, 0)])), (r[6], anchors(&[(0, 0)])), (r[7], anchors(&[(0, 9), (3, 0)]))],
vec![(r[1], anchors(&[(0, 0), (0, 1)])), (r[3], anchors(&[(0, 2)])), (r[1], anchors(&all)), (r[3], anchors(&all))],
vec![(r[4], anchors(&[])), (r[4], anchors(&[(0, 2)]))],
vec![(r[1], anchors(&all)), (r[3], anchors(&all)), (r[1], anchors(&[(0, 0)])), (r[3], anchors(&[(0, 2)]))],
vec![(r[8], anchors(&[(0, 0)])), (r[0], anchors(&all)), (r[8], anchors(&all)), (r[0], anchors(&[(0, 1)]))],
];
let pool: Vec<NodeId> = r.iter().copied().chain([group]).collect();
let mut x: u64 = 0x9e37_79b9_7f4a_7c15;
let mut next = move || {
x ^= x << 13;
x ^= x >> 7;
x ^= x << 17;
x
};
for len in [3, 9, 25, 80, 200] {
let items = (0..len)
.map(|_| {
let id = pool[(next() % pool.len() as u64) as usize];
// Bits 0 to 4 of a draw pick anchors 0 to 3 and one past the end.
let bits = next();
let refs = (0..5).filter(|i| (bits >> i) & 1 == 1).map(|i| (0, i)).collect();
(id, refs)
})
.collect();
streams.push(items);
}
streams
}
/// Starting selections: the seeded one, none, every rectangle whole, and every rectangle with
/// one anchor.
fn starts(r: &[NodeId], group: NodeId) -> Vec<Selection> {
let mut whole = Selection::default();
whole.set(r.iter().copied().chain([group]));
let mut partial = whole.clone();
for id in r {
partial.anchors.insert(*id, anchors(&[(0, 1)]));
}
vec![seeded(r, group), Selection::default(), whole, partial]
}
#[test]
fn anchor_items_do_what_the_item_by_item_loop_does() {
let (d, r, group) = doc(12);
for start in starts(&r, group) {
for items in item_streams(&r, group) {
for mode in MODES {
let mut expected = start.clone();
item_by_item(&d, &mut expected, items.clone(), mode);
let mut got = start.clone();
select_anchor_items(&d, &mut got, items.clone(), mode);
assert_eq!(got, expected, "mode {mode}, items {items:?}, from {start:?}");
assert_eq!(got.new_art, expected.new_art);
}
}
}
}
#[test]
fn a_path_deselected_and_selected_again_goes_last_without_its_key() {
let (d, r, group) = doc(12);
let all = anchors(&[(0, 0), (0, 1), (0, 2), (0, 3)]);
let mut s = seeded(&r, group);
// Toggling the selected anchors of 1 and 3 deselects them; toggling again selects them again.
let items = vec![(r[1], anchors(&[(0, 0), (0, 1)])), (r[3], anchors(&[(0, 2)])), (r[1], anchors(&[(0, 0)])), (r[3], all)];
select_anchor_items(&d, &mut s, items, "toggle");
assert_eq!(s.objects, [r[0], r[2], group, r[2], r[4], r[1], r[3]]);
assert_eq!(s.anchors.get(&r[1]), Some(&anchors(&[(0, 0)])));
assert_eq!(s.anchors.get(&r[3]), None);
assert_eq!((s.key, s.key_anchor), (None, None));
}
/// Every rectangle with one anchor, as a Direct Selection marquee sends them.
fn marquee(r: &[NodeId]) -> Items {
r.iter().map(|id| (*id, anchors(&[(0, 0)]))).collect()
}
/// Every rectangle with all four anchors, which deselects each in subtract mode.
fn every_anchor(r: &[NodeId]) -> Items {
r.iter().map(|id| (*id, anchors(&[(0, 0), (0, 1), (0, 2), (0, 3)]))).collect()
}
#[test]
fn anchor_items_walk_the_selected_objects_at_most_twice() {
let (d, r, group) = doc(2000);
let mut all = Selection::default();
all.set(r.iter().copied().chain([group]));
for (start, items, mode) in [
(Selection::default(), marquee(&r), "set"),
(all.clone(), marquee(&r), "toggle"),
(all.clone(), every_anchor(&r), "subtract"),
(all.clone(), every_anchor(&r).into_iter().chain(marquee(&r)).collect(), "toggle"),
] {
let mut s = start;
OBJECTS_WALKS.set(0);
select_anchor_items(&d, &mut s, items, mode);
let walks = OBJECTS_WALKS.get();
assert!(walks <= 2, "{mode}: {walks} walks over the selected objects");
}
}
/// The CPU time this thread has used, from Linux's scheduler statistics; `None` elsewhere.
fn thread_cpu() -> Option<Duration> {
let stat = std::fs::read_to_string("/proc/thread-self/schedstat").ok()?;
stat.split_whitespace().next()?.parse().ok().map(Duration::from_nanos)
}
/// The time `f` takes: this thread's CPU time where Linux reports it, otherwise the wall clock.
fn time(f: impl FnOnce()) -> Duration {
match thread_cpu() {
Some(before) => {
f();
thread_cpu().map_or(Duration::ZERO, |after| after.saturating_sub(before))
}
None => {
let start = Instant::now();
f();
start.elapsed()
}
}
}
fn ms(d: Duration) -> f64 {
d.as_secs_f64() * 1000.0
}
/// Timings of the item loop and the item-by-item loop on 2,000, 20,000 and 50,000 rectangles, run
/// in turn on clones of the same selection, 7 runs each. Ignored by default; it prints the median,
/// fastest and slowest run and sets no bound on them:
/// `cargo test --release -p vectorcraft-engine --lib anchor_items_perf -- --ignored --nocapture`.
#[test]
#[ignore = "a benchmark: run with --ignored --nocapture"]
fn anchor_items_perf() {
const RUNS: usize = 7;
eprintln!("anchor_items_perf: {}", if thread_cpu().is_some() { "thread CPU time" } else { "wall clock" });
eprintln!("anchor_items_perf: {:>6} {:<26} {:>28} {:>28}", "paths", "case", "item by item ms (min-max)", "item loop ms (min-max)");
for n in [2_000, 20_000, 50_000] {
let (d, r, group) = doc(n);
let mut all = Selection::default();
all.set(r.iter().copied().chain([group]));
for (case, start, items, mode) in [
("set, marquee", Selection::default(), marquee(&r), "set"),
("add, marquee", Selection::default(), marquee(&r), "add"),
("toggle, Select All", all.clone(), marquee(&r), "toggle"),
("subtract every anchor", all.clone(), every_anchor(&r), "subtract"),
] {
let (mut old, mut new) = (Vec::new(), Vec::new());
for run in 0..RUNS {
let (mut a, mut b) = (start.clone(), start.clone());
let (ia, ib) = (items.clone(), items.clone());
// The two loops take turns going first.
if run % 2 == 0 {
old.push(time(|| item_by_item(&d, &mut a, ia, mode)));
new.push(time(|| select_anchor_items(&d, &mut b, ib, mode)));
} else {
new.push(time(|| select_anchor_items(&d, &mut b, ib, mode)));
old.push(time(|| item_by_item(&d, &mut a, ia, mode)));
}
assert_eq!(a, b, "{n} paths, {case}");
}
old.sort();
new.sort();
eprintln!(
"anchor_items_perf: {n:>6} {case:<26} {:>10.3} ({:>7.3}-{:>8.3}) {:>10.3} ({:>7.3}-{:>8.3})",
ms(old[RUNS / 2]),
ms(old[0]),
ms(old[RUNS - 1]),
ms(new[RUNS / 2]),
ms(new[0]),
ms(new[RUNS - 1]),
);
}
}
}
+10 -2
View File
@@ -53,7 +53,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
style_delete
),
cmd!("graphicStyle.duplicate", "Duplicate Graphic Style", ["Window", "Graphic Styles"], None, "{name} → {name}", has_doc, style_duplicate),
cmd!(
"graphicStyle.duplicate",
"Duplicate Graphic Style",
["Window", "Graphic Styles"],
None,
"{name} a copy of the style at the end of the list, named `<name> copy` (`<name> copy 2`… when that is taken); no object is linked to it → {name}",
has_doc,
style_duplicate
),
cmd!(
query "graphicStyle.list",
"List Graphic Styles",
@@ -431,7 +439,7 @@ fn style_duplicate(s: &mut Session, p: &Value) -> Result<Value> {
let pos = style_index(d, &name)?;
let nm = unique_name(&format!("{name} copy"), |n| d.graphic_style(n).is_some());
let g = GraphicStyle { name: nm.clone(), id: d.next_graphic_style_id(), ..d.graphic_styles[pos].clone() };
d.graphic_styles.insert(pos + 1, g);
d.graphic_styles.push(g);
Ok(nm)
})?;
Ok(json!({"name": new}))
+222 -31
View File
@@ -5,13 +5,14 @@
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use vectorcraft_color::Paint;
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
use vectorcraft_doc::{ColorMode, Document, Node, NodeId, NodeKind};
use super::select::selectable_ids;
use super::{CommandSpec, EngineError, Result, Session, always, bad, bool_or, cmd, has_doc, object_param, str_param};
use super::{CommandSpec, EngineError, Result, Session, always, bad, cmd, has_doc, object_param, str_param, switch_or};
/// Magic Wand panel settings. Tolerances: colours as 0–255 RGB distance, stroke weight in
/// points, opacity in percent.
/// Magic Wand panel settings. Tolerances: colors as a Euclidean distance, 0–255 between RGB
/// values in an RGB document and 0–100 between CMYK percentages in a CMYK document; stroke
/// weight in points; opacity in percent.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct WandSettings {
@@ -58,33 +59,68 @@ pub fn specs() -> Vec<CommandSpec> {
"Magic Wand Options",
["Window", "Magic Wand"],
None,
"{fillColor?, fillTolerance?: 0-255, strokeColor?, strokeTolerance?: 0-255, strokeWeight?, weightTolerance?: pt, opacity?, opacityTolerance?: %, blendingMode?, reset?: bool} → the settings",
"{fillColor?, fillTolerance?: 0-255 in an RGB document or 0-100 in a CMYK one, strokeColor?, strokeTolerance?: as fillTolerance, strokeWeight?, weightTolerance?: 0-1000 pt, opacity?, opacityTolerance?: 0-100 %, blendingMode?, reset?: bool} → the settings; a value out of range is an error and changes nothing, and an omitted one keeps its setting",
always,
set
),
cmd!(query "magicWand.options", "Magic Wand Settings", [], None, "{} → the Magic Wand settings", always, |s, _| Ok(json!(s.menu.wand))),
cmd!(
query "magicWand.options",
"Magic Wand Settings",
[],
None,
"{} → the Magic Wand settings (color tolerances at most 100 in a CMYK document)",
always,
|s, _| Ok(json!(s.menu.wand.effective(active_mode(s))))
),
]
}
fn set(s: &mut Session, p: &Value) -> Result<Value> {
if bool_or(p, "reset", false) {
s.menu.wand = WandSettings::default();
/// The active document's color mode, RGB with no document open.
fn active_mode(s: &Session) -> ColorMode {
s.doc().map(|st| st.doc.color_mode).unwrap_or_default()
}
/// The largest Fill Color and Stroke Color tolerance in a document of `mode`.
pub fn color_tolerance_max(mode: ColorMode) -> f64 {
match mode {
ColorMode::Rgb => 255.0,
ColorMode::Cmyk => 100.0,
}
let mut v = serde_json::to_value(&s.menu.wand).map_err(|e| EngineError::Other(e.to_string()))?;
if let (Some(o), Some(src)) = (v.as_object_mut(), p.as_object()) {
for (k, val) in src {
if o.contains_key(k) {
o.insert(k.clone(), val.clone());
}
}
fn set(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "magicWand.set";
let mode = active_mode(s);
let color_max = color_tolerance_max(mode);
let mut w = if switch_or(p, "reset", false, CMD)? { WandSettings::default() } else { s.menu.wand.clone() };
for (key, flag) in [
("fillColor", &mut w.fill_color),
("strokeColor", &mut w.stroke_color),
("strokeWeight", &mut w.stroke_weight),
("opacity", &mut w.opacity),
("blendingMode", &mut w.blending_mode),
] {
// Only a missing key keeps the setting; null, like any other value that isn't true or
// false, is an error.
if let Some(v) = p.get(key) {
*flag = v.as_bool().ok_or_else(|| bad(CMD, format!("`{key}` must be true or false")))?;
}
}
let mut w: WandSettings = serde_json::from_value(v).map_err(|e| bad("magicWand.set", e.to_string()))?;
w.fill_tolerance = w.fill_tolerance.clamp(0.0, 255.0);
w.stroke_tolerance = w.stroke_tolerance.clamp(0.0, 255.0);
w.weight_tolerance = w.weight_tolerance.clamp(0.0, 1000.0);
w.opacity_tolerance = w.opacity_tolerance.clamp(0.0, 100.0);
for (key, value, max) in [
("fillTolerance", &mut w.fill_tolerance, color_max),
("strokeTolerance", &mut w.stroke_tolerance, color_max),
("weightTolerance", &mut w.weight_tolerance, 1000.0),
("opacityTolerance", &mut w.opacity_tolerance, 100.0),
] {
let Some(v) = p.get(key) else { continue };
let n = v.as_f64().ok_or_else(|| bad(CMD, format!("`{key}` must be a number, not {v}")))?;
if !(n.is_finite() && (0.0..=max).contains(&n)) {
return Err(bad(CMD, format!("`{key}` must be from 0 to {max}, not {n}")));
}
*value = n;
}
s.menu.wand = w;
Ok(json!(s.menu.wand))
Ok(json!(s.menu.wand.effective(mode)))
}
/// The fill an object shows: type's comes from its characters (the first run speaks for all; type
@@ -104,25 +140,48 @@ pub(crate) fn stroke_of(n: &Node) -> (Paint, f64) {
}
}
/// Are two paints within `tol` (0–255 Euclidean RGB distance)? Non-solid paints must match exactly.
pub fn similar_paint(a: &Paint, b: &Paint, tol: f64) -> bool {
/// Are two paints within `tol`? In an RGB document `tol` is a 0–255 Euclidean distance between
/// the display RGB values; in a CMYK document it is a 0–100 Euclidean distance between the CMYK
/// percentages (a CMYK color's own values, any other color converted to CMYK). Non-solid paints
/// must match exactly.
pub fn similar_paint(a: &Paint, b: &Paint, tol: f64, mode: ColorMode) -> bool {
match (a.color(), b.color()) {
(Some(x), Some(y)) => {
let (x, y) = (x.to_rgb(), y.to_rgb());
let d: f64 = (0..3).map(|i| ((x[i] - y[i]) as f64 * 255.0).powi(2)).sum::<f64>().sqrt();
d <= tol + 1e-6
let (d, margin) = match mode {
ColorMode::Rgb => {
let (x, y) = (x.to_rgb(), y.to_rgb());
((0..3).map(|i| ((x[i] - y[i]) as f64 * 255.0).powi(2)).sum::<f64>().sqrt(), 1e-6)
}
// CMYK components are f32 fractions, so a distance of exactly `tol` points can come
// out a few millionths over.
ColorMode::Cmyk => {
let (x, y) = (x.to_cmyk(), y.to_cmyk());
((0..4).map(|i| ((x[i] - y[i]) as f64 * 100.0).powi(2)).sum::<f64>().sqrt(), 1e-4)
}
};
d <= tol + margin
}
_ => a == b,
}
}
impl WandSettings {
/// Does `n` match `reference` on every enabled attribute?
pub fn matches(&self, reference: &Node, n: &Node) -> bool {
/// The settings in effect in a document of `mode`: the color tolerances are capped at that
/// mode's maximum, so a larger value set in an RGB document applies as 100 in a CMYK one and
/// comes back in an RGB one.
pub fn effective(&self, mode: ColorMode) -> WandSettings {
let max = color_tolerance_max(mode);
WandSettings { fill_tolerance: self.fill_tolerance.min(max), stroke_tolerance: self.stroke_tolerance.min(max), ..self.clone() }
}
/// Does `n` match `reference` on every enabled attribute, comparing colors as in a document of
/// `mode`?
pub fn matches(&self, reference: &Node, n: &Node, mode: ColorMode) -> bool {
let w = self.effective(mode);
let (rs, rw) = stroke_of(reference);
let (ns, nw) = stroke_of(n);
(!self.fill_color || similar_paint(&fill_of(reference), &fill_of(n), self.fill_tolerance))
&& (!self.stroke_color || similar_paint(&rs, &ns, self.stroke_tolerance))
(!w.fill_color || similar_paint(&fill_of(reference), &fill_of(n), w.fill_tolerance, mode))
&& (!w.stroke_color || similar_paint(&rs, &ns, w.stroke_tolerance, mode))
&& (!self.stroke_weight || (rw - nw).abs() <= self.weight_tolerance + 1e-9)
&& (!self.opacity || ((reference.opacity - n.opacity).abs() as f64 * 100.0) <= self.opacity_tolerance + 1e-6)
&& (!self.blending_mode || reference.blend == n.blend)
@@ -156,12 +215,13 @@ fn magic_wand(s: &mut Session, p: &Value) -> Result<Value> {
let st = s.doc()?;
let reference = st.doc.node(id).ok_or(EngineError::NoNode(id))?.clone();
let w = s.menu.wand.clone();
let mode = st.doc.color_mode;
// In isolation mode only the isolated group's contents can be picked, as for Select Same.
let inside = st.isolation.map(|iso| selectable_ids(&st.doc, Some(iso)));
let hits: Vec<NodeId> = paintable(&st.doc)
.into_iter()
.filter(|i| inside.as_ref().is_none_or(|set| set.contains(i)))
.filter(|i| st.doc.node(*i).is_some_and(|n| w.matches(&reference, n)))
.filter(|i| st.doc.node(*i).is_some_and(|n| w.matches(&reference, n, mode)))
.collect();
let ids: Vec<NodeId> = match str_param(p, "mode").unwrap_or("set") {
"add" => st.selection.objects.iter().copied().chain(hits.iter().copied().filter(|h| !st.selection.objects.contains(h))).collect(),
@@ -232,6 +292,137 @@ mod tests {
assert_eq!(selected(&s), [b]);
}
/// A 10 × 10 rectangle at `x` filled and stroked with the given colors (JSON color values).
fn painted(s: &mut Session, x: f64, fill: Value, stroke: Value) -> u64 {
let id = s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
s.execute("paint.setFill", &json!({ "color": fill })).unwrap();
s.execute("paint.setStroke", &json!({ "color": stroke })).unwrap();
id
}
fn cmyk(c: f64, m: f64, y: f64, k: f64) -> Value {
json!({"model": "cmyk", "c": c, "m": m, "y": y, "k": k})
}
#[test]
fn cmyk_document_compares_fill_and_stroke_colors_in_cmyk() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 200, "colorMode": "cmyk"})).unwrap();
let white = cmyk(0.0, 0.0, 0.0, 0.0);
let a = painted(&mut s, 0.0, cmyk(0.1, 0.0, 0.0, 0.0), white.clone());
let b = painted(&mut s, 20.0, cmyk(0.0, 0.0, 0.0, 0.0), white.clone());
let c = painted(&mut s, 40.0, cmyk(0.0, 0.1, 0.0, 0.0), white.clone());
// a to b is 10 points of cyan; a to c is 10 points of cyan and 10 of magenta (14.1).
s.execute("magicWand.set", &json!({"fillTolerance": 10})).unwrap();
s.execute("select.magicWand", &json!({"id": a})).unwrap();
assert_eq!(selected(&s), [a, b]);
s.execute("magicWand.set", &json!({"fillTolerance": 9.9})).unwrap();
s.execute("select.magicWand", &json!({"id": a})).unwrap();
assert_eq!(selected(&s), [a]);
s.execute("magicWand.set", &json!({"fillTolerance": 14.2})).unwrap();
s.execute("select.magicWand", &json!({"id": a})).unwrap();
assert_eq!(selected(&s), [a, b, c]);
// Stroke Color alone, the same rule: d's stroke is 5 points of black from a's.
let d = painted(&mut s, 60.0, cmyk(1.0, 1.0, 1.0, 1.0), cmyk(0.0, 0.0, 0.0, 0.05));
s.execute("magicWand.set", &json!({"fillColor": false, "strokeColor": true, "strokeTolerance": 5})).unwrap();
s.execute("select.magicWand", &json!({"id": d})).unwrap();
assert_eq!(selected(&s), [a, b, c, d]);
s.execute("magicWand.set", &json!({"strokeTolerance": 4.9})).unwrap();
s.execute("select.magicWand", &json!({"id": d})).unwrap();
assert_eq!(selected(&s), [d]);
}
#[test]
fn cmyk_document_compares_gray_as_black_ink() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 200, "colorMode": "cmyk"})).unwrap();
let none = cmyk(0.0, 0.0, 0.0, 0.0);
let a = painted(&mut s, 0.0, json!({"gray": 0.5}), none.clone());
let b = painted(&mut s, 20.0, cmyk(0.0, 0.0, 0.0, 0.5), none.clone());
let c = painted(&mut s, 40.0, cmyk(0.0, 0.0, 0.0, 0.6), none);
s.execute("magicWand.set", &json!({"fillTolerance": 0})).unwrap();
s.execute("select.magicWand", &json!({"id": a})).unwrap();
assert_eq!(selected(&s), [a, b]);
s.execute("magicWand.set", &json!({"fillTolerance": 10})).unwrap();
s.execute("select.magicWand", &json!({"id": a})).unwrap();
assert_eq!(selected(&s), [a, b, c]);
}
#[test]
fn rgb_document_keeps_the_rgb_distance() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 200})).unwrap();
let a = rect(&mut s, 0.0, "#000000", 1.0);
let b = rect(&mut s, 20.0, "#0a0000", 1.0);
s.execute("magicWand.set", &json!({"fillTolerance": 10})).unwrap();
s.execute("select.magicWand", &json!({"id": a})).unwrap();
assert_eq!(selected(&s), [a, b]);
s.execute("magicWand.set", &json!({"fillTolerance": 9.9})).unwrap();
s.execute("select.magicWand", &json!({"id": a})).unwrap();
assert_eq!(selected(&s), [a]);
assert_eq!(s.execute("magicWand.set", &json!({"fillTolerance": 255})).unwrap()["fillTolerance"], 255.0);
}
#[test]
fn set_rejects_tolerances_out_of_range_and_changes_nothing() {
let mut s = Session::new();
// With no document the color range is the RGB one.
assert!(s.execute("magicWand.set", &json!({"fillTolerance": 256})).is_err());
s.execute("magicWand.set", &json!({"fillTolerance": 200})).unwrap();
s.execute("file.new", &json!({"width": 400, "height": 200, "colorMode": "cmyk"})).unwrap();
s.execute("magicWand.set", &json!({"fillTolerance": 40, "strokeTolerance": 50})).unwrap();
let before = s.execute("magicWand.options", &json!({})).unwrap();
for bad_value in [
json!({"fillTolerance": 101}),
json!({"strokeTolerance": 100.5}),
json!({"fillTolerance": -1}),
json!({"fillTolerance": "40"}),
json!({"weightTolerance": 1001}),
json!({"opacityTolerance": -0.5}),
json!({"fillColor": "yes"}),
json!({"fillTolerance": null}),
json!({"strokeColor": null}),
json!({"reset": "yes", "fillColor": false}),
json!({"reset": true, "fillTolerance": 101}),
json!({"fillColor": false, "strokeTolerance": 101}),
] {
let e = s.execute("magicWand.set", &bad_value).unwrap_err().to_string();
assert!(e.contains("magicWand.set"), "{bad_value}: {e}");
assert_eq!(s.execute("magicWand.options", &json!({})).unwrap(), before, "{bad_value} changed the settings");
}
assert!(s.execute("magicWand.set", &json!({"fillTolerance": 101})).unwrap_err().to_string().contains("from 0 to 100"));
assert_eq!(s.execute("magicWand.set", &json!({"fillTolerance": 100})).unwrap()["fillTolerance"], 100.0);
// An omitted value keeps its setting.
assert_eq!(s.execute("magicWand.set", &json!({"strokeColor": true})).unwrap()["strokeTolerance"], 50.0);
}
#[test]
fn a_larger_rgb_tolerance_applies_as_100_in_a_cmyk_document_and_comes_back() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 200})).unwrap();
s.execute("magicWand.set", &json!({"fillTolerance": 200, "strokeTolerance": 60})).unwrap();
s.execute("file.new", &json!({"width": 400, "height": 200, "colorMode": "cmyk"})).unwrap();
let o = s.execute("magicWand.options", &json!({})).unwrap();
assert_eq!((o["fillTolerance"].as_f64(), o["strokeTolerance"].as_f64()), (Some(100.0), Some(60.0)));
// Setting another field does not overwrite the stored fill tolerance.
assert_eq!(s.execute("magicWand.set", &json!({"opacity": true})).unwrap()["fillTolerance"], 100.0);
// 100 applies: two colors 100 points apart in one channel match, 100 apart in two do not.
let none = cmyk(0.0, 0.0, 0.0, 0.0);
let a = painted(&mut s, 0.0, cmyk(0.0, 0.0, 0.0, 0.0), none.clone());
let b = painted(&mut s, 20.0, cmyk(1.0, 0.0, 0.0, 0.0), none.clone());
let c = painted(&mut s, 40.0, cmyk(1.0, 1.0, 0.0, 0.0), none);
s.execute("magicWand.set", &json!({"opacity": false})).unwrap();
s.execute("select.magicWand", &json!({"id": a})).unwrap();
assert_eq!(selected(&s), [a, b]);
assert!(!selected(&s).contains(&c));
s.execute("document.activate", &json!({"index": 0})).unwrap();
assert_eq!(s.execute("magicWand.options", &json!({})).unwrap()["fillTolerance"], 200.0);
// Reset gives 32 in either mode.
s.execute("document.activate", &json!({"index": 1})).unwrap();
let o = s.execute("magicWand.set", &json!({"reset": true})).unwrap();
assert_eq!((o["fillTolerance"].as_f64(), o["strokeTolerance"].as_f64()), (Some(32.0), Some(32.0)));
}
#[test]
fn isolation_mode_limits_the_wand_to_the_isolated_group() {
let mut s = Session::new();
+2 -2
View File
@@ -782,9 +782,9 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8
/// An optimised image as straight RGBA → `(pixels, width, height)` (the dialog's preview).
pub fn decode(o: &Optimized) -> std::result::Result<(Vec<u8>, u32, u32), String> {
let img = image::load_from_memory(o.display()).map_err(|e| format!("the optimised image can't be read back: {e}"))?.to_rgba8();
let img = craft_image_codecs::decode(o.display()).map_err(|e| format!("the optimised image can't be read back: {e}"))?;
let (w, h) = img.dimensions();
Ok((img.into_raw(), w, h))
Ok((img.to_rgba8(), w, h))
}
/// Seconds to download `bytes` at `kbps` kilobits per second.
+1
View File
@@ -122,6 +122,7 @@ mod panelcmds;
mod paragraphs;
mod params;
mod path_menu_enabled;
mod pathfinder_clip;
mod pathops;
mod pathtype;
mod pattern;
+71 -3
View File
@@ -31,7 +31,41 @@ pub(crate) fn fill_hex(n: &Node) -> String {
fn red_image(s: &mut Session) -> NodeId {
let img = image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 0, 0, 255]));
let mut png = vec![];
img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
{
let __dyn: image::DynamicImage = img.into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| png.extend_from_slice(&__b))
}
.unwrap();
s.edit("Place", |d, sel| {
d.images.insert("pic".into(), vectorcraft_doc::ImageBlob::png(png));
let id = d.alloc_id();
@@ -108,13 +142,47 @@ fn an_embedded_image_is_adjusted_for_export_without_changing_its_pixels() {
let baked = vectorcraft_render::effects::bake_document(&doc).unwrap();
let NodeKind::Image(im) = &baked.node(id).unwrap().kind else { panic!("not an image") };
assert_ne!(im.key, "pic", "a recoloured copy");
let px = image::load_from_memory(&baked.images[&im.key].bytes).unwrap().to_rgba8();
let px = craft_image_codecs::decode(&baked.images[&im.key].bytes)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8();
assert_eq!(px.get_pixel(1, 1).0, [0, 255, 0, 255]);
assert_eq!(doc.images.len(), 1, "the document keeps its one image");
// Through Expand Appearance too.
s.execute("effect.expandAppearance", &json!({})).unwrap();
let NodeKind::Image(im) = &node(&s, id).kind else { panic!("not an image") };
let px = image::load_from_memory(&s.doc().unwrap().doc.images[&im.key].bytes).unwrap().to_rgba8();
let px = craft_image_codecs::decode(&s.doc().unwrap().doc.images[&im.key].bytes)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8();
assert_eq!(px.get_pixel(0, 0).0, [0, 255, 0, 255]);
}
+77 -4
View File
@@ -140,7 +140,24 @@ fn an_asset_exports_its_art_alone() {
run(&mut s, "assets.add", json!({"ids": [red]}));
let out = files(&run(&mut s, "assets.export", json!({"formats": [{"format": "png", "scale": "2x"}]})));
assert_eq!(out[0].0, "Asset-1@2x.png");
let img = image::load_from_memory(&out[0].1).unwrap().to_rgba8();
let img = craft_image_codecs::decode(&out[0].1)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8();
assert_eq!(img.dimensions(), (40, 40));
assert!(img.pixels().all(|p| p.0 == [255, 0, 0, 255]), "only the red square");
// Vector formats crop to it too.
@@ -163,7 +180,24 @@ fn an_assets_crop_takes_in_its_drop_shadow() {
// The shadow's reach (10 pt) on every side.
assert_eq!(assets(&mut s)[0]["bounds"], json!([40.0, 40.0, 40.0, 40.0]));
let out = files(&run(&mut s, "assets.export", json!({"formats": [{"format": "png", "scale": "1x"}]})));
let img = image::load_from_memory(&out[0].1).unwrap().to_rgba8();
let img = craft_image_codecs::decode(&out[0].1)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8();
assert_eq!(img.dimensions(), (40, 40));
// The shadow's right half, x 70 to 80.
assert!(img.get_pixel(35, 20)[3] > 0, "the shadow is in the image");
@@ -417,7 +451,29 @@ fn export_for_screens_writes_chosen_assets_and_keeps_its_rules() {
let out = files(&r);
assert_eq!(out.len(), 1);
assert_eq!(out[0].0, "Asset-2@60w.png");
assert_eq!(image::load_from_memory(&out[0].1).unwrap().to_rgba8().dimensions(), (60, 40), "the width of the asset, not the artboard");
assert_eq!(
craft_image_codecs::decode(&out[0].1)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8()
.dimensions(),
(60, 40),
"the width of the asset, not the artboard"
);
// The choice of art isn't remembered; the formats are.
let settings = run(&mut s, "document.exportSettings", json!({}))["settings"].clone();
assert!(settings.get("assets").is_none() && settings["formats"][0]["scale"] == "60w");
@@ -466,7 +522,24 @@ fn assets_export_leaves_no_seam_between_abutting_shapes() {
}),
));
assert_eq!(out[0].0, "Asset-1.png");
let img = image::load_from_memory(&out[0].1).unwrap().to_rgba8();
let img = craft_image_codecs::decode(&out[0].1)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8();
assert_eq!(img.dimensions(), (40, 20));
// Column 20 is the shared edge in crop space; green must stay red (no white bleed).
let palest_g = (2..18).map(|y| img.get_pixel(20, y).0[1].max(img.get_pixel(19, y).0[1])).max().unwrap();
+47
View File
@@ -2599,3 +2599,50 @@ fn symbol_sort_by_name_orders_the_symbols_in_one_undo_step() {
s.execute("symbol.sortByName", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().history.undo.len(), before);
}
/// `cmd::current_symbol` answers what `symbol.list` answers as `current`, and what `rule` (the
/// stored name while a symbol has it, else the first of all the names) answers:
/// with no symbols, with no stored name, with a stored name that is not first, after the current
/// symbol is deleted, with a stored name no symbol has and with a stored value that is not text.
#[test]
fn current_symbol_is_the_current_symbol_list_answers() {
fn rule(d: &Document) -> Option<String> {
let names: Vec<String> = d.symbols.iter().map(|s| s.name.clone()).collect();
let stored = d.unknown.get("currentSymbol").and_then(Value::as_str).filter(|n| d.symbols.iter().any(|s| s.name == *n)).map(str::to_string);
stored.or_else(|| names.into_iter().next())
}
fn check(s: &mut Session, want: Option<&str>, case: &str) {
let listed = s.execute("symbol.list", &json!({})).unwrap()["current"].clone();
let d = &s.doc().unwrap().doc;
let helper = crate::cmd::current_symbol(d);
assert_eq!(helper.as_deref(), want, "{case}");
assert_eq!(json!(helper), listed, "{case}: symbol.list");
assert_eq!(helper, rule(d), "{case}: the rule");
}
fn store(s: &mut Session, v: Value) {
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).unknown.insert("currentSymbol".into(), v);
}
let mut s = session();
check(&mut s, None, "no symbols");
store(&mut s, json!("Gone"));
check(&mut s, None, "no symbols and a stored name");
for (i, name) in ["A", "B", "C"].into_iter().enumerate() {
rect(&mut s, 20.0 * i as f64, 0.0, 10.0, 10.0);
s.execute("symbol.new", &json!({"name": name})).unwrap();
}
check(&mut s, Some("C"), "the newest symbol is current");
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).unknown.remove("currentSymbol");
check(&mut s, Some("A"), "no stored name");
s.execute("symbol.setCurrent", &json!({"name": "B"})).unwrap();
check(&mut s, Some("B"), "a stored name that is not first");
s.execute("symbol.delete", &json!({"name": "B"})).unwrap();
check(&mut s, Some("A"), "the current symbol deleted");
store(&mut s, json!("Renamed"));
check(&mut s, Some("A"), "a stored name no symbol has");
store(&mut s, json!(3));
check(&mut s, Some("A"), "a stored number");
store(&mut s, json!(["C"]));
check(&mut s, Some("A"), "a stored list");
store(&mut s, json!("C"));
check(&mut s, Some("C"), "a stored name that is last");
}
+166 -1
View File
@@ -5198,6 +5198,137 @@ fn live_paint_bucket_drag_rejects_invalid_points_atomically() {
}
}
/// The edge of `g` through (`x`, 25), halfway up the squares of [`live_squares`].
fn vertical_edge(s: &Session, g: NodeId, x: f64) -> NodeId {
vectorcraft_tools::builder::edge_near(&node(s, g), Point::new(x, 25.0), 0.5).map(|e| e.id).unwrap_or_else(|| panic!("an edge at x {x}"))
}
/// A Shift-drag from an edge strokes every visible edge of that group the drag crosses, between
/// pointer events and on the release too, as one undo step that Escape cancels; hidden edges and
/// another group's edges keep their strokes.
#[test]
fn live_paint_bucket_drag_strokes_crossed_edges_as_one_undo() {
for cancel in [false, true] {
let mut s = session();
let g = live_squares(&mut s, &[0.0, 50.0, 100.0, 150.0, 200.0]);
let other = live_squares(&mut s, &[300.0]);
let black = Paint::solid(Color::rgb(0.0, 0.0, 0.0));
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
let all: Vec<NodeId> = [g, other].iter().flat_map(|g| edges_in(&s, *g, Rect::new(-1.0, -1.0, 351.0, 51.0))).collect();
paint_parts(&mut s, &all, &black, &[]);
let hidden = vertical_edge(&s, g, 100.0);
s.edit("t", |d, _| {
d.node_mut(hidden).unwrap().visible = false;
Ok(())
})
.unwrap();
let before = s.doc().unwrap().doc.clone();
let depth = s.doc().unwrap().history.undo.len();
let v = ViewInfo::default();
s.select_tool("livePaintBucket", v).unwrap();
s.paint.stroke = green.clone();
s.paint.stroke_width = 3.0;
let shift = Mods { shift: true, ..Default::default() };
s.pointer(&PointerEvent::new(PointerKind::Down, 50.0, 25.0).with_mods(shift), v).unwrap();
// Past the hidden edge and the edge at 150, then back across it, between pointer events.
s.pointer(&PointerEvent::new(PointerKind::Drag, 160.0, 25.0).with_mods(shift), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 140.0, 30.0).with_mods(shift), v).unwrap();
if cancel {
assert!(s.tool_busy());
s.tool_key(ToolKey::Escape, Mods::default(), v).unwrap();
assert!(!s.tool_busy());
}
// The release crosses the edges at 200 and 250 and goes on into the other group.
s.pointer(&PointerEvent::new(PointerKind::Up, 325.0, 25.0).with_mods(shift), v).unwrap();
if cancel {
assert!(s.doc().unwrap().doc == before, "Escape cancels the whole drag");
assert_eq!(s.doc().unwrap().history.undo.len(), depth);
continue;
}
let stroke = |s: &Session, id: NodeId| {
let n = node(s, id);
(n.appearance.stroke_paint(), n.appearance.stroke().map(|st| st.width))
};
for x in [50.0, 150.0, 200.0, 250.0] {
assert_eq!(stroke(&s, vertical_edge(&s, g, x)), (green.clone(), Some(3.0)), "edge at {x}");
}
for (group, x) in [(g, 0.0), (g, 100.0), (other, 300.0), (other, 350.0)] {
assert_eq!(stroke(&s, vertical_edge(&s, group, x)), (black.clone(), Some(1.0)), "edge at {x}");
}
for e in edges_in(&s, g, Rect::new(-1.0, -1.0, 201.0, 1.0)) {
assert_eq!(stroke(&s, e).0, black, "a top edge is not crossed");
}
assert_eq!(s.doc().unwrap().history.undo.len(), depth + 1, "one undo step");
s.execute("edit.undo", &json!({})).unwrap();
assert!(s.doc().unwrap().doc == before, "one Undo restores every edge");
}
}
/// A stroke drag over edges that already have the stroke records no undo step and keeps the redo
/// steps.
#[test]
fn live_paint_bucket_stroke_drag_no_op_keeps_history() {
let mut s = session();
let g = live_squares(&mut s, &[0.0, 50.0]);
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 101.0, 51.0));
paint_parts(&mut s, &all, &green, &[]);
paint_parts(&mut s, &all, &green, &[]);
s.execute("edit.undo", &json!({})).unwrap();
let before = s.doc().unwrap().doc.clone();
let (undo, redo) = (s.doc().unwrap().history.undo.len(), s.doc().unwrap().history.redo.len());
assert_eq!(redo, 1);
let v = ViewInfo::default();
s.select_tool("livePaintBucket", v).unwrap();
s.paint.stroke = green;
s.paint.stroke_width = 1.0;
let shift = Mods { shift: true, ..Default::default() };
s.pointer(&PointerEvent::new(PointerKind::Down, 0.0, 25.0).with_mods(shift), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 60.0, 25.0).with_mods(shift), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 110.0, 25.0).with_mods(shift), v).unwrap();
assert!(s.doc().unwrap().doc == before);
assert_eq!((s.doc().unwrap().history.undo.len(), s.doc().unwrap().history.redo.len()), (undo, redo));
}
/// `livePaint.strokeEdge` with `points` paints the crossed edges, counting the edge at the point;
/// a malformed path or a scope other than "one" with `points` is an error that changes nothing.
#[test]
fn live_paint_stroke_drag_rejects_invalid_points_atomically() {
let mut s = session();
let g = live_squares(&mut s, &[0.0, 50.0, 100.0]);
let before = s.doc().unwrap().doc.clone();
let stroke = |s: &mut Session, extra: Value| {
let mut p = json!({"group": g.0, "point": [50.0, 25.0], "color": "#00ff00"});
for (k, v) in extra.as_object().unwrap() {
p[k] = v.clone();
}
s.execute("livePaint.strokeEdge", &p)
};
for points in
[json!([]), json!([[51.0, 25.0]]), json!([[50.0, 25.0], [null, 0]]), json!([[50.0, 25.0], [1e30, 0]]), json!(vec![[50.0, 25.0]; 4097])]
{
assert!(stroke(&mut s, json!({ "points": points })).is_err(), "{points}");
assert_eq!(s.doc().unwrap().doc, before);
}
for continuation in [json!(null), json!([[[51.0, 25.0], [125.0, 25.0]]]), json!([vec![[50.0, 25.0]; 4097]])] {
assert!(stroke(&mut s, json!({ "points": [[50.0, 25.0]], "continuation": continuation })).is_err(), "{continuation}");
assert_eq!(s.doc().unwrap().doc, before);
}
assert!(stroke(&mut s, json!({ "continuation": [[[50.0, 25.0]]] })).is_err());
for scope in ["connected", "samePaint"] {
assert!(stroke(&mut s, json!({ "points": [[50.0, 25.0], [125.0, 25.0]], "scope": scope })).is_err(), "{scope}");
}
assert_eq!(s.doc().unwrap().doc, before);
// A path in two chunks reaches the edges at 50, 100 and 150, not the one at 0.
let r = stroke(&mut s, json!({ "points": [[50.0, 25.0], [90.0, 25.0]], "continuation": [[[90.0, 25.0], [160.0, 25.0]]] })).unwrap();
assert_eq!(r["count"], 3);
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
for x in [50.0, 100.0, 150.0] {
assert_eq!(node(&s, vertical_edge(&s, g, x)).appearance.stroke_paint(), green, "edge at {x}");
}
assert_ne!(node(&s, vertical_edge(&s, g, 0.0)).appearance.stroke_paint(), green);
}
#[test]
fn live_paint_bucket_tool_fills_face() {
let mut s = session();
@@ -5391,7 +5522,41 @@ fn live_paint_bucket_alt_image_samples_fill_and_clears_stroke() {
let mut s = session();
let img = image::RgbaImage::from_raw(1, 1, vec![0, 255, 0, 255]).unwrap();
let mut png = vec![];
img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
{
let __dyn: image::DynamicImage = img.into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| png.extend_from_slice(&__b))
}
.unwrap();
s.edit("Place", |d, _| {
d.images.insert("px".into(), ImageBlob::png(png));
let id = d.alloc_id();
+175 -6
View File
@@ -59,7 +59,24 @@ fn exported_png_of_a_red_square_is_red() {
copy_red_square(&mut s);
let r = run(&mut s, "clipboard.exportPng", json!({"scale": 2}));
assert_eq!((r["width"].as_u64(), r["height"].as_u64()), (Some(80), Some(80)));
let img = image::load_from_memory(&decode(&r)).unwrap().to_rgba8();
let img = craft_image_codecs::decode(&decode(&r))
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8();
assert_eq!(img.dimensions(), (80, 80));
assert_eq!(img.get_pixel(40, 40).0, [255, 0, 0, 255]);
assert_eq!(img.get_pixel(2, 77).0, [255, 0, 0, 255], "cropped to the square");
@@ -155,7 +172,41 @@ fn import_image_then_paste_gives_an_image() {
#[test]
fn an_image_read_apart_loads_as_import_image_loads_it() {
let mut bmp = vec![];
image::RgbImage::from_pixel(30, 20, image::Rgb([200, 40, 40])).write_to(&mut std::io::Cursor::new(&mut bmp), image::ImageFormat::Bmp).unwrap();
{
let __dyn: image::DynamicImage = (image::RgbImage::from_pixel(30, 20, image::Rgb([200, 40, 40]))).into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Bmp, &craft_image_codecs::EncodeOptions::default())
.map(|__b| bmp.extend_from_slice(&__b))
}
.unwrap();
let (mut at_once, mut apart) = (session(), session());
let p = json!({"mime": "image/bmp", "center": [100, 80]});
let mut with_data = p.clone();
@@ -195,7 +246,41 @@ fn a_pasted_bitmap_is_drawn_without_decoding_it_again() {
// The image has pixels no other test uses, since every test shares the image store.
let img = image::RgbImage::from_fn(300, 200, |x, y| image::Rgb([(x % 253) as u8, (y % 233) as u8, 17]));
let mut png = vec![];
img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
{
let __dyn: image::DynamicImage = img.into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| png.extend_from_slice(&__b))
}
.unwrap();
let mut s = session();
run(&mut s, "clipboard.importImage", json!({"dataBase64": vectorcraft_format::base64_encode(&png), "mime": "image/png"}));
run(&mut s, "edit.paste", json!({}));
@@ -278,7 +363,41 @@ fn copied_files_paste_by_their_content() {
let png = decode(&run(&mut s, "clipboard.exportPng", json!({})));
let pdf = decode(&run(&mut s, "clipboard.exportPdf", json!({})));
let mut jpeg = vec![];
image::RgbImage::new(2, 2).write_to(&mut std::io::Cursor::new(&mut jpeg), image::ImageFormat::Jpeg).unwrap();
{
let __dyn: image::DynamicImage = (image::RgbImage::new(2, 2)).into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Jpeg, &craft_image_codecs::EncodeOptions::default())
.map(|__b| jpeg.extend_from_slice(&__b))
}
.unwrap();
let svg = b"<svg xmlns=\"http://www.w3.org/2000/svg\"><rect width=\"4\" height=\"4\"/></svg>";
let of = |name: &str, bytes: &[u8]| file_flavour(name, &bytes[..bytes.len().min(FILE_HEAD)], &PASTE_ORDER);
assert_eq!(of("red.png", &png), Some(PNG));
@@ -402,7 +521,23 @@ fn copy_leaves_out_the_png_of_art_too_large_to_scale_down() {
run(&mut s, "select.set", json!({"ids": [id]}));
run(&mut s, "edit.copy", json!({}));
let png = s.clipboard.flavours(false, false).into_iter().find(|f| f.mime == PNG).expect("a PNG");
let img = image::load_from_memory(&png.data).unwrap();
let img = craft_image_codecs::decode(&png.data)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap();
assert!(img.width() <= 4096 && img.height() <= 4096, "{}x{}", img.width(), img.height());
}
@@ -445,7 +580,41 @@ fn noise_png(side: u32) -> Vec<u8> {
})
.collect();
let mut out = vec![];
image::RgbImage::from_raw(side, side, px).unwrap().write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap();
{
let __dyn: image::DynamicImage = (image::RgbImage::from_raw(side, side, px).unwrap()).into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| out.extend_from_slice(&__b))
}
.unwrap();
out
}
+35 -1
View File
@@ -15,7 +15,41 @@ fn session() -> Session {
fn png(img: image::DynamicImage) -> ImageBlob {
let mut out = Vec::new();
img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap();
{
let __dyn: image::DynamicImage = img;
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| out.extend_from_slice(&__b))
}
.unwrap();
ImageBlob::png(out)
}
+94
View File
@@ -412,3 +412,97 @@ fn constrain_angle_turns_a_click_made_grid_about_its_reference_point() {
let b = bounds(&s, id);
assert_eq!((b.x0, b.y0, b.x1, b.y1), (175.0, 150.0, 225.0, 250.0), "turned about the click: {b:?}");
}
/// The anchor points of the path `id`.
fn path_points(s: &Session, id: NodeId) -> Vec<Point> {
match &s.doc().unwrap().doc.node(id).unwrap().kind {
NodeKind::Path { path, .. } => path.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p)).collect(),
other => panic!("a path: {other:?}"),
}
}
/// The direction (degrees, counter-clockwise on the page) of the arc `id`'s first handle.
fn first_handle_angle(s: &Session, id: NodeId) -> f64 {
let NodeKind::Path { path, .. } = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("a path") };
let a = &path.subpaths[0].anchors[0];
let v = a.h_out - a.p;
(-v.y).atan2(v.x).to_degrees()
}
fn near(p: Point, x: f64, y: f64) -> bool {
close(p.x, x) && close(p.y, y)
}
/// An arc dragged out runs along the turned axes: at 30° it still runs from the drag's start to
/// its end, its base leaves the start along the turned x axis and its bounding box turns 30°; at
/// 0° it is as before.
#[test]
fn constrain_angle_draws_a_dragged_arc_along_the_turned_axes() {
let mut s = new_doc();
for (deg, handle) in [(0.0, 0.0), (30.0, 30.0)] {
set_angle(&mut s, deg);
s.select_tool("arc", ViewInfo::default()).unwrap();
gesture(&mut s, Mods::default(), &[(Down, 100.0, 100.0), (Drag, 130.0, 110.0), (Drag, 160.0, 120.0), (Up, 160.0, 120.0)]);
let id = last_id(&s);
let pts = path_points(&s, id);
assert!(near(pts[0], 100.0, 100.0) && near(pts[1], 160.0, 120.0), "{deg}°: {pts:?}");
assert!(close(first_handle_angle(&s, id), handle), "{deg}°: {}", first_handle_angle(&s, id));
if deg == 0.0 {
assert_eq!(bbox_angle(&s, id).to_bits(), 0.0f64.to_bits());
} else {
assert!(close(bbox_angle(&s, id), 30.0), "{}", bbox_angle(&s, id));
}
}
}
/// An arc placed by the click dialog keeps its reference point at the click and runs its lengths
/// along the turned axes: at 30° from the top-left reference point, and at 90° about the center
/// one; at 0° the dialog's params are unchanged.
#[test]
fn constrain_angle_turns_a_click_made_arc_about_its_reference_point() {
let mut s = new_doc();
let params = |reference: u64, x: f64, y: f64| json!({"x": x, "y": y, "lengthX": 100, "lengthY": 50, "reference": reference, "baseAlong": "x", "slope": 50, "closed": false, "fillArc": false});
let click = Point::new(200.0, 200.0);
let p = params(0, 200.0, 200.0);
assert_eq!(constrain_click(&s, "shape.arc", p.clone(), click), p, "0°");
set_angle(&mut s, 30.0);
let turned = constrain_click(&s, "shape.arc", p, click);
assert_eq!(turned["rotation"], json!(-30.0));
let id = NodeId(s.execute("shape.arc", &turned).unwrap()["id"].as_u64().unwrap());
let pts = path_points(&s, id);
let r = 30f64.to_radians();
let end = (200.0 + 100.0 * r.cos() + 50.0 * r.sin(), 200.0 - 100.0 * r.sin() + 50.0 * r.cos());
assert!(near(pts[0], 200.0, 200.0) && near(pts[1], end.0, end.1), "{pts:?} vs {end:?}");
assert!(close(bbox_angle(&s, id), 30.0));
set_angle(&mut s, 90.0);
let p = constrain_click(&s, "shape.arc", params(4, 200.0, 200.0), click);
let id = NodeId(s.execute("shape.arc", &p).unwrap()["id"].as_u64().unwrap());
// The ends at opposite corners of the 100 × 50 box centered on the click, turned exactly.
assert_eq!(path_points(&s, id), vec![Point::new(175.0, 250.0), Point::new(225.0, 150.0)]);
let b = bounds(&s, id);
assert!(close(b.x0, 175.0) && close(b.y0, 150.0) && close(b.x1, 225.0) && close(b.y1, 250.0), "turned about the click: {b:?}");
assert_eq!(bbox_angle(&s, id), 90.0);
}
/// `shape.arc` turns by an explicit `rotation` (clockwise) about `x1`, `y1` or about its reference
/// point; a `rotation` that is not a number is refused and adds nothing.
#[test]
fn arc_rotation_turns_it_and_must_be_a_number() {
let mut s = new_doc();
let id = NodeId(s.execute("shape.arc", &json!({"x1": 0, "y1": 0, "x2": 10, "y2": 20, "rotation": 90})).unwrap()["id"].as_u64().unwrap());
let pts = path_points(&s, id);
assert!(near(pts[0], 0.0, 0.0) && near(pts[1], -20.0, 10.0), "{pts:?}");
assert_eq!(bbox_angle(&s, id), -90.0, "a quarter turn clockwise");
let id =
NodeId(s.execute("shape.arc", &json!({"x": 50, "y": 50, "lengthX": 10, "lengthY": 20, "rotation": 360})).unwrap()["id"].as_u64().unwrap());
assert_eq!(path_points(&s, id), vec![Point::new(50.0, 50.0), Point::new(60.0, 70.0)], "a whole turn leaves it upright");
assert_eq!(bbox_angle(&s, id).to_bits(), 0.0f64.to_bits());
for bad in [json!("x"), Value::Null] {
for p in
[json!({"x1": 0, "y1": 0, "x2": 10, "y2": 20, "rotation": bad}), json!({"x": 0, "y": 0, "lengthX": 10, "lengthY": 20, "rotation": bad})]
{
assert!(s.execute("shape.arc", &p).is_err(), "{p}");
assert_eq!(last_id(&s), id, "nothing added for {p}");
}
}
}
+108 -11
View File
@@ -186,9 +186,41 @@ fn type_with_an_inline_graphic_stays_type_when_its_own_stroke_has_an_effect() {
/// A selected 30×30 red image placed with its frame from (50, 50) to (80, 80).
fn image(s: &mut Session) -> NodeId {
let mut png = vec![];
image::RgbaImage::from_pixel(30, 30, image::Rgba([255, 0, 0, 255]))
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
.unwrap();
{
let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(30, 30, image::Rgba([255, 0, 0, 255]))).into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| png.extend_from_slice(&__b))
}
.unwrap();
let r = run(s, "file.place", json!({"name": "red.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [65, 65]}));
NodeId(r["ids"][0].as_u64().unwrap())
}
@@ -259,11 +291,44 @@ fn an_images_stroke_with_outline_object_draws_exports_and_expands_along_its_fram
/// A 100×100 PNG, transparent but for an opaque red disc of radius 30 in its middle.
fn disc_png() -> Vec<u8> {
let mut png = vec![];
image::RgbaImage::from_fn(100, 100, |x, y| {
let r = (f64::from(x) + 0.5 - 50.0).hypot(f64::from(y) + 0.5 - 50.0);
image::Rgba([255, 0, 0, if r <= 30.0 { 255 } else { 0 }])
})
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
{
let __dyn: image::DynamicImage = (image::RgbaImage::from_fn(100, 100, |x, y| {
let r = (f64::from(x) + 0.5 - 50.0).hypot(f64::from(y) + 0.5 - 50.0);
image::Rgba([255, 0, 0, if r <= 30.0 { 255 } else { 0 }])
}))
.into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| png.extend_from_slice(&__b))
}
.unwrap();
png
}
@@ -316,9 +381,41 @@ fn an_images_stroke_with_outline_object_follows_its_opaque_area() {
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("opaque.png");
let mut png = vec![];
image::RgbaImage::from_pixel(100, 100, image::Rgba([255, 0, 0, 255]))
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
.unwrap();
{
let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(100, 100, image::Rgba([255, 0, 0, 255]))).into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| png.extend_from_slice(&__b))
}
.unwrap();
std::fs::write(&path, png).unwrap();
run(&mut s, "links.relink", json!({"ids": [im.0], "path": path}));
assert_eq!([shade(&s, 41, 100), shade(&s, 45, 100), shade(&s, 64, 100)], ["white", "black", "red"]);
+21
View File
@@ -174,6 +174,27 @@ fn language_picks_its_quotes_unless_quotes_are_given() {
assert_eq!((setup(&s).quotes.double, setup(&s).quotes.single), (['“', '”'], ['‹', '›']));
}
/// Sanskrit, Nepali, Assamese, Konkani and Sindhi (#4943): each is a document language, new type
/// takes its tag, and each can be set on a text by name or tag.
#[test]
fn the_further_indian_languages_are_document_and_text_languages() {
let mut s = session();
let id = create_text(&mut s, "a");
for (name, tag) in [("Sanskrit", "sa"), ("Nepali", "ne"), ("Assamese", "as"), ("Konkani", "kok"), ("Sindhi", "sd")] {
s.execute("document.setup", &json!({"language": name.to_lowercase()})).unwrap();
assert_eq!((setup(&s).language.as_str(), setup(&s).quotes.double), (name, ['“', '”']));
let new = create_text(&mut s, "b");
assert_eq!(text(&s, new).runs[0].style.language.as_deref(), Some(tag), "new type in {name}");
s.execute("document.setup", &json!({"language": "English: USA"})).unwrap();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("text.setFormat", &json!({"language": name})).unwrap();
assert_eq!(text(&s, id).runs[0].style.language.as_deref(), Some(tag), "{name} by name");
s.execute("text.setFormat", &json!({"language": "English: USA"})).unwrap();
s.execute("text.setFormat", &json!({"language": tag.to_uppercase()})).unwrap();
assert_eq!(text(&s, id).runs[0].style.language.as_deref(), Some(tag), "{name} by tag");
}
}
#[test]
fn typographers_quotes_setting_changes_typed_quotes() {
let mut s = session();
+215 -3
View File
@@ -2658,6 +2658,66 @@ fn shape_arc_closed_along_y_closes_through_the_top_left_corner() {
assert!((area - std::f64::consts::FRAC_PI_4).abs() < 0.01, "{area}");
}
/// A `reference` that is not a whole number from 0 to 8, a `baseAlong` other than x or y, and a
/// `slope` outside -100 to 100 are errors naming the key in both forms of `shape.arc`, null
/// included, and nothing is drawn and no undo step is added.
#[test]
fn shape_arc_rejects_an_invalid_reference_base_along_or_slope() {
let mut s = session();
let objects = |s: &Session| s.doc().unwrap().doc.layers[0].children().unwrap().len();
let undo = |s: &Session| s.doc().unwrap().history.undo.len();
let (before, steps) = (objects(&s), undo(&s));
let sized = json!({"x": 100, "y": 50, "lengthX": 80, "lengthY": 40});
let ends = json!({"x1": 0, "y1": 0, "x2": 50, "y2": 50});
let mut cases = vec![];
for v in [json!("4"), json!(-1), json!(4.5), json!(9), json!(9.0), json!(true), json!(null), json!([0])] {
cases.push(("reference", "`reference` must be a whole number from 0 to 8".to_string(), v));
}
for v in [json!("z"), json!("yes"), json!(""), json!(1), json!(false), json!(null), json!({"axis": "y"})] {
cases.push(("baseAlong", "`baseAlong` must be one of x, y".to_string(), v));
}
for (v, shown) in [(json!(150), "150"), (json!(-100.5), "-100.5")] {
cases.push(("slope", format!("`slope` must be from -100 to 100, not {shown}"), v));
}
for form in [&sized, &ends] {
for (key, want, v) in &cases {
let mut p = form.clone();
p[*key] = v.clone();
let r = s.execute("shape.arc", &p);
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == want), "{p}: {r:?}");
assert_eq!((objects(&s), undo(&s)), (before, steps), "{p}");
}
}
}
/// `shape.arc` takes each of the nine reference points (`4.0` as 4) and x or y in either case for
/// `baseAlong`; a left-out `reference` is 0 and a left-out `baseAlong` is x.
#[test]
fn shape_arc_takes_every_reference_point_and_either_base_axis() {
let mut s = session();
let arc = |s: &mut Session, extra: serde_json::Value| {
let mut p = json!({"x": 100, "y": 50, "lengthX": 80, "lengthY": 40});
for (k, v) in extra.as_object().unwrap() {
p[k] = v.clone();
}
let id = NodeId(s.execute("shape.arc", &p).unwrap()["id"].as_u64().unwrap());
s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().clone()
};
let start = |path: &PathData| path.subpaths[0].anchors[0].p;
for r in 0..=8u64 {
let p = start(&arc(&mut s, json!({ "reference": r })));
let (col, row) = ((r % 3) as f64, (r / 3) as f64);
assert_eq!(p, Point::new(100.0 - 40.0 * col, 50.0 - 20.0 * row), "reference {r}");
}
assert_eq!(arc(&mut s, json!({"reference": 4.0})), arc(&mut s, json!({"reference": 4})));
assert_eq!(arc(&mut s, json!({})), arc(&mut s, json!({"reference": 0, "baseAlong": "x"})));
assert_eq!(arc(&mut s, json!({"baseAlong": "X"})), arc(&mut s, json!({"baseAlong": "x"})));
assert_eq!(arc(&mut s, json!({"baseAlong": "Y"})), arc(&mut s, json!({"baseAlong": "y"})));
assert_ne!(arc(&mut s, json!({"baseAlong": "y"})), arc(&mut s, json!({"baseAlong": "x"})));
let ends = json!({"x1": 0, "y1": 0, "x2": 50, "y2": 50, "slope": -100});
assert!(s.execute("shape.arc", &ends).is_ok());
}
/// A spiral dragged out with Alt pressed part way gets four more segments per wind as its outer end
/// moves out. Ctrl/Cmd pressed part way fits the decay so the inner end keeps its distance from the
/// center. The Spiral tool keeps both values for the next spiral.
@@ -2822,7 +2882,7 @@ fn polar_grid_options_compound_fill_and_skew() {
assert!(tips(&inward)[1..].iter().all(|t| t.x < 50.0), "counterclockwise of the top: {:?}", tips(&inward));
}
/// A divider count written as a whole float (`3.0`) is the same as `3`; a fraction gives the default 5.
/// A divider count written as a whole float (`3.0`) is the same as `3`.
#[test]
fn grid_divider_counts_accept_whole_floats() {
let mut s = session();
@@ -2834,8 +2894,30 @@ fn grid_divider_counts_accept_whole_floats() {
let float = grid(&mut s, "shape.polarGrid", with(&size, json!({"concentric": 2.0, "radial": 3.0})));
let int = grid(&mut s, "shape.polarGrid", with(&size, json!({"concentric": 2, "radial": 3})));
assert_eq!(float.len(), int.len());
let frac = grid(&mut s, "shape.rectangularGrid", with(&size, json!({"rows": 2.5, "columns": 2.5})));
assert_eq!(frac.len(), 11);
}
/// A divider count that is not a whole number of 0 or more (a fraction, a negative) is an error
/// naming the key, and no grid is made; a left-out or null count is 5.
#[test]
fn grid_divider_counts_reject_fractions_and_negatives() {
let mut s = session();
let size = json!({"x": 0, "y": 0, "width": 100, "height": 100});
let undo = |s: &Session| s.doc().unwrap().history.undo.len();
let before = undo(&s);
for (cmd, key, value, shown) in [
("shape.rectangularGrid", "rows", json!(2.5), "2.5"),
("shape.rectangularGrid", "columns", json!(-1), "-1"),
("shape.polarGrid", "concentric", json!(0.5), "0.5"),
("shape.polarGrid", "radial", json!(-3.0), "-3"),
] {
let r = s.execute(cmd, &with(&size, json!({ key: value })));
let want = format!("`{key}` must be a whole number of at least 0, not {shown}");
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if *msg == want), "{cmd} {key}={value}: {r:?}");
assert_eq!(undo(&s), before, "{cmd} {key}={value}");
}
let omitted = grid(&mut s, "shape.rectangularGrid", size.clone());
let null = grid(&mut s, "shape.rectangularGrid", with(&size, json!({"rows": null, "columns": null})));
assert_eq!((omitted.len(), null.len()), (11, 11));
}
/// The grid options are checked: a divider count or a skew is a number and a switch true or false,
@@ -3219,6 +3301,88 @@ fn split_refuses_a_subpath_anchor_or_segment_that_is_not_a_whole_number() {
}
}
/// Give `id` a 4 pt round-capped Inside stroke and, above it, a hidden red copy aligned Outside.
/// Returns the appearance it now has.
fn side_strokes(s: &mut Session, id: NodeId) -> vectorcraft_doc::Appearance {
use vectorcraft_doc::{AppearanceItem, LineCap, StrokeAlign};
s.edit("Side Strokes", |d, _| {
let ap = &mut d.node_mut(id).unwrap().appearance;
let st = ap.stroke_mut().unwrap();
(st.width, st.cap, st.align) = (4.0, LineCap::Round, StrokeAlign::Inside);
let mut top = st.clone();
(top.align, top.visible, top.paint) =
(StrokeAlign::Outside, false, vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0)));
ap.items.push(AppearanceItem::Stroke(top));
Ok(())
})
.unwrap();
appearance(s, id)
}
fn appearance(s: &Session, id: NodeId) -> vectorcraft_doc::Appearance {
(*s.doc().unwrap().doc.node(id).unwrap().appearance).clone()
}
/// `ap` with every stroke aligned Center and nothing else changed.
fn centered(ap: &vectorcraft_doc::Appearance) -> vectorcraft_doc::Appearance {
let mut ap = ap.clone();
for it in &mut ap.items {
if let vectorcraft_doc::AppearanceItem::Stroke(st) = it {
st.align = vectorcraft_doc::StrokeAlign::Center;
}
}
ap
}
#[test]
fn scissors_cut_paths_have_their_strokes_centered() {
// The paths a Scissors cut makes keep the source's fill and strokes, every stroke centered,
// in the cut's one undo step; redo centers them again.
let mut s = session();
let r = rect(&mut s, 100.0, 100.0, 100.0, 100.0);
let before = side_strokes(&mut s, r);
assert_ne!(before, centered(&before));
let undo = undo_steps(&s);
s.execute("path.split", &json!({"id": r.0, "anchor": 2})).unwrap();
assert_eq!(undo_steps(&s), undo + 1);
assert!(!path(&s, r).subpaths[0].closed);
assert_eq!(appearance(&s, r), centered(&before), "closed path");
s.execute("edit.undo", &json!({})).unwrap();
assert!(path(&s, r).subpaths[0].closed);
assert_eq!(appearance(&s, r), before, "undo");
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(appearance(&s, r), centered(&before), "redo");
// An open path becomes two, at an anchor or inside a segment, both centered.
let anchors = json!([{"x": 100, "y": 300}, {"x": 200, "y": 300}, {"x": 300, "y": 300}]);
for at in [json!({"anchor": 1}), json!({"segment": 0, "t": 0.5})] {
let id = NodeId(s.execute("path.create", &json!({"anchors": anchors})).unwrap()["id"].as_u64().unwrap());
let before = side_strokes(&mut s, id);
let made = s.execute("path.split", &with(&at, json!({"id": id.0}))).unwrap();
let ids: Vec<NodeId> = made["ids"].as_array().unwrap().iter().map(|v| NodeId(v.as_u64().unwrap())).collect();
assert_eq!(ids.len(), 2, "{at}");
for i in ids {
assert_eq!(appearance(&s, i), centered(&before), "{at}: {i:?}");
}
}
// A path of several subpaths keeps one node: its other subpath's strokes are centered too.
let id = two_subpaths(&mut s);
let before = side_strokes(&mut s, id);
s.execute("path.split", &json!({"id": id.0, "anchor": 1})).unwrap();
assert_eq!(path(&s, id).subpaths.len(), 3);
assert_eq!(appearance(&s, id), centered(&before), "several subpaths");
// A cut that fails, at an open path's end point, changes neither the strokes nor the history.
let id = NodeId(s.execute("path.create", &json!({"anchors": anchors})).unwrap()["id"].as_u64().unwrap());
let before = side_strokes(&mut s, id);
let undo = undo_steps(&s);
assert!(s.execute("path.split", &json!({"id": id.0, "anchor": 0})).is_err());
assert_eq!((undo_steps(&s), appearance(&s, id)), (undo, before));
// Strokes already centered stay shared with the undo history's copy.
let id = NodeId(s.execute("path.create", &json!({"anchors": anchors})).unwrap()["id"].as_u64().unwrap());
let shared = s.doc().unwrap().doc.node(id).unwrap().appearance.clone();
s.execute("path.split", &json!({"id": id.0, "anchor": 1})).unwrap();
assert!(vectorcraft_doc::Shared::ptr_eq(&s.doc().unwrap().doc.node(id).unwrap().appearance, &shared));
}
/// A subpath, anchor or segment of 2^32 + k fails, where k names one that exists, and the document
/// and the undo history stay as they were. A 32-bit build read the number as k.
#[test]
@@ -3938,6 +4102,54 @@ fn cut_at_anchors_splits_paths_and_leaves_one_end_selected() {
assert_eq!(undo_steps(&s), undo);
}
#[test]
fn cut_at_anchors_paths_have_their_strokes_centered() {
// Every path the cut makes keeps the source's fill and strokes, every stroke centered, in one
// undo step; a path whose anchors were not selected keeps its strokes.
let mut s = session();
let anchors = json!([{"x": 100, "y": 100}, {"x": 200, "y": 100}, {"x": 300, "y": 100}, {"x": 400, "y": 100}]);
let id = NodeId(s.execute("path.create", &json!({"anchors": anchors})).unwrap()["id"].as_u64().unwrap());
let open = side_strokes(&mut s, id);
let r = rect(&mut s, 500.0, 100.0, 100.0, 100.0);
let closed = side_strokes(&mut s, r);
let other = rect(&mut s, 100.0, 300.0, 100.0, 100.0);
let untouched = side_strokes(&mut s, other);
s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 1], [0, 2]]})).unwrap();
s.execute("select.anchors", &json!({"id": r.0, "anchors": [[0, 2]], "mode": "add"})).unwrap();
assert_eq!(s.doc().unwrap().selection.anchors.len(), 2);
let undo = undo_steps(&s);
let made = s.execute("path.cutAtAnchors", &json!({})).unwrap();
let ids: Vec<NodeId> = made["ids"].as_array().unwrap().iter().map(|v| NodeId(v.as_u64().unwrap())).collect();
assert_eq!(undo_steps(&s), undo + 1);
assert_eq!(ids.len(), 4, "three pieces and the opened rectangle");
for i in &ids {
let want = if *i == r { centered(&closed) } else { centered(&open) };
assert_eq!(appearance(&s, *i), want, "{i:?}");
}
assert_eq!(appearance(&s, other), untouched);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!((appearance(&s, id), appearance(&s, r)), (open.clone(), closed.clone()), "undo");
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!((appearance(&s, id), appearance(&s, r)), (centered(&open), centered(&closed)), "redo");
// A cut member of a compound path: the compound path's strokes, which it shows, are centered.
let a = rect(&mut s, 100.0, 450.0, 100.0, 100.0);
let b = rect(&mut s, 125.0, 475.0, 50.0, 50.0);
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
s.execute("object.compoundPath.make", &json!({})).unwrap();
let compound = s.doc().unwrap().selection.objects[0];
let before = side_strokes(&mut s, compound);
let members: Vec<NodeId> = match &s.doc().unwrap().doc.node(compound).unwrap().kind {
NodeKind::Compound { children, .. } => children.iter().map(|c| c.id).collect(),
k => panic!("not a compound path: {k:?}"),
};
let held = path(&s, members[1]);
s.execute("select.anchors", &json!({"id": members[0].0, "anchors": [[0, 2]]})).unwrap();
s.execute("path.cutAtAnchors", &json!({})).unwrap();
assert!(!path(&s, members[0]).subpaths[0].closed);
assert_eq!(path(&s, members[1]), held, "the other member keeps its shape");
assert_eq!(appearance(&s, compound), centered(&before), "compound path");
}
#[test]
fn direct_segment_delete_keeps_the_other_rectangle_edges_and_one_undo() {
for initially_selected in [false, true] {
+35 -1
View File
@@ -798,7 +798,41 @@ fn a_blend_around_a_picked_objects_instance_is_left_alone() {
fn image_symbol(s: &mut Session) -> (NodeId, Value) {
let mut png = Vec::new();
let pixels = image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(2, 1, vec![0, 255]).unwrap());
pixels.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
{
let __dyn: image::DynamicImage = pixels;
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| png.extend_from_slice(&__b))
}
.unwrap();
let im = s
.edit("Place", |d, _| {
d.images.insert("gray".into(), vectorcraft_doc::ImageBlob::png(png));
+126 -4
View File
@@ -403,14 +403,68 @@ fn blend_moves_a_mesh_to_the_blended_colour() {
fn png(px: [[u8; 4]; 4]) -> Vec<u8> {
let img = image::RgbaImage::from_raw(2, 2, px.concat()).unwrap();
let mut out = Vec::new();
img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap();
{
let __dyn: image::DynamicImage = img.into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| out.extend_from_slice(&__b))
}
.unwrap();
out
}
fn pixels(s: &Session, id: NodeId) -> Vec<[u8; 4]> {
let d = &s.doc().unwrap().doc;
let NodeKind::Image(im) = &d.node(id).unwrap().kind else { panic!("not an image") };
image::load_from_memory(&d.images[&im.key].bytes).unwrap().to_rgba8().pixels().map(|p| p.0).collect()
craft_image_codecs::decode(&d.images[&im.key].bytes)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8()
.pixels()
.map(|p| p.0)
.collect()
}
/// A selected embedded 2×2 image.
@@ -652,7 +706,41 @@ fn convert_to_indexed_refuses_bad_params() {
/// An embedded `w` × `h` image of the pixels `f(x, y)`, placed and selected.
fn placed(s: &mut Session, w: u32, h: u32, f: impl Fn(u32, u32) -> [u8; 4]) -> NodeId {
let mut png = Vec::new();
image::RgbaImage::from_fn(w, h, |x, y| image::Rgba(f(x, y))).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
{
let __dyn: image::DynamicImage = (image::RgbaImage::from_fn(w, h, |x, y| image::Rgba(f(x, y)))).into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| png.extend_from_slice(&__b))
}
.unwrap();
let r = s.execute("file.place", &json!({"name": "art.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap();
NodeId(r["ids"][0].as_u64().unwrap())
}
@@ -681,7 +769,41 @@ fn convert_to_indexed_takes_ids_and_leaves_linked_and_colorized_images() {
assert_eq!(image_key(&s, a), ka);
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step");
let mut png = Vec::new();
image::GrayImage::from_pixel(4, 4, image::Luma([90])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
{
let __dyn: image::DynamicImage = (image::GrayImage::from_pixel(4, 4, image::Luma([90]))).into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| png.extend_from_slice(&__b))
}
.unwrap();
let r = s.execute("file.place", &json!({"name": "gray.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap();
let gray = NodeId(r["ids"][0].as_u64().unwrap());
s.execute("paint.setFill", &json!({"ids": [gray.0], "color": "#ff0000"})).unwrap();
+105 -3
View File
@@ -117,7 +117,41 @@ fn the_frame_round_trips_natively() {
fn red_image(s: &mut Session) -> NodeId {
let img = image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 0, 0, 255]));
let mut png = vec![];
img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
{
let __dyn: image::DynamicImage = img.into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| png.extend_from_slice(&__b))
}
.unwrap();
s.edit("Place", |d, sel| {
d.images.insert("pic".into(), vectorcraft_doc::ImageBlob::png(png));
let id = d.alloc_id();
@@ -159,7 +193,41 @@ fn a_colorized_image_keeps_its_color_in_an_envelope() {
let mut s = session();
let img = image::GrayImage::from_pixel(4, 4, image::Luma([0]));
let mut png = vec![];
image::DynamicImage::ImageLuma8(img).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
{
let __dyn: image::DynamicImage = image::DynamicImage::ImageLuma8(img);
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| png.extend_from_slice(&__b))
}
.unwrap();
let im = s
.edit("Place", |d, sel| {
d.images.insert("gray".into(), vectorcraft_doc::ImageBlob::png(png));
@@ -187,7 +255,41 @@ fn a_colorized_image_keeps_its_color_in_an_envelope() {
fn two_color_image(s: &mut Session) -> NodeId {
let img = image::RgbaImage::from_fn(2, 2, |x, _| if x == 0 { image::Rgba([255, 0, 0, 255]) } else { image::Rgba([0, 0, 255, 255]) });
let mut png = vec![];
img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
{
let __dyn: image::DynamicImage = img.into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| png.extend_from_slice(&__b))
}
.unwrap();
s.edit("Place", |d, sel| {
d.images.insert("two".into(), vectorcraft_doc::ImageBlob::png(png));
let id = d.alloc_id();
+70 -2
View File
@@ -562,7 +562,41 @@ fn clicking_an_image_samples_its_pixel() {
// Two pixels, orange and teal, 100 pt each, at (300, 0).
let img = image::RgbaImage::from_raw(2, 1, [[255, 128, 0, 255], [0, 128, 128, 255]].concat()).unwrap();
let mut png = vec![];
img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
{
let __dyn: image::DynamicImage = img.into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| png.extend_from_slice(&__b))
}
.unwrap();
s.edit("Place", |d, _| {
d.images.insert("px".into(), ImageBlob::png(png));
let l = d.layers[0].id;
@@ -588,7 +622,41 @@ fn cmyk_doc_with_image(px: &[[u8; 4]]) -> Session {
let w = px.len() as u32;
let img = image::RgbaImage::from_raw(w, 1, px.concat()).unwrap();
let mut png = vec![];
img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
{
let __dyn: image::DynamicImage = img.into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| png.extend_from_slice(&__b))
}
.unwrap();
s.edit("Place", |d, _| {
d.images.insert("px".into(), ImageBlob::png(png));
let l = d.layers[0].id;
+72 -4
View File
@@ -459,7 +459,24 @@ fn export_selection_keeps_the_effects_in_the_crop() {
assert_eq!(plain["bounds"], json!([99.5, 99.5, 21.0, 21.0]), "a plain path keeps its crop: {plain}");
s.execute("effect.apply", &json!({"effect": effect, "params": params})).unwrap();
let png = |v: &serde_json::Value| {
image::load_from_memory(&vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap()).unwrap().to_rgba8()
craft_image_codecs::decode(&vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap())
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8()
};
let v = s.execute("document.exportSelection", &json!({"format": "png", "background": "transparent"})).unwrap();
let b: Vec<f64> = v["bounds"].as_array().unwrap().iter().map(|n| n.as_f64().unwrap()).collect();
@@ -485,7 +502,24 @@ fn a_screen_outer_glow_is_in_raster_exports() {
s.execute("effect.apply", &json!({"effect": "stylize.outerGlow"})).unwrap();
let mut pixel = |p: serde_json::Value| {
let v = s.execute("document.export", &p).unwrap();
let img = image::load_from_memory(&vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap()).unwrap().to_rgba8();
let img = craft_image_codecs::decode(&vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap())
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8();
// 2 pt past the square's stroke, on the right.
*img.get_pixel(122, 110)
};
@@ -512,7 +546,24 @@ fn export_selection_keeps_a_groups_shadow_in_the_crop() {
let b: Vec<f64> = v["bounds"].as_array().unwrap().iter().map(|n| n.as_f64().unwrap()).collect();
// The shadow of the right square reaches x = 158.5.
assert!(b[0] < 99.5 && b[0] + b[2] >= 158.5, "{v}");
let img = image::load_from_memory(&vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap()).unwrap().to_rgba8();
let img = craft_image_codecs::decode(&vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap())
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8();
assert!(img.get_pixel((155.0 - b[0]) as u32, img.height() / 2)[3] > 0, "the shadow is in the image");
}
@@ -534,7 +585,24 @@ fn the_arts_bounds_take_in_the_shadow_of_a_group_and_of_type() {
s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "ids": [id], "params": {"x": 8, "y": 0, "blur": 0}})).unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
let png = |v: &serde_json::Value| {
image::load_from_memory(&vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap()).unwrap().to_rgba8()
craft_image_codecs::decode(&vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap())
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8()
};
let art = s.execute("document.export", &json!({"format": "png", "useArtboards": false, "background": "transparent"})).unwrap();
let sel = s.execute("document.exportSelection", &json!({"format": "png", "background": "transparent"})).unwrap();
+20 -1
View File
@@ -499,7 +499,26 @@ fn png_exports_carry_text_chunks() {
assert_eq!(get("Keywords"), Some("fair, Poster, print"));
assert_eq!(get("Copyright"), Some("(c) 2026 Ada"));
assert!(get("Creation Time").is_some_and(|t| t.ends_with('Z')));
assert!(image::load_from_memory(&png).is_ok(), "still a valid PNG");
assert!(
craft_image_codecs::decode(&png)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.is_ok(),
"still a valid PNG"
);
}
#[test]
+210 -9
View File
@@ -300,7 +300,41 @@ fn a_radial_gradient_lists_its_stops_from_the_first() {
/// A `w`×`h` PNG of one colour (`rgba`), 72 ppi.
fn png(w: u32, h: u32, rgba: [u8; 4]) -> Vec<u8> {
let mut out = vec![];
image::RgbaImage::from_pixel(w, h, image::Rgba(rgba)).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap();
{
let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(w, h, image::Rgba(rgba))).into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| out.extend_from_slice(&__b))
}
.unwrap();
out
}
@@ -402,7 +436,41 @@ fn disk(size: u32, r: f64) -> Vec<u8> {
image::Rgba([0, 0, 0, ((r + 0.5 - d).clamp(0.0, 1.0) * 255.0).round() as u8])
});
let mut out = vec![];
img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap();
{
let __dyn: image::DynamicImage = img.into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| out.extend_from_slice(&__b))
}
.unwrap();
out
}
@@ -530,7 +598,41 @@ fn colorized_bitmap_over_square() -> (Session, Vec<u8>) {
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
let gray = vec![0, 255, 0, 255, 255, 0, 255, 0];
let mut bytes = vec![];
image::GrayImage::from_raw(4, 2, gray.clone()).unwrap().write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap();
{
let __dyn: image::DynamicImage = (image::GrayImage::from_raw(4, 2, gray.clone()).unwrap()).into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| bytes.extend_from_slice(&__b))
}
.unwrap();
let p = json!({"name": "b.png", "dataBase64": vectorcraft_format::base64_encode(&bytes), "rect": [30, 10, 40, 20]});
s.execute("file.place", &p).unwrap();
s.execute("paint.setFill", &json!({"swatch": "Ink"})).unwrap();
@@ -593,10 +695,41 @@ fn a_colorized_image_of_black_and_clear_pixels_is_written_as_an_image_mask() {
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
s.execute("swatch.new", &json!({"name": "Ink", "color": {"c": 100, "m": 0, "y": 0, "k": 0}, "spot": true})).unwrap();
let mut bytes = vec![];
image::GrayAlphaImage::from_raw(2, 1, vec![0, 255, 0, 0])
.unwrap()
.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png)
.unwrap();
{
let __dyn: image::DynamicImage = (image::GrayAlphaImage::from_raw(2, 1, vec![0, 255, 0, 0]).unwrap()).into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| bytes.extend_from_slice(&__b))
}
.unwrap();
let p = json!({"name": "c.png", "dataBase64": vectorcraft_format::base64_encode(&bytes), "rect": [30, 10, 20, 10]});
s.execute("file.place", &p).unwrap();
s.execute("paint.setFill", &json!({"swatch": "Ink"})).unwrap();
@@ -732,7 +865,41 @@ fn an_artboard_the_document_does_not_have_is_refused_as_an_export_refuses_it() {
fn checker(a: [u8; 4], b: [u8; 4]) -> Vec<u8> {
let img = image::RgbaImage::from_fn(32, 32, |x, y| image::Rgba(if (x < 16) == (y < 16) { a } else { b }));
let mut out = vec![];
img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap();
{
let __dyn: image::DynamicImage = img.into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| out.extend_from_slice(&__b))
}
.unwrap();
out
}
@@ -760,7 +927,41 @@ fn colorized_pattern_over_blue() -> Session {
let tile = image::GrayImage::from_fn(32, 32, |x, y| image::Luma([if (x < 16) == (y < 16) { 0 } else { 255 }]));
let mut bytes = vec![];
tile.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap();
{
let __dyn: image::DynamicImage = tile.into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| bytes.extend_from_slice(&__b))
}
.unwrap();
let mut s = pattern_over_blue(&bytes, 1.0);
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
assert!(d.patterns[0].art.iter_mut().any(|art| colorize_image(std::sync::Arc::make_mut(art))));
+158 -7
View File
@@ -35,7 +35,41 @@ impl Drop for Folder {
pub(crate) fn png(w: u32, h: u32, rgb: [u8; 3]) -> Vec<u8> {
let mut out = vec![];
let [r, g, b] = rgb;
image::RgbaImage::from_pixel(w, h, image::Rgba([r, g, b, 255])).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap();
{
let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(w, h, image::Rgba([r, g, b, 255]))).into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| out.extend_from_slice(&__b))
}
.unwrap();
out
}
@@ -200,7 +234,41 @@ fn linked_dib_and_pns_files_place_update_and_relink() {
let bmp = |w: u32, h: u32, rgb: [u8; 3]| {
let mut out = vec![];
let [r, g, b] = rgb;
image::RgbImage::from_pixel(w, h, image::Rgb([r, g, b])).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Bmp).unwrap();
{
let __dyn: image::DynamicImage = (image::RgbImage::from_pixel(w, h, image::Rgb([r, g, b]))).into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Bmp, &craft_image_codecs::EncodeOptions::default())
.map(|__b| out.extend_from_slice(&__b))
}
.unwrap();
out
};
let dir = Folder::new("dib");
@@ -1300,7 +1368,41 @@ pub(crate) fn cut_png(w: u32, h: u32) -> Vec<u8> {
image::Rgb([v as u8, (v >> 8) as u8, (v >> 16) as u8])
});
let mut out = vec![];
img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap();
{
let __dyn: image::DynamicImage = img.into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| out.extend_from_slice(&__b))
}
.unwrap();
out.truncate(out.len() / 2);
out
}
@@ -1414,12 +1516,27 @@ fn low_res_proxy_eps_export_uses_full_resolution_from_the_linked_file() {
let (full, warnings) = cmd::links::full_linked_images(&s.doc().unwrap().doc, Default::default());
assert!(warnings.is_empty(), "{warnings:?}");
assert!(!full.images[&key].is_proxy());
let dim =
image::ImageReader::new(std::io::Cursor::new(full.images[&key].bytes.as_ref())).with_guessed_format().unwrap().into_dimensions().unwrap();
let dim = craft_image_codecs::decode(full.images[&key].bytes.as_ref()).unwrap().dimensions();
assert_eq!(dim, (600, 300));
let png_out = s.execute("document.export", &json!({"format": "png"})).unwrap();
let bytes = vectorcraft_format::base64_decode(png_out["dataBase64"].as_str().unwrap()).unwrap();
let rendered = image::load_from_memory(&bytes).unwrap();
let rendered = craft_image_codecs::decode(&bytes)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap();
assert!(rendered.width() >= 400 && rendered.height() >= 300);
assert!(near(centre_colour(&s.doc().unwrap().doc), RED), "canvas still shows the preview");
}
@@ -1489,7 +1606,41 @@ fn a_file_read_for_opening_has_its_links_read_and_its_type_laid_out() {
let dir = Folder::new("read-for-open");
let tif = dir.file("art/photo.tif");
let mut tiff = vec![];
image::RgbImage::from_pixel(600, 300, image::Rgb(RED)).write_to(&mut std::io::Cursor::new(&mut tiff), image::ImageFormat::Tiff).unwrap();
{
let __dyn: image::DynamicImage = (image::RgbImage::from_pixel(600, 300, image::Rgb(RED))).into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Tiff, &craft_image_codecs::EncodeOptions::default())
.map(|__b| tiff.extend_from_slice(&__b))
}
.unwrap();
write(&tif, &tiff);
let (gone, changed) = (dir.file("gone.png"), dir.file("changed.png"));
write(&gone, &png(300, 100, BLUE));
+35 -1
View File
@@ -1525,7 +1525,41 @@ fn two_colour_image(s: &mut Session, clear_right: bool, linked: bool) -> NodeId
let right = image::Rgba([0, 0, 255, if clear_right { 0 } else { 255 }]);
let img = image::RgbaImage::from_fn(8, 4, |x, _| if x < 4 { image::Rgba([255, 0, 0, 255]) } else { right });
let mut png = vec![];
img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
{
let __dyn: image::DynamicImage = img.into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| png.extend_from_slice(&__b))
}
.unwrap();
s.edit("Place", |d, sel| {
d.images.insert("pic".into(), vectorcraft_doc::ImageBlob::png(png));
let id = d.alloc_id();
+52 -2
View File
@@ -126,7 +126,23 @@ fn preview_is_at_most_256_pixels() {
let mut s = session();
let bytes = saved(&mut s, json!({"preview": true, "compress": true}));
let png = vectorcraft_format::preview(&bytes).expect("a preview");
let img = image::load_from_memory(&png).unwrap();
let img = craft_image_codecs::decode(&png)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap();
assert_eq!((img.width(), img.height()), (256, 128), "the 400×200 artboard fitted into 256 px");
assert!(vectorcraft_format::preview(&saved(&mut s, json!({}))).is_none(), "off by default");
}
@@ -154,7 +170,41 @@ fn saving_writes_through_a_temporary_file() {
fn unused_images_are_left_out_of_saves() {
let mut s = session();
let mut png = vec![];
image::RgbaImage::from_pixel(4, 4, image::Rgba([1, 2, 3, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
{
let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(4, 4, image::Rgba([1, 2, 3, 255]))).into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| png.extend_from_slice(&__b))
}
.unwrap();
let r = s.execute("file.place", &json!({"name": "a.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap();
let id = r["ids"][0].as_u64().unwrap();
assert_eq!(json_of(&saved(&mut s, json!({})))["images"].as_object().unwrap().len(), 1);

Some files were not shown because too many files have changed in this diff Show More