[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:
2026-11-17 10:07:12 +01:00
parent e46cbe3547
commit 17db54fdbf
26 changed files with 6589 additions and 7 deletions
+189
View File
@@ -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);
}