Files
vectorcraft/crates/eps/src/import/tests_illustrator.rs
T
dotCooCoo b61674f2ab .ai import: legacy PostScript .ai files open on their own artboard
A .ai in the legacy PostScript format opened with the box around all of
its art as the artboard, so art placed off the artboard came in on it.
Files opened as .eps keep their page.

- A .ai file read through its layers used the EPS rule from #1102, which
  makes the art's bounding box the artboard. It now keeps the artboard
  its header gives (%AI5_ArtSize around the center of %AI3_TemplateBox),
  with its art outside it. The engine opens a PostScript .ai or .ait
  through the new vectorcraft_eps::import_ai; an EPS's private data is
  still read as an EPS.
- A .ai of versions 3 and 4 (no %AI5_FileFormat) does not record its
  artboard's size. When it has a template box, its artboard is now
  VectorCraft's own default, a US Letter page, centered on the template
  box's center, which the version 7 specification (section 2.2) places
  at the artboard's center. Before, it was the art's box. This also
  applies to .ai files other apps write with a template box and no art
  size (#1027).
- The center of a template box with a size (a file with a template
  image) is now the middle of the box, not its lower-left corner.

A .ai with neither an art size nor a template box keeps its art's box
as the artboard.
2026-11-14 19:02:25 -08:00

638 lines
37 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! Illustrator files (Illustrator 3–8 and their EPS): the groups they write (`u` … `U`) come in
//! as groups, nested as they were, between and inside clipping groups.
use std::sync::Arc;
use kurbo::Point;
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::clipnest::MAX_NEST;
use vectorcraft_doc::{LayerColor, LineCap, Node, NodeKind};
use vectorcraft_geom::Rect;
use crate::import::{import, import_ai};
/// A minimal file in Illustrator's format: its header comments, a prolog of our own defining the
/// operators `body` uses (`u` and `U` as `ugroup` and `Ugroup`), and `body`.
fn ai(header: &str, ugroup: &str, body: &str) -> Vec<u8> {
format!(
"%!PS-Adobe-3.0 EPSF-3.0\n{header}%%BoundingBox: 0 0 100 100\n%%EndComments\n%%BeginProlog\n\
/m {{moveto}} def /L {{lineto}} def /f {{closepath fill}} def /S {{stroke}} def /g {{setgray}} def\n\
/u {{{ugroup}}} def /U {{{}}} def\n%%EndProlog\n{body}\nshowpage\n%%EOF\n",
if ugroup.contains("gsave") { "grestore" } else { "" }
)
.into_bytes()
}
/// A legacy Illustrator format header: the reader takes `u` … `U` as groups only in files whose
/// header says they are in that format (`%AI…` comments or the creator, which the format's
/// published specification documents; see the `import` module docs).
const AI8: &str = "%%Creator: Adobe Illustrator(R) 8.0\n%AI5_FileFormat 4.0\n";
/// The editing text of a version 7 file (`%AI5_FileFormat 3`), no prolog: `setup` in its setup,
/// then `body`.
fn stream7(setup: &str, body: &str) -> Vec<u8> {
format!(
"%!PS-Adobe-3.0\n%%Creator: a script\n%%BoundingBox: 0 0 100 100\n%AI5_FileFormat 3\n%AI3_Cropmarks: 0 0 100 100\n%%EndComments\n\
%%BeginProlog\n%%EndProlog\n%%BeginSetup\n{setup}%%EndSetup\n{body}%%PageTrailer\n%%Trailer\n%%EOF\n"
)
.into_bytes()
}
/// A triangle filled at `x`.
fn tri(x: u32) -> String {
format!("{x} {x} m {} {x} L {} {} L f", x + 5, x + 5, x + 5)
}
/// The layer's objects as a tree: `p` a path, `c` a clip path, `g[…]` a group, `k[…]` a clipping
/// group.
fn tree(nodes: &[Arc<Node>]) -> String {
let one = |n: &Arc<Node>| match &n.kind {
NodeKind::Group { children, clip: false } => format!("g[{}]", tree(children)),
NodeKind::Group { children, clip: true } => format!("k[{}]", tree(children)),
NodeKind::Path { clipping: true, .. } => "c".into(),
NodeKind::Path { .. } => "p".into(),
k => format!("{k:?}"),
};
nodes.iter().map(one).collect::<Vec<_>>().join(" ")
}
fn read(header: &str, ugroup: &str, body: &str) -> (String, Vec<String>) {
let r = import(&ai(header, ugroup, body)).unwrap();
(tree(r.document.layers[0].children().unwrap()), r.warnings)
}
#[test]
fn groups_and_nested_groups_come_in_as_groups() {
let body = format!("u {} u {} {} U U {}", tri(10), tri(30), tri(50), tri(70));
assert_eq!(read(AI8, "", &body), ("g[p g[p p]] p".into(), vec![]));
// Illustrator 3's header names it only as the creator; a prolog whose groups save and restore
// the graphics state groups the same.
assert_eq!(read("%%Creator:Adobe Illustrator(TM) 3.2\n", "gsave", &body).0, "g[p g[p p]] p");
// Groups of one object, and groups next to each other.
assert_eq!(read(AI8, "", &format!("u {} U u {} U", tri(10), tri(30))).0, "g[p] g[p]");
}
#[test]
fn groups_nest_with_clipping_groups() {
// A clipping group inside a group, a group inside a clipping group.
let clip = "gsave 0 0 m 50 0 L 50 50 L 0 50 L closepath clip newpath";
let body = format!("u {} {clip} u {} {} U grestore {} U", tri(10), tri(20), tri(30), tri(40));
assert_eq!(read(AI8, "", &body).0, "g[p k[c g[p p]] p]");
// A fill and a stroke of one path in a group stay one object.
let body = "u 10 10 m 20 10 L 20 20 L closepath gsave 0 g fill grestore S U";
let r = import(&ai(AI8, "", body)).unwrap();
let layer = r.document.layers[0].children().unwrap();
assert_eq!(tree(layer), "g[p]");
assert_eq!(layer[0].children().unwrap()[0].appearance.items.len(), 2);
}
#[test]
fn other_postscript_keeps_its_own_u() {
// A program that isn't Illustrator's may name its own procedures `u` and `U`.
let body = format!("u {} {} U", tri(10), tri(30));
assert_eq!(read("%%Creator: some app\n", "", &body).0, "p p");
}
/// A `.ai` in PostScript form as other apps write it (#1027): its header and prolog name the
/// procsets that define its operators (by the DSC resource comments) without including them, so
/// its program can't be run. Its layers come from the program itself: names as they are, the
/// legacy format's ten-operand `Lb`, flatness `i`, the bounding box as the page.
const NAMED_PROLOG: &str = "%!PS-Adobe-3.0\n%%Creator: a CAD app\n%%BoundingBox: 0 0 200 100\n\
%%DocumentNeededResources: procset Adobe_packedarray 2.0 0\n%%+ procset Adobe_IllustratorA_AI3 1.0 0\n\
%AI3_TemplateBox: 288 384 288 384\n%%EndComments\n%%BeginProlog\n%%IncludeResource: procset Adobe_packedarray 2.0 0\n\
Adobe_packedarray /initialize get exec\n%%IncludeResource: procset Adobe_IllustratorA_AI3 1.0 0\n%%EndProlog\n\
%%BeginSetup\nAdobe_IllustratorA_AI3 /initialize get exec\n%%EndSetup\n\
%AI5_BeginLayer\n1 1 1 1 0 0 -1 0 0 0 Lb\n(SECTION::Cut) Ln\n0 A\n0 R\n0 0 0 1 K\n0 i 1 J 1 j 0.8 w 4 M []0 d\n0 D\n\
10 10 m\n90 10 L\n90 90 L\n10 90 L\n10 10 L\nS\nLB\n%AI5_EndLayer--\n\
%AI5_BeginLayer\n1 1 1 1 0 0 -1 191 63 255 Lb\n(SECTION::Hatch) Ln\n0 A\n0 R\n0 0 0 1 K\n0.1 w\n110 10 m\n190 90 L\nS\nLB\n%AI5_EndLayer--\n\
%%PageTrailer\ngsave annotatepage grestore showpage\n%%Trailer\nAdobe_IllustratorA_AI3 /terminate get exec\n%%EOF\n";
#[test]
fn a_postscript_ai_that_names_its_prolog_without_including_it_opens_with_its_layers() {
let r = import(NAMED_PROLOG.as_bytes()).unwrap();
assert!(r.warnings.is_empty() && !r.preview, "{:?}", r.warnings);
let d = &r.document;
let names: Vec<_> = d.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect();
assert_eq!(names, ["SECTION::Cut", "SECTION::Hatch"]);
let colors: Vec<_> = d.layers.iter().map(|l| if let NodeKind::Layer { color, .. } = l.kind { Some(color) } else { None }).collect();
assert_eq!(colors, [Some(LayerColor::Custom([0, 0, 0])), Some(LayerColor::Custom([191, 63, 255]))]);
assert_eq!(d.artboards[0].rect, Rect::new(0.0, 0.0, 200.0, 100.0), "the page is the bounding box");
let square = &d.layers[0].children().unwrap()[0];
assert_eq!(square.geometric_bounds(), Some(Rect::new(10.0, 10.0, 90.0, 90.0)));
let stroke = square.appearance.stroke().unwrap();
assert_eq!((stroke.width, stroke.cap), (0.8, LineCap::Round));
assert_eq!(tree(d.layers[1].children().unwrap()), "p");
}
/// A `.ai` in PostScript form with a pattern defined in the version 7 form (§3.4): the layer keeps
/// its name, and the pattern is a swatch that fills the path from its offset.
#[test]
fn a_postscript_ai_with_a_version_7_pattern_fills_with_it() {
let pattern = "%AI3_BeginPattern: (Stripes)\n(Stripes) 0 0 10 10 [\n%AI3_Tile\n(0 O 0 R 0 0 0 0.5 k) @ _ &\n\
(0 O 0 R 0 0 0 1 K) @ (\r1 w\r0 5 m\r10 5 L\rS\r) &\n] E\n%AI3_EndPattern\n";
let setup = "Adobe_IllustratorA_AI3 /initialize get exec\n";
let style = "0 i 1 J 1 j 0.8 w 4 M []0 d\n0 D\n";
let src = NAMED_PROLOG
.replace(setup, &format!("{setup}{pattern}"))
.replace(style, &format!("{style}(Stripes) 5 5 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n"))
.replace("10 10 L\nS\n", "10 10 L\nB\n");
let r = import(src.as_bytes()).unwrap();
assert!(r.warnings.is_empty() && !r.preview, "{:?}", r.warnings);
let d = &r.document;
assert_eq!(d.layers[0].name.as_deref(), Some("SECTION::Cut"));
assert!(matches!(&d.swatch("Stripes").unwrap().paint, Paint::Pattern { pattern, .. } if pattern == "Stripes"));
assert_eq!(d.pattern("Stripes").unwrap().art.len(), 2);
let square = &d.layers[0].children().unwrap()[0];
let Some(Paint::Pattern { pattern, xf }) = square.appearance.fill().map(|f| f.paint.clone()) else { panic!("{:?}", square.appearance) };
assert_eq!(pattern, "Stripes");
// The tile's top left, (0, 10) in its space, is at (5, 15) in art space: 85 down the 100-point page.
assert_eq!(xf * Point::ZERO, Point::new(5.0, 85.0));
}
/// A `.ai` in PostScript form with a graph on each of two layers (version 7 specification §17): its
/// data on `%_` lines, then its drawn art in a group, each object followed by `%_… Go`.
fn graphs_on_layers() -> String {
let graph = |x: u32| {
format!(
"%_Gs\n%_{x} 10 {} 90 Gb\n%_2 0 0 12 1 1 0 0 2 30 0 Gy\n%_1 1 1 1 Gz\n%_() Gc 5 Gc GC\n%_Gt\n%_0.5 g\n%_GT\n\
u\n0 0 0 1 k\n{x} 10 m\n{} 10 L\n{} 50 L\n{x} 50 L\n{x} 10 L\nf\n%_1 0 0 0 Go\nu\nU\nU\n%_GS\n",
x + 60,
x + 20,
x + 20
)
};
NAMED_PROLOG
.replace("10 10 L\nS\nLB", &format!("10 10 L\nS\n{}LB", graph(100)))
.replace("190 90 L\nS\nLB", &format!("190 90 L\nS\n{}LB", graph(10)))
}
#[test]
fn graphs_open_as_their_drawn_art_on_their_layers() {
let r = import(graphs_on_layers().as_bytes()).unwrap();
assert!(!r.preview, "read through the layers, not a fallback preview");
let d = &r.document;
let names: Vec<_> = d.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect();
assert_eq!(names, ["SECTION::Cut", "SECTION::Hatch"]);
assert_eq!(tree(d.layers[0].children().unwrap()), "p g[p g[]]");
assert_eq!(tree(d.layers[1].children().unwrap()), "p g[p g[]]");
let notes: Vec<_> = r.warnings.iter().filter(|w| w.contains("graphs come in as plain art")).collect();
assert_eq!(notes.len(), 1, "{:?}", r.warnings);
assert!(!r.warnings.iter().any(|w| w.contains("doesn't know") || w.contains("couldn't be read")), "{:?}", r.warnings);
}
/// A `.ai` in PostScript form whose layers can't be read either says why, after what stopped its
/// program.
#[test]
fn a_postscript_ai_whose_layers_cant_be_read_says_why() {
let damaged = NAMED_PROLOG.replace("0 D\n", "0 D\n1 2 frobnicate\n");
let e = import(damaged.as_bytes()).unwrap_err();
assert!(e.contains("`Adobe_packedarray`") && e.contains("its layers couldn't be read either") && e.contains("`frobnicate`"), "{e}");
}
/// A `.ai` in PostScript form with a multi-layer mask (`Mb`, its path, `Md`, objects in both
/// layers, `MB`) opens through its layers: a clipping group in each, and what follows `MB` unclipped.
#[test]
fn a_postscript_ai_with_a_multi_layer_mask_opens_with_its_layers() {
let src = NAMED_PROLOG
.replace("0 D\n10 10 m", "0 D\nMb\n20 20 m\n180 20 L\n180 80 L\n20 80 L\nh\nW\nn\nMd\n10 10 m")
.replace("190 90 L\nS\nLB", "190 90 L\nS\nMB\n150 50 m\n195 95 L\nS\nLB");
let r = import(src.as_bytes()).unwrap();
assert!(!r.preview, "read through the layers, not a fallback preview");
let d = &r.document;
let names: Vec<_> = d.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect();
assert_eq!(names, ["SECTION::Cut", "SECTION::Hatch"]);
assert_eq!(tree(d.layers[0].children().unwrap()), "k[c p]");
assert_eq!(tree(d.layers[1].children().unwrap()), "k[c p] p");
let mask = d.layers[1].children().unwrap()[0].children().unwrap()[0].clone();
assert_eq!(mask.geometric_bounds(), Some(Rect::new(20.0, 20.0, 180.0, 80.0)));
assert!(r.warnings.iter().any(|w| w.contains("clipping group in each layer")), "{:?}", r.warnings);
}
/// A `.ai` in PostScript form (read through its layers) whose text carries hyphenation, tab-ruler
/// and kerning attributes: `XL` (hyphenation language), `Xb`/`Xe`/`XB` (a tab definition), `Th`
/// (hyphen control), `Tk` (a manual kerning pair) and `T+` (a discretionary hyphen). The reader
/// keeps the language, the tab definition as the paragraph's tab stops, the pair's kerning and the
/// soft hyphen.
#[test]
fn text_with_hyphenation_and_tab_attributes_opens_instead_of_failing() {
let text = "0 To\n1 0 0 1 10 50 0 Tp\nTP\n0 Tr\n0 0 0 1 k\n/_Helvetica 9 Tf\n\
%_ 3 XL\n36 1 Xb\n0 0 3 72 Xe\nXB\n0 1 2 2 99 Th\n0 Ta\n(h) Tx\n0 -40 Tk\n(i) Tx\nT+\n(ho) Tx\nTO\n";
// The operators sit on a visible layer (so they'd be reported as unknown, not quietly skipped
// on a hidden one), beside the square so the layer is never empty.
let src = NAMED_PROLOG.replace("S\nLB\n%AI5_EndLayer--\n%AI5_BeginLayer", &format!("S\n{text}LB\n%AI5_EndLayer--\n%AI5_BeginLayer"));
let r = import(src.as_bytes()).unwrap();
assert!(!r.preview, "read through the layers, not a fallback preview");
assert!(!r.warnings.iter().any(|w| w.contains("doesn't know") || w.contains("couldn't be read")), "{:?}", r.warnings);
// `Th` sets the paragraph's hyphenation: off, 2 letters before and after a hyphen, and the
// limit of 99 hyphens in a row kept to the 25 `text.setFormat` takes.
let mut texts = vec![];
r.document.walk(|n| {
if let NodeKind::Text(t) = &n.kind {
texts.push((**t).clone());
}
});
let [t] = texts.as_slice() else { panic!("{texts:?}") };
assert_eq!(t.plain_text(), "hi\u{ad}ho");
let runs: Vec<_> = t.runs.iter().map(|r| (r.text.as_str(), r.style.kerning, r.style.language.as_deref())).collect();
assert_eq!(runs, [("h", Some(-40.0), Some("de")), ("i\u{ad}ho", None, Some("de"))]);
let p = t.para_at(0);
assert!(!p.hyphenate);
assert_eq!((p.hyphenation.after_first, p.hyphenation.before_last, p.hyphenation.hyphen_limit), (2, 2, 25));
let tabs: Vec<_> = p.tabs.iter().map(|t| (t.position, t.align)).collect();
assert_eq!(tabs, [(72.0, vectorcraft_doc::TabAlign::Right)]);
}
/// An Illustrator 3 file of paths alone, as image editors export their paths (storytold/photocraft#6036):
/// no prolog and no layers, the paths unpainted (`n` closes, `N` doesn't), a compound path of two.
const PATHS_ONLY: &str = "%!PS-Adobe-2.0 EPSF-1.2\n%%Creator: an image editor\n%%BoundingBox: 0 0 200 100\n\
%AI3_Cropmarks: 0 0 200 100\n%%EndComments\n%%EndProlog\n%%BeginSetup\n%%EndSetup\n\
%%Note: Outline\n10 10 m\n100 10 L\n50 80 60 90 10 10 C\nn\n\
*u\n20 20 m\n30 20 L\nN\n40 40 m\n50 50 L\n60 40 L\nn\n*U\n%%PageTrailer\n%%Trailer\n%%EOF\n";
#[test]
fn an_illustrator_3_file_without_layers_opens_its_paths_on_one_layer() {
let r = import(PATHS_ONLY.as_bytes()).unwrap();
assert!(r.warnings.is_empty() && !r.preview, "{:?}", r.warnings);
let d = &r.document;
assert_eq!(d.layers.len(), 1);
assert_eq!(d.artboards[0].rect, Rect::new(0.0, 0.0, 200.0, 100.0));
let art = d.layers[0].children().unwrap();
assert_eq!(art.len(), 2);
// Art space has y up: (10, 10) is 10 above the artboard's bottom.
let NodeKind::Path { path, .. } = &art[0].kind else { panic!("{:?}", art[0].kind) };
let ends: Vec<_> = path.subpaths[0].anchors.iter().map(|a| (a.p.x, a.p.y)).collect();
assert_eq!(ends, [(10.0, 90.0), (100.0, 90.0)]);
assert!(path.subpaths[0].closed);
assert!(art[0].appearance.items.is_empty(), "unpainted");
let NodeKind::Compound { children, .. } = &art[1].kind else { panic!("{:?}", art[1].kind) };
let closed: Vec<_> = children.iter().map(|c| if let NodeKind::Path { path, .. } = &c.kind { path.is_closed() } else { false }).collect();
assert_eq!(closed, [false, true]);
assert_eq!(art[1].geometric_bounds(), Some(Rect::new(20.0, 50.0, 60.0, 80.0)));
}
/// In an Illustrator 3 file the case of a segment's operator says whether the anchor it ends on is
/// smooth (lower case) or a corner (upper case).
#[test]
fn an_illustrator_3_files_anchors_are_smooth_or_corners_by_their_operators_case() {
use vectorcraft_geom::AnchorKind::{Corner, Smooth};
let src = PATHS_ONLY.replace("10 10 m\n100 10 L\n50 80 60 90 10 10 C\nn\n", "0 0 m\n10 10 20 0 30 0 c\n40 10 50 0 60 0 C\nh\nS\n");
let r = import(src.as_bytes()).unwrap();
assert!(r.warnings.is_empty() && !r.preview, "{:?}", r.warnings);
let art = r.document.layers[0].children().unwrap();
let path = art[0].path_data().unwrap();
let kinds: Vec<_> = path.subpaths[0].anchors.iter().map(|a| a.kind).collect();
assert_eq!(kinds, [Corner, Smooth, Corner]);
let middle = path.subpaths[0].anchors[1];
assert_eq!([(middle.h_in.x, middle.h_in.y), (middle.h_out.x, middle.h_out.y)], [(20.0, 100.0), (40.0, 90.0)]);
}
/// The same program in a file that doesn't say it is in Illustrator's format is PostScript whose
/// operators the reader doesn't know: it is still refused.
#[test]
fn the_same_program_in_other_postscript_is_still_refused() {
let other = PATHS_ONLY.replace("%AI3_Cropmarks: 0 0 200 100\n", "");
let e = import(other.as_bytes()).unwrap_err();
assert!(e.contains("it uses `m`") && !e.contains("layers"), "{e}");
}
/// The editing text of a newer file saved as PostScript (no prolog at all, a non-printing setup):
/// it opens with its sublayers.
#[test]
fn newer_editing_text_as_postscript_opens_with_its_sublayers() {
let layer =
|name: &str, art: &str| format!("%AI5_BeginLayer\n1 1 1 1 0 0 1 -1 79 128 255 0 50 0 Lb\n({name}) Ln\n0 A\n0 Xw\n{art}LB\n%AI5_EndLayer--\n");
let ground = layer("Ground", &(layer("Lawn", "0 0 0 0.3 k\n10 20 m\n70 20 L\n70 80 L\n10 80 L\nf\n") + &layer("Paving", "")));
let text = format!(
"%!PS-Adobe-3.0\n%%Creator: a script\n%%BoundingBox: 0 0 250 100\n%AI5_FileFormat 14.0\n%AI3_Cropmarks: 0 0 250 100\n%%EndComments\n\
%%BeginProlog\n%%EndProlog\n%%BeginSetup\n%AI5_Begin_NonPrinting\nNp\n%AI5_End_NonPrinting--\n%%EndSetup\n{ground}%%PageTrailer\n%%Trailer\n%%EOF\n"
);
let r = import(text.as_bytes()).unwrap();
let d = &r.document;
assert_eq!(d.layers.len(), 1, "{:?}", r.warnings);
let subs: Vec<_> = d.layers[0].children().unwrap().iter().map(|l| l.name.clone().unwrap_or_default()).collect();
assert_eq!(subs, ["Lawn", "Paving"]);
}
/// A file in the legacy format whose prolog is included (here one of our own) runs as its page, and
/// comes in through the layers its program has when they look like the page.
#[test]
fn a_legacy_file_with_its_prolog_comes_in_through_its_layers() {
let prolog = "/Lb {10 {pop} repeat} def /Ln {pop} def /LB {} def /A {pop} def /k {setcmykcolor} def";
let body = format!("%AI5_BeginLayer\n1 1 1 1 0 0 0 79 128 255 Lb\n(Back) Ln\n0 A\n0 0 0 1 k\n{} LB\n%AI5_EndLayer--\n", tri(10));
let file = String::from_utf8(ai(AI8, "", &body)).unwrap().replace("%%EndProlog", &format!("{prolog}\n%%EndProlog"));
let r = import(file.as_bytes()).unwrap();
let names: Vec<_> = r.document.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect();
assert_eq!(names, ["Back"], "{:?}", r.warnings);
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
// Without the editing data, it is its page.
let page = crate::import::import_with(file.as_bytes(), false).unwrap();
assert_eq!(page.document.layers[0].name.as_deref(), Some("Layer 1"));
}
/// A `.ai` in the legacy format (version 8, `%AI5_FileFormat 4.0`) whose prolog is included: a
/// square on its 200-point artboard and one far to its right. Its bounding box is the box of that
/// art; its artboard is its art size around the template box's center (version 7 specification
/// §2.2). Its first line names the EPSF version, as the format's files may.
const LEGACY_AI_ART_OFF_ITS_ARTBOARD: &str = "%!PS-Adobe-2.0 EPSF-1.2\n%%Creator: a script\n%%BoundingBox: 10 10 320 30\n\
%%HiResBoundingBox: 10 10 320 30\n%AI5_FileFormat 4.0\n%AI3_TemplateBox: 100.5 99.5 100.5 99.5\n%AI5_ArtSize: 200 200\n\
%%EndComments\n%%BeginProlog\n/m {moveto} def /L {lineto} def /f {closepath fill} def\n\
/Lb {10 {pop} repeat} def /Ln {pop} def /LB {} def /A {pop} def /k {setcmykcolor} def\n%%EndProlog\n%%BeginSetup\n%%EndSetup\n\
%AI5_BeginLayer\n1 1 1 1 0 0 0 79 128 255 Lb\n(Art) Ln\n0 A\n0 0 0 1 k\n\
10 10 m\n30 10 L\n30 30 L\n10 30 L\nf\n300 10 m\n320 10 L\n320 30 L\n300 30 L\nf\nLB\n%AI5_EndLayer--\n\
%%PageTrailer\nshowpage\n%%Trailer\n%%EOF\n";
/// `bytes` opened as a `.ai`.
fn open_ai(bytes: &[u8]) -> crate::Imported {
import_ai(bytes, true, false, crate::NameEncoding::default()).unwrap()
}
/// Such a `.ai` keeps the artboard its header gives, with the square outside it, when it comes in
/// through its layers. The same program opened as an EPS comes in on its page, its art's box
/// (#1102).
#[test]
fn a_legacy_ai_keeps_its_artboard_and_the_art_outside_it() {
let r = open_ai(LEGACY_AI_ART_OFF_ITS_ARTBOARD.as_bytes());
assert!(r.warnings.is_empty() && !r.preview, "{:?}", r.warnings);
let d = &r.document;
let boards: Vec<_> = d.artboards.iter().map(|a| a.rect).collect();
assert_eq!(boards, [Rect::new(0.0, 0.0, 200.0, 200.0)]);
let art: Vec<_> = d.layers[0].children().unwrap().iter().map(|n| n.geometric_bounds().unwrap()).collect();
// Art space has y up from the artboard's bottom: (10, 10) is 10 above it.
assert_eq!(art, [Rect::new(10.0, 170.0, 30.0, 190.0), Rect::new(300.0, 170.0, 320.0, 190.0)]);
let eps = import(LEGACY_AI_ART_OFF_ITS_ARTBOARD.as_bytes()).unwrap();
let boards: Vec<_> = eps.document.artboards.iter().map(|a| a.rect.size()).collect();
assert_eq!(boards, [kurbo::Size::new(310.0, 20.0)], "{:?}", eps.warnings);
}
/// A version 3 `.ai` doesn't give its artboard's size (`%AI5_ArtSize` came with version 5): its
/// artboard is VectorCraft's own default, a US Letter page, around the template box's center, the
/// artboard's center (version 7 specification §2.2). Without a template box it is the art's box,
/// and so is the page of the same file opened as an EPS.
#[test]
fn a_version_3_ai_has_a_letter_artboard_around_its_template_boxs_center() {
let v3 = PATHS_ONLY.replace("%AI3_Cropmarks: 0 0 200 100\n", "%AI3_TemplateBox: 100 100 100 100\n");
let r = open_ai(v3.as_bytes());
assert!(r.warnings.is_empty() && !r.preview, "{:?}", r.warnings);
let d = &r.document;
let boards: Vec<_> = d.artboards.iter().map(|a| a.rect).collect();
assert_eq!(boards, [Rect::new(0.0, 0.0, 612.0, 792.0)]);
// The artboard runs from -206 to 406 across and from -296 to 496 up in art space.
let art = d.layers[0].children().unwrap();
assert_eq!(art[1].geometric_bounds(), Some(Rect::new(226.0, 446.0, 266.0, 476.0)));
// The center of a template box with a size (a file with a template image).
let r = open_ai(PATHS_ONLY.replace("%AI3_Cropmarks: 0 0 200 100\n", "%AI3_TemplateBox: 50 50 150 150\n").as_bytes());
assert_eq!(r.document.layers[0].children().unwrap()[1].geometric_bounds(), Some(Rect::new(226.0, 446.0, 266.0, 476.0)));
let r = open_ai(PATHS_ONLY.replace("%AI3_Cropmarks: 0 0 200 100\n", "%AI3_ColorUsage: Color\n").as_bytes());
assert_eq!(r.document.artboards[0].rect, Rect::new(0.0, 0.0, 200.0, 100.0), "{:?}", r.warnings);
let r = import(v3.as_bytes()).unwrap();
assert_eq!(r.document.artboards[0].rect, Rect::new(0.0, 0.0, 200.0, 100.0), "{:?}", r.warnings);
// A newer file (`%AI5_FileFormat`, version 5 on) without an art size keeps the art's box too.
let r = open_ai(v3.replace("%%EndComments", "%AI5_FileFormat 1.0\n%%EndComments").as_bytes());
assert_eq!(r.document.artboards[0].rect, Rect::new(0.0, 0.0, 200.0, 100.0), "{:?}", r.warnings);
}
/// A version 3 `.ai` whose prolog is included and whose program has no layers: its page draws, and
/// its art comes in on one layer around a US Letter artboard, the square far to the right outside
/// it.
#[test]
fn a_version_3_ai_that_draws_keeps_its_letter_artboard_and_the_art_outside_it() {
let v3 = "%!PS-Adobe-2.0 EPSF-1.2\n%%Creator: a script\n%%BoundingBox: 10 10 720 30\n%AI3_TemplateBox: 100 100 100 100\n\
%%EndComments\n%%BeginProlog\n/m {moveto} def /L {lineto} def /f {closepath fill} def /k {setcmykcolor} def\n\
%%EndProlog\n%%BeginSetup\n%%EndSetup\n0 0 0 1 k\n10 10 m\n30 10 L\n30 30 L\n10 30 L\nf\n\
700 10 m\n720 10 L\n720 30 L\n700 30 L\nf\n%%PageTrailer\nshowpage\n%%Trailer\n%%EOF\n";
let r = open_ai(v3.as_bytes());
assert!(r.warnings.is_empty() && !r.preview, "{:?}", r.warnings);
let boards: Vec<_> = r.document.artboards.iter().map(|a| a.rect).collect();
assert_eq!(boards, [Rect::new(0.0, 0.0, 612.0, 792.0)]);
assert_eq!(r.document.layers.len(), 1);
let art: Vec<_> = r.document.layers[0].children().unwrap().iter().map(|n| n.geometric_bounds().unwrap()).collect();
// The artboard runs from -206 to 406 across and from -296 to 496 up in art space.
assert_eq!(art, [Rect::new(216.0, 466.0, 236.0, 486.0), Rect::new(906.0, 466.0, 926.0, 486.0)]);
let eps = import(v3.as_bytes()).unwrap();
assert_eq!(eps.document.artboards[0].rect, Rect::new(0.0, 0.0, 710.0, 20.0), "{:?}", eps.warnings);
}
/// A `.ai` another app wrote (#1027) that gives a template box but no art size opens on a US Letter
/// artboard around the box's center, from -18 to 594 across and -12 to 780 up in art space (as an
/// EPS it opens on its bounding box, see above).
#[test]
fn a_postscript_ai_with_a_template_box_and_no_art_size_opens_on_a_letter_artboard() {
let r = open_ai(NAMED_PROLOG.as_bytes());
assert_eq!(r.document.artboards[0].rect, Rect::new(0.0, 0.0, 612.0, 792.0), "{:?}", r.warnings);
let square = &r.document.layers[0].children().unwrap()[0];
assert_eq!(square.geometric_bounds(), Some(Rect::new(28.0, 690.0, 108.0, 770.0)));
}
/// A placed EPS in the legacy format (version 7 specification §16, no `%AI5_BeginPlace`), its file
/// included whole: the layers come in, the placed file as the art the page draws in its box.
#[test]
fn a_legacy_file_with_a_placed_eps_comes_in_through_its_layers() {
// `` ` `` takes the file's user space into the page's (`concat`); `~` restores it.
let prolog = "/Lb {10 {pop} repeat} def /Ln {pop} def /LB {} def /A {pop} def /k {setcmykcolor} def\n\
/` {gsave 5 {pop} repeat concat} def /~ {grestore} def";
let eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 10 20 50 50\n%%EndComments\n1 0 0 setrgbcolor\n\
newpath 10 20 moveto 50 20 lineto 50 50 lineto 10 50 lineto closepath fill\n%%EOF\n";
let placed = format!("[1 0 0 1 10 20] 10 20 50 50 (art.eps) `\n%%BeginDocument: art.eps\n{eps}%%EndDocument\n~\n");
let body = format!("%AI5_BeginLayer\n1 1 1 1 0 0 0 79 128 255 Lb\n(Back) Ln\n0 A\n0 0 0 1 k\n{} {placed}LB\n%AI5_EndLayer--\n", tri(10));
let file = String::from_utf8(ai(AI8, "", &body)).unwrap().replace("%%EndProlog", &format!("{prolog}\n%%EndProlog"));
let r = import(file.as_bytes()).unwrap();
assert!(!r.preview);
let names: Vec<_> = r.document.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect();
assert_eq!(names, ["Back"], "{:?}", r.warnings);
let art = r.document.layers[0].children().unwrap();
assert_eq!(tree(art), "p g[p]", "{:?}", r.warnings);
// The file's box, moved by the matrix: 20 40 60 70 on the page, y up.
let bounds = art[1].geometric_bounds().unwrap();
assert!(
(bounds.x0 - 20.0).abs() < 0.01 && (bounds.y0 - 30.0).abs() < 0.01 && (bounds.x1 - 60.0).abs() < 0.01 && (bounds.y1 - 60.0).abs() < 0.01,
"{bounds:?}"
);
assert!(r.warnings.iter().any(|w| w.contains("placed files")), "{:?}", r.warnings);
}
/// A legacy file with a linked image (version 7 specification §8.2, §8.3: `(path) modified XG`, then
/// `XF` with no samples) comes in through its layers, the image as a linked image of that file
/// showing a placeholder where the matrix puts the image.
#[test]
fn a_legacy_file_with_a_linked_image_comes_in_through_its_layers() {
let prolog = "/Lb {10 {pop} repeat} def /Ln {pop} def /LB {} def /A {pop} def /k {setcmykcolor} def\n\
/XG {pop pop} def /XF {13 {pop} repeat} def";
let raster = "%AI5_File:\n%AI5_BeginRaster\n(photo.tif) 0 XG\n[2 0 0 3 20 80] 0 0 10 20 10 20 8 3 0 0 0 0 XF\n%AI5_EndRaster\n";
let body = format!("%AI5_BeginLayer\n1 1 1 1 0 0 0 79 128 255 Lb\n(Back) Ln\n0 A\n0 0 0 1 k\n{}\n{raster}LB\n%AI5_EndLayer--\n", tri(10));
let file = String::from_utf8(ai(AI8, "", &body)).unwrap().replace("%%EndProlog", &format!("{prolog}\n%%EndProlog"));
let r = import(file.as_bytes()).unwrap();
assert!(!r.preview);
let names: Vec<_> = r.document.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect();
assert_eq!(names, ["Back"], "{:?}", r.warnings);
let art = r.document.layers[0].children().unwrap();
assert_eq!(art.len(), 2, "{:?}", r.warnings);
let NodeKind::Image(im) = &art[1].kind else { panic!("{:?}", art[1].kind) };
assert_eq!(im.link.as_ref().map(|l| l.path.as_str()), Some("photo.tif"));
// The image's 10 × 20 pixels from (20, 80) in art space, 2 and 3 points each: 20 20 40 80 on
// the page, y down.
assert_eq!((im.width, im.height), (10, 20));
let (top_left, bottom_right) = (im.xf * Point::ZERO, im.xf * Point::new(10.0, 20.0));
assert!(
(top_left - Point::new(20.0, 20.0)).hypot() < 0.01 && (bottom_right - Point::new(40.0, 80.0)).hypot() < 0.01,
"{top_left:?} {bottom_right:?}"
);
assert!(r.warnings.iter().any(|w| w.contains("show a placeholder")), "{:?}", r.warnings);
}
/// A file in the legacy format without layers (Illustrator 3) whose prolog is included: its prolog,
/// a setup, and `art`.
fn layerless(art: &str) -> Vec<u8> {
format!(
"%!PS-Adobe-3.0 EPSF-3.0\n%%Creator: a script\n%%BoundingBox: 0 0 100 100\n%AI3_Cropmarks: 0 0 100 100\n%%EndComments\n\
%%BeginProlog\n/m {{moveto}} def /L {{lineto}} def /f {{closepath fill}} def /A {{pop}} def /k {{setcmykcolor}} def\n\
%%EndProlog\n%%BeginSetup\n%%EndSetup\n{art}\n%%PageTrailer\nshowpage\n%%Trailer\n%%EOF\n"
)
.into_bytes()
}
/// A file in the legacy format without layers whose prolog is included runs as its page, and comes
/// in through its art on one layer when that looks like the page: what only the format keeps (here
/// a lock) stays.
#[test]
fn a_legacy_file_without_layers_comes_in_through_its_art_on_one_layer() {
let file = layerless(&format!("1 A\n0 0 0 1 k\n{}", tri(10)));
let r = import(&file).unwrap();
assert!(r.warnings.is_empty() && !r.preview, "{:?}", r.warnings);
let d = &r.document;
assert_eq!(d.layers.len(), 1);
let art = d.layers[0].children().unwrap();
assert_eq!(tree(art), "p");
assert!(art[0].locked, "the lock is kept");
// Without the editing data, it is its page, which has no locks.
let page = crate::import::import_with(&file, false).unwrap();
assert!(!page.document.layers[0].children().unwrap()[0].locked);
}
/// When its art can't be read as the format (here a procedure of its own draws it), the file comes
/// in as its page, as before, without a note.
#[test]
fn a_legacy_file_without_layers_whose_art_cannot_be_read_comes_in_as_its_page() {
let file = layerless("/x {20 20 moveto 80 20 lineto 80 80 lineto closepath fill} def x");
let r = import(&file).unwrap();
assert!(r.warnings.is_empty() && !r.preview, "{:?}", r.warnings);
let page = crate::import::import_with(&file, false).unwrap();
assert_eq!(tree(r.document.layers[0].children().unwrap()), tree(page.document.layers[0].children().unwrap()));
assert_eq!(r.document.layers[0].children().unwrap()[0].visual_bounds(), page.document.layers[0].children().unwrap()[0].visual_bounds());
}
/// A version 7 palette writes no swatch names (the AI7 spec's §11 example): its swatches come in
/// named by their paint, in its order, in place of the defaults.
#[test]
fn a_version_7_palette_keeps_its_swatches_without_names() {
let setup = "%AI5_BeginGradient: (B&W)\n(B&W) 0 2 Bd\n[\n%_1 0 50 0 Bs\n%_0 0 50 100 Bs\nBD\n%AI5_EndGradient\n\
%AI5_BeginPalette\n0 0 Pb\nPn\nPc\n1 g\nPc\n0 g\nPc\n0 0 0 0 k\nPc\n0.75 g\nPc\n\
Bb\n2 (B&W) 0 0 0 1 1 0 0 1 0 0 1 Bg\n0 BB\nPc\n0.25 0 0 0 k\nPc\n0 1 1 0 (Spot A) 0 x\nPc\n0.75 g\nPc\nPc\nPB\n%AI5_EndPalette\n";
let body = format!("%AI5_BeginLayer\n1 1 1 1 0 0 1 -1 79 128 255 0 50 0 Lb\n(Art) Ln\n0 A\n0 Xw\n0 0 0 1 k\n{}\nLB\n%AI5_EndLayer--\n", tri(10));
let r = import(&stream7(setup, &body)).unwrap();
let d = &r.document;
assert_eq!(d.layers.len(), 1, "{:?}", r.warnings);
let names: Vec<&str> = d.swatches.iter().map(|s| s.name.as_str()).collect();
assert_eq!(
names,
["[None]", "Gray K=0", "Gray K=100", "C=0 M=0 Y=0 K=0", "Gray K=25", "B&W", "C=25 M=0 Y=0 K=0", "Spot A", "Gray K=25"],
"{:?}",
r.warnings
);
assert!(d.swatch_groups.is_empty());
let spot = d.swatch("Spot A").unwrap();
assert!(spot.spot && spot.global, "{spot:?}");
assert!(d.swatches.iter().filter(|s| s.name != "Spot A").all(|s| !s.spot && !s.global));
assert!(matches!(&d.swatch("B&W").unwrap().paint, Paint::Gradient(g) if g.swatch.is_none()));
assert_eq!(d.swatch("Gray K=0").unwrap().paint.color(), Some(Color::gray(0.0)), "1 g is white");
}
/// A gradient's name in the file is shown up to its newline (the AI7 spec's §4): two gradients
/// named `Sky` apart from what follows the newline come in as swatches "Sky" and "Sky 2", and each
/// object keeps its own gradient, linked to its own swatch. A palette swatch that has the name
/// "Sky" of its own keeps it, and the gradients take the next free names.
#[test]
fn gradient_names_are_shown_up_to_their_newline() {
let gradient = |name: &str, gray: f64| {
format!("%AI5_BeginGradient: ({name})\n({name}) 0 2 Bd\n[\n%_{gray} 0 50 0 Bs\n%_0 0 50 100 Bs\nBD\n%AI5_EndGradient\n")
};
let cell = |name: &str| format!("Bb\n2 ({name}) 0 0 0 1 1 0 0 1 0 0 1 Bg\n0 BB\nPc\n");
let fill = |name: &str, x: u32| format!("Bb\n1 ({name}) 0 0 0 100 1 0 0 1 0 0 Bg\n{}\n0 BB\n", tri(x));
let body = format!(
"%AI5_BeginLayer\n1 1 1 1 0 0 1 -1 79 128 255 0 50 0 Lb\n(Art) Ln\n0 A\n0 Xw\n{}{}LB\n%AI5_EndLayer--\n",
fill("Sky\\n2", 10),
fill("Sky\\n1", 30)
);
let first_stop = |p: &Paint| match p {
Paint::Gradient(g) => (g.swatch.clone(), g.gradient.stops.first().map(|s| s.color)),
_ => panic!("{p:?}"),
};
for (own, first, second) in [("", "Sky", "Sky 2"), ("0 1 1 0 (Sky) 0 x\nPc\n", "Sky 2", "Sky 3")] {
let setup = format!(
"{}{}%AI5_BeginPalette\n0 0 Pb\nPn\nPc\n{own}{}{}PB\n%AI5_EndPalette\n",
gradient("Sky\\n1", 1.0),
gradient("Sky\\n2", 0.5),
cell("Sky\\n1"),
cell("Sky\\n2")
);
let r = import(&stream7(&setup, &body)).unwrap();
let d = &r.document;
let names: Vec<&str> = d.swatches.iter().map(|s| s.name.as_str()).collect();
let expected: Vec<&str> = ["[None]"].into_iter().chain((!own.is_empty()).then_some("Sky")).chain([first, second]).collect();
assert_eq!(names, expected, "{:?}", r.warnings);
assert_eq!(first_stop(&d.swatch(first).unwrap().paint), (None, Some(Color::gray(0.0))));
assert_eq!(first_stop(&d.swatch(second).unwrap().paint), (None, Some(Color::gray(0.5))));
let art = d.layers[0].children().unwrap();
let fills: Vec<_> = art.iter().map(|n| first_stop(&n.appearance.fill().unwrap().paint)).collect();
assert_eq!(fills, [(Some(second.into()), Some(Color::gray(0.5))), (Some(first.into()), Some(Color::gray(0.0)))]);
}
}
/// A version 8 file's paths keep their notes and Show Center.
#[test]
fn a_legacy_files_paths_keep_their_notes_and_show_center() {
let body = format!(
"%AI5_BeginLayer\n1 1 1 1 0 0 0 79 128 255 Lb\n(Notes) Ln\n0 A\n%AI3_Note:first\n%AI5_NoteMore:second line\n1 Ap\n0 0 0 1 k\n{}\n\
%AI3_Note:\n0 Ap\n{}\nLB\n%AI5_EndLayer--\n",
tri(10),
tri(40)
);
let r = import(&ai(AI8, "", &body)).unwrap();
let kids = r.document.layers[0].children().unwrap();
let attrs: Vec<_> = kids.iter().map(|n| n.extras().attrs.as_deref().map(|a| (a.note.clone(), a.show_center))).collect();
assert_eq!(attrs, [Some(("first\nsecond line".into(), Some(true))), None], "{:?}", r.warnings);
assert!(kids[0].shows_center() && !kids[1].shows_center());
}
/// A version 8 file's object tags open as each object's URL and data.
#[test]
fn a_legacy_files_object_tags_open_as_urls_and_data() {
let body = format!(
"%AI5_BeginLayer\n1 1 1 1 0 0 0 79 128 255 Lb\n(Tags) Ln\n0 A\n0 0 0 1 k\n{}\n/AdobeURL (https://example.com) XT\n/sku (B-7) XT\n\
u\n{}\nU\n/part () XT\nLB\n%AI5_EndLayer--\n",
tri(10),
tri(40)
);
let r = import(&ai(AI8, "", &body)).unwrap();
let kids = r.document.layers[0].children().unwrap();
let attrs: Vec<_> = kids.iter().map(|n| n.extras().attrs.as_deref().map(|a| (a.url.clone(), a.data.clone()))).collect();
assert_eq!(
attrs,
[Some(("https://example.com".into(), vec![("sku".into(), "B-7".into())])), Some((String::new(), vec![("part".into(), String::new())]))],
"{:?}",
r.warnings
);
}
#[test]
fn unbalanced_and_runaway_groups_are_read_safely() {
// Ends without a beginning end nothing; groups left open hold the rest.
assert_eq!(read(AI8, "", &format!("U U {} u {} u {}", tri(10), tri(20), tri(30))).0, "p g[p g[p]]");
// Groups nest only so deep: the deeper ones' art goes into the innermost group read, and the
// groups around them close where they should.
let n = MAX_NEST + 50;
let body = format!("{} {} {} {}", "u ".repeat(n), tri(10), "U ".repeat(n), tri(30));
let (t, warnings) = read(AI8, "", &body);
assert_eq!(t, format!("{}p{} p", "g[".repeat(MAX_NEST), "]".repeat(MAX_NEST)));
assert!(warnings.iter().any(|w| w.contains("nested more than")), "{warnings:?}");
}