[doc] Editor core: document model, exact undo, .pictor format, text layout, display list, tiny-skia render, bitmap tools, SVG import, PNG/JPG/SVG/PDF export; worker doc.open and doc.import_svg
This commit is contained in:
@@ -0,0 +1,174 @@
|
||||
//! Bitmap tools: fill tolerance, magic wand, lasso, delete, brush clipped by a selection, adjustments' identities,
|
||||
//! the clone stamp, and exact undo of a pixel edit.
|
||||
use pictor_doc::bitmap::{self, Adjust, Brush, Mask};
|
||||
use pictor_doc::ops::History;
|
||||
use pictor_doc::*;
|
||||
|
||||
/// Left half red, right half a slightly different red, with a black wall at x = 30.
|
||||
fn two_reds() -> Raster {
|
||||
let mut r = Raster::new(60, 40);
|
||||
for y in 0..40 {
|
||||
for x in 0..60 {
|
||||
let i = (y * 60 + x) * 4;
|
||||
let c = if x == 30 {
|
||||
[0, 0, 0, 255]
|
||||
} else if x < 30 {
|
||||
[200, 20, 20, 255]
|
||||
} else {
|
||||
[206, 24, 20, 255]
|
||||
};
|
||||
r.rgba[i..i + 4].copy_from_slice(&c);
|
||||
}
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fill_respects_tolerance_and_walls() {
|
||||
let mut r = two_reds();
|
||||
bitmap::fill(&mut r, 5, 5, 0, [0, 0, 255, 255], None);
|
||||
assert_eq!(r.pixel(29, 39), [0, 0, 255, 255]);
|
||||
assert_eq!(r.pixel(30, 5), [0, 0, 0, 255], "the wall stays");
|
||||
assert_eq!(r.pixel(40, 5), [206, 24, 20, 255], "behind the wall nothing changes");
|
||||
// Without the wall, tolerance 10 takes the near red too, tolerance 0 does not.
|
||||
let mut r = two_reds();
|
||||
for y in 0..40 {
|
||||
let i = (y * 60 + 30) * 4;
|
||||
r.rgba[i..i + 4].copy_from_slice(&[203, 22, 20, 255]);
|
||||
}
|
||||
let mut strict = r.clone();
|
||||
bitmap::fill(&mut strict, 5, 5, 0, [0, 255, 0, 255], None);
|
||||
assert_eq!(strict.pixel(45, 5), [206, 24, 20, 255]);
|
||||
bitmap::fill(&mut r, 5, 5, 10, [0, 255, 0, 255], None);
|
||||
assert_eq!(r.pixel(45, 5), [0, 255, 0, 255]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wand_selects_a_region_and_delete_clears_only_it() {
|
||||
let mut r = two_reds();
|
||||
let m = bitmap::region(&r, 5, 5, 0);
|
||||
assert_eq!(m.bbox(), PixelRect { x: 0, y: 0, w: 30, h: 40 });
|
||||
bitmap::clear(&mut r, Some(&m));
|
||||
assert_eq!(r.pixel(10, 10)[3], 0);
|
||||
assert_eq!(r.pixel(30, 10), [0, 0, 0, 255]);
|
||||
assert_eq!(r.pixel(50, 10), [206, 24, 20, 255]);
|
||||
assert!(!m.outline().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lasso_and_rect_masks() {
|
||||
let m = Mask::polygon(100, 100, &[(10.0, 10.0), (90.0, 10.0), (10.0, 90.0)]);
|
||||
assert_eq!(m.get(20, 20), 255);
|
||||
assert_eq!(m.get(80, 80), 0);
|
||||
let r = Mask::rect(50, 50, PixelRect { x: 10, y: 10, w: 5, h: 5 });
|
||||
assert_eq!(r.bbox(), PixelRect { x: 10, y: 10, w: 5, h: 5 });
|
||||
let o = r.outline();
|
||||
assert_eq!(o.matches('M').count(), 4, "{o}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_brush_stroke_paints_along_its_path_inside_the_selection() {
|
||||
let mut r = Raster::filled(100, 60, [255, 255, 255, 255]);
|
||||
let sel = Mask::rect(100, 60, PixelRect { x: 0, y: 0, w: 50, h: 60 });
|
||||
let b = Brush { radius: 6.0, hardness: 0.8, color: [0, 0, 0, 255], opacity: 1.0, erase: false };
|
||||
let dirty = bitmap::brush(&mut r, &[(10.0, 30.0, 1.0), (90.0, 30.0, 1.0)], &b, Some(&sel));
|
||||
assert!(dirty.w > 70);
|
||||
assert_eq!(r.pixel(30, 30), [0, 0, 0, 255], "painted on the line");
|
||||
assert_eq!(r.pixel(30, 5), [255, 255, 255, 255], "away from the line");
|
||||
assert_eq!(r.pixel(70, 30), [255, 255, 255, 255], "outside the selection");
|
||||
// The eraser takes the alpha.
|
||||
bitmap::brush(&mut r, &[(30.0, 30.0, 1.0)], &Brush { erase: true, ..b }, None);
|
||||
assert_eq!(r.pixel(30, 30)[3], 0);
|
||||
// A pencil sets exact pixels.
|
||||
bitmap::pencil(&mut r, &[(0.0, 0.0), (5.0, 0.0)], 1, [1, 2, 3, 255], false, None);
|
||||
assert_eq!(r.pixel(3, 0), [1, 2, 3, 255]);
|
||||
assert_eq!(r.pixel(3, 1), [255, 255, 255, 255]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn neutral_adjustments_change_nothing_and_invert_twice_returns() {
|
||||
let src = fixtures::picture(64, 48);
|
||||
for a in [
|
||||
Adjust::Brightness { amount: 0.0 },
|
||||
Adjust::Contrast { amount: 0.0 },
|
||||
Adjust::Levels { in_black: 0.0, in_white: 255.0, gamma: 1.0, out_black: 0.0, out_white: 255.0 },
|
||||
Adjust::HueSaturation { hue: 0.0, saturation: 0.0, lightness: 0.0 },
|
||||
Adjust::Sharpen { amount: 0.0, radius: 2.0 },
|
||||
] {
|
||||
let mut dst = src.clone();
|
||||
bitmap::adjust(&src, &mut dst, &a, None);
|
||||
let worst = src.rgba.iter().zip(&dst.rgba).map(|(a, b)| (*a as i16 - *b as i16).abs()).max().unwrap();
|
||||
assert!(worst <= 1, "{a:?} changed a pixel by {worst}");
|
||||
}
|
||||
let mut once = src.clone();
|
||||
bitmap::adjust(&src, &mut once, &Adjust::Invert, None);
|
||||
assert_ne!(once, src);
|
||||
let mut twice = once.clone();
|
||||
bitmap::adjust(&once, &mut twice, &Adjust::Invert, None);
|
||||
assert_eq!(twice, src);
|
||||
// Brightness +50 makes a mid grey lighter; a blur smooths an edge.
|
||||
let grey = Raster::filled(4, 4, [100, 100, 100, 255]);
|
||||
let mut lighter = grey.clone();
|
||||
bitmap::adjust(&grey, &mut lighter, &Adjust::Brightness { amount: 50.0 }, None);
|
||||
assert!(lighter.pixel(0, 0)[0] > 200);
|
||||
let mut edge = Raster::filled(20, 1, [0, 0, 0, 255]);
|
||||
for x in 10..20 {
|
||||
edge.rgba[x * 4..x * 4 + 3].copy_from_slice(&[255, 255, 255]);
|
||||
}
|
||||
let mut soft = edge.clone();
|
||||
bitmap::adjust(&edge, &mut soft, &Adjust::Blur { radius: 3.0 }, None);
|
||||
let mid = soft.pixel(10, 0)[0];
|
||||
assert!(mid > 40 && mid < 230, "{mid}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_clone_stamp_copies_from_its_offset() {
|
||||
let src = fixtures::picture(80, 80);
|
||||
let mut r = src.clone();
|
||||
let b = Brush { radius: 4.0, hardness: 1.0, color: [0; 4], opacity: 1.0, erase: false };
|
||||
bitmap::clone_stamp(&mut r, &src, (30.0, 10.0), &[(20.0, 20.0, 1.0)], &b, None);
|
||||
assert_eq!(r.pixel(20, 20), src.pixel(50, 30));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pixel_edit_undoes_exactly() {
|
||||
let mut doc = fixtures::bitmap();
|
||||
let original = doc.clone();
|
||||
let asset = doc.assets.keys().next().unwrap().clone();
|
||||
let b = Brush { radius: 10.0, hardness: 0.3, color: [10, 200, 30, 255], opacity: 0.8, erase: false };
|
||||
let (op, inv) =
|
||||
bitmap::edit(&mut doc, &asset, |r| bitmap::brush(r, &[(20.0, 20.0, 1.0), (200.0, 140.0, 0.5)], &b, None))
|
||||
.unwrap();
|
||||
let mut h = History::default();
|
||||
h.record(op, inv);
|
||||
assert_ne!(doc, original);
|
||||
assert!(h.undo(&mut doc).unwrap());
|
||||
assert_eq!(doc, original);
|
||||
assert!(h.redo(&mut doc).unwrap());
|
||||
assert_ne!(doc, original);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn svg_import_makes_objects() {
|
||||
let svg = br##"<svg xmlns="http://www.w3.org/2000/svg" width="200" height="100" viewBox="0 0 200 100">
|
||||
<defs><linearGradient id="g" x1="0" y1="0" x2="1" y2="0"><stop offset="0" stop-color="#f27ab9"/><stop offset="1" stop-color="#1f2a44"/></linearGradient></defs>
|
||||
<rect x="10" y="10" width="80" height="40" rx="6" fill="url(#g)" stroke="#000" stroke-width="2"/>
|
||||
<g opacity="0.5"><circle cx="150" cy="50" r="30" fill="#3ad07a"/></g>
|
||||
<path d="M10 90 A 20 20 0 0 1 50 90" fill="none" stroke="red" stroke-width="3" stroke-dasharray="4 2"/>
|
||||
<text x="100" y="95" font-family="Arial" font-size="12">Hello</text>
|
||||
</svg>"##;
|
||||
let doc = svg::import(svg, svg::system_fontdb()).unwrap();
|
||||
assert!((doc.pages[0].width - 150.0).abs() < 0.01, "200 px = 150 pt");
|
||||
let LayerKind::Vector { objects } = &doc.pages[0].layers[0].kind else { panic!() };
|
||||
let Shape::Group { objects: inner } = &objects[0].shape else { panic!() };
|
||||
assert!(inner.len() >= 4, "{}", inner.len());
|
||||
assert!(inner.iter().any(|o| matches!(o.fill, Some(Paint::Linear { .. }))));
|
||||
assert!(inner.iter().any(|o| matches!(o.shape, Shape::Group { .. }) && o.opacity < 0.6));
|
||||
assert!(inner.iter().any(|o| o.stroke.as_ref().is_some_and(|s| !s.dash.is_empty())));
|
||||
// It renders and round-trips through the format.
|
||||
let book = FontBook::system();
|
||||
assert!(render::page(&doc, &doc.pages[0], &book, 1.0).is_some());
|
||||
let bytes = format::write(&doc, &[]).unwrap();
|
||||
assert_eq!(format::read(&bytes, &Limits::default()).unwrap().0, doc);
|
||||
assert!(svg::import(b"<svg><g", svg::system_fontdb()).is_err());
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
//! Day 3 mandatory test 3 (the PDF half): a PDF export keeps its text extractable in reading order and every page at
|
||||
//! its exact size; pdfium draws it like the core's own render. Also PNG at a scale, JPG and SVG.
|
||||
use pictor_doc::{Document, FontBook, export, fixtures, render};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
fn book() -> &'static FontBook {
|
||||
static B: OnceLock<FontBook> = OnceLock::new();
|
||||
B.get_or_init(FontBook::system)
|
||||
}
|
||||
|
||||
fn engine() -> &'static pictor_pdf::Engine {
|
||||
let dir = std::env::var_os("PDFIUM_DYNAMIC_LIB_PATH")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../third_party/pdfium/bin"));
|
||||
pictor_pdf::Engine::load(Some(&dir)).expect("pdfium: run scripts/fetch-pdfium.ps1 first")
|
||||
}
|
||||
|
||||
/// An A4 page with the text fixture's boxes on it, plus a second page of another size.
|
||||
fn a4_with_text() -> Document {
|
||||
let mut d = fixtures::text();
|
||||
d.pages[0].width = pictor_doc::A4.0;
|
||||
d.pages[0].height = pictor_doc::A4.1;
|
||||
let mut second = fixtures::shapes().pages.remove(0);
|
||||
second.id = d.new_id();
|
||||
for l in &mut second.layers {
|
||||
l.id = d.new_id();
|
||||
if let pictor_doc::LayerKind::Vector { objects } = &mut l.kind {
|
||||
for o in objects {
|
||||
o.id = d.new_id();
|
||||
}
|
||||
}
|
||||
}
|
||||
d.pages.push(second);
|
||||
d
|
||||
}
|
||||
|
||||
fn squash(s: &str) -> String {
|
||||
s.split_whitespace().collect::<Vec<_>>().join(" ")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pdf_text_is_extractable_in_order_and_pages_are_exact() {
|
||||
let doc = a4_with_text();
|
||||
let pdf = export::pdf(&doc, book()).unwrap();
|
||||
std::fs::write(format!("{}/export-text.pdf", env!("CARGO_TARGET_TMPDIR")), &pdf).unwrap();
|
||||
let sizes = pictor_pdf::page_sizes(engine(), &pdf, None).unwrap();
|
||||
assert_eq!(sizes.len(), 2);
|
||||
assert!((sizes[0].0 - 595.276).abs() < 0.01 && (sizes[0].1 - 841.89).abs() < 0.01, "A4 is {sizes:?}");
|
||||
assert!((sizes[1].0 - 400.0).abs() < 0.01 && (sizes[1].1 - 300.0).abs() < 0.01, "{sizes:?}");
|
||||
let text = pictor_pdf::extract_text(engine(), &pdf, None).unwrap();
|
||||
let t = squash(&text[0]);
|
||||
let mut at = 0;
|
||||
for w in [
|
||||
"Monika Nováková",
|
||||
"Pictor lays text out in the core: shaping,",
|
||||
"line breaks and alignment, so the screen",
|
||||
"Příliš žluťoučký kůň",
|
||||
"úpěl ďábelské ódy.",
|
||||
"Centred",
|
||||
"in two lines",
|
||||
"Right, italic",
|
||||
] {
|
||||
match t[at..].find(w) {
|
||||
Some(i) => at += i + w.len(),
|
||||
None => panic!("{w:?} missing or out of order in:\n{t}"),
|
||||
}
|
||||
}
|
||||
// Letter-spaced capitals: pdfium may read the tracking as spaces; the letters are all there, in order.
|
||||
assert!(t.replace(' ', "").contains("PROJEKTOVÁMANAŽERKA"), "{t}");
|
||||
// The fonts are embedded subsets.
|
||||
let raw = String::from_utf8_lossy(&pdf);
|
||||
assert!(raw.contains("/FontFile2") || raw.contains("/FontFile3"), "no embedded font program");
|
||||
assert!(raw.contains("/ToUnicode"));
|
||||
}
|
||||
|
||||
fn diff(a: &image::RgbaImage, b: &pictor_doc::Raster) -> f64 {
|
||||
assert_eq!((a.width(), a.height()), (b.width, b.height));
|
||||
let mut sum = 0u64;
|
||||
for (p, q) in a.as_raw().as_chunks::<4>().0.iter().zip(b.rgba.as_chunks::<4>().0) {
|
||||
// The core's pixels over white paper, as pdfium draws them.
|
||||
let a = q[3] as i32;
|
||||
for i in 0..3 {
|
||||
let over_white = (q[i] as i32 * a + 255 * (255 - a)) / 255;
|
||||
sum += (p[i] as i32 - over_white).unsigned_abs() as u64;
|
||||
}
|
||||
}
|
||||
sum as f64 / (a.width() as f64 * a.height() as f64 * 3.0)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pdfium_draws_the_pdf_like_the_core_does() {
|
||||
for (name, doc) in fixtures::all() {
|
||||
let pdf = export::pdf(&doc, book()).unwrap();
|
||||
std::fs::write(format!("{}/export-{name}.pdf", env!("CARGO_TARGET_TMPDIR")), &pdf).unwrap();
|
||||
let page = &doc.pages[0];
|
||||
let scale = 2.0;
|
||||
let core = render::page(&doc, page, book(), scale).unwrap();
|
||||
let theirs = pictor_pdf::render_page(engine(), &pdf, None, 0, core.width).unwrap().into_rgba8();
|
||||
let theirs = image::imageops::resize(&theirs, core.width, core.height, image::imageops::FilterType::Triangle);
|
||||
let d = diff(&theirs, &core);
|
||||
theirs.save(format!("{}/export-{name}-pdfium.png", env!("CARGO_TARGET_TMPDIR"))).unwrap();
|
||||
// Anti-aliasing and image filtering differ; a misplaced shape or a missing glyph run costs far more.
|
||||
assert!(d < 3.0, "{name}: mean difference {d:.2} per channel");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn png_jpg_and_svg() {
|
||||
let doc = fixtures::shapes();
|
||||
let page = &doc.pages[0];
|
||||
let png = export::png(&doc, page, book(), 3.0).unwrap();
|
||||
let img = image::load_from_memory(&png).unwrap();
|
||||
assert_eq!((img.width(), img.height()), (1200, 900));
|
||||
let jpg = export::jpg(&doc, page, book(), 1.0, 90).unwrap();
|
||||
let img = image::load_from_memory(&jpg).unwrap();
|
||||
assert_eq!((img.width(), img.height()), (400, 300));
|
||||
for (name, doc) in fixtures::all() {
|
||||
let svg = export::svg(&doc, &doc.pages[0], book());
|
||||
std::fs::write(format!("{}/export-{name}.svg", env!("CARGO_TARGET_TMPDIR")), &svg).unwrap();
|
||||
let tree = usvg::Tree::from_str(&svg, &usvg::Options::default()).unwrap_or_else(|e| panic!("{name}: {e}"));
|
||||
assert!(tree.root().has_children(), "{name}: empty SVG");
|
||||
}
|
||||
let svg = export::svg(&fixtures::text(), &fixtures::text().pages[0], book());
|
||||
assert!(svg.contains(">Monika Nováková</text>"), "text is not text in the SVG");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_huge_png_is_refused() {
|
||||
let doc = fixtures::shapes();
|
||||
assert!(matches!(export::png(&doc, &doc.pages[0], book(), 100.0), Err(export::ExportError::TooLarge)));
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
//! Day 3 mandatory test 4: a font whose licence forbids embedding (OS/2 fsType) is refused for PDF export, and the
|
||||
//! error names the font and the reason. The test font is a system font with its fsType patched in memory.
|
||||
use pictor_doc::export::{self, ExportError};
|
||||
use pictor_doc::text::Embedding;
|
||||
use pictor_doc::*;
|
||||
|
||||
fn system_font() -> Vec<u8> {
|
||||
for p in [r"C:\Windows\Fonts\arial.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"] {
|
||||
if let Ok(d) = std::fs::read(p) {
|
||||
return d;
|
||||
}
|
||||
}
|
||||
panic!("no system font to patch");
|
||||
}
|
||||
|
||||
/// The font with OS/2 fsType set to `fs_type` (and version ≥ 2 so the bits mean what they say).
|
||||
fn with_fs_type(mut data: Vec<u8>, fs_type: u16) -> Vec<u8> {
|
||||
let n = u16::from_be_bytes([data[4], data[5]]) as usize;
|
||||
for i in 0..n {
|
||||
let rec = 12 + i * 16;
|
||||
if &data[rec..rec + 4] == b"OS/2" {
|
||||
let off = u32::from_be_bytes(data[rec + 8..rec + 12].try_into().unwrap()) as usize;
|
||||
let version = u16::from_be_bytes([data[off], data[off + 1]]);
|
||||
assert!(version >= 2, "the OS/2 table is too old for this test");
|
||||
data[off + 8..off + 10].copy_from_slice(&fs_type.to_be_bytes());
|
||||
return data;
|
||||
}
|
||||
}
|
||||
panic!("no OS/2 table");
|
||||
}
|
||||
|
||||
fn family_of(data: &[u8]) -> String {
|
||||
let book = FontBook::empty();
|
||||
assert!(book.add(data.to_vec()));
|
||||
book.families().remove(0)
|
||||
}
|
||||
|
||||
fn doc_with_text(family: &str) -> Document {
|
||||
let mut d = Document::a4();
|
||||
let id = d.new_id();
|
||||
if let LayerKind::Vector { objects } = &mut d.pages[0].layers[0].kind {
|
||||
objects.push(Object {
|
||||
id,
|
||||
name: String::new(),
|
||||
transform: [1.0, 0.0, 0.0, 1.0, 50.0, 50.0],
|
||||
opacity: 1.0,
|
||||
visible: true,
|
||||
locked: false,
|
||||
fill: None,
|
||||
stroke: None,
|
||||
shape: Shape::Text {
|
||||
w: 0.0,
|
||||
text: "Embedding test".into(),
|
||||
style: TextStyle {
|
||||
family: family.into(),
|
||||
weight: 400,
|
||||
italic: false,
|
||||
size: 14.0,
|
||||
color: Rgba::BLACK,
|
||||
align: Align::Left,
|
||||
line_height: 1.2,
|
||||
letter_spacing: 0.0,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
d
|
||||
}
|
||||
|
||||
fn export_with(font: Vec<u8>) -> (String, Result<Vec<u8>, ExportError>) {
|
||||
let family = family_of(&font);
|
||||
let book = FontBook::empty();
|
||||
assert!(book.add(font));
|
||||
let r = export::pdf(&doc_with_text(&family), &book);
|
||||
(family, r)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_restricted_font_is_refused_with_its_name_and_the_reason() {
|
||||
let (family, r) = export_with(with_fs_type(system_font(), 0x0002));
|
||||
match r {
|
||||
Err(e @ ExportError::FontNotEmbeddable { .. }) => {
|
||||
let msg = e.to_string();
|
||||
assert!(msg.contains(&family), "{msg}");
|
||||
assert!(msg.contains("forbids embedding"), "{msg}");
|
||||
}
|
||||
other => panic!("a restricted font was embedded: {:?}", other.map(|b| b.len())),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bitmap_only_font_is_refused() {
|
||||
let (_, r) = export_with(with_fs_type(system_font(), 0x0200));
|
||||
assert!(matches!(r, Err(ExportError::FontNotEmbeddable { reason, .. }) if reason.contains("bitmap")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn installable_editable_and_print_fonts_are_embedded() {
|
||||
for fs in [0x0000u16, 0x0004, 0x0008] {
|
||||
let (_, r) = export_with(with_fs_type(system_font(), fs));
|
||||
let pdf = r.unwrap_or_else(|e| panic!("fsType {fs:#06x}: {e}"));
|
||||
assert!(String::from_utf8_lossy(&pdf).contains("/FontFile2"));
|
||||
}
|
||||
let book = FontBook::empty();
|
||||
assert!(book.add(with_fs_type(system_font(), 0x0004)));
|
||||
let k = book.resolve(&book.families()[0], 400, false).unwrap();
|
||||
assert_eq!(book.font(k).embedding, Embedding::PrintOnly);
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
//! Day 3 mandatory test 1: the .pictor format. Fixture documents round-trip without loss; hostile zips (zip slip,
|
||||
//! bombs, a huge picture, too many entries, a missing asset, broken JSON) are refused cleanly; a newer format is
|
||||
//! refused with its message.
|
||||
use pictor_doc::format::{self, FormatError, Limits};
|
||||
use pictor_doc::{FontFile, fixtures};
|
||||
use std::io::{Cursor, Write};
|
||||
|
||||
fn zip_of(entries: &[(&str, &[u8])], method: zip::CompressionMethod) -> Vec<u8> {
|
||||
let mut z = zip::ZipWriter::new(Cursor::new(Vec::new()));
|
||||
let opts = zip::write::SimpleFileOptions::default().compression_method(method);
|
||||
for (name, data) in entries {
|
||||
z.start_file(*name, opts).unwrap();
|
||||
z.write_all(data).unwrap();
|
||||
}
|
||||
z.finish().unwrap().into_inner()
|
||||
}
|
||||
|
||||
/// A valid document.json for a one-page document with no assets.
|
||||
fn plain_json() -> Vec<u8> {
|
||||
let bytes = format::write(&pictor_doc::Document::a4(), &[]).unwrap();
|
||||
let mut z = zip::ZipArchive::new(Cursor::new(bytes)).unwrap();
|
||||
let mut s = Vec::new();
|
||||
std::io::Read::read_to_end(&mut z.by_name("document.json").unwrap(), &mut s).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fixtures_round_trip_without_loss() {
|
||||
for (name, doc) in fixtures::all() {
|
||||
let font = FontFile { family: "Fixture".into(), weight: 400, italic: false, data: fake_font() };
|
||||
let bytes = format::write(&doc, std::slice::from_ref(&font)).unwrap();
|
||||
let (back, fonts) = format::read(&bytes, &Limits::default()).unwrap_or_else(|e| panic!("{name}: {e}"));
|
||||
assert_eq!(back, doc, "{name} changed in the round trip");
|
||||
assert_eq!(fonts, vec![font], "{name}: fonts");
|
||||
// Writing again gives the same bytes' content (stable).
|
||||
let again = format::write(&back, &fonts).unwrap();
|
||||
assert_eq!(format::read(&again, &Limits::default()).unwrap().0, doc);
|
||||
}
|
||||
}
|
||||
|
||||
/// The smallest font ttf-parser accepts is a real one: take any system font if there is one, else skip the font part.
|
||||
fn fake_font() -> Vec<u8> {
|
||||
for p in [r"C:\Windows\Fonts\arial.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"] {
|
||||
if let Ok(d) = std::fs::read(p) {
|
||||
return d;
|
||||
}
|
||||
}
|
||||
panic!("no system font to embed in the fixture");
|
||||
}
|
||||
|
||||
fn err(bytes: &[u8]) -> FormatError {
|
||||
match format::read(bytes, &Limits::default()) {
|
||||
Ok(_) => panic!("a hostile file was accepted"),
|
||||
Err(e) => e,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zip_slip_and_odd_names_are_refused() {
|
||||
let json = plain_json();
|
||||
for bad in ["../evil.txt", "assets/../../evil.png", "/etc/passwd", "C:/Windows/x.dll", "assets\\x.png", "a//b"] {
|
||||
let z = zip_of(&[("document.json", &json), (bad, b"x")], zip::CompressionMethod::Stored);
|
||||
assert!(matches!(err(&z), FormatError::UnsafeName(_)), "{bad} was not refused as unsafe");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bomb_is_refused_by_size_and_ratio() {
|
||||
// 300 MB of zeros, compressed to a few hundred KB: refused by its declared size before anything is inflated.
|
||||
let mut z = zip::ZipWriter::new(Cursor::new(Vec::new()));
|
||||
let opts =
|
||||
zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated).large_file(true);
|
||||
z.start_file("document.json", opts).unwrap();
|
||||
let block = vec![b' '; 1 << 20];
|
||||
for _ in 0..300 {
|
||||
z.write_all(&block).unwrap();
|
||||
}
|
||||
let bomb = z.finish().unwrap().into_inner();
|
||||
assert!(bomb.len() < 2 << 20, "the bomb itself is small ({} bytes)", bomb.len());
|
||||
assert!(matches!(err(&bomb), FormatError::TooLarge(_)));
|
||||
|
||||
// A 5 MB asset of zeros compresses over 1000×: refused for its ratio.
|
||||
let json = String::from_utf8(plain_json()).unwrap();
|
||||
let json = json.replacen("\"assets\":[]", "\"assets\":[{\"id\":\"b9\",\"width\":1000,\"height\":1250}]", 1);
|
||||
let zeros = vec![0u8; 5 << 20];
|
||||
let z = zip_of(&[("document.json", json.as_bytes()), ("assets/b9.png", &zeros)], zip::CompressionMethod::Deflated);
|
||||
assert!(matches!(err(&z), FormatError::TooLarge(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_huge_picture_is_refused_before_decoding() {
|
||||
let json = String::from_utf8(plain_json()).unwrap();
|
||||
let json = json.replacen("\"assets\":[]", "\"assets\":[{\"id\":\"b9\",\"width\":50000,\"height\":50000}]", 1);
|
||||
let z = zip_of(
|
||||
&[("document.json", json.as_bytes()), ("assets/b9.png", b"not even a png")],
|
||||
zip::CompressionMethod::Stored,
|
||||
);
|
||||
assert!(matches!(err(&z), FormatError::TooLarge(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn too_many_entries_are_refused() {
|
||||
let json = plain_json();
|
||||
let names: Vec<String> = (0..5000).map(|i| format!("extra/{i}")).collect();
|
||||
let mut entries: Vec<(&str, &[u8])> = vec![("document.json", &json)];
|
||||
entries.extend(names.iter().map(|n| (n.as_str(), b"" as &[u8])));
|
||||
let z = zip_of(&entries, zip::CompressionMethod::Stored);
|
||||
assert!(matches!(err(&z), FormatError::TooLarge(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_or_wrong_asset_is_refused() {
|
||||
// The bitmap fixture without its picture.
|
||||
let bytes = format::write(&fixtures::bitmap(), &[]).unwrap();
|
||||
let mut src = zip::ZipArchive::new(Cursor::new(bytes)).unwrap();
|
||||
let mut json = Vec::new();
|
||||
std::io::Read::read_to_end(&mut src.by_name("document.json").unwrap(), &mut json).unwrap();
|
||||
let z = zip_of(&[("document.json", &json)], zip::CompressionMethod::Deflated);
|
||||
assert!(matches!(err(&z), FormatError::MissingAsset(_)), "{:?}", err(&z));
|
||||
// A picture that is not the size the document says.
|
||||
let wrong = format::encode_png(&fixtures::picture(10, 10)).unwrap();
|
||||
let asset = src.file_names().find(|n| n.starts_with("assets/")).unwrap().to_string();
|
||||
let z = zip_of(&[("document.json", &json), (&asset, &wrong)], zip::CompressionMethod::Stored);
|
||||
assert!(matches!(err(&z), FormatError::Damaged(_)), "{:?}", err(&z));
|
||||
// An asset referenced by a layer but not listed.
|
||||
let json2 = String::from_utf8(json.clone()).unwrap();
|
||||
let start = json2.find("\"assets\":[").unwrap();
|
||||
let end = json2[start..].find(']').unwrap() + start + 1;
|
||||
let json2 = format!("{}\"assets\":[]{}", &json2[..start], &json2[end..]);
|
||||
let z = zip_of(&[("document.json", json2.as_bytes())], zip::CompressionMethod::Stored);
|
||||
assert!(matches!(err(&z), FormatError::MissingAsset(_)), "{:?}", err(&z));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn broken_json_and_non_zips_are_refused() {
|
||||
let z = zip_of(&[("document.json", b"{\"format\":1,\"pages\":[{")], zip::CompressionMethod::Stored);
|
||||
assert!(matches!(err(&z), FormatError::Damaged(_)));
|
||||
assert!(matches!(err(b"%PDF-1.7 not a zip"), FormatError::NotPictor));
|
||||
let z = zip_of(&[("readme.txt", b"hi")], zip::CompressionMethod::Stored);
|
||||
assert!(matches!(err(&z), FormatError::NotPictor));
|
||||
// Valid JSON with lies in it: a repeated id, a NaN-like size, a bad path, an asset id with a slash.
|
||||
let good = String::from_utf8(plain_json()).unwrap();
|
||||
for (from, to) in [
|
||||
("\"next_id\":3", "\"next_id\":1"),
|
||||
("\"width\":595.276", "\"width\":-5"),
|
||||
(
|
||||
"\"layers\":[{",
|
||||
"\"layers\":[{\"kind\":\"bitmap\",\"asset\":\"../x\",\"x\":0,\"y\":0,\"w\":1,\"h\":1,\"id\":9,\"name\":\"x\"},{",
|
||||
),
|
||||
] {
|
||||
assert!(good.contains(from), "fixture json lacks {from}: {good}");
|
||||
let bad = good.replacen(from, to, 1);
|
||||
let z = zip_of(&[("document.json", bad.as_bytes())], zip::CompressionMethod::Stored);
|
||||
let e = err(&z);
|
||||
assert!(matches!(e, FormatError::Damaged(_) | FormatError::UnsafeName(_)), "{from} → {to}: {e:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_newer_format_is_refused_with_its_message() {
|
||||
let z = zip_of(&[("document.json", b"{\"format\":2,\"anything\":\"new\"}")], zip::CompressionMethod::Stored);
|
||||
let e = err(&z);
|
||||
assert!(matches!(e, FormatError::Newer(2)), "{e:?}");
|
||||
let msg = e.to_string();
|
||||
assert!(msg.contains("newer Pictor") && msg.contains("format 2") && msg.contains("format 1"), "{msg}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bad_path_is_refused() {
|
||||
let good = String::from_utf8(plain_json()).unwrap();
|
||||
let mut doc = pictor_doc::Document::a4();
|
||||
let id = doc.new_id();
|
||||
if let pictor_doc::LayerKind::Vector { objects } = &mut doc.pages[0].layers[0].kind {
|
||||
objects.push(pictor_doc::Object {
|
||||
id,
|
||||
name: String::new(),
|
||||
transform: pictor_doc::identity(),
|
||||
opacity: 1.0,
|
||||
visible: true,
|
||||
locked: false,
|
||||
fill: None,
|
||||
stroke: None,
|
||||
shape: pictor_doc::Shape::Path { d: "M0 0 A 1 1 0 0 1 5 5".into() },
|
||||
});
|
||||
}
|
||||
let bytes = format::write(&doc, &[]).unwrap();
|
||||
assert!(matches!(format::read(&bytes, &Limits::default()), Err(FormatError::Damaged(_))));
|
||||
drop(good);
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
//! The core's painter: fixture documents render to what they say (spot colours at known places), and every fixture
|
||||
//! is written to `target/tmp/render-<name>.png` for a look.
|
||||
use pictor_doc::{FontBook, fixtures, render};
|
||||
use std::sync::OnceLock;
|
||||
|
||||
pub fn book() -> &'static FontBook {
|
||||
static B: OnceLock<FontBook> = OnceLock::new();
|
||||
B.get_or_init(FontBook::system)
|
||||
}
|
||||
|
||||
fn near(a: [u8; 4], b: [u8; 4], tol: i32) -> bool {
|
||||
a.iter().zip(b).all(|(x, y)| (*x as i32 - y as i32).abs() <= tol)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fixtures_render_and_are_written_for_a_look() {
|
||||
for (name, doc) in fixtures::all() {
|
||||
let r = render::page(&doc, &doc.pages[0], book(), 2.0).expect("renders");
|
||||
assert_eq!(
|
||||
(r.width, r.height),
|
||||
((doc.pages[0].width * 2.0).round() as u32, (doc.pages[0].height * 2.0).round() as u32)
|
||||
);
|
||||
let png = pictor_doc::format::encode_png(&r).unwrap();
|
||||
std::fs::write(format!("{}/render-{name}.png", env!("CARGO_TARGET_TMPDIR")), png).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shapes_land_where_the_document_says() {
|
||||
let doc = fixtures::shapes();
|
||||
let r = render::page(&doc, &doc.pages[0], book(), 1.0).unwrap();
|
||||
// Inside the navy rounded rectangle (20,20 140×90), away from its brass stroke.
|
||||
assert!(near(r.pixel(90, 65), [0x1f, 0x2a, 0x44, 255], 2), "{:?}", r.pixel(90, 65));
|
||||
// On its brass stroke (top edge at y = 20).
|
||||
assert!(near(r.pixel(90, 20), [0xb0, 0x8d, 0x57, 255], 30), "{:?}", r.pixel(90, 20));
|
||||
// The white paper outside everything.
|
||||
assert_eq!(r.pixel(390, 5), [255, 255, 255, 255]);
|
||||
// The group at 50 %: green over white is a light green.
|
||||
let g = r.pixel(225, 155);
|
||||
assert!(near(g, [0x9c, 0xe7, 0xbc, 255], 6), "{g:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bitmap_layer_at_scale_one_keeps_its_pixels() {
|
||||
let mut doc = fixtures::bitmap();
|
||||
doc.pages[0].layers[0].opacity = 1.0;
|
||||
doc.pages[0].layers.truncate(1);
|
||||
let r = render::page(&doc, &doc.pages[0], book(), 1.0).unwrap();
|
||||
assert_eq!(r, doc.assets.values().next().unwrap().clone());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_is_drawn_in_its_colour() {
|
||||
let doc = fixtures::text();
|
||||
let r = render::page(&doc, &doc.pages[0], book(), 2.0).unwrap();
|
||||
// Somewhere in the title's band there is navy ink.
|
||||
let navy = (40..140)
|
||||
.flat_map(|x| (36..90).map(move |y| (x, y)))
|
||||
.any(|(x, y)| near(r.pixel(x, y), [0x1f, 0x2a, 0x44, 255], 20));
|
||||
assert!(navy, "no navy title ink");
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
//! Day 3 mandatory test 2: undo is exact. Any random sequence of operations followed by the same number of undos
|
||||
//! returns the document to its original state, and as many redos return the edited one.
|
||||
use pictor_doc::ops::History;
|
||||
use pictor_doc::*;
|
||||
use proptest::prelude::*;
|
||||
|
||||
/// What a random step does; turned into a concrete operation against the document as it is at that moment.
|
||||
#[derive(Clone, Debug)]
|
||||
enum Step {
|
||||
AddRect { x: f32, y: f32, w: f32, h: f32, color: [u8; 4] },
|
||||
AddText { text: String, size: f32 },
|
||||
RemoveObject { pick: usize },
|
||||
MoveObject { pick: usize, dx: f32, dy: f32 },
|
||||
Recolour { pick: usize, color: [u8; 4] },
|
||||
AddLayer { at: usize },
|
||||
RemoveLayer { pick: usize },
|
||||
HideLayer { pick: usize, opacity: f32 },
|
||||
Resize { w: f32, h: f32 },
|
||||
Paint { x: u32, y: u32, w: u32, h: u32, color: [u8; 4] },
|
||||
NewBitmap { w: u32, h: u32 },
|
||||
Group { pick: usize },
|
||||
AddPage,
|
||||
RemovePage { pick: usize },
|
||||
}
|
||||
|
||||
fn step() -> impl Strategy<Value = Step> {
|
||||
let color = any::<[u8; 4]>();
|
||||
let f = -500.0f32..500.0;
|
||||
prop_oneof![
|
||||
(f.clone(), f.clone(), 1.0f32..300.0, 1.0f32..300.0, color).prop_map(|(x, y, w, h, color)| Step::AddRect {
|
||||
x,
|
||||
y,
|
||||
w,
|
||||
h,
|
||||
color
|
||||
}),
|
||||
("[a-zA-Zá-ž ]{0,30}", 4.0f32..60.0).prop_map(|(text, size)| Step::AddText { text, size }),
|
||||
any::<usize>().prop_map(|pick| Step::RemoveObject { pick }),
|
||||
(any::<usize>(), f.clone(), f.clone()).prop_map(|(pick, dx, dy)| Step::MoveObject { pick, dx, dy }),
|
||||
(any::<usize>(), color).prop_map(|(pick, color)| Step::Recolour { pick, color }),
|
||||
any::<usize>().prop_map(|at| Step::AddLayer { at }),
|
||||
any::<usize>().prop_map(|pick| Step::RemoveLayer { pick }),
|
||||
(any::<usize>(), 0.0f32..=1.0).prop_map(|(pick, opacity)| Step::HideLayer { pick, opacity }),
|
||||
(1.0f32..2000.0, 1.0f32..2000.0).prop_map(|(w, h)| Step::Resize { w, h }),
|
||||
(0u32..300, 0u32..200, 1u32..120, 1u32..120, color).prop_map(|(x, y, w, h, color)| Step::Paint {
|
||||
x,
|
||||
y,
|
||||
w,
|
||||
h,
|
||||
color
|
||||
}),
|
||||
(1u32..64, 1u32..64).prop_map(|(w, h)| Step::NewBitmap { w, h }),
|
||||
any::<usize>().prop_map(|pick| Step::Group { pick }),
|
||||
Just(Step::AddPage),
|
||||
any::<usize>().prop_map(|pick| Step::RemovePage { pick }),
|
||||
]
|
||||
}
|
||||
|
||||
fn object(doc: &mut Document, shape: Shape, fill: Option<Paint>) -> Object {
|
||||
Object {
|
||||
id: doc.new_id(),
|
||||
name: String::new(),
|
||||
transform: identity(),
|
||||
opacity: 1.0,
|
||||
visible: true,
|
||||
locked: false,
|
||||
fill,
|
||||
stroke: None,
|
||||
shape,
|
||||
}
|
||||
}
|
||||
|
||||
/// Every (page, vector layer, object) in the document.
|
||||
fn all_objects(doc: &Document) -> Vec<(Id, Id, Object)> {
|
||||
let mut out = Vec::new();
|
||||
for p in &doc.pages {
|
||||
fn walk(p: Id, ls: &[Layer], out: &mut Vec<(Id, Id, Object)>) {
|
||||
for l in ls {
|
||||
match &l.kind {
|
||||
LayerKind::Vector { objects } => out.extend(objects.iter().map(|o| (p, l.id, o.clone()))),
|
||||
LayerKind::Group { layers } => walk(p, layers, out),
|
||||
LayerKind::Bitmap { .. } => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
walk(p.id, &p.layers, &mut out);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn first_vector_layer(doc: &Document) -> Option<(Id, Id)> {
|
||||
doc.pages
|
||||
.iter()
|
||||
.find_map(|p| p.layers.iter().find(|l| matches!(l.kind, LayerKind::Vector { .. })).map(|l| (p.id, l.id)))
|
||||
}
|
||||
|
||||
/// The operation for a step, or none when the document has nothing for it to act on. `doc` is only read, except
|
||||
/// that taking new ids moves `next_id` (which the operation does not undo, as in the app).
|
||||
fn op_for(doc: &mut Document, s: &Step) -> Option<Op> {
|
||||
let objs = all_objects(doc);
|
||||
let pick = |n: usize, len: usize| if len == 0 { None } else { Some(n % len) };
|
||||
Some(match s {
|
||||
Step::AddRect { x, y, w, h, color } => {
|
||||
let (page, layer) = first_vector_layer(doc)?;
|
||||
let mut o = object(doc, Shape::Rect { w: *w, h: *h, radius: 0.0 }, Some(Paint::solid(Rgba(*color))));
|
||||
o.transform[4] = *x;
|
||||
o.transform[5] = *y;
|
||||
Op::InsertObject { page, layer, parent: None, index: 0, object: o }
|
||||
}
|
||||
Step::AddText { text, size } => {
|
||||
let (page, layer) = first_vector_layer(doc)?;
|
||||
let style = TextStyle {
|
||||
family: "Arial".into(),
|
||||
weight: 400,
|
||||
italic: false,
|
||||
size: *size,
|
||||
color: Rgba::BLACK,
|
||||
align: Align::Left,
|
||||
line_height: 1.2,
|
||||
letter_spacing: 0.0,
|
||||
};
|
||||
let o = object(doc, Shape::Text { w: 100.0, text: text.clone(), style }, None);
|
||||
Op::InsertObject { page, layer, parent: None, index: 0, object: o }
|
||||
}
|
||||
Step::RemoveObject { pick: n } => {
|
||||
let (page, layer, o) = objs.get(pick(*n, objs.len())?)?.clone();
|
||||
let index = layer_objects(doc, page, layer).iter().position(|x| x.id == o.id)?;
|
||||
Op::RemoveObject { page, layer, parent: None, index }
|
||||
}
|
||||
Step::MoveObject { pick: n, dx, dy } => {
|
||||
let (page, layer, mut o) = objs.get(pick(*n, objs.len())?)?.clone();
|
||||
o.transform[4] += dx;
|
||||
o.transform[5] += dy;
|
||||
Op::ReplaceObject { page, layer, object: o }
|
||||
}
|
||||
Step::Recolour { pick: n, color } => {
|
||||
let (page, layer, mut o) = objs.get(pick(*n, objs.len())?)?.clone();
|
||||
o.fill = Some(Paint::solid(Rgba(*color)));
|
||||
Op::ReplaceObject { page, layer, object: o }
|
||||
}
|
||||
Step::AddLayer { at } => {
|
||||
let page = doc.pages.first()?.id;
|
||||
let len = doc.pages[0].layers.len();
|
||||
let id = doc.new_id();
|
||||
Op::InsertLayer { page, parent: None, index: at % (len + 1), layer: Layer::vector(id, "New") }
|
||||
}
|
||||
Step::RemoveLayer { pick: n } => {
|
||||
let p = doc.pages.first()?;
|
||||
Op::RemoveLayer { page: p.id, parent: None, index: pick(*n, p.layers.len())? }
|
||||
}
|
||||
Step::HideLayer { pick: n, opacity } => {
|
||||
let p = doc.pages.first()?;
|
||||
let l = &p.layers[pick(*n, p.layers.len())?];
|
||||
Op::SetLayer {
|
||||
page: p.id,
|
||||
layer: l.id,
|
||||
name: format!("{} *", l.name),
|
||||
visible: !l.visible,
|
||||
locked: !l.locked,
|
||||
opacity: *opacity,
|
||||
place: match l.kind {
|
||||
LayerKind::Bitmap { .. } => Some(Rect { x: 1.0, y: 2.0, w: 30.0, h: 40.0 }),
|
||||
_ => None,
|
||||
},
|
||||
}
|
||||
}
|
||||
Step::Resize { w, h } => {
|
||||
let p = doc.pages.first()?;
|
||||
Op::SetPage {
|
||||
page: p.id,
|
||||
width: *w,
|
||||
height: *h,
|
||||
margins: [w / 20.0; 4],
|
||||
guides: vec![Guide { vertical: true, at: w / 2.0 }],
|
||||
background: Some(Rgba::WHITE),
|
||||
}
|
||||
}
|
||||
Step::Paint { x, y, w, h, color } => {
|
||||
let (asset, r) = doc.assets.iter().next()?;
|
||||
let rect = PixelRect { x: *x, y: *y, w: *w, h: *h }.clamp(r.width, r.height);
|
||||
if rect.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let pixels = std::iter::repeat_n(*color, (rect.w * rect.h) as usize).flatten().collect();
|
||||
Op::Patch { asset: asset.clone(), rect, pixels }
|
||||
}
|
||||
Step::NewBitmap { w, h } => {
|
||||
let page = doc.pages.first()?.id;
|
||||
let id = doc.new_id();
|
||||
let asset = format!("b{id}");
|
||||
let layer = Layer {
|
||||
id,
|
||||
name: "Paint".into(),
|
||||
visible: true,
|
||||
locked: false,
|
||||
opacity: 1.0,
|
||||
kind: LayerKind::Bitmap { asset: asset.clone(), x: 0.0, y: 0.0, w: *w as f32, h: *h as f32 },
|
||||
};
|
||||
Op::Batch {
|
||||
ops: vec![
|
||||
Op::PutAsset { asset, raster: Some(Raster::filled(*w, *h, [9, 8, 7, 6])) },
|
||||
Op::InsertLayer { page, parent: None, index: 0, layer },
|
||||
],
|
||||
}
|
||||
}
|
||||
Step::Group { pick: n } => {
|
||||
// Group two objects of one layer: remove both, insert a group holding them.
|
||||
let (page, layer) = first_vector_layer(doc)?;
|
||||
let list = layer_objects(doc, page, layer);
|
||||
if list.len() < 2 {
|
||||
return None;
|
||||
}
|
||||
let i = n % (list.len() - 1);
|
||||
let (a, b) = (list[i].clone(), list[i + 1].clone());
|
||||
let g = object(doc, Shape::Group { objects: vec![a, b] }, None);
|
||||
Op::Batch {
|
||||
ops: vec![
|
||||
Op::RemoveObject { page, layer, parent: None, index: i + 1 },
|
||||
Op::RemoveObject { page, layer, parent: None, index: i },
|
||||
Op::InsertObject { page, layer, parent: None, index: i, object: g },
|
||||
],
|
||||
}
|
||||
}
|
||||
Step::AddPage => {
|
||||
let pid = doc.new_id();
|
||||
let lid = doc.new_id();
|
||||
let page = Page {
|
||||
id: pid,
|
||||
width: 100.0,
|
||||
height: 100.0,
|
||||
margins: [0.0; 4],
|
||||
guides: vec![],
|
||||
background: None,
|
||||
layers: vec![Layer::vector(lid, "Layer")],
|
||||
};
|
||||
Op::InsertPage { index: doc.pages.len(), page }
|
||||
}
|
||||
Step::RemovePage { pick: n } => {
|
||||
if doc.pages.len() < 2 {
|
||||
return None;
|
||||
}
|
||||
Op::RemovePage { index: n % doc.pages.len() }
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn layer_objects(doc: &Document, page: Id, layer: Id) -> Vec<Object> {
|
||||
match doc.page(page).and_then(|p| p.layer(layer)).map(|l| &l.kind) {
|
||||
Some(LayerKind::Vector { objects }) => objects.clone(),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#![proptest_config(ProptestConfig { cases: 256, .. ProptestConfig::default() })]
|
||||
|
||||
#[test]
|
||||
fn random_edits_then_as_many_undos_restore_the_document(
|
||||
start in 0usize..4,
|
||||
steps in proptest::collection::vec(step(), 1..60),
|
||||
) {
|
||||
let mut doc = fixtures::all().swap_remove(start).1;
|
||||
let mut history = History::default();
|
||||
let mut n = 0;
|
||||
for s in &steps {
|
||||
if let Some(op) = op_for(&mut doc, s) {
|
||||
history.apply(&mut doc, op).expect("a well-formed operation applies");
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
// next_id only grows (ids are never reused); compare everything else.
|
||||
let edited = doc.clone();
|
||||
let mut original = fixtures::all().swap_remove(start).1;
|
||||
original.next_id = doc.next_id;
|
||||
for _ in 0..n {
|
||||
prop_assert!(history.undo(&mut doc).unwrap());
|
||||
}
|
||||
prop_assert!(!history.undo(&mut doc).unwrap(), "more undos than edits");
|
||||
prop_assert_eq!(&doc, &original);
|
||||
for _ in 0..n {
|
||||
prop_assert!(history.redo(&mut doc).unwrap());
|
||||
}
|
||||
prop_assert_eq!(&doc, &edited);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failing_batch_leaves_nothing_behind() {
|
||||
let mut doc = fixtures::shapes();
|
||||
let before = doc.clone();
|
||||
let page = doc.pages[0].id;
|
||||
let layer = doc.pages[0].layers[0].id;
|
||||
let bad = Op::Batch {
|
||||
ops: vec![
|
||||
Op::RemoveObject { page, layer, parent: None, index: 0 },
|
||||
Op::RemoveObject { page, layer, parent: None, index: 99 },
|
||||
],
|
||||
};
|
||||
let mut h = History::default();
|
||||
assert!(h.apply(&mut doc, bad).is_err());
|
||||
assert_eq!(doc, before);
|
||||
assert!(!h.can_undo());
|
||||
}
|
||||
Reference in New Issue
Block a user