Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 5 additions & 5 deletions ROADMAP.md

Large diffs are not rendered by default.

15 changes: 14 additions & 1 deletion crates/engine/src/cmd/fileio/load.rs
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,20 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
.then(|| vectorcraft_pdf::editing_with(bytes, opts.password.as_deref()))
.flatten()
.map(|e| (e.intact, move || Some(e.data)));
restore_or_import(editing, || super::pdfimport::import(bytes, opts))?
restore_or_import(editing, || {
// An Illustrator file: the document its editing data holds, else its PDF.
let whole = opts.pages.is_none() && matches!(format.id, "ai" | "ait");
let why = match whole.then(|| vectorcraft_pdf::ai_private_data(bytes, opts.password.as_deref())).flatten() {
None => return super::pdfimport::import(bytes, opts),
Some(raw) => match raw.and_then(|raw| vectorcraft_eps::import_ai(&raw)) {
Ok(i) => return Ok((i.document, i.warnings)),
Err(why) => why,
},
};
let (doc, mut warnings) = super::pdfimport::import(bytes, opts)?;
warnings.insert(0, vectorcraft_eps::editing_fallback(&why, vectorcraft_eps::PDF_CONTENT));
Ok((doc, warnings))
})?
}
"dxf" => {
let (doc, warnings) = super::dxfimport::import(bytes, &opts.dxf)?;
Expand Down
3 changes: 3 additions & 0 deletions crates/engine/src/cmd/fileio/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -936,6 +936,9 @@ mod tests_psd;
#[cfg(test)]
mod tests_epsimport;

#[cfg(test)]
mod tests_aiimport;

#[cfg(test)]
mod tests_pdflayers;

Expand Down
103 changes: 103 additions & 0 deletions crates/engine/src/cmd/fileio/tests_aiimport.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
//! Illustrator EPS and `.ai` files open from the editing data they carry: layers, groups, names,
//! hidden objects, artboards, colours and images as they were; what the reader doesn't read yet
//! opens as before, with a warning saying why.

use std::io::Write as _;
use std::sync::Arc;

use serde_json::{Value, json};
use vectorcraft_doc::{Node, NodeKind};
use vectorcraft_testkit::ai;

use super::*;

fn open(s: &mut Session, name: &str, bytes: &[u8], params: Value) -> Result<Value> {
let mut p = json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(bytes)});
if let (Some(p), Some(extra)) = (p.as_object_mut(), params.as_object()) {
p.extend(extra.clone());
}
s.execute("document.open", &p)
}

fn zlib(data: &[u8]) -> Vec<u8> {
let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default());
e.write_all(data).unwrap();
e.finish().unwrap()
}

/// The `.ai` private data of `data`, compressed as such files compress it.
fn compressed(data: &[u8]) -> Vec<u8> {
[&b"%AI12_CompressedData"[..], &zlib(data)].concat()
}

fn names(nodes: &[Arc<Node>]) -> Vec<String> {
nodes.iter().map(|n| n.name.clone().unwrap_or_default()).collect()
}

/// The sample's structure, as [`ai::sample`] builds it.
fn check_sample(s: &Session) {
let doc = &s.doc().unwrap().doc;
assert_eq!(names(&doc.layers), ["Art", "Hidden", "Images"]);
assert_eq!(doc.artboards.len(), 1);
assert_eq!(doc.artboards[0].rect, vectorcraft_geom::Rect::new(0.0, 0.0, 200.0, 100.0));
let art = doc.layers[0].children().unwrap();
assert_eq!(names(art), ["Pair", "Ring", "Window", "Shaded", ""]);
let pair = art[0].children().unwrap();
assert_eq!(names(pair), ["Red", ""]);
assert!(pair[0].visible && !pair[1].visible, "the hidden member stays hidden");
assert!(matches!(art[1].kind, NodeKind::Compound { .. }));
assert!(matches!(&art[2].kind, NodeKind::Group { clip: true, children } if matches!(children[0].kind, NodeKind::Path { clipping: true, .. })));
assert!(matches!(art[3].appearance.fill().map(|f| &f.paint), Some(vectorcraft_color::Paint::Gradient(_))));
assert_eq!((art[4].opacity, art[4].blend), (0.5, vectorcraft_color::BlendMode::Screen));
let hidden = &doc.layers[1];
assert!(!hidden.visible);
let sub = &hidden.children().unwrap()[0];
assert!(sub.locked && matches!(sub.kind, NodeKind::Layer { .. }));
let image = &doc.layers[2].children().unwrap()[0];
let NodeKind::Image(im) = &image.kind else { panic!("an image") };
assert_eq!((im.width, im.height), (2, 1));
}

#[test]
fn an_illustrator_eps_opens_with_its_layers() {
let mut s = Session::new();
let r = open(&mut s, "art.eps", &ai::eps(&ai::sample_data()), json!({})).unwrap();
assert_eq!((&r["format"], &r["warnings"]), (&json!("eps"), &json!([])), "{r}");
check_sample(&s);
// Saved as EPS and opened again, it comes back the same.
let eps = s.execute("document.exportEps", &json!({})).unwrap();
let bytes = vectorcraft_format::base64_decode(eps["dataBase64"].as_str().unwrap()).unwrap();
let r = open(&mut s, "again.eps", &bytes, json!({})).unwrap();
assert_eq!(r["restored"], json!(true), "{r}");
check_sample(&s);
}

#[test]
fn an_illustrator_ai_file_opens_from_its_editing_data() {
let mut s = Session::new();
let r = open(&mut s, "art.ai", &ai::ai(&compressed(&ai::sample_data())), json!({})).unwrap();
assert_eq!((&r["format"], &r["warnings"]), (&json!("ai"), &json!([])), "{r}");
check_sample(&s);
// Pages picked: the PDF's.
let r = open(&mut s, "art.ai", &ai::ai(&compressed(&ai::sample_data())), json!({"pages": "1"})).unwrap();
assert_eq!(names(&s.doc().unwrap().doc.layers).len(), 1, "{r}");
// A PDF that happens to carry the data opens as a PDF.
open(&mut s, "art.pdf", &ai::ai(&compressed(&ai::sample_data())), json!({})).unwrap();
assert_ne!(names(&s.doc().unwrap().doc.layers), ["Art", "Hidden", "Images"]);
}

#[test]
fn what_the_reader_doesnt_read_opens_as_before_with_a_warning() {
let text = ai::editing_data(200.0, 100.0, &ai::layer("Words", "/AI11Text :\n0 /FreeUndo ,\n0 /FrameIndex ,\n0 /StoryIndex ,\n;\n"));
let mut s = Session::new();
let r = open(&mut s, "words.eps", &ai::eps(text.as_bytes()), json!({})).unwrap();
let first = r["warnings"][0].as_str().unwrap();
assert!(first.contains("editing data couldn't be read") && first.contains("type") && first.contains("printed page"), "{r}");
assert!(s.doc().unwrap().doc.layers.iter().any(|l| l.children().is_some_and(|c| !c.is_empty())), "the page's line");
let r = open(&mut s, "words.ai", &ai::ai(&compressed(text.as_bytes())), json!({})).unwrap();
let first = r["warnings"][0].as_str().unwrap();
assert!(first.contains("type") && first.contains("PDF content"), "{r}");
// Damaged data says so.
let r = open(&mut s, "damaged.ai", &ai::ai(b"%AI12_CompressedData not zlib at all"), json!({})).unwrap();
assert!(r["warnings"][0].as_str().unwrap().contains("zlib"), "{r}");
}
179 changes: 178 additions & 1 deletion crates/engine/tests/import_fuzz.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
//! must load as an error or as a document that then renders and exports, without a panic; nor may
//! bitmaps, PDF and text pasted from other apps, nor EMF and WMF pictures (damaged files, records
//! of every kind with random contents) opened, placed or pasted, nor EPS and PostScript files
//! (damaged ones, hostile programs) read by the PostScript interpreter, nor Affinity documents
//! (damaged ones, hostile programs) read by the PostScript interpreter, nor the editing data of
//! Illustrator EPS and `.ai` files (damaged, hostile operators and sections), nor Affinity documents
//! (mutated object streams, archives and indexed PNG previews, hostile image dimensions).
//!
//! `PROPTEST_CASES=20000 cargo test -p vectorcraft-engine --test import_fuzz` runs a deeper search.
Expand Down Expand Up @@ -1295,6 +1296,182 @@ proptest! {
}
}

// ---------- Illustrator editing data ----------

/// The operators, operands and section comments of hostile editing data.
fn arb_ai_token() -> impl Strategy<Value = String> {
prop_oneof![
arb_num(),
prop::sample::select(vec![
"m",
"l",
"L",
"c",
"C",
"v",
"V",
"y",
"Y",
"h",
"H",
"N",
"n",
"F",
"f",
"S",
"s",
"B",
"b",
"W",
"(b) *",
"u",
"U",
"*u",
"*U",
"q",
"Q",
"LB",
"Lb",
"Ln",
"(name) Ln",
"g",
"G",
"k",
"K",
"x",
"X",
"Xa",
"XA",
"Xx",
"XX",
"(Ink) 0.5 x",
"O",
"R",
"XR",
"w",
"J",
"j",
"M",
"d",
"[6 3] 0 d",
"[]0 d",
"Xy",
"2 0.5 1 1 1 Xy",
"99 -4 Xy",
"Xw",
"1 Xw",
"A",
"1 A",
"Ae",
"XW",
"1 (style) XW",
"9 () XW",
"Bd",
"(G) 1 3 Bd",
"Bs",
"0 0 0 0 1 0 0 2 1 6 50 0 Bs",
"BD",
"Bb",
"1 Bb",
"BB",
"2 BB",
"1 (G) 0 0 0 1 1 0 0 1 0 0 1 Bg",
"Bg",
"Bm",
"1e308 0 0 1e-308 0 0 Bm",
"Bh",
"XN",
"/DeviceCMYK XN",
"/DeviceGray XN",
"[ 1 0 0 1 0 0 ] 0 0 2 2 2 2 8 3 1 0 1 0",
"[ 1 0 0 1 0 0 ] 0 0 99999 99999 99999 99999 1 1 0 0 0 0",
"[",
"]",
"/Name",
"(text)",
"<ff00>",
":",
";",
",",
"/ArtDictionary :",
"/XMLUID : (A_x41_) ; (AI10_ArtUID) ,",
"(n) /String (AIArtName) ,",
"/Document :",
"/Array :",
"/Dictionary :",
"0 0 /RealPoint (PositionPoint1) ,",
"/AI11Text :",
"/SymbolInstance :",
"/Binary : /ASCII85Decode ,",
"~>",
"p",
"To",
"frobnicate",
"\n%AI5_BeginLayer\n",
"\n%AI5_EndLayer--\n",
"\n%_",
"\n%AI5_BeginRaster\n",
"\n%AI5_EndRaster\n",
"\n%%BeginData: 12\rXI\n",
"\n%%EndData\n",
"\n%AI5_BeginGradient: (G)\n",
"\n%AI14_BeginSymbol\n",
"\n%AI10_EndSymbol\n",
"\n%AI17_Begin_Content_if_version_gt:24 4\n",
"\n%AI17_Alternate_Content\n",
"\n%AI17_End_Versioned_Content\n",
"\n%AI3_Cropmarks: 0 0 1e308 -1e308\n",
"\n%AI5_ArtSize: 0 0\n",
"\n%AI9_ColorModel: 2\n",
"\n%AI5_BeginPlace\n",
"\n%AI26_BeginPlacedObjectPreview\n",
"\n%%PageTrailer\n",
])
.prop_map(str::to_string),
]
}

/// The sample editing data, compressed as `.ai` files compress it.
fn ai_sample_compressed() -> Vec<u8> {
use std::io::Write as _;
let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default());
e.write_all(&vectorcraft_testkit::ai::sample_data()).unwrap();
[&b"%AI12_CompressedData"[..], &e.finish().unwrap()].concat()
}

proptest! {
#![proptest_config(config())]

/// Hostile editing data in Illustrator EPS and `.ai` files: operators in any order with any
/// operands, sections and dictionaries left open, images of any size.
#[test]
fn ai_hostile_editing_data_never_panics(tokens in prop::collection::vec(arb_ai_token(), 0..80)) {
use vectorcraft_testkit::ai;
let data = ai::editing_data(200.0, 100.0, &format!("%AI5_BeginLayer\n1 1 1 1 0 0 1 0 79 128 255 0 50 0 Lb\n(L) Ln\n{}\nLB\n", tokens.join(" ")));
survive("hostile editing data", || vectorcraft_eps::import_ai(data.as_bytes()).ok().map(|r| r.document))?;
let eps = ai::eps(data.as_bytes());
survive("hostile editing data in an EPS", || vectorcraft_engine::cmd::fileio::load("x.eps", &eps).ok().map(|l| l.doc))?;
}

/// Damaged editing data, as it is and compressed in a `.ai` file.
#[test]
fn ai_mutated_editing_data_never_panics(cut in 0usize..4_000, edits in prop::collection::vec((0usize..4_000, any::<u8>()), 0..12)) {
static PLAIN: std::sync::OnceLock<Vec<u8>> = std::sync::OnceLock::new();
static PACKED: std::sync::OnceLock<Vec<u8>> = std::sync::OnceLock::new();
for (what, sample) in [("editing data", PLAIN.get_or_init(vectorcraft_testkit::ai::sample_data)), ("compressed editing data", PACKED.get_or_init(ai_sample_compressed))] {
let mut bytes = sample.clone();
for &(at, b) in &edits {
let n = bytes.len();
bytes[at % n] = b;
}
bytes.truncate(cut.max(4));
survive(what, || vectorcraft_eps::import_ai(&bytes).ok().map(|r| r.document))?;
let file = vectorcraft_testkit::ai::ai(&bytes);
survive(what, || vectorcraft_engine::cmd::fileio::load("x.ai", &file).ok().map(|l| l.doc))?;
}
}
}

// ---------- DXF ----------

/// The rich document exported as DXF (2018: hatches, splines, text, images; R12: polylines).
Expand Down
2 changes: 2 additions & 0 deletions crates/eps/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ vectorcraft-render = { workspace = true }
kurbo = { workspace = true }
image = { workspace = true }
flate2 = { workspace = true }
# Illustrator's editing data (Zstandard): pure Rust, builds for wasm.
ruzstd = "0.9"

[dev-dependencies]
vectorcraft-testkit = { workspace = true }
Loading